File: //srv/wordpress/core/beta/wp-includes/js/dist/block-editor.js
"use strict";
var wp;
(wp ||= {}).blockEditor = (() => {
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to2, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to2, key) && key !== except)
__defProp(to2, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to2;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// package-external:@wordpress/blocks
var require_blocks = __commonJS({
"package-external:@wordpress/blocks"(exports, module) {
module.exports = window.wp.blocks;
}
});
// package-external:@wordpress/element
var require_element = __commonJS({
"package-external:@wordpress/element"(exports, module) {
module.exports = window.wp.element;
}
});
// package-external:@wordpress/data
var require_data = __commonJS({
"package-external:@wordpress/data"(exports, module) {
module.exports = window.wp.data;
}
});
// package-external:@wordpress/compose
var require_compose = __commonJS({
"package-external:@wordpress/compose"(exports, module) {
module.exports = window.wp.compose;
}
});
// package-external:@wordpress/hooks
var require_hooks = __commonJS({
"package-external:@wordpress/hooks"(exports, module) {
module.exports = window.wp.hooks;
}
});
// package-external:@wordpress/components
var require_components = __commonJS({
"package-external:@wordpress/components"(exports, module) {
module.exports = window.wp.components;
}
});
// package-external:@wordpress/private-apis
var require_private_apis = __commonJS({
"package-external:@wordpress/private-apis"(exports, module) {
module.exports = window.wp.privateApis;
}
});
// package-external:@wordpress/deprecated
var require_deprecated = __commonJS({
"package-external:@wordpress/deprecated"(exports, module) {
module.exports = window.wp.deprecated;
}
});
// vendor-external:react/jsx-runtime
var require_jsx_runtime = __commonJS({
"vendor-external:react/jsx-runtime"(exports, module) {
module.exports = window.ReactJSXRuntime;
}
});
// package-external:@wordpress/url
var require_url = __commonJS({
"package-external:@wordpress/url"(exports, module) {
module.exports = window.wp.url;
}
});
// package-external:@wordpress/i18n
var require_i18n = __commonJS({
"package-external:@wordpress/i18n"(exports, module) {
module.exports = window.wp.i18n;
}
});
// node_modules/fast-deep-equal/es6/index.js
var require_es6 = __commonJS({
"node_modules/fast-deep-equal/es6/index.js"(exports, module) {
"use strict";
module.exports = function equal(a2, b2) {
if (a2 === b2) return true;
if (a2 && b2 && typeof a2 == "object" && typeof b2 == "object") {
if (a2.constructor !== b2.constructor) return false;
var length, i2, keys;
if (Array.isArray(a2)) {
length = a2.length;
if (length != b2.length) return false;
for (i2 = length; i2-- !== 0; )
if (!equal(a2[i2], b2[i2])) return false;
return true;
}
if (a2 instanceof Map && b2 instanceof Map) {
if (a2.size !== b2.size) return false;
for (i2 of a2.entries())
if (!b2.has(i2[0])) return false;
for (i2 of a2.entries())
if (!equal(i2[1], b2.get(i2[0]))) return false;
return true;
}
if (a2 instanceof Set && b2 instanceof Set) {
if (a2.size !== b2.size) return false;
for (i2 of a2.entries())
if (!b2.has(i2[0])) return false;
return true;
}
if (ArrayBuffer.isView(a2) && ArrayBuffer.isView(b2)) {
length = a2.length;
if (length != b2.length) return false;
for (i2 = length; i2-- !== 0; )
if (a2[i2] !== b2[i2]) return false;
return true;
}
if (a2.constructor === RegExp) return a2.source === b2.source && a2.flags === b2.flags;
if (a2.valueOf !== Object.prototype.valueOf) return a2.valueOf() === b2.valueOf();
if (a2.toString !== Object.prototype.toString) return a2.toString() === b2.toString();
keys = Object.keys(a2);
length = keys.length;
if (length !== Object.keys(b2).length) return false;
for (i2 = length; i2-- !== 0; )
if (!Object.prototype.hasOwnProperty.call(b2, keys[i2])) return false;
for (i2 = length; i2-- !== 0; ) {
var key = keys[i2];
if (!equal(a2[key], b2[key])) return false;
}
return true;
}
return a2 !== a2 && b2 !== b2;
};
}
});
// package-external:@wordpress/primitives
var require_primitives = __commonJS({
"package-external:@wordpress/primitives"(exports, module) {
module.exports = window.wp.primitives;
}
});
// package-external:@wordpress/rich-text
var require_rich_text = __commonJS({
"package-external:@wordpress/rich-text"(exports, module) {
module.exports = window.wp.richText;
}
});
// package-external:@wordpress/block-serialization-default-parser
var require_block_serialization_default_parser = __commonJS({
"package-external:@wordpress/block-serialization-default-parser"(exports, module) {
module.exports = window.wp.blockSerializationDefaultParser;
}
});
// package-external:@wordpress/style-engine
var require_style_engine = __commonJS({
"package-external:@wordpress/style-engine"(exports, module) {
module.exports = window.wp.styleEngine;
}
});
// node_modules/deepmerge/dist/cjs.js
var require_cjs = __commonJS({
"node_modules/deepmerge/dist/cjs.js"(exports, module) {
"use strict";
var isMergeableObject = function isMergeableObject2(value) {
return isNonNullObject(value) && !isSpecial(value);
};
function isNonNullObject(value) {
return !!value && typeof value === "object";
}
function isSpecial(value) {
var stringValue = Object.prototype.toString.call(value);
return stringValue === "[object RegExp]" || stringValue === "[object Date]" || isReactElement(value);
}
var canUseSymbol = typeof Symbol === "function" && Symbol.for;
var REACT_ELEMENT_TYPE = canUseSymbol ? /* @__PURE__ */ Symbol.for("react.element") : 60103;
function isReactElement(value) {
return value.$$typeof === REACT_ELEMENT_TYPE;
}
function emptyTarget(val) {
return Array.isArray(val) ? [] : {};
}
function cloneUnlessOtherwiseSpecified(value, options) {
return options.clone !== false && options.isMergeableObject(value) ? deepmerge2(emptyTarget(value), value, options) : value;
}
function defaultArrayMerge(target, source, options) {
return target.concat(source).map(function(element) {
return cloneUnlessOtherwiseSpecified(element, options);
});
}
function getMergeFunction(key, options) {
if (!options.customMerge) {
return deepmerge2;
}
var customMerge = options.customMerge(key);
return typeof customMerge === "function" ? customMerge : deepmerge2;
}
function getEnumerableOwnPropertySymbols(target) {
return Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(target).filter(function(symbol) {
return Object.propertyIsEnumerable.call(target, symbol);
}) : [];
}
function getKeys(target) {
return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target));
}
function propertyIsOnObject(object, property) {
try {
return property in object;
} catch (_) {
return false;
}
}
function propertyIsUnsafe(target, key) {
return propertyIsOnObject(target, key) && !(Object.hasOwnProperty.call(target, key) && Object.propertyIsEnumerable.call(target, key));
}
function mergeObject(target, source, options) {
var destination = {};
if (options.isMergeableObject(target)) {
getKeys(target).forEach(function(key) {
destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
});
}
getKeys(source).forEach(function(key) {
if (propertyIsUnsafe(target, key)) {
return;
}
if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) {
destination[key] = getMergeFunction(key, options)(target[key], source[key], options);
} else {
destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
}
});
return destination;
}
function deepmerge2(target, source, options) {
options = options || {};
options.arrayMerge = options.arrayMerge || defaultArrayMerge;
options.isMergeableObject = options.isMergeableObject || isMergeableObject;
options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;
var sourceIsArray = Array.isArray(source);
var targetIsArray = Array.isArray(target);
var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
if (!sourceAndTargetTypesMatch) {
return cloneUnlessOtherwiseSpecified(source, options);
} else if (sourceIsArray) {
return options.arrayMerge(target, source, options);
} else {
return mergeObject(target, source, options);
}
}
deepmerge2.all = function deepmergeAll(array, options) {
if (!Array.isArray(array)) {
throw new Error("first argument should be an array");
}
return array.reduce(function(prev, next) {
return deepmerge2(prev, next, options);
}, {});
};
var deepmerge_1 = deepmerge2;
module.exports = deepmerge_1;
}
});
// package-external:@wordpress/a11y
var require_a11y = __commonJS({
"package-external:@wordpress/a11y"(exports, module) {
module.exports = window.wp.a11y;
}
});
// package-external:@wordpress/notices
var require_notices = __commonJS({
"package-external:@wordpress/notices"(exports, module) {
module.exports = window.wp.notices;
}
});
// package-external:@wordpress/preferences
var require_preferences = __commonJS({
"package-external:@wordpress/preferences"(exports, module) {
module.exports = window.wp.preferences;
}
});
// node_modules/remove-accents/index.js
var require_remove_accents = __commonJS({
"node_modules/remove-accents/index.js"(exports, module) {
var characterMap = {
"\xC0": "A",
"\xC1": "A",
"\xC2": "A",
"\xC3": "A",
"\xC4": "A",
"\xC5": "A",
"\u1EA4": "A",
"\u1EAE": "A",
"\u1EB2": "A",
"\u1EB4": "A",
"\u1EB6": "A",
"\xC6": "AE",
"\u1EA6": "A",
"\u1EB0": "A",
"\u0202": "A",
"\u1EA2": "A",
"\u1EA0": "A",
"\u1EA8": "A",
"\u1EAA": "A",
"\u1EAC": "A",
"\xC7": "C",
"\u1E08": "C",
"\xC8": "E",
"\xC9": "E",
"\xCA": "E",
"\xCB": "E",
"\u1EBE": "E",
"\u1E16": "E",
"\u1EC0": "E",
"\u1E14": "E",
"\u1E1C": "E",
"\u0206": "E",
"\u1EBA": "E",
"\u1EBC": "E",
"\u1EB8": "E",
"\u1EC2": "E",
"\u1EC4": "E",
"\u1EC6": "E",
"\xCC": "I",
"\xCD": "I",
"\xCE": "I",
"\xCF": "I",
"\u1E2E": "I",
"\u020A": "I",
"\u1EC8": "I",
"\u1ECA": "I",
"\xD0": "D",
"\xD1": "N",
"\xD2": "O",
"\xD3": "O",
"\xD4": "O",
"\xD5": "O",
"\xD6": "O",
"\xD8": "O",
"\u1ED0": "O",
"\u1E4C": "O",
"\u1E52": "O",
"\u020E": "O",
"\u1ECE": "O",
"\u1ECC": "O",
"\u1ED4": "O",
"\u1ED6": "O",
"\u1ED8": "O",
"\u1EDC": "O",
"\u1EDE": "O",
"\u1EE0": "O",
"\u1EDA": "O",
"\u1EE2": "O",
"\xD9": "U",
"\xDA": "U",
"\xDB": "U",
"\xDC": "U",
"\u1EE6": "U",
"\u1EE4": "U",
"\u1EEC": "U",
"\u1EEE": "U",
"\u1EF0": "U",
"\xDD": "Y",
"\xE0": "a",
"\xE1": "a",
"\xE2": "a",
"\xE3": "a",
"\xE4": "a",
"\xE5": "a",
"\u1EA5": "a",
"\u1EAF": "a",
"\u1EB3": "a",
"\u1EB5": "a",
"\u1EB7": "a",
"\xE6": "ae",
"\u1EA7": "a",
"\u1EB1": "a",
"\u0203": "a",
"\u1EA3": "a",
"\u1EA1": "a",
"\u1EA9": "a",
"\u1EAB": "a",
"\u1EAD": "a",
"\xE7": "c",
"\u1E09": "c",
"\xE8": "e",
"\xE9": "e",
"\xEA": "e",
"\xEB": "e",
"\u1EBF": "e",
"\u1E17": "e",
"\u1EC1": "e",
"\u1E15": "e",
"\u1E1D": "e",
"\u0207": "e",
"\u1EBB": "e",
"\u1EBD": "e",
"\u1EB9": "e",
"\u1EC3": "e",
"\u1EC5": "e",
"\u1EC7": "e",
"\xEC": "i",
"\xED": "i",
"\xEE": "i",
"\xEF": "i",
"\u1E2F": "i",
"\u020B": "i",
"\u1EC9": "i",
"\u1ECB": "i",
"\xF0": "d",
"\xF1": "n",
"\xF2": "o",
"\xF3": "o",
"\xF4": "o",
"\xF5": "o",
"\xF6": "o",
"\xF8": "o",
"\u1ED1": "o",
"\u1E4D": "o",
"\u1E53": "o",
"\u020F": "o",
"\u1ECF": "o",
"\u1ECD": "o",
"\u1ED5": "o",
"\u1ED7": "o",
"\u1ED9": "o",
"\u1EDD": "o",
"\u1EDF": "o",
"\u1EE1": "o",
"\u1EDB": "o",
"\u1EE3": "o",
"\xF9": "u",
"\xFA": "u",
"\xFB": "u",
"\xFC": "u",
"\u1EE7": "u",
"\u1EE5": "u",
"\u1EED": "u",
"\u1EEF": "u",
"\u1EF1": "u",
"\xFD": "y",
"\xFF": "y",
"\u0100": "A",
"\u0101": "a",
"\u0102": "A",
"\u0103": "a",
"\u0104": "A",
"\u0105": "a",
"\u0106": "C",
"\u0107": "c",
"\u0108": "C",
"\u0109": "c",
"\u010A": "C",
"\u010B": "c",
"\u010C": "C",
"\u010D": "c",
"C\u0306": "C",
"c\u0306": "c",
"\u010E": "D",
"\u010F": "d",
"\u0110": "D",
"\u0111": "d",
"\u0112": "E",
"\u0113": "e",
"\u0114": "E",
"\u0115": "e",
"\u0116": "E",
"\u0117": "e",
"\u0118": "E",
"\u0119": "e",
"\u011A": "E",
"\u011B": "e",
"\u011C": "G",
"\u01F4": "G",
"\u011D": "g",
"\u01F5": "g",
"\u011E": "G",
"\u011F": "g",
"\u0120": "G",
"\u0121": "g",
"\u0122": "G",
"\u0123": "g",
"\u0124": "H",
"\u0125": "h",
"\u0126": "H",
"\u0127": "h",
"\u1E2A": "H",
"\u1E2B": "h",
"\u0128": "I",
"\u0129": "i",
"\u012A": "I",
"\u012B": "i",
"\u012C": "I",
"\u012D": "i",
"\u012E": "I",
"\u012F": "i",
"\u0130": "I",
"\u0131": "i",
"\u0132": "IJ",
"\u0133": "ij",
"\u0134": "J",
"\u0135": "j",
"\u0136": "K",
"\u0137": "k",
"\u1E30": "K",
"\u1E31": "k",
"K\u0306": "K",
"k\u0306": "k",
"\u0139": "L",
"\u013A": "l",
"\u013B": "L",
"\u013C": "l",
"\u013D": "L",
"\u013E": "l",
"\u013F": "L",
"\u0140": "l",
"\u0141": "l",
"\u0142": "l",
"\u1E3E": "M",
"\u1E3F": "m",
"M\u0306": "M",
"m\u0306": "m",
"\u0143": "N",
"\u0144": "n",
"\u0145": "N",
"\u0146": "n",
"\u0147": "N",
"\u0148": "n",
"\u0149": "n",
"N\u0306": "N",
"n\u0306": "n",
"\u014C": "O",
"\u014D": "o",
"\u014E": "O",
"\u014F": "o",
"\u0150": "O",
"\u0151": "o",
"\u0152": "OE",
"\u0153": "oe",
"P\u0306": "P",
"p\u0306": "p",
"\u0154": "R",
"\u0155": "r",
"\u0156": "R",
"\u0157": "r",
"\u0158": "R",
"\u0159": "r",
"R\u0306": "R",
"r\u0306": "r",
"\u0212": "R",
"\u0213": "r",
"\u015A": "S",
"\u015B": "s",
"\u015C": "S",
"\u015D": "s",
"\u015E": "S",
"\u0218": "S",
"\u0219": "s",
"\u015F": "s",
"\u0160": "S",
"\u0161": "s",
"\u0162": "T",
"\u0163": "t",
"\u021B": "t",
"\u021A": "T",
"\u0164": "T",
"\u0165": "t",
"\u0166": "T",
"\u0167": "t",
"T\u0306": "T",
"t\u0306": "t",
"\u0168": "U",
"\u0169": "u",
"\u016A": "U",
"\u016B": "u",
"\u016C": "U",
"\u016D": "u",
"\u016E": "U",
"\u016F": "u",
"\u0170": "U",
"\u0171": "u",
"\u0172": "U",
"\u0173": "u",
"\u0216": "U",
"\u0217": "u",
"V\u0306": "V",
"v\u0306": "v",
"\u0174": "W",
"\u0175": "w",
"\u1E82": "W",
"\u1E83": "w",
"X\u0306": "X",
"x\u0306": "x",
"\u0176": "Y",
"\u0177": "y",
"\u0178": "Y",
"Y\u0306": "Y",
"y\u0306": "y",
"\u0179": "Z",
"\u017A": "z",
"\u017B": "Z",
"\u017C": "z",
"\u017D": "Z",
"\u017E": "z",
"\u017F": "s",
"\u0192": "f",
"\u01A0": "O",
"\u01A1": "o",
"\u01AF": "U",
"\u01B0": "u",
"\u01CD": "A",
"\u01CE": "a",
"\u01CF": "I",
"\u01D0": "i",
"\u01D1": "O",
"\u01D2": "o",
"\u01D3": "U",
"\u01D4": "u",
"\u01D5": "U",
"\u01D6": "u",
"\u01D7": "U",
"\u01D8": "u",
"\u01D9": "U",
"\u01DA": "u",
"\u01DB": "U",
"\u01DC": "u",
"\u1EE8": "U",
"\u1EE9": "u",
"\u1E78": "U",
"\u1E79": "u",
"\u01FA": "A",
"\u01FB": "a",
"\u01FC": "AE",
"\u01FD": "ae",
"\u01FE": "O",
"\u01FF": "o",
"\xDE": "TH",
"\xFE": "th",
"\u1E54": "P",
"\u1E55": "p",
"\u1E64": "S",
"\u1E65": "s",
"X\u0301": "X",
"x\u0301": "x",
"\u0403": "\u0413",
"\u0453": "\u0433",
"\u040C": "\u041A",
"\u045C": "\u043A",
"A\u030B": "A",
"a\u030B": "a",
"E\u030B": "E",
"e\u030B": "e",
"I\u030B": "I",
"i\u030B": "i",
"\u01F8": "N",
"\u01F9": "n",
"\u1ED2": "O",
"\u1ED3": "o",
"\u1E50": "O",
"\u1E51": "o",
"\u1EEA": "U",
"\u1EEB": "u",
"\u1E80": "W",
"\u1E81": "w",
"\u1EF2": "Y",
"\u1EF3": "y",
"\u0200": "A",
"\u0201": "a",
"\u0204": "E",
"\u0205": "e",
"\u0208": "I",
"\u0209": "i",
"\u020C": "O",
"\u020D": "o",
"\u0210": "R",
"\u0211": "r",
"\u0214": "U",
"\u0215": "u",
"B\u030C": "B",
"b\u030C": "b",
"\u010C\u0323": "C",
"\u010D\u0323": "c",
"\xCA\u030C": "E",
"\xEA\u030C": "e",
"F\u030C": "F",
"f\u030C": "f",
"\u01E6": "G",
"\u01E7": "g",
"\u021E": "H",
"\u021F": "h",
"J\u030C": "J",
"\u01F0": "j",
"\u01E8": "K",
"\u01E9": "k",
"M\u030C": "M",
"m\u030C": "m",
"P\u030C": "P",
"p\u030C": "p",
"Q\u030C": "Q",
"q\u030C": "q",
"\u0158\u0329": "R",
"\u0159\u0329": "r",
"\u1E66": "S",
"\u1E67": "s",
"V\u030C": "V",
"v\u030C": "v",
"W\u030C": "W",
"w\u030C": "w",
"X\u030C": "X",
"x\u030C": "x",
"Y\u030C": "Y",
"y\u030C": "y",
"A\u0327": "A",
"a\u0327": "a",
"B\u0327": "B",
"b\u0327": "b",
"\u1E10": "D",
"\u1E11": "d",
"\u0228": "E",
"\u0229": "e",
"\u0190\u0327": "E",
"\u025B\u0327": "e",
"\u1E28": "H",
"\u1E29": "h",
"I\u0327": "I",
"i\u0327": "i",
"\u0197\u0327": "I",
"\u0268\u0327": "i",
"M\u0327": "M",
"m\u0327": "m",
"O\u0327": "O",
"o\u0327": "o",
"Q\u0327": "Q",
"q\u0327": "q",
"U\u0327": "U",
"u\u0327": "u",
"X\u0327": "X",
"x\u0327": "x",
"Z\u0327": "Z",
"z\u0327": "z",
"\u0439": "\u0438",
"\u0419": "\u0418",
"\u0451": "\u0435",
"\u0401": "\u0415"
};
var chars = Object.keys(characterMap).join("|");
var allAccents = new RegExp(chars, "g");
var firstAccent = new RegExp(chars, "");
function matcher(match2) {
return characterMap[match2];
}
var removeAccents2 = function(string) {
return string.replace(allAccents, matcher);
};
var hasAccents = function(string) {
return !!string.match(firstAccent);
};
module.exports = removeAccents2;
module.exports.has = hasAccents;
module.exports.remove = removeAccents2;
}
});
// package-external:@wordpress/keycodes
var require_keycodes = __commonJS({
"package-external:@wordpress/keycodes"(exports, module) {
module.exports = window.wp.keycodes;
}
});
// package-external:@wordpress/dom
var require_dom = __commonJS({
"package-external:@wordpress/dom"(exports, module) {
module.exports = window.wp.dom;
}
});
// vendor-external:react
var require_react = __commonJS({
"vendor-external:react"(exports, module) {
module.exports = window.React;
}
});
// node_modules/react-is/cjs/react-is.development.js
var require_react_is_development = __commonJS({
"node_modules/react-is/cjs/react-is.development.js"(exports) {
"use strict";
if (true) {
(function() {
"use strict";
var hasSymbol = typeof Symbol === "function" && Symbol.for;
var REACT_ELEMENT_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.element") : 60103;
var REACT_PORTAL_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.portal") : 60106;
var REACT_FRAGMENT_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.fragment") : 60107;
var REACT_STRICT_MODE_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.strict_mode") : 60108;
var REACT_PROFILER_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.profiler") : 60114;
var REACT_PROVIDER_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.provider") : 60109;
var REACT_CONTEXT_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.context") : 60110;
var REACT_ASYNC_MODE_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.async_mode") : 60111;
var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.concurrent_mode") : 60111;
var REACT_FORWARD_REF_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.forward_ref") : 60112;
var REACT_SUSPENSE_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.suspense") : 60113;
var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.suspense_list") : 60120;
var REACT_MEMO_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.memo") : 60115;
var REACT_LAZY_TYPE2 = hasSymbol ? /* @__PURE__ */ Symbol.for("react.lazy") : 60116;
var REACT_BLOCK_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.block") : 60121;
var REACT_FUNDAMENTAL_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.fundamental") : 60117;
var REACT_RESPONDER_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.responder") : 60118;
var REACT_SCOPE_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.scope") : 60119;
function isValidElementType(type) {
return typeof type === "string" || typeof type === "function" || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === "object" && type !== null && (type.$$typeof === REACT_LAZY_TYPE2 || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE);
}
function typeOf(object) {
if (typeof object === "object" && object !== null) {
var $$typeof = object.$$typeof;
switch ($$typeof) {
case REACT_ELEMENT_TYPE:
var type = object.type;
switch (type) {
case REACT_ASYNC_MODE_TYPE:
case REACT_CONCURRENT_MODE_TYPE:
case REACT_FRAGMENT_TYPE:
case REACT_PROFILER_TYPE:
case REACT_STRICT_MODE_TYPE:
case REACT_SUSPENSE_TYPE:
return type;
default:
var $$typeofType = type && type.$$typeof;
switch ($$typeofType) {
case REACT_CONTEXT_TYPE:
case REACT_FORWARD_REF_TYPE:
case REACT_LAZY_TYPE2:
case REACT_MEMO_TYPE:
case REACT_PROVIDER_TYPE:
return $$typeofType;
default:
return $$typeof;
}
}
case REACT_PORTAL_TYPE:
return $$typeof;
}
}
return void 0;
}
var AsyncMode = REACT_ASYNC_MODE_TYPE;
var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
var ContextConsumer = REACT_CONTEXT_TYPE;
var ContextProvider = REACT_PROVIDER_TYPE;
var Element2 = REACT_ELEMENT_TYPE;
var ForwardRef = REACT_FORWARD_REF_TYPE;
var Fragment101 = REACT_FRAGMENT_TYPE;
var Lazy = REACT_LAZY_TYPE2;
var Memo = REACT_MEMO_TYPE;
var Portal3 = REACT_PORTAL_TYPE;
var Profiler = REACT_PROFILER_TYPE;
var StrictMode2 = REACT_STRICT_MODE_TYPE;
var Suspense = REACT_SUSPENSE_TYPE;
var hasWarnedAboutDeprecatedIsAsyncMode = false;
function isAsyncMode(object) {
{
if (!hasWarnedAboutDeprecatedIsAsyncMode) {
hasWarnedAboutDeprecatedIsAsyncMode = true;
console["warn"]("The ReactIs.isAsyncMode() alias has been deprecated, and will be removed in React 17+. Update your code to use ReactIs.isConcurrentMode() instead. It has the exact same API.");
}
}
return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;
}
function isConcurrentMode(object) {
return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;
}
function isContextConsumer(object) {
return typeOf(object) === REACT_CONTEXT_TYPE;
}
function isContextProvider(object) {
return typeOf(object) === REACT_PROVIDER_TYPE;
}
function isElement2(object) {
return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
function isForwardRef(object) {
return typeOf(object) === REACT_FORWARD_REF_TYPE;
}
function isFragment(object) {
return typeOf(object) === REACT_FRAGMENT_TYPE;
}
function isLazy(object) {
return typeOf(object) === REACT_LAZY_TYPE2;
}
function isMemo(object) {
return typeOf(object) === REACT_MEMO_TYPE;
}
function isPortal(object) {
return typeOf(object) === REACT_PORTAL_TYPE;
}
function isProfiler(object) {
return typeOf(object) === REACT_PROFILER_TYPE;
}
function isStrictMode(object) {
return typeOf(object) === REACT_STRICT_MODE_TYPE;
}
function isSuspense(object) {
return typeOf(object) === REACT_SUSPENSE_TYPE;
}
exports.AsyncMode = AsyncMode;
exports.ConcurrentMode = ConcurrentMode;
exports.ContextConsumer = ContextConsumer;
exports.ContextProvider = ContextProvider;
exports.Element = Element2;
exports.ForwardRef = ForwardRef;
exports.Fragment = Fragment101;
exports.Lazy = Lazy;
exports.Memo = Memo;
exports.Portal = Portal3;
exports.Profiler = Profiler;
exports.StrictMode = StrictMode2;
exports.Suspense = Suspense;
exports.isAsyncMode = isAsyncMode;
exports.isConcurrentMode = isConcurrentMode;
exports.isContextConsumer = isContextConsumer;
exports.isContextProvider = isContextProvider;
exports.isElement = isElement2;
exports.isForwardRef = isForwardRef;
exports.isFragment = isFragment;
exports.isLazy = isLazy;
exports.isMemo = isMemo;
exports.isPortal = isPortal;
exports.isProfiler = isProfiler;
exports.isStrictMode = isStrictMode;
exports.isSuspense = isSuspense;
exports.isValidElementType = isValidElementType;
exports.typeOf = typeOf;
})();
}
}
});
// node_modules/react-is/index.js
var require_react_is = __commonJS({
"node_modules/react-is/index.js"(exports, module) {
"use strict";
if (false) {
module.exports = null;
} else {
module.exports = require_react_is_development();
}
}
});
// node_modules/object-assign/index.js
var require_object_assign = __commonJS({
"node_modules/object-assign/index.js"(exports, module) {
"use strict";
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === void 0) {
throw new TypeError("Object.assign cannot be called with null or undefined");
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
var test1 = new String("abc");
test1[5] = "de";
if (Object.getOwnPropertyNames(test1)[0] === "5") {
return false;
}
var test2 = {};
for (var i2 = 0; i2 < 10; i2++) {
test2["_" + String.fromCharCode(i2)] = i2;
}
var order2 = Object.getOwnPropertyNames(test2).map(function(n2) {
return test2[n2];
});
if (order2.join("") !== "0123456789") {
return false;
}
var test3 = {};
"abcdefghijklmnopqrst".split("").forEach(function(letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") {
return false;
}
return true;
} catch (err) {
return false;
}
}
module.exports = shouldUseNative() ? Object.assign : function(target, source) {
var from;
var to2 = toObject(target);
var symbols;
for (var s2 = 1; s2 < arguments.length; s2++) {
from = Object(arguments[s2]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to2[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i2 = 0; i2 < symbols.length; i2++) {
if (propIsEnumerable.call(from, symbols[i2])) {
to2[symbols[i2]] = from[symbols[i2]];
}
}
}
}
return to2;
};
}
});
// node_modules/prop-types/lib/ReactPropTypesSecret.js
var require_ReactPropTypesSecret = __commonJS({
"node_modules/prop-types/lib/ReactPropTypesSecret.js"(exports, module) {
"use strict";
var ReactPropTypesSecret = "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";
module.exports = ReactPropTypesSecret;
}
});
// node_modules/prop-types/lib/has.js
var require_has = __commonJS({
"node_modules/prop-types/lib/has.js"(exports, module) {
module.exports = Function.call.bind(Object.prototype.hasOwnProperty);
}
});
// node_modules/prop-types/checkPropTypes.js
var require_checkPropTypes = __commonJS({
"node_modules/prop-types/checkPropTypes.js"(exports, module) {
"use strict";
var printWarning = function() {
};
if (true) {
ReactPropTypesSecret = require_ReactPropTypesSecret();
loggedTypeFailures = {};
has2 = require_has();
printWarning = function(text) {
var message2 = "Warning: " + text;
if (typeof console !== "undefined") {
console.error(message2);
}
try {
throw new Error(message2);
} catch (x2) {
}
};
}
var ReactPropTypesSecret;
var loggedTypeFailures;
var has2;
function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
if (true) {
for (var typeSpecName in typeSpecs) {
if (has2(typeSpecs, typeSpecName)) {
var error2;
try {
if (typeof typeSpecs[typeSpecName] !== "function") {
var err = Error(
(componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."
);
err.name = "Invariant Violation";
throw err;
}
error2 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
} catch (ex) {
error2 = ex;
}
if (error2 && !(error2 instanceof Error)) {
printWarning(
(componentName || "React class") + ": type specification of " + location + " `" + typeSpecName + "` is invalid; the type checker function must return `null` or an `Error` but returned a " + typeof error2 + ". You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument)."
);
}
if (error2 instanceof Error && !(error2.message in loggedTypeFailures)) {
loggedTypeFailures[error2.message] = true;
var stack = getStack ? getStack() : "";
printWarning(
"Failed " + location + " type: " + error2.message + (stack != null ? stack : "")
);
}
}
}
}
}
checkPropTypes.resetWarningCache = function() {
if (true) {
loggedTypeFailures = {};
}
};
module.exports = checkPropTypes;
}
});
// node_modules/prop-types/factoryWithTypeCheckers.js
var require_factoryWithTypeCheckers = __commonJS({
"node_modules/prop-types/factoryWithTypeCheckers.js"(exports, module) {
"use strict";
var ReactIs = require_react_is();
var assign2 = require_object_assign();
var ReactPropTypesSecret = require_ReactPropTypesSecret();
var has2 = require_has();
var checkPropTypes = require_checkPropTypes();
var printWarning = function() {
};
if (true) {
printWarning = function(text) {
var message2 = "Warning: " + text;
if (typeof console !== "undefined") {
console.error(message2);
}
try {
throw new Error(message2);
} catch (x2) {
}
};
}
function emptyFunctionThatReturnsNull() {
return null;
}
module.exports = function(isValidElement3, throwOnDirectAccess) {
var ITERATOR_SYMBOL = typeof Symbol === "function" && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = "@@iterator";
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === "function") {
return iteratorFn;
}
}
var ANONYMOUS = "<<anonymous>>";
var ReactPropTypes = {
array: createPrimitiveTypeChecker("array"),
bigint: createPrimitiveTypeChecker("bigint"),
bool: createPrimitiveTypeChecker("boolean"),
func: createPrimitiveTypeChecker("function"),
number: createPrimitiveTypeChecker("number"),
object: createPrimitiveTypeChecker("object"),
string: createPrimitiveTypeChecker("string"),
symbol: createPrimitiveTypeChecker("symbol"),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
elementType: createElementTypeTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker,
exact: createStrictShapeTypeChecker
};
function is2(x2, y2) {
if (x2 === y2) {
return x2 !== 0 || 1 / x2 === 1 / y2;
} else {
return x2 !== x2 && y2 !== y2;
}
}
function PropTypeError(message2, data) {
this.message = message2;
this.data = data && typeof data === "object" ? data : {};
this.stack = "";
}
PropTypeError.prototype = Error.prototype;
function createChainableTypeChecker(validate) {
if (true) {
var manualPropTypeCallCache = {};
var manualPropTypeWarningCount = 0;
}
function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (secret !== ReactPropTypesSecret) {
if (throwOnDirectAccess) {
var err = new Error(
"Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types"
);
err.name = "Invariant Violation";
throw err;
} else if (typeof console !== "undefined") {
var cacheKey2 = componentName + ":" + propName;
if (!manualPropTypeCallCache[cacheKey2] && // Avoid spamming the console because they are often not actionable except for lib authors
manualPropTypeWarningCount < 3) {
printWarning(
"You are manually calling a React.PropTypes validation function for the `" + propFullName + "` prop on `" + componentName + "`. This is deprecated and will throw in the standalone `prop-types` package. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details."
);
manualPropTypeCallCache[cacheKey2] = true;
manualPropTypeWarningCount++;
}
}
}
if (props[propName] == null) {
if (isRequired) {
if (props[propName] === null) {
return new PropTypeError("The " + location + " `" + propFullName + "` is marked as required " + ("in `" + componentName + "`, but its value is `null`."));
}
return new PropTypeError("The " + location + " `" + propFullName + "` is marked as required in " + ("`" + componentName + "`, but its value is `undefined`."));
}
return null;
} else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location, propFullName, secret) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
var preciseType = getPreciseType(propValue);
return new PropTypeError(
"Invalid " + location + " `" + propFullName + "` of type " + ("`" + preciseType + "` supplied to `" + componentName + "`, expected ") + ("`" + expectedType + "`."),
{ expectedType }
);
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunctionThatReturnsNull);
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== "function") {
return new PropTypeError("Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside arrayOf.");
}
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected an array."));
}
for (var i2 = 0; i2 < propValue.length; i2++) {
var error2 = typeChecker(propValue, i2, componentName, location, propFullName + "[" + i2 + "]", ReactPropTypesSecret);
if (error2 instanceof Error) {
return error2;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!isValidElement3(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected a single ReactElement."));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!ReactIs.isValidElementType(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected a single ReactElement type."));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location, propFullName) {
if (!(props[propName] instanceof expectedClass)) {
var expectedClassName = expectedClass.name || ANONYMOUS;
var actualClassName = getClassName(props[propName]);
return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + actualClassName + "` supplied to `" + componentName + "`, expected ") + ("instance of `" + expectedClassName + "`."));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
if (!Array.isArray(expectedValues)) {
if (true) {
if (arguments.length > 1) {
printWarning(
"Invalid arguments supplied to oneOf, expected an array, got " + arguments.length + " arguments. A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z])."
);
} else {
printWarning("Invalid argument supplied to oneOf, expected an array.");
}
}
return emptyFunctionThatReturnsNull;
}
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
for (var i2 = 0; i2 < expectedValues.length; i2++) {
if (is2(propValue, expectedValues[i2])) {
return null;
}
}
var valuesString = JSON.stringify(expectedValues, function replacer(key, value) {
var type = getPreciseType(value);
if (type === "symbol") {
return String(value);
}
return value;
});
return new PropTypeError("Invalid " + location + " `" + propFullName + "` of value `" + String(propValue) + "` " + ("supplied to `" + componentName + "`, expected one of " + valuesString + "."));
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== "function") {
return new PropTypeError("Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside objectOf.");
}
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== "object") {
return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected an object."));
}
for (var key in propValue) {
if (has2(propValue, key)) {
var error2 = typeChecker(propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret);
if (error2 instanceof Error) {
return error2;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
true ? printWarning("Invalid argument supplied to oneOfType, expected an instance of array.") : void 0;
return emptyFunctionThatReturnsNull;
}
for (var i2 = 0; i2 < arrayOfTypeCheckers.length; i2++) {
var checker = arrayOfTypeCheckers[i2];
if (typeof checker !== "function") {
printWarning(
"Invalid argument supplied to oneOfType. Expected an array of check functions, but received " + getPostfixForTypeWarning(checker) + " at index " + i2 + "."
);
return emptyFunctionThatReturnsNull;
}
}
function validate(props, propName, componentName, location, propFullName) {
var expectedTypes = [];
for (var i3 = 0; i3 < arrayOfTypeCheckers.length; i3++) {
var checker2 = arrayOfTypeCheckers[i3];
var checkerResult = checker2(props, propName, componentName, location, propFullName, ReactPropTypesSecret);
if (checkerResult == null) {
return null;
}
if (checkerResult.data && has2(checkerResult.data, "expectedType")) {
expectedTypes.push(checkerResult.data.expectedType);
}
}
var expectedTypesMessage = expectedTypes.length > 0 ? ", expected one of type [" + expectedTypes.join(", ") + "]" : "";
return new PropTypeError("Invalid " + location + " `" + propFullName + "` supplied to " + ("`" + componentName + "`" + expectedTypesMessage + "."));
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!isNode2(props[propName])) {
return new PropTypeError("Invalid " + location + " `" + propFullName + "` supplied to " + ("`" + componentName + "`, expected a ReactNode."));
}
return null;
}
return createChainableTypeChecker(validate);
}
function invalidValidatorError(componentName, location, propFullName, key, type) {
return new PropTypeError(
(componentName || "React class") + ": " + location + " type `" + propFullName + "." + key + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + type + "`."
);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== "object") {
return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type `" + propType + "` " + ("supplied to `" + componentName + "`, expected `object`."));
}
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (typeof checker !== "function") {
return invalidValidatorError(componentName, location, propFullName, key, getPreciseType(checker));
}
var error2 = checker(propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret);
if (error2) {
return error2;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createStrictShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== "object") {
return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type `" + propType + "` " + ("supplied to `" + componentName + "`, expected `object`."));
}
var allKeys = assign2({}, props[propName], shapeTypes);
for (var key in allKeys) {
var checker = shapeTypes[key];
if (has2(shapeTypes, key) && typeof checker !== "function") {
return invalidValidatorError(componentName, location, propFullName, key, getPreciseType(checker));
}
if (!checker) {
return new PropTypeError(
"Invalid " + location + " `" + propFullName + "` key `" + key + "` supplied to `" + componentName + "`.\nBad object: " + JSON.stringify(props[propName], null, " ") + "\nValid keys: " + JSON.stringify(Object.keys(shapeTypes), null, " ")
);
}
var error2 = checker(propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret);
if (error2) {
return error2;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode2(propValue) {
switch (typeof propValue) {
case "number":
case "string":
case "undefined":
return true;
case "boolean":
return !propValue;
case "object":
if (Array.isArray(propValue)) {
return propValue.every(isNode2);
}
if (propValue === null || isValidElement3(propValue)) {
return true;
}
var iteratorFn = getIteratorFn(propValue);
if (iteratorFn) {
var iterator = iteratorFn.call(propValue);
var step;
if (iteratorFn !== propValue.entries) {
while (!(step = iterator.next()).done) {
if (!isNode2(step.value)) {
return false;
}
}
} else {
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
if (!isNode2(entry[1])) {
return false;
}
}
}
}
} else {
return false;
}
return true;
default:
return false;
}
}
function isSymbol(propType, propValue) {
if (propType === "symbol") {
return true;
}
if (!propValue) {
return false;
}
if (propValue["@@toStringTag"] === "Symbol") {
return true;
}
if (typeof Symbol === "function" && propValue instanceof Symbol) {
return true;
}
return false;
}
function getPropType(propValue) {
var propType = typeof propValue;
if (Array.isArray(propValue)) {
return "array";
}
if (propValue instanceof RegExp) {
return "object";
}
if (isSymbol(propType, propValue)) {
return "symbol";
}
return propType;
}
function getPreciseType(propValue) {
if (typeof propValue === "undefined" || propValue === null) {
return "" + propValue;
}
var propType = getPropType(propValue);
if (propType === "object") {
if (propValue instanceof Date) {
return "date";
} else if (propValue instanceof RegExp) {
return "regexp";
}
}
return propType;
}
function getPostfixForTypeWarning(value) {
var type = getPreciseType(value);
switch (type) {
case "array":
case "object":
return "an " + type;
case "boolean":
case "date":
case "regexp":
return "a " + type;
default:
return type;
}
}
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return ANONYMOUS;
}
return propValue.constructor.name;
}
ReactPropTypes.checkPropTypes = checkPropTypes;
ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
}
});
// node_modules/prop-types/index.js
var require_prop_types = __commonJS({
"node_modules/prop-types/index.js"(exports, module) {
if (true) {
ReactIs = require_react_is();
throwOnDirectAccess = true;
module.exports = require_factoryWithTypeCheckers()(ReactIs.isElement, throwOnDirectAccess);
} else {
module.exports = null();
}
var ReactIs;
var throwOnDirectAccess;
}
});
// node_modules/autosize/dist/autosize.js
var require_autosize = __commonJS({
"node_modules/autosize/dist/autosize.js"(exports, module) {
(function(global, factory) {
if (typeof define === "function" && define.amd) {
define(["module", "exports"], factory);
} else if (typeof exports !== "undefined") {
factory(module, exports);
} else {
var mod = {
exports: {}
};
factory(mod, mod.exports);
global.autosize = mod.exports;
}
})(exports, function(module2, exports2) {
"use strict";
var map = typeof Map === "function" ? /* @__PURE__ */ new Map() : /* @__PURE__ */ (function() {
var keys = [];
var values = [];
return {
has: function has2(key) {
return keys.indexOf(key) > -1;
},
get: function get(key) {
return values[keys.indexOf(key)];
},
set: function set3(key, value) {
if (keys.indexOf(key) === -1) {
keys.push(key);
values.push(value);
}
},
delete: function _delete(key) {
var index2 = keys.indexOf(key);
if (index2 > -1) {
keys.splice(index2, 1);
values.splice(index2, 1);
}
}
};
})();
var createEvent = function createEvent2(name) {
return new Event(name, { bubbles: true });
};
try {
new Event("test");
} catch (e2) {
createEvent = function createEvent2(name) {
var evt = document.createEvent("Event");
evt.initEvent(name, true, false);
return evt;
};
}
function assign2(ta) {
if (!ta || !ta.nodeName || ta.nodeName !== "TEXTAREA" || map.has(ta)) return;
var heightOffset = null;
var clientWidth = null;
var cachedHeight = null;
function init() {
var style = window.getComputedStyle(ta, null);
if (style.resize === "vertical") {
ta.style.resize = "none";
} else if (style.resize === "both") {
ta.style.resize = "horizontal";
}
if (style.boxSizing === "content-box") {
heightOffset = -(parseFloat(style.paddingTop) + parseFloat(style.paddingBottom));
} else {
heightOffset = parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth);
}
if (isNaN(heightOffset)) {
heightOffset = 0;
}
update5();
}
function changeOverflow(value) {
{
var width = ta.style.width;
ta.style.width = "0px";
ta.offsetWidth;
ta.style.width = width;
}
ta.style.overflowY = value;
}
function getParentOverflows(el) {
var arr = [];
while (el && el.parentNode && el.parentNode instanceof Element) {
if (el.parentNode.scrollTop) {
arr.push({
node: el.parentNode,
scrollTop: el.parentNode.scrollTop
});
}
el = el.parentNode;
}
return arr;
}
function resize() {
if (ta.scrollHeight === 0) {
return;
}
var overflows = getParentOverflows(ta);
var docTop = document.documentElement && document.documentElement.scrollTop;
ta.style.height = "";
ta.style.height = ta.scrollHeight + heightOffset + "px";
clientWidth = ta.clientWidth;
overflows.forEach(function(el) {
el.node.scrollTop = el.scrollTop;
});
if (docTop) {
document.documentElement.scrollTop = docTop;
}
}
function update5() {
resize();
var styleHeight = Math.round(parseFloat(ta.style.height));
var computed = window.getComputedStyle(ta, null);
var actualHeight = computed.boxSizing === "content-box" ? Math.round(parseFloat(computed.height)) : ta.offsetHeight;
if (actualHeight < styleHeight) {
if (computed.overflowY === "hidden") {
changeOverflow("scroll");
resize();
actualHeight = computed.boxSizing === "content-box" ? Math.round(parseFloat(window.getComputedStyle(ta, null).height)) : ta.offsetHeight;
}
} else {
if (computed.overflowY !== "hidden") {
changeOverflow("hidden");
resize();
actualHeight = computed.boxSizing === "content-box" ? Math.round(parseFloat(window.getComputedStyle(ta, null).height)) : ta.offsetHeight;
}
}
if (cachedHeight !== actualHeight) {
cachedHeight = actualHeight;
var evt = createEvent("autosize:resized");
try {
ta.dispatchEvent(evt);
} catch (err) {
}
}
}
var pageResize = function pageResize2() {
if (ta.clientWidth !== clientWidth) {
update5();
}
};
var destroy2 = function(style) {
window.removeEventListener("resize", pageResize, false);
ta.removeEventListener("input", update5, false);
ta.removeEventListener("keyup", update5, false);
ta.removeEventListener("autosize:destroy", destroy2, false);
ta.removeEventListener("autosize:update", update5, false);
Object.keys(style).forEach(function(key) {
ta.style[key] = style[key];
});
map.delete(ta);
}.bind(ta, {
height: ta.style.height,
resize: ta.style.resize,
overflowY: ta.style.overflowY,
overflowX: ta.style.overflowX,
wordWrap: ta.style.wordWrap
});
ta.addEventListener("autosize:destroy", destroy2, false);
if ("onpropertychange" in ta && "oninput" in ta) {
ta.addEventListener("keyup", update5, false);
}
window.addEventListener("resize", pageResize, false);
ta.addEventListener("input", update5, false);
ta.addEventListener("autosize:update", update5, false);
ta.style.overflowX = "hidden";
ta.style.wordWrap = "break-word";
map.set(ta, {
destroy: destroy2,
update: update5
});
init();
}
function destroy(ta) {
var methods = map.get(ta);
if (methods) {
methods.destroy();
}
}
function update4(ta) {
var methods = map.get(ta);
if (methods) {
methods.update();
}
}
var autosize = null;
if (typeof window === "undefined" || typeof window.getComputedStyle !== "function") {
autosize = function autosize2(el) {
return el;
};
autosize.destroy = function(el) {
return el;
};
autosize.update = function(el) {
return el;
};
} else {
autosize = function autosize2(el, options) {
if (el) {
Array.prototype.forEach.call(el.length ? el : [el], function(x2) {
return assign2(x2, options);
});
}
return el;
};
autosize.destroy = function(el) {
if (el) {
Array.prototype.forEach.call(el.length ? el : [el], destroy);
}
return el;
};
autosize.update = function(el) {
if (el) {
Array.prototype.forEach.call(el.length ? el : [el], update4);
}
return el;
};
}
exports2.default = autosize;
module2.exports = exports2["default"];
});
}
});
// node_modules/computed-style/dist/computedStyle.commonjs.js
var require_computedStyle_commonjs = __commonJS({
"node_modules/computed-style/dist/computedStyle.commonjs.js"(exports, module) {
var computedStyle = function(el, prop, getComputedStyle3) {
getComputedStyle3 = window.getComputedStyle;
return (
// If we have getComputedStyle
(getComputedStyle3 ? (
// Query it
// TODO: From CSS-Query notes, we might need (node, null) for FF
getComputedStyle3(el)
) : (
// Otherwise, we are in IE and use currentStyle
el.currentStyle
))[
// Switch to camelCase for CSSOM
// DEV: Grabbed from jQuery
// https://github.com/jquery/jquery/blob/1.9-stable/src/css.js#L191-L194
// https://github.com/jquery/jquery/blob/1.9-stable/src/core.js#L593-L597
prop.replace(/-(\w)/gi, function(word, letter) {
return letter.toUpperCase();
})
]
);
};
module.exports = computedStyle;
}
});
// node_modules/line-height/lib/line-height.js
var require_line_height = __commonJS({
"node_modules/line-height/lib/line-height.js"(exports, module) {
var computedStyle = require_computedStyle_commonjs();
function lineHeight(node) {
var lnHeightStr = computedStyle(node, "line-height");
var lnHeight = parseFloat(lnHeightStr, 10);
if (lnHeightStr === lnHeight + "") {
var _lnHeightStyle = node.style.lineHeight;
node.style.lineHeight = lnHeightStr + "em";
lnHeightStr = computedStyle(node, "line-height");
lnHeight = parseFloat(lnHeightStr, 10);
if (_lnHeightStyle) {
node.style.lineHeight = _lnHeightStyle;
} else {
delete node.style.lineHeight;
}
}
if (lnHeightStr.indexOf("pt") !== -1) {
lnHeight *= 4;
lnHeight /= 3;
} else if (lnHeightStr.indexOf("mm") !== -1) {
lnHeight *= 96;
lnHeight /= 25.4;
} else if (lnHeightStr.indexOf("cm") !== -1) {
lnHeight *= 96;
lnHeight /= 2.54;
} else if (lnHeightStr.indexOf("in") !== -1) {
lnHeight *= 96;
} else if (lnHeightStr.indexOf("pc") !== -1) {
lnHeight *= 16;
}
lnHeight = Math.round(lnHeight);
if (lnHeightStr === "normal") {
var nodeName = node.nodeName;
var _node = document.createElement(nodeName);
_node.innerHTML = " ";
if (nodeName.toUpperCase() === "TEXTAREA") {
_node.setAttribute("rows", "1");
}
var fontSizeStr = computedStyle(node, "font-size");
_node.style.fontSize = fontSizeStr;
_node.style.padding = "0px";
_node.style.border = "0px";
var body = document.body;
body.appendChild(_node);
var height = _node.offsetHeight;
lnHeight = height;
body.removeChild(_node);
}
return lnHeight;
}
module.exports = lineHeight;
}
});
// node_modules/react-autosize-textarea/lib/TextareaAutosize.js
var require_TextareaAutosize = __commonJS({
"node_modules/react-autosize-textarea/lib/TextareaAutosize.js"(exports) {
"use strict";
var __extends2 = exports && exports.__extends || (function() {
var extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
d2.__proto__ = b2;
} || function(d2, b2) {
for (var p2 in b2) if (b2.hasOwnProperty(p2)) d2[p2] = b2[p2];
};
return function(d2, b2) {
extendStatics2(d2, b2);
function __231() {
this.constructor = d2;
}
d2.prototype = b2 === null ? Object.create(b2) : (__231.prototype = b2.prototype, new __231());
};
})();
var __assign2 = exports && exports.__assign || Object.assign || function(t3) {
for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
s2 = arguments[i2];
for (var p2 in s2) if (Object.prototype.hasOwnProperty.call(s2, p2))
t3[p2] = s2[p2];
}
return t3;
};
var __rest = exports && exports.__rest || function(s2, e2) {
var t3 = {};
for (var p2 in s2) if (Object.prototype.hasOwnProperty.call(s2, p2) && e2.indexOf(p2) < 0)
t3[p2] = s2[p2];
if (s2 != null && typeof Object.getOwnPropertySymbols === "function") {
for (var i2 = 0, p2 = Object.getOwnPropertySymbols(s2); i2 < p2.length; i2++) if (e2.indexOf(p2[i2]) < 0)
t3[p2[i2]] = s2[p2[i2]];
}
return t3;
};
exports.__esModule = true;
var React118 = require_react();
var PropTypes = require_prop_types();
var autosize = require_autosize();
var _getLineHeight = require_line_height();
var getLineHeight = _getLineHeight;
var RESIZED = "autosize:resized";
var TextareaAutosizeClass = (
/** @class */
(function(_super) {
__extends2(TextareaAutosizeClass2, _super);
function TextareaAutosizeClass2() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.state = {
lineHeight: null
};
_this.textarea = null;
_this.onResize = function(e2) {
if (_this.props.onResize) {
_this.props.onResize(e2);
}
};
_this.updateLineHeight = function() {
if (_this.textarea) {
_this.setState({
lineHeight: getLineHeight(_this.textarea)
});
}
};
_this.onChange = function(e2) {
var onChange = _this.props.onChange;
_this.currentValue = e2.currentTarget.value;
onChange && onChange(e2);
};
return _this;
}
TextareaAutosizeClass2.prototype.componentDidMount = function() {
var _this = this;
var _a = this.props, maxRows = _a.maxRows, async = _a.async;
if (typeof maxRows === "number") {
this.updateLineHeight();
}
if (typeof maxRows === "number" || async) {
setTimeout(function() {
return _this.textarea && autosize(_this.textarea);
});
} else {
this.textarea && autosize(this.textarea);
}
if (this.textarea) {
this.textarea.addEventListener(RESIZED, this.onResize);
}
};
TextareaAutosizeClass2.prototype.componentWillUnmount = function() {
if (this.textarea) {
this.textarea.removeEventListener(RESIZED, this.onResize);
autosize.destroy(this.textarea);
}
};
TextareaAutosizeClass2.prototype.render = function() {
var _this = this;
var _a = this, _b = _a.props, onResize = _b.onResize, maxRows = _b.maxRows, onChange = _b.onChange, style = _b.style, innerRef = _b.innerRef, children = _b.children, props = __rest(_b, ["onResize", "maxRows", "onChange", "style", "innerRef", "children"]), lineHeight = _a.state.lineHeight;
var maxHeight = maxRows && lineHeight ? lineHeight * maxRows : null;
return React118.createElement("textarea", __assign2({}, props, { onChange: this.onChange, style: maxHeight ? __assign2({}, style, { maxHeight }) : style, ref: function(element) {
_this.textarea = element;
if (typeof _this.props.innerRef === "function") {
_this.props.innerRef(element);
} else if (_this.props.innerRef) {
_this.props.innerRef.current = element;
}
} }), children);
};
TextareaAutosizeClass2.prototype.componentDidUpdate = function() {
this.textarea && autosize.update(this.textarea);
};
TextareaAutosizeClass2.defaultProps = {
rows: 1,
async: false
};
TextareaAutosizeClass2.propTypes = {
rows: PropTypes.number,
maxRows: PropTypes.number,
onResize: PropTypes.func,
innerRef: PropTypes.any,
async: PropTypes.bool
};
return TextareaAutosizeClass2;
})(React118.Component)
);
exports.TextareaAutosize = React118.forwardRef(function(props, ref) {
return React118.createElement(TextareaAutosizeClass, __assign2({}, props, { innerRef: ref }));
});
}
});
// node_modules/react-autosize-textarea/lib/index.js
var require_lib = __commonJS({
"node_modules/react-autosize-textarea/lib/index.js"(exports, module) {
"use strict";
var TextareaAutosize_1 = require_TextareaAutosize();
module.exports = TextareaAutosize_1.TextareaAutosize;
}
});
// package-external:@wordpress/warning
var require_warning = __commonJS({
"package-external:@wordpress/warning"(exports, module) {
module.exports = window.wp.warning;
}
});
// vendor-external:react-dom
var require_react_dom = __commonJS({
"vendor-external:react-dom"(exports, module) {
module.exports = window.ReactDOM;
}
});
// package-external:@wordpress/keyboard-shortcuts
var require_keyboard_shortcuts = __commonJS({
"package-external:@wordpress/keyboard-shortcuts"(exports, module) {
module.exports = window.wp.keyboardShortcuts;
}
});
// package-external:@wordpress/html-entities
var require_html_entities = __commonJS({
"package-external:@wordpress/html-entities"(exports, module) {
module.exports = window.wp.htmlEntities;
}
});
// node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js
var require_use_sync_external_store_shim_development = __commonJS({
"node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js"(exports) {
"use strict";
(function() {
function is2(x2, y2) {
return x2 === y2 && (0 !== x2 || 1 / x2 === 1 / y2) || x2 !== x2 && y2 !== y2;
}
function useSyncExternalStore$2(subscribe, getSnapshot) {
didWarnOld18Alpha || void 0 === React118.startTransition || (didWarnOld18Alpha = true, console.error(
"You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."
));
var value = getSnapshot();
if (!didWarnUncachedGetSnapshot) {
var cachedValue = getSnapshot();
objectIs(value, cachedValue) || (console.error(
"The result of getSnapshot should be cached to avoid an infinite loop"
), didWarnUncachedGetSnapshot = true);
}
cachedValue = useState122({
inst: { value, getSnapshot }
});
var inst = cachedValue[0].inst, forceUpdate = cachedValue[1];
useLayoutEffect18(
function() {
inst.value = value;
inst.getSnapshot = getSnapshot;
checkIfSnapshotChanged(inst) && forceUpdate({ inst });
},
[subscribe, value, getSnapshot]
);
useEffect94(
function() {
checkIfSnapshotChanged(inst) && forceUpdate({ inst });
return subscribe(function() {
checkIfSnapshotChanged(inst) && forceUpdate({ inst });
});
},
[subscribe]
);
useDebugValue2(value);
return value;
}
function checkIfSnapshotChanged(inst) {
var latestGetSnapshot = inst.getSnapshot;
inst = inst.value;
try {
var nextValue = latestGetSnapshot();
return !objectIs(inst, nextValue);
} catch (error2) {
return true;
}
}
function useSyncExternalStore$1(subscribe, getSnapshot) {
return getSnapshot();
}
"undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
var React118 = require_react(), objectIs = "function" === typeof Object.is ? Object.is : is2, useState122 = React118.useState, useEffect94 = React118.useEffect, useLayoutEffect18 = React118.useLayoutEffect, useDebugValue2 = React118.useDebugValue, didWarnOld18Alpha = false, didWarnUncachedGetSnapshot = false, shim = "undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement ? useSyncExternalStore$1 : useSyncExternalStore$2;
exports.useSyncExternalStore = void 0 !== React118.useSyncExternalStore ? React118.useSyncExternalStore : shim;
"undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
})();
}
});
// node_modules/use-sync-external-store/shim/index.js
var require_shim = __commonJS({
"node_modules/use-sync-external-store/shim/index.js"(exports, module) {
"use strict";
if (false) {
module.exports = null;
} else {
module.exports = require_use_sync_external_store_shim_development();
}
}
});
// node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js
var require_with_selector_development = __commonJS({
"node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js"(exports) {
"use strict";
(function() {
function is2(x2, y2) {
return x2 === y2 && (0 !== x2 || 1 / x2 === 1 / y2) || x2 !== x2 && y2 !== y2;
}
"undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
var React118 = require_react(), shim = require_shim(), objectIs = "function" === typeof Object.is ? Object.is : is2, useSyncExternalStore2 = shim.useSyncExternalStore, useRef108 = React118.useRef, useEffect94 = React118.useEffect, useMemo154 = React118.useMemo, useDebugValue2 = React118.useDebugValue;
exports.useSyncExternalStoreWithSelector = function(subscribe, getSnapshot, getServerSnapshot, selector3, isEqual2) {
var instRef = useRef108(null);
if (null === instRef.current) {
var inst = { hasValue: false, value: null };
instRef.current = inst;
} else inst = instRef.current;
instRef = useMemo154(
function() {
function memoizedSelector(nextSnapshot) {
if (!hasMemo) {
hasMemo = true;
memoizedSnapshot = nextSnapshot;
nextSnapshot = selector3(nextSnapshot);
if (void 0 !== isEqual2 && inst.hasValue) {
var currentSelection = inst.value;
if (isEqual2(currentSelection, nextSnapshot))
return memoizedSelection = currentSelection;
}
return memoizedSelection = nextSnapshot;
}
currentSelection = memoizedSelection;
if (objectIs(memoizedSnapshot, nextSnapshot))
return currentSelection;
var nextSelection = selector3(nextSnapshot);
if (void 0 !== isEqual2 && isEqual2(currentSelection, nextSelection))
return memoizedSnapshot = nextSnapshot, currentSelection;
memoizedSnapshot = nextSnapshot;
return memoizedSelection = nextSelection;
}
var hasMemo = false, memoizedSnapshot, memoizedSelection, maybeGetServerSnapshot = void 0 === getServerSnapshot ? null : getServerSnapshot;
return [
function() {
return memoizedSelector(getSnapshot());
},
null === maybeGetServerSnapshot ? void 0 : function() {
return memoizedSelector(maybeGetServerSnapshot());
}
];
},
[getSnapshot, getServerSnapshot, selector3, isEqual2]
);
var value = useSyncExternalStore2(subscribe, instRef[0], instRef[1]);
useEffect94(
function() {
inst.hasValue = true;
inst.value = value;
},
[value]
);
useDebugValue2(value);
return value;
};
"undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
})();
}
});
// node_modules/use-sync-external-store/shim/with-selector.js
var require_with_selector = __commonJS({
"node_modules/use-sync-external-store/shim/with-selector.js"(exports, module) {
"use strict";
if (false) {
module.exports = null;
} else {
module.exports = require_with_selector_development();
}
}
});
// package-external:@wordpress/theme
var require_theme = __commonJS({
"package-external:@wordpress/theme"(exports, module) {
module.exports = window.wp.theme;
}
});
// package-external:@wordpress/upload-media
var require_upload_media = __commonJS({
"package-external:@wordpress/upload-media"(exports, module) {
module.exports = window.wp.uploadMedia;
}
});
// node_modules/picocolors/picocolors.browser.js
var require_picocolors_browser = __commonJS({
"node_modules/picocolors/picocolors.browser.js"(exports, module) {
var x2 = String;
var create6 = function() {
return { isColorSupported: false, reset: x2, bold: x2, dim: x2, italic: x2, underline: x2, inverse: x2, hidden: x2, strikethrough: x2, black: x2, red: x2, green: x2, yellow: x2, blue: x2, magenta: x2, cyan: x2, white: x2, gray: x2, bgBlack: x2, bgRed: x2, bgGreen: x2, bgYellow: x2, bgBlue: x2, bgMagenta: x2, bgCyan: x2, bgWhite: x2, blackBright: x2, redBright: x2, greenBright: x2, yellowBright: x2, blueBright: x2, magentaBright: x2, cyanBright: x2, whiteBright: x2, bgBlackBright: x2, bgRedBright: x2, bgGreenBright: x2, bgYellowBright: x2, bgBlueBright: x2, bgMagentaBright: x2, bgCyanBright: x2, bgWhiteBright: x2 };
};
module.exports = create6();
module.exports.createColors = create6;
}
});
// (disabled):node_modules/postcss/lib/terminal-highlight
var require_terminal_highlight = __commonJS({
"(disabled):node_modules/postcss/lib/terminal-highlight"() {
}
});
// node_modules/postcss/lib/css-syntax-error.js
var require_css_syntax_error = __commonJS({
"node_modules/postcss/lib/css-syntax-error.js"(exports, module) {
"use strict";
var pico = require_picocolors_browser();
var terminalHighlight = require_terminal_highlight();
var CssSyntaxError2 = class _CssSyntaxError extends Error {
constructor(message2, line, column, source, file, plugin) {
super(message2);
this.name = "CssSyntaxError";
this.reason = message2;
if (file) {
this.file = file;
}
if (source) {
this.source = source;
}
if (plugin) {
this.plugin = plugin;
}
if (typeof line !== "undefined" && typeof column !== "undefined") {
if (typeof line === "number") {
this.line = line;
this.column = column;
} else {
this.line = line.line;
this.column = line.column;
this.endLine = column.line;
this.endColumn = column.column;
}
}
this.setMessage();
if (Error.captureStackTrace) {
Error.captureStackTrace(this, _CssSyntaxError);
}
}
setMessage() {
this.message = this.plugin ? this.plugin + ": " : "";
this.message += this.file ? this.file : "<css input>";
if (typeof this.line !== "undefined") {
this.message += ":" + this.line + ":" + this.column;
}
this.message += ": " + this.reason;
}
showSourceCode(color) {
if (!this.source) return "";
let css = this.source;
if (color == null) color = pico.isColorSupported;
let aside = (text) => text;
let mark = (text) => text;
let highlight = (text) => text;
if (color) {
let { bold, gray, red } = pico.createColors(true);
mark = (text) => bold(red(text));
aside = (text) => gray(text);
if (terminalHighlight) {
highlight = (text) => terminalHighlight(text);
}
}
let lines = css.split(/\r?\n/);
let start2 = Math.max(this.line - 3, 0);
let end = Math.min(this.line + 2, lines.length);
let maxWidth = String(end).length;
return lines.slice(start2, end).map((line, index2) => {
let number = start2 + 1 + index2;
let gutter = " " + (" " + number).slice(-maxWidth) + " | ";
if (number === this.line) {
if (line.length > 160) {
let padding = 20;
let subLineStart = Math.max(0, this.column - padding);
let subLineEnd = Math.max(
this.column + padding,
this.endColumn + padding
);
let subLine = line.slice(subLineStart, subLineEnd);
let spacing2 = aside(gutter.replace(/\d/g, " ")) + line.slice(0, Math.min(this.column - 1, padding - 1)).replace(/[^\t]/g, " ");
return mark(">") + aside(gutter) + highlight(subLine) + "\n " + spacing2 + mark("^");
}
let spacing = aside(gutter.replace(/\d/g, " ")) + line.slice(0, this.column - 1).replace(/[^\t]/g, " ");
return mark(">") + aside(gutter) + highlight(line) + "\n " + spacing + mark("^");
}
return " " + aside(gutter) + highlight(line);
}).join("\n");
}
toString() {
let code = this.showSourceCode();
if (code) {
code = "\n\n" + code + "\n";
}
return this.name + ": " + this.message + code;
}
};
module.exports = CssSyntaxError2;
CssSyntaxError2.default = CssSyntaxError2;
}
});
// node_modules/postcss/lib/stringifier.js
var require_stringifier = __commonJS({
"node_modules/postcss/lib/stringifier.js"(exports, module) {
"use strict";
var STYLE_TAG = /(<)(\/?style\b)/gi;
var COMMENT_OPEN = /(<)(!--)/g;
function escapeHTMLInCSS(str) {
if (typeof str !== "string") return str;
if (!str.includes("<")) return str;
return str.replace(STYLE_TAG, "\\3c $2").replace(COMMENT_OPEN, "\\3c $2");
}
var DEFAULT_RAW = {
after: "\n",
beforeClose: "\n",
beforeComment: "\n",
beforeDecl: "\n",
beforeOpen: " ",
beforeRule: "\n",
colon: ": ",
commentLeft: " ",
commentRight: " ",
emptyBody: "",
indent: " ",
semicolon: false
};
function capitalize(str) {
return str[0].toUpperCase() + str.slice(1);
}
var Stringifier = class {
constructor(builder) {
this.builder = builder;
}
atrule(node, semicolon) {
let raws = node.raws;
let name = "@" + node.name;
let params = node.params ? this.rawValue(node, "params") : "";
if (typeof raws.afterName !== "undefined") {
name += raws.afterName;
} else if (params) {
name += " ";
}
if (node.nodes) {
this.block(node, name + params);
} else {
let end = (raws.between || "") + (semicolon ? ";" : "");
this.builder(escapeHTMLInCSS(name + params + end), node);
}
}
beforeAfter(node, detect) {
let value;
if (node.type === "decl") {
value = this.raw(node, null, "beforeDecl");
} else if (node.type === "comment") {
value = this.raw(node, null, "beforeComment");
} else if (detect === "before") {
value = this.raw(node, null, "beforeRule");
} else {
value = this.raw(node, null, "beforeClose");
}
let buf = node.parent;
let depth = 0;
while (buf && buf.type !== "root") {
depth += 1;
buf = buf.parent;
}
if (value.includes("\n")) {
let indent = this.raw(node, null, "indent");
if (indent.length) {
for (let step = 0; step < depth; step++) value += indent;
}
}
return value;
}
block(node, start2) {
let between = this.raw(node, "between", "beforeOpen");
this.builder(escapeHTMLInCSS(start2 + between) + "{", node, "start");
let after;
if (node.nodes && node.nodes.length) {
this.body(node);
after = this.raw(node, "after");
} else {
after = this.raw(node, "after", "emptyBody");
}
if (after) this.builder(escapeHTMLInCSS(after));
this.builder("}", node, "end");
}
body(node) {
let nodes = node.nodes;
let last = nodes.length - 1;
while (last > 0) {
if (nodes[last].type !== "comment") break;
last -= 1;
}
let semicolon = this.raw(node, "semicolon");
let isDocument = node.type === "document";
for (let i2 = 0; i2 < nodes.length; i2++) {
let child = nodes[i2];
let before = this.raw(child, "before");
if (before) this.builder(isDocument ? before : escapeHTMLInCSS(before));
this.stringify(child, last !== i2 || semicolon);
}
}
comment(node) {
let left = this.raw(node, "left", "commentLeft");
let right = this.raw(node, "right", "commentRight");
this.builder(escapeHTMLInCSS("/*" + left + node.text + right + "*/"), node);
}
decl(node, semicolon) {
let raws = node.raws;
let between = this.raw(node, "between", "colon");
let string = node.prop + between + this.rawValue(node, "value");
if (node.important) {
string += raws.important || " !important";
}
if (semicolon) string += ";";
this.builder(escapeHTMLInCSS(string), node);
}
document(node) {
this.body(node);
}
raw(node, own, detect) {
let value;
if (!detect) detect = own;
if (own) {
value = node.raws[own];
if (typeof value !== "undefined") return value;
}
let parent = node.parent;
if (detect === "before") {
if (!parent || parent.type === "root" && parent.first === node) {
return "";
}
if (parent && parent.type === "document") {
return "";
}
}
if (!parent) return DEFAULT_RAW[detect];
let root = node.root();
let cache = root.rawCache || (root.rawCache = {});
if (typeof cache[detect] !== "undefined") {
return cache[detect];
}
if (detect === "before" || detect === "after") {
return this.beforeAfter(node, detect);
} else {
let method = "raw" + capitalize(detect);
if (this[method]) {
value = this[method](root, node);
} else {
root.walk((i2) => {
value = i2.raws[own];
if (typeof value !== "undefined") return false;
});
}
}
if (typeof value === "undefined") value = DEFAULT_RAW[detect];
cache[detect] = value;
return value;
}
rawBeforeClose(root) {
let value;
root.walk((i2) => {
if (i2.nodes && i2.nodes.length > 0) {
if (typeof i2.raws.after !== "undefined") {
value = i2.raws.after;
if (value.includes("\n")) {
value = value.replace(/[^\n]+$/, "");
}
return false;
}
}
});
if (value) value = value.replace(/\S/g, "");
return value;
}
rawBeforeComment(root, node) {
let value;
root.walkComments((i2) => {
if (typeof i2.raws.before !== "undefined") {
value = i2.raws.before;
if (value.includes("\n")) {
value = value.replace(/[^\n]+$/, "");
}
return false;
}
});
if (typeof value === "undefined") {
value = this.raw(node, null, "beforeDecl");
} else if (value) {
value = value.replace(/\S/g, "");
}
return value;
}
rawBeforeDecl(root, node) {
let value;
root.walkDecls((i2) => {
if (typeof i2.raws.before !== "undefined") {
value = i2.raws.before;
if (value.includes("\n")) {
value = value.replace(/[^\n]+$/, "");
}
return false;
}
});
if (typeof value === "undefined") {
value = this.raw(node, null, "beforeRule");
} else if (value) {
value = value.replace(/\S/g, "");
}
return value;
}
rawBeforeOpen(root) {
let value;
root.walk((i2) => {
if (i2.type !== "decl") {
value = i2.raws.between;
if (typeof value !== "undefined") return false;
}
});
return value;
}
rawBeforeRule(root) {
let value;
root.walk((i2) => {
if (i2.nodes && (i2.parent !== root || root.first !== i2)) {
if (typeof i2.raws.before !== "undefined") {
value = i2.raws.before;
if (value.includes("\n")) {
value = value.replace(/[^\n]+$/, "");
}
return false;
}
}
});
if (value) value = value.replace(/\S/g, "");
return value;
}
rawColon(root) {
let value;
root.walkDecls((i2) => {
if (typeof i2.raws.between !== "undefined") {
value = i2.raws.between.replace(/[^\s:]/g, "");
return false;
}
});
return value;
}
rawEmptyBody(root) {
let value;
root.walk((i2) => {
if (i2.nodes && i2.nodes.length === 0) {
value = i2.raws.after;
if (typeof value !== "undefined") return false;
}
});
return value;
}
rawIndent(root) {
if (root.raws.indent) return root.raws.indent;
let value;
root.walk((i2) => {
let p2 = i2.parent;
if (p2 && p2 !== root && p2.parent && p2.parent === root) {
if (typeof i2.raws.before !== "undefined") {
let parts = i2.raws.before.split("\n");
value = parts[parts.length - 1];
value = value.replace(/\S/g, "");
return false;
}
}
});
return value;
}
rawSemicolon(root) {
let value;
root.walk((i2) => {
if (i2.nodes && i2.nodes.length && i2.last.type === "decl") {
value = i2.raws.semicolon;
if (typeof value !== "undefined") return false;
}
});
return value;
}
rawValue(node, prop) {
let value = node[prop];
let raw = node.raws[prop];
if (raw && raw.value === value) {
return raw.raw;
}
return value;
}
root(node) {
this.body(node);
if (node.raws.after) {
let after = node.raws.after;
let isDocument = node.parent && node.parent.type === "document";
this.builder(isDocument ? after : escapeHTMLInCSS(after));
}
}
rule(node) {
this.block(node, this.rawValue(node, "selector"));
if (node.raws.ownSemicolon) {
this.builder(escapeHTMLInCSS(node.raws.ownSemicolon), node, "end");
}
}
stringify(node, semicolon) {
if (!this[node.type]) {
throw new Error(
"Unknown AST node type " + node.type + ". Maybe you need to change PostCSS stringifier."
);
}
this[node.type](node, semicolon);
}
};
module.exports = Stringifier;
Stringifier.default = Stringifier;
}
});
// node_modules/postcss/lib/stringify.js
var require_stringify = __commonJS({
"node_modules/postcss/lib/stringify.js"(exports, module) {
"use strict";
var Stringifier = require_stringifier();
function stringify2(node, builder) {
let str = new Stringifier(builder);
str.stringify(node);
}
module.exports = stringify2;
stringify2.default = stringify2;
}
});
// node_modules/postcss/lib/symbols.js
var require_symbols = __commonJS({
"node_modules/postcss/lib/symbols.js"(exports, module) {
"use strict";
module.exports.isClean = /* @__PURE__ */ Symbol("isClean");
module.exports.my = /* @__PURE__ */ Symbol("my");
}
});
// node_modules/postcss/lib/node.js
var require_node = __commonJS({
"node_modules/postcss/lib/node.js"(exports, module) {
"use strict";
var CssSyntaxError2 = require_css_syntax_error();
var Stringifier = require_stringifier();
var stringify2 = require_stringify();
var { isClean, my } = require_symbols();
function cloneNode(obj, parent) {
let cloned = new obj.constructor();
for (let i2 in obj) {
if (!Object.prototype.hasOwnProperty.call(obj, i2)) {
continue;
}
if (i2 === "proxyCache") continue;
let value = obj[i2];
let type = typeof value;
if (i2 === "parent" && type === "object") {
if (parent) cloned[i2] = parent;
} else if (i2 === "source") {
cloned[i2] = value;
} else if (Array.isArray(value)) {
cloned[i2] = value.map((j2) => cloneNode(j2, cloned));
} else {
if (type === "object" && value !== null) value = cloneNode(value);
cloned[i2] = value;
}
}
return cloned;
}
function sourceOffset(inputCSS, position) {
if (position && typeof position.offset !== "undefined") {
return position.offset;
}
let column = 1;
let line = 1;
let offset4 = 0;
for (let i2 = 0; i2 < inputCSS.length; i2++) {
if (line === position.line && column === position.column) {
offset4 = i2;
break;
}
if (inputCSS[i2] === "\n") {
column = 1;
line += 1;
} else {
column += 1;
}
}
return offset4;
}
var Node2 = class {
get proxyOf() {
return this;
}
constructor(defaults2 = {}) {
this.raws = {};
this[isClean] = false;
this[my] = true;
for (let name in defaults2) {
if (name === "nodes") {
this.nodes = [];
for (let node of defaults2[name]) {
if (typeof node.clone === "function" && node.parent) {
this.append(node.clone());
} else {
this.append(node);
}
}
} else {
this[name] = defaults2[name];
}
}
}
addToError(error2) {
error2.postcssNode = this;
if (error2.stack && this.source && /\n\s{4}at /.test(error2.stack)) {
let s2 = this.source;
error2.stack = error2.stack.replace(
/\n\s{4}at /,
`$&${s2.input.from}:${s2.start.line}:${s2.start.column}$&`
);
}
return error2;
}
after(add2) {
this.parent.insertAfter(this, add2);
return this;
}
assign(overrides = {}) {
for (let name in overrides) {
this[name] = overrides[name];
}
return this;
}
before(add2) {
this.parent.insertBefore(this, add2);
return this;
}
cleanRaws(keepBetween) {
delete this.raws.before;
delete this.raws.after;
if (!keepBetween) delete this.raws.between;
}
clone(overrides = {}) {
let cloned = cloneNode(this);
for (let name in overrides) {
cloned[name] = overrides[name];
}
return cloned;
}
cloneAfter(overrides = {}) {
let cloned = this.clone(overrides);
this.parent.insertAfter(this, cloned);
return cloned;
}
cloneBefore(overrides = {}) {
let cloned = this.clone(overrides);
this.parent.insertBefore(this, cloned);
return cloned;
}
error(message2, opts = {}) {
if (this.source) {
let { end, start: start2 } = this.rangeBy(opts);
return this.source.input.error(
message2,
{ column: start2.column, line: start2.line },
{ column: end.column, line: end.line },
opts
);
}
return new CssSyntaxError2(message2);
}
getProxyProcessor() {
return {
get(node, prop) {
if (prop === "proxyOf") {
return node;
} else if (prop === "root") {
return () => node.root().toProxy();
} else {
return node[prop];
}
},
set(node, prop, value) {
if (node[prop] === value) return true;
node[prop] = value;
if (prop === "prop" || prop === "value" || prop === "name" || prop === "params" || prop === "important" || /* c8 ignore next */
prop === "text") {
node.markDirty();
}
return true;
}
};
}
/* c8 ignore next 3 */
markClean() {
this[isClean] = true;
}
markDirty() {
if (this[isClean]) {
this[isClean] = false;
let next = this;
while (next = next.parent) {
next[isClean] = false;
}
}
}
next() {
if (!this.parent) return void 0;
let index2 = this.parent.index(this);
return this.parent.nodes[index2 + 1];
}
positionBy(opts = {}) {
let inputString = "document" in this.source.input ? this.source.input.document : this.source.input.css;
let pos = {
column: this.source.start.column,
line: this.source.start.line,
offset: sourceOffset(inputString, this.source.start)
};
if (opts.index) {
pos = this.positionInside(opts.index);
} else if (opts.word) {
let stringRepresentation = inputString.slice(
sourceOffset(inputString, this.source.start),
sourceOffset(inputString, this.source.end)
);
let index2 = stringRepresentation.indexOf(opts.word);
if (index2 !== -1) pos = this.positionInside(index2);
}
return pos;
}
positionInside(index2) {
let column = this.source.start.column;
let line = this.source.start.line;
let inputString = "document" in this.source.input ? this.source.input.document : this.source.input.css;
let offset4 = sourceOffset(inputString, this.source.start);
let end = offset4 + index2;
for (let i2 = offset4; i2 < end; i2++) {
if (inputString[i2] === "\n") {
column = 1;
line += 1;
} else {
column += 1;
}
}
return { column, line, offset: end };
}
prev() {
if (!this.parent) return void 0;
let index2 = this.parent.index(this);
return this.parent.nodes[index2 - 1];
}
rangeBy(opts = {}) {
let inputString = "document" in this.source.input ? this.source.input.document : this.source.input.css;
let start2 = {
column: this.source.start.column,
line: this.source.start.line,
offset: sourceOffset(inputString, this.source.start)
};
let end = this.source.end ? {
column: this.source.end.column + 1,
line: this.source.end.line,
offset: typeof this.source.end.offset === "number" ? (
// `source.end.offset` is exclusive, so we don't need to add 1
this.source.end.offset
) : (
// Since line/column in this.source.end is inclusive,
// the `sourceOffset(... , this.source.end)` returns an inclusive offset.
// So, we add 1 to convert it to exclusive.
sourceOffset(inputString, this.source.end) + 1
)
} : {
column: start2.column + 1,
line: start2.line,
offset: start2.offset + 1
};
if (opts.word) {
let stringRepresentation = inputString.slice(
sourceOffset(inputString, this.source.start),
sourceOffset(inputString, this.source.end)
);
let index2 = stringRepresentation.indexOf(opts.word);
if (index2 !== -1) {
start2 = this.positionInside(index2);
end = this.positionInside(index2 + opts.word.length);
}
} else {
if (opts.start) {
start2 = {
column: opts.start.column,
line: opts.start.line,
offset: sourceOffset(inputString, opts.start)
};
} else if (typeof opts.index === "number") {
start2 = this.positionInside(opts.index);
}
if (opts.end) {
end = {
column: opts.end.column,
line: opts.end.line,
offset: sourceOffset(inputString, opts.end)
};
} else if (typeof opts.endIndex === "number") {
end = this.positionInside(opts.endIndex);
} else if (typeof opts.index === "number") {
end = this.positionInside(opts.index + 1);
}
}
if (end.line < start2.line || end.line === start2.line && end.column <= start2.column) {
end = {
column: start2.column + 1,
line: start2.line,
offset: start2.offset + 1
};
}
return { end, start: start2 };
}
raw(prop, defaultType) {
let str = new Stringifier();
return str.raw(this, prop, defaultType);
}
remove() {
if (this.parent) {
this.parent.removeChild(this);
}
this.parent = void 0;
return this;
}
replaceWith(...nodes) {
if (this.parent) {
let bookmark = this;
let foundSelf = false;
for (let node of nodes) {
if (node === this) {
foundSelf = true;
} else if (foundSelf) {
this.parent.insertAfter(bookmark, node);
bookmark = node;
} else {
this.parent.insertBefore(bookmark, node);
}
}
if (!foundSelf) {
this.remove();
}
}
return this;
}
root() {
let result = this;
while (result.parent && result.parent.type !== "document") {
result = result.parent;
}
return result;
}
toJSON(_, inputs) {
let fixed = {};
let emitInputs = inputs == null;
inputs = inputs || /* @__PURE__ */ new Map();
let inputsNextIndex = 0;
for (let name in this) {
if (!Object.prototype.hasOwnProperty.call(this, name)) {
continue;
}
if (name === "parent" || name === "proxyCache") continue;
let value = this[name];
if (Array.isArray(value)) {
fixed[name] = value.map((i2) => {
if (typeof i2 === "object" && i2.toJSON) {
return i2.toJSON(null, inputs);
} else {
return i2;
}
});
} else if (typeof value === "object" && value.toJSON) {
fixed[name] = value.toJSON(null, inputs);
} else if (name === "source") {
if (value == null) continue;
let inputId = inputs.get(value.input);
if (inputId == null) {
inputId = inputsNextIndex;
inputs.set(value.input, inputsNextIndex);
inputsNextIndex++;
}
fixed[name] = {
end: value.end,
inputId,
start: value.start
};
} else {
fixed[name] = value;
}
}
if (emitInputs) {
fixed.inputs = [...inputs.keys()].map((input) => input.toJSON());
}
return fixed;
}
toProxy() {
if (!this.proxyCache) {
this.proxyCache = new Proxy(this, this.getProxyProcessor());
}
return this.proxyCache;
}
toString(stringifier = stringify2) {
if (stringifier.stringify) stringifier = stringifier.stringify;
let result = "";
stringifier(this, (i2) => {
result += i2;
});
return result;
}
warn(result, text, opts = {}) {
let data = { node: this };
for (let i2 in opts) data[i2] = opts[i2];
return result.warn(text, data);
}
};
module.exports = Node2;
Node2.default = Node2;
}
});
// node_modules/postcss/lib/comment.js
var require_comment = __commonJS({
"node_modules/postcss/lib/comment.js"(exports, module) {
"use strict";
var Node2 = require_node();
var Comment = class extends Node2 {
constructor(defaults2) {
super(defaults2);
this.type = "comment";
}
};
module.exports = Comment;
Comment.default = Comment;
}
});
// node_modules/postcss/lib/declaration.js
var require_declaration = __commonJS({
"node_modules/postcss/lib/declaration.js"(exports, module) {
"use strict";
var Node2 = require_node();
var Declaration = class extends Node2 {
get variable() {
return this.prop.startsWith("--") || this.prop[0] === "$";
}
constructor(defaults2) {
if (defaults2 && typeof defaults2.value !== "undefined" && typeof defaults2.value !== "string") {
defaults2 = { ...defaults2, value: String(defaults2.value) };
}
super(defaults2);
this.type = "decl";
}
};
module.exports = Declaration;
Declaration.default = Declaration;
}
});
// node_modules/postcss/lib/container.js
var require_container = __commonJS({
"node_modules/postcss/lib/container.js"(exports, module) {
"use strict";
var Comment = require_comment();
var Declaration = require_declaration();
var Node2 = require_node();
var { isClean, my } = require_symbols();
var AtRule;
var parse4;
var Root8;
var Rule;
function cleanSource(nodes) {
return nodes.map((i2) => {
if (i2.nodes) i2.nodes = cleanSource(i2.nodes);
delete i2.source;
return i2;
});
}
function markTreeDirty(node) {
node[isClean] = false;
if (node.proxyOf.nodes) {
for (let i2 of node.proxyOf.nodes) {
markTreeDirty(i2);
}
}
}
var Container = class _Container extends Node2 {
get first() {
if (!this.proxyOf.nodes) return void 0;
return this.proxyOf.nodes[0];
}
get last() {
if (!this.proxyOf.nodes) return void 0;
return this.proxyOf.nodes[this.proxyOf.nodes.length - 1];
}
append(...children) {
for (let child of children) {
let nodes = this.normalize(child, this.last);
for (let node of nodes) this.proxyOf.nodes.push(node);
}
this.markDirty();
return this;
}
cleanRaws(keepBetween) {
super.cleanRaws(keepBetween);
if (this.nodes) {
for (let node of this.nodes) node.cleanRaws(keepBetween);
}
}
each(callback) {
if (!this.proxyOf.nodes) return void 0;
let iterator = this.getIterator();
let index2, result;
while (this.indexes[iterator] < this.proxyOf.nodes.length) {
index2 = this.indexes[iterator];
result = callback(this.proxyOf.nodes[index2], index2);
if (result === false) break;
this.indexes[iterator] += 1;
}
delete this.indexes[iterator];
return result;
}
every(condition) {
return this.nodes.every(condition);
}
getIterator() {
if (!this.lastEach) this.lastEach = 0;
if (!this.indexes) this.indexes = {};
this.lastEach += 1;
let iterator = this.lastEach;
this.indexes[iterator] = 0;
return iterator;
}
getProxyProcessor() {
return {
get(node, prop) {
if (prop === "proxyOf") {
return node;
} else if (!node[prop]) {
return node[prop];
} else if (prop === "each" || typeof prop === "string" && prop.startsWith("walk")) {
return (...args) => {
return node[prop](
...args.map((i2) => {
if (typeof i2 === "function") {
return (child, index2) => i2(child.toProxy(), index2);
} else {
return i2;
}
})
);
};
} else if (prop === "every" || prop === "some") {
return (cb) => {
return node[prop](
(child, ...other) => cb(child.toProxy(), ...other)
);
};
} else if (prop === "root") {
return () => node.root().toProxy();
} else if (prop === "nodes") {
return node.nodes.map((i2) => i2.toProxy());
} else if (prop === "first" || prop === "last") {
return node[prop].toProxy();
} else {
return node[prop];
}
},
set(node, prop, value) {
if (node[prop] === value) return true;
node[prop] = value;
if (prop === "name" || prop === "params" || prop === "selector") {
node.markDirty();
}
return true;
}
};
}
index(child) {
if (typeof child === "number") return child;
if (child.proxyOf) child = child.proxyOf;
return this.proxyOf.nodes.indexOf(child);
}
insertAfter(exist, add2) {
let existIndex = this.index(exist);
let nodes = this.normalize(add2, this.proxyOf.nodes[existIndex]).reverse();
existIndex = this.index(exist);
for (let node of nodes) this.proxyOf.nodes.splice(existIndex + 1, 0, node);
let index2;
for (let id in this.indexes) {
index2 = this.indexes[id];
if (existIndex < index2) {
this.indexes[id] = index2 + nodes.length;
}
}
this.markDirty();
return this;
}
insertBefore(exist, add2) {
let existIndex = this.index(exist);
let type = existIndex === 0 ? "prepend" : false;
let nodes = this.normalize(
add2,
this.proxyOf.nodes[existIndex],
type
).reverse();
existIndex = this.index(exist);
for (let node of nodes) this.proxyOf.nodes.splice(existIndex, 0, node);
let index2;
for (let id in this.indexes) {
index2 = this.indexes[id];
if (existIndex <= index2) {
this.indexes[id] = index2 + nodes.length;
}
}
this.markDirty();
return this;
}
normalize(nodes, sample) {
if (typeof nodes === "string") {
nodes = cleanSource(parse4(nodes).nodes);
} else if (typeof nodes === "undefined") {
nodes = [];
} else if (Array.isArray(nodes)) {
nodes = nodes.slice(0);
for (let i2 of nodes) {
if (i2.parent) i2.parent.removeChild(i2, "ignore");
}
} else if (nodes.type === "root" && this.type !== "document") {
nodes = nodes.nodes.slice(0);
for (let i2 of nodes) {
if (i2.parent) i2.parent.removeChild(i2, "ignore");
}
} else if (nodes.type) {
nodes = [nodes];
} else if (nodes.prop) {
if (typeof nodes.value === "undefined") {
throw new Error("Value field is missed in node creation");
} else if (typeof nodes.value !== "string") {
nodes.value = String(nodes.value);
}
nodes = [new Declaration(nodes)];
} else if (nodes.selector || nodes.selectors) {
nodes = [new Rule(nodes)];
} else if (nodes.name) {
nodes = [new AtRule(nodes)];
} else if (nodes.text) {
nodes = [new Comment(nodes)];
} else {
throw new Error("Unknown node type in node creation");
}
let processed = nodes.map((i2) => {
if (!i2[my]) _Container.rebuild(i2);
i2 = i2.proxyOf;
if (i2.parent) i2.parent.removeChild(i2);
if (i2[isClean]) markTreeDirty(i2);
if (!i2.raws) i2.raws = {};
if (typeof i2.raws.before === "undefined") {
if (sample && typeof sample.raws.before !== "undefined") {
i2.raws.before = sample.raws.before.replace(/\S/g, "");
}
}
i2.parent = this.proxyOf;
return i2;
});
return processed;
}
prepend(...children) {
children = children.reverse();
for (let child of children) {
let nodes = this.normalize(child, this.first, "prepend").reverse();
for (let node of nodes) this.proxyOf.nodes.unshift(node);
for (let id in this.indexes) {
this.indexes[id] = this.indexes[id] + nodes.length;
}
}
this.markDirty();
return this;
}
push(child) {
child.parent = this;
this.proxyOf.nodes.push(child);
return this;
}
removeAll() {
for (let node of this.proxyOf.nodes) node.parent = void 0;
this.proxyOf.nodes = [];
this.markDirty();
return this;
}
removeChild(child) {
child = this.index(child);
this.proxyOf.nodes[child].parent = void 0;
this.proxyOf.nodes.splice(child, 1);
let index2;
for (let id in this.indexes) {
index2 = this.indexes[id];
if (index2 >= child) {
this.indexes[id] = index2 - 1;
}
}
this.markDirty();
return this;
}
replaceValues(pattern, opts, callback) {
if (!callback) {
callback = opts;
opts = {};
}
this.walkDecls((decl) => {
if (opts.props && !opts.props.includes(decl.prop)) return;
if (opts.fast && !decl.value.includes(opts.fast)) return;
decl.value = decl.value.replace(pattern, callback);
});
this.markDirty();
return this;
}
some(condition) {
return this.nodes.some(condition);
}
walk(callback) {
return this.each((child, i2) => {
let result;
try {
result = callback(child, i2);
} catch (e2) {
throw child.addToError(e2);
}
if (result !== false && child.walk) {
result = child.walk(callback);
}
return result;
});
}
walkAtRules(name, callback) {
if (!callback) {
callback = name;
return this.walk((child, i2) => {
if (child.type === "atrule") {
return callback(child, i2);
}
});
}
if (name instanceof RegExp) {
return this.walk((child, i2) => {
if (child.type === "atrule" && name.test(child.name)) {
return callback(child, i2);
}
});
}
return this.walk((child, i2) => {
if (child.type === "atrule" && child.name === name) {
return callback(child, i2);
}
});
}
walkComments(callback) {
return this.walk((child, i2) => {
if (child.type === "comment") {
return callback(child, i2);
}
});
}
walkDecls(prop, callback) {
if (!callback) {
callback = prop;
return this.walk((child, i2) => {
if (child.type === "decl") {
return callback(child, i2);
}
});
}
if (prop instanceof RegExp) {
return this.walk((child, i2) => {
if (child.type === "decl" && prop.test(child.prop)) {
return callback(child, i2);
}
});
}
return this.walk((child, i2) => {
if (child.type === "decl" && child.prop === prop) {
return callback(child, i2);
}
});
}
walkRules(selector3, callback) {
if (!callback) {
callback = selector3;
return this.walk((child, i2) => {
if (child.type === "rule") {
return callback(child, i2);
}
});
}
if (selector3 instanceof RegExp) {
return this.walk((child, i2) => {
if (child.type === "rule" && selector3.test(child.selector)) {
return callback(child, i2);
}
});
}
return this.walk((child, i2) => {
if (child.type === "rule" && child.selector === selector3) {
return callback(child, i2);
}
});
}
};
Container.registerParse = (dependant) => {
parse4 = dependant;
};
Container.registerRule = (dependant) => {
Rule = dependant;
};
Container.registerAtRule = (dependant) => {
AtRule = dependant;
};
Container.registerRoot = (dependant) => {
Root8 = dependant;
};
module.exports = Container;
Container.default = Container;
Container.rebuild = (node) => {
if (node.type === "atrule") {
Object.setPrototypeOf(node, AtRule.prototype);
} else if (node.type === "rule") {
Object.setPrototypeOf(node, Rule.prototype);
} else if (node.type === "decl") {
Object.setPrototypeOf(node, Declaration.prototype);
} else if (node.type === "comment") {
Object.setPrototypeOf(node, Comment.prototype);
} else if (node.type === "root") {
Object.setPrototypeOf(node, Root8.prototype);
}
node[my] = true;
if (node.nodes) {
node.nodes.forEach((child) => {
Container.rebuild(child);
});
}
};
}
});
// node_modules/postcss/lib/document.js
var require_document = __commonJS({
"node_modules/postcss/lib/document.js"(exports, module) {
"use strict";
var Container = require_container();
var LazyResult;
var Processor2;
var Document = class extends Container {
constructor(defaults2) {
super({ type: "document", ...defaults2 });
if (!this.nodes) {
this.nodes = [];
}
}
toResult(opts = {}) {
let lazy = new LazyResult(new Processor2(), this, opts);
return lazy.stringify();
}
};
Document.registerLazyResult = (dependant) => {
LazyResult = dependant;
};
Document.registerProcessor = (dependant) => {
Processor2 = dependant;
};
module.exports = Document;
Document.default = Document;
}
});
// (disabled):path
var require_path = __commonJS({
"(disabled):path"() {
}
});
// (disabled):node_modules/postcss/node_modules/source-map-js/source-map.js
var require_source_map = __commonJS({
"(disabled):node_modules/postcss/node_modules/source-map-js/source-map.js"() {
}
});
// (disabled):node_modules/url/url.js
var require_url2 = __commonJS({
"(disabled):node_modules/url/url.js"() {
}
});
// node_modules/nanoid/non-secure/index.cjs
var require_non_secure = __commonJS({
"node_modules/nanoid/non-secure/index.cjs"(exports, module) {
var urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
var customAlphabet = (alphabet, defaultSize = 21) => {
return (size4 = defaultSize) => {
let id = "";
let i2 = size4 | 0;
while (i2--) {
id += alphabet[Math.random() * alphabet.length | 0];
}
return id;
};
};
var nanoid = (size4 = 21) => {
let id = "";
let i2 = size4 | 0;
while (i2--) {
id += urlAlphabet[Math.random() * 64 | 0];
}
return id;
};
module.exports = { nanoid, customAlphabet };
}
});
// (disabled):fs
var require_fs = __commonJS({
"(disabled):fs"() {
}
});
// node_modules/postcss/lib/previous-map.js
var require_previous_map = __commonJS({
"node_modules/postcss/lib/previous-map.js"(exports, module) {
"use strict";
var { existsSync, readFileSync } = require_fs();
var { dirname, join } = require_path();
var { SourceMapConsumer, SourceMapGenerator } = require_source_map();
function fromBase64(str) {
if (Buffer) {
return Buffer.from(str, "base64").toString();
} else {
return window.atob(str);
}
}
var PreviousMap = class {
constructor(css, opts) {
if (opts.map === false) return;
if (opts.unsafeMap) this.unsafeMap = true;
this.loadAnnotation(css);
this.inline = this.startWith(this.annotation, "data:");
let prev = opts.map ? opts.map.prev : void 0;
let text = this.loadMap(opts.from, prev);
if (!this.mapFile && opts.from) {
this.mapFile = opts.from;
}
if (this.mapFile) this.root = dirname(this.mapFile);
if (text) this.text = text;
}
consumer() {
if (!this.consumerCache) {
this.consumerCache = new SourceMapConsumer(this.json || this.text);
}
return this.consumerCache;
}
decodeInline(text) {
let baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/;
let baseUri = /^data:application\/json;base64,/;
let charsetUri = /^data:application\/json;charset=utf-?8,/;
let uri = /^data:application\/json,/;
let uriMatch = text.match(charsetUri) || text.match(uri);
if (uriMatch) {
return decodeURIComponent(text.substr(uriMatch[0].length));
}
let baseUriMatch = text.match(baseCharsetUri) || text.match(baseUri);
if (baseUriMatch) {
return fromBase64(text.substr(baseUriMatch[0].length));
}
let encoding = text.slice("data:application/json;".length);
encoding = encoding.slice(0, encoding.indexOf(","));
throw new Error("Unsupported source map encoding " + encoding);
}
getAnnotationURL(sourceMapString) {
return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, "").trim();
}
isMap(map) {
if (typeof map !== "object") return false;
return typeof map.mappings === "string" || typeof map._mappings === "string" || Array.isArray(map.sections);
}
loadAnnotation(css) {
let comments = css.match(/\/\*\s*# sourceMappingURL=/g);
if (!comments) return;
let start2 = css.lastIndexOf(comments.pop());
let end = css.indexOf("*/", start2);
if (start2 > -1 && end > -1) {
this.annotation = this.getAnnotationURL(css.substring(start2, end));
}
}
loadFile(path, cssFile, trusted) {
if (!trusted && !this.unsafeMap) {
if (!/\.map$/i.test(path)) {
return void 0;
}
}
this.root = dirname(path);
if (existsSync(path)) {
this.mapFile = path;
return readFileSync(path, "utf-8").toString().trim();
}
}
loadMap(file, prev) {
if (prev === false) return false;
if (prev) {
if (typeof prev === "string") {
return prev;
} else if (typeof prev === "function") {
let prevPath = prev(file);
if (prevPath) {
let map = this.loadFile(prevPath, file, true);
if (!map) {
throw new Error(
"Unable to load previous source map: " + prevPath.toString()
);
}
return map;
}
} else if (prev instanceof SourceMapConsumer) {
return SourceMapGenerator.fromSourceMap(prev).toString();
} else if (prev instanceof SourceMapGenerator) {
return prev.toString();
} else if (this.isMap(prev)) {
return JSON.stringify(prev);
} else {
throw new Error(
"Unsupported previous source map format: " + prev.toString()
);
}
} else if (this.inline) {
return this.decodeInline(this.annotation);
} else if (this.annotation) {
let map = this.annotation;
if (file) map = join(dirname(file), map);
let unknown = this.loadFile(map, file, false);
if (unknown) {
try {
this.json = JSON.parse(unknown.replace(/^\)]}'[^\n]*\n/, ""));
} catch {
return void 0;
}
}
return unknown;
}
}
startWith(string, start2) {
if (!string) return false;
return string.substr(0, start2.length) === start2;
}
withContent() {
return !!(this.consumer().sourcesContent && this.consumer().sourcesContent.length > 0);
}
};
module.exports = PreviousMap;
PreviousMap.default = PreviousMap;
}
});
// node_modules/postcss/lib/input.js
var require_input = __commonJS({
"node_modules/postcss/lib/input.js"(exports, module) {
"use strict";
var { nanoid } = require_non_secure();
var { isAbsolute, resolve } = require_path();
var { SourceMapConsumer, SourceMapGenerator } = require_source_map();
var { fileURLToPath, pathToFileURL } = require_url2();
var CssSyntaxError2 = require_css_syntax_error();
var PreviousMap = require_previous_map();
var terminalHighlight = require_terminal_highlight();
var lineToIndexCache = /* @__PURE__ */ Symbol("lineToIndexCache");
var sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator);
var pathAvailable = Boolean(resolve && isAbsolute);
function getLineToIndex(input) {
if (input[lineToIndexCache]) return input[lineToIndexCache];
let lines = input.css.split("\n");
let lineToIndex = new Array(lines.length);
let prevIndex = 0;
for (let i2 = 0, l2 = lines.length; i2 < l2; i2++) {
lineToIndex[i2] = prevIndex;
prevIndex += lines[i2].length + 1;
}
input[lineToIndexCache] = lineToIndex;
return lineToIndex;
}
var Input = class {
get from() {
return this.file || this.id;
}
constructor(css, opts = {}) {
if (css === null || typeof css === "undefined" || typeof css === "object" && !css.toString) {
throw new Error(`PostCSS received ${css} instead of CSS string`);
}
this.css = css.toString();
if (this.css[0] === "\uFEFF" || this.css[0] === "\uFFFE") {
this.hasBOM = true;
this.css = this.css.slice(1);
} else {
this.hasBOM = false;
}
this.document = this.css;
if (opts.document) this.document = opts.document.toString();
if (opts.from) {
if (!pathAvailable || /^\w+:\/\//.test(opts.from) || isAbsolute(opts.from)) {
this.file = opts.from;
} else {
this.file = resolve(opts.from);
}
}
if (pathAvailable && sourceMapAvailable) {
let map = new PreviousMap(this.css, opts);
if (map.text) {
this.map = map;
let file = map.consumer().file;
if (!this.file && file) this.file = this.mapResolve(file);
}
}
if (!this.file) {
this.id = "<input css " + nanoid(6) + ">";
}
if (this.map) this.map.file = this.from;
}
error(message2, line, column, opts = {}) {
let endColumn, endLine, endOffset, offset4, result;
if (line && typeof line === "object") {
let start2 = line;
let end = column;
if (typeof start2.offset === "number") {
offset4 = start2.offset;
let pos = this.fromOffset(offset4);
line = pos.line;
column = pos.col;
} else {
line = start2.line;
column = start2.column;
offset4 = this.fromLineAndColumn(line, column);
}
if (typeof end.offset === "number") {
endOffset = end.offset;
let pos = this.fromOffset(endOffset);
endLine = pos.line;
endColumn = pos.col;
} else {
endLine = end.line;
endColumn = end.column;
endOffset = this.fromLineAndColumn(end.line, end.column);
}
} else if (!column) {
offset4 = line;
let pos = this.fromOffset(offset4);
line = pos.line;
column = pos.col;
} else {
offset4 = this.fromLineAndColumn(line, column);
}
let origin = this.origin(line, column, endLine, endColumn);
if (origin) {
result = new CssSyntaxError2(
message2,
origin.endLine === void 0 ? origin.line : { column: origin.column, line: origin.line },
origin.endLine === void 0 ? origin.column : { column: origin.endColumn, line: origin.endLine },
origin.source,
origin.file,
opts.plugin
);
} else {
result = new CssSyntaxError2(
message2,
endLine === void 0 ? line : { column, line },
endLine === void 0 ? column : { column: endColumn, line: endLine },
this.css,
this.file,
opts.plugin
);
}
result.input = {
column,
endColumn,
endLine,
endOffset,
line,
offset: offset4,
source: this.css
};
if (this.file) {
if (pathToFileURL) {
result.input.url = pathToFileURL(this.file).toString();
}
result.input.file = this.file;
}
return result;
}
fromLineAndColumn(line, column) {
let lineToIndex = getLineToIndex(this);
let index2 = lineToIndex[line - 1];
return index2 + column - 1;
}
fromOffset(offset4) {
let lineToIndex = getLineToIndex(this);
let lastLine = lineToIndex[lineToIndex.length - 1];
let min2 = 0;
if (offset4 >= lastLine) {
min2 = lineToIndex.length - 1;
} else {
let max2 = lineToIndex.length - 2;
let mid;
while (min2 < max2) {
mid = min2 + (max2 - min2 >> 1);
if (offset4 < lineToIndex[mid]) {
max2 = mid - 1;
} else if (offset4 >= lineToIndex[mid + 1]) {
min2 = mid + 1;
} else {
min2 = mid;
break;
}
}
}
return {
col: offset4 - lineToIndex[min2] + 1,
line: min2 + 1
};
}
mapResolve(file) {
if (/^\w+:\/\//.test(file)) {
return file;
}
return resolve(this.map.consumer().sourceRoot || this.map.root || ".", file);
}
origin(line, column, endLine, endColumn) {
if (!this.map) return false;
let consumer = this.map.consumer();
let from = consumer.originalPositionFor({ column: column - 1, line });
if (!from.source) return false;
let to2;
if (typeof endLine === "number") {
to2 = consumer.originalPositionFor({
column: endColumn - 1,
line: endLine
});
}
let fromUrl;
if (isAbsolute(from.source)) {
fromUrl = pathToFileURL(from.source);
} else {
fromUrl = new URL(
from.source,
this.map.consumer().sourceRoot || pathToFileURL(this.map.mapFile)
);
}
let result = {
column: from.column + 1,
endColumn: to2 && to2.column + 1,
endLine: to2 && to2.line,
line: from.line,
url: fromUrl.toString()
};
if (fromUrl.protocol === "file:") {
if (fileURLToPath) {
result.file = fileURLToPath(fromUrl);
} else {
throw new Error(`file: protocol is not available in this PostCSS build`);
}
}
let source = consumer.sourceContentFor(from.source);
if (source) result.source = source;
return result;
}
toJSON() {
let json = {};
for (let name of ["hasBOM", "css", "file", "id"]) {
if (this[name] != null) {
json[name] = this[name];
}
}
if (this.map) {
json.map = { ...this.map };
if (json.map.consumerCache) {
json.map.consumerCache = void 0;
}
}
return json;
}
};
module.exports = Input;
Input.default = Input;
if (terminalHighlight && terminalHighlight.registerInput) {
terminalHighlight.registerInput(Input);
}
}
});
// node_modules/postcss/lib/map-generator.js
var require_map_generator = __commonJS({
"node_modules/postcss/lib/map-generator.js"(exports, module) {
"use strict";
var { dirname, relative, resolve, sep } = require_path();
var { SourceMapConsumer, SourceMapGenerator } = require_source_map();
var { pathToFileURL } = require_url2();
var Input = require_input();
var sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator);
var pathAvailable = Boolean(dirname && resolve && relative && sep);
var MapGenerator = class {
constructor(stringify2, root, opts, cssString) {
this.stringify = stringify2;
this.mapOpts = opts.map || {};
this.root = root;
this.opts = opts;
this.css = cssString;
this.originalCSS = cssString;
this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute;
this.memoizedFileURLs = /* @__PURE__ */ new Map();
this.memoizedPaths = /* @__PURE__ */ new Map();
this.memoizedURLs = /* @__PURE__ */ new Map();
}
addAnnotation() {
let content;
if (this.isInline()) {
content = "data:application/json;base64," + this.toBase64(this.map.toString());
} else if (typeof this.mapOpts.annotation === "string") {
content = this.mapOpts.annotation;
} else if (typeof this.mapOpts.annotation === "function") {
content = this.mapOpts.annotation(this.opts.to, this.root);
} else {
content = this.outputFile() + ".map";
}
let eol = "\n";
if (this.css.includes("\r\n")) eol = "\r\n";
this.css += eol + "/*# sourceMappingURL=" + content + " */";
}
applyPrevMaps() {
for (let prev of this.previous()) {
let from = this.toUrl(this.path(prev.file));
let root = prev.root || dirname(prev.file);
let map;
if (this.mapOpts.sourcesContent === false) {
map = new SourceMapConsumer(prev.text);
if (map.sourcesContent) {
map.sourcesContent = null;
}
} else {
map = prev.consumer();
}
this.map.applySourceMap(map, from, this.toUrl(this.path(root)));
}
}
clearAnnotation() {
if (this.mapOpts.annotation === false) return;
if (this.root) {
let node;
for (let i2 = this.root.nodes.length - 1; i2 >= 0; i2--) {
node = this.root.nodes[i2];
if (node.type !== "comment") continue;
if (node.text.startsWith("# sourceMappingURL=")) {
this.root.removeChild(i2);
}
}
} else if (this.css) {
let startIndex;
while ((startIndex = this.css.lastIndexOf("/*#")) !== -1) {
let endIndex = this.css.indexOf("*/", startIndex + 3);
if (endIndex === -1) break;
while (startIndex > 0 && this.css[startIndex - 1] === "\n") {
startIndex--;
}
this.css = this.css.slice(0, startIndex) + this.css.slice(endIndex + 2);
}
}
}
generate() {
this.clearAnnotation();
if (pathAvailable && sourceMapAvailable && this.isMap()) {
return this.generateMap();
} else {
let result = "";
this.stringify(this.root, (i2) => {
result += i2;
});
return [result];
}
}
generateMap() {
if (this.root) {
this.generateString();
} else if (this.previous().length === 1) {
let prev = this.previous()[0].consumer();
prev.file = this.outputFile();
this.map = SourceMapGenerator.fromSourceMap(prev, {
ignoreInvalidMapping: true
});
} else {
this.map = new SourceMapGenerator({
file: this.outputFile(),
ignoreInvalidMapping: true
});
this.map.addMapping({
generated: { column: 0, line: 1 },
original: { column: 0, line: 1 },
source: this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>"
});
}
if (this.isSourcesContent()) this.setSourcesContent();
if (this.root && this.previous().length > 0) this.applyPrevMaps();
if (this.isAnnotation()) this.addAnnotation();
if (this.isInline()) {
return [this.css];
} else {
return [this.css, this.map];
}
}
generateString() {
this.css = "";
this.map = new SourceMapGenerator({
file: this.outputFile(),
ignoreInvalidMapping: true
});
let line = 1;
let column = 1;
let noSource = "<no source>";
let mapping = {
generated: { column: 0, line: 0 },
original: { column: 0, line: 0 },
source: ""
};
let last, lines;
this.stringify(this.root, (str, node, type) => {
this.css += str;
if (node && type !== "end") {
mapping.generated.line = line;
mapping.generated.column = column - 1;
if (node.source && node.source.start) {
mapping.source = this.sourcePath(node);
mapping.original.line = node.source.start.line;
mapping.original.column = node.source.start.column - 1;
this.map.addMapping(mapping);
} else {
mapping.source = noSource;
mapping.original.line = 1;
mapping.original.column = 0;
this.map.addMapping(mapping);
}
}
lines = str.match(/\n/g);
if (lines) {
line += lines.length;
last = str.lastIndexOf("\n");
column = str.length - last;
} else {
column += str.length;
}
if (node && type !== "start") {
let p2 = node.parent || { raws: {} };
let childless = node.type === "decl" || node.type === "atrule" && !node.nodes;
if (!childless || node !== p2.last || p2.raws.semicolon) {
if (node.source && node.source.end) {
mapping.source = this.sourcePath(node);
mapping.original.line = node.source.end.line;
mapping.original.column = node.source.end.column - 1;
mapping.generated.line = line;
mapping.generated.column = column - 2;
this.map.addMapping(mapping);
} else {
mapping.source = noSource;
mapping.original.line = 1;
mapping.original.column = 0;
mapping.generated.line = line;
mapping.generated.column = column - 1;
this.map.addMapping(mapping);
}
}
}
});
}
isAnnotation() {
if (this.isInline()) {
return true;
}
if (typeof this.mapOpts.annotation !== "undefined") {
return this.mapOpts.annotation;
}
if (this.previous().length) {
return this.previous().some((i2) => i2.annotation);
}
return true;
}
isInline() {
if (typeof this.mapOpts.inline !== "undefined") {
return this.mapOpts.inline;
}
let annotation = this.mapOpts.annotation;
if (typeof annotation !== "undefined" && annotation !== true) {
return false;
}
if (this.previous().length) {
return this.previous().some((i2) => i2.inline);
}
return true;
}
isMap() {
if (typeof this.opts.map !== "undefined") {
return !!this.opts.map;
}
return this.previous().length > 0;
}
isSourcesContent() {
if (typeof this.mapOpts.sourcesContent !== "undefined") {
return this.mapOpts.sourcesContent;
}
if (this.previous().length) {
return this.previous().some((i2) => i2.withContent());
}
return true;
}
outputFile() {
if (this.opts.to) {
return this.path(this.opts.to);
} else if (this.opts.from) {
return this.path(this.opts.from);
} else {
return "to.css";
}
}
path(file) {
if (this.mapOpts.absolute) return file;
if (file.charCodeAt(0) === 60) return file;
if (/^\w+:\/\//.test(file)) return file;
let cached = this.memoizedPaths.get(file);
if (cached) return cached;
let from = this.opts.to ? dirname(this.opts.to) : ".";
if (typeof this.mapOpts.annotation === "string") {
from = dirname(resolve(from, this.mapOpts.annotation));
}
let path = relative(from, file);
this.memoizedPaths.set(file, path);
return path;
}
previous() {
if (!this.previousMaps) {
this.previousMaps = [];
if (this.root) {
this.root.walk((node) => {
if (node.source && node.source.input.map) {
let map = node.source.input.map;
if (!this.previousMaps.includes(map)) {
this.previousMaps.push(map);
}
}
});
} else {
let input = new Input(this.originalCSS, this.opts);
if (input.map) this.previousMaps.push(input.map);
}
}
return this.previousMaps;
}
setSourcesContent() {
let already = {};
if (this.root) {
this.root.walk((node) => {
if (node.source) {
let from = node.source.input.from;
if (from && !already[from]) {
already[from] = true;
let fromUrl = this.usesFileUrls ? this.toFileUrl(from) : this.toUrl(this.path(from));
this.map.setSourceContent(fromUrl, node.source.input.css);
}
}
});
} else if (this.css) {
let from = this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>";
this.map.setSourceContent(from, this.css);
}
}
sourcePath(node) {
if (this.mapOpts.from) {
return this.toUrl(this.mapOpts.from);
} else if (this.usesFileUrls) {
return this.toFileUrl(node.source.input.from);
} else {
return this.toUrl(this.path(node.source.input.from));
}
}
toBase64(str) {
if (Buffer) {
return Buffer.from(str).toString("base64");
} else {
return window.btoa(unescape(encodeURIComponent(str)));
}
}
toFileUrl(path) {
let cached = this.memoizedFileURLs.get(path);
if (cached) return cached;
if (pathToFileURL) {
let fileURL = pathToFileURL(path).toString();
this.memoizedFileURLs.set(path, fileURL);
return fileURL;
} else {
throw new Error(
"`map.absolute` option is not available in this PostCSS build"
);
}
}
toUrl(path) {
let cached = this.memoizedURLs.get(path);
if (cached) return cached;
if (sep === "\\") {
path = path.replace(/\\/g, "/");
}
let url = encodeURI(path).replace(/[#?]/g, encodeURIComponent);
this.memoizedURLs.set(path, url);
return url;
}
};
module.exports = MapGenerator;
}
});
// node_modules/postcss/lib/at-rule.js
var require_at_rule = __commonJS({
"node_modules/postcss/lib/at-rule.js"(exports, module) {
"use strict";
var Container = require_container();
var AtRule = class extends Container {
constructor(defaults2) {
super(defaults2);
this.type = "atrule";
}
append(...children) {
if (!this.proxyOf.nodes) this.nodes = [];
return super.append(...children);
}
prepend(...children) {
if (!this.proxyOf.nodes) this.nodes = [];
return super.prepend(...children);
}
};
module.exports = AtRule;
AtRule.default = AtRule;
Container.registerAtRule(AtRule);
}
});
// node_modules/postcss/lib/root.js
var require_root = __commonJS({
"node_modules/postcss/lib/root.js"(exports, module) {
"use strict";
var Container = require_container();
var LazyResult;
var Processor2;
var Root8 = class extends Container {
constructor(defaults2) {
super(defaults2);
this.type = "root";
if (!this.nodes) this.nodes = [];
}
normalize(child, sample, type) {
let nodes = super.normalize(child);
if (sample) {
if (type === "prepend") {
if (this.nodes.length > 1) {
sample.raws.before = this.nodes[1].raws.before;
} else {
delete sample.raws.before;
}
} else if (this.first !== sample) {
for (let node of nodes) {
node.raws.before = sample.raws.before;
}
}
}
return nodes;
}
removeChild(child, ignore) {
let index2 = this.index(child);
if (!ignore && index2 === 0 && this.nodes.length > 1) {
this.nodes[1].raws.before = this.nodes[index2].raws.before;
}
return super.removeChild(child);
}
toResult(opts = {}) {
let lazy = new LazyResult(new Processor2(), this, opts);
return lazy.stringify();
}
};
Root8.registerLazyResult = (dependant) => {
LazyResult = dependant;
};
Root8.registerProcessor = (dependant) => {
Processor2 = dependant;
};
module.exports = Root8;
Root8.default = Root8;
Container.registerRoot(Root8);
}
});
// node_modules/postcss/lib/list.js
var require_list = __commonJS({
"node_modules/postcss/lib/list.js"(exports, module) {
"use strict";
var list = {
comma(string) {
return list.split(string, [","], true);
},
space(string) {
let spaces = [" ", "\n", " "];
return list.split(string, spaces);
},
split(string, separators, last) {
let array = [];
let current = "";
let split2 = false;
let func = 0;
let inQuote = false;
let prevQuote = "";
let escape = false;
for (let letter of string) {
if (escape) {
escape = false;
} else if (letter === "\\") {
escape = true;
} else if (inQuote) {
if (letter === prevQuote) {
inQuote = false;
}
} else if (letter === '"' || letter === "'") {
inQuote = true;
prevQuote = letter;
} else if (letter === "(") {
func += 1;
} else if (letter === ")") {
if (func > 0) func -= 1;
} else if (func === 0) {
if (separators.includes(letter)) split2 = true;
}
if (split2) {
if (current !== "") array.push(current.trim());
current = "";
split2 = false;
} else {
current += letter;
}
}
if (last || current !== "") array.push(current.trim());
return array;
}
};
module.exports = list;
list.default = list;
}
});
// node_modules/postcss/lib/rule.js
var require_rule = __commonJS({
"node_modules/postcss/lib/rule.js"(exports, module) {
"use strict";
var Container = require_container();
var list = require_list();
var Rule = class extends Container {
get selectors() {
return list.comma(this.selector);
}
set selectors(values) {
let match2 = this.selector ? this.selector.match(/,\s*/) : null;
let sep = match2 ? match2[0] : "," + this.raw("between", "beforeOpen");
this.selector = values.join(sep);
}
constructor(defaults2) {
super(defaults2);
this.type = "rule";
if (!this.nodes) this.nodes = [];
}
};
module.exports = Rule;
Rule.default = Rule;
Container.registerRule(Rule);
}
});
// node_modules/postcss/lib/tokenize.js
var require_tokenize = __commonJS({
"node_modules/postcss/lib/tokenize.js"(exports, module) {
"use strict";
var SINGLE_QUOTE = "'".charCodeAt(0);
var DOUBLE_QUOTE = '"'.charCodeAt(0);
var BACKSLASH = "\\".charCodeAt(0);
var SLASH = "/".charCodeAt(0);
var NEWLINE = "\n".charCodeAt(0);
var SPACE3 = " ".charCodeAt(0);
var FEED = "\f".charCodeAt(0);
var TAB5 = " ".charCodeAt(0);
var CR = "\r".charCodeAt(0);
var OPEN_SQUARE = "[".charCodeAt(0);
var CLOSE_SQUARE = "]".charCodeAt(0);
var OPEN_PARENTHESES = "(".charCodeAt(0);
var CLOSE_PARENTHESES = ")".charCodeAt(0);
var OPEN_CURLY = "{".charCodeAt(0);
var CLOSE_CURLY = "}".charCodeAt(0);
var SEMICOLON = ";".charCodeAt(0);
var ASTERISK = "*".charCodeAt(0);
var COLON = ":".charCodeAt(0);
var AT = "@".charCodeAt(0);
var RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g;
var RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g;
var RE_BAD_BRACKET = /.[\r\n"'(/\\]/;
var RE_HEX_ESCAPE = /[\da-f]/i;
module.exports = function tokenizer(input, options = {}) {
let css = input.css.valueOf();
let ignore = options.ignoreErrors;
let code, content, escape, next, quote;
let currentToken, escaped, escapePos, n2, prev;
let length = css.length;
let pos = 0;
let buffer = [];
let returned = [];
let lastBadParen = -1;
function position() {
return pos;
}
function unclosed(what) {
throw input.error("Unclosed " + what, pos);
}
function endOfFile() {
return returned.length === 0 && pos >= length;
}
function nextToken(opts) {
if (returned.length) return returned.pop();
if (pos >= length) return;
let ignoreUnclosed = opts ? opts.ignoreUnclosed : false;
code = css.charCodeAt(pos);
switch (code) {
case NEWLINE:
case SPACE3:
case TAB5:
case CR:
case FEED: {
next = pos;
do {
next += 1;
code = css.charCodeAt(next);
} while (code === SPACE3 || code === NEWLINE || code === TAB5 || code === CR || code === FEED);
currentToken = ["space", css.slice(pos, next)];
pos = next - 1;
break;
}
case OPEN_SQUARE:
case CLOSE_SQUARE:
case OPEN_CURLY:
case CLOSE_CURLY:
case COLON:
case SEMICOLON:
case CLOSE_PARENTHESES: {
let controlChar = String.fromCharCode(code);
currentToken = [controlChar, controlChar, pos];
break;
}
case OPEN_PARENTHESES: {
prev = buffer.length ? buffer.pop()[1] : "";
n2 = css.charCodeAt(pos + 1);
if (prev === "url" && n2 !== SINGLE_QUOTE && n2 !== DOUBLE_QUOTE && n2 !== SPACE3 && n2 !== NEWLINE && n2 !== TAB5 && n2 !== FEED && n2 !== CR) {
next = pos;
do {
escaped = false;
next = css.indexOf(")", next + 1);
if (next === -1) {
if (ignore || ignoreUnclosed) {
next = pos;
break;
} else {
unclosed("bracket");
}
}
escapePos = next;
while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
escapePos -= 1;
escaped = !escaped;
}
} while (escaped);
currentToken = ["brackets", css.slice(pos, next + 1), pos, next];
pos = next;
} else if (pos <= lastBadParen) {
currentToken = ["(", "(", pos];
} else {
next = css.indexOf(")", pos + 1);
content = css.slice(pos, next + 1);
if (next === -1 || RE_BAD_BRACKET.test(content)) {
lastBadParen = next === -1 ? length : next;
currentToken = ["(", "(", pos];
} else {
currentToken = ["brackets", content, pos, next];
pos = next;
}
}
break;
}
case SINGLE_QUOTE:
case DOUBLE_QUOTE: {
quote = code === SINGLE_QUOTE ? "'" : '"';
next = pos;
do {
escaped = false;
next = css.indexOf(quote, next + 1);
if (next === -1) {
if (ignore || ignoreUnclosed) {
next = pos + 1;
break;
} else {
unclosed("string");
}
}
escapePos = next;
while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
escapePos -= 1;
escaped = !escaped;
}
} while (escaped);
currentToken = ["string", css.slice(pos, next + 1), pos, next];
pos = next;
break;
}
case AT: {
RE_AT_END.lastIndex = pos + 1;
RE_AT_END.test(css);
if (RE_AT_END.lastIndex === 0) {
next = css.length - 1;
} else {
next = RE_AT_END.lastIndex - 2;
}
currentToken = ["at-word", css.slice(pos, next + 1), pos, next];
pos = next;
break;
}
case BACKSLASH: {
next = pos;
escape = true;
while (css.charCodeAt(next + 1) === BACKSLASH) {
next += 1;
escape = !escape;
}
code = css.charCodeAt(next + 1);
if (escape && code !== SLASH && code !== SPACE3 && code !== NEWLINE && code !== TAB5 && code !== CR && code !== FEED) {
next += 1;
if (RE_HEX_ESCAPE.test(css.charAt(next))) {
while (RE_HEX_ESCAPE.test(css.charAt(next + 1))) {
next += 1;
}
if (css.charCodeAt(next + 1) === SPACE3) {
next += 1;
}
}
}
currentToken = ["word", css.slice(pos, next + 1), pos, next];
pos = next;
break;
}
default: {
if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
next = css.indexOf("*/", pos + 2) + 1;
if (next === 0) {
if (ignore || ignoreUnclosed) {
next = css.length;
} else {
unclosed("comment");
}
}
currentToken = ["comment", css.slice(pos, next + 1), pos, next];
pos = next;
} else {
RE_WORD_END.lastIndex = pos + 1;
RE_WORD_END.test(css);
if (RE_WORD_END.lastIndex === 0) {
next = css.length - 1;
} else {
next = RE_WORD_END.lastIndex - 2;
}
currentToken = ["word", css.slice(pos, next + 1), pos, next];
buffer.push(currentToken);
pos = next;
}
break;
}
}
pos++;
return currentToken;
}
function back(token) {
returned.push(token);
}
return {
back,
endOfFile,
nextToken,
position
};
};
}
});
// node_modules/postcss/lib/parser.js
var require_parser = __commonJS({
"node_modules/postcss/lib/parser.js"(exports, module) {
"use strict";
var AtRule = require_at_rule();
var Comment = require_comment();
var Declaration = require_declaration();
var Root8 = require_root();
var Rule = require_rule();
var tokenizer = require_tokenize();
var SAFE_COMMENT_NEIGHBOR = {
empty: true,
space: true
};
function findLastWithPosition(tokens) {
for (let i2 = tokens.length - 1; i2 >= 0; i2--) {
let token = tokens[i2];
let pos = token[3] || token[2];
if (pos) return pos;
}
}
function tokensToString(tokens, from, to2) {
let result = "";
for (let i2 = from; i2 < to2; i2++) result += tokens[i2][1];
return result;
}
var Parser = class {
constructor(input) {
this.input = input;
this.root = new Root8();
this.current = this.root;
this.spaces = "";
this.semicolon = false;
this.createTokenizer();
this.root.source = { input, start: { column: 1, line: 1, offset: 0 } };
}
atrule(token) {
let node = new AtRule();
node.name = token[1].slice(1);
if (node.name === "") {
this.unnamedAtrule(node, token);
}
this.init(node, token[2]);
let type;
let prev;
let shift4;
let last = false;
let open = false;
let params = [];
let brackets = [];
while (!this.tokenizer.endOfFile()) {
token = this.tokenizer.nextToken();
type = token[0];
if (type === "(" || type === "[") {
brackets.push(type === "(" ? ")" : "]");
} else if (type === "{" && brackets.length > 0) {
brackets.push("}");
} else if (type === brackets[brackets.length - 1]) {
brackets.pop();
}
if (brackets.length === 0) {
if (type === ";") {
node.source.end = this.getPosition(token[2]);
node.source.end.offset++;
this.semicolon = true;
break;
} else if (type === "{") {
open = true;
break;
} else if (type === "}") {
if (params.length > 0) {
shift4 = params.length - 1;
prev = params[shift4];
while (prev && prev[0] === "space") {
prev = params[--shift4];
}
if (prev) {
node.source.end = this.getPosition(prev[3] || prev[2]);
node.source.end.offset++;
}
}
this.end(token);
break;
} else {
params.push(token);
}
} else {
params.push(token);
}
if (this.tokenizer.endOfFile()) {
last = true;
break;
}
}
node.raws.between = this.spacesAndCommentsFromEnd(params);
if (params.length) {
node.raws.afterName = this.spacesAndCommentsFromStart(params);
this.raw(node, "params", params);
if (last) {
token = params[params.length - 1];
node.source.end = this.getPosition(token[3] || token[2]);
node.source.end.offset++;
this.spaces = node.raws.between;
node.raws.between = "";
}
} else {
node.raws.afterName = "";
node.params = "";
}
if (open) {
node.nodes = [];
this.current = node;
}
}
checkMissedSemicolon(tokens) {
let colon = this.colon(tokens);
if (colon === false) return;
let founded = 0;
let token;
for (let j2 = colon - 1; j2 >= 0; j2--) {
token = tokens[j2];
if (token[0] !== "space") {
founded += 1;
if (founded === 2) break;
}
}
throw this.input.error(
"Missed semicolon",
token[0] === "word" ? token[3] + 1 : token[2]
);
}
colon(tokens) {
let brackets = 0;
let prev, token, type;
for (let [i2, element] of tokens.entries()) {
token = element;
type = token[0];
if (type === "(") {
brackets += 1;
}
if (type === ")") {
brackets -= 1;
}
if (brackets === 0 && type === ":") {
if (!prev) {
this.doubleColon(token);
} else if (prev[0] === "word" && prev[1] === "progid") {
continue;
} else {
return i2;
}
}
prev = token;
}
return false;
}
comment(token) {
let node = new Comment();
this.init(node, token[2]);
node.source.end = this.getPosition(token[3] || token[2]);
node.source.end.offset++;
let text = token[1].slice(2, -2);
if (!text.trim()) {
node.text = "";
node.raws.left = text;
node.raws.right = "";
} else {
let match2 = text.match(/^(\s*)([^]*\S)(\s*)$/);
node.text = match2[2];
node.raws.left = match2[1];
node.raws.right = match2[3];
}
}
createTokenizer() {
this.tokenizer = tokenizer(this.input);
}
decl(tokens, customProperty) {
let node = new Declaration();
this.init(node, tokens[0][2]);
let last = tokens[tokens.length - 1];
if (last[0] === ";") {
this.semicolon = true;
tokens.pop();
}
node.source.end = this.getPosition(
last[3] || last[2] || findLastWithPosition(tokens)
);
node.source.end.offset++;
let start2 = 0;
while (tokens[start2][0] !== "word") {
if (start2 === tokens.length - 1) this.unknownWord([tokens[start2]]);
start2++;
}
node.raws.before += tokensToString(tokens, 0, start2);
node.source.start = this.getPosition(tokens[start2][2]);
let propStart = start2;
while (start2 < tokens.length) {
let type = tokens[start2][0];
if (type === ":" || type === "space" || type === "comment") {
break;
}
start2++;
}
node.prop = tokensToString(tokens, propStart, start2);
let betweenStart = start2;
let token;
while (start2 < tokens.length) {
token = tokens[start2];
start2++;
if (token[0] === ":") break;
if (token[0] === "word" && /\w/.test(token[1])) {
this.unknownWord([token]);
}
}
node.raws.between = tokensToString(tokens, betweenStart, start2);
if (node.prop[0] === "_" || node.prop[0] === "*") {
node.raws.before += node.prop[0];
node.prop = node.prop.slice(1);
}
let firstSpacesStart = start2;
while (start2 < tokens.length) {
let next = tokens[start2][0];
if (next !== "space" && next !== "comment") break;
start2++;
}
let firstSpaces = tokens.slice(firstSpacesStart, start2);
tokens = tokens.slice(start2);
this.precheckMissedSemicolon(tokens);
for (let i2 = tokens.length - 1; i2 >= 0; i2--) {
token = tokens[i2];
if (token[1].toLowerCase() === "!important") {
node.important = true;
let string = this.stringFrom(tokens, i2);
string = this.spacesFromEnd(tokens) + string;
if (string !== " !important") node.raws.important = string;
break;
} else if (token[1].toLowerCase() === "important") {
let cache = tokens.slice(0);
let str = "";
for (let j2 = i2; j2 > 0; j2--) {
let type = cache[j2][0];
if (str.trim().startsWith("!") && type !== "space") {
break;
}
str = cache.pop()[1] + str;
}
if (str.trim().startsWith("!")) {
node.important = true;
node.raws.important = str;
tokens = cache;
}
}
if (token[0] !== "space" && token[0] !== "comment") {
break;
}
}
let hasWord = tokens.some((i2) => i2[0] !== "space" && i2[0] !== "comment");
if (hasWord) {
node.raws.between += firstSpaces.map((i2) => i2[1]).join("");
firstSpaces = [];
}
this.raw(node, "value", firstSpaces.concat(tokens), customProperty);
if (node.value.includes(":") && !customProperty) {
this.checkMissedSemicolon(tokens);
}
}
doubleColon(token) {
throw this.input.error(
"Double colon",
{ offset: token[2] },
{ offset: token[2] + token[1].length }
);
}
emptyRule(token) {
let node = new Rule();
this.init(node, token[2]);
node.selector = "";
node.raws.between = "";
this.current = node;
}
end(token) {
if (this.current.nodes && this.current.nodes.length) {
this.current.raws.semicolon = this.semicolon;
}
this.semicolon = false;
this.current.raws.after = (this.current.raws.after || "") + this.spaces;
this.spaces = "";
if (this.current.parent) {
this.current.source.end = this.getPosition(token[2]);
this.current.source.end.offset++;
this.current = this.current.parent;
} else {
this.unexpectedClose(token);
}
}
endFile() {
if (this.current.parent) this.unclosedBlock();
if (this.current.nodes && this.current.nodes.length) {
this.current.raws.semicolon = this.semicolon;
}
this.current.raws.after = (this.current.raws.after || "") + this.spaces;
this.root.source.end = this.getPosition(this.tokenizer.position());
}
freeSemicolon(token) {
this.spaces += token[1];
if (this.current.nodes) {
let prev = this.current.nodes[this.current.nodes.length - 1];
if (prev && prev.type === "rule" && !prev.raws.ownSemicolon) {
prev.raws.ownSemicolon = this.spaces;
this.spaces = "";
prev.source.end = this.getPosition(token[2]);
prev.source.end.offset += prev.raws.ownSemicolon.length;
}
}
}
// Helpers
getPosition(offset4) {
let pos = this.input.fromOffset(offset4);
return {
column: pos.col,
line: pos.line,
offset: offset4
};
}
init(node, offset4) {
this.current.push(node);
node.source = {
input: this.input,
start: this.getPosition(offset4)
};
node.raws.before = this.spaces;
this.spaces = "";
if (node.type !== "comment") this.semicolon = false;
}
other(start2) {
let end = false;
let type = null;
let colon = false;
let bracket = null;
let brackets = [];
let customProperty = start2[1].startsWith("--");
let tokens = [];
let token = start2;
while (token) {
type = token[0];
tokens.push(token);
if (type === "(" || type === "[") {
if (!bracket) bracket = token;
brackets.push(type === "(" ? ")" : "]");
} else if (customProperty && colon && type === "{") {
if (!bracket) bracket = token;
brackets.push("}");
} else if (brackets.length === 0) {
if (type === ";") {
if (colon) {
this.decl(tokens, customProperty);
return;
} else {
break;
}
} else if (type === "{") {
this.rule(tokens);
return;
} else if (type === "}") {
this.tokenizer.back(tokens.pop());
end = true;
break;
} else if (type === ":") {
colon = true;
}
} else if (type === brackets[brackets.length - 1]) {
brackets.pop();
if (brackets.length === 0) bracket = null;
}
token = this.tokenizer.nextToken();
}
if (this.tokenizer.endOfFile()) end = true;
if (brackets.length > 0) this.unclosedBracket(bracket);
if (end && colon) {
if (!customProperty) {
while (tokens.length) {
token = tokens[tokens.length - 1][0];
if (token !== "space" && token !== "comment") break;
this.tokenizer.back(tokens.pop());
}
}
this.decl(tokens, customProperty);
} else {
this.unknownWord(tokens);
}
}
parse() {
let token;
while (!this.tokenizer.endOfFile()) {
token = this.tokenizer.nextToken();
switch (token[0]) {
case "space":
this.spaces += token[1];
break;
case ";":
this.freeSemicolon(token);
break;
case "}":
this.end(token);
break;
case "comment":
this.comment(token);
break;
case "at-word":
this.atrule(token);
break;
case "{":
this.emptyRule(token);
break;
default:
this.other(token);
break;
}
}
this.endFile();
}
precheckMissedSemicolon() {
}
raw(node, prop, tokens, customProperty) {
let token, type;
let length = tokens.length;
let value = "";
let clean = true;
let next, prev;
for (let i2 = 0; i2 < length; i2 += 1) {
token = tokens[i2];
type = token[0];
if (type === "space" && i2 === length - 1 && !customProperty) {
clean = false;
} else if (type === "comment") {
prev = tokens[i2 - 1] ? tokens[i2 - 1][0] : "empty";
next = tokens[i2 + 1] ? tokens[i2 + 1][0] : "empty";
if (!SAFE_COMMENT_NEIGHBOR[prev] && !SAFE_COMMENT_NEIGHBOR[next]) {
if (value.slice(-1) === ",") {
clean = false;
} else {
value += token[1];
}
} else {
clean = false;
}
} else {
value += token[1];
}
}
if (!clean) {
let raw = tokens.reduce((all, i2) => all + i2[1], "");
node.raws[prop] = { raw, value };
}
node[prop] = value;
}
rule(tokens) {
tokens.pop();
let node = new Rule();
this.init(node, tokens[0][2]);
node.raws.between = this.spacesAndCommentsFromEnd(tokens);
this.raw(node, "selector", tokens);
this.current = node;
}
spacesAndCommentsFromEnd(tokens) {
let lastTokenType;
let spaces = "";
while (tokens.length) {
lastTokenType = tokens[tokens.length - 1][0];
if (lastTokenType !== "space" && lastTokenType !== "comment") break;
spaces = tokens.pop()[1] + spaces;
}
return spaces;
}
// Errors
spacesAndCommentsFromStart(tokens) {
let next;
let spaces = "";
while (tokens.length) {
next = tokens[0][0];
if (next !== "space" && next !== "comment") break;
spaces += tokens.shift()[1];
}
return spaces;
}
spacesFromEnd(tokens) {
let lastTokenType;
let spaces = "";
while (tokens.length) {
lastTokenType = tokens[tokens.length - 1][0];
if (lastTokenType !== "space") break;
spaces = tokens.pop()[1] + spaces;
}
return spaces;
}
stringFrom(tokens, from) {
let result = "";
for (let i2 = from; i2 < tokens.length; i2++) {
result += tokens[i2][1];
}
tokens.splice(from, tokens.length - from);
return result;
}
unclosedBlock() {
let pos = this.current.source.start;
throw this.input.error("Unclosed block", pos.line, pos.column);
}
unclosedBracket(bracket) {
throw this.input.error(
"Unclosed bracket",
{ offset: bracket[2] },
{ offset: bracket[2] + 1 }
);
}
unexpectedClose(token) {
throw this.input.error(
"Unexpected }",
{ offset: token[2] },
{ offset: token[2] + 1 }
);
}
unknownWord(tokens) {
throw this.input.error(
"Unknown word " + tokens[0][1],
{ offset: tokens[0][2] },
{ offset: tokens[0][2] + tokens[0][1].length }
);
}
unnamedAtrule(node, token) {
throw this.input.error(
"At-rule without name",
{ offset: token[2] },
{ offset: token[2] + token[1].length }
);
}
};
module.exports = Parser;
}
});
// node_modules/postcss/lib/parse.js
var require_parse = __commonJS({
"node_modules/postcss/lib/parse.js"(exports, module) {
"use strict";
var Container = require_container();
var Input = require_input();
var Parser = require_parser();
function parse4(css, opts) {
let input = new Input(css, opts);
let parser = new Parser(input);
try {
parser.parse();
} catch (e2) {
if (true) {
if (e2.name === "CssSyntaxError" && opts && opts.from) {
if (/\.scss$/i.test(opts.from)) {
e2.message += "\nYou tried to parse SCSS with the standard CSS parser; try again with the postcss-scss parser";
} else if (/\.sass/i.test(opts.from)) {
e2.message += "\nYou tried to parse Sass with the standard CSS parser; try again with the postcss-sass parser";
} else if (/\.less$/i.test(opts.from)) {
e2.message += "\nYou tried to parse Less with the standard CSS parser; try again with the postcss-less parser";
}
}
}
throw e2;
}
return parser.root;
}
module.exports = parse4;
parse4.default = parse4;
Container.registerParse(parse4);
}
});
// node_modules/postcss/lib/warning.js
var require_warning2 = __commonJS({
"node_modules/postcss/lib/warning.js"(exports, module) {
"use strict";
var Warning2 = class {
constructor(text, opts = {}) {
this.type = "warning";
this.text = text;
if (opts.node && opts.node.source) {
let range2 = opts.node.rangeBy(opts);
this.line = range2.start.line;
this.column = range2.start.column;
this.endLine = range2.end.line;
this.endColumn = range2.end.column;
}
for (let opt in opts) this[opt] = opts[opt];
}
toString() {
if (this.node) {
return this.node.error(this.text, {
index: this.index,
plugin: this.plugin,
word: this.word
}).message;
}
if (this.plugin) {
return this.plugin + ": " + this.text;
}
return this.text;
}
};
module.exports = Warning2;
Warning2.default = Warning2;
}
});
// node_modules/postcss/lib/result.js
var require_result = __commonJS({
"node_modules/postcss/lib/result.js"(exports, module) {
"use strict";
var Warning2 = require_warning2();
var Result = class {
get content() {
return this.css;
}
constructor(processor, root, opts) {
this.processor = processor;
this.messages = [];
this.root = root;
this.opts = opts;
this.css = "";
this.map = void 0;
}
toString() {
return this.css;
}
warn(text, opts = {}) {
if (!opts.plugin) {
if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
opts.plugin = this.lastPlugin.postcssPlugin;
}
}
let warning6 = new Warning2(text, opts);
this.messages.push(warning6);
return warning6;
}
warnings() {
return this.messages.filter((i2) => i2.type === "warning");
}
};
module.exports = Result;
Result.default = Result;
}
});
// node_modules/postcss/lib/warn-once.js
var require_warn_once = __commonJS({
"node_modules/postcss/lib/warn-once.js"(exports, module) {
"use strict";
var printed = {};
module.exports = function warnOnce(message2) {
if (printed[message2]) return;
printed[message2] = true;
if (typeof console !== "undefined" && console.warn) {
console.warn(message2);
}
};
}
});
// node_modules/postcss/lib/lazy-result.js
var require_lazy_result = __commonJS({
"node_modules/postcss/lib/lazy-result.js"(exports, module) {
"use strict";
var Container = require_container();
var Document = require_document();
var MapGenerator = require_map_generator();
var parse4 = require_parse();
var Result = require_result();
var Root8 = require_root();
var stringify2 = require_stringify();
var { isClean, my } = require_symbols();
var warnOnce = require_warn_once();
var TYPE_TO_CLASS_NAME = {
atrule: "AtRule",
comment: "Comment",
decl: "Declaration",
document: "Document",
root: "Root",
rule: "Rule"
};
var PLUGIN_PROPS = {
AtRule: true,
AtRuleExit: true,
Comment: true,
CommentExit: true,
Declaration: true,
DeclarationExit: true,
Document: true,
DocumentExit: true,
Once: true,
OnceExit: true,
postcssPlugin: true,
prepare: true,
Root: true,
RootExit: true,
Rule: true,
RuleExit: true
};
var NOT_VISITORS = {
Once: true,
postcssPlugin: true,
prepare: true
};
var CHILDREN = 0;
function isPromise(obj) {
return typeof obj === "object" && typeof obj.then === "function";
}
function getEvents(node) {
let key = false;
let type = TYPE_TO_CLASS_NAME[node.type];
if (node.type === "decl") {
key = node.prop.toLowerCase();
} else if (node.type === "atrule") {
key = node.name.toLowerCase();
}
if (key && node.append) {
return [
type,
type + "-" + key,
CHILDREN,
type + "Exit",
type + "Exit-" + key
];
} else if (key) {
return [type, type + "-" + key, type + "Exit", type + "Exit-" + key];
} else if (node.append) {
return [type, CHILDREN, type + "Exit"];
} else {
return [type, type + "Exit"];
}
}
function toStack(node) {
let events;
if (node.type === "document") {
events = ["Document", CHILDREN, "DocumentExit"];
} else if (node.type === "root") {
events = ["Root", CHILDREN, "RootExit"];
} else {
events = getEvents(node);
}
return {
eventIndex: 0,
events,
iterator: 0,
node,
visitorIndex: 0,
visitors: []
};
}
function cleanMarks(node) {
node[isClean] = false;
if (node.nodes) node.nodes.forEach((i2) => cleanMarks(i2));
return node;
}
var postcss = {};
var LazyResult = class _LazyResult {
get content() {
return this.stringify().content;
}
get css() {
return this.stringify().css;
}
get map() {
return this.stringify().map;
}
get messages() {
return this.sync().messages;
}
get opts() {
return this.result.opts;
}
get processor() {
return this.result.processor;
}
get root() {
return this.sync().root;
}
get [Symbol.toStringTag]() {
return "LazyResult";
}
constructor(processor, css, opts) {
this.stringified = false;
this.processed = false;
let root;
if (typeof css === "object" && css !== null && (css.type === "root" || css.type === "document")) {
root = cleanMarks(css);
} else if (css instanceof _LazyResult || css instanceof Result) {
root = cleanMarks(css.root);
if (css.map) {
if (typeof opts.map === "undefined") opts.map = {};
if (!opts.map.inline) opts.map.inline = false;
opts.map.prev = css.map;
}
} else {
let parser = parse4;
if (opts.syntax) parser = opts.syntax.parse;
if (opts.parser) parser = opts.parser;
if (parser.parse) parser = parser.parse;
try {
root = parser(css, opts);
} catch (error2) {
this.processed = true;
this.error = error2;
}
if (root && !root[my]) {
Container.rebuild(root);
}
}
this.result = new Result(processor, root, opts);
this.helpers = { ...postcss, postcss, result: this.result };
this.plugins = this.processor.plugins.map((plugin) => {
if (typeof plugin === "object" && plugin.prepare) {
return { ...plugin, ...plugin.prepare(this.result) };
} else {
return plugin;
}
});
}
async() {
if (this.error) return Promise.reject(this.error);
if (this.processed) return Promise.resolve(this.result);
if (!this.processing) {
this.processing = this.runAsync();
}
return this.processing;
}
catch(onRejected) {
return this.async().catch(onRejected);
}
finally(onFinally) {
return this.async().then(onFinally, onFinally);
}
getAsyncError() {
throw new Error("Use process(css).then(cb) to work with async plugins");
}
handleError(error2, node) {
let plugin = this.result.lastPlugin;
try {
if (node) node.addToError(error2);
this.error = error2;
if (error2.name === "CssSyntaxError" && !error2.plugin) {
error2.plugin = plugin.postcssPlugin;
error2.setMessage();
} else if (plugin.postcssVersion) {
if (true) {
let pluginName = plugin.postcssPlugin;
let pluginVer = plugin.postcssVersion;
let runtimeVer = this.result.processor.version;
let a2 = pluginVer.split(".");
let b2 = runtimeVer.split(".");
if (a2[0] !== b2[0] || parseInt(a2[1]) > parseInt(b2[1])) {
console.error(
"Unknown error from PostCSS plugin. Your current PostCSS version is " + runtimeVer + ", but " + pluginName + " uses " + pluginVer + ". Perhaps this is the source of the error below."
);
}
}
}
} catch (err) {
if (console && console.error) console.error(err);
}
return error2;
}
prepareVisitors() {
this.listeners = {};
let add2 = (plugin, type, cb) => {
if (!this.listeners[type]) this.listeners[type] = [];
this.listeners[type].push([plugin, cb]);
};
for (let plugin of this.plugins) {
if (typeof plugin === "object") {
for (let event in plugin) {
if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) {
throw new Error(
`Unknown event ${event} in ${plugin.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`
);
}
if (!NOT_VISITORS[event]) {
if (typeof plugin[event] === "object") {
for (let filter in plugin[event]) {
if (filter === "*") {
add2(plugin, event, plugin[event][filter]);
} else {
add2(
plugin,
event + "-" + filter.toLowerCase(),
plugin[event][filter]
);
}
}
} else if (typeof plugin[event] === "function") {
add2(plugin, event, plugin[event]);
}
}
}
}
}
this.hasListener = Object.keys(this.listeners).length > 0;
}
async runAsync() {
this.plugin = 0;
for (let i2 = 0; i2 < this.plugins.length; i2++) {
let plugin = this.plugins[i2];
let promise = this.runOnRoot(plugin);
if (isPromise(promise)) {
try {
await promise;
} catch (error2) {
throw this.handleError(error2);
}
}
}
this.prepareVisitors();
if (this.hasListener) {
let root = this.result.root;
while (!root[isClean]) {
root[isClean] = true;
let stack = [toStack(root)];
while (stack.length > 0) {
let promise = this.visitTick(stack);
if (isPromise(promise)) {
try {
await promise;
} catch (e2) {
let node = stack[stack.length - 1].node;
throw this.handleError(e2, node);
}
}
}
}
if (this.listeners.OnceExit) {
for (let [plugin, visitor] of this.listeners.OnceExit) {
this.result.lastPlugin = plugin;
try {
if (root.type === "document") {
let roots = root.nodes.map(
(subRoot) => visitor(subRoot, this.helpers)
);
await Promise.all(roots);
} else {
await visitor(root, this.helpers);
}
} catch (e2) {
throw this.handleError(e2);
}
}
}
}
this.processed = true;
return this.stringify();
}
runOnRoot(plugin) {
this.result.lastPlugin = plugin;
try {
if (typeof plugin === "object" && plugin.Once) {
if (this.result.root.type === "document") {
let roots = this.result.root.nodes.map(
(root) => plugin.Once(root, this.helpers)
);
if (isPromise(roots[0])) {
return Promise.all(roots);
}
return roots;
}
return plugin.Once(this.result.root, this.helpers);
} else if (typeof plugin === "function") {
return plugin(this.result.root, this.result);
}
} catch (error2) {
throw this.handleError(error2);
}
}
stringify() {
if (this.error) throw this.error;
if (this.stringified) return this.result;
this.stringified = true;
this.sync();
let opts = this.result.opts;
let str = stringify2;
if (opts.syntax) str = opts.syntax.stringify;
if (opts.stringifier) str = opts.stringifier;
if (str.stringify) str = str.stringify;
let rootSource = this.result.root.source;
if (opts.map === void 0 && !(rootSource && rootSource.input && rootSource.input.map)) {
let result = "";
str(this.result.root, (i2) => {
result += i2;
});
this.result.css = result;
return this.result;
}
let map = new MapGenerator(str, this.result.root, this.result.opts);
let data = map.generate();
this.result.css = data[0];
this.result.map = data[1];
return this.result;
}
sync() {
if (this.error) throw this.error;
if (this.processed) return this.result;
this.processed = true;
if (this.processing) {
throw this.getAsyncError();
}
for (let plugin of this.plugins) {
let promise = this.runOnRoot(plugin);
if (isPromise(promise)) {
throw this.getAsyncError();
}
}
this.prepareVisitors();
if (this.hasListener) {
let root = this.result.root;
while (!root[isClean]) {
root[isClean] = true;
this.walkSync(root);
}
if (this.listeners.OnceExit) {
if (root.type === "document") {
for (let subRoot of root.nodes) {
this.visitSync(this.listeners.OnceExit, subRoot);
}
} else {
this.visitSync(this.listeners.OnceExit, root);
}
}
}
return this.result;
}
then(onFulfilled, onRejected) {
if (true) {
if (!("from" in this.opts)) {
warnOnce(
"Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning."
);
}
}
return this.async().then(onFulfilled, onRejected);
}
toString() {
return this.css;
}
visitSync(visitors, node) {
for (let [plugin, visitor] of visitors) {
this.result.lastPlugin = plugin;
let promise;
try {
promise = visitor(node, this.helpers);
} catch (e2) {
throw this.handleError(e2, node.proxyOf);
}
if (node.type !== "root" && node.type !== "document" && !node.parent) {
return true;
}
if (isPromise(promise)) {
throw this.getAsyncError();
}
}
}
visitTick(stack) {
let visit = stack[stack.length - 1];
let { node, visitors } = visit;
if (node.type !== "root" && node.type !== "document" && !node.parent) {
stack.pop();
return;
}
if (visitors.length > 0 && visit.visitorIndex < visitors.length) {
let [plugin, visitor] = visitors[visit.visitorIndex];
visit.visitorIndex += 1;
if (visit.visitorIndex === visitors.length) {
visit.visitors = [];
visit.visitorIndex = 0;
}
this.result.lastPlugin = plugin;
try {
return visitor(node.toProxy(), this.helpers);
} catch (e2) {
throw this.handleError(e2, node);
}
}
if (visit.iterator !== 0) {
let iterator = visit.iterator;
let child;
while (child = node.nodes[node.indexes[iterator]]) {
node.indexes[iterator] += 1;
if (!child[isClean]) {
child[isClean] = true;
stack.push(toStack(child));
return;
}
}
visit.iterator = 0;
delete node.indexes[iterator];
}
let events = visit.events;
while (visit.eventIndex < events.length) {
let event = events[visit.eventIndex];
visit.eventIndex += 1;
if (event === CHILDREN) {
if (node.nodes && node.nodes.length) {
node[isClean] = true;
visit.iterator = node.getIterator();
}
return;
} else if (this.listeners[event]) {
visit.visitors = this.listeners[event];
return;
}
}
stack.pop();
}
walkSync(node) {
node[isClean] = true;
let events = getEvents(node);
for (let event of events) {
if (event === CHILDREN) {
if (node.nodes) {
node.each((child) => {
if (!child[isClean]) this.walkSync(child);
});
}
} else {
let visitors = this.listeners[event];
if (visitors) {
if (this.visitSync(visitors, node.toProxy())) return;
}
}
}
}
warnings() {
return this.sync().warnings();
}
};
LazyResult.registerPostcss = (dependant) => {
postcss = dependant;
};
module.exports = LazyResult;
LazyResult.default = LazyResult;
Root8.registerLazyResult(LazyResult);
Document.registerLazyResult(LazyResult);
}
});
// node_modules/postcss/lib/no-work-result.js
var require_no_work_result = __commonJS({
"node_modules/postcss/lib/no-work-result.js"(exports, module) {
"use strict";
var MapGenerator = require_map_generator();
var parse4 = require_parse();
var Result = require_result();
var stringify2 = require_stringify();
var warnOnce = require_warn_once();
var NoWorkResult = class {
get content() {
return this.result.css;
}
get css() {
return this.result.css;
}
get map() {
return this.result.map;
}
get messages() {
return [];
}
get opts() {
return this.result.opts;
}
get processor() {
return this.result.processor;
}
get root() {
if (this._root) {
return this._root;
}
let root;
let parser = parse4;
try {
root = parser(this._css, this._opts);
} catch (error2) {
this.error = error2;
}
if (this.error) {
throw this.error;
} else {
this._root = root;
return root;
}
}
get [Symbol.toStringTag]() {
return "NoWorkResult";
}
constructor(processor, css, opts) {
css = css.toString();
this.stringified = false;
this._processor = processor;
this._css = css;
this._opts = opts;
this._map = void 0;
let str = stringify2;
this.result = new Result(this._processor, void 0, this._opts);
this.result.css = css;
let self = this;
Object.defineProperty(this.result, "root", {
get() {
return self.root;
}
});
let map = new MapGenerator(str, void 0, this._opts, css);
if (map.isMap()) {
let [generatedCSS, generatedMap] = map.generate();
if (generatedCSS) {
this.result.css = generatedCSS;
}
if (generatedMap) {
this.result.map = generatedMap;
}
} else {
map.clearAnnotation();
this.result.css = map.css;
}
}
async() {
if (this.error) return Promise.reject(this.error);
return Promise.resolve(this.result);
}
catch(onRejected) {
return this.async().catch(onRejected);
}
finally(onFinally) {
return this.async().then(onFinally, onFinally);
}
sync() {
if (this.error) throw this.error;
return this.result;
}
then(onFulfilled, onRejected) {
if (true) {
if (!("from" in this._opts)) {
warnOnce(
"Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning."
);
}
}
return this.async().then(onFulfilled, onRejected);
}
toString() {
return this._css;
}
warnings() {
return [];
}
};
module.exports = NoWorkResult;
NoWorkResult.default = NoWorkResult;
}
});
// node_modules/postcss/lib/processor.js
var require_processor = __commonJS({
"node_modules/postcss/lib/processor.js"(exports, module) {
"use strict";
var Document = require_document();
var LazyResult = require_lazy_result();
var NoWorkResult = require_no_work_result();
var Root8 = require_root();
var Processor2 = class {
constructor(plugins = []) {
this.version = "8.5.16";
this.plugins = this.normalize(plugins);
}
normalize(plugins) {
let normalized = [];
for (let i2 of plugins) {
if (i2.postcss === true) {
i2 = i2();
} else if (i2.postcss) {
i2 = i2.postcss;
}
if (typeof i2 === "object" && Array.isArray(i2.plugins)) {
normalized = normalized.concat(i2.plugins);
} else if (typeof i2 === "object" && i2.postcssPlugin) {
normalized.push(i2);
} else if (typeof i2 === "function") {
normalized.push(i2);
} else if (typeof i2 === "object" && (i2.parse || i2.stringify)) {
if (true) {
throw new Error(
"PostCSS syntaxes cannot be used as plugins. Instead, please use one of the syntax/parser/stringifier options as outlined in your PostCSS runner documentation."
);
}
} else {
throw new Error(i2 + " is not a PostCSS plugin");
}
}
return normalized;
}
process(css, opts = {}) {
if (!this.plugins.length && !opts.parser && !opts.stringifier && !opts.syntax) {
return new NoWorkResult(this, css, opts);
} else {
return new LazyResult(this, css, opts);
}
}
use(plugin) {
this.plugins = this.plugins.concat(this.normalize([plugin]));
return this;
}
};
module.exports = Processor2;
Processor2.default = Processor2;
Root8.registerProcessor(Processor2);
Document.registerProcessor(Processor2);
}
});
// node_modules/postcss-prefix-selector/index.js
var require_postcss_prefix_selector = __commonJS({
"node_modules/postcss-prefix-selector/index.js"(exports, module) {
module.exports = function postcssPrefixSelector(options) {
const prefix2 = options.prefix;
const prefixWithSpace = /\s+$/.test(prefix2) ? prefix2 : `${prefix2} `;
const ignoreFiles = options.ignoreFiles ? [].concat(options.ignoreFiles) : [];
const includeFiles = options.includeFiles ? [].concat(options.includeFiles) : [];
return function(root) {
if (ignoreFiles.length && root.source.input.file && isFileInArray(root.source.input.file, ignoreFiles)) {
return;
}
if (includeFiles.length && root.source.input.file && !isFileInArray(root.source.input.file, includeFiles)) {
return;
}
root.walkRules((rule) => {
const keyframeRules = [
"keyframes",
"-webkit-keyframes",
"-moz-keyframes",
"-o-keyframes",
"-ms-keyframes"
];
if (rule.parent && keyframeRules.includes(rule.parent.name)) {
return;
}
rule.selectors = rule.selectors.map((selector3) => {
if (options.exclude && excludeSelector(selector3, options.exclude)) {
return selector3;
}
if (options.transform) {
return options.transform(
prefix2,
selector3,
prefixWithSpace + selector3,
root.source.input.file,
rule
);
}
return prefixWithSpace + selector3;
});
});
};
};
function isFileInArray(file, arr) {
return arr.some((ruleOrString) => {
if (ruleOrString instanceof RegExp) {
return ruleOrString.test(file);
}
return file.includes(ruleOrString);
});
}
function excludeSelector(selector3, excludeArr) {
return excludeArr.some((excludeRule) => {
if (excludeRule instanceof RegExp) {
return excludeRule.test(selector3);
}
return selector3 === excludeRule;
});
}
}
});
// node_modules/postcss-value-parser/lib/parse.js
var require_parse2 = __commonJS({
"node_modules/postcss-value-parser/lib/parse.js"(exports, module) {
var openParentheses = "(".charCodeAt(0);
var closeParentheses = ")".charCodeAt(0);
var singleQuote = "'".charCodeAt(0);
var doubleQuote = '"'.charCodeAt(0);
var backslash = "\\".charCodeAt(0);
var slash = "/".charCodeAt(0);
var comma = ",".charCodeAt(0);
var colon = ":".charCodeAt(0);
var star = "*".charCodeAt(0);
var uLower = "u".charCodeAt(0);
var uUpper = "U".charCodeAt(0);
var plus = "+".charCodeAt(0);
var isUnicodeRange = /^[a-f0-9?-]+$/i;
module.exports = function(input) {
var tokens = [];
var value = input;
var next, quote, prev, token, escape, escapePos, whitespacePos, parenthesesOpenPos;
var pos = 0;
var code = value.charCodeAt(pos);
var max2 = value.length;
var stack = [{ nodes: tokens }];
var balanced = 0;
var parent;
var name = "";
var before = "";
var after = "";
while (pos < max2) {
if (code <= 32) {
next = pos;
do {
next += 1;
code = value.charCodeAt(next);
} while (code <= 32);
token = value.slice(pos, next);
prev = tokens[tokens.length - 1];
if (code === closeParentheses && balanced) {
after = token;
} else if (prev && prev.type === "div") {
prev.after = token;
prev.sourceEndIndex += token.length;
} else if (code === comma || code === colon || code === slash && value.charCodeAt(next + 1) !== star && (!parent || parent && parent.type === "function" && parent.value !== "calc")) {
before = token;
} else {
tokens.push({
type: "space",
sourceIndex: pos,
sourceEndIndex: next,
value: token
});
}
pos = next;
} else if (code === singleQuote || code === doubleQuote) {
next = pos;
quote = code === singleQuote ? "'" : '"';
token = {
type: "string",
sourceIndex: pos,
quote
};
do {
escape = false;
next = value.indexOf(quote, next + 1);
if (~next) {
escapePos = next;
while (value.charCodeAt(escapePos - 1) === backslash) {
escapePos -= 1;
escape = !escape;
}
} else {
value += quote;
next = value.length - 1;
token.unclosed = true;
}
} while (escape);
token.value = value.slice(pos + 1, next);
token.sourceEndIndex = token.unclosed ? next : next + 1;
tokens.push(token);
pos = next + 1;
code = value.charCodeAt(pos);
} else if (code === slash && value.charCodeAt(pos + 1) === star) {
next = value.indexOf("*/", pos);
token = {
type: "comment",
sourceIndex: pos,
sourceEndIndex: next + 2
};
if (next === -1) {
token.unclosed = true;
next = value.length;
token.sourceEndIndex = next;
}
token.value = value.slice(pos + 2, next);
tokens.push(token);
pos = next + 2;
code = value.charCodeAt(pos);
} else if ((code === slash || code === star) && parent && parent.type === "function" && parent.value === "calc") {
token = value[pos];
tokens.push({
type: "word",
sourceIndex: pos - before.length,
sourceEndIndex: pos + token.length,
value: token
});
pos += 1;
code = value.charCodeAt(pos);
} else if (code === slash || code === comma || code === colon) {
token = value[pos];
tokens.push({
type: "div",
sourceIndex: pos - before.length,
sourceEndIndex: pos + token.length,
value: token,
before,
after: ""
});
before = "";
pos += 1;
code = value.charCodeAt(pos);
} else if (openParentheses === code) {
next = pos;
do {
next += 1;
code = value.charCodeAt(next);
} while (code <= 32);
parenthesesOpenPos = pos;
token = {
type: "function",
sourceIndex: pos - name.length,
value: name,
before: value.slice(parenthesesOpenPos + 1, next)
};
pos = next;
if (name === "url" && code !== singleQuote && code !== doubleQuote) {
next -= 1;
do {
escape = false;
next = value.indexOf(")", next + 1);
if (~next) {
escapePos = next;
while (value.charCodeAt(escapePos - 1) === backslash) {
escapePos -= 1;
escape = !escape;
}
} else {
value += ")";
next = value.length - 1;
token.unclosed = true;
}
} while (escape);
whitespacePos = next;
do {
whitespacePos -= 1;
code = value.charCodeAt(whitespacePos);
} while (code <= 32);
if (parenthesesOpenPos < whitespacePos) {
if (pos !== whitespacePos + 1) {
token.nodes = [
{
type: "word",
sourceIndex: pos,
sourceEndIndex: whitespacePos + 1,
value: value.slice(pos, whitespacePos + 1)
}
];
} else {
token.nodes = [];
}
if (token.unclosed && whitespacePos + 1 !== next) {
token.after = "";
token.nodes.push({
type: "space",
sourceIndex: whitespacePos + 1,
sourceEndIndex: next,
value: value.slice(whitespacePos + 1, next)
});
} else {
token.after = value.slice(whitespacePos + 1, next);
token.sourceEndIndex = next;
}
} else {
token.after = "";
token.nodes = [];
}
pos = next + 1;
token.sourceEndIndex = token.unclosed ? next : pos;
code = value.charCodeAt(pos);
tokens.push(token);
} else {
balanced += 1;
token.after = "";
token.sourceEndIndex = pos + 1;
tokens.push(token);
stack.push(token);
tokens = token.nodes = [];
parent = token;
}
name = "";
} else if (closeParentheses === code && balanced) {
pos += 1;
code = value.charCodeAt(pos);
parent.after = after;
parent.sourceEndIndex += after.length;
after = "";
balanced -= 1;
stack[stack.length - 1].sourceEndIndex = pos;
stack.pop();
parent = stack[balanced];
tokens = parent.nodes;
} else {
next = pos;
do {
if (code === backslash) {
next += 1;
}
next += 1;
code = value.charCodeAt(next);
} while (next < max2 && !(code <= 32 || code === singleQuote || code === doubleQuote || code === comma || code === colon || code === slash || code === openParentheses || code === star && parent && parent.type === "function" && parent.value === "calc" || code === slash && parent.type === "function" && parent.value === "calc" || code === closeParentheses && balanced));
token = value.slice(pos, next);
if (openParentheses === code) {
name = token;
} else if ((uLower === token.charCodeAt(0) || uUpper === token.charCodeAt(0)) && plus === token.charCodeAt(1) && isUnicodeRange.test(token.slice(2))) {
tokens.push({
type: "unicode-range",
sourceIndex: pos,
sourceEndIndex: next,
value: token
});
} else {
tokens.push({
type: "word",
sourceIndex: pos,
sourceEndIndex: next,
value: token
});
}
pos = next;
}
}
for (pos = stack.length - 1; pos; pos -= 1) {
stack[pos].unclosed = true;
stack[pos].sourceEndIndex = value.length;
}
return stack[0].nodes;
};
}
});
// node_modules/postcss-value-parser/lib/walk.js
var require_walk = __commonJS({
"node_modules/postcss-value-parser/lib/walk.js"(exports, module) {
module.exports = function walk(nodes, cb, bubble) {
var i2, max2, node, result;
for (i2 = 0, max2 = nodes.length; i2 < max2; i2 += 1) {
node = nodes[i2];
if (!bubble) {
result = cb(node, i2, nodes);
}
if (result !== false && node.type === "function" && Array.isArray(node.nodes)) {
walk(node.nodes, cb, bubble);
}
if (bubble) {
cb(node, i2, nodes);
}
}
};
}
});
// node_modules/postcss-value-parser/lib/stringify.js
var require_stringify2 = __commonJS({
"node_modules/postcss-value-parser/lib/stringify.js"(exports, module) {
function stringifyNode(node, custom) {
var type = node.type;
var value = node.value;
var buf;
var customResult;
if (custom && (customResult = custom(node)) !== void 0) {
return customResult;
} else if (type === "word" || type === "space") {
return value;
} else if (type === "string") {
buf = node.quote || "";
return buf + value + (node.unclosed ? "" : buf);
} else if (type === "comment") {
return "/*" + value + (node.unclosed ? "" : "*/");
} else if (type === "div") {
return (node.before || "") + value + (node.after || "");
} else if (Array.isArray(node.nodes)) {
buf = stringify2(node.nodes, custom);
if (type !== "function") {
return buf;
}
return value + "(" + (node.before || "") + buf + (node.after || "") + (node.unclosed ? "" : ")");
}
return value;
}
function stringify2(nodes, custom) {
var result, i2;
if (Array.isArray(nodes)) {
result = "";
for (i2 = nodes.length - 1; ~i2; i2 -= 1) {
result = stringifyNode(nodes[i2], custom) + result;
}
return result;
}
return stringifyNode(nodes, custom);
}
module.exports = stringify2;
}
});
// node_modules/postcss-value-parser/lib/unit.js
var require_unit = __commonJS({
"node_modules/postcss-value-parser/lib/unit.js"(exports, module) {
var minus = "-".charCodeAt(0);
var plus = "+".charCodeAt(0);
var dot = ".".charCodeAt(0);
var exp = "e".charCodeAt(0);
var EXP = "E".charCodeAt(0);
function likeNumber(value) {
var code = value.charCodeAt(0);
var nextCode;
if (code === plus || code === minus) {
nextCode = value.charCodeAt(1);
if (nextCode >= 48 && nextCode <= 57) {
return true;
}
var nextNextCode = value.charCodeAt(2);
if (nextCode === dot && nextNextCode >= 48 && nextNextCode <= 57) {
return true;
}
return false;
}
if (code === dot) {
nextCode = value.charCodeAt(1);
if (nextCode >= 48 && nextCode <= 57) {
return true;
}
return false;
}
if (code >= 48 && code <= 57) {
return true;
}
return false;
}
module.exports = function(value) {
var pos = 0;
var length = value.length;
var code;
var nextCode;
var nextNextCode;
if (length === 0 || !likeNumber(value)) {
return false;
}
code = value.charCodeAt(pos);
if (code === plus || code === minus) {
pos++;
}
while (pos < length) {
code = value.charCodeAt(pos);
if (code < 48 || code > 57) {
break;
}
pos += 1;
}
code = value.charCodeAt(pos);
nextCode = value.charCodeAt(pos + 1);
if (code === dot && nextCode >= 48 && nextCode <= 57) {
pos += 2;
while (pos < length) {
code = value.charCodeAt(pos);
if (code < 48 || code > 57) {
break;
}
pos += 1;
}
}
code = value.charCodeAt(pos);
nextCode = value.charCodeAt(pos + 1);
nextNextCode = value.charCodeAt(pos + 2);
if ((code === exp || code === EXP) && (nextCode >= 48 && nextCode <= 57 || (nextCode === plus || nextCode === minus) && nextNextCode >= 48 && nextNextCode <= 57)) {
pos += nextCode === plus || nextCode === minus ? 3 : 2;
while (pos < length) {
code = value.charCodeAt(pos);
if (code < 48 || code > 57) {
break;
}
pos += 1;
}
}
return {
number: value.slice(0, pos),
unit: value.slice(pos)
};
};
}
});
// node_modules/postcss-value-parser/lib/index.js
var require_lib2 = __commonJS({
"node_modules/postcss-value-parser/lib/index.js"(exports, module) {
var parse4 = require_parse2();
var walk = require_walk();
var stringify2 = require_stringify2();
function ValueParser(value) {
if (this instanceof ValueParser) {
this.nodes = parse4(value);
return this;
}
return new ValueParser(value);
}
ValueParser.prototype.toString = function() {
return Array.isArray(this.nodes) ? stringify2(this.nodes) : "";
};
ValueParser.prototype.walk = function(cb, bubble) {
walk(this.nodes, cb, bubble);
return this;
};
ValueParser.unit = require_unit();
ValueParser.walk = walk;
ValueParser.stringify = stringify2;
module.exports = ValueParser;
}
});
// packages/block-editor/node_modules/postcss-urlrebase/index.js
var require_postcss_urlrebase = __commonJS({
"packages/block-editor/node_modules/postcss-urlrebase/index.js"(exports, module) {
var CSSValueParser = require_lib2();
module.exports = (opts) => {
const DEFAULTS = {
skipHostRelativeUrls: true
};
const config2 = Object.assign(DEFAULTS, opts);
return {
postcssPlugin: "rebaseUrl",
Declaration(decl) {
const parsedValue = CSSValueParser(decl.value);
let valueChanged = false;
parsedValue.walk((node) => {
if (node.type !== "function" || node.value !== "url") {
return;
}
const urlVal = node.nodes[0].value;
const basedUrl = new URL(urlVal, opts.rootUrl);
if (basedUrl.pathname === urlVal && config2.skipHostRelativeUrls) {
return false;
}
node.nodes[0].value = basedUrl.toString();
valueChanged = true;
return false;
});
if (valueChanged) {
decl.value = CSSValueParser.stringify(parsedValue);
}
}
};
};
module.exports.postcss = true;
}
});
// package-external:@wordpress/priority-queue
var require_priority_queue = __commonJS({
"package-external:@wordpress/priority-queue"(exports, module) {
module.exports = window.wp.priorityQueue;
}
});
// package-external:@wordpress/blob
var require_blob = __commonJS({
"package-external:@wordpress/blob"(exports, module) {
module.exports = window.wp.blob;
}
});
// package-external:@wordpress/is-shallow-equal
var require_is_shallow_equal = __commonJS({
"package-external:@wordpress/is-shallow-equal"(exports, module) {
module.exports = window.wp.isShallowEqual;
}
});
// package-external:@wordpress/token-list
var require_token_list = __commonJS({
"package-external:@wordpress/token-list"(exports, module) {
module.exports = window.wp.tokenList;
}
});
// package-external:@wordpress/commands
var require_commands = __commonJS({
"package-external:@wordpress/commands"(exports, module) {
module.exports = window.wp.commands;
}
});
// package-external:@wordpress/date
var require_date = __commonJS({
"package-external:@wordpress/date"(exports, module) {
module.exports = window.wp.date;
}
});
// node_modules/normalize-wheel/src/UserAgent_DEPRECATED.js
var require_UserAgent_DEPRECATED = __commonJS({
"node_modules/normalize-wheel/src/UserAgent_DEPRECATED.js"(exports, module) {
var _populated = false;
var _ie;
var _firefox;
var _opera;
var _webkit;
var _chrome;
var _ie_real_version;
var _osx;
var _windows;
var _linux;
var _android;
var _win64;
var _iphone;
var _ipad;
var _native;
var _mobile;
function _populate() {
if (_populated) {
return;
}
_populated = true;
var uas = navigator.userAgent;
var agent = /(?:MSIE.(\d+\.\d+))|(?:(?:Firefox|GranParadiso|Iceweasel).(\d+\.\d+))|(?:Opera(?:.+Version.|.)(\d+\.\d+))|(?:AppleWebKit.(\d+(?:\.\d+)?))|(?:Trident\/\d+\.\d+.*rv:(\d+\.\d+))/.exec(uas);
var os = /(Mac OS X)|(Windows)|(Linux)/.exec(uas);
_iphone = /\b(iPhone|iP[ao]d)/.exec(uas);
_ipad = /\b(iP[ao]d)/.exec(uas);
_android = /Android/i.exec(uas);
_native = /FBAN\/\w+;/i.exec(uas);
_mobile = /Mobile/i.exec(uas);
_win64 = !!/Win64/.exec(uas);
if (agent) {
_ie = agent[1] ? parseFloat(agent[1]) : agent[5] ? parseFloat(agent[5]) : NaN;
if (_ie && document && document.documentMode) {
_ie = document.documentMode;
}
var trident = /(?:Trident\/(\d+.\d+))/.exec(uas);
_ie_real_version = trident ? parseFloat(trident[1]) + 4 : _ie;
_firefox = agent[2] ? parseFloat(agent[2]) : NaN;
_opera = agent[3] ? parseFloat(agent[3]) : NaN;
_webkit = agent[4] ? parseFloat(agent[4]) : NaN;
if (_webkit) {
agent = /(?:Chrome\/(\d+\.\d+))/.exec(uas);
_chrome = agent && agent[1] ? parseFloat(agent[1]) : NaN;
} else {
_chrome = NaN;
}
} else {
_ie = _firefox = _opera = _chrome = _webkit = NaN;
}
if (os) {
if (os[1]) {
var ver = /(?:Mac OS X (\d+(?:[._]\d+)?))/.exec(uas);
_osx = ver ? parseFloat(ver[1].replace("_", ".")) : true;
} else {
_osx = false;
}
_windows = !!os[2];
_linux = !!os[3];
} else {
_osx = _windows = _linux = false;
}
}
var UserAgent_DEPRECATED = {
/**
* Check if the UA is Internet Explorer.
*
*
* @return float|NaN Version number (if match) or NaN.
*/
ie: function() {
return _populate() || _ie;
},
/**
* Check if we're in Internet Explorer compatibility mode.
*
* @return bool true if in compatibility mode, false if
* not compatibility mode or not ie
*/
ieCompatibilityMode: function() {
return _populate() || _ie_real_version > _ie;
},
/**
* Whether the browser is 64-bit IE. Really, this is kind of weak sauce; we
* only need this because Skype can't handle 64-bit IE yet. We need to remove
* this when we don't need it -- tracked by #601957.
*/
ie64: function() {
return UserAgent_DEPRECATED.ie() && _win64;
},
/**
* Check if the UA is Firefox.
*
*
* @return float|NaN Version number (if match) or NaN.
*/
firefox: function() {
return _populate() || _firefox;
},
/**
* Check if the UA is Opera.
*
*
* @return float|NaN Version number (if match) or NaN.
*/
opera: function() {
return _populate() || _opera;
},
/**
* Check if the UA is WebKit.
*
*
* @return float|NaN Version number (if match) or NaN.
*/
webkit: function() {
return _populate() || _webkit;
},
/**
* For Push
* WILL BE REMOVED VERY SOON. Use UserAgent_DEPRECATED.webkit
*/
safari: function() {
return UserAgent_DEPRECATED.webkit();
},
/**
* Check if the UA is a Chrome browser.
*
*
* @return float|NaN Version number (if match) or NaN.
*/
chrome: function() {
return _populate() || _chrome;
},
/**
* Check if the user is running Windows.
*
* @return bool `true' if the user's OS is Windows.
*/
windows: function() {
return _populate() || _windows;
},
/**
* Check if the user is running Mac OS X.
*
* @return float|bool Returns a float if a version number is detected,
* otherwise true/false.
*/
osx: function() {
return _populate() || _osx;
},
/**
* Check if the user is running Linux.
*
* @return bool `true' if the user's OS is some flavor of Linux.
*/
linux: function() {
return _populate() || _linux;
},
/**
* Check if the user is running on an iPhone or iPod platform.
*
* @return bool `true' if the user is running some flavor of the
* iPhone OS.
*/
iphone: function() {
return _populate() || _iphone;
},
mobile: function() {
return _populate() || (_iphone || _ipad || _android || _mobile);
},
nativeApp: function() {
return _populate() || _native;
},
android: function() {
return _populate() || _android;
},
ipad: function() {
return _populate() || _ipad;
}
};
module.exports = UserAgent_DEPRECATED;
}
});
// node_modules/normalize-wheel/src/ExecutionEnvironment.js
var require_ExecutionEnvironment = __commonJS({
"node_modules/normalize-wheel/src/ExecutionEnvironment.js"(exports, module) {
"use strict";
var canUseDOM = !!(typeof window !== "undefined" && window.document && window.document.createElement);
var ExecutionEnvironment = {
canUseDOM,
canUseWorkers: typeof Worker !== "undefined",
canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent),
canUseViewport: canUseDOM && !!window.screen,
isInWorker: !canUseDOM
// For now, this is true - might change in the future.
};
module.exports = ExecutionEnvironment;
}
});
// node_modules/normalize-wheel/src/isEventSupported.js
var require_isEventSupported = __commonJS({
"node_modules/normalize-wheel/src/isEventSupported.js"(exports, module) {
"use strict";
var ExecutionEnvironment = require_ExecutionEnvironment();
var useHasFeature;
if (ExecutionEnvironment.canUseDOM) {
useHasFeature = document.implementation && document.implementation.hasFeature && // always returns true in newer browsers as per the standard.
// @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature
document.implementation.hasFeature("", "") !== true;
}
function isEventSupported(eventNameSuffix, capture) {
if (!ExecutionEnvironment.canUseDOM || capture && !("addEventListener" in document)) {
return false;
}
var eventName = "on" + eventNameSuffix;
var isSupported = eventName in document;
if (!isSupported) {
var element = document.createElement("div");
element.setAttribute(eventName, "return;");
isSupported = typeof element[eventName] === "function";
}
if (!isSupported && useHasFeature && eventNameSuffix === "wheel") {
isSupported = document.implementation.hasFeature("Events.wheel", "3.0");
}
return isSupported;
}
module.exports = isEventSupported;
}
});
// node_modules/normalize-wheel/src/normalizeWheel.js
var require_normalizeWheel = __commonJS({
"node_modules/normalize-wheel/src/normalizeWheel.js"(exports, module) {
"use strict";
var UserAgent_DEPRECATED = require_UserAgent_DEPRECATED();
var isEventSupported = require_isEventSupported();
var PIXEL_STEP = 10;
var LINE_HEIGHT = 40;
var PAGE_HEIGHT = 800;
function normalizeWheel2(event) {
var sX = 0, sY = 0, pX = 0, pY = 0;
if ("detail" in event) {
sY = event.detail;
}
if ("wheelDelta" in event) {
sY = -event.wheelDelta / 120;
}
if ("wheelDeltaY" in event) {
sY = -event.wheelDeltaY / 120;
}
if ("wheelDeltaX" in event) {
sX = -event.wheelDeltaX / 120;
}
if ("axis" in event && event.axis === event.HORIZONTAL_AXIS) {
sX = sY;
sY = 0;
}
pX = sX * PIXEL_STEP;
pY = sY * PIXEL_STEP;
if ("deltaY" in event) {
pY = event.deltaY;
}
if ("deltaX" in event) {
pX = event.deltaX;
}
if ((pX || pY) && event.deltaMode) {
if (event.deltaMode == 1) {
pX *= LINE_HEIGHT;
pY *= LINE_HEIGHT;
} else {
pX *= PAGE_HEIGHT;
pY *= PAGE_HEIGHT;
}
}
if (pX && !sX) {
sX = pX < 1 ? -1 : 1;
}
if (pY && !sY) {
sY = pY < 1 ? -1 : 1;
}
return {
spinX: sX,
spinY: sY,
pixelX: pX,
pixelY: pY
};
}
normalizeWheel2.getEventType = function() {
return UserAgent_DEPRECATED.firefox() ? "DOMMouseScroll" : isEventSupported("wheel") ? "wheel" : "mousewheel";
};
module.exports = normalizeWheel2;
}
});
// node_modules/normalize-wheel/index.js
var require_normalize_wheel = __commonJS({
"node_modules/normalize-wheel/index.js"(exports, module) {
module.exports = require_normalizeWheel();
}
});
// node_modules/fast-deep-equal/index.js
var require_fast_deep_equal = __commonJS({
"node_modules/fast-deep-equal/index.js"(exports, module) {
"use strict";
module.exports = function equal(a2, b2) {
if (a2 === b2) return true;
if (a2 && b2 && typeof a2 == "object" && typeof b2 == "object") {
if (a2.constructor !== b2.constructor) return false;
var length, i2, keys;
if (Array.isArray(a2)) {
length = a2.length;
if (length != b2.length) return false;
for (i2 = length; i2-- !== 0; )
if (!equal(a2[i2], b2[i2])) return false;
return true;
}
if (a2.constructor === RegExp) return a2.source === b2.source && a2.flags === b2.flags;
if (a2.valueOf !== Object.prototype.valueOf) return a2.valueOf() === b2.valueOf();
if (a2.toString !== Object.prototype.toString) return a2.toString() === b2.toString();
keys = Object.keys(a2);
length = keys.length;
if (length !== Object.keys(b2).length) return false;
for (i2 = length; i2-- !== 0; )
if (!Object.prototype.hasOwnProperty.call(b2, keys[i2])) return false;
for (i2 = length; i2-- !== 0; ) {
var key = keys[i2];
if (!equal(a2[key], b2[key])) return false;
}
return true;
}
return a2 !== a2 && b2 !== b2;
};
}
});
// packages/block-editor/build-module/index.mjs
var index_exports = {};
__export(index_exports, {
AlignmentControl: () => AlignmentControl,
AlignmentToolbar: () => AlignmentToolbar,
Autocomplete: () => autocomplete_default,
BlockAlignmentControl: () => BlockAlignmentControl,
BlockAlignmentToolbar: () => BlockAlignmentToolbar,
BlockBindingsAttributeControl: () => BlockBindingsAttributeControl,
BlockBindingsSourceFieldsList: () => BlockBindingsSourceFieldsList,
BlockBreadcrumb: () => block_breadcrumb_default,
BlockCanvas: () => block_canvas_default,
BlockColorsStyleSelector: () => color_style_selector_default,
BlockContextProvider: () => BlockContextProvider,
BlockControls: () => block_controls_default,
BlockEdit: () => BlockEdit,
BlockEditorKeyboardShortcuts: () => keyboard_shortcuts_default,
BlockEditorProvider: () => provider_default,
BlockFormatControls: () => BlockFormatControls,
BlockIcon: () => block_icon_default,
BlockInspector: () => block_inspector_default,
BlockList: () => BlockList,
BlockMover: () => block_mover_default,
BlockNavigationDropdown: () => dropdown_default,
BlockPopover: () => block_popover_default,
BlockPreview: () => block_preview_default,
BlockSelectionClearer: () => BlockSelectionClearer,
BlockSettingsMenu: () => block_settings_menu_default,
BlockSettingsMenuControls: () => block_settings_menu_controls_default,
BlockStyles: () => block_styles_default,
BlockTitle: () => BlockTitle,
BlockToolbar: () => BlockToolbar,
BlockTools: () => BlockTools,
BlockVerticalAlignmentControl: () => BlockVerticalAlignmentControl,
BlockVerticalAlignmentToolbar: () => BlockVerticalAlignmentToolbar,
ButtonBlockAppender: () => button_block_appender_default,
ButtonBlockerAppender: () => ButtonBlockerAppender,
ColorPalette: () => color_palette_default,
ColorPaletteControl: () => ColorPaletteControl,
ContrastChecker: () => contrast_checker_default,
CopyHandler: () => CopyHandler,
DefaultBlockAppender: () => DefaultBlockAppender,
DimensionControl: () => DimensionControl,
FontSizePicker: () => font_size_picker_default,
HeadingLevelDropdown: () => HeadingLevelDropdown,
HeightControl: () => HeightControl,
InnerBlocks: () => inner_blocks_default,
Inserter: () => inserter_default,
InspectorAdvancedControls: () => InspectorAdvancedControls,
InspectorControls: () => inspector_controls_default,
JustifyContentControl: () => JustifyContentControl,
JustifyToolbar: () => JustifyToolbar,
LineHeightControl: () => line_height_control_default,
LinkControl: () => link_control_default,
MediaPlaceholder: () => media_placeholder_default,
MediaReplaceFlow: () => media_replace_flow_default,
MediaUpload: () => media_upload_default,
MediaUploadCheck: () => check_default2,
MultiSelectScrollIntoView: () => MultiSelectScrollIntoView,
NavigableToolbar: () => NavigableToolbar,
ObserveTyping: () => observe_typing_default,
PanelColorSettings: () => panel_color_settings_default,
PlainText: () => plain_text_default,
RecursionProvider: () => RecursionProvider,
RichText: () => rich_text_default,
RichTextShortcut: () => RichTextShortcut,
RichTextToolbarButton: () => RichTextToolbarButton,
SETTINGS_DEFAULTS: () => SETTINGS_DEFAULTS,
SkipToSelectedBlock: () => SkipToSelectedBlock,
ToolSelector: () => tool_selector_default,
Typewriter: () => typewriter_default,
URLInput: () => url_input_default,
URLInputButton: () => button_default,
URLPopover: () => url_popover_default,
Warning: () => warning_default,
WritingFlow: () => writing_flow_default,
__experimentalBlockAlignmentMatrixControl: () => block_alignment_matrix_control_default,
__experimentalBlockFullHeightAligmentControl: () => block_full_height_alignment_control_default,
__experimentalBlockPatternSetup: () => block_pattern_setup_default,
__experimentalBlockPatternsList: () => block_patterns_list_default,
__experimentalBlockVariationPicker: () => block_variation_picker_default,
__experimentalBlockVariationTransforms: () => block_variation_transforms_default,
__experimentalBorderRadiusControl: () => BorderRadiusControl,
__experimentalColorGradientControl: () => control_default,
__experimentalColorGradientSettingsDropdown: () => ColorGradientSettingsDropdown,
__experimentalDateFormatPicker: () => DateFormatPicker,
__experimentalDuotoneControl: () => duotone_control_default,
__experimentalFontAppearanceControl: () => FontAppearanceControl,
__experimentalFontFamilyControl: () => FontFamilyControl,
__experimentalGetBorderClassesAndStyles: () => getBorderClassesAndStyles,
__experimentalGetColorClassesAndStyles: () => getColorClassesAndStyles,
__experimentalGetDimensionsClassesAndStyles: () => getDimensionsClassesAndStyles,
__experimentalGetElementClassName: () => __experimentalGetElementClassName,
__experimentalGetGapCSSValue: () => getGapCSSValue2,
__experimentalGetGradientClass: () => __experimentalGetGradientClass,
__experimentalGetGradientObjectByGradientValue: () => __experimentalGetGradientObjectByGradientValue,
__experimentalGetShadowClassesAndStyles: () => getShadowClassesAndStyles,
__experimentalGetSpacingClassesAndStyles: () => getSpacingClassesAndStyles,
__experimentalImageEditor: () => ImageEditor,
__experimentalImageSizeControl: () => ImageSizeControl,
__experimentalImageURLInputUI: () => ImageURLInputUI,
__experimentalInspectorPopoverHeader: () => InspectorPopoverHeader,
__experimentalLetterSpacingControl: () => LetterSpacingControl,
__experimentalLibrary: () => library_default,
__experimentalLinkControl: () => DeprecatedExperimentalLinkControl,
__experimentalLinkControlSearchInput: () => __experimentalLinkControlSearchInput,
__experimentalLinkControlSearchItem: () => __experimentalLinkControlSearchItem,
__experimentalLinkControlSearchResults: () => __experimentalLinkControlSearchResults,
__experimentalListView: () => list_view_default2,
__experimentalPanelColorGradientSettings: () => panel_color_gradient_settings_default,
__experimentalPreviewOptions: () => PreviewOptions,
__experimentalPublishDateTimePicker: () => publish_date_time_picker_default,
__experimentalRecursionProvider: () => DeprecatedExperimentalRecursionProvider,
__experimentalResponsiveBlockControl: () => responsive_block_control_default,
__experimentalSpacingSizesControl: () => SpacingSizesControl,
__experimentalTextDecorationControl: () => TextDecorationControl,
__experimentalTextTransformControl: () => TextTransformControl,
__experimentalUnitControl: () => UnitControl6,
__experimentalUseBlockOverlayActive: () => useBlockOverlayActive,
__experimentalUseBlockPreview: () => useBlockPreview,
__experimentalUseBorderProps: () => useBorderProps,
__experimentalUseColorProps: () => useColorProps,
__experimentalUseCustomSides: () => useCustomSides,
__experimentalUseGradient: () => useGradient,
__experimentalUseHasRecursion: () => DeprecatedExperimentalUseHasRecursion,
__experimentalUseMultipleOriginColorsAndGradients: () => useMultipleOriginColorsAndGradients,
__experimentalUseResizeCanvas: () => useResizeCanvas,
__experimentalWritingModeControl: () => WritingModeControl,
__unstableBlockSettingsMenuFirstItem: () => block_settings_menu_first_item_default,
__unstableBlockToolbarLastItem: () => block_toolbar_last_item_default,
__unstableEditorStyles: () => editor_styles_default,
__unstableIframe: () => iframe_default,
__unstableInserterMenuExtension: () => inserter_menu_extension_default,
__unstableRichTextInputEvent: () => RichTextInputEvent,
__unstableUseBlockSelectionClearer: () => useBlockSelectionClearer,
__unstableUseClipboardHandler: () => __unstableUseClipboardHandler,
__unstableUseMouseMoveTypingReset: () => useMouseMoveTypingReset,
__unstableUseTypewriter: () => useTypewriter,
__unstableUseTypingObserver: () => useTypingObserver,
createCustomColorsHOC: () => createCustomColorsHOC,
getColorClassName: () => getColorClassName,
getColorObjectByAttributeValues: () => getColorObjectByAttributeValues,
getColorObjectByColorValue: () => getColorObjectByColorValue,
getComputedFluidTypographyValue: () => getComputedFluidTypographyValue2,
getCustomValueFromPreset: () => getCustomValueFromPreset,
getDimensionsClassesAndStyles: () => getDimensionsClassesAndStyles,
getFontSize: () => getFontSize,
getFontSizeClass: () => getFontSizeClass,
getFontSizeObjectByValue: () => getFontSizeObjectByValue,
getGradientSlugByValue: () => getGradientSlugByValue,
getGradientValueBySlug: () => getGradientValueBySlug,
getPxFromCssUnit: () => get_px_from_css_unit_default,
getSpacingPresetCssVar: () => getSpacingPresetCssVar2,
getTypographyClassesAndStyles: () => getTypographyClassesAndStyles,
isValueSpacingPreset: () => isValueSpacingPreset,
privateApis: () => privateApis14,
store: () => store,
storeConfig: () => storeConfig,
transformStyles: () => transform_styles_default,
useBlockBindingsUtils: () => useBlockBindingsUtils,
useBlockCommands: () => useBlockCommands,
useBlockDisplayInformation: () => useBlockDisplayInformation,
useBlockEditContext: () => useBlockEditContext,
useBlockEditingMode: () => useBlockEditingMode,
useBlockProps: () => useBlockProps,
useCachedTruthy: () => useCachedTruthy,
useHasRecursion: () => useHasRecursion,
useInnerBlocksProps: () => useInnerBlocksProps,
useSetting: () => useSetting,
useSettings: () => useSettings,
useStyleOverride: () => useStyleOverride,
withColorContext: () => with_color_context_default,
withColors: () => withColors,
withFontSizes: () => with_font_sizes_default
});
// node_modules/clsx/dist/clsx.mjs
function r(e2) {
var t3, f2, n2 = "";
if ("string" == typeof e2 || "number" == typeof e2) n2 += e2;
else if ("object" == typeof e2) if (Array.isArray(e2)) {
var o3 = e2.length;
for (t3 = 0; t3 < o3; t3++) e2[t3] && (f2 = r(e2[t3])) && (n2 && (n2 += " "), n2 += f2);
} else for (f2 in e2) e2[f2] && (n2 && (n2 += " "), n2 += f2);
return n2;
}
function clsx() {
for (var e2, t3, f2 = 0, n2 = "", o3 = arguments.length; f2 < o3; f2++) (e2 = arguments[f2]) && (t3 = r(e2)) && (n2 && (n2 += " "), n2 += t3);
return n2;
}
var clsx_default = clsx;
// packages/block-editor/build-module/hooks/utils.mjs
var import_blocks104 = __toESM(require_blocks(), 1);
var import_element273 = __toESM(require_element(), 1);
var import_data179 = __toESM(require_data(), 1);
var import_compose96 = __toESM(require_compose(), 1);
var import_hooks18 = __toESM(require_hooks(), 1);
// packages/block-editor/build-module/components/block-edit/context.mjs
var import_element = __toESM(require_element(), 1);
var mayDisplayControlsKey = /* @__PURE__ */ Symbol("mayDisplayControls");
var mayDisplayParentControlsKey = /* @__PURE__ */ Symbol("mayDisplayParentControls");
var mayDisplayPatternEditingControlsKey = /* @__PURE__ */ Symbol(
"mayDisplayPatternEditingControls"
);
var blockEditingModeKey = /* @__PURE__ */ Symbol("blockEditingMode");
var blockBindingsKey = /* @__PURE__ */ Symbol("blockBindings");
var isPreviewModeKey = /* @__PURE__ */ Symbol("isPreviewMode");
var isInListViewBlockSupportTreeKey = /* @__PURE__ */ Symbol(
"isInListViewBlockSupportTree"
);
var DEFAULT_BLOCK_EDIT_CONTEXT = {
name: "",
isSelected: false
};
var Context = (0, import_element.createContext)(DEFAULT_BLOCK_EDIT_CONTEXT);
Context.displayName = "BlockEditContext";
var { Provider } = Context;
function useBlockEditContext() {
return (0, import_element.useContext)(Context);
}
// node_modules/colord/index.mjs
var r2 = { grad: 0.9, turn: 360, rad: 360 / (2 * Math.PI) };
var t = function(r3) {
return "string" == typeof r3 ? r3.length > 0 : "number" == typeof r3;
};
var n = function(r3, t3, n2) {
return void 0 === t3 && (t3 = 0), void 0 === n2 && (n2 = Math.pow(10, t3)), Math.round(n2 * r3) / n2 + 0;
};
var e = function(r3, t3, n2) {
return void 0 === t3 && (t3 = 0), void 0 === n2 && (n2 = 1), r3 > n2 ? n2 : r3 > t3 ? r3 : t3;
};
var u = function(r3) {
return (r3 = isFinite(r3) ? r3 % 360 : 0) > 0 ? r3 : r3 + 360;
};
var a = function(r3) {
return { r: e(r3.r, 0, 255), g: e(r3.g, 0, 255), b: e(r3.b, 0, 255), a: e(r3.a) };
};
var o = function(r3) {
return { r: n(r3.r), g: n(r3.g), b: n(r3.b), a: n(r3.a, 3) };
};
var i = /^#([0-9a-f]{3,8})$/i;
var s = function(r3) {
var t3 = r3.toString(16);
return t3.length < 2 ? "0" + t3 : t3;
};
var h = function(r3) {
var t3 = r3.r, n2 = r3.g, e2 = r3.b, u2 = r3.a, a2 = Math.max(t3, n2, e2), o3 = a2 - Math.min(t3, n2, e2), i2 = o3 ? a2 === t3 ? (n2 - e2) / o3 : a2 === n2 ? 2 + (e2 - t3) / o3 : 4 + (t3 - n2) / o3 : 0;
return { h: 60 * (i2 < 0 ? i2 + 6 : i2), s: a2 ? o3 / a2 * 100 : 0, v: a2 / 255 * 100, a: u2 };
};
var b = function(r3) {
var t3 = r3.h, n2 = r3.s, e2 = r3.v, u2 = r3.a;
t3 = t3 / 360 * 6, n2 /= 100, e2 /= 100;
var a2 = Math.floor(t3), o3 = e2 * (1 - n2), i2 = e2 * (1 - (t3 - a2) * n2), s2 = e2 * (1 - (1 - t3 + a2) * n2), h2 = a2 % 6;
return { r: 255 * [e2, i2, o3, o3, s2, e2][h2], g: 255 * [s2, e2, e2, i2, o3, o3][h2], b: 255 * [o3, o3, s2, e2, e2, i2][h2], a: u2 };
};
var g = function(r3) {
return { h: u(r3.h), s: e(r3.s, 0, 100), l: e(r3.l, 0, 100), a: e(r3.a) };
};
var d = function(r3) {
return { h: n(r3.h), s: n(r3.s), l: n(r3.l), a: n(r3.a, 3) };
};
var f = function(r3) {
return b((n2 = (t3 = r3).s, { h: t3.h, s: (n2 *= ((e2 = t3.l) < 50 ? e2 : 100 - e2) / 100) > 0 ? 2 * n2 / (e2 + n2) * 100 : 0, v: e2 + n2, a: t3.a }));
var t3, n2, e2;
};
var c = function(r3) {
return { h: (t3 = h(r3)).h, s: (u2 = (200 - (n2 = t3.s)) * (e2 = t3.v) / 100) > 0 && u2 < 200 ? n2 * e2 / 100 / (u2 <= 100 ? u2 : 200 - u2) * 100 : 0, l: u2 / 2, a: t3.a };
var t3, n2, e2, u2;
};
var l = /^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i;
var p = /^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i;
var v = /^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i;
var m = /^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i;
var y = { string: [[function(r3) {
var t3 = i.exec(r3);
return t3 ? (r3 = t3[1]).length <= 4 ? { r: parseInt(r3[0] + r3[0], 16), g: parseInt(r3[1] + r3[1], 16), b: parseInt(r3[2] + r3[2], 16), a: 4 === r3.length ? n(parseInt(r3[3] + r3[3], 16) / 255, 2) : 1 } : 6 === r3.length || 8 === r3.length ? { r: parseInt(r3.substr(0, 2), 16), g: parseInt(r3.substr(2, 2), 16), b: parseInt(r3.substr(4, 2), 16), a: 8 === r3.length ? n(parseInt(r3.substr(6, 2), 16) / 255, 2) : 1 } : null : null;
}, "hex"], [function(r3) {
var t3 = v.exec(r3) || m.exec(r3);
return t3 ? t3[2] !== t3[4] || t3[4] !== t3[6] ? null : a({ r: Number(t3[1]) / (t3[2] ? 100 / 255 : 1), g: Number(t3[3]) / (t3[4] ? 100 / 255 : 1), b: Number(t3[5]) / (t3[6] ? 100 / 255 : 1), a: void 0 === t3[7] ? 1 : Number(t3[7]) / (t3[8] ? 100 : 1) }) : null;
}, "rgb"], [function(t3) {
var n2 = l.exec(t3) || p.exec(t3);
if (!n2) return null;
var e2, u2, a2 = g({ h: (e2 = n2[1], u2 = n2[2], void 0 === u2 && (u2 = "deg"), Number(e2) * (r2[u2] || 1)), s: Number(n2[3]), l: Number(n2[4]), a: void 0 === n2[5] ? 1 : Number(n2[5]) / (n2[6] ? 100 : 1) });
return f(a2);
}, "hsl"]], object: [[function(r3) {
var n2 = r3.r, e2 = r3.g, u2 = r3.b, o3 = r3.a, i2 = void 0 === o3 ? 1 : o3;
return t(n2) && t(e2) && t(u2) ? a({ r: Number(n2), g: Number(e2), b: Number(u2), a: Number(i2) }) : null;
}, "rgb"], [function(r3) {
var n2 = r3.h, e2 = r3.s, u2 = r3.l, a2 = r3.a, o3 = void 0 === a2 ? 1 : a2;
if (!t(n2) || !t(e2) || !t(u2)) return null;
var i2 = g({ h: Number(n2), s: Number(e2), l: Number(u2), a: Number(o3) });
return f(i2);
}, "hsl"], [function(r3) {
var n2 = r3.h, a2 = r3.s, o3 = r3.v, i2 = r3.a, s2 = void 0 === i2 ? 1 : i2;
if (!t(n2) || !t(a2) || !t(o3)) return null;
var h2 = (function(r4) {
return { h: u(r4.h), s: e(r4.s, 0, 100), v: e(r4.v, 0, 100), a: e(r4.a) };
})({ h: Number(n2), s: Number(a2), v: Number(o3), a: Number(s2) });
return b(h2);
}, "hsv"]] };
var N = function(r3, t3) {
for (var n2 = 0; n2 < t3.length; n2++) {
var e2 = t3[n2][0](r3);
if (e2) return [e2, t3[n2][1]];
}
return [null, void 0];
};
var x = function(r3) {
return "string" == typeof r3 ? N(r3.trim(), y.string) : "object" == typeof r3 && null !== r3 ? N(r3, y.object) : [null, void 0];
};
var M = function(r3, t3) {
var n2 = c(r3);
return { h: n2.h, s: e(n2.s + 100 * t3, 0, 100), l: n2.l, a: n2.a };
};
var H = function(r3) {
return (299 * r3.r + 587 * r3.g + 114 * r3.b) / 1e3 / 255;
};
var $ = function(r3, t3) {
var n2 = c(r3);
return { h: n2.h, s: n2.s, l: e(n2.l + 100 * t3, 0, 100), a: n2.a };
};
var j = (function() {
function r3(r4) {
this.parsed = x(r4)[0], this.rgba = this.parsed || { r: 0, g: 0, b: 0, a: 1 };
}
return r3.prototype.isValid = function() {
return null !== this.parsed;
}, r3.prototype.brightness = function() {
return n(H(this.rgba), 2);
}, r3.prototype.isDark = function() {
return H(this.rgba) < 0.5;
}, r3.prototype.isLight = function() {
return H(this.rgba) >= 0.5;
}, r3.prototype.toHex = function() {
return r4 = o(this.rgba), t3 = r4.r, e2 = r4.g, u2 = r4.b, i2 = (a2 = r4.a) < 1 ? s(n(255 * a2)) : "", "#" + s(t3) + s(e2) + s(u2) + i2;
var r4, t3, e2, u2, a2, i2;
}, r3.prototype.toRgb = function() {
return o(this.rgba);
}, r3.prototype.toRgbString = function() {
return r4 = o(this.rgba), t3 = r4.r, n2 = r4.g, e2 = r4.b, (u2 = r4.a) < 1 ? "rgba(" + t3 + ", " + n2 + ", " + e2 + ", " + u2 + ")" : "rgb(" + t3 + ", " + n2 + ", " + e2 + ")";
var r4, t3, n2, e2, u2;
}, r3.prototype.toHsl = function() {
return d(c(this.rgba));
}, r3.prototype.toHslString = function() {
return r4 = d(c(this.rgba)), t3 = r4.h, n2 = r4.s, e2 = r4.l, (u2 = r4.a) < 1 ? "hsla(" + t3 + ", " + n2 + "%, " + e2 + "%, " + u2 + ")" : "hsl(" + t3 + ", " + n2 + "%, " + e2 + "%)";
var r4, t3, n2, e2, u2;
}, r3.prototype.toHsv = function() {
return r4 = h(this.rgba), { h: n(r4.h), s: n(r4.s), v: n(r4.v), a: n(r4.a, 3) };
var r4;
}, r3.prototype.invert = function() {
return w({ r: 255 - (r4 = this.rgba).r, g: 255 - r4.g, b: 255 - r4.b, a: r4.a });
var r4;
}, r3.prototype.saturate = function(r4) {
return void 0 === r4 && (r4 = 0.1), w(M(this.rgba, r4));
}, r3.prototype.desaturate = function(r4) {
return void 0 === r4 && (r4 = 0.1), w(M(this.rgba, -r4));
}, r3.prototype.grayscale = function() {
return w(M(this.rgba, -1));
}, r3.prototype.lighten = function(r4) {
return void 0 === r4 && (r4 = 0.1), w($(this.rgba, r4));
}, r3.prototype.darken = function(r4) {
return void 0 === r4 && (r4 = 0.1), w($(this.rgba, -r4));
}, r3.prototype.rotate = function(r4) {
return void 0 === r4 && (r4 = 15), this.hue(this.hue() + r4);
}, r3.prototype.alpha = function(r4) {
return "number" == typeof r4 ? w({ r: (t3 = this.rgba).r, g: t3.g, b: t3.b, a: r4 }) : n(this.rgba.a, 3);
var t3;
}, r3.prototype.hue = function(r4) {
var t3 = c(this.rgba);
return "number" == typeof r4 ? w({ h: r4, s: t3.s, l: t3.l, a: t3.a }) : n(t3.h);
}, r3.prototype.isEqual = function(r4) {
return this.toHex() === w(r4).toHex();
}, r3;
})();
var w = function(r3) {
return r3 instanceof j ? r3 : new j(r3);
};
var S = [];
var k = function(r3) {
r3.forEach(function(r4) {
S.indexOf(r4) < 0 && (r4(j, y), S.push(r4));
});
};
// node_modules/colord/plugins/names.mjs
function names_default(e2, f2) {
var a2 = { 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" }, r3 = {};
for (var d2 in a2) r3[a2[d2]] = d2;
var l2 = {};
e2.prototype.toName = function(f3) {
if (!(this.rgba.a || this.rgba.r || this.rgba.g || this.rgba.b)) return "transparent";
var d3, i2, n2 = r3[this.toHex()];
if (n2) return n2;
if (null == f3 ? void 0 : f3.closest) {
var o3 = this.toRgb(), t3 = 1 / 0, b2 = "black";
if (!l2.length) for (var c6 in a2) l2[c6] = new e2(a2[c6]).toRgb();
for (var g2 in a2) {
var u2 = (d3 = o3, i2 = l2[g2], Math.pow(d3.r - i2.r, 2) + Math.pow(d3.g - i2.g, 2) + Math.pow(d3.b - i2.b, 2));
u2 < t3 && (t3 = u2, b2 = g2);
}
return b2;
}
};
f2.string.push([function(f3) {
var r4 = f3.toLowerCase(), d3 = "transparent" === r4 ? "#0000" : a2[r4];
return d3 ? new e2(d3).toRgb() : null;
}, "name"]);
}
// node_modules/colord/plugins/a11y.mjs
var o2 = function(o3) {
var t3 = o3 / 255;
return t3 < 0.04045 ? t3 / 12.92 : Math.pow((t3 + 0.055) / 1.055, 2.4);
};
var t2 = function(t3) {
return 0.2126 * o2(t3.r) + 0.7152 * o2(t3.g) + 0.0722 * o2(t3.b);
};
function a11y_default(o3) {
o3.prototype.luminance = function() {
return o4 = t2(this.rgba), void 0 === (r3 = 2) && (r3 = 0), void 0 === n2 && (n2 = Math.pow(10, r3)), Math.round(n2 * o4) / n2 + 0;
var o4, r3, n2;
}, o3.prototype.contrast = function(r3) {
void 0 === r3 && (r3 = "#FFF");
var n2, a2, i2, e2, v2, u2, d2, c6 = r3 instanceof o3 ? r3 : new o3(r3);
return e2 = this.rgba, v2 = c6.toRgb(), u2 = t2(e2), d2 = t2(v2), n2 = u2 > d2 ? (u2 + 0.05) / (d2 + 0.05) : (d2 + 0.05) / (u2 + 0.05), void 0 === (a2 = 2) && (a2 = 0), void 0 === i2 && (i2 = Math.pow(10, a2)), Math.floor(i2 * n2) / i2 + 0;
}, o3.prototype.isReadable = function(o4, t3) {
return void 0 === o4 && (o4 = "#FFF"), void 0 === t3 && (t3 = {}), this.contrast(o4) >= (e2 = void 0 === (i2 = (r3 = t3).size) ? "normal" : i2, "AAA" === (a2 = void 0 === (n2 = r3.level) ? "AA" : n2) && "normal" === e2 ? 7 : "AA" === a2 && "large" === e2 ? 3 : 4.5);
var r3, n2, a2, i2, e2;
};
}
// packages/block-editor/build-module/components/colors/utils.mjs
var import_components = __toESM(require_components(), 1);
// packages/block-editor/build-module/lock-unlock.mjs
var import_private_apis = __toESM(require_private_apis(), 1);
var { lock, unlock } = (0, import_private_apis.__dangerousOptInToUnstableAPIsOnlyForCoreModules)(
"I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.",
"@wordpress/block-editor"
);
// packages/block-editor/build-module/components/colors/utils.mjs
k([names_default, a11y_default]);
var { kebabCase } = unlock(import_components.privateApis);
var getColorObjectByAttributeValues = (colors2, definedColor, customColor) => {
if (definedColor) {
const colorObj = colors2?.find(
(color) => color.slug === definedColor
);
if (colorObj) {
return colorObj;
}
}
return {
color: customColor
};
};
var getColorObjectByColorValue = (colors2, colorValue) => {
return colors2?.find((color) => color.color === colorValue);
};
function getColorClassName(colorContextName, colorSlug) {
if (!colorContextName || !colorSlug) {
return void 0;
}
return `has-${kebabCase(colorSlug)}-${colorContextName}`;
}
function getMostReadableColor(colors2, colorValue) {
const colordColor = w(colorValue);
const getColorContrast = ({ color }) => colordColor.contrast(color);
const maxContrast = Math.max(...colors2.map(getColorContrast));
return colors2.find((color) => getColorContrast(color) === maxContrast).color;
}
// packages/block-editor/build-module/components/colors/with-colors.mjs
var import_element7 = __toESM(require_element(), 1);
var import_compose2 = __toESM(require_compose(), 1);
var import_components5 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/use-settings/index.mjs
var import_data8 = __toESM(require_data(), 1);
var import_deprecated5 = __toESM(require_deprecated(), 1);
// packages/block-editor/build-module/components/block-edit/index.mjs
var import_element6 = __toESM(require_element(), 1);
var import_blocks10 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/components/block-edit/edit.mjs
var import_blocks = __toESM(require_blocks(), 1);
var import_components2 = __toESM(require_components(), 1);
var import_data = __toESM(require_data(), 1);
var import_element4 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/block-context/index.mjs
var import_element2 = __toESM(require_element(), 1);
var import_jsx_runtime = __toESM(require_jsx_runtime(), 1);
var Context2 = (0, import_element2.createContext)({});
Context2.displayName = "BlockContext";
function BlockContextProvider({ value, children }) {
const context = (0, import_element2.useContext)(Context2);
const nextValue = (0, import_element2.useMemo)(
() => ({ ...context, ...value }),
[context, value]
);
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Context2.Provider, { value: nextValue, children });
}
var block_context_default = Context2;
// packages/block-editor/build-module/components/link-control/is-url-like.mjs
var import_url = __toESM(require_url(), 1);
function isHashLink(val) {
return val?.startsWith("#") && (0, import_url.isValidFragment)(val);
}
function isRelativePath(val) {
return val?.startsWith("/") || val?.startsWith("./") || val?.startsWith("../");
}
function isURLLike(val) {
const hasSpaces = val.includes(" ");
if (hasSpaces) {
return false;
}
const protocol = (0, import_url.getProtocol)(val);
const protocolIsValid = (0, import_url.isValidProtocol)(protocol);
const mayBeTLD = hasPossibleTLD(val);
const isWWW = val?.startsWith("www.");
return protocolIsValid || isWWW || isHashLink(val) || mayBeTLD || isRelativePath(val);
}
function hasPossibleTLD(url, maxLength = 6) {
const cleanedURL = url.split(/[?#]/)[0];
const regex = new RegExp(
`(?<=\\S)\\.(?:[a-zA-Z_]{2,${maxLength}})(?:\\/|$)`
);
return regex.test(cleanedURL);
}
// packages/block-editor/build-module/utils/block-bindings.mjs
var DEFAULT_ATTRIBUTE = "__default";
var PATTERN_OVERRIDES_SOURCE = "core/pattern-overrides";
var EMPTY_CONTEXT = {};
function getBlockBindingsContext(blockContext, blockTypeUsesContext, sources) {
let context;
if (blockTypeUsesContext) {
for (const [key, value] of Object.entries(blockContext)) {
if (blockTypeUsesContext.includes(key)) {
if (context === void 0) {
context = {};
}
context[key] = value;
}
}
}
if (sources) {
for (const source of sources) {
source?.usesContext?.forEach((key) => {
if (key in blockContext) {
if (context === void 0) {
context = {};
}
context[key] = blockContext[key];
}
});
}
}
return context ?? EMPTY_CONTEXT;
}
function hasPatternOverridesDefaultBinding(bindings) {
return bindings?.[DEFAULT_ATTRIBUTE]?.source === PATTERN_OVERRIDES_SOURCE;
}
function replacePatternOverridesDefaultBinding(bindings, supportedAttributes) {
if (!hasPatternOverridesDefaultBinding(bindings)) {
return bindings;
}
const bindingsWithDefaults = {};
for (const attributeName of supportedAttributes) {
const bindingSource = bindings[attributeName] ? bindings[attributeName] : { source: PATTERN_OVERRIDES_SOURCE };
bindingsWithDefaults[attributeName] = bindingSource;
}
return bindingsWithDefaults;
}
// packages/block-editor/build-module/components/block-list/private-block-context.mjs
var import_element3 = __toESM(require_element(), 1);
var PrivateBlockContext = (0, import_element3.createContext)({});
PrivateBlockContext.displayName = "PrivateBlockContext";
// packages/block-editor/build-module/components/block-edit/edit.mjs
var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1);
var Edit = (props) => {
const { name } = props;
const blockType = (0, import_blocks.getBlockType)(name);
if (!blockType) {
return null;
}
const Component6 = blockType.edit || blockType.save;
return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Component6, { ...props });
};
var EditWithFilters = (0, import_components2.withFilters)("editor.BlockEdit")(Edit);
var EditWithGeneratedProps = (props) => {
const { name, clientId, attributes, setAttributes } = props;
const registry = (0, import_data.useRegistry)();
const blockType = (0, import_blocks.getBlockType)(name);
const blockContext = (0, import_element4.useContext)(block_context_default);
const registeredSources = (0, import_data.useSelect)(
(select3) => unlock(select3(import_blocks.store)).getAllBlockBindingsSources(),
[]
);
const { bindableAttributes } = (0, import_element4.useContext)(PrivateBlockContext);
const { blockBindings, context, hasPatternOverrides } = (0, import_element4.useMemo)(() => {
return {
blockBindings: replacePatternOverridesDefaultBinding(
attributes?.metadata?.bindings,
bindableAttributes
),
// Assign context values using the block type's declared context
// needs, plus the context requested by the block's bindings
// sources.
context: getBlockBindingsContext(
blockContext,
blockType?.usesContext,
attributes?.metadata?.bindings ? Object.values(attributes.metadata.bindings).map(
(binding) => registeredSources[binding?.source]
) : void 0
),
hasPatternOverrides: hasPatternOverridesDefaultBinding(
attributes?.metadata?.bindings
)
};
}, [
blockType?.usesContext,
blockContext,
attributes?.metadata?.bindings,
bindableAttributes,
registeredSources
]);
const computedAttributes = (0, import_data.useSelect)(
(select3) => {
if (!blockBindings) {
return attributes;
}
const attributesFromSources = {};
const blockBindingsBySource = /* @__PURE__ */ new Map();
for (const [attributeName, binding] of Object.entries(
blockBindings
)) {
const { source: sourceName, args: sourceArgs } = binding;
const source = registeredSources[sourceName];
if (!source || !bindableAttributes?.includes(attributeName)) {
continue;
}
blockBindingsBySource.set(source, {
...blockBindingsBySource.get(source),
[attributeName]: {
args: sourceArgs
}
});
}
if (blockBindingsBySource.size) {
for (const [source, bindings] of blockBindingsBySource) {
let values = {};
if (!source.getValues) {
Object.keys(bindings).forEach((attr2) => {
values[attr2] = source.label;
});
} else {
values = source.getValues({
select: select3,
context,
clientId,
bindings
});
}
for (const [attributeName, value] of Object.entries(
values
)) {
if (attributeName === "url" && (!value || !isURLLike(value))) {
attributesFromSources[attributeName] = null;
} else {
attributesFromSources[attributeName] = value;
}
}
}
}
return {
...attributes,
...attributesFromSources
};
},
[
attributes,
bindableAttributes,
blockBindings,
clientId,
context,
registeredSources
]
);
const setBoundAttributes = (0, import_element4.useCallback)(
(nextAttributes) => {
if (!blockBindings) {
setAttributes(nextAttributes);
return;
}
registry.batch(() => {
const keptAttributes = { ...nextAttributes };
const blockBindingsBySource = /* @__PURE__ */ new Map();
for (const [attributeName, newValue] of Object.entries(
keptAttributes
)) {
if (!blockBindings[attributeName] || !bindableAttributes?.includes(attributeName)) {
continue;
}
const binding = blockBindings[attributeName];
const source = registeredSources[binding?.source];
if (!source?.setValues) {
continue;
}
blockBindingsBySource.set(source, {
...blockBindingsBySource.get(source),
[attributeName]: {
args: binding.args,
newValue
}
});
delete keptAttributes[attributeName];
}
if (blockBindingsBySource.size) {
for (const [
source,
bindings
] of blockBindingsBySource) {
source.setValues({
select: registry.select,
dispatch: registry.dispatch,
context,
clientId,
bindings
});
}
}
const hasParentPattern = !!context["pattern/overrides"];
if (
// Don't update non-connected attributes if the block is using pattern overrides
// and the editing is happening while overriding the pattern (not editing the original).
!(hasPatternOverrides && hasParentPattern) && Object.keys(keptAttributes).length
) {
if (hasPatternOverrides) {
delete keptAttributes.href;
}
setAttributes(keptAttributes);
}
});
},
[
bindableAttributes,
blockBindings,
clientId,
context,
hasPatternOverrides,
setAttributes,
registeredSources,
registry
]
);
if (!blockType) {
return null;
}
if (blockType.apiVersion > 1) {
return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
EditWithFilters,
{
...props,
attributes: computedAttributes,
context,
setAttributes: setBoundAttributes
}
);
}
const generatedClassName = (0, import_blocks.hasBlockSupport)(blockType, "className", true) ? (0, import_blocks.getBlockDefaultClassName)(name) : null;
const className = clsx_default(
generatedClassName,
attributes?.className,
props.className
);
return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
EditWithFilters,
{
...props,
attributes: computedAttributes,
className,
context,
setAttributes: setBoundAttributes
}
);
};
var edit_default = EditWithGeneratedProps;
// packages/block-editor/build-module/components/block-edit/multiple-usage-warning.mjs
var import_blocks9 = __toESM(require_blocks(), 1);
var import_components4 = __toESM(require_components(), 1);
var import_data7 = __toESM(require_data(), 1);
var import_i18n7 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/store/index.mjs
var import_data6 = __toESM(require_data(), 1);
// packages/block-editor/build-module/store/reducer.mjs
var import_es6 = __toESM(require_es6(), 1);
var import_compose = __toESM(require_compose(), 1);
var import_data2 = __toESM(require_data(), 1);
var import_deprecated = __toESM(require_deprecated(), 1);
var import_blocks2 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/store/defaults.mjs
var import_i18n = __toESM(require_i18n(), 1);
var PREFERENCES_DEFAULTS = {
insertUsage: {}
};
var SETTINGS_DEFAULTS = {
alignWide: false,
supportsLayout: true,
// colors setting is not used anymore now defaults are passed from theme.json on the server and core has its own defaults.
// The setting is only kept for backward compatibility purposes.
colors: [
{
name: (0, import_i18n.__)("Black"),
slug: "black",
color: "#000000"
},
{
name: (0, import_i18n.__)("Cyan bluish gray"),
slug: "cyan-bluish-gray",
color: "#abb8c3"
},
{
name: (0, import_i18n.__)("White"),
slug: "white",
color: "#ffffff"
},
{
name: (0, import_i18n.__)("Pale pink"),
slug: "pale-pink",
color: "#f78da7"
},
{ name: (0, import_i18n.__)("Vivid red"), slug: "vivid-red", color: "#cf2e2e" },
{
name: (0, import_i18n.__)("Luminous vivid orange"),
slug: "luminous-vivid-orange",
color: "#ff6900"
},
{
name: (0, import_i18n.__)("Luminous vivid amber"),
slug: "luminous-vivid-amber",
color: "#fcb900"
},
{
name: (0, import_i18n.__)("Light green cyan"),
slug: "light-green-cyan",
color: "#7bdcb5"
},
{
name: (0, import_i18n.__)("Vivid green cyan"),
slug: "vivid-green-cyan",
color: "#00d084"
},
{
name: (0, import_i18n.__)("Pale cyan blue"),
slug: "pale-cyan-blue",
color: "#8ed1fc"
},
{
name: (0, import_i18n.__)("Vivid cyan blue"),
slug: "vivid-cyan-blue",
color: "#0693e3"
},
{
name: (0, import_i18n.__)("Vivid purple"),
slug: "vivid-purple",
color: "#9b51e0"
}
],
// fontSizes setting is not used anymore now defaults are passed from theme.json on the server and core has its own defaults.
// The setting is only kept for backward compatibility purposes.
fontSizes: [
{
name: (0, import_i18n._x)("Small", "font size name"),
size: 13,
slug: "small"
},
{
name: (0, import_i18n._x)("Normal", "font size name"),
size: 16,
slug: "normal"
},
{
name: (0, import_i18n._x)("Medium", "font size name"),
size: 20,
slug: "medium"
},
{
name: (0, import_i18n._x)("Large", "font size name"),
size: 36,
slug: "large"
},
{
name: (0, import_i18n._x)("Huge", "font size name"),
size: 42,
slug: "huge"
}
],
// Image default size slug.
imageDefaultSize: "large",
imageSizes: [
{ slug: "thumbnail", name: (0, import_i18n.__)("Thumbnail") },
{ slug: "medium", name: (0, import_i18n.__)("Medium") },
{ slug: "large", name: (0, import_i18n.__)("Large") },
{ slug: "full", name: (0, import_i18n.__)("Full Size") }
],
// Allow plugin to disable Image Editor if need be.
imageEditing: true,
// This is current max width of the block inner area
// It's used to constraint image resizing and this value could be overridden later by themes
maxWidth: 580,
// Allowed block types for the editor, defaulting to true (all supported).
allowedBlockTypes: true,
// Maximum upload size in bytes allowed for the site.
maxUploadFileSize: 0,
// List of allowed mime types and file extensions.
allowedMimeTypes: null,
// Allows to disable block locking interface.
canLockBlocks: true,
// Whether the user can edit custom CSS (requires edit_css capability).
// Defaults to false for safety - PHP passes true when user has capability.
canEditCSS: false,
// Allows to disable Openverse media category in the inserter.
enableOpenverseMediaCategory: true,
clearBlockSelection: true,
__experimentalCanUserUseUnfilteredHTML: false,
__experimentalBlockDirectory: false,
__mobileEnablePageTemplates: false,
__experimentalBlockPatterns: [],
__experimentalBlockPatternCategories: [],
isPreviewMode: false,
// These settings will be completely revamped in the future.
// The goal is to evolve this into an API which will instruct
// the block inspector to animate transitions between what it
// displays based on the relationship between the selected block
// and its parent, and only enable it if the parent is controlling
// its children blocks.
blockInspectorAnimation: {
animationParent: "core/navigation",
"core/navigation": { enterDirection: "leftToRight" },
"core/navigation-submenu": { enterDirection: "rightToLeft" },
"core/navigation-link": { enterDirection: "rightToLeft" },
"core/search": { enterDirection: "rightToLeft" },
"core/social-links": { enterDirection: "rightToLeft" },
"core/page-list": { enterDirection: "rightToLeft" },
"core/spacer": { enterDirection: "rightToLeft" },
"core/home-link": { enterDirection: "rightToLeft" },
"core/site-title": { enterDirection: "rightToLeft" },
"core/site-logo": { enterDirection: "rightToLeft" }
},
generateAnchors: false,
// gradients setting is not used anymore now defaults are passed from theme.json on the server and core has its own defaults.
// The setting is only kept for backward compatibility purposes.
gradients: [
{
name: (0, import_i18n.__)("Vivid cyan blue to vivid purple"),
gradient: "linear-gradient(135deg,rgba(6,147,227,1) 0%,rgb(155,81,224) 100%)",
slug: "vivid-cyan-blue-to-vivid-purple"
},
{
name: (0, import_i18n.__)("Light green cyan to vivid green cyan"),
gradient: "linear-gradient(135deg,rgb(122,220,180) 0%,rgb(0,208,130) 100%)",
slug: "light-green-cyan-to-vivid-green-cyan"
},
{
name: (0, import_i18n.__)("Luminous vivid amber to luminous vivid orange"),
gradient: "linear-gradient(135deg,rgba(252,185,0,1) 0%,rgba(255,105,0,1) 100%)",
slug: "luminous-vivid-amber-to-luminous-vivid-orange"
},
{
name: (0, import_i18n.__)("Luminous vivid orange to vivid red"),
gradient: "linear-gradient(135deg,rgba(255,105,0,1) 0%,rgb(207,46,46) 100%)",
slug: "luminous-vivid-orange-to-vivid-red"
},
{
name: (0, import_i18n.__)("Very light gray to cyan bluish gray"),
gradient: "linear-gradient(135deg,rgb(238,238,238) 0%,rgb(169,184,195) 100%)",
slug: "very-light-gray-to-cyan-bluish-gray"
},
{
name: (0, import_i18n.__)("Cool to warm spectrum"),
gradient: "linear-gradient(135deg,rgb(74,234,220) 0%,rgb(151,120,209) 20%,rgb(207,42,186) 40%,rgb(238,44,130) 60%,rgb(251,105,98) 80%,rgb(254,248,76) 100%)",
slug: "cool-to-warm-spectrum"
},
{
name: (0, import_i18n.__)("Blush light purple"),
gradient: "linear-gradient(135deg,rgb(255,206,236) 0%,rgb(152,150,240) 100%)",
slug: "blush-light-purple"
},
{
name: (0, import_i18n.__)("Blush bordeaux"),
gradient: "linear-gradient(135deg,rgb(254,205,165) 0%,rgb(254,45,45) 50%,rgb(107,0,62) 100%)",
slug: "blush-bordeaux"
},
{
name: (0, import_i18n.__)("Luminous dusk"),
gradient: "linear-gradient(135deg,rgb(255,203,112) 0%,rgb(199,81,192) 50%,rgb(65,88,208) 100%)",
slug: "luminous-dusk"
},
{
name: (0, import_i18n.__)("Pale ocean"),
gradient: "linear-gradient(135deg,rgb(255,245,203) 0%,rgb(182,227,212) 50%,rgb(51,167,181) 100%)",
slug: "pale-ocean"
},
{
name: (0, import_i18n.__)("Electric grass"),
gradient: "linear-gradient(135deg,rgb(202,248,128) 0%,rgb(113,206,126) 100%)",
slug: "electric-grass"
},
{
name: (0, import_i18n.__)("Midnight"),
gradient: "linear-gradient(135deg,rgb(2,3,129) 0%,rgb(40,116,252) 100%)",
slug: "midnight"
}
],
__unstableResolvedAssets: { styles: [], scripts: [] }
};
// packages/block-editor/build-module/store/array.mjs
function insertAt(array, elements, index2) {
return [
...array.slice(0, index2),
...Array.isArray(elements) ? elements : [elements],
...array.slice(index2)
];
}
function moveTo(array, from, to2, count = 1) {
const withoutMovedElements = [...array];
withoutMovedElements.splice(from, count);
return insertAt(
withoutMovedElements,
array.slice(from, from + count),
to2
);
}
// packages/block-editor/build-module/store/private-keys.mjs
var globalStylesDataKey = /* @__PURE__ */ Symbol("globalStylesDataKey");
var globalStylesLinksDataKey = /* @__PURE__ */ Symbol("globalStylesLinks");
var selectBlockPatternsKey = /* @__PURE__ */ Symbol("selectBlockPatternsKey");
var reusableBlocksSelectKey = /* @__PURE__ */ Symbol("reusableBlocksSelect");
var userPatternCategoriesSelectKey = /* @__PURE__ */ Symbol(
"userPatternCategoriesSelect"
);
var sectionRootClientIdKey = /* @__PURE__ */ Symbol("sectionRootClientIdKey");
var mediaEditKey = /* @__PURE__ */ Symbol("mediaEditKey");
var getMediaSelectKey = /* @__PURE__ */ Symbol("getMediaSelect");
var isIsolatedEditorKey = /* @__PURE__ */ Symbol("isIsolatedEditor");
var deviceTypeKey = /* @__PURE__ */ Symbol("deviceTypeKey");
var isNavigationOverlayContextKey = /* @__PURE__ */ Symbol(
"isNavigationOverlayContext"
);
var isNavigationPostEditorKey = /* @__PURE__ */ Symbol("isNavigationPostEditor");
var mediaUploadOnSuccessKey = /* @__PURE__ */ Symbol("mediaUploadOnSuccess");
var mediaSideloadFromUrlKey = /* @__PURE__ */ Symbol("mediaSideloadFromUrl");
var openMediaEditorModalKey = /* @__PURE__ */ Symbol("openMediaEditorModal");
// packages/block-editor/build-module/store/reducer.mjs
var { isContentBlock } = unlock(import_blocks2.privateApis);
var identity = (x2) => x2;
function mapBlockOrder(blocks2, rootClientId = "") {
const result = /* @__PURE__ */ new Map();
const current = [];
result.set(rootClientId, current);
blocks2.forEach((block) => {
const { clientId, innerBlocks } = block;
current.push(clientId);
mapBlockOrder(innerBlocks, clientId).forEach(
(order, subClientId) => {
result.set(subClientId, order);
}
);
});
return result;
}
function mapBlockParents(blocks2, rootClientId = "") {
const result = [];
const stack = [[rootClientId, blocks2]];
while (stack.length) {
const [parent, currentBlocks] = stack.shift();
currentBlocks.forEach(({ innerBlocks, ...block }) => {
result.push([block.clientId, parent]);
if (innerBlocks?.length) {
stack.push([block.clientId, innerBlocks]);
}
});
}
return result;
}
function flattenBlocks(blocks2, transform = identity) {
const result = [];
const stack = [...blocks2];
while (stack.length) {
const { innerBlocks, ...block } = stack.shift();
stack.push(...innerBlocks);
result.push([block.clientId, transform(block)]);
}
return result;
}
function getFlattenedClientIds(blocks2) {
const result = {};
const stack = [...blocks2];
while (stack.length) {
const { innerBlocks, ...block } = stack.shift();
stack.push(...innerBlocks);
result[block.clientId] = true;
}
return result;
}
function getFlattenedBlocksWithoutAttributes(blocks2) {
return flattenBlocks(blocks2, (block) => {
const { attributes, ...restBlock } = block;
return restBlock;
});
}
function getFlattenedBlockAttributes(blocks2) {
return flattenBlocks(blocks2, (block) => block.attributes);
}
function hasSameKeys(a2, b2) {
return (0, import_es6.default)(Object.keys(a2), Object.keys(b2));
}
function isUpdatingSameBlockAttribute(action, lastAction) {
return action.type === "UPDATE_BLOCK_ATTRIBUTES" && lastAction !== void 0 && lastAction.type === "UPDATE_BLOCK_ATTRIBUTES" && (0, import_es6.default)(action.clientIds, lastAction.clientIds) && hasSameKeys(action.attributes, lastAction.attributes);
}
function updateBlockTreeForBlocks(state, blocks2) {
const treeToUpdate = state.tree;
const stack = [...blocks2];
const flattenedBlocks = [...blocks2];
while (stack.length) {
const block = stack.shift();
stack.push(...block.innerBlocks);
flattenedBlocks.push(...block.innerBlocks);
}
for (const block of flattenedBlocks) {
treeToUpdate.set(block.clientId, {});
}
for (const block of flattenedBlocks) {
treeToUpdate.set(
block.clientId,
Object.assign(treeToUpdate.get(block.clientId), {
...state.byClientId.get(block.clientId),
attributes: state.attributes.get(block.clientId),
innerBlocks: block.innerBlocks.map(
(subBlock) => treeToUpdate.get(subBlock.clientId)
)
})
);
}
}
function updateParentInnerBlocksInTree(state, updatedClientIds, updateChildrenOfUpdatedClientIds = false) {
const treeToUpdate = state.tree;
const uncontrolledParents = /* @__PURE__ */ new Set([]);
const controlledParents = /* @__PURE__ */ new Set();
for (const clientId of updatedClientIds) {
let current = updateChildrenOfUpdatedClientIds ? clientId : state.parents.get(clientId);
do {
if (state.controlledInnerBlocks.has(current)) {
controlledParents.add(current);
break;
} else {
uncontrolledParents.add(current);
current = state.parents.get(current);
}
} while (current !== void 0);
}
for (const clientId of uncontrolledParents) {
treeToUpdate.set(clientId, { ...treeToUpdate.get(clientId) });
}
for (const clientId of uncontrolledParents) {
treeToUpdate.get(clientId).innerBlocks = (state.order.get(clientId) || []).map((subClientId) => treeToUpdate.get(subClientId));
}
for (const clientId of controlledParents) {
treeToUpdate.set("controlled||" + clientId, {
innerBlocks: (state.order.get(clientId) || []).map(
(subClientId) => treeToUpdate.get(subClientId)
)
});
}
}
var withBlockTree = (reducer3) => (state = {}, action) => {
const newState = reducer3(state, action);
if (newState === state) {
return state;
}
newState.tree = state.tree ? state.tree : /* @__PURE__ */ new Map();
switch (action.type) {
case "RECEIVE_BLOCKS":
case "INSERT_BLOCKS": {
newState.tree = new Map(newState.tree);
updateBlockTreeForBlocks(newState, action.blocks);
updateParentInnerBlocksInTree(
newState,
action.rootClientId ? [action.rootClientId] : [""],
true
);
break;
}
case "UPDATE_BLOCK":
newState.tree = new Map(newState.tree);
newState.tree.set(action.clientId, {
...newState.tree.get(action.clientId),
...newState.byClientId.get(action.clientId),
attributes: newState.attributes.get(action.clientId)
});
updateParentInnerBlocksInTree(
newState,
[action.clientId],
false
);
break;
case "UPDATE_BLOCK_ATTRIBUTES": {
newState.tree = new Map(newState.tree);
action.clientIds.forEach((clientId) => {
newState.tree.set(clientId, {
...newState.tree.get(clientId),
attributes: newState.attributes.get(clientId)
});
});
updateParentInnerBlocksInTree(
newState,
action.clientIds,
false
);
break;
}
case "REPLACE_BLOCKS_AUGMENTED_WITH_CHILDREN": {
const inserterClientIds = getFlattenedClientIds(
action.blocks
);
newState.tree = new Map(newState.tree);
action.replacedClientIds.forEach((clientId) => {
newState.tree.delete(clientId);
if (!inserterClientIds[clientId]) {
newState.tree.delete("controlled||" + clientId);
}
});
updateBlockTreeForBlocks(newState, action.blocks);
updateParentInnerBlocksInTree(
newState,
action.blocks.map((b2) => b2.clientId),
false
);
const parentsOfRemovedBlocks2 = [];
for (const clientId of action.clientIds) {
const parentId = state.parents.get(clientId);
if (parentId !== void 0 && (parentId === "" || newState.byClientId.get(parentId))) {
parentsOfRemovedBlocks2.push(parentId);
}
}
updateParentInnerBlocksInTree(
newState,
parentsOfRemovedBlocks2,
true
);
break;
}
case "REMOVE_BLOCKS_AUGMENTED_WITH_CHILDREN":
const parentsOfRemovedBlocks = [];
for (const clientId of action.clientIds) {
const parentId = state.parents.get(clientId);
if (parentId !== void 0 && (parentId === "" || newState.byClientId.get(parentId))) {
parentsOfRemovedBlocks.push(parentId);
}
}
newState.tree = new Map(newState.tree);
action.removedClientIds.forEach((clientId) => {
newState.tree.delete(clientId);
newState.tree.delete("controlled||" + clientId);
});
updateParentInnerBlocksInTree(
newState,
parentsOfRemovedBlocks,
true
);
break;
case "MOVE_BLOCKS_TO_POSITION": {
const updatedBlockUids = [];
if (action.fromRootClientId) {
updatedBlockUids.push(action.fromRootClientId);
} else {
updatedBlockUids.push("");
}
if (action.toRootClientId) {
updatedBlockUids.push(action.toRootClientId);
}
newState.tree = new Map(newState.tree);
updateParentInnerBlocksInTree(
newState,
updatedBlockUids,
true
);
break;
}
case "MOVE_BLOCKS_UP":
case "MOVE_BLOCKS_DOWN": {
const updatedBlockUids = [
action.rootClientId ? action.rootClientId : ""
];
newState.tree = new Map(newState.tree);
updateParentInnerBlocksInTree(
newState,
updatedBlockUids,
true
);
break;
}
}
return newState;
};
function withPersistentBlockChange(reducer3) {
let lastAction;
let nextHistoryMode;
return (state, action) => {
const nextState = reducer3(state, action);
const pendingHistoryMode = nextHistoryMode;
nextHistoryMode = action.type === "MARK_NEXT_CHANGE_AS_NOT_PERSISTENT" ? action.history ?? "merge" : void 0;
const isExplicitPersistentChange = action.type === "MARK_LAST_CHANGE_AS_PERSISTENT" || pendingHistoryMode;
if (state === nextState && !isExplicitPersistentChange) {
if (state.isPersistentChange !== void 0) {
return state;
}
return { ...nextState, isPersistentChange: true };
}
const isPersistentChange = isExplicitPersistentChange ? !pendingHistoryMode : !isUpdatingSameBlockAttribute(action, lastAction);
lastAction = action;
if (pendingHistoryMode === "ignore") {
return {
...nextState,
isPersistentChange,
lastBlockChangeHistoryMode: "ignore"
};
}
const { lastBlockChangeHistoryMode, ...blockChange } = nextState;
return { ...blockChange, isPersistentChange };
};
}
function withIgnoredBlockChange(reducer3) {
const IGNORED_ACTION_TYPES = /* @__PURE__ */ new Set(["RECEIVE_BLOCKS"]);
return (state, action) => {
const nextState = reducer3(state, action);
if (nextState !== state) {
nextState.isIgnoredChange = IGNORED_ACTION_TYPES.has(action.type);
}
return nextState;
};
}
var withInnerBlocksRemoveCascade = (reducer3) => (state, action) => {
const getAllChildren = (clientIds) => {
let result = clientIds;
for (let i2 = 0; i2 < result.length; i2++) {
if (!state.order.get(result[i2]) || action.keepControlledInnerBlocks && action.keepControlledInnerBlocks[result[i2]]) {
continue;
}
if (result === clientIds) {
result = [...result];
}
result.push(...state.order.get(result[i2]));
}
return result;
};
if (state) {
switch (action.type) {
case "REMOVE_BLOCKS":
action = {
...action,
type: "REMOVE_BLOCKS_AUGMENTED_WITH_CHILDREN",
removedClientIds: getAllChildren(action.clientIds)
};
break;
case "REPLACE_BLOCKS":
action = {
...action,
type: "REPLACE_BLOCKS_AUGMENTED_WITH_CHILDREN",
replacedClientIds: getAllChildren(action.clientIds)
};
break;
}
}
return reducer3(state, action);
};
var withBlockReset = (reducer3) => (state, action) => {
if (action.type === "RESET_BLOCKS") {
const newState = reducer3(void 0, {
type: "INSERT_BLOCKS",
rootClientId: "",
blocks: action.blocks
});
const preservedControlledInnerBlocks = state?.controlledInnerBlocks ?? /* @__PURE__ */ new Set();
if (state?.order) {
for (const clientId of preservedControlledInnerBlocks) {
if (!newState.byClientId.has(clientId)) {
continue;
}
newState.controlledInnerBlocks.add(clientId);
const oldOrder = state.order.get(clientId);
if (!oldOrder?.length) {
continue;
}
newState.order.set(clientId, oldOrder);
const preserveBlock = (blockId, parentId) => {
const blockData = state.byClientId.get(blockId);
if (!blockData) {
return;
}
newState.byClientId.set(blockId, blockData);
newState.attributes.set(
blockId,
state.attributes.get(blockId)
);
newState.parents.set(blockId, parentId);
const childOrder = state.order.get(blockId) || [];
newState.order.set(blockId, childOrder);
childOrder.forEach(
(childId) => preserveBlock(childId, blockId)
);
};
oldOrder.forEach((id) => preserveBlock(id, clientId));
}
}
for (const clientId of newState.controlledInnerBlocks) {
const controlledOrder = newState.order.get(clientId);
if (!controlledOrder?.length) {
continue;
}
const innerBlocks = controlledOrder.map(
(id) => state.tree.get(id)
);
const existingEntry = newState.tree.get(clientId);
if (existingEntry) {
existingEntry.innerBlocks = innerBlocks;
}
newState.tree.set("controlled||" + clientId, { innerBlocks });
const preserveTreeEntry = (blockId) => {
const treeEntry = state.tree.get(blockId);
if (!treeEntry) {
return;
}
newState.tree.set(blockId, treeEntry);
const childOrder = newState.order.get(blockId) || [];
childOrder.forEach(preserveTreeEntry);
};
controlledOrder.forEach(preserveTreeEntry);
}
const preservedBlockEditingModes = state?.blockEditingModes ?? /* @__PURE__ */ new Map();
for (const [clientId, mode2] of preservedBlockEditingModes) {
if (!newState.tree.has(clientId)) {
continue;
}
newState.blockEditingModes.set(clientId, mode2);
}
return newState;
}
return reducer3(state, action);
};
var withReplaceInnerBlocks = (reducer3) => (state, action) => {
if (action.type !== "REPLACE_INNER_BLOCKS") {
return reducer3(state, action);
}
const nestedControllers = {};
if (state.controlledInnerBlocks.size) {
const stack = [...action.blocks];
while (stack.length) {
const { innerBlocks, ...block } = stack.shift();
stack.push(...innerBlocks);
if (state.controlledInnerBlocks.has(block.clientId)) {
nestedControllers[block.clientId] = true;
}
}
}
let stateAfterBlocksRemoval = state;
if (state.order.get(action.rootClientId)) {
stateAfterBlocksRemoval = reducer3(stateAfterBlocksRemoval, {
type: "REMOVE_BLOCKS",
keepControlledInnerBlocks: nestedControllers,
clientIds: state.order.get(action.rootClientId)
});
}
let stateAfterInsert = stateAfterBlocksRemoval;
if (action.blocks.length) {
stateAfterInsert = reducer3(stateAfterInsert, {
...action,
type: "INSERT_BLOCKS",
index: 0
});
const stateAfterInsertOrder = new Map(stateAfterInsert.order);
Object.keys(nestedControllers).forEach((key) => {
if (state.order.get(key)) {
stateAfterInsertOrder.set(key, state.order.get(key));
}
});
stateAfterInsert.order = stateAfterInsertOrder;
stateAfterInsert.tree = new Map(stateAfterInsert.tree);
Object.keys(nestedControllers).forEach((_key) => {
const key = `controlled||${_key}`;
if (state.tree.has(key)) {
stateAfterInsert.tree.set(key, state.tree.get(key));
}
});
}
return stateAfterInsert;
};
var withResetControlledBlocks = (reducer3) => (state, action) => {
if (action.type === "SET_HAS_CONTROLLED_INNER_BLOCKS") {
const innerBlockOrder = state.order.get(action.clientId);
if (innerBlockOrder?.length) {
const tempState = reducer3(state, {
type: "REPLACE_INNER_BLOCKS",
rootClientId: action.clientId,
blocks: []
});
return reducer3(tempState, action);
}
return reducer3(state, action);
}
return reducer3(state, action);
};
var blocks = (0, import_compose.pipe)(
import_data2.combineReducers,
withBlockTree,
// Needs to be before withInnerBlocksRemoveCascade.
withInnerBlocksRemoveCascade,
withReplaceInnerBlocks,
// Needs to be after withInnerBlocksRemoveCascade.
withBlockReset,
withPersistentBlockChange,
withIgnoredBlockChange,
withResetControlledBlocks
)({
// The state is using a Map instead of a plain object for performance reasons.
// You can run the "./test/performance.js" unit test to check the impact
// code changes can have on this reducer.
byClientId(state = /* @__PURE__ */ new Map(), action) {
switch (action.type) {
case "RECEIVE_BLOCKS":
case "INSERT_BLOCKS": {
const newState = new Map(state);
getFlattenedBlocksWithoutAttributes(action.blocks).forEach(
([key, value]) => {
newState.set(key, value);
}
);
return newState;
}
case "UPDATE_BLOCK": {
if (!state.has(action.clientId)) {
return state;
}
const { attributes, ...changes } = action.updates;
if (Object.values(changes).length === 0) {
return state;
}
const newState = new Map(state);
newState.set(action.clientId, {
...state.get(action.clientId),
...changes
});
return newState;
}
case "REPLACE_BLOCKS_AUGMENTED_WITH_CHILDREN": {
if (!action.blocks) {
return state;
}
const newState = new Map(state);
action.replacedClientIds.forEach((clientId) => {
newState.delete(clientId);
});
getFlattenedBlocksWithoutAttributes(action.blocks).forEach(
([key, value]) => {
newState.set(key, value);
}
);
return newState;
}
case "REMOVE_BLOCKS_AUGMENTED_WITH_CHILDREN": {
const newState = new Map(state);
action.removedClientIds.forEach((clientId) => {
newState.delete(clientId);
});
return newState;
}
}
return state;
},
// The state is using a Map instead of a plain object for performance reasons.
// You can run the "./test/performance.js" unit test to check the impact
// code changes can have on this reducer.
attributes(state = /* @__PURE__ */ new Map(), action) {
switch (action.type) {
case "RECEIVE_BLOCKS":
case "INSERT_BLOCKS": {
const newState = new Map(state);
getFlattenedBlockAttributes(action.blocks).forEach(
([key, value]) => {
newState.set(key, value);
}
);
return newState;
}
case "UPDATE_BLOCK": {
if (!state.get(action.clientId) || !action.updates.attributes) {
return state;
}
const newState = new Map(state);
newState.set(action.clientId, {
...state.get(action.clientId),
...action.updates.attributes
});
return newState;
}
case "UPDATE_BLOCK_ATTRIBUTES": {
if (action.clientIds.every((id) => !state.get(id))) {
return state;
}
let hasChange = false;
const newState = new Map(state);
for (const clientId of action.clientIds) {
const updatedAttributeEntries = Object.entries(
!!action.options?.uniqueByBlock ? action.attributes[clientId] : action.attributes ?? {}
);
if (updatedAttributeEntries.length === 0) {
continue;
}
let hasUpdatedAttributes = false;
const existingAttributes = state.get(clientId);
const newAttributes = {};
updatedAttributeEntries.forEach(([key, value]) => {
if (existingAttributes[key] !== value) {
hasUpdatedAttributes = true;
newAttributes[key] = value;
}
});
hasChange = hasChange || hasUpdatedAttributes;
if (hasUpdatedAttributes) {
newState.set(clientId, {
...existingAttributes,
...newAttributes
});
}
}
return hasChange ? newState : state;
}
case "REPLACE_BLOCKS_AUGMENTED_WITH_CHILDREN": {
if (!action.blocks) {
return state;
}
const newState = new Map(state);
action.replacedClientIds.forEach((clientId) => {
newState.delete(clientId);
});
getFlattenedBlockAttributes(action.blocks).forEach(
([key, value]) => {
newState.set(key, value);
}
);
return newState;
}
case "REMOVE_BLOCKS_AUGMENTED_WITH_CHILDREN": {
const newState = new Map(state);
action.removedClientIds.forEach((clientId) => {
newState.delete(clientId);
});
return newState;
}
}
return state;
},
// The state is using a Map instead of a plain object for performance reasons.
// You can run the "./test/performance.js" unit test to check the impact
// code changes can have on this reducer.
order(state = /* @__PURE__ */ new Map(), action) {
switch (action.type) {
case "RECEIVE_BLOCKS": {
const blockOrder = mapBlockOrder(action.blocks);
const newState = new Map(state);
blockOrder.forEach((order, clientId) => {
if (clientId !== "") {
newState.set(clientId, order);
}
});
newState.set(
"",
(state.get("") ?? []).concat(blockOrder[""])
);
return newState;
}
case "INSERT_BLOCKS": {
const { rootClientId = "" } = action;
const subState = state.get(rootClientId) || [];
const mappedBlocks = mapBlockOrder(
action.blocks,
rootClientId
);
const { index: index2 = subState.length } = action;
const newState = new Map(state);
mappedBlocks.forEach((order, clientId) => {
newState.set(clientId, order);
});
newState.set(
rootClientId,
insertAt(
subState,
mappedBlocks.get(rootClientId),
index2
)
);
return newState;
}
case "MOVE_BLOCKS_TO_POSITION": {
const {
fromRootClientId = "",
toRootClientId = "",
clientIds
} = action;
const { index: index2 = state.get(toRootClientId).length } = action;
if (fromRootClientId === toRootClientId) {
const subState = state.get(toRootClientId);
const fromIndex = subState.indexOf(clientIds[0]);
if (fromIndex === -1) {
return state;
}
const newState2 = new Map(state);
newState2.set(
toRootClientId,
moveTo(
state.get(toRootClientId),
fromIndex,
index2,
clientIds.length
)
);
return newState2;
}
const newState = new Map(state);
newState.set(
fromRootClientId,
state.get(fromRootClientId)?.filter((id) => !clientIds.includes(id)) ?? []
);
newState.set(
toRootClientId,
insertAt(state.get(toRootClientId), clientIds, index2)
);
return newState;
}
case "MOVE_BLOCKS_UP": {
const { clientIds, rootClientId = "" } = action;
const firstClientId = clientIds[0];
const subState = state.get(rootClientId);
if (!subState.length || firstClientId === subState[0]) {
return state;
}
const firstIndex = subState.indexOf(firstClientId);
const newState = new Map(state);
newState.set(
rootClientId,
moveTo(
subState,
firstIndex,
firstIndex - 1,
clientIds.length
)
);
return newState;
}
case "MOVE_BLOCKS_DOWN": {
const { clientIds, rootClientId = "" } = action;
const firstClientId = clientIds[0];
const lastClientId = clientIds[clientIds.length - 1];
const subState = state.get(rootClientId);
if (!subState.length || lastClientId === subState[subState.length - 1]) {
return state;
}
const firstIndex = subState.indexOf(firstClientId);
const newState = new Map(state);
newState.set(
rootClientId,
moveTo(
subState,
firstIndex,
firstIndex + 1,
clientIds.length
)
);
return newState;
}
case "REPLACE_BLOCKS_AUGMENTED_WITH_CHILDREN": {
const { clientIds } = action;
if (!action.blocks) {
return state;
}
const mappedBlocks = mapBlockOrder(action.blocks);
const newState = new Map(state);
action.replacedClientIds.forEach((clientId) => {
newState.delete(clientId);
});
mappedBlocks.forEach((order, clientId) => {
if (clientId !== "") {
newState.set(clientId, order);
}
});
newState.forEach((order, clientId) => {
const newSubOrder = Object.values(order).reduce(
(result, subClientId) => {
if (subClientId === clientIds[0]) {
return [...result, ...mappedBlocks.get("")];
}
if (clientIds.indexOf(subClientId) === -1) {
result.push(subClientId);
}
return result;
},
[]
);
newState.set(clientId, newSubOrder);
});
return newState;
}
case "REMOVE_BLOCKS_AUGMENTED_WITH_CHILDREN": {
const newState = new Map(state);
action.removedClientIds.forEach((clientId) => {
newState.delete(clientId);
});
newState.forEach((order, clientId) => {
const newSubOrder = order?.filter(
(id) => !action.removedClientIds.includes(id)
) ?? [];
if (newSubOrder.length !== order.length) {
newState.set(clientId, newSubOrder);
}
});
return newState;
}
}
return state;
},
// While technically redundant data as the inverse of `order`, it serves as
// an optimization for the selectors which derive the ancestry of a block.
parents(state = /* @__PURE__ */ new Map(), action) {
switch (action.type) {
case "RECEIVE_BLOCKS": {
const newState = new Map(state);
mapBlockParents(action.blocks).forEach(
([key, value]) => {
newState.set(key, value);
}
);
return newState;
}
case "INSERT_BLOCKS": {
const newState = new Map(state);
mapBlockParents(
action.blocks,
action.rootClientId || ""
).forEach(([key, value]) => {
newState.set(key, value);
});
return newState;
}
case "MOVE_BLOCKS_TO_POSITION": {
const newState = new Map(state);
action.clientIds.forEach((id) => {
newState.set(id, action.toRootClientId || "");
});
return newState;
}
case "REPLACE_BLOCKS_AUGMENTED_WITH_CHILDREN": {
const newState = new Map(state);
action.replacedClientIds.forEach((clientId) => {
newState.delete(clientId);
});
mapBlockParents(
action.blocks,
state.get(action.clientIds[0])
).forEach(([key, value]) => {
newState.set(key, value);
});
return newState;
}
case "REMOVE_BLOCKS_AUGMENTED_WITH_CHILDREN": {
const newState = new Map(state);
action.removedClientIds.forEach((clientId) => {
newState.delete(clientId);
});
return newState;
}
}
return state;
},
controlledInnerBlocks(state = /* @__PURE__ */ new Set(), { type, clientId, hasControlledInnerBlocks }) {
if (type === "SET_HAS_CONTROLLED_INNER_BLOCKS") {
if (hasControlledInnerBlocks) {
if (state.has(clientId)) {
return state;
}
return new Set(state).add(clientId);
}
if (!state.has(clientId)) {
return state;
}
const newState = new Set(state);
newState.delete(clientId);
return newState;
}
return state;
},
blockEditingModes(state = /* @__PURE__ */ new Map(), action) {
switch (action.type) {
case "SET_BLOCK_EDITING_MODE":
if (state.get(action.clientId) === action.mode) {
return state;
}
return new Map(state).set(action.clientId, action.mode);
case "UNSET_BLOCK_EDITING_MODE": {
if (!state.has(action.clientId)) {
return state;
}
const newState = new Map(state);
newState.delete(action.clientId);
return newState;
}
}
return state;
}
});
function isBlockInterfaceHidden(state = false, action) {
switch (action.type) {
case "HIDE_BLOCK_INTERFACE":
return true;
case "SHOW_BLOCK_INTERFACE":
return false;
}
return state;
}
function isTyping(state = false, action) {
switch (action.type) {
case "START_TYPING":
return true;
case "STOP_TYPING":
return false;
}
return state;
}
function isDragging(state = false, action) {
switch (action.type) {
case "START_DRAGGING":
return true;
case "STOP_DRAGGING":
return false;
}
return state;
}
function draggedBlocks(state = [], action) {
switch (action.type) {
case "START_DRAGGING_BLOCKS":
return action.clientIds;
case "STOP_DRAGGING_BLOCKS":
return [];
}
return state;
}
function blockVisibility(state = {}, action) {
if (action.type === "SET_BLOCK_VISIBILITY") {
return {
...state,
...action.updates
};
}
return state;
}
function selectionHelper(state = {}, action) {
switch (action.type) {
case "CLEAR_SELECTED_BLOCK": {
if (state.clientId) {
return {};
}
return state;
}
case "SELECT_BLOCK":
if (action.clientId === state.clientId) {
return state;
}
return { clientId: action.clientId };
case "REPLACE_INNER_BLOCKS":
case "INSERT_BLOCKS": {
if (!action.updateSelection || !action.blocks.length) {
return state;
}
return { clientId: action.blocks[0].clientId };
}
case "REMOVE_BLOCKS":
if (!action.clientIds || !action.clientIds.length || action.clientIds.indexOf(state.clientId) === -1) {
return state;
}
return {};
case "REPLACE_BLOCKS": {
if (action.clientIds.indexOf(state.clientId) === -1) {
return state;
}
const blockToSelect = action.blocks[action.indexToSelect] || action.blocks[action.blocks.length - 1];
if (!blockToSelect) {
return {};
}
if (blockToSelect.clientId === state.clientId) {
return state;
}
return { clientId: blockToSelect.clientId };
}
}
return state;
}
function selection(state = {}, action) {
switch (action.type) {
case "SELECTION_CHANGE":
if (action.clientId) {
return {
selectionStart: {
clientId: action.clientId,
attributeKey: action.attributeKey,
offset: action.startOffset
},
selectionEnd: {
clientId: action.clientId,
attributeKey: action.attributeKey,
offset: action.endOffset
}
};
}
return {
selectionStart: action.start || state.selectionStart,
selectionEnd: action.end || state.selectionEnd
};
case "RESET_SELECTION":
const { selectionStart: selectionStart2, selectionEnd: selectionEnd2 } = action;
return {
selectionStart: selectionStart2,
selectionEnd: selectionEnd2
};
case "MULTI_SELECT":
const { start: start2, end } = action;
if (start2 === state.selectionStart?.clientId && end === state.selectionEnd?.clientId) {
return state;
}
return {
selectionStart: { clientId: start2 },
selectionEnd: { clientId: end }
};
case "RESET_BLOCKS":
const startClientId = state?.selectionStart?.clientId;
const endClientId = state?.selectionEnd?.clientId;
if (!startClientId && !endClientId) {
return state;
}
if (!action.blocks.some(
(block) => block.clientId === startClientId
)) {
return {
selectionStart: {},
selectionEnd: {}
};
}
if (!action.blocks.some(
(block) => block.clientId === endClientId
)) {
return {
...state,
selectionEnd: state.selectionStart
};
}
}
const selectionStart = selectionHelper(state.selectionStart, action);
const selectionEnd = selectionHelper(state.selectionEnd, action);
if (selectionStart === state.selectionStart && selectionEnd === state.selectionEnd) {
return state;
}
return {
selectionStart,
selectionEnd
};
}
function isMultiSelecting(state = false, action) {
switch (action.type) {
case "START_MULTI_SELECT":
return true;
case "STOP_MULTI_SELECT":
return false;
}
return state;
}
function isSelectionEnabled(state = true, action) {
switch (action.type) {
case "TOGGLE_SELECTION":
return action.isSelectionEnabled;
}
return state;
}
function viewportModalClientIds(state = null, action) {
switch (action.type) {
case "SHOW_VIEWPORT_MODAL":
return action.clientIds;
case "HIDE_VIEWPORT_MODAL":
return null;
}
return state;
}
function removalPromptData(state = false, action) {
switch (action.type) {
case "DISPLAY_BLOCK_REMOVAL_PROMPT":
const { clientIds, selectPrevious, message: message2 } = action;
return {
clientIds,
selectPrevious,
message: message2
};
case "CLEAR_BLOCK_REMOVAL_PROMPT":
return false;
}
return state;
}
function blockRemovalRules(state = false, action) {
switch (action.type) {
case "SET_BLOCK_REMOVAL_RULES":
return action.rules;
}
return state;
}
function initialPosition(state = null, action) {
if (action.type === "REPLACE_BLOCKS" && action.initialPosition !== void 0) {
return action.initialPosition;
} else if ([
"MULTI_SELECT",
"SELECT_BLOCK",
"RESET_SELECTION",
"INSERT_BLOCKS",
"REPLACE_INNER_BLOCKS"
].includes(action.type)) {
return action.initialPosition;
}
return state;
}
function blocksMode(state = {}, action) {
if (action.type === "TOGGLE_BLOCK_MODE") {
const { clientId } = action;
return {
...state,
[clientId]: state[clientId] && state[clientId] === "html" ? "visual" : "html"
};
}
return state;
}
function insertionCue(state = null, action) {
switch (action.type) {
case "SHOW_INSERTION_POINT": {
const {
rootClientId,
index: index2,
__unstableWithInserter,
operation,
nearestSide
} = action;
const nextState = {
rootClientId,
index: index2,
__unstableWithInserter,
operation,
nearestSide
};
return (0, import_es6.default)(state, nextState) ? state : nextState;
}
case "HIDE_INSERTION_POINT":
return null;
}
return state;
}
function template(state = { isValid: true }, action) {
switch (action.type) {
case "SET_TEMPLATE_VALIDITY":
return {
...state,
isValid: action.isValid
};
}
return state;
}
function settings(state = SETTINGS_DEFAULTS, action) {
switch (action.type) {
case "UPDATE_SETTINGS": {
const updatedSettings = action.reset ? {
...SETTINGS_DEFAULTS,
...action.settings
} : {
...state,
...action.settings
};
Object.defineProperty(updatedSettings, "__unstableIsPreviewMode", {
get() {
(0, import_deprecated.default)("__unstableIsPreviewMode", {
since: "6.8",
alternative: "isPreviewMode"
});
return this.isPreviewMode;
}
});
return updatedSettings;
}
}
return state;
}
function preferences(state = PREFERENCES_DEFAULTS, action) {
switch (action.type) {
case "INSERT_BLOCKS":
case "REPLACE_BLOCKS": {
const nextInsertUsage = action.blocks.reduce(
(prevUsage, block) => {
const { attributes, name: blockName } = block;
let id = blockName;
const match2 = (0, import_data2.select)(import_blocks2.store).getActiveBlockVariation(
blockName,
attributes
);
if (match2?.name) {
id += "/" + match2.name;
}
if (blockName === "core/block") {
id += "/" + attributes.ref;
}
return {
...prevUsage,
[id]: {
time: action.time,
count: prevUsage[id] ? prevUsage[id].count + 1 : 1
}
};
},
state.insertUsage
);
return {
...state,
insertUsage: nextInsertUsage
};
}
}
return state;
}
var blockListSettings = (state = /* @__PURE__ */ new Map(), action) => {
switch (action.type) {
case "REPLACE_BLOCKS": {
const replacementIds = /* @__PURE__ */ new Set();
const stack = [...action.blocks];
while (stack.length) {
const block = stack.shift();
replacementIds.add(block.clientId);
stack.push(...block.innerBlocks);
}
const newState = new Map(state);
for (const clientId of action.clientIds) {
if (!replacementIds.has(clientId)) {
newState.delete(clientId);
}
}
return newState;
}
case "REMOVE_BLOCKS": {
const newState = new Map(state);
for (const clientId of action.clientIds) {
newState.delete(clientId);
}
return newState;
}
case "UPDATE_BLOCK_LIST_SETTINGS": {
const updates = typeof action.clientId === "string" ? [[action.clientId, action.settings]] : Object.entries(action.clientId);
const relevantUpdates = updates.filter(
([clientId, nextSettings]) => !nextSettings ? state.has(clientId) : !(0, import_es6.default)(state.get(clientId), nextSettings)
);
if (!relevantUpdates.length) {
return state;
}
const newState = new Map(state);
for (const [clientId, nextSettings] of relevantUpdates) {
if (!nextSettings) {
newState.delete(clientId);
} else {
newState.set(clientId, nextSettings);
}
}
return newState;
}
}
return state;
};
function lastBlockAttributesChange(state = null, action) {
switch (action.type) {
case "UPDATE_BLOCK":
if (!action.updates.attributes) {
break;
}
return { [action.clientId]: action.updates.attributes };
case "UPDATE_BLOCK_ATTRIBUTES":
return action.clientIds.reduce(
(accumulator, id) => ({
...accumulator,
[id]: !!action.options?.uniqueByBlock ? action.attributes[id] : action.attributes
}),
{}
);
}
return state;
}
function highlightedBlock(state, action) {
switch (action.type) {
case "TOGGLE_BLOCK_HIGHLIGHT":
const { clientId, isHighlighted } = action;
if (isHighlighted) {
return clientId;
} else if (state === clientId) {
return null;
}
return state;
case "SELECT_BLOCK":
if (action.clientId !== state) {
return null;
}
}
return state;
}
function hasBlockSpotlight(state, action) {
switch (action.type) {
case "TOGGLE_BLOCK_SPOTLIGHT":
const { clientId, hasBlockSpotlight: _hasBlockSpotlight } = action;
if (_hasBlockSpotlight) {
return clientId;
} else if (state === clientId) {
return null;
}
return state;
case "SELECT_BLOCK":
if (action.clientId !== state) {
return null;
}
return state;
case "SELECTION_CHANGE":
if (action.start?.clientId !== state || action.end?.clientId !== state) {
return null;
}
return state;
case "CLEAR_SELECTED_BLOCK":
return null;
}
return state;
}
function expandedBlock(state = null, action) {
switch (action.type) {
case "SET_BLOCK_EXPANDED_IN_LIST_VIEW":
return action.clientId;
case "SELECT_BLOCK":
if (action.clientId !== state) {
return null;
}
}
return state;
}
function lastBlockInserted(state = {}, action) {
switch (action.type) {
case "INSERT_BLOCKS":
case "REPLACE_BLOCKS":
if (!action.blocks.length) {
return state;
}
const clientIds = action.blocks.map((block) => {
return block.clientId;
});
const source = action.meta?.source;
return { clientIds, source };
case "RESET_BLOCKS":
return {};
}
return state;
}
function editedContentOnlySection(state, action) {
if (action.type === "EDIT_CONTENT_ONLY_SECTION") {
return action.clientId;
}
if (!state) {
return state;
}
switch (action.type) {
case "REMOVE_BLOCKS":
case "REPLACE_BLOCKS":
if (action.clientIds.includes(state)) {
return void 0;
}
break;
case "RESET_BLOCKS":
if (!getFlattenedClientIds(action.blocks)[state]) {
return void 0;
}
break;
}
return state;
}
function styleOverrides(state = /* @__PURE__ */ new Map(), action) {
switch (action.type) {
case "SET_STYLE_OVERRIDE":
return new Map(state).set(action.id, action.style);
case "DELETE_STYLE_OVERRIDE": {
const newState = new Map(state);
newState.delete(action.id);
return newState;
}
}
return state;
}
function registeredInserterMediaCategories(state = [], action) {
switch (action.type) {
case "REGISTER_INSERTER_MEDIA_CATEGORY":
return [...state, action.category];
}
return state;
}
function lastFocus(state = false, action) {
switch (action.type) {
case "LAST_FOCUS":
return action.lastFocus;
}
return state;
}
function zoomLevel(state = 100, action) {
switch (action.type) {
case "SET_ZOOM_LEVEL":
return action.zoom;
case "RESET_ZOOM_LEVEL":
return 100;
}
return state;
}
function insertionPoint(state = null, action) {
switch (action.type) {
case "SET_INSERTION_POINT":
return action.value;
case "SELECT_BLOCK":
return null;
}
return state;
}
function openedListViewPanels(state = { allOpen: false, panels: {} }, action) {
switch (action.type) {
case "SET_OPEN_LIST_VIEW_PANEL":
return {
allOpen: false,
panels: action.clientId ? { [action.clientId]: true } : {}
};
case "SET_ALL_LIST_VIEW_PANELS_OPEN":
return { allOpen: true, panels: {} };
case "TOGGLE_LIST_VIEW_PANEL":
return {
allOpen: false,
panels: {
...state.panels,
[action.clientId]: action.isOpen
}
};
case "REPLACE_BLOCKS":
case "REMOVE_BLOCKS": {
if (!action.clientIds || action.clientIds.length === 0) {
return state;
}
const newPanels = { ...state.panels };
let hasChanges = false;
action.clientIds.forEach((clientId) => {
if (clientId in newPanels) {
delete newPanels[clientId];
hasChanges = true;
}
});
return hasChanges ? { ...state, panels: newPanels } : state;
}
}
return state;
}
function listViewExpandRevision(state = 0, action) {
switch (action.type) {
case "INCREMENT_LIST_VIEW_EXPAND_REVISION":
return state + 1;
}
return state;
}
function listViewContentPanelOpen(state = false, action) {
switch (action.type) {
case "OPEN_LIST_VIEW_CONTENT_PANEL":
return true;
case "CLOSE_LIST_VIEW_CONTENT_PANEL":
return false;
// Close when selection is cleared
case "CLEAR_SELECTED_BLOCK":
return false;
}
return state;
}
function requestedInspectorTab(state = null, action) {
switch (action.type) {
case "REQUEST_INSPECTOR_TAB":
return {
tabName: action.tabName,
options: action.options
};
case "CLEAR_REQUESTED_INSPECTOR_TAB":
return null;
}
return state;
}
function selectedBlockStyleState(state = void 0, action) {
switch (action.type) {
case "SET_SELECTED_BLOCK_STYLE_STATE": {
if (!action.clientId || !action.value) {
return void 0;
}
const showStateOnCanvas = state?.clientId === action.clientId ? state.showStateOnCanvas ?? true : true;
const previousValue = state?.clientId === action.clientId ? state.value : {};
return {
clientId: action.clientId,
showStateOnCanvas,
value: {
pseudo: "default",
...previousValue,
...action.value
}
};
}
case "SET_SELECTED_BLOCK_STYLE_STATE_CANVAS_PREVIEW": {
if (!action.clientId || typeof action.value !== "boolean") {
return state;
}
const previousValue = state?.clientId === action.clientId ? state.value : {};
return {
clientId: action.clientId,
showStateOnCanvas: action.value,
value: {
pseudo: "default",
...previousValue
}
};
}
case "SELECT_BLOCK":
case "SELECTION_CHANGE": {
if (state?.clientId && state.clientId !== action.clientId) {
return void 0;
}
break;
}
case "RESET_SELECTION": {
if (state?.clientId && state.clientId !== action.selectionStart?.clientId) {
return void 0;
}
break;
}
case "CLEAR_SELECTED_BLOCK":
case "MULTI_SELECT":
return void 0;
case "REMOVE_BLOCKS":
case "REPLACE_BLOCKS": {
if (state?.clientId && action.clientIds?.includes(state.clientId)) {
return void 0;
}
break;
}
case "RESET_BLOCKS": {
if (state?.clientId && !getFlattenedClientIds(action.blocks)[state.clientId]) {
return void 0;
}
break;
}
}
return state;
}
function styleStateViewport(state = "default", action) {
if (action.type === "SET_STYLE_STATE_VIEWPORT") {
return action.viewport ?? "default";
}
return state;
}
function isResponsiveEditing(state = false, action) {
if (action.type === "SET_RESPONSIVE_EDITING") {
return action.enabled;
}
return state;
}
var combinedReducers = (0, import_data2.combineReducers)({
blocks,
isDragging,
isTyping,
isBlockInterfaceHidden,
draggedBlocks,
selection,
isMultiSelecting,
isSelectionEnabled,
initialPosition,
blocksMode,
blockListSettings,
insertionPoint,
insertionCue,
template,
settings,
preferences,
lastBlockAttributesChange,
lastFocus,
expandedBlock,
highlightedBlock,
lastBlockInserted,
editedContentOnlySection,
blockVisibility,
viewportModalClientIds,
styleOverrides,
removalPromptData,
blockRemovalRules,
registeredInserterMediaCategories,
zoomLevel,
hasBlockSpotlight,
openedListViewPanels,
listViewExpandRevision,
listViewContentPanelOpen,
requestedInspectorTab,
selectedBlockStyleState,
styleStateViewport,
isResponsiveEditing
});
function getBlockTreeBlock(state, clientId) {
if (clientId === "") {
const rootBlock = state.blocks.tree.get(clientId);
if (!rootBlock) {
return;
}
return {
clientId: "",
...rootBlock
};
}
if (!state.blocks.controlledInnerBlocks.has(clientId)) {
return state.blocks.tree.get(clientId);
}
const controlledTree = state.blocks.tree.get(`controlled||${clientId}`);
const regularTree = state.blocks.tree.get(clientId);
return {
...regularTree,
innerBlocks: controlledTree?.innerBlocks
};
}
function traverseBlockTree(state, clientId, callback) {
const tree = getBlockTreeBlock(state, clientId);
if (!tree) {
return;
}
callback(tree);
if (!tree?.innerBlocks?.length) {
return;
}
for (const innerBlock of tree?.innerBlocks) {
traverseBlockTree(state, innerBlock.clientId, callback);
}
}
function findParentInClientIdsList(state, clientId, clientIds) {
if (!clientIds.length) {
return;
}
let parent = state.blocks.parents.get(clientId);
while (parent !== void 0) {
if (clientIds.includes(parent)) {
return parent;
}
parent = state.blocks.parents.get(parent);
}
}
function hasBindings(block) {
return block?.attributes?.metadata?.bindings && Object.keys(block?.attributes?.metadata?.bindings).length;
}
function getDerivedBlockEditingModesForTree(state, treeClientId = "") {
const isZoomedOut = state?.zoomLevel < 100 || state?.zoomLevel === "auto-scaled";
const derivedBlockEditingModes = /* @__PURE__ */ new Map();
const sectionRootClientId = state.settings?.[sectionRootClientIdKey];
const sectionClientIds = state.blocks.order.get(sectionRootClientId);
const hasDisabledBlocks = Array.from(state.blocks.blockEditingModes).some(
([, mode2]) => mode2 === "disabled"
);
const templatePartClientIds = [];
const syncedPatternClientIds = [];
state.blocks.controlledInnerBlocks.forEach((clientId) => {
const block = state.blocks.byClientId?.get(clientId);
if (block?.name === "core/template-part") {
templatePartClientIds.push(clientId);
}
if (block?.name === "core/block") {
syncedPatternClientIds.push(clientId);
}
});
const contentOnlyTemplateLockedClientIds = Array.from(
state.blockListSettings
).flatMap(
([clientId, listSettings]) => listSettings?.templateLock === "contentOnly" ? [clientId] : []
);
const isIsolatedEditor = state.settings?.[isIsolatedEditorKey];
const disableContentOnlyForUnsyncedPatterns = state.settings?.disableContentOnlyForUnsyncedPatterns;
const unsyncedPatternClientIds = isIsolatedEditor || disableContentOnlyForUnsyncedPatterns ? [] : Array.from(state.blocks.attributes.keys()).filter(
(clientId) => state.blocks.attributes.get(clientId)?.metadata?.patternName
);
const disableContentOnlyForTemplateParts = state.settings?.disableContentOnlyForTemplateParts;
const contentOnlyParents = [
...contentOnlyTemplateLockedClientIds,
...unsyncedPatternClientIds,
...isIsolatedEditor || disableContentOnlyForTemplateParts ? [] : templatePartClientIds
];
traverseBlockTree(state, treeClientId, (block) => {
const { clientId, name: blockName } = block;
const hasEditedContentOnlySection = !!state.editedContentOnlySection;
let isWithinEditedContentOnlySection2 = false;
if (hasEditedContentOnlySection) {
isWithinEditedContentOnlySection2 = clientId === state.editedContentOnlySection || !!findParentInClientIdsList(state, clientId, [
state.editedContentOnlySection
]);
if (!isWithinEditedContentOnlySection2) {
derivedBlockEditingModes.set(clientId, "disabled");
return;
}
}
if (state.blocks.blockEditingModes.has(clientId)) {
return;
}
if (hasDisabledBlocks) {
let ancestorBlockEditingMode;
let parent = state.blocks.parents.get(clientId);
while (parent !== void 0) {
if (state.blocks.blockEditingModes.has(parent)) {
ancestorBlockEditingMode = state.blocks.blockEditingModes.get(parent);
}
if (ancestorBlockEditingMode) {
break;
}
parent = state.blocks.parents.get(parent);
}
if (ancestorBlockEditingMode === "disabled") {
derivedBlockEditingModes.set(clientId, "disabled");
return;
}
}
if (isZoomedOut) {
if (clientId === sectionRootClientId) {
derivedBlockEditingModes.set(clientId, "contentOnly");
return;
}
if (!sectionClientIds?.length) {
derivedBlockEditingModes.set(clientId, "disabled");
return;
}
if (sectionClientIds.includes(clientId)) {
derivedBlockEditingModes.set(clientId, "contentOnly");
return;
}
derivedBlockEditingModes.set(clientId, "disabled");
return;
}
if (syncedPatternClientIds.length) {
if (syncedPatternClientIds.includes(clientId)) {
if (findParentInClientIdsList(
state,
clientId,
syncedPatternClientIds
)) {
derivedBlockEditingModes.set(clientId, "disabled");
return;
}
return;
}
const parentSyncedPatternClientId = findParentInClientIdsList(
state,
clientId,
syncedPatternClientIds
);
if (parentSyncedPatternClientId) {
if (findParentInClientIdsList(
state,
parentSyncedPatternClientId,
syncedPatternClientIds
)) {
derivedBlockEditingModes.set(clientId, "disabled");
return;
}
if (hasBindings(block)) {
derivedBlockEditingModes.set(clientId, "contentOnly");
return;
}
derivedBlockEditingModes.set(clientId, "disabled");
return;
}
}
if (hasEditedContentOnlySection && isWithinEditedContentOnlySection2) {
derivedBlockEditingModes.set(clientId, "default");
return;
}
if (contentOnlyParents.length) {
const hasContentOnlyParent = !!findParentInClientIdsList(
state,
clientId,
contentOnlyParents
);
if (hasContentOnlyParent) {
if (isContentBlock(blockName)) {
derivedBlockEditingModes.set(clientId, "contentOnly");
} else {
derivedBlockEditingModes.set(clientId, "disabled");
}
}
}
});
return derivedBlockEditingModes;
}
function getDerivedBlockEditingModesUpdates({
prevState,
nextState,
addedBlocks,
removedClientIds
}) {
const prevDerivedBlockEditingModes = prevState.derivedBlockEditingModes;
let nextDerivedBlockEditingModes;
removedClientIds?.forEach((clientId) => {
traverseBlockTree(prevState, clientId, (block) => {
if (prevDerivedBlockEditingModes.has(block.clientId)) {
if (!nextDerivedBlockEditingModes) {
nextDerivedBlockEditingModes = new Map(
prevDerivedBlockEditingModes
);
}
nextDerivedBlockEditingModes.delete(block.clientId);
}
});
});
addedBlocks?.forEach((addedBlock) => {
const updates = getDerivedBlockEditingModesForTree(
nextState,
addedBlock.clientId
);
if (updates.size) {
if (!nextDerivedBlockEditingModes) {
nextDerivedBlockEditingModes = new Map([
...prevDerivedBlockEditingModes?.size ? prevDerivedBlockEditingModes : [],
...updates
]);
} else {
nextDerivedBlockEditingModes = new Map([
...nextDerivedBlockEditingModes?.size ? nextDerivedBlockEditingModes : [],
...updates
]);
}
}
});
return nextDerivedBlockEditingModes;
}
function withDerivedBlockEditingModes(reducer3) {
return (state, action) => {
const nextState = reducer3(state, action);
if (action.type !== "SET_EDITOR_MODE" && nextState === state) {
return state;
}
switch (action.type) {
case "REMOVE_BLOCKS": {
const nextDerivedBlockEditingModes = getDerivedBlockEditingModesUpdates({
prevState: state,
nextState,
removedClientIds: action.clientIds
});
if (nextDerivedBlockEditingModes) {
return {
...nextState,
derivedBlockEditingModes: nextDerivedBlockEditingModes ?? state.derivedBlockEditingModes
};
}
break;
}
case "RECEIVE_BLOCKS":
case "INSERT_BLOCKS": {
const nextDerivedBlockEditingModes = getDerivedBlockEditingModesUpdates({
prevState: state,
nextState,
addedBlocks: action.blocks
});
if (nextDerivedBlockEditingModes) {
return {
...nextState,
derivedBlockEditingModes: nextDerivedBlockEditingModes ?? state.derivedBlockEditingModes
};
}
break;
}
case "UPDATE_BLOCK_ATTRIBUTES": {
const disableContentOnlyForUnsyncedPatterns = nextState.settings?.disableContentOnlyForUnsyncedPatterns;
if (disableContentOnlyForUnsyncedPatterns) {
break;
}
const addedBlocks = [];
const removedClientIds = [];
for (const clientId of action?.clientIds) {
const attributes = action.options?.uniqueByBlock ? action.attributes[clientId] : action.attributes;
if (!attributes) {
break;
}
if (
// patternName is switching from falsy to truthy, indicating
// this block is becoming an unsynced pattern.
attributes.metadata?.patternName && !state.blocks.attributes.get(clientId)?.metadata?.patternName
) {
addedBlocks.push(
nextState.blocks.tree.get(clientId)
);
} else if (
// patternName is switching from truthy to falsy, this block is becoming
// a regular block but was an unsynced pattern.
// Check that `metadata` is part of the included attributes, as
// `updateBlockAttributes` merges attributes, if it isn't present
// the previous `metadata` would be retained.
attributes.metadata && !attributes.metadata?.patternName && state.blocks.attributes.get(clientId)?.metadata?.patternName
) {
removedClientIds.push(clientId);
}
}
if (!addedBlocks?.length && !removedClientIds?.length) {
break;
}
const nextDerivedBlockEditingModes = getDerivedBlockEditingModesUpdates({
prevState: state,
nextState,
addedBlocks,
removedClientIds
});
if (nextDerivedBlockEditingModes) {
return {
...nextState,
derivedBlockEditingModes: nextDerivedBlockEditingModes ?? state.derivedBlockEditingModes
};
}
break;
}
case "UPDATE_BLOCK_LIST_SETTINGS": {
const addedBlocks = [];
const removedClientIds = [];
const updates = typeof action.clientId === "string" ? { [action.clientId]: action.settings } : action.clientId;
for (const clientId in updates) {
const isNewContentOnlyBlock = state.blockListSettings.get(clientId)?.templateLock !== "contentOnly" && nextState.blockListSettings.get(clientId)?.templateLock === "contentOnly";
const wasContentOnlyBlock = state.blockListSettings.get(clientId)?.templateLock === "contentOnly" && nextState.blockListSettings.get(clientId)?.templateLock !== "contentOnly";
if (isNewContentOnlyBlock) {
addedBlocks.push(
nextState.blocks.tree.get(clientId)
);
} else if (wasContentOnlyBlock) {
removedClientIds.push(clientId);
}
}
if (!addedBlocks.length && !removedClientIds.length) {
break;
}
const nextDerivedBlockEditingModes = getDerivedBlockEditingModesUpdates({
prevState: state,
nextState,
addedBlocks,
removedClientIds
});
if (nextDerivedBlockEditingModes) {
return {
...nextState,
derivedBlockEditingModes: nextDerivedBlockEditingModes ?? state.derivedBlockEditingModes
};
}
break;
}
case "SET_BLOCK_EDITING_MODE":
case "UNSET_BLOCK_EDITING_MODE":
case "SET_HAS_CONTROLLED_INNER_BLOCKS": {
const updatedBlock = getBlockTreeBlock(
nextState,
action.clientId
);
if (!updatedBlock) {
break;
}
const nextDerivedBlockEditingModes = getDerivedBlockEditingModesUpdates({
prevState: state,
nextState,
removedClientIds: [action.clientId],
addedBlocks: [updatedBlock]
});
if (nextDerivedBlockEditingModes) {
return {
...nextState,
derivedBlockEditingModes: nextDerivedBlockEditingModes ?? state.derivedBlockEditingModes
};
}
break;
}
case "REPLACE_BLOCKS": {
const nextDerivedBlockEditingModes = getDerivedBlockEditingModesUpdates({
prevState: state,
nextState,
addedBlocks: action.blocks,
removedClientIds: action.clientIds
});
if (nextDerivedBlockEditingModes) {
return {
...nextState,
derivedBlockEditingModes: nextDerivedBlockEditingModes ?? state.derivedBlockEditingModes
};
}
break;
}
case "REPLACE_INNER_BLOCKS": {
const removedClientIds = state.blocks.order.get(
action.rootClientId
);
const nextDerivedBlockEditingModes = getDerivedBlockEditingModesUpdates({
prevState: state,
nextState,
addedBlocks: action.blocks,
removedClientIds
});
if (nextDerivedBlockEditingModes) {
return {
...nextState,
derivedBlockEditingModes: nextDerivedBlockEditingModes ?? state.derivedBlockEditingModes
};
}
break;
}
case "MOVE_BLOCKS_TO_POSITION": {
const addedBlocks = action.clientIds.map((clientId) => {
return nextState.blocks.byClientId.get(clientId);
});
const nextDerivedBlockEditingModes = getDerivedBlockEditingModesUpdates({
prevState: state,
nextState,
addedBlocks,
removedClientIds: action.clientIds
});
if (nextDerivedBlockEditingModes) {
return {
...nextState,
derivedBlockEditingModes: nextDerivedBlockEditingModes ?? state.derivedBlockEditingModes
};
}
break;
}
case "UPDATE_SETTINGS": {
if (state?.settings?.[sectionRootClientIdKey] !== nextState?.settings?.[sectionRootClientIdKey] || !!state?.settings?.disableContentOnlyForUnsyncedPatterns !== !!nextState?.settings?.disableContentOnlyForUnsyncedPatterns || !!state?.settings?.[isIsolatedEditorKey] !== !!nextState?.settings?.[isIsolatedEditorKey] || !!state?.settings?.disableContentOnlyForTemplateParts !== !!nextState?.settings?.disableContentOnlyForTemplateParts) {
return {
...nextState,
derivedBlockEditingModes: getDerivedBlockEditingModesForTree(nextState)
};
}
break;
}
case "RESET_BLOCKS":
case "EDIT_CONTENT_ONLY_SECTION":
case "SET_EDITOR_MODE":
case "RESET_ZOOM_LEVEL":
case "SET_ZOOM_LEVEL": {
return {
...nextState,
derivedBlockEditingModes: getDerivedBlockEditingModesForTree(nextState)
};
}
}
nextState.derivedBlockEditingModes = state?.derivedBlockEditingModes ?? /* @__PURE__ */ new Map();
return nextState;
};
}
function withAutomaticChangeReset(reducer3) {
return (state, action) => {
const nextState = reducer3(state, action);
if (!state) {
return nextState;
}
nextState.automaticChangeStatus = state.automaticChangeStatus;
if (action.type === "MARK_AUTOMATIC_CHANGE") {
return {
...nextState,
automaticChangeStatus: "pending"
};
}
if (action.type === "MARK_AUTOMATIC_CHANGE_FINAL" && state.automaticChangeStatus === "pending") {
return {
...nextState,
automaticChangeStatus: "final"
};
}
if (nextState.blocks === state.blocks && nextState.selection === state.selection) {
return nextState;
}
if (nextState.automaticChangeStatus !== "final" && nextState.selection !== state.selection) {
return nextState;
}
return {
...nextState,
automaticChangeStatus: void 0
};
};
}
var reducer_default = (0, import_compose.pipe)(
withDerivedBlockEditingModes,
withAutomaticChangeReset
)(combinedReducers);
// packages/block-editor/build-module/store/selectors.mjs
var selectors_exports = {};
__export(selectors_exports, {
__experimentalGetActiveBlockIdByBlockNames: () => __experimentalGetActiveBlockIdByBlockNames,
__experimentalGetAllowedBlocks: () => __experimentalGetAllowedBlocks,
__experimentalGetAllowedPatterns: () => __experimentalGetAllowedPatterns,
__experimentalGetBlockListSettingsForBlocks: () => __experimentalGetBlockListSettingsForBlocks,
__experimentalGetDirectInsertBlock: () => __experimentalGetDirectInsertBlock,
__experimentalGetGlobalBlocksByName: () => __experimentalGetGlobalBlocksByName,
__experimentalGetLastBlockAttributeChanges: () => __experimentalGetLastBlockAttributeChanges,
__experimentalGetParsedPattern: () => __experimentalGetParsedPattern,
__experimentalGetPatternTransformItems: () => __experimentalGetPatternTransformItems,
__experimentalGetPatternsByBlockTypes: () => __experimentalGetPatternsByBlockTypes,
__experimentalGetReusableBlockTitle: () => __experimentalGetReusableBlockTitle,
__unstableGetBlockWithoutInnerBlocks: () => __unstableGetBlockWithoutInnerBlocks,
__unstableGetClientIdWithClientIdsTree: () => __unstableGetClientIdWithClientIdsTree,
__unstableGetClientIdsTree: () => __unstableGetClientIdsTree,
__unstableGetContentLockingParent: () => __unstableGetContentLockingParent,
__unstableGetLastBlockChangeHistoryMode: () => __unstableGetLastBlockChangeHistoryMode,
__unstableGetSelectedBlocksWithPartialSelection: () => __unstableGetSelectedBlocksWithPartialSelection,
__unstableGetTemporarilyEditingAsBlocks: () => __unstableGetTemporarilyEditingAsBlocks,
__unstableGetVisibleBlocks: () => __unstableGetVisibleBlocks,
__unstableHasActiveBlockOverlayActive: () => __unstableHasActiveBlockOverlayActive,
__unstableIsFullySelected: () => __unstableIsFullySelected,
__unstableIsLastBlockChangeIgnored: () => __unstableIsLastBlockChangeIgnored,
__unstableIsSelectionCollapsed: () => __unstableIsSelectionCollapsed,
__unstableIsSelectionMergeable: () => __unstableIsSelectionMergeable,
__unstableIsWithinBlockOverlay: () => __unstableIsWithinBlockOverlay,
__unstableSelectionHasUnmergeableBlock: () => __unstableSelectionHasUnmergeableBlock,
areInnerBlocksControlled: () => areInnerBlocksControlled,
canEditBlock: () => canEditBlock,
canInsertBlockType: () => canInsertBlockType,
canInsertBlocks: () => canInsertBlocks,
canLockBlockType: () => canLockBlockType,
canMoveBlock: () => canMoveBlock,
canMoveBlocks: () => canMoveBlocks,
canRemoveBlock: () => canRemoveBlock,
canRemoveBlocks: () => canRemoveBlocks,
didAutomaticChange: () => didAutomaticChange,
getAdjacentBlockClientId: () => getAdjacentBlockClientId,
getAllowedBlocks: () => getAllowedBlocks,
getBlock: () => getBlock,
getBlockAttributes: () => getBlockAttributes,
getBlockCount: () => getBlockCount,
getBlockEditingMode: () => getBlockEditingMode,
getBlockHierarchyRootClientId: () => getBlockHierarchyRootClientId,
getBlockIndex: () => getBlockIndex,
getBlockInsertionPoint: () => getBlockInsertionPoint,
getBlockListSettings: () => getBlockListSettings,
getBlockMode: () => getBlockMode,
getBlockName: () => getBlockName,
getBlockNamesByClientId: () => getBlockNamesByClientId,
getBlockOrder: () => getBlockOrder,
getBlockParents: () => getBlockParents,
getBlockParentsByBlockName: () => getBlockParentsByBlockName,
getBlockRootClientId: () => getBlockRootClientId,
getBlockSelectionEnd: () => getBlockSelectionEnd,
getBlockSelectionStart: () => getBlockSelectionStart,
getBlockTransformItems: () => getBlockTransformItems,
getBlocks: () => getBlocks,
getBlocksByClientId: () => getBlocksByClientId,
getBlocksByName: () => getBlocksByName,
getClientIdsOfDescendants: () => getClientIdsOfDescendants,
getClientIdsWithDescendants: () => getClientIdsWithDescendants,
getDirectInsertBlock: () => getDirectInsertBlock,
getDraggedBlockClientIds: () => getDraggedBlockClientIds,
getFirstMultiSelectedBlockClientId: () => getFirstMultiSelectedBlockClientId,
getGlobalBlockCount: () => getGlobalBlockCount,
getHoveredBlockClientId: () => getHoveredBlockClientId,
getInserterItems: () => getInserterItems,
getLastMultiSelectedBlockClientId: () => getLastMultiSelectedBlockClientId,
getLowestCommonAncestorWithSelectedBlock: () => getLowestCommonAncestorWithSelectedBlock,
getMultiSelectedBlockClientIds: () => getMultiSelectedBlockClientIds,
getMultiSelectedBlocks: () => getMultiSelectedBlocks,
getMultiSelectedBlocksEndClientId: () => getMultiSelectedBlocksEndClientId,
getMultiSelectedBlocksStartClientId: () => getMultiSelectedBlocksStartClientId,
getNextBlockClientId: () => getNextBlockClientId,
getPatternsByBlockTypes: () => getPatternsByBlockTypes,
getPreviousBlockClientId: () => getPreviousBlockClientId,
getSelectedBlock: () => getSelectedBlock,
getSelectedBlockClientId: () => getSelectedBlockClientId,
getSelectedBlockClientIds: () => getSelectedBlockClientIds,
getSelectedBlockCount: () => getSelectedBlockCount,
getSelectedBlocksInitialCaretPosition: () => getSelectedBlocksInitialCaretPosition,
getSelectionEnd: () => getSelectionEnd,
getSelectionStart: () => getSelectionStart,
getSettings: () => getSettings,
getTemplate: () => getTemplate,
getTemplateLock: () => getTemplateLock,
hasBlockMovingClientId: () => hasBlockMovingClientId,
hasDraggedInnerBlock: () => hasDraggedInnerBlock,
hasInserterItems: () => hasInserterItems,
hasMultiSelection: () => hasMultiSelection,
hasSelectedBlock: () => hasSelectedBlock,
hasSelectedInnerBlock: () => hasSelectedInnerBlock,
isAncestorBeingDragged: () => isAncestorBeingDragged,
isAncestorMultiSelected: () => isAncestorMultiSelected,
isBlockBeingDragged: () => isBlockBeingDragged,
isBlockHighlighted: () => isBlockHighlighted,
isBlockInsertionPointVisible: () => isBlockInsertionPointVisible,
isBlockMultiSelected: () => isBlockMultiSelected,
isBlockSelected: () => isBlockSelected,
isBlockValid: () => isBlockValid,
isBlockVisible: () => isBlockVisible,
isBlockWithinSelection: () => isBlockWithinSelection,
isCaretWithinFormattedText: () => isCaretWithinFormattedText,
isDraggingBlocks: () => isDraggingBlocks,
isFirstMultiSelectedBlock: () => isFirstMultiSelectedBlock,
isGroupable: () => isGroupable,
isLastBlockChangePersistent: () => isLastBlockChangePersistent,
isMultiSelecting: () => isMultiSelecting2,
isSelectionEnabled: () => isSelectionEnabled2,
isTyping: () => isTyping2,
isUngroupable: () => isUngroupable,
isValidTemplate: () => isValidTemplate,
wasBlockJustInserted: () => wasBlockJustInserted
});
var import_blocks7 = __toESM(require_blocks(), 1);
var import_hooks2 = __toESM(require_hooks(), 1);
// packages/icons/build-module/icon/index.mjs
var import_element5 = __toESM(require_element(), 1);
var icon_default = (0, import_element5.forwardRef)(
({ icon, size: size4 = 24, ...props }, ref) => {
return (0, import_element5.cloneElement)(icon, {
width: size4,
height: size4,
...props,
ref
});
}
);
// packages/icons/build-module/library/align-center.mjs
var import_primitives = __toESM(require_primitives(), 1);
var import_jsx_runtime3 = __toESM(require_jsx_runtime(), 1);
var align_center_default = /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_primitives.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_primitives.Path, { d: "M7.5 5.5h9V4h-9v1.5Zm-3.5 7h16V11H4v1.5Zm3.5 7h9V18h-9v1.5Z" }) });
// packages/icons/build-module/library/align-justify.mjs
var import_primitives2 = __toESM(require_primitives(), 1);
var import_jsx_runtime4 = __toESM(require_jsx_runtime(), 1);
var align_justify_default = /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_primitives2.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_primitives2.Path, { d: "M4 12.8h16v-1.5H4v1.5zm0 7h12.4v-1.5H4v1.5zM4 4.3v1.5h16V4.3H4z" }) });
// packages/icons/build-module/library/align-left.mjs
var import_primitives3 = __toESM(require_primitives(), 1);
var import_jsx_runtime5 = __toESM(require_jsx_runtime(), 1);
var align_left_default = /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_primitives3.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_primitives3.Path, { d: "M13 5.5H4V4h9v1.5Zm7 7H4V11h16v1.5Zm-7 7H4V18h9v1.5Z" }) });
// packages/icons/build-module/library/align-none.mjs
var import_primitives4 = __toESM(require_primitives(), 1);
var import_jsx_runtime6 = __toESM(require_jsx_runtime(), 1);
var align_none_default = /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_primitives4.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_primitives4.Path, { d: "M19 5.5H5V4h14v1.5ZM19 20H5v-1.5h14V20ZM5 9h14v6H5V9Z" }) });
// packages/icons/build-module/library/align-right.mjs
var import_primitives5 = __toESM(require_primitives(), 1);
var import_jsx_runtime7 = __toESM(require_jsx_runtime(), 1);
var align_right_default = /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_primitives5.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_primitives5.Path, { d: "M11.111 5.5H20V4h-8.889v1.5ZM4 12.5h16V11H4v1.5Zm7.111 7H20V18h-8.889v1.5Z" }) });
// packages/icons/build-module/library/arrow-down.mjs
var import_primitives6 = __toESM(require_primitives(), 1);
var import_jsx_runtime8 = __toESM(require_jsx_runtime(), 1);
var arrow_down_default = /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(import_primitives6.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(import_primitives6.Path, { d: "m16.5 13.5-3.7 3.7V4h-1.5v13.2l-3.8-3.7-1 1 5.5 5.6 5.5-5.6z" }) });
// packages/icons/build-module/library/arrow-left.mjs
var import_primitives7 = __toESM(require_primitives(), 1);
var import_jsx_runtime9 = __toESM(require_jsx_runtime(), 1);
var arrow_left_default = /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(import_primitives7.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(import_primitives7.Path, { d: "M20 11.2H6.8l3.7-3.7-1-1L3.9 12l5.6 5.5 1-1-3.7-3.7H20z" }) });
// packages/icons/build-module/library/arrow-right.mjs
var import_primitives8 = __toESM(require_primitives(), 1);
var import_jsx_runtime10 = __toESM(require_jsx_runtime(), 1);
var arrow_right_default = /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(import_primitives8.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(import_primitives8.Path, { d: "m14.5 6.5-1 1 3.7 3.7H4v1.6h13.2l-3.7 3.7 1 1 5.6-5.5z" }) });
// packages/icons/build-module/library/aspect-ratio.mjs
var import_primitives9 = __toESM(require_primitives(), 1);
var import_jsx_runtime11 = __toESM(require_jsx_runtime(), 1);
var aspect_ratio_default = /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_primitives9.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_primitives9.Path, { d: "M18.5 5.5h-13c-1.1 0-2 .9-2 2v9c0 1.1.9 2 2 2h13c1.1 0 2-.9 2-2v-9c0-1.1-.9-2-2-2zm.5 11c0 .3-.2.5-.5.5h-13c-.3 0-.5-.2-.5-.5v-9c0-.3.2-.5.5-.5h13c.3 0 .5.2.5.5v9zM6.5 12H8v-2h2V8.5H6.5V12zm9.5 2h-2v1.5h3.5V12H16v2z" }) });
// packages/icons/build-module/library/audio.mjs
var import_primitives10 = __toESM(require_primitives(), 1);
var import_jsx_runtime12 = __toESM(require_jsx_runtime(), 1);
var audio_default = /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(import_primitives10.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(import_primitives10.Path, { d: "M17.7 4.3c-1.2 0-2.8 0-3.8 1-.6.6-.9 1.5-.9 2.6V14c-.6-.6-1.5-1-2.5-1C8.6 13 7 14.6 7 16.5S8.6 20 10.5 20c1.5 0 2.8-1 3.3-2.3.5-.8.7-1.8.7-2.5V7.9c0-.7.2-1.2.5-1.6.6-.6 1.8-.6 2.8-.6h.3V4.3h-.4z" }) });
// packages/icons/build-module/library/block-default.mjs
var import_primitives11 = __toESM(require_primitives(), 1);
var import_jsx_runtime13 = __toESM(require_jsx_runtime(), 1);
var block_default_default = /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_primitives11.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_primitives11.Path, { d: "M19 8h-1V6h-5v2h-2V6H6v2H5c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-8c0-1.1-.9-2-2-2zm.5 10c0 .3-.2.5-.5.5H5c-.3 0-.5-.2-.5-.5v-8c0-.3.2-.5.5-.5h14c.3 0 .5.2.5.5v8z" }) });
// packages/icons/build-module/library/category.mjs
var import_primitives12 = __toESM(require_primitives(), 1);
var import_jsx_runtime14 = __toESM(require_jsx_runtime(), 1);
var category_default = /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_primitives12.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_primitives12.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M6 5.5h3a.5.5 0 01.5.5v3a.5.5 0 01-.5.5H6a.5.5 0 01-.5-.5V6a.5.5 0 01.5-.5zM4 6a2 2 0 012-2h3a2 2 0 012 2v3a2 2 0 01-2 2H6a2 2 0 01-2-2V6zm11-.5h3a.5.5 0 01.5.5v3a.5.5 0 01-.5.5h-3a.5.5 0 01-.5-.5V6a.5.5 0 01.5-.5zM13 6a2 2 0 012-2h3a2 2 0 012 2v3a2 2 0 01-2 2h-3a2 2 0 01-2-2V6zm5 8.5h-3a.5.5 0 00-.5.5v3a.5.5 0 00.5.5h3a.5.5 0 00.5-.5v-3a.5.5 0 00-.5-.5zM15 13a2 2 0 00-2 2v3a2 2 0 002 2h3a2 2 0 002-2v-3a2 2 0 00-2-2h-3zm-9 1.5h3a.5.5 0 01.5.5v3a.5.5 0 01-.5.5H6a.5.5 0 01-.5-.5v-3a.5.5 0 01.5-.5zM4 15a2 2 0 012-2h3a2 2 0 012 2v3a2 2 0 01-2 2H6a2 2 0 01-2-2v-3z" }) });
// packages/icons/build-module/library/caution.mjs
var import_primitives13 = __toESM(require_primitives(), 1);
var import_jsx_runtime15 = __toESM(require_jsx_runtime(), 1);
var caution_default = /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(import_primitives13.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(import_primitives13.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M5.5 12a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0ZM12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16Zm-.75 12v-1.5h1.5V16h-1.5Zm0-8v5h1.5V8h-1.5Z" }) });
// packages/icons/build-module/library/check.mjs
var import_primitives14 = __toESM(require_primitives(), 1);
var import_jsx_runtime16 = __toESM(require_jsx_runtime(), 1);
var check_default = /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(import_primitives14.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(import_primitives14.Path, { d: "M16.5 7.5 10 13.9l-2.5-2.4-1 1 3.5 3.6 7.5-7.6z" }) });
// packages/icons/build-module/library/chevron-down.mjs
var import_primitives15 = __toESM(require_primitives(), 1);
var import_jsx_runtime17 = __toESM(require_jsx_runtime(), 1);
var chevron_down_default = /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(import_primitives15.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(import_primitives15.Path, { d: "M17.5 11.6L12 16l-5.5-4.4.9-1.2L12 14l4.5-3.6 1 1.2z" }) });
// packages/icons/build-module/library/chevron-left-small.mjs
var import_primitives16 = __toESM(require_primitives(), 1);
var import_jsx_runtime18 = __toESM(require_jsx_runtime(), 1);
var chevron_left_small_default = /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(import_primitives16.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(import_primitives16.Path, { d: "m13.1 16-3.4-4 3.4-4 1.1 1-2.6 3 2.6 3-1.1 1z" }) });
// packages/icons/build-module/library/chevron-left.mjs
var import_primitives17 = __toESM(require_primitives(), 1);
var import_jsx_runtime19 = __toESM(require_jsx_runtime(), 1);
var chevron_left_default = /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(import_primitives17.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(import_primitives17.Path, { d: "M14.6 7l-1.2-1L8 12l5.4 6 1.2-1-4.6-5z" }) });
// packages/icons/build-module/library/chevron-right-small.mjs
var import_primitives18 = __toESM(require_primitives(), 1);
var import_jsx_runtime20 = __toESM(require_jsx_runtime(), 1);
var chevron_right_small_default = /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(import_primitives18.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(import_primitives18.Path, { d: "M10.8622 8.04053L14.2805 12.0286L10.8622 16.0167L9.72327 15.0405L12.3049 12.0286L9.72327 9.01672L10.8622 8.04053Z" }) });
// packages/icons/build-module/library/chevron-right.mjs
var import_primitives19 = __toESM(require_primitives(), 1);
var import_jsx_runtime21 = __toESM(require_jsx_runtime(), 1);
var chevron_right_default = /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(import_primitives19.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(import_primitives19.Path, { d: "M10.6 6L9.4 7l4.6 5-4.6 5 1.2 1 5.4-6z" }) });
// packages/icons/build-module/library/chevron-up.mjs
var import_primitives20 = __toESM(require_primitives(), 1);
var import_jsx_runtime22 = __toESM(require_jsx_runtime(), 1);
var chevron_up_default = /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(import_primitives20.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(import_primitives20.Path, { d: "M6.5 12.4L12 8l5.5 4.4-.9 1.2L12 10l-4.5 3.6-1-1.2z" }) });
// packages/icons/build-module/library/close-small.mjs
var import_primitives21 = __toESM(require_primitives(), 1);
var import_jsx_runtime23 = __toESM(require_jsx_runtime(), 1);
var close_small_default = /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(import_primitives21.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(import_primitives21.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" }) });
// packages/icons/build-module/library/cog.mjs
var import_primitives22 = __toESM(require_primitives(), 1);
var import_jsx_runtime24 = __toESM(require_jsx_runtime(), 1);
var cog_default = /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(import_primitives22.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(import_primitives22.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M10.289 4.836A1 1 0 0111.275 4h1.306a1 1 0 01.987.836l.244 1.466c.787.26 1.503.679 2.108 1.218l1.393-.522a1 1 0 011.216.437l.653 1.13a1 1 0 01-.23 1.273l-1.148.944a6.025 6.025 0 010 2.435l1.149.946a1 1 0 01.23 1.272l-.653 1.13a1 1 0 01-1.216.437l-1.394-.522c-.605.54-1.32.958-2.108 1.218l-.244 1.466a1 1 0 01-.987.836h-1.306a1 1 0 01-.986-.836l-.244-1.466a5.995 5.995 0 01-2.108-1.218l-1.394.522a1 1 0 01-1.217-.436l-.653-1.131a1 1 0 01.23-1.272l1.149-.946a6.026 6.026 0 010-2.435l-1.148-.944a1 1 0 01-.23-1.272l.653-1.131a1 1 0 011.217-.437l1.393.522a5.994 5.994 0 012.108-1.218l.244-1.466zM14.929 12a3 3 0 11-6 0 3 3 0 016 0z" }) });
// packages/icons/build-module/library/copy-small.mjs
var import_primitives23 = __toESM(require_primitives(), 1);
var import_jsx_runtime25 = __toESM(require_jsx_runtime(), 1);
var copy_small_default = /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(import_primitives23.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(import_primitives23.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M5.625 5.5h9.75c.069 0 .125.056.125.125v9.75a.125.125 0 0 1-.125.125h-9.75a.125.125 0 0 1-.125-.125v-9.75c0-.069.056-.125.125-.125ZM4 5.625C4 4.728 4.728 4 5.625 4h9.75C16.273 4 17 4.728 17 5.625v9.75c0 .898-.727 1.625-1.625 1.625h-9.75A1.625 1.625 0 0 1 4 15.375v-9.75Zm14.5 11.656v-9H20v9C20 18.8 18.77 20 17.251 20H6.25v-1.5h11.001c.69 0 1.249-.528 1.249-1.219Z" }) });
// packages/icons/build-module/library/copy.mjs
var import_primitives24 = __toESM(require_primitives(), 1);
var import_jsx_runtime26 = __toESM(require_jsx_runtime(), 1);
var copy_default = /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(import_primitives24.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(import_primitives24.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M5 4.5h11a.5.5 0 0 1 .5.5v11a.5.5 0 0 1-.5.5H5a.5.5 0 0 1-.5-.5V5a.5.5 0 0 1 .5-.5ZM3 5a2 2 0 0 1 2-2h11a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5Zm17 3v10.75c0 .69-.56 1.25-1.25 1.25H6v1.5h12.75a2.75 2.75 0 0 0 2.75-2.75V8H20Z" }) });
// packages/icons/build-module/library/corner-all.mjs
var import_primitives25 = __toESM(require_primitives(), 1);
var import_jsx_runtime27 = __toESM(require_jsx_runtime(), 1);
var corner_all_default = /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(import_primitives25.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(import_primitives25.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M5.75 6A.25.25 0 0 1 6 5.75h3v-1.5H6A1.75 1.75 0 0 0 4.25 6v3h1.5V6ZM18 18.25h-3v1.5h3A1.75 1.75 0 0 0 19.75 18v-3h-1.5v3a.25.25 0 0 1-.25.25ZM18.25 9V6a.25.25 0 0 0-.25-.25h-3v-1.5h3c.966 0 1.75.784 1.75 1.75v3h-1.5Zm-12.5 9v-3h-1.5v3c0 .966.784 1.75 1.75 1.75h3v-1.5H6a.25.25 0 0 1-.25-.25Z" }) });
// packages/icons/build-module/library/corner-bottom-left.mjs
var import_primitives26 = __toESM(require_primitives(), 1);
var import_jsx_runtime28 = __toESM(require_jsx_runtime(), 1);
var corner_bottom_left_default = /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(import_primitives26.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: [
/* @__PURE__ */ (0, import_jsx_runtime28.jsx)(import_primitives26.G, { opacity: ".25", children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(import_primitives26.Path, { d: "M5.75 6A.25.25 0 0 1 6 5.75h3v-1.5H6A1.75 1.75 0 0 0 4.25 6v3h1.5V6ZM18 18.25h-3v1.5h3A1.75 1.75 0 0 0 19.75 18v-3h-1.5v3a.25.25 0 0 1-.25.25ZM18.25 9V6a.25.25 0 0 0-.25-.25h-3v-1.5h3c.966 0 1.75.784 1.75 1.75v3h-1.5ZM5.75 18v-3h-1.5v3c0 .966.784 1.75 1.75 1.75h3v-1.5H6a.25.25 0 0 1-.25-.25Z" }) }),
/* @__PURE__ */ (0, import_jsx_runtime28.jsx)(import_primitives26.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M5.75 15v3c0 .138.112.25.25.25h3v1.5H6A1.75 1.75 0 0 1 4.25 18v-3h1.5Z" })
] });
// packages/icons/build-module/library/corner-bottom-right.mjs
var import_primitives27 = __toESM(require_primitives(), 1);
var import_jsx_runtime29 = __toESM(require_jsx_runtime(), 1);
var corner_bottom_right_default = /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(import_primitives27.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: [
/* @__PURE__ */ (0, import_jsx_runtime29.jsx)(import_primitives27.G, { opacity: ".25", children: /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(import_primitives27.Path, { d: "M5.75 6A.25.25 0 0 1 6 5.75h3v-1.5H6A1.75 1.75 0 0 0 4.25 6v3h1.5V6ZM18 18.25h-3v1.5h3A1.75 1.75 0 0 0 19.75 18v-3h-1.5v3a.25.25 0 0 1-.25.25ZM18.25 9V6a.25.25 0 0 0-.25-.25h-3v-1.5h3c.966 0 1.75.784 1.75 1.75v3h-1.5ZM5.75 18v-3h-1.5v3c0 .966.784 1.75 1.75 1.75h3v-1.5H6a.25.25 0 0 1-.25-.25Z" }) }),
/* @__PURE__ */ (0, import_jsx_runtime29.jsx)(import_primitives27.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M15 18.25h3a.25.25 0 0 0 .25-.25v-3h1.5v3A1.75 1.75 0 0 1 18 19.75h-3v-1.5Z" })
] });
// packages/icons/build-module/library/corner-top-left.mjs
var import_primitives28 = __toESM(require_primitives(), 1);
var import_jsx_runtime30 = __toESM(require_jsx_runtime(), 1);
var corner_top_left_default = /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(import_primitives28.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: [
/* @__PURE__ */ (0, import_jsx_runtime30.jsx)(import_primitives28.G, { opacity: ".25", children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(import_primitives28.Path, { d: "M5.75 6A.25.25 0 0 1 6 5.75h3v-1.5H6A1.75 1.75 0 0 0 4.25 6v3h1.5V6ZM18 18.25h-3v1.5h3A1.75 1.75 0 0 0 19.75 18v-3h-1.5v3a.25.25 0 0 1-.25.25ZM18.25 9V6a.25.25 0 0 0-.25-.25h-3v-1.5h3c.966 0 1.75.784 1.75 1.75v3h-1.5ZM5.75 18v-3h-1.5v3c0 .966.784 1.75 1.75 1.75h3v-1.5H6a.25.25 0 0 1-.25-.25Z" }) }),
/* @__PURE__ */ (0, import_jsx_runtime30.jsx)(import_primitives28.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M6 5.75a.25.25 0 0 0-.25.25v3h-1.5V6c0-.966.784-1.75 1.75-1.75h3v1.5H6Z" })
] });
// packages/icons/build-module/library/corner-top-right.mjs
var import_primitives29 = __toESM(require_primitives(), 1);
var import_jsx_runtime31 = __toESM(require_jsx_runtime(), 1);
var corner_top_right_default = /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(import_primitives29.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: [
/* @__PURE__ */ (0, import_jsx_runtime31.jsx)(import_primitives29.G, { opacity: ".25", children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(import_primitives29.Path, { d: "M5.75 6A.25.25 0 0 1 6 5.75h3v-1.5H6A1.75 1.75 0 0 0 4.25 6v3h1.5V6ZM18 18.25h-3v1.5h3A1.75 1.75 0 0 0 19.75 18v-3h-1.5v3a.25.25 0 0 1-.25.25ZM18.25 9V6a.25.25 0 0 0-.25-.25h-3v-1.5h3c.966 0 1.75.784 1.75 1.75v3h-1.5ZM5.75 18v-3h-1.5v3c0 .966.784 1.75 1.75 1.75h3v-1.5H6a.25.25 0 0 1-.25-.25Z" }) }),
/* @__PURE__ */ (0, import_jsx_runtime31.jsx)(import_primitives29.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M18.25 9V6a.25.25 0 0 0-.25-.25h-3v-1.5h3c.966 0 1.75.784 1.75 1.75v3h-1.5Z" })
] });
// packages/icons/build-module/library/desktop.mjs
var import_primitives30 = __toESM(require_primitives(), 1);
var import_jsx_runtime32 = __toESM(require_jsx_runtime(), 1);
var desktop_default = /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(import_primitives30.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(import_primitives30.Path, { d: "M20.5 16h-.7V8c0-1.1-.9-2-2-2H6.2c-1.1 0-2 .9-2 2v8h-.7c-.8 0-1.5.7-1.5 1.5h20c0-.8-.7-1.5-1.5-1.5zM5.7 8c0-.3.2-.5.5-.5h11.6c.3 0 .5.2.5.5v7.6H5.7V8z" }) });
// packages/icons/build-module/library/drag-handle.mjs
var import_primitives31 = __toESM(require_primitives(), 1);
var import_jsx_runtime33 = __toESM(require_jsx_runtime(), 1);
var drag_handle_default = /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(import_primitives31.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(import_primitives31.Path, { d: "M8 7h2V5H8v2zm0 6h2v-2H8v2zm0 6h2v-2H8v2zm6-14v2h2V5h-2zm0 8h2v-2h-2v2zm0 6h2v-2h-2v2z" }) });
// packages/icons/build-module/library/envelope.mjs
var import_primitives32 = __toESM(require_primitives(), 1);
var import_jsx_runtime34 = __toESM(require_jsx_runtime(), 1);
var envelope_default = /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(import_primitives32.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(import_primitives32.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M3 7c0-1.1.9-2 2-2h14a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Zm2-.5h14c.3 0 .5.2.5.5v1L12 13.5 4.5 7.9V7c0-.3.2-.5.5-.5Zm-.5 3.3V17c0 .3.2.5.5.5h14c.3 0 .5-.2.5-.5V9.8L12 15.4 4.5 9.8Z" }) });
// packages/icons/build-module/library/error.mjs
var import_primitives33 = __toESM(require_primitives(), 1);
var import_jsx_runtime35 = __toESM(require_jsx_runtime(), 1);
var error_default = /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(import_primitives33.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(import_primitives33.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M12.218 5.377a.25.25 0 0 0-.436 0l-7.29 12.96a.25.25 0 0 0 .218.373h14.58a.25.25 0 0 0 .218-.372l-7.29-12.96Zm-1.743-.735c.669-1.19 2.381-1.19 3.05 0l7.29 12.96a1.75 1.75 0 0 1-1.525 2.608H4.71a1.75 1.75 0 0 1-1.525-2.608l7.29-12.96ZM12.75 17.46h-1.5v-1.5h1.5v1.5Zm-1.5-3h1.5v-5h-1.5v5Z" }) });
// packages/icons/build-module/library/external.mjs
var import_primitives34 = __toESM(require_primitives(), 1);
var import_jsx_runtime36 = __toESM(require_jsx_runtime(), 1);
var external_default = /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(import_primitives34.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(import_primitives34.Path, { d: "M19.5 4.5h-7V6h4.44l-5.97 5.97 1.06 1.06L18 7.06v4.44h1.5v-7Zm-13 1a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-3H17v3a.5.5 0 0 1-.5.5h-10a.5.5 0 0 1-.5-.5v-10a.5.5 0 0 1 .5-.5h3V5.5h-3Z" }) });
// packages/icons/build-module/library/file.mjs
var import_primitives35 = __toESM(require_primitives(), 1);
var import_jsx_runtime37 = __toESM(require_jsx_runtime(), 1);
var file_default = /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(import_primitives35.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(import_primitives35.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M12.848 8a1 1 0 0 1-.914-.594l-.723-1.63a.5.5 0 0 0-.447-.276H5a.5.5 0 0 0-.5.5v11.5a.5.5 0 0 0 .5.5h14a.5.5 0 0 0 .5-.5v-9A.5.5 0 0 0 19 8h-6.152Zm.612-1.5a.5.5 0 0 1-.462-.31l-.445-1.084A2 2 0 0 0 10.763 4H5a2 2 0 0 0-2 2v11.5a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-9a2 2 0 0 0-2-2h-5.54Z" }) });
// packages/icons/build-module/library/filter.mjs
var import_primitives36 = __toESM(require_primitives(), 1);
var import_jsx_runtime38 = __toESM(require_jsx_runtime(), 1);
var filter_default = /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(import_primitives36.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(import_primitives36.Path, { d: "M12 4 4 19h16L12 4zm0 3.2 5.5 10.3H12V7.2z" }) });
// packages/icons/build-module/library/format-capitalize.mjs
var import_primitives37 = __toESM(require_primitives(), 1);
var import_jsx_runtime39 = __toESM(require_jsx_runtime(), 1);
var format_capitalize_default = /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(import_primitives37.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(import_primitives37.Path, { d: "M7.1 6.8L3.1 18h1.6l1.1-3h4.3l1.1 3h1.6l-4-11.2H7.1zm-.8 6.8L8 8.9l1.7 4.7H6.3zm14.5-1.5c-.3-.6-.7-1.1-1.2-1.5-.6-.4-1.2-.6-1.9-.6-.5 0-.9.1-1.4.3-.4.2-.8.5-1.1.8V6h-1.4v12h1.3l.2-1c.2.4.6.6 1 .8.4.2.9.3 1.4.3.7 0 1.2-.2 1.8-.5.5-.4 1-.9 1.3-1.5.3-.6.5-1.3.5-2.1-.1-.6-.2-1.3-.5-1.9zm-1.7 4c-.4.5-.9.8-1.6.8s-1.2-.2-1.7-.7c-.4-.5-.7-1.2-.7-2.1 0-.9.2-1.6.7-2.1.4-.5 1-.7 1.7-.7s1.2.3 1.6.8c.4.5.6 1.2.6 2 .1.8-.2 1.4-.6 2z" }) });
// packages/icons/build-module/library/format-lowercase.mjs
var import_primitives38 = __toESM(require_primitives(), 1);
var import_jsx_runtime40 = __toESM(require_jsx_runtime(), 1);
var format_lowercase_default = /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(import_primitives38.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(import_primitives38.Path, { d: "M11 16.8c-.1-.1-.2-.3-.3-.5v-2.6c0-.9-.1-1.7-.3-2.2-.2-.5-.5-.9-.9-1.2-.4-.2-.9-.3-1.6-.3-.5 0-1 .1-1.5.2s-.9.3-1.2.6l.2 1.2c.4-.3.7-.4 1.1-.5.3-.1.7-.2 1-.2.6 0 1 .1 1.3.4.3.2.4.7.4 1.4-1.2 0-2.3.2-3.3.7s-1.4 1.1-1.4 2.1c0 .7.2 1.2.7 1.6.4.4 1 .6 1.8.6.9 0 1.7-.4 2.4-1.2.1.3.2.5.4.7.1.2.3.3.6.4.3.1.6.1 1.1.1h.1l.2-1.2h-.1c-.4.1-.6 0-.7-.1zM9.2 16c-.2.3-.5.6-.9.8-.3.1-.7.2-1.1.2-.4 0-.7-.1-.9-.3-.2-.2-.3-.5-.3-.9 0-.6.2-1 .7-1.3.5-.3 1.3-.4 2.5-.5v2zm10.6-3.9c-.3-.6-.7-1.1-1.2-1.5-.6-.4-1.2-.6-1.9-.6-.5 0-.9.1-1.4.3-.4.2-.8.5-1.1.8V6h-1.4v12h1.3l.2-1c.2.4.6.6 1 .8.4.2.9.3 1.4.3.7 0 1.2-.2 1.8-.5.5-.4 1-.9 1.3-1.5.3-.6.5-1.3.5-2.1-.1-.6-.2-1.3-.5-1.9zm-1.7 4c-.4.5-.9.8-1.6.8s-1.2-.2-1.7-.7c-.4-.5-.7-1.2-.7-2.1 0-.9.2-1.6.7-2.1.4-.5 1-.7 1.7-.7s1.2.3 1.6.8c.4.5.6 1.2.6 2s-.2 1.4-.6 2z" }) });
// packages/icons/build-module/library/format-strikethrough.mjs
var import_primitives39 = __toESM(require_primitives(), 1);
var import_jsx_runtime41 = __toESM(require_jsx_runtime(), 1);
var format_strikethrough_default = /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(import_primitives39.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(import_primitives39.Path, { d: "M9.1 9v-.5c0-.6.2-1.1.7-1.4.5-.3 1.2-.5 2-.5.7 0 1.4.1 2.1.3.7.2 1.4.5 2.1.9l.2-1.9c-.6-.3-1.2-.5-1.9-.7-.8-.1-1.6-.2-2.4-.2-1.5 0-2.7.3-3.6 1-.8.7-1.2 1.5-1.2 2.6V9h2zM20 12H4v1h8.3c.3.1.6.2.8.3.5.2.9.5 1.1.8.3.3.4.7.4 1.2 0 .7-.2 1.1-.8 1.5-.5.3-1.2.5-2.1.5-.8 0-1.6-.1-2.4-.3-.8-.2-1.5-.5-2.2-.8L7 18.1c.5.2 1.2.4 2 .6.8.2 1.6.3 2.4.3 1.7 0 3-.3 3.9-1 .9-.7 1.3-1.6 1.3-2.8 0-.9-.2-1.7-.7-2.2H20v-1z" }) });
// packages/icons/build-module/library/format-underline.mjs
var import_primitives40 = __toESM(require_primitives(), 1);
var import_jsx_runtime42 = __toESM(require_jsx_runtime(), 1);
var format_underline_default = /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(import_primitives40.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(import_primitives40.Path, { d: "M7 18v1h10v-1H7zm5-2c1.5 0 2.6-.4 3.4-1.2.8-.8 1.1-2 1.1-3.5V5H15v5.8c0 1.2-.2 2.1-.6 2.8-.4.7-1.2 1-2.4 1s-2-.3-2.4-1c-.4-.7-.6-1.6-.6-2.8V5H7.5v6.2c0 1.5.4 2.7 1.1 3.5.8.9 1.9 1.3 3.4 1.3z" }) });
// packages/icons/build-module/library/format-uppercase.mjs
var import_primitives41 = __toESM(require_primitives(), 1);
var import_jsx_runtime43 = __toESM(require_jsx_runtime(), 1);
var format_uppercase_default = /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(import_primitives41.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(import_primitives41.Path, { d: "M6.1 6.8L2.1 18h1.6l1.1-3h4.3l1.1 3h1.6l-4-11.2H6.1zm-.8 6.8L7 8.9l1.7 4.7H5.3zm15.1-.7c-.4-.5-.9-.8-1.6-1 .4-.2.7-.5.8-.9.2-.4.3-.9.3-1.4 0-.9-.3-1.6-.8-2-.6-.5-1.3-.7-2.4-.7h-3.5V18h4.2c1.1 0 2-.3 2.6-.8.6-.6 1-1.4 1-2.4-.1-.8-.3-1.4-.6-1.9zm-5.7-4.7h1.8c.6 0 1.1.1 1.4.4.3.2.5.7.5 1.3 0 .6-.2 1.1-.5 1.3-.3.2-.8.4-1.4.4h-1.8V8.2zm4 8c-.4.3-.9.5-1.5.5h-2.6v-3.8h2.6c1.4 0 2 .6 2 1.9.1.6-.1 1-.5 1.4z" }) });
// packages/icons/build-module/library/full-height.mjs
var import_primitives42 = __toESM(require_primitives(), 1);
var import_jsx_runtime44 = __toESM(require_jsx_runtime(), 1);
var full_height_default = /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(import_primitives42.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(import_primitives42.Path, { d: "M12.75 19.45 15 17.5l1 1.1-4 3.4-4-3.4 1-1.1 2.25 1.95V14.5h1.5v4.95ZM19 12.75H5v-1.5h14v1.5ZM16 5.4l-1 1.1-2.25-1.95V9.5h-1.5V4.55L9 6.5 8 5.4 12 2l4 3.4Z" }) });
// packages/icons/build-module/library/fullscreen.mjs
var import_primitives43 = __toESM(require_primitives(), 1);
var import_jsx_runtime45 = __toESM(require_jsx_runtime(), 1);
var fullscreen_default = /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(import_primitives43.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(import_primitives43.Path, { d: "M6 4a2 2 0 0 0-2 2v3h1.5V6a.5.5 0 0 1 .5-.5h3V4H6Zm3 14.5H6a.5.5 0 0 1-.5-.5v-3H4v3a2 2 0 0 0 2 2h3v-1.5Zm6 1.5v-1.5h3a.5.5 0 0 0 .5-.5v-3H20v3a2 2 0 0 1-2 2h-3Zm3-16a2 2 0 0 1 2 2v3h-1.5V6a.5.5 0 0 0-.5-.5h-3V4h3Z" }) });
// packages/icons/build-module/library/globe.mjs
var import_primitives44 = __toESM(require_primitives(), 1);
var import_jsx_runtime46 = __toESM(require_jsx_runtime(), 1);
var globe_default = /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_primitives44.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_primitives44.Path, { d: "M12 4c-4.4 0-8 3.6-8 8s3.6 8 8 8 8-3.6 8-8-3.6-8-8-8Zm6.5 8c0 .6 0 1.2-.2 1.8h-2.7c0-.6.2-1.1.2-1.8s0-1.2-.2-1.8h2.7c.2.6.2 1.1.2 1.8Zm-.9-3.2h-2.4c-.3-.9-.7-1.8-1.1-2.4-.1-.2-.2-.4-.3-.5 1.6.5 3 1.6 3.8 3ZM12.8 17c-.3.5-.6 1-.8 1.3-.2-.3-.5-.8-.8-1.3-.3-.5-.6-1.1-.8-1.7h3.3c-.2.6-.5 1.2-.8 1.7Zm-2.9-3.2c-.1-.6-.2-1.1-.2-1.8s0-1.2.2-1.8H14c.1.6.2 1.1.2 1.8s0 1.2-.2 1.8H9.9ZM11.2 7c.3-.5.6-1 .8-1.3.2.3.5.8.8 1.3.3.5.6 1.1.8 1.7h-3.3c.2-.6.5-1.2.8-1.7Zm-1-1.2c-.1.2-.2.3-.3.5-.4.7-.8 1.5-1.1 2.4H6.4c.8-1.4 2.2-2.5 3.8-3Zm-1.8 8H5.7c-.2-.6-.2-1.1-.2-1.8s0-1.2.2-1.8h2.7c0 .6-.2 1.1-.2 1.8s0 1.2.2 1.8Zm-2 1.4h2.4c.3.9.7 1.8 1.1 2.4.1.2.2.4.3.5-1.6-.5-3-1.6-3.8-3Zm7.4 3c.1-.2.2-.3.3-.5.4-.7.8-1.5 1.1-2.4h2.4c-.8 1.4-2.2 2.5-3.8 3Z" }) });
// packages/icons/build-module/library/grid.mjs
var import_primitives45 = __toESM(require_primitives(), 1);
var import_jsx_runtime47 = __toESM(require_jsx_runtime(), 1);
var grid_default = /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(import_primitives45.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(import_primitives45.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "m3 5c0-1.10457.89543-2 2-2h13.5c1.1046 0 2 .89543 2 2v13.5c0 1.1046-.8954 2-2 2h-13.5c-1.10457 0-2-.8954-2-2zm2-.5h6v6.5h-6.5v-6c0-.27614.22386-.5.5-.5zm-.5 8v6c0 .2761.22386.5.5.5h6v-6.5zm8 0v6.5h6c.2761 0 .5-.2239.5-.5v-6zm0-8v6.5h6.5v-6c0-.27614-.2239-.5-.5-.5z" }) });
// packages/icons/build-module/library/group.mjs
var import_primitives46 = __toESM(require_primitives(), 1);
var import_jsx_runtime48 = __toESM(require_jsx_runtime(), 1);
var group_default = /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(import_primitives46.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(import_primitives46.Path, { d: "M18 4h-7c-1.1 0-2 .9-2 2v3H6c-1.1 0-2 .9-2 2v7c0 1.1.9 2 2 2h7c1.1 0 2-.9 2-2v-3h3c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-4.5 14c0 .3-.2.5-.5.5H6c-.3 0-.5-.2-.5-.5v-7c0-.3.2-.5.5-.5h3V13c0 1.1.9 2 2 2h2.5v3zm0-4.5H11c-.3 0-.5-.2-.5-.5v-2.5H13c.3 0 .5.2.5.5v2.5zm5-.5c0 .3-.2.5-.5.5h-3V11c0-1.1-.9-2-2-2h-2.5V6c0-.3.2-.5.5-.5h7c.3 0 .5.2.5.5v7z" }) });
// packages/icons/build-module/library/heading-level-1.mjs
var import_primitives47 = __toESM(require_primitives(), 1);
var import_jsx_runtime49 = __toESM(require_jsx_runtime(), 1);
var heading_level_1_default = /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(import_primitives47.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(import_primitives47.Path, { d: "M17.6 7c-.6.9-1.5 1.7-2.6 2v1h2v7h2V7h-1.4zM11 11H7V7H5v10h2v-4h4v4h2V7h-2v4z" }) });
// packages/icons/build-module/library/heading-level-2.mjs
var import_primitives48 = __toESM(require_primitives(), 1);
var import_jsx_runtime50 = __toESM(require_jsx_runtime(), 1);
var heading_level_2_default = /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(import_primitives48.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(import_primitives48.Path, { d: "M9 11.1H5v-4H3v10h2v-4h4v4h2v-10H9v4zm8 4c.5-.4.6-.6 1.1-1.1.4-.4.8-.8 1.2-1.3.3-.4.6-.8.9-1.3.2-.4.3-.8.3-1.3 0-.4-.1-.9-.3-1.3-.2-.4-.4-.7-.8-1-.3-.3-.7-.5-1.2-.6-.5-.2-1-.2-1.5-.2-.4 0-.7 0-1.1.1-.3.1-.7.2-1 .3-.3.1-.6.3-.9.5-.3.2-.6.4-.8.7l1.2 1.2c.3-.3.6-.5 1-.7.4-.2.7-.3 1.2-.3s.9.1 1.3.4c.3.3.5.7.5 1.1 0 .4-.1.8-.4 1.1-.3.5-.6.9-1 1.2-.4.4-1 .9-1.6 1.4-.6.5-1.4 1.1-2.2 1.6v1.5h8v-2H17z" }) });
// packages/icons/build-module/library/heading-level-3.mjs
var import_primitives49 = __toESM(require_primitives(), 1);
var import_jsx_runtime51 = __toESM(require_jsx_runtime(), 1);
var heading_level_3_default = /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(import_primitives49.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(import_primitives49.Path, { d: "M9 11H5V7H3v10h2v-4h4v4h2V7H9v4zm11.3 1.7c-.4-.4-1-.7-1.6-.8v-.1c.6-.2 1.1-.5 1.5-.9.3-.4.5-.8.5-1.3 0-.4-.1-.8-.3-1.1-.2-.3-.5-.6-.8-.8-.4-.2-.8-.4-1.2-.5-.6-.1-1.1-.2-1.6-.2-.6 0-1.3.1-1.8.3s-1.1.5-1.6.9l1.2 1.4c.4-.2.7-.4 1.1-.6.3-.2.7-.3 1.1-.3.4 0 .8.1 1.1.3.3.2.4.5.4.8 0 .4-.2.7-.6.9-.7.3-1.5.5-2.2.4v1.6c.5 0 1 0 1.5.1.3.1.7.2 1 .3.2.1.4.2.5.4s.1.4.1.6c0 .3-.2.7-.5.8-.4.2-.9.3-1.4.3s-1-.1-1.4-.3c-.4-.2-.8-.4-1.2-.7L13 15.6c.5.4 1 .8 1.6 1 .7.3 1.5.4 2.3.4.6 0 1.1-.1 1.6-.2.4-.1.9-.2 1.3-.5.4-.2.7-.5.9-.9.2-.4.3-.8.3-1.2 0-.6-.3-1.1-.7-1.5z" }) });
// packages/icons/build-module/library/heading-level-4.mjs
var import_primitives50 = __toESM(require_primitives(), 1);
var import_jsx_runtime52 = __toESM(require_jsx_runtime(), 1);
var heading_level_4_default = /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(import_primitives50.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(import_primitives50.Path, { d: "M20 13V7h-3l-4 6v2h5v2h2v-2h1v-2h-1zm-2 0h-2.8L18 9v4zm-9-2H5V7H3v10h2v-4h4v4h2V7H9v4z" }) });
// packages/icons/build-module/library/heading-level-5.mjs
var import_primitives51 = __toESM(require_primitives(), 1);
var import_jsx_runtime53 = __toESM(require_jsx_runtime(), 1);
var heading_level_5_default = /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(import_primitives51.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(import_primitives51.Path, { d: "M9 11H5V7H3v10h2v-4h4v4h2V7H9v4zm11.7 1.2c-.2-.3-.5-.7-.8-.9-.3-.3-.7-.5-1.1-.6-.5-.1-.9-.2-1.4-.2-.2 0-.5.1-.7.1-.2.1-.5.1-.7.2l.1-1.9h4.3V7H14l-.3 5 1 .6.5-.2.4-.1c.1-.1.3-.1.4-.1h.5c.5 0 1 .1 1.4.4.4.2.6.7.6 1.1 0 .4-.2.8-.6 1.1-.4.3-.9.4-1.4.4-.4 0-.9-.1-1.3-.3-.4-.2-.7-.4-1.1-.7 0 0-1.1 1.4-1 1.5.5.4 1 .8 1.6 1 .7.3 1.5.4 2.3.4.5 0 1-.1 1.5-.3s.9-.4 1.3-.7c.4-.3.7-.7.9-1.1s.3-.9.3-1.4-.1-1-.3-1.4z" }) });
// packages/icons/build-module/library/heading-level-6.mjs
var import_primitives52 = __toESM(require_primitives(), 1);
var import_jsx_runtime54 = __toESM(require_jsx_runtime(), 1);
var heading_level_6_default = /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(import_primitives52.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(import_primitives52.Path, { d: "M20.7 12.4c-.2-.3-.4-.6-.7-.9s-.6-.5-1-.6c-.4-.2-.8-.2-1.2-.2-.5 0-.9.1-1.3.3s-.8.5-1.2.8c0-.5 0-.9.2-1.4l.6-.9c.2-.2.5-.4.8-.5.6-.2 1.3-.2 1.9 0 .3.1.6.3.8.5 0 0 1.3-1.3 1.3-1.4-.4-.3-.9-.6-1.4-.8-.6-.2-1.3-.3-2-.3-.6 0-1.1.1-1.7.4-.5.2-1 .5-1.4.9-.4.4-.8 1-1 1.6-.3.7-.4 1.5-.4 2.3s.1 1.5.3 2.1c.2.6.6 1.1 1 1.5.4.4.9.7 1.4.9 1 .3 2 .3 3 0 .4-.1.8-.3 1.2-.6.3-.3.6-.6.8-1 .2-.5.3-.9.3-1.4s-.1-.9-.3-1.3zm-2 2.1c-.1.2-.3.4-.4.5-.1.1-.3.2-.5.2-.2.1-.4.1-.6.1-.2.1-.5 0-.7-.1-.2 0-.3-.2-.5-.3-.1-.2-.3-.4-.4-.6-.2-.3-.3-.7-.3-1 .3-.3.6-.5 1-.7.3-.1.7-.2 1-.2.4 0 .8.1 1.1.3.3.3.4.7.4 1.1 0 .2 0 .5-.1.7zM9 11H5V7H3v10h2v-4h4v4h2V7H9v4z" }) });
// packages/icons/build-module/library/home.mjs
var import_primitives53 = __toESM(require_primitives(), 1);
var import_jsx_runtime55 = __toESM(require_jsx_runtime(), 1);
var home_default = /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(import_primitives53.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(import_primitives53.Path, { d: "M12 4L4 7.9V20h16V7.9L12 4zm6.5 14.5H14V13h-4v5.5H5.5V8.8L12 5.7l6.5 3.1v9.7z" }) });
// packages/icons/build-module/library/image.mjs
var import_primitives54 = __toESM(require_primitives(), 1);
var import_jsx_runtime56 = __toESM(require_jsx_runtime(), 1);
var image_default = /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(import_primitives54.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(import_primitives54.Path, { d: "M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM5 4.5h14c.3 0 .5.2.5.5v8.4l-3-2.9c-.3-.3-.8-.3-1 0L11.9 14 9 12c-.3-.2-.6-.2-.8 0l-3.6 2.6V5c-.1-.3.1-.5.4-.5zm14 15H5c-.3 0-.5-.2-.5-.5v-2.4l4.1-3 3 1.9c.3.2.7.2.9-.1L16 12l3.5 3.4V19c0 .3-.2.5-.5.5z" }) });
// packages/icons/build-module/library/info.mjs
var import_primitives55 = __toESM(require_primitives(), 1);
var import_jsx_runtime57 = __toESM(require_jsx_runtime(), 1);
var info_default = /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(import_primitives55.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(import_primitives55.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M5.5 12a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0ZM12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16Zm.75 4v1.5h-1.5V8h1.5Zm0 8v-5h-1.5v5h1.5Z" }) });
// packages/icons/build-module/library/justify-bottom.mjs
var import_primitives56 = __toESM(require_primitives(), 1);
var import_jsx_runtime58 = __toESM(require_jsx_runtime(), 1);
var justify_bottom_default = /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(import_primitives56.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(import_primitives56.Path, { d: "M15 4H9v11h6V4zM4 18.5V20h16v-1.5H4z" }) });
// packages/icons/build-module/library/justify-center-vertical.mjs
var import_primitives57 = __toESM(require_primitives(), 1);
var import_jsx_runtime59 = __toESM(require_jsx_runtime(), 1);
var justify_center_vertical_default = /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(import_primitives57.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(import_primitives57.Path, { d: "M20 11h-5V4H9v7H4v1.5h5V20h6v-7.5h5z" }) });
// packages/icons/build-module/library/justify-center.mjs
var import_primitives58 = __toESM(require_primitives(), 1);
var import_jsx_runtime60 = __toESM(require_jsx_runtime(), 1);
var justify_center_default = /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(import_primitives58.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(import_primitives58.Path, { d: "M12.5 15v5H11v-5H4V9h7V4h1.5v5h7v6h-7Z" }) });
// packages/icons/build-module/library/justify-left.mjs
var import_primitives59 = __toESM(require_primitives(), 1);
var import_jsx_runtime61 = __toESM(require_jsx_runtime(), 1);
var justify_left_default = /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(import_primitives59.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(import_primitives59.Path, { d: "M9 9v6h11V9H9zM4 20h1.5V4H4v16z" }) });
// packages/icons/build-module/library/justify-right.mjs
var import_primitives60 = __toESM(require_primitives(), 1);
var import_jsx_runtime62 = __toESM(require_jsx_runtime(), 1);
var justify_right_default = /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(import_primitives60.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(import_primitives60.Path, { d: "M4 15h11V9H4v6zM18.5 4v16H20V4h-1.5z" }) });
// packages/icons/build-module/library/justify-space-between-vertical.mjs
var import_primitives61 = __toESM(require_primitives(), 1);
var import_jsx_runtime63 = __toESM(require_jsx_runtime(), 1);
var justify_space_between_vertical_default = /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(import_primitives61.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(import_primitives61.Path, { d: "M7 4H17V8L7 8V4ZM7 16L17 16V20L7 20V16ZM20 11.25H4V12.75H20V11.25Z" }) });
// packages/icons/build-module/library/justify-space-between.mjs
var import_primitives62 = __toESM(require_primitives(), 1);
var import_jsx_runtime64 = __toESM(require_jsx_runtime(), 1);
var justify_space_between_default = /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(import_primitives62.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(import_primitives62.Path, { d: "M9 15h6V9H9v6zm-5 5h1.5V4H4v16zM18.5 4v16H20V4h-1.5z" }) });
// packages/icons/build-module/library/justify-stretch-vertical.mjs
var import_primitives63 = __toESM(require_primitives(), 1);
var import_jsx_runtime65 = __toESM(require_jsx_runtime(), 1);
var justify_stretch_vertical_default = /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(import_primitives63.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(import_primitives63.Path, { d: "M4 4L20 4L20 5.5L4 5.5L4 4ZM10 7L14 7L14 17L10 17L10 7ZM20 18.5L4 18.5L4 20L20 20L20 18.5Z" }) });
// packages/icons/build-module/library/justify-stretch.mjs
var import_primitives64 = __toESM(require_primitives(), 1);
var import_jsx_runtime66 = __toESM(require_jsx_runtime(), 1);
var justify_stretch_default = /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(import_primitives64.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(import_primitives64.Path, { d: "M4 4H5.5V20H4V4ZM7 10L17 10V14L7 14V10ZM20 4H18.5V20H20V4Z" }) });
// packages/icons/build-module/library/justify-top.mjs
var import_primitives65 = __toESM(require_primitives(), 1);
var import_jsx_runtime67 = __toESM(require_jsx_runtime(), 1);
var justify_top_default = /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(import_primitives65.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(import_primitives65.Path, { d: "M9 20h6V9H9v11zM4 4v1.5h16V4H4z" }) });
// packages/icons/build-module/library/keyboard-return.mjs
var import_primitives66 = __toESM(require_primitives(), 1);
var import_jsx_runtime68 = __toESM(require_jsx_runtime(), 1);
var keyboard_return_default = /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(import_primitives66.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(import_primitives66.Path, { d: "m6.734 16.106 2.176-2.38-1.093-1.028-3.846 4.158 3.846 4.158 1.093-1.028-2.176-2.38h2.811c1.125 0 2.25.03 3.374 0 1.428-.001 3.362-.25 4.963-1.277 1.66-1.065 2.868-2.906 2.868-5.859 0-2.479-1.327-4.896-3.65-5.93-1.82-.813-3.044-.8-4.806-.788l-.567.002v1.5c.184 0 .368 0 .553-.002 1.82-.007 2.704-.014 4.21.657 1.854.827 2.76 2.657 2.76 4.561 0 2.472-.973 3.824-2.178 4.596-1.258.807-2.864 1.04-4.163 1.04h-.02c-1.115.03-2.229 0-3.344 0H6.734Z" }) });
// packages/icons/build-module/library/layout.mjs
var import_primitives67 = __toESM(require_primitives(), 1);
var import_jsx_runtime69 = __toESM(require_jsx_runtime(), 1);
var layout_default = /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(import_primitives67.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(import_primitives67.Path, { d: "M18 5.5H6a.5.5 0 00-.5.5v3h13V6a.5.5 0 00-.5-.5zm.5 5H10v8h8a.5.5 0 00.5-.5v-7.5zm-10 0h-3V18a.5.5 0 00.5.5h2.5v-8zM6 4h12a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V6a2 2 0 012-2z" }) });
// packages/icons/build-module/library/link-off.mjs
var import_primitives68 = __toESM(require_primitives(), 1);
var import_jsx_runtime70 = __toESM(require_jsx_runtime(), 1);
var link_off_default = /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(import_primitives68.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(import_primitives68.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" }) });
// packages/icons/build-module/library/link.mjs
var import_primitives69 = __toESM(require_primitives(), 1);
var import_jsx_runtime71 = __toESM(require_jsx_runtime(), 1);
var link_default = /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(import_primitives69.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(import_primitives69.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" }) });
// packages/icons/build-module/library/list-view.mjs
var import_primitives70 = __toESM(require_primitives(), 1);
var import_jsx_runtime72 = __toESM(require_jsx_runtime(), 1);
var list_view_default = /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(import_primitives70.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(import_primitives70.Path, { d: "M3 6h11v1.5H3V6Zm3.5 5.5h11V13h-11v-1.5ZM21 17H10v1.5h11V17Z" }) });
// packages/icons/build-module/library/lock-outline.mjs
var import_primitives71 = __toESM(require_primitives(), 1);
var import_jsx_runtime73 = __toESM(require_jsx_runtime(), 1);
var lock_outline_default = /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(import_primitives71.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(import_primitives71.Path, { d: "M17 10h-1.2V7c0-2.1-1.7-3.8-3.8-3.8-2.1 0-3.8 1.7-3.8 3.8v3H7c-.6 0-1 .4-1 1v8c0 .6.4 1 1 1h10c.6 0 1-.4 1-1v-8c0-.6-.4-1-1-1zM9.8 7c0-1.2 1-2.2 2.2-2.2 1.2 0 2.2 1 2.2 2.2v3H9.8V7zm6.7 11.5h-9v-7h9v7z" }) });
// packages/icons/build-module/library/lock-small.mjs
var import_primitives72 = __toESM(require_primitives(), 1);
var import_jsx_runtime74 = __toESM(require_jsx_runtime(), 1);
var lock_small_default = /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(import_primitives72.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(import_primitives72.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M15 11h-.2V9c0-1.5-1.2-2.8-2.8-2.8S9.2 7.5 9.2 9v2H9c-.6 0-1 .4-1 1v4c0 .6.4 1 1 1h6c.6 0 1-.4 1-1v-4c0-.6-.4-1-1-1zm-1.8 0h-2.5V9c0-.7.6-1.2 1.2-1.2s1.2.6 1.2 1.2v2z" }) });
// packages/icons/build-module/library/lock.mjs
var import_primitives73 = __toESM(require_primitives(), 1);
var import_jsx_runtime75 = __toESM(require_jsx_runtime(), 1);
var lock_default = /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(import_primitives73.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(import_primitives73.Path, { d: "M17 10h-1.2V7c0-2.1-1.7-3.8-3.8-3.8-2.1 0-3.8 1.7-3.8 3.8v3H7c-.6 0-1 .4-1 1v8c0 .6.4 1 1 1h10c.6 0 1-.4 1-1v-8c0-.6-.4-1-1-1zm-2.8 0H9.8V7c0-1.2 1-2.2 2.2-2.2s2.2 1 2.2 2.2v3z" }) });
// packages/icons/build-module/library/media.mjs
var import_primitives74 = __toESM(require_primitives(), 1);
var import_jsx_runtime76 = __toESM(require_jsx_runtime(), 1);
var media_default = /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)(import_primitives74.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: [
/* @__PURE__ */ (0, import_jsx_runtime76.jsx)(import_primitives74.Path, { d: "m7 6.5 4 2.5-4 2.5z" }),
/* @__PURE__ */ (0, import_jsx_runtime76.jsx)(import_primitives74.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "m5 3c-1.10457 0-2 .89543-2 2v14c0 1.1046.89543 2 2 2h14c1.1046 0 2-.8954 2-2v-14c0-1.10457-.8954-2-2-2zm14 1.5h-14c-.27614 0-.5.22386-.5.5v10.7072l3.62953-2.6465c.25108-.1831.58905-.1924.84981-.0234l2.92666 1.8969 3.5712-3.4719c.2911-.2831.7545-.2831 1.0456 0l2.9772 2.8945v-9.3568c0-.27614-.2239-.5-.5-.5zm-14.5 14.5v-1.4364l4.09643-2.987 2.99567 1.9417c.2936.1903.6798.1523.9307-.0917l3.4772-3.3806 3.4772 3.3806.0228-.0234v2.5968c0 .2761-.2239.5-.5.5h-14c-.27614 0-.5-.2239-.5-.5z" })
] });
// packages/icons/build-module/library/mobile.mjs
var import_primitives75 = __toESM(require_primitives(), 1);
var import_jsx_runtime77 = __toESM(require_jsx_runtime(), 1);
var mobile_default = /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(import_primitives75.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(import_primitives75.Path, { d: "M15 4H9c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h6c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm.5 14c0 .3-.2.5-.5.5H9c-.3 0-.5-.2-.5-.5V6c0-.3.2-.5.5-.5h6c.3 0 .5.2.5.5v12zm-4.5-.5h2V16h-2v1.5z" }) });
// packages/icons/build-module/library/more-vertical.mjs
var import_primitives76 = __toESM(require_primitives(), 1);
var import_jsx_runtime78 = __toESM(require_jsx_runtime(), 1);
var more_vertical_default = /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(import_primitives76.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(import_primitives76.Path, { d: "M13 19h-2v-2h2v2zm0-6h-2v-2h2v2zm0-6h-2V5h2v2z" }) });
// packages/icons/build-module/library/page.mjs
var import_primitives77 = __toESM(require_primitives(), 1);
var import_jsx_runtime79 = __toESM(require_jsx_runtime(), 1);
var page_default = /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(import_primitives77.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: [
/* @__PURE__ */ (0, import_jsx_runtime79.jsx)(import_primitives77.Path, { d: "M15.5 7.5h-7V9h7V7.5Zm-7 3.5h7v1.5h-7V11Zm7 3.5h-7V16h7v-1.5Z" }),
/* @__PURE__ */ (0, import_jsx_runtime79.jsx)(import_primitives77.Path, { d: "M17 4H7a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2ZM7 5.5h10a.5.5 0 0 1 .5.5v12a.5.5 0 0 1-.5.5H7a.5.5 0 0 1-.5-.5V6a.5.5 0 0 1 .5-.5Z" })
] });
// packages/icons/build-module/library/paragraph.mjs
var import_primitives78 = __toESM(require_primitives(), 1);
var import_jsx_runtime80 = __toESM(require_jsx_runtime(), 1);
var paragraph_default = /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(import_primitives78.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(import_primitives78.Path, { d: "m9.99609 14v-.2251l.00391.0001v6.225h1.5v-14.5h2.5v14.5h1.5v-14.5h3v-1.5h-8.50391c-2.76142 0-5 2.23858-5 5 0 2.7614 2.23858 5 5 5z" }) });
// packages/icons/build-module/library/pencil.mjs
var import_primitives79 = __toESM(require_primitives(), 1);
var import_jsx_runtime81 = __toESM(require_jsx_runtime(), 1);
var pencil_default = /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(import_primitives79.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(import_primitives79.Path, { d: "m19 7-3-3-8.5 8.5-1 4 4-1L19 7Zm-7 11.5H5V20h7v-1.5Z" }) });
// packages/icons/build-module/library/pin-small.mjs
var import_primitives80 = __toESM(require_primitives(), 1);
var import_jsx_runtime82 = __toESM(require_jsx_runtime(), 1);
var pin_small_default = /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(import_primitives80.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(import_primitives80.Path, { d: "M10.97 10.159a3.382 3.382 0 0 0-2.857.955l1.724 1.723-2.836 2.913L7 17h1.25l2.913-2.837 1.723 1.723a3.38 3.38 0 0 0 .606-.825c.33-.63.446-1.343.35-2.032L17 10.695 13.305 7l-2.334 3.159Z" }) });
// packages/icons/build-module/library/plus.mjs
var import_primitives81 = __toESM(require_primitives(), 1);
var import_jsx_runtime83 = __toESM(require_jsx_runtime(), 1);
var plus_default = /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(import_primitives81.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(import_primitives81.Path, { d: "M11 12.5V17.5H12.5V12.5H17.5V11H12.5V6H11V11H6V12.5H11Z" }) });
// packages/icons/build-module/library/position-center.mjs
var import_primitives82 = __toESM(require_primitives(), 1);
var import_jsx_runtime84 = __toESM(require_jsx_runtime(), 1);
var position_center_default = /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(import_primitives82.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(import_primitives82.Path, { d: "M19 5.5H5V4h14v1.5ZM19 20H5v-1.5h14V20ZM7 9h10v6H7V9Z" }) });
// packages/icons/build-module/library/position-left.mjs
var import_primitives83 = __toESM(require_primitives(), 1);
var import_jsx_runtime85 = __toESM(require_jsx_runtime(), 1);
var position_left_default = /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(import_primitives83.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(import_primitives83.Path, { d: "M5 5.5h8V4H5v1.5ZM5 20h8v-1.5H5V20ZM19 9H5v6h14V9Z" }) });
// packages/icons/build-module/library/position-right.mjs
var import_primitives84 = __toESM(require_primitives(), 1);
var import_jsx_runtime86 = __toESM(require_jsx_runtime(), 1);
var position_right_default = /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(import_primitives84.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(import_primitives84.Path, { d: "M19 5.5h-8V4h8v1.5ZM19 20h-8v-1.5h8V20ZM5 9h14v6H5V9Z" }) });
// packages/icons/build-module/library/post-featured-image.mjs
var import_primitives85 = __toESM(require_primitives(), 1);
var import_jsx_runtime87 = __toESM(require_jsx_runtime(), 1);
var post_featured_image_default = /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(import_primitives85.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(import_primitives85.Path, { d: "M19 3H5c-.6 0-1 .4-1 1v7c0 .5.4 1 1 1h14c.5 0 1-.4 1-1V4c0-.6-.4-1-1-1zM5.5 10.5v-.4l1.8-1.3 1.3.8c.3.2.7.2.9-.1L11 8.1l2.4 2.4H5.5zm13 0h-2.9l-4-4c-.3-.3-.8-.3-1.1 0L8.9 8l-1.2-.8c-.3-.2-.6-.2-.9 0l-1.3 1V4.5h13v6zM4 20h9v-1.5H4V20zm0-4h16v-1.5H4V16z" }) });
// packages/icons/build-module/library/post-list.mjs
var import_primitives86 = __toESM(require_primitives(), 1);
var import_jsx_runtime88 = __toESM(require_jsx_runtime(), 1);
var post_list_default = /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(import_primitives86.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(import_primitives86.Path, { d: "M18 5.5H6a.5.5 0 0 0-.5.5v12a.5.5 0 0 0 .5.5h12a.5.5 0 0 0 .5-.5V6a.5.5 0 0 0-.5-.5ZM6 4h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2Zm1 5h1.5v1.5H7V9Zm1.5 4.5H7V15h1.5v-1.5ZM10 9h7v1.5h-7V9Zm7 4.5h-7V15h7v-1.5Z" }) });
// packages/icons/build-module/library/reset.mjs
var import_primitives87 = __toESM(require_primitives(), 1);
var import_jsx_runtime89 = __toESM(require_jsx_runtime(), 1);
var reset_default = /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(import_primitives87.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(import_primitives87.Path, { d: "M7 11.5h10V13H7z" }) });
// packages/icons/build-module/library/rotate-right.mjs
var import_primitives88 = __toESM(require_primitives(), 1);
var import_jsx_runtime90 = __toESM(require_jsx_runtime(), 1);
var rotate_right_default = /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(import_primitives88.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(import_primitives88.Path, { d: "M15.1 4.8l-3-2.5V4c-4.4 0-8 3.6-8 8 0 3.7 2.5 6.9 6 7.7.3.1.6.1 1 .2l.2-1.5c-.4 0-.7-.1-1.1-.2l-.1.2v-.2c-2.6-.8-4.5-3.3-4.5-6.2 0-3.6 2.9-6.5 6.5-6.5v1.8l3-2.5zM20 11c-.2-1.4-.7-2.7-1.6-3.8l-1.2.8c.7.9 1.1 2 1.3 3.1L20 11zm-1.5 1.8c-.1.5-.2 1.1-.4 1.6s-.5 1-.8 1.5l1.2.9c.4-.5.8-1.1 1-1.8s.5-1.3.5-2l-1.5-.2zm-5.6 5.6l.2 1.5c1.4-.2 2.7-.7 3.8-1.6l-.9-1.1c-.9.7-2 1.1-3.1 1.2z" }) });
// packages/icons/build-module/library/row.mjs
var import_primitives89 = __toESM(require_primitives(), 1);
var import_jsx_runtime91 = __toESM(require_jsx_runtime(), 1);
var row_default = /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(import_primitives89.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(import_primitives89.Path, { d: "M4 6.5h5a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2H4V16h5a.5.5 0 0 0 .5-.5v-7A.5.5 0 0 0 9 8H4V6.5Zm16 0h-5a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h5V16h-5a.5.5 0 0 1-.5-.5v-7A.5.5 0 0 1 15 8h5V6.5Z" }) });
// packages/icons/build-module/library/search.mjs
var import_primitives90 = __toESM(require_primitives(), 1);
var import_jsx_runtime92 = __toESM(require_jsx_runtime(), 1);
var search_default = /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(import_primitives90.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(import_primitives90.Path, { d: "M13 5c-3.3 0-6 2.7-6 6 0 1.4.5 2.7 1.3 3.7l-3.8 3.8 1.1 1.1 3.8-3.8c1 .8 2.3 1.3 3.7 1.3 3.3 0 6-2.7 6-6S16.3 5 13 5zm0 10.5c-2.5 0-4.5-2-4.5-4.5s2-4.5 4.5-4.5 4.5 2 4.5 4.5-2 4.5-4.5 4.5z" }) });
// packages/icons/build-module/library/seen.mjs
var import_primitives91 = __toESM(require_primitives(), 1);
var import_jsx_runtime93 = __toESM(require_jsx_runtime(), 1);
var seen_default = /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(import_primitives91.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(import_primitives91.Path, { d: "M3.99961 13C4.67043 13.3354 4.6703 13.3357 4.67017 13.3359L4.67298 13.3305C4.67621 13.3242 4.68184 13.3135 4.68988 13.2985C4.70595 13.2686 4.7316 13.2218 4.76695 13.1608C4.8377 13.0385 4.94692 12.8592 5.09541 12.6419C5.39312 12.2062 5.84436 11.624 6.45435 11.0431C7.67308 9.88241 9.49719 8.75 11.9996 8.75C14.502 8.75 16.3261 9.88241 17.5449 11.0431C18.1549 11.624 18.6061 12.2062 18.9038 12.6419C19.0523 12.8592 19.1615 13.0385 19.2323 13.1608C19.2676 13.2218 19.2933 13.2686 19.3093 13.2985C19.3174 13.3135 19.323 13.3242 19.3262 13.3305L19.3291 13.3359C19.3289 13.3357 19.3288 13.3354 19.9996 13C20.6704 12.6646 20.6703 12.6643 20.6701 12.664L20.6697 12.6632L20.6688 12.6614L20.6662 12.6563L20.6583 12.6408C20.6517 12.6282 20.6427 12.6108 20.631 12.5892C20.6078 12.5459 20.5744 12.4852 20.5306 12.4096C20.4432 12.2584 20.3141 12.0471 20.1423 11.7956C19.7994 11.2938 19.2819 10.626 18.5794 9.9569C17.1731 8.61759 14.9972 7.25 11.9996 7.25C9.00203 7.25 6.82614 8.61759 5.41987 9.9569C4.71736 10.626 4.19984 11.2938 3.85694 11.7956C3.68511 12.0471 3.55605 12.2584 3.4686 12.4096C3.42484 12.4852 3.39142 12.5459 3.36818 12.5892C3.35656 12.6108 3.34748 12.6282 3.34092 12.6408L3.33297 12.6563L3.33041 12.6614L3.32948 12.6632L3.32911 12.664C3.32894 12.6643 3.32879 12.6646 3.99961 13ZM11.9996 16C13.9326 16 15.4996 14.433 15.4996 12.5C15.4996 10.567 13.9326 9 11.9996 9C10.0666 9 8.49961 10.567 8.49961 12.5C8.49961 14.433 10.0666 16 11.9996 16Z" }) });
// packages/icons/build-module/library/settings.mjs
var import_primitives92 = __toESM(require_primitives(), 1);
var import_jsx_runtime94 = __toESM(require_jsx_runtime(), 1);
var settings_default = /* @__PURE__ */ (0, import_jsx_runtime94.jsxs)(import_primitives92.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: [
/* @__PURE__ */ (0, import_jsx_runtime94.jsx)(import_primitives92.Path, { d: "m19 7.5h-7.628c-.3089-.87389-1.1423-1.5-2.122-1.5-.97966 0-1.81309.62611-2.12197 1.5h-2.12803v1.5h2.12803c.30888.87389 1.14231 1.5 2.12197 1.5.9797 0 1.8131-.62611 2.122-1.5h7.628z" }),
/* @__PURE__ */ (0, import_jsx_runtime94.jsx)(import_primitives92.Path, { d: "m19 15h-2.128c-.3089-.8739-1.1423-1.5-2.122-1.5s-1.8131.6261-2.122 1.5h-7.628v1.5h7.628c.3089.8739 1.1423 1.5 2.122 1.5s1.8131-.6261 2.122-1.5h2.128z" })
] });
// packages/icons/build-module/library/shadow.mjs
var import_primitives93 = __toESM(require_primitives(), 1);
var import_jsx_runtime95 = __toESM(require_jsx_runtime(), 1);
var shadow_default = /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(import_primitives93.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(import_primitives93.Path, { d: "M12 8c-2.2 0-4 1.8-4 4s1.8 4 4 4 4-1.8 4-4-1.8-4-4-4zm0 6.5c-1.4 0-2.5-1.1-2.5-2.5s1.1-2.5 2.5-2.5 2.5 1.1 2.5 2.5-1.1 2.5-2.5 2.5zM12.8 3h-1.5v3h1.5V3zm-1.6 18h1.5v-3h-1.5v3zm6.8-9.8v1.5h3v-1.5h-3zm-12 0H3v1.5h3v-1.5zm9.7 5.6 2.1 2.1 1.1-1.1-2.1-2.1-1.1 1.1zM8.3 7.2 6.2 5.1 5.1 6.2l2.1 2.1 1.1-1.1zM5.1 17.8l1.1 1.1 2.1-2.1-1.1-1.1-2.1 2.1zM18.9 6.2l-1.1-1.1-2.1 2.1 1.1 1.1 2.1-2.1z" }) });
// packages/icons/build-module/library/sides-all.mjs
var import_primitives94 = __toESM(require_primitives(), 1);
var import_jsx_runtime96 = __toESM(require_jsx_runtime(), 1);
var sides_all_default = /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(import_primitives94.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(import_primitives94.Path, { d: "m7.5 6h9v-1.5h-9zm0 13.5h9v-1.5h-9zm-3-3h1.5v-9h-1.5zm13.5-9v9h1.5v-9z" }) });
// packages/icons/build-module/library/sides-bottom.mjs
var import_primitives95 = __toESM(require_primitives(), 1);
var import_jsx_runtime97 = __toESM(require_jsx_runtime(), 1);
var sides_bottom_default = /* @__PURE__ */ (0, import_jsx_runtime97.jsxs)(import_primitives95.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: [
/* @__PURE__ */ (0, import_jsx_runtime97.jsx)(import_primitives95.Path, { d: "m7.5 6h9v-1.5h-9zm0 13.5h9v-1.5h-9zm-3-3h1.5v-9h-1.5zm13.5-9v9h1.5v-9z", style: { opacity: 0.25 } }),
/* @__PURE__ */ (0, import_jsx_runtime97.jsx)(import_primitives95.Path, { d: "m16.5 19.5h-9v-1.5h9z" })
] });
// packages/icons/build-module/library/sides-horizontal.mjs
var import_primitives96 = __toESM(require_primitives(), 1);
var import_jsx_runtime98 = __toESM(require_jsx_runtime(), 1);
var sides_horizontal_default = /* @__PURE__ */ (0, import_jsx_runtime98.jsxs)(import_primitives96.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: [
/* @__PURE__ */ (0, import_jsx_runtime98.jsx)(import_primitives96.Path, { d: "m7.5 6h9v-1.5h-9zm0 13.5h9v-1.5h-9zm-3-3h1.5v-9h-1.5zm13.5-9v9h1.5v-9z", style: { opacity: 0.25 } }),
/* @__PURE__ */ (0, import_jsx_runtime98.jsx)(import_primitives96.Path, { d: "m4.5 7.5v9h1.5v-9z" }),
/* @__PURE__ */ (0, import_jsx_runtime98.jsx)(import_primitives96.Path, { d: "m18 7.5v9h1.5v-9z" })
] });
// packages/icons/build-module/library/sides-left.mjs
var import_primitives97 = __toESM(require_primitives(), 1);
var import_jsx_runtime99 = __toESM(require_jsx_runtime(), 1);
var sides_left_default = /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)(import_primitives97.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: [
/* @__PURE__ */ (0, import_jsx_runtime99.jsx)(import_primitives97.Path, { d: "m7.5 6h9v-1.5h-9zm0 13.5h9v-1.5h-9zm-3-3h1.5v-9h-1.5zm13.5-9v9h1.5v-9z", style: { opacity: 0.25 } }),
/* @__PURE__ */ (0, import_jsx_runtime99.jsx)(import_primitives97.Path, { d: "m4.5 16.5v-9h1.5v9z" })
] });
// packages/icons/build-module/library/sides-right.mjs
var import_primitives98 = __toESM(require_primitives(), 1);
var import_jsx_runtime100 = __toESM(require_jsx_runtime(), 1);
var sides_right_default = /* @__PURE__ */ (0, import_jsx_runtime100.jsxs)(import_primitives98.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: [
/* @__PURE__ */ (0, import_jsx_runtime100.jsx)(import_primitives98.Path, { d: "m7.5 6h9v-1.5h-9zm0 13.5h9v-1.5h-9zm-3-3h1.5v-9h-1.5zm13.5-9v9h1.5v-9z", style: { opacity: 0.25 } }),
/* @__PURE__ */ (0, import_jsx_runtime100.jsx)(import_primitives98.Path, { d: "m18 16.5v-9h1.5v9z" })
] });
// packages/icons/build-module/library/sides-top.mjs
var import_primitives99 = __toESM(require_primitives(), 1);
var import_jsx_runtime101 = __toESM(require_jsx_runtime(), 1);
var sides_top_default = /* @__PURE__ */ (0, import_jsx_runtime101.jsxs)(import_primitives99.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: [
/* @__PURE__ */ (0, import_jsx_runtime101.jsx)(import_primitives99.Path, { d: "m7.5 6h9v-1.5h-9zm0 13.5h9v-1.5h-9zm-3-3h1.5v-9h-1.5zm13.5-9v9h1.5v-9z", style: { opacity: 0.25 } }),
/* @__PURE__ */ (0, import_jsx_runtime101.jsx)(import_primitives99.Path, { d: "m16.5 6h-9v-1.5h9z" })
] });
// packages/icons/build-module/library/sides-vertical.mjs
var import_primitives100 = __toESM(require_primitives(), 1);
var import_jsx_runtime102 = __toESM(require_jsx_runtime(), 1);
var sides_vertical_default = /* @__PURE__ */ (0, import_jsx_runtime102.jsxs)(import_primitives100.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: [
/* @__PURE__ */ (0, import_jsx_runtime102.jsx)(import_primitives100.Path, { d: "m7.5 6h9v-1.5h-9zm0 13.5h9v-1.5h-9zm-3-3h1.5v-9h-1.5zm13.5-9v9h1.5v-9z", style: { opacity: 0.25 } }),
/* @__PURE__ */ (0, import_jsx_runtime102.jsx)(import_primitives100.Path, { d: "m7.5 6h9v-1.5h-9z" }),
/* @__PURE__ */ (0, import_jsx_runtime102.jsx)(import_primitives100.Path, { d: "m7.5 19.5h9v-1.5h-9z" })
] });
// packages/icons/build-module/library/stack.mjs
var import_primitives101 = __toESM(require_primitives(), 1);
var import_jsx_runtime103 = __toESM(require_jsx_runtime(), 1);
var stack_default = /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(import_primitives101.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(import_primitives101.Path, { d: "M17.5 4v5a2 2 0 0 1-2 2h-7a2 2 0 0 1-2-2V4H8v5a.5.5 0 0 0 .5.5h7A.5.5 0 0 0 16 9V4h1.5Zm0 16v-5a2 2 0 0 0-2-2h-7a2 2 0 0 0-2 2v5H8v-5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 .5.5v5h1.5Z" }) });
// packages/icons/build-module/library/stretch-full-width.mjs
var import_primitives102 = __toESM(require_primitives(), 1);
var import_jsx_runtime104 = __toESM(require_jsx_runtime(), 1);
var stretch_full_width_default = /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(import_primitives102.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(import_primitives102.Path, { d: "M5 4h14v11H5V4Zm11 16H8v-1.5h8V20Z" }) });
// packages/icons/build-module/library/stretch-wide.mjs
var import_primitives103 = __toESM(require_primitives(), 1);
var import_jsx_runtime105 = __toESM(require_jsx_runtime(), 1);
var stretch_wide_default = /* @__PURE__ */ (0, import_jsx_runtime105.jsx)(import_primitives103.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime105.jsx)(import_primitives103.Path, { d: "M16 5.5H8V4h8v1.5ZM16 20H8v-1.5h8V20ZM5 9h14v6H5V9Z" }) });
// packages/icons/build-module/library/styles.mjs
var import_primitives104 = __toESM(require_primitives(), 1);
var import_jsx_runtime106 = __toESM(require_jsx_runtime(), 1);
var styles_default = /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(import_primitives104.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(import_primitives104.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M20 12a8 8 0 1 1-16 0 8 8 0 0 1 16 0Zm-1.5 0a6.5 6.5 0 0 1-6.5 6.5v-13a6.5 6.5 0 0 1 6.5 6.5Z" }) });
// packages/icons/build-module/library/symbol.mjs
var import_primitives105 = __toESM(require_primitives(), 1);
var import_jsx_runtime107 = __toESM(require_jsx_runtime(), 1);
var symbol_default = /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(import_primitives105.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(import_primitives105.Path, { d: "M21.3 10.8l-5.6-5.6c-.7-.7-1.8-.7-2.5 0l-5.6 5.6c-.7.7-.7 1.8 0 2.5l5.6 5.6c.3.3.8.5 1.2.5s.9-.2 1.2-.5l5.6-5.6c.8-.7.8-1.9.1-2.5zm-1 1.4l-5.6 5.6c-.1.1-.3.1-.4 0l-5.6-5.6c-.1-.1-.1-.3 0-.4l5.6-5.6s.1-.1.2-.1.1 0 .2.1l5.6 5.6c.1.1.1.3 0 .4zm-16.6-.4L10 5.5l-1-1-6.3 6.3c-.7.7-.7 1.8 0 2.5L9 19.5l1.1-1.1-6.3-6.3c-.2 0-.2-.2-.1-.3z" }) });
// packages/icons/build-module/library/tablet.mjs
var import_primitives106 = __toESM(require_primitives(), 1);
var import_jsx_runtime108 = __toESM(require_jsx_runtime(), 1);
var tablet_default = /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(import_primitives106.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(import_primitives106.Path, { d: "M17 4H7c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm.5 14c0 .3-.2.5-.5.5H7c-.3 0-.5-.2-.5-.5V6c0-.3.2-.5.5-.5h10c.3 0 .5.2.5.5v12zm-7.5-.5h4V16h-4v1.5z" }) });
// packages/icons/build-module/library/tag.mjs
var import_primitives107 = __toESM(require_primitives(), 1);
var import_jsx_runtime109 = __toESM(require_jsx_runtime(), 1);
var tag_default = /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(import_primitives107.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(import_primitives107.Path, { d: "M4.75 4a.75.75 0 0 0-.75.75v7.826c0 .2.08.39.22.53l6.72 6.716a2.313 2.313 0 0 0 3.276-.001l5.61-5.611-.531-.53.532.528a2.315 2.315 0 0 0 0-3.264L13.104 4.22a.75.75 0 0 0-.53-.22H4.75ZM19 12.576a.815.815 0 0 1-.236.574l-5.61 5.611a.814.814 0 0 1-1.153 0L5.5 12.264V5.5h6.763l6.5 6.502a.816.816 0 0 1 .237.574ZM8.75 9.75a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z" }) });
// packages/icons/build-module/library/text-horizontal.mjs
var import_primitives108 = __toESM(require_primitives(), 1);
var import_jsx_runtime110 = __toESM(require_jsx_runtime(), 1);
var text_horizontal_default = /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(import_primitives108.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(import_primitives108.Path, { d: "M8.2 14.4h3.9L13 17h1.7L11 6.5H9.3L5.6 17h1.7l.9-2.6zm2-5.5 1.4 4H8.8l1.4-4zm7.4 7.5-1.3.8.8 1.4H5.5V20h14.3l-2.2-3.6z" }) });
// packages/icons/build-module/library/text-vertical.mjs
var import_primitives109 = __toESM(require_primitives(), 1);
var import_jsx_runtime111 = __toESM(require_jsx_runtime(), 1);
var text_vertical_default = /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(import_primitives109.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(import_primitives109.Path, { d: "M7 5.6v1.7l2.6.9v3.9L7 13v1.7L17.5 11V9.3L7 5.6zm4.2 6V8.8l4 1.4-4 1.4zm-5.7 5.6V5.5H4v14.3l3.6-2.2-.8-1.3-1.3.9z" }) });
// packages/icons/build-module/library/trash.mjs
var import_primitives110 = __toESM(require_primitives(), 1);
var import_jsx_runtime112 = __toESM(require_jsx_runtime(), 1);
var trash_default = /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(import_primitives110.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(import_primitives110.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M12 5.5A2.25 2.25 0 0 0 9.878 7h4.244A2.251 2.251 0 0 0 12 5.5ZM12 4a3.751 3.751 0 0 0-3.675 3H5v1.5h1.27l.818 8.997a2.75 2.75 0 0 0 2.739 2.501h4.347a2.75 2.75 0 0 0 2.738-2.5L17.73 8.5H19V7h-3.325A3.751 3.751 0 0 0 12 4Zm4.224 4.5H7.776l.806 8.861a1.25 1.25 0 0 0 1.245 1.137h4.347a1.25 1.25 0 0 0 1.245-1.137l.805-8.861Z" }) });
// packages/icons/build-module/library/ungroup.mjs
var import_primitives111 = __toESM(require_primitives(), 1);
var import_jsx_runtime113 = __toESM(require_jsx_runtime(), 1);
var ungroup_default = /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(import_primitives111.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(import_primitives111.Path, { d: "M18 4h-7c-1.1 0-2 .9-2 2v7c0 1.1.9 2 2 2h7c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm.5 9c0 .3-.2.5-.5.5h-7c-.3 0-.5-.2-.5-.5V6c0-.3.2-.5.5-.5h7c.3 0 .5.2.5.5v7zm-5 5c0 .3-.2.5-.5.5H6c-.3 0-.5-.2-.5-.5v-7c0-.3.2-.5.5-.5h1V9H6c-1.1 0-2 .9-2 2v7c0 1.1.9 2 2 2h7c1.1 0 2-.9 2-2v-1h-1.5v1z" }) });
// packages/icons/build-module/library/unlock.mjs
var import_primitives112 = __toESM(require_primitives(), 1);
var import_jsx_runtime114 = __toESM(require_jsx_runtime(), 1);
var unlock_default = /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(import_primitives112.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(import_primitives112.Path, { d: "M17 10h-1.2V7c0-2.1-1.7-3.8-3.8-3.8-2.1 0-3.8 1.7-3.8 3.8h1.5c0-1.2 1-2.2 2.2-2.2s2.2 1 2.2 2.2v3H7c-.6 0-1 .4-1 1v8c0 .6.4 1 1 1h10c.6 0 1-.4 1-1v-8c0-.6-.4-1-1-1z" }) });
// packages/icons/build-module/library/unseen.mjs
var import_primitives113 = __toESM(require_primitives(), 1);
var import_jsx_runtime115 = __toESM(require_jsx_runtime(), 1);
var unseen_default = /* @__PURE__ */ (0, import_jsx_runtime115.jsx)(import_primitives113.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime115.jsx)(import_primitives113.Path, { d: "M20.7 12.7s0-.1-.1-.2c0-.2-.2-.4-.4-.6-.3-.5-.9-1.2-1.6-1.8-.7-.6-1.5-1.3-2.6-1.8l-.6 1.4c.9.4 1.6 1 2.1 1.5.6.6 1.1 1.2 1.4 1.6.1.2.3.4.3.5v.1l.7-.3.7-.3Zm-5.2-9.3-1.8 4c-.5-.1-1.1-.2-1.7-.2-3 0-5.2 1.4-6.6 2.7-.7.7-1.2 1.3-1.6 1.8-.2.3-.3.5-.4.6 0 0 0 .1-.1.2s0 0 .7.3l.7.3V13c0-.1.2-.3.3-.5.3-.4.7-1 1.4-1.6 1.2-1.2 3-2.3 5.5-2.3H13v.3c-.4 0-.8-.1-1.1-.1-1.9 0-3.5 1.6-3.5 3.5s.6 2.3 1.6 2.9l-2 4.4.9.4 7.6-16.2-.9-.4Zm-3 12.6c1.7-.2 3-1.7 3-3.5s-.2-1.4-.6-1.9L12.4 16Z" }) });
// packages/icons/build-module/library/upload.mjs
var import_primitives114 = __toESM(require_primitives(), 1);
var import_jsx_runtime116 = __toESM(require_jsx_runtime(), 1);
var upload_default = /* @__PURE__ */ (0, import_jsx_runtime116.jsx)(import_primitives114.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime116.jsx)(import_primitives114.Path, { d: "M18.5 15v3.5H13V6.7l4.5 4.1 1-1.1-6.2-5.8-5.8 5.8 1 1.1 4-4v11.7h-6V15H4v5h16v-5z" }) });
// packages/icons/build-module/library/verse.mjs
var import_primitives115 = __toESM(require_primitives(), 1);
var import_jsx_runtime117 = __toESM(require_jsx_runtime(), 1);
var verse_default = /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(import_primitives115.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(import_primitives115.Path, { d: "M17.8 2l-.9.3c-.1 0-3.6 1-5.2 2.1C10 5.5 9.3 6.5 8.9 7.1c-.6.9-1.7 4.7-1.7 6.3l-.9 2.3c-.2.4 0 .8.4 1 .1 0 .2.1.3.1.3 0 .6-.2.7-.5l.6-1.5c.3 0 .7-.1 1.2-.2.7-.1 1.4-.3 2.2-.5.8-.2 1.6-.5 2.4-.8.7-.3 1.4-.7 1.9-1.2s.8-1.2 1-1.9c.2-.7.3-1.6.4-2.4.1-.8.1-1.7.2-2.5 0-.8.1-1.5.2-2.1V2zm-1.9 5.6c-.1.8-.2 1.5-.3 2.1-.2.6-.4 1-.6 1.3-.3.3-.8.6-1.4.9-.7.3-1.4.5-2.2.8-.6.2-1.3.3-1.8.4L15 7.5c.3-.3.6-.7 1-1.1 0 .4 0 .8-.1 1.2zM6 20h8v-1.5H6V20z" }) });
// packages/icons/build-module/library/video.mjs
var import_primitives116 = __toESM(require_primitives(), 1);
var import_jsx_runtime118 = __toESM(require_jsx_runtime(), 1);
var video_default = /* @__PURE__ */ (0, import_jsx_runtime118.jsx)(import_primitives116.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime118.jsx)(import_primitives116.Path, { d: "M18.7 3H5.3C4 3 3 4 3 5.3v13.4C3 20 4 21 5.3 21h13.4c1.3 0 2.3-1 2.3-2.3V5.3C21 4 20 3 18.7 3zm.8 15.7c0 .4-.4.8-.8.8H5.3c-.4 0-.8-.4-.8-.8V5.3c0-.4.4-.8.8-.8h13.4c.4 0 .8.4.8.8v13.4zM10 15l5-3-5-3v6z" }) });
// packages/block-editor/build-module/store/selectors.mjs
var import_rich_text = __toESM(require_rich_text(), 1);
var import_deprecated2 = __toESM(require_deprecated(), 1);
var import_data5 = __toESM(require_data(), 1);
// packages/block-editor/build-module/store/utils.mjs
var import_blocks6 = __toESM(require_blocks(), 1);
var import_block_serialization_default_parser = __toESM(require_block_serialization_default_parser(), 1);
// packages/block-editor/build-module/store/constants.mjs
var STORE_NAME = "core/block-editor";
// packages/block-editor/build-module/store/private-selectors.mjs
var private_selectors_exports = {};
__export(private_selectors_exports, {
getAllPatterns: () => getAllPatterns,
getBlockRemovalRules: () => getBlockRemovalRules,
getBlockSettings: () => getBlockSettings,
getBlockStyles: () => getBlockStyles,
getBlockWithoutAttributes: () => getBlockWithoutAttributes,
getClientIdWithClientIdsTree: () => getClientIdWithClientIdsTree,
getClientIdsTree: () => getClientIdsTree,
getClosestAllowedInsertionPoint: () => getClosestAllowedInsertionPoint,
getClosestAllowedInsertionPointForPattern: () => getClosestAllowedInsertionPointForPattern,
getContentLockingParent: () => getContentLockingParent,
getEditedContentOnlySection: () => getEditedContentOnlySection,
getEnabledBlockParents: () => getEnabledBlockParents,
getEnabledClientIdsTree: () => getEnabledClientIdsTree,
getExpandedBlock: () => getExpandedBlock,
getInserterMediaCategories: () => getInserterMediaCategories,
getInsertionPoint: () => getInsertionPoint,
getLastFocus: () => getLastFocus,
getLastInsertedBlocksClientIds: () => getLastInsertedBlocksClientIds,
getListViewClientIdsTree: () => getListViewClientIdsTree,
getListViewExpandRevision: () => getListViewExpandRevision,
getParentSectionBlock: () => getParentSectionBlock,
getPatternBySlug: () => getPatternBySlug,
getRegisteredInserterMediaCategories: () => getRegisteredInserterMediaCategories,
getRemovalPromptData: () => getRemovalPromptData,
getRequestedInspectorTab: () => getRequestedInspectorTab,
getReusableBlocks: () => getReusableBlocks,
getSectionRootClientId: () => getSectionRootClientId,
getSelectedBlockStyleState: () => getSelectedBlockStyleState,
getStyleOverrides: () => getStyleOverrides,
getStyleStateViewport: () => getStyleStateViewport,
getViewportModalClientIds: () => getViewportModalClientIds,
getZoomLevel: () => getZoomLevel,
hasAllowedPatterns: () => hasAllowedPatterns,
hasBlockSpotlight: () => hasBlockSpotlight2,
hasSelectedStyleState: () => hasSelectedStyleState,
isBlockHiddenAnywhere: () => isBlockHiddenAnywhere,
isBlockHiddenAtViewport: () => isBlockHiddenAtViewport,
isBlockHiddenEverywhere: () => isBlockHiddenEverywhere,
isBlockInterfaceHidden: () => isBlockInterfaceHidden2,
isBlockParentHiddenAtViewport: () => isBlockParentHiddenAtViewport,
isBlockParentHiddenEverywhere: () => isBlockParentHiddenEverywhere,
isBlockSubtreeDisabled: () => isBlockSubtreeDisabled,
isContainerInsertableToInContentOnlyMode: () => isContainerInsertableToInContentOnlyMode,
isDragging: () => isDragging2,
isEditLockedBlock: () => isEditLockedBlock,
isListViewContentPanelOpen: () => isListViewContentPanelOpen,
isListViewPanelOpened: () => isListViewPanelOpened,
isLockedBlock: () => isLockedBlock,
isMoveLockedBlock: () => isMoveLockedBlock,
isRemoveLockedBlock: () => isRemoveLockedBlock,
isResponsiveEditing: () => isResponsiveEditing2,
isSectionBlock: () => isSectionBlock,
isSelectedBlockStyleStateShownOnCanvas: () => isSelectedBlockStyleStateShownOnCanvas,
isWithinEditedContentOnlySection: () => isWithinEditedContentOnlySection,
isZoomOut: () => isZoomOut,
shouldRenderBlockListView: () => shouldRenderBlockListView
});
var import_data4 = __toESM(require_data(), 1);
var import_blocks5 = __toESM(require_blocks(), 1);
// packages/global-styles-engine/build-module/utils/object.mjs
function setImmutably(object, path, value) {
path = Array.isArray(path) ? [...path] : [path];
object = Array.isArray(object) ? [...object] : { ...object };
const leaf = path.pop();
let prev = object;
for (const key of path) {
const lvl = prev[key];
prev = prev[key] = Array.isArray(lvl) ? [...lvl] : { ...lvl };
}
prev[leaf] = value;
return object;
}
var getValueFromObjectPath = (object, path, defaultValue) => {
const arrayPath = Array.isArray(path) ? path : path.split(".");
let value = object;
arrayPath.forEach((fieldName) => {
value = value?.[fieldName];
});
return value ?? defaultValue;
};
// packages/global-styles-engine/build-module/utils/common.mjs
var import_style_engine = __toESM(require_style_engine(), 1);
// packages/global-styles-engine/build-module/utils/fluid.mjs
var DEFAULT_MAXIMUM_VIEWPORT_WIDTH = "1600px";
var DEFAULT_MINIMUM_VIEWPORT_WIDTH = "320px";
var DEFAULT_SCALE_FACTOR = 1;
var DEFAULT_MINIMUM_FONT_SIZE_FACTOR_MIN = 0.25;
var DEFAULT_MINIMUM_FONT_SIZE_FACTOR_MAX = 0.75;
var DEFAULT_MINIMUM_FONT_SIZE_LIMIT = "14px";
function getComputedFluidTypographyValue({
minimumFontSize,
maximumFontSize,
fontSize,
minimumViewportWidth = DEFAULT_MINIMUM_VIEWPORT_WIDTH,
maximumViewportWidth = DEFAULT_MAXIMUM_VIEWPORT_WIDTH,
scaleFactor = DEFAULT_SCALE_FACTOR,
minimumFontSizeLimit
}) {
minimumFontSizeLimit = !!getTypographyValueAndUnit(minimumFontSizeLimit) ? minimumFontSizeLimit : DEFAULT_MINIMUM_FONT_SIZE_LIMIT;
if (fontSize) {
const fontSizeParsed = getTypographyValueAndUnit(fontSize);
if (!fontSizeParsed?.unit || !fontSizeParsed?.value) {
return null;
}
const minimumFontSizeLimitParsed = getTypographyValueAndUnit(
minimumFontSizeLimit,
{
coerceTo: fontSizeParsed.unit
}
);
if (!!minimumFontSizeLimitParsed?.value && !minimumFontSize && !maximumFontSize) {
if (fontSizeParsed?.value <= minimumFontSizeLimitParsed?.value) {
return null;
}
}
if (!maximumFontSize) {
maximumFontSize = `${fontSizeParsed.value}${fontSizeParsed.unit}`;
}
if (!minimumFontSize) {
const fontSizeValueInPx = fontSizeParsed.unit === "px" ? fontSizeParsed.value : fontSizeParsed.value * 16;
const minimumFontSizeFactor = Math.min(
Math.max(
1 - 0.075 * Math.log2(fontSizeValueInPx),
DEFAULT_MINIMUM_FONT_SIZE_FACTOR_MIN
),
DEFAULT_MINIMUM_FONT_SIZE_FACTOR_MAX
);
const calculatedMinimumFontSize = roundToPrecision(
fontSizeParsed.value * minimumFontSizeFactor,
3
);
if (!!minimumFontSizeLimitParsed?.value && calculatedMinimumFontSize < minimumFontSizeLimitParsed?.value) {
minimumFontSize = `${minimumFontSizeLimitParsed.value}${minimumFontSizeLimitParsed.unit}`;
} else {
minimumFontSize = `${calculatedMinimumFontSize}${fontSizeParsed.unit}`;
}
}
}
const minimumFontSizeParsed = getTypographyValueAndUnit(minimumFontSize);
const fontSizeUnit = minimumFontSizeParsed?.unit || "rem";
const maximumFontSizeParsed = getTypographyValueAndUnit(maximumFontSize, {
coerceTo: fontSizeUnit
});
if (!minimumFontSizeParsed || !maximumFontSizeParsed) {
return null;
}
const minimumFontSizeRem = getTypographyValueAndUnit(minimumFontSize, {
coerceTo: "rem"
});
const maximumViewportWidthParsed = getTypographyValueAndUnit(
maximumViewportWidth,
{ coerceTo: fontSizeUnit }
);
const minimumViewportWidthParsed = getTypographyValueAndUnit(
minimumViewportWidth,
{ coerceTo: fontSizeUnit }
);
if (!maximumViewportWidthParsed || !minimumViewportWidthParsed || !minimumFontSizeRem) {
return null;
}
const linearDenominator = maximumViewportWidthParsed.value - minimumViewportWidthParsed.value;
if (!linearDenominator) {
return null;
}
const minViewportWidthOffsetValue = roundToPrecision(
minimumViewportWidthParsed.value / 100,
3
);
const viewportWidthOffset = roundToPrecision(minViewportWidthOffsetValue, 3) + fontSizeUnit;
const linearFactor = 100 * ((maximumFontSizeParsed.value - minimumFontSizeParsed.value) / linearDenominator);
const linearFactorScaled = roundToPrecision(
(linearFactor || 1) * scaleFactor,
3
);
const fluidTargetFontSize = `${minimumFontSizeRem.value}${minimumFontSizeRem.unit} + ((1vw - ${viewportWidthOffset}) * ${linearFactorScaled})`;
return `clamp(${minimumFontSize}, ${fluidTargetFontSize}, ${maximumFontSize})`;
}
function getTypographyValueAndUnit(rawValue, options = {}) {
if (typeof rawValue !== "string" && typeof rawValue !== "number") {
return null;
}
if (isFinite(rawValue)) {
rawValue = `${rawValue}px`;
}
const { coerceTo, rootSizeValue, acceptableUnits } = {
coerceTo: "",
// Default browser font size. Later we could inject some JS to compute this `getComputedStyle( document.querySelector( "html" ) ).fontSize`.
rootSizeValue: 16,
acceptableUnits: ["rem", "px", "em"],
...options
};
const acceptableUnitsGroup = acceptableUnits?.join("|");
const regexUnits = new RegExp(
`^(\\d*\\.?\\d+)(${acceptableUnitsGroup}){1,1}$`
);
const matches = rawValue.toString().match(regexUnits);
if (!matches || matches.length < 3) {
return null;
}
let [, value, unit] = matches;
let returnValue = parseFloat(value);
if ("px" === coerceTo && ("em" === unit || "rem" === unit)) {
returnValue = returnValue * rootSizeValue;
unit = coerceTo;
}
if ("px" === unit && ("em" === coerceTo || "rem" === coerceTo)) {
returnValue = returnValue / rootSizeValue;
unit = coerceTo;
}
if (("em" === coerceTo || "rem" === coerceTo) && ("em" === unit || "rem" === unit)) {
unit = coerceTo;
}
if (!unit) {
return null;
}
return {
value: roundToPrecision(returnValue, 3),
unit
};
}
function roundToPrecision(value, digits = 3) {
const base = Math.pow(10, digits);
return Math.round(value * base) / base;
}
// packages/global-styles-engine/build-module/utils/typography.mjs
function isFluidTypographyEnabled(typographySettings) {
const fluidSettings = typographySettings?.fluid;
return true === fluidSettings || fluidSettings && typeof fluidSettings === "object" && Object.keys(fluidSettings).length > 0;
}
function getFluidTypographyOptionsFromSettings(settings2) {
const typographySettings = settings2?.typography ?? {};
const layoutSettings = settings2?.layout;
const defaultMaxViewportWidth = getTypographyValueAndUnit(
layoutSettings?.wideSize
) ? layoutSettings?.wideSize : null;
return isFluidTypographyEnabled(typographySettings) && defaultMaxViewportWidth ? {
fluid: {
maxViewportWidth: defaultMaxViewportWidth,
...typeof typographySettings.fluid === "object" ? typographySettings.fluid : {}
}
} : {
fluid: typographySettings?.fluid
};
}
function getTypographyFontSizeValue(preset, settings2) {
const { size: defaultSize } = preset;
if (!defaultSize || "0" === defaultSize || false === preset?.fluid) {
return defaultSize;
}
if (!isFluidTypographyEnabled(settings2?.typography) && !isFluidTypographyEnabled(preset)) {
return defaultSize;
}
const fluidTypographySettings = getFluidTypographyOptionsFromSettings(settings2)?.fluid ?? {};
const fluidFontSizeValue = getComputedFluidTypographyValue({
minimumFontSize: typeof preset?.fluid === "boolean" ? void 0 : preset?.fluid?.min,
maximumFontSize: typeof preset?.fluid === "boolean" ? void 0 : preset?.fluid?.max,
fontSize: defaultSize,
minimumFontSizeLimit: typeof fluidTypographySettings === "object" ? fluidTypographySettings?.minFontSize : void 0,
maximumViewportWidth: typeof fluidTypographySettings === "object" ? fluidTypographySettings?.maxViewportWidth : void 0,
minimumViewportWidth: typeof fluidTypographySettings === "object" ? fluidTypographySettings?.minViewportWidth : void 0
});
if (!!fluidFontSizeValue) {
return fluidFontSizeValue;
}
return defaultSize;
}
// packages/global-styles-engine/build-module/utils/common.mjs
var ROOT_BLOCK_SELECTOR = "body";
var ROOT_CSS_PROPERTIES_SELECTOR = ":root";
function splitSelectorList(selector3) {
if (!selector3.includes(",")) {
return [selector3];
}
const selectors4 = [];
let currentSelector = "";
let parenthesesDepth = 0;
for (const char of selector3) {
if (char === "(") {
parenthesesDepth++;
} else if (char === ")" && parenthesesDepth > 0) {
parenthesesDepth--;
} else if (char === "," && parenthesesDepth === 0) {
selectors4.push(currentSelector);
currentSelector = "";
continue;
}
currentSelector += char;
}
selectors4.push(currentSelector);
return selectors4;
}
var PRESET_METADATA = [
{
path: ["color", "palette"],
valueKey: "color",
cssVarInfix: "color",
classes: [
{ classSuffix: "color", propertyName: "color" },
{
classSuffix: "background-color",
propertyName: "background-color"
},
{
classSuffix: "border-color",
propertyName: "border-color"
}
]
},
{
path: ["color", "gradients"],
valueKey: "gradient",
cssVarInfix: "gradient",
classes: [
{
classSuffix: "gradient-background",
propertyName: "background"
}
]
},
{
path: ["color", "duotone"],
valueKey: "colors",
cssVarInfix: "duotone",
valueFunc: ({ slug }) => `url( '#wp-duotone-${slug}' )`,
classes: []
},
{
path: ["shadow", "presets"],
valueKey: "shadow",
cssVarInfix: "shadow",
classes: []
},
{
path: ["typography", "fontSizes"],
valueFunc: (preset, settings2) => getTypographyFontSizeValue(preset, settings2),
valueKey: "size",
cssVarInfix: "font-size",
classes: [{ classSuffix: "font-size", propertyName: "font-size" }]
},
{
path: ["typography", "fontFamilies"],
valueKey: "fontFamily",
cssVarInfix: "font-family",
classes: [
{ classSuffix: "font-family", propertyName: "font-family" }
]
},
{
path: ["spacing", "spacingSizes"],
valueKey: "size",
cssVarInfix: "spacing",
valueFunc: ({ size: size4 }) => size4,
classes: []
},
{
path: ["border", "radiusSizes"],
valueKey: "size",
cssVarInfix: "border-radius",
classes: []
},
{
path: ["dimensions", "dimensionSizes"],
valueKey: "size",
cssVarInfix: "dimension",
classes: []
}
];
function scopeSelector(scope, selector3) {
if (!scope || !selector3) {
return selector3;
}
const scopes = splitSelectorList(scope);
const selectors4 = splitSelectorList(selector3);
const selectorsScoped = [];
scopes.forEach((outer) => {
selectors4.forEach((inner) => {
selectorsScoped.push(`${outer.trim()} ${inner.trim()}`);
});
});
return selectorsScoped.join(", ");
}
function scopeFeatureSelectors(scope, selectors4) {
if (!scope || !selectors4) {
return;
}
const featureSelectors = {};
Object.entries(selectors4).forEach(([feature, selector3]) => {
if (typeof selector3 === "string") {
featureSelectors[feature] = scopeSelector(scope, selector3);
}
if (typeof selector3 === "object") {
featureSelectors[feature] = {};
Object.entries(selector3).forEach(
([subfeature, subfeatureSelector]) => {
featureSelectors[feature][subfeature] = scopeSelector(
scope,
subfeatureSelector
);
}
);
}
});
return featureSelectors;
}
function appendToSelector(selector3, toAppend) {
if (!selector3.includes(",")) {
return selector3 + toAppend;
}
const selectors4 = splitSelectorList(selector3);
const newSelectors = selectors4.map((sel) => sel + toAppend);
return newSelectors.join(",");
}
function getBlockStyleVariationSelector(variation, blockSelector) {
const variationClass = `.is-style-${variation}`;
if (!blockSelector) {
return variationClass;
}
const ancestorRegex = /[^\s:]+/;
const addVariationClass = (match2) => match2 + variationClass;
const result = splitSelectorList(blockSelector).map(
(part) => part.replace(ancestorRegex, addVariationClass)
);
return result.join(",");
}
function getBlockStyleVariationFeatureSelector(variation, featureSelector) {
const variationClass = `.is-style-${variation}`;
const selectorParts = splitSelectorList(featureSelector).map(
(selector3) => {
const trimmedSelector = selector3.trim();
const prefix2 = `${variationClass} `;
if (trimmedSelector.startsWith(prefix2)) {
return trimmedSelector.slice(prefix2.length);
}
return trimmedSelector;
}
);
return getBlockStyleVariationSelector(
variation,
selectorParts.join(",")
);
}
function getResolvedRefValue(ruleValue, tree) {
if (!ruleValue || !tree) {
return ruleValue;
}
if (typeof ruleValue === "object" && "ref" in ruleValue && ruleValue?.ref) {
const resolvedRuleValue = (0, import_style_engine.getCSSValueFromRawStyle)(
getValueFromObjectPath(tree, ruleValue.ref)
);
if (typeof resolvedRuleValue === "object" && resolvedRuleValue !== null && "ref" in resolvedRuleValue && resolvedRuleValue?.ref) {
return void 0;
}
if (resolvedRuleValue === void 0) {
return ruleValue;
}
return resolvedRuleValue;
}
return ruleValue;
}
function getResolvedThemeFilePath(file, themeFileURIs) {
if (!file || !themeFileURIs || !Array.isArray(themeFileURIs)) {
return file;
}
const uri = themeFileURIs.find(
(themeFileUri) => themeFileUri?.name === file
);
if (!uri?.href) {
return file;
}
return uri?.href;
}
function getResolvedValue(ruleValue, tree) {
if (!ruleValue || !tree) {
return ruleValue;
}
const resolvedValue = getResolvedRefValue(ruleValue, tree);
if (typeof resolvedValue === "object" && resolvedValue !== null && "url" in resolvedValue && resolvedValue?.url) {
resolvedValue.url = getResolvedThemeFilePath(
resolvedValue.url,
tree?._links?.["wp:theme-file"]
);
}
return resolvedValue;
}
function findInPresetsBy(settings2, blockName, presetPath = [], presetProperty = "slug", presetValueValue) {
const orderedPresetsByOrigin = [
blockName ? getValueFromObjectPath(settings2, [
"blocks",
blockName,
...presetPath
]) : void 0,
getValueFromObjectPath(settings2, presetPath)
].filter(Boolean);
for (const presetByOrigin of orderedPresetsByOrigin) {
if (presetByOrigin) {
const origins = ["custom", "theme", "default"];
for (const origin of origins) {
const presets = presetByOrigin[origin];
if (presets) {
const presetObject = presets.find(
(preset) => preset[presetProperty] === presetValueValue
);
if (presetObject) {
if (presetProperty === "slug") {
return presetObject;
}
const highestPresetObjectWithSameSlug = findInPresetsBy(
settings2,
blockName,
presetPath,
"slug",
presetObject.slug
);
if (highestPresetObjectWithSameSlug[presetProperty] === presetObject[presetProperty]) {
return presetObject;
}
return void 0;
}
}
}
}
}
}
function getValueFromPresetVariable(features, blockName, variable, [presetType, slug] = []) {
const metadata = PRESET_METADATA.find(
(data) => data.cssVarInfix === presetType
);
if (!metadata || !features.settings) {
return variable;
}
const presetObject = findInPresetsBy(
features.settings,
blockName,
metadata.path,
"slug",
slug
);
if (presetObject) {
const { valueKey } = metadata;
const result = presetObject[valueKey];
return getValueFromVariable(features, blockName, result);
}
return variable;
}
function getValueFromCustomVariable(features, blockName, variable, path = []) {
const result = (blockName ? getValueFromObjectPath(features?.settings ?? {}, [
"blocks",
blockName,
"custom",
...path
]) : void 0) ?? getValueFromObjectPath(features?.settings ?? {}, [
"custom",
...path
]);
if (!result) {
return variable;
}
return getValueFromVariable(features, blockName, result);
}
function getValueFromVariable(features, blockName, variable) {
if (!variable || typeof variable !== "string") {
if (typeof variable === "object" && variable !== null && "ref" in variable && typeof variable.ref === "string") {
const resolvedVariable = getValueFromObjectPath(
features,
variable.ref
);
if (!resolvedVariable || typeof resolvedVariable === "object" && "ref" in resolvedVariable) {
return resolvedVariable;
}
variable = resolvedVariable;
} else {
return variable;
}
}
const USER_VALUE_PREFIX = "var:";
const THEME_VALUE_PREFIX = "var(--wp--";
const THEME_VALUE_SUFFIX = ")";
let parsedVar;
if (variable.startsWith(USER_VALUE_PREFIX)) {
parsedVar = variable.slice(USER_VALUE_PREFIX.length).split("|");
} else if (variable.startsWith(THEME_VALUE_PREFIX) && variable.endsWith(THEME_VALUE_SUFFIX)) {
parsedVar = variable.slice(THEME_VALUE_PREFIX.length, -THEME_VALUE_SUFFIX.length).split("--");
} else {
return variable;
}
const [type, ...path] = parsedVar;
if (type === "preset") {
return getValueFromPresetVariable(
features,
blockName,
variable,
path
);
}
if (type === "custom") {
return getValueFromCustomVariable(
features,
blockName,
variable,
path
);
}
return variable;
}
// packages/global-styles-engine/build-module/style-state-back-compat.mjs
var LEGACY_STYLE_STATE_ALIASES = {
"@mobile": "mobile",
"@tablet": "tablet",
"-current": "@current"
};
function isObjectRecord(value) {
return !!value && typeof value === "object" && !Array.isArray(value);
}
function normalizeStyleStateNode(node) {
if (!isObjectRecord(node)) {
return node;
}
let normalized = node;
Object.entries(LEGACY_STYLE_STATE_ALIASES).forEach(
([state, legacyState]) => {
if (Object.hasOwn(node, legacyState)) {
if (normalized === node) {
normalized = { ...node };
}
if (!Object.hasOwn(node, state)) {
normalized[state] = node[legacyState];
}
delete normalized[legacyState];
}
}
);
Object.entries(normalized).forEach(([key, value]) => {
if (!isObjectRecord(value)) {
return;
}
const normalizedValue = normalizeStyleStateNode(value);
if (normalizedValue !== value) {
if (normalized === node) {
normalized = { ...node };
}
normalized[key] = normalizedValue;
}
});
return normalized;
}
function normalizeStyleStateAliases(globalStyles) {
if (true) {
return globalStyles;
}
if (!globalStyles?.styles) {
return globalStyles;
}
const styles = normalizeStyleStateNode(globalStyles.styles);
return styles === globalStyles.styles ? globalStyles : { ...globalStyles, styles };
}
// packages/global-styles-engine/build-module/core/merge.mjs
var import_deepmerge = __toESM(require_cjs(), 1);
// node_modules/is-plain-object/dist/is-plain-object.mjs
function isObject(o3) {
return Object.prototype.toString.call(o3) === "[object Object]";
}
function isPlainObject(o3) {
var ctor, prot;
if (isObject(o3) === false) return false;
ctor = o3.constructor;
if (ctor === void 0) return true;
prot = ctor.prototype;
if (isObject(prot) === false) return false;
if (prot.hasOwnProperty("isPrototypeOf") === false) {
return false;
}
return true;
}
// packages/global-styles-engine/build-module/core/merge.mjs
function mergeGlobalStyles(base, user) {
return (0, import_deepmerge.default)(
normalizeStyleStateAliases(base),
normalizeStyleStateAliases(user),
{
/*
* We only pass as arrays the presets,
* in which case we want the new array of values
* to override the old array (no merging).
*/
isMergeableObject: isPlainObject,
/*
* Exceptions to the above rule.
* Background images should be replaced, not merged,
* as they themselves are specific object definitions for the style.
*/
customMerge: (key) => {
if (key === "backgroundImage") {
return (baseConfig, userConfig) => userConfig ?? baseConfig;
}
return void 0;
}
}
);
}
// packages/global-styles-engine/build-module/core/render.mjs
var import_blocks3 = __toESM(require_blocks(), 1);
var import_style_engine2 = __toESM(require_style_engine(), 1);
var import_data3 = __toESM(require_data(), 1);
// packages/global-styles-engine/build-module/core/selectors.mjs
function getBlockSelector(blockType, target = "root", options = {}) {
if (!target) {
return null;
}
const { fallback = false } = options;
const { name, selectors: selectors4, supports } = blockType;
const hasSelectors = selectors4 && Object.keys(selectors4).length > 0;
const path = Array.isArray(target) ? target.join(".") : target;
let rootSelector = null;
if (hasSelectors && selectors4.root) {
rootSelector = selectors4?.root;
} else if (supports?.__experimentalSelector) {
rootSelector = supports.__experimentalSelector;
} else {
rootSelector = ".wp-block-" + name.replace("core/", "").replace("/", "-");
}
if (path === "root") {
return rootSelector;
}
const pathArray = Array.isArray(target) ? target : target.split(".");
if (pathArray.length === 1) {
const fallbackSelector = fallback ? rootSelector : null;
if (hasSelectors) {
const featureSelector2 = getValueFromObjectPath(
selectors4,
`${path}.root`,
null
) || getValueFromObjectPath(selectors4, path, null);
return featureSelector2 || fallbackSelector;
}
const featureSelector = supports ? getValueFromObjectPath(
supports,
`${path}.__experimentalSelector`,
null
) : void 0;
if (!featureSelector) {
return fallbackSelector;
}
return scopeSelector(rootSelector, featureSelector);
}
let subfeatureSelector;
if (hasSelectors) {
subfeatureSelector = getValueFromObjectPath(selectors4, path, null);
}
if (subfeatureSelector) {
return subfeatureSelector;
}
if (fallback) {
return getBlockSelector(blockType, pathArray[0], options);
}
return null;
}
// packages/global-styles-engine/build-module/utils/string.mjs
function kebabCase2(str) {
return str.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/([0-9])([a-zA-Z])/g, "$1-$2").replace(/([a-zA-Z])([0-9])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase();
}
// packages/global-styles-engine/build-module/utils/spacing.mjs
function getSpacingPresetCssVar(value) {
if (!value) {
return;
}
const slug = value.match(/var:preset\|spacing\|(.+)/);
if (!slug) {
return value;
}
return `var(--wp--preset--spacing--${slug[1]})`;
}
// packages/global-styles-engine/build-module/utils/gap.mjs
function getGapBoxControlValueFromStyle(blockGapValue) {
if (!blockGapValue) {
return null;
}
const isValueString = typeof blockGapValue === "string";
return {
top: isValueString ? blockGapValue : blockGapValue?.top,
left: isValueString ? blockGapValue : blockGapValue?.left
};
}
function getGapCSSValue(blockGapValue, defaultValue = "0") {
const blockGapBoxControlValue = getGapBoxControlValueFromStyle(blockGapValue);
if (!blockGapBoxControlValue) {
return null;
}
const row = getSpacingPresetCssVar(blockGapBoxControlValue?.top) || defaultValue;
const column = getSpacingPresetCssVar(blockGapBoxControlValue?.left) || defaultValue;
return row === column ? row : `${row} ${column}`;
}
// packages/global-styles-engine/build-module/utils/background.mjs
var BACKGROUND_BLOCK_DEFAULT_VALUES = {
backgroundSize: "cover",
backgroundPosition: "50% 50%"
// used only when backgroundSize is 'contain'.
};
function setBackgroundStyleDefaults(backgroundStyle) {
if (!backgroundStyle || // @ts-expect-error
!backgroundStyle?.backgroundImage?.url) {
return;
}
let backgroundStylesWithDefaults;
if (!backgroundStyle?.backgroundSize) {
backgroundStylesWithDefaults = {
backgroundSize: BACKGROUND_BLOCK_DEFAULT_VALUES.backgroundSize
};
}
if ("contain" === backgroundStyle?.backgroundSize && !backgroundStyle?.backgroundPosition) {
backgroundStylesWithDefaults = {
backgroundPosition: BACKGROUND_BLOCK_DEFAULT_VALUES.backgroundPosition
};
}
return backgroundStylesWithDefaults;
}
// packages/global-styles-engine/build-module/utils/layout.mjs
var LAYOUT_DEFINITIONS = {
default: {
name: "default",
slug: "flow",
className: "is-layout-flow",
baseStyles: [
{
selector: " > .alignleft",
rules: {
float: "left",
"margin-inline-start": "0",
"margin-inline-end": "2em"
}
},
{
selector: " > .alignright",
rules: {
float: "right",
"margin-inline-start": "2em",
"margin-inline-end": "0"
}
},
{
selector: " > .aligncenter",
rules: {
"margin-left": "auto !important",
"margin-right": "auto !important"
}
}
],
spacingStyles: [
{
selector: " > :first-child",
rules: {
"margin-block-start": "0"
}
},
{
selector: " > :last-child",
rules: {
"margin-block-end": "0"
}
},
{
selector: " > *",
rules: {
"margin-block-start": null,
"margin-block-end": "0"
}
}
]
},
constrained: {
name: "constrained",
slug: "constrained",
className: "is-layout-constrained",
baseStyles: [
{
selector: " > .alignleft",
rules: {
float: "left",
"margin-inline-start": "0",
"margin-inline-end": "2em"
}
},
{
selector: " > .alignright",
rules: {
float: "right",
"margin-inline-start": "2em",
"margin-inline-end": "0"
}
},
{
selector: " > .aligncenter",
rules: {
"margin-left": "auto !important",
"margin-right": "auto !important"
}
},
{
selector: " > :where(:not(.alignleft):not(.alignright):not(.alignfull))",
rules: {
"max-width": "var(--wp--style--global--content-size)",
"margin-left": "auto !important",
"margin-right": "auto !important"
}
},
{
selector: " > .alignwide",
rules: {
"max-width": "var(--wp--style--global--wide-size)"
}
}
],
spacingStyles: [
{
selector: " > :first-child",
rules: {
"margin-block-start": "0"
}
},
{
selector: " > :last-child",
rules: {
"margin-block-end": "0"
}
},
{
selector: " > *",
rules: {
"margin-block-start": null,
"margin-block-end": "0"
}
}
]
},
flex: {
name: "flex",
slug: "flex",
className: "is-layout-flex",
displayMode: "flex",
baseStyles: [
{
selector: "",
rules: {
"flex-wrap": "wrap",
"align-items": "center"
}
},
{
selector: " > :is(*, div)",
// :is(*, div) instead of just * increases the specificity by 001.
rules: {
margin: "0"
}
}
],
spacingStyles: [
{
selector: "",
rules: {
gap: null
}
}
]
},
grid: {
name: "grid",
slug: "grid",
className: "is-layout-grid",
displayMode: "grid",
baseStyles: [
{
selector: " > :is(*, div)",
// :is(*, div) instead of just * increases the specificity by 001.
rules: {
margin: "0"
}
}
],
spacingStyles: [
{
selector: "",
rules: {
gap: null
}
}
]
}
};
// packages/global-styles-engine/build-module/utils/viewport.mjs
var DEFAULT_VIEWPORT_BREAKPOINTS = {
mobile: "480px",
tablet: "782px"
};
var VIEWPORT_SIZE_REGEXP = /^(\d+|\d*\.\d+)(px|em|rem)$/;
var DEFAULT_FONT_SIZE = 16;
function isViewportSettings(configOrSettings) {
return "mobile" in configOrSettings || "tablet" in configOrSettings;
}
function getViewportSettings(configOrSettings) {
if (!configOrSettings || typeof configOrSettings !== "object") {
return {};
}
if (isViewportSettings(configOrSettings)) {
return configOrSettings;
}
return configOrSettings.settings?.viewport ?? {};
}
function isValidViewportSize(value) {
return typeof value === "string" && VIEWPORT_SIZE_REGEXP.test(value.trim());
}
function getViewportBreakpointValueInPixels(value) {
if (typeof value === "number") {
return value;
}
if (typeof value !== "string") {
return void 0;
}
const match2 = value.trim().match(VIEWPORT_SIZE_REGEXP);
if (!match2) {
return void 0;
}
const numericValue = Number.parseFloat(match2[1]);
const unit = match2[2];
return unit === "px" ? numericValue : numericValue * DEFAULT_FONT_SIZE;
}
function getViewportBreakpoints(configOrSettings) {
const viewportSettings = getViewportSettings(configOrSettings);
const breakpoints = {};
const breakpointValuesInPixels = {};
Object.keys(DEFAULT_VIEWPORT_BREAKPOINTS).forEach((breakpoint) => {
const key = breakpoint;
const value = viewportSettings[key];
const px = getViewportBreakpointValueInPixels(value);
if (px !== void 0 && isValidViewportSize(value)) {
breakpoints[key] = value.trim();
breakpointValuesInPixels[key] = px;
}
});
const breakpointNames = Object.keys(breakpoints);
if (!breakpointNames.length) {
return { ...DEFAULT_VIEWPORT_BREAKPOINTS };
}
if (1 === breakpointNames.length) {
return breakpoints;
}
const mobile = breakpoints.mobile;
const tablet = breakpoints.tablet;
if (breakpointValuesInPixels.mobile >= breakpointValuesInPixels.tablet) {
return { mobile };
}
return { mobile, tablet };
}
function getResponsiveMediaQueries(configOrSettings) {
const breakpoints = getViewportBreakpoints(configOrSettings);
const mediaQueries = {};
if (breakpoints.mobile) {
mediaQueries["@mobile"] = `@media (width <= ${breakpoints.mobile})`;
}
if (breakpoints.tablet) {
mediaQueries["@tablet"] = breakpoints.mobile ? `@media (${breakpoints.mobile} < width <= ${breakpoints.tablet})` : `@media (width <= ${breakpoints.tablet})`;
}
return mediaQueries;
}
// packages/global-styles-engine/build-module/core/render.mjs
var ELEMENT_CLASS_NAMES = {
button: "wp-element-button",
caption: "wp-element-caption"
};
var BLOCK_SUPPORT_FEATURE_LEVEL_SELECTORS = {
__experimentalBorder: "border",
color: "color",
dimensions: "dimensions",
spacing: "spacing",
typography: "typography"
};
var VALID_BLOCK_PSEUDO_SELECTORS = {
"core/button": [":hover", ":focus", ":focus-visible", ":active"],
"core/navigation-link": [":hover", ":focus", ":focus-visible", ":active"]
};
var VALID_ELEMENT_PSEUDO_SELECTORS = {
link: [
":link",
":any-link",
":visited",
":hover",
":focus",
":focus-visible",
":active"
],
button: [
":link",
":any-link",
":visited",
":hover",
":focus",
":focus-visible",
":active"
]
};
function getPresetsClasses(blockSelector = "*", blockPresets = {}) {
return PRESET_METADATA.reduce(
(declarations, { path, cssVarInfix, classes }) => {
if (!classes) {
return declarations;
}
const presetByOrigin = getValueFromObjectPath(
blockPresets,
path,
[]
);
["default", "theme", "custom"].forEach((origin) => {
if (presetByOrigin[origin]) {
presetByOrigin[origin].forEach(
({ slug }) => {
classes.forEach(
({
classSuffix,
propertyName
}) => {
const classSelectorToUse = `.has-${kebabCase2(
slug
)}-${classSuffix}`;
const selectorToUse = blockSelector.split(",").map(
(selector3) => `${selector3}${classSelectorToUse}`
).join(",");
const value = `var(--wp--preset--${cssVarInfix}--${kebabCase2(
slug
)})`;
declarations += `${selectorToUse}{${propertyName}: ${value} !important;}`;
}
);
}
);
}
});
return declarations;
},
""
);
}
var updateParagraphTextIndentSelector = (featureDeclarations, settings2, blockName) => {
if (blockName !== "core/paragraph") {
return featureDeclarations;
}
const blockSettings = settings2?.blocks?.["core/paragraph"];
const textIndentSetting = blockSettings?.typography?.textIndent ?? settings2?.typography?.textIndent ?? "subsequent";
if (textIndentSetting !== "all") {
return featureDeclarations;
}
const oldSelector = ".wp-block-paragraph + .wp-block-paragraph";
const newSelector = ".wp-block-paragraph";
if (oldSelector in featureDeclarations) {
const declarations = featureDeclarations[oldSelector];
const updated = { ...featureDeclarations };
delete updated[oldSelector];
updated[newSelector] = declarations;
return updated;
}
return featureDeclarations;
};
var updateButtonWidthDeclarations = (featureDeclarations, settings2) => {
const buttonSelector = ".wp-block-button";
if (!(buttonSelector in featureDeclarations)) {
return featureDeclarations;
}
const updated = { ...featureDeclarations };
updated[buttonSelector] = updated[buttonSelector].map(
(declaration) => {
const match2 = declaration.match(/^width:\s*(.+)$/);
if (!match2) {
return declaration;
}
const value = match2[1];
let percentage = null;
if (value.endsWith("%")) {
percentage = parseFloat(value);
}
const presetPrefix = "var(--wp--preset--dimension--";
if (percentage === null && value.startsWith(presetPrefix) && value.endsWith(")")) {
const slug = value.slice(presetPrefix.length, -1);
const dimensionSizes = {
...settings2?.dimensions?.dimensionSizes ?? {},
...settings2?.blocks?.["core/button"]?.dimensions?.dimensionSizes ?? {}
};
for (const origin of Object.values(dimensionSizes)) {
if (!Array.isArray(origin)) {
continue;
}
for (const preset of origin) {
if (preset.slug === slug && typeof preset.size === "string" && preset.size.endsWith("%")) {
percentage = parseFloat(preset.size);
break;
}
}
if (percentage !== null) {
break;
}
}
}
if (percentage === null || isNaN(percentage)) {
return declaration;
}
return `width: calc(${percentage} * 1% - (var(--wp--style--block-gap, 0.5em) * (1 - ${percentage} / 100)))`;
}
);
return updated;
};
var getFeatureDeclarations = (selectors4, styles) => {
const declarations = {};
Object.entries(selectors4).forEach(([feature, selector3]) => {
if (feature === "root" || !styles?.[feature]) {
return;
}
const isShorthand = typeof selector3 === "string";
if (!isShorthand && typeof selector3 === "object" && selector3 !== null) {
Object.entries(selector3).forEach(
([subfeature, subfeatureSelector]) => {
if (subfeature === "root" || !styles?.[feature][subfeature]) {
return;
}
const subfeatureStyles = {
[feature]: {
[subfeature]: styles[feature][subfeature]
}
};
const newDeclarations = getStylesDeclarations(subfeatureStyles);
declarations[subfeatureSelector] = [
...declarations[subfeatureSelector] || [],
...newDeclarations
];
delete styles[feature][subfeature];
}
);
}
if (isShorthand || typeof selector3 === "object" && selector3 !== null && "root" in selector3) {
const featureSelector = isShorthand ? selector3 : selector3.root;
const featureStyles = { [feature]: styles[feature] };
const newDeclarations = getStylesDeclarations(featureStyles);
declarations[featureSelector] = [
...declarations[featureSelector] || [],
...newDeclarations
];
delete styles[feature];
}
});
return declarations;
};
function getStylesDeclarations(blockStyles = {}, selector3 = "", useRootPaddingAlign, tree = {}, disableRootPadding = false) {
const isRoot = ROOT_BLOCK_SELECTOR === selector3;
const output = Object.entries(
import_blocks3.__EXPERIMENTAL_STYLE_PROPERTY
).reduce(
(declarations, [key, { value, properties, useEngine, rootOnly }]) => {
if (rootOnly && !isRoot) {
return declarations;
}
const pathToValue = value;
if (pathToValue[0] === "elements" || useEngine) {
return declarations;
}
const styleValue = getValueFromObjectPath(
blockStyles,
pathToValue
);
if (key === "--wp--style--root--padding" && (typeof styleValue === "string" || !useRootPaddingAlign)) {
return declarations;
}
if (properties && typeof styleValue !== "string") {
Object.entries(properties).forEach((entry) => {
const [name, prop] = entry;
if (!getValueFromObjectPath(styleValue, [prop], false)) {
return;
}
const cssProperty = name.startsWith("--") ? name : kebabCase2(name);
declarations.push(
`${cssProperty}: ${(0, import_style_engine2.getCSSValueFromRawStyle)(
getValueFromObjectPath(styleValue, [prop])
)}`
);
});
} else if (getValueFromObjectPath(blockStyles, pathToValue, false)) {
const cssProperty = key.startsWith("--") ? key : kebabCase2(key);
declarations.push(
`${cssProperty}: ${(0, import_style_engine2.getCSSValueFromRawStyle)(
getValueFromObjectPath(blockStyles, pathToValue)
)}`
);
}
return declarations;
},
[]
);
if (!!blockStyles.background) {
if (blockStyles.background?.backgroundImage) {
blockStyles.background.backgroundImage = getResolvedValue(
blockStyles.background.backgroundImage,
tree
);
}
if (!isRoot && !!blockStyles.background?.backgroundImage?.id) {
blockStyles = {
...blockStyles,
background: {
...blockStyles.background,
...setBackgroundStyleDefaults(blockStyles.background)
}
};
}
}
const extraRules = (0, import_style_engine2.getCSSRules)(blockStyles);
extraRules.forEach((rule) => {
if (isRoot && (useRootPaddingAlign || disableRootPadding) && rule.key.startsWith("padding")) {
return;
}
const cssProperty = rule.key.startsWith("--") ? rule.key : kebabCase2(rule.key);
let ruleValue = getResolvedValue(rule.value, tree);
if (cssProperty === "font-size") {
ruleValue = getTypographyFontSizeValue(
{ name: "", slug: "", size: ruleValue },
tree?.settings
);
}
if (cssProperty === "aspect-ratio") {
output.push("min-height: unset");
}
output.push(`${cssProperty}: ${ruleValue}`);
});
return output;
}
function getLayoutStyles({
layoutDefinitions = LAYOUT_DEFINITIONS,
style,
selector: selector3,
hasBlockGapSupport,
hasFallbackGapSupport,
fallbackGapValue
}) {
let ruleset = "";
let gapValue = hasBlockGapSupport ? getGapCSSValue(style?.spacing?.blockGap) : "";
if (hasFallbackGapSupport) {
if (selector3 === ROOT_BLOCK_SELECTOR) {
gapValue = !gapValue ? "0.5em" : gapValue;
} else if (!hasBlockGapSupport && fallbackGapValue) {
gapValue = fallbackGapValue;
}
}
if (gapValue && layoutDefinitions) {
Object.values(layoutDefinitions).forEach(
({ className, name, spacingStyles }) => {
if (!hasBlockGapSupport && "flex" !== name && "grid" !== name) {
return;
}
if (spacingStyles?.length) {
spacingStyles.forEach((spacingStyle) => {
const declarations = [];
if (spacingStyle.rules) {
Object.entries(spacingStyle.rules).forEach(
([cssProperty, cssValue]) => {
declarations.push(
`${cssProperty}: ${cssValue ? cssValue : gapValue}`
);
}
);
}
if (declarations.length) {
let combinedSelector = "";
if (!hasBlockGapSupport) {
combinedSelector = selector3 === ROOT_BLOCK_SELECTOR ? `:where(.${className}${spacingStyle?.selector || ""})` : `:where(${selector3}.${className}${spacingStyle?.selector || ""})`;
} else {
combinedSelector = selector3 === ROOT_BLOCK_SELECTOR ? `:root :where(.${className})${spacingStyle?.selector || ""}` : `:root :where(${selector3}-${className})${spacingStyle?.selector || ""}`;
}
ruleset += `${combinedSelector} { ${declarations.join(
"; "
)}; }`;
}
});
}
}
);
if (selector3 === ROOT_BLOCK_SELECTOR && hasBlockGapSupport) {
ruleset += `${ROOT_CSS_PROPERTIES_SELECTOR} { --wp--style--block-gap: ${gapValue}; }`;
}
}
if (selector3 === ROOT_BLOCK_SELECTOR && layoutDefinitions) {
const validDisplayModes = ["block", "flex", "grid"];
Object.values(layoutDefinitions).forEach(
({ className, displayMode, baseStyles }) => {
if (displayMode && validDisplayModes.includes(displayMode)) {
ruleset += `${selector3} .${className} { display:${displayMode}; }`;
}
if (baseStyles?.length) {
baseStyles.forEach((baseStyle) => {
const declarations = [];
if (baseStyle.rules) {
Object.entries(baseStyle.rules).forEach(
([cssProperty, cssValue]) => {
declarations.push(
`${cssProperty}: ${cssValue}`
);
}
);
}
if (declarations.length) {
const combinedSelector = `.${className}${baseStyle?.selector || ""}`;
ruleset += `${combinedSelector} { ${declarations.join(
"; "
)}; }`;
}
});
}
}
);
}
return ruleset;
}
var STYLE_KEYS = [
"border",
"color",
"dimensions",
"spacing",
"typography",
"filter",
"outline",
"shadow",
"background"
];
function pickStyleKeys(treeToPickFrom, responsiveMediaQueries) {
return pickStyleAndPseudoKeys(
treeToPickFrom,
void 0,
responsiveMediaQueries
);
}
function pickStyleAndPseudoKeys(treeToPickFrom, blockName, responsiveMediaQueries) {
if (!treeToPickFrom) {
return {};
}
const entries = Object.entries(treeToPickFrom);
const allowedPseudoSelectors = blockName ? VALID_BLOCK_PSEUDO_SELECTORS[blockName] ?? [] : [];
const pickedEntries = entries.filter(
([key]) => STYLE_KEYS.includes(key) || allowedPseudoSelectors.includes(key) || responsiveMediaQueries[key]
);
const clonedEntries = pickedEntries.map(([key, style]) => [
key,
JSON.parse(JSON.stringify(style))
]);
return Object.fromEntries(clonedEntries);
}
function getPseudoStyleNodes(node) {
const {
styles,
selector: selector3,
featureSelectors,
name,
elementName,
mediaQuery,
variationName
} = node;
const pseudoSelectors = name ? VALID_BLOCK_PSEUDO_SELECTORS[name] ?? [] : VALID_ELEMENT_PSEUDO_SELECTORS[elementName ?? ""] ?? [];
if (!pseudoSelectors.length) {
return [];
}
return pseudoSelectors.flatMap((pseudoSelector) => {
const pseudoStyles = styles?.[pseudoSelector];
if (!pseudoStyles || typeof pseudoStyles !== "object") {
return [];
}
return [
{
styles: JSON.parse(JSON.stringify(pseudoStyles)),
selector: selector3,
selectorSuffix: pseudoSelector,
mediaQuery,
featureSelectors: featureSelectors && typeof featureSelectors !== "string" ? featureSelectors : void 0,
name,
elementName,
variationName
}
];
});
}
function getResponsiveStyleNodes(node, responsiveMediaQueries) {
const {
styles,
selector: selector3,
fallbackGapValue,
featureSelectors,
hasLayoutSupport: hasLayoutSupport2,
layoutHasBlockGapSupport,
layoutSelector,
name,
elementName,
isStyleVariation,
variationName
} = node;
if (!name && !elementName) {
return [];
}
return Object.entries(responsiveMediaQueries).flatMap(
([breakpointKey, mediaQuery]) => {
const breakpointStyles = styles?.[breakpointKey];
if (!breakpointStyles || typeof breakpointStyles !== "object") {
return [];
}
return [
{
styles: JSON.parse(JSON.stringify(breakpointStyles)),
selector: selector3,
mediaQuery,
featureSelectors: featureSelectors && typeof featureSelectors !== "string" ? featureSelectors : void 0,
fallbackGapValue,
hasLayoutSupport: hasLayoutSupport2,
name,
elementName,
isStyleVariation,
variationName,
layoutSelector,
layoutHasBlockGapSupport
}
];
}
);
}
var getNodesWithStyles = (tree, blockSelectors) => {
const nodes = [];
if (!tree?.styles) {
return nodes;
}
const responsiveMediaQueries = getResponsiveMediaQueries(tree);
const styles = pickStyleKeys(tree.styles, responsiveMediaQueries);
if (styles) {
nodes.push({
styles,
selector: ROOT_BLOCK_SELECTOR,
// Root selector (body) styles should not be wrapped in `:root where()` to keep
// specificity at (0,0,1) and maintain backwards compatibility.
skipSelectorWrapper: true
});
}
Object.entries(import_blocks3.__EXPERIMENTAL_ELEMENTS).forEach(([name, selector3]) => {
if (tree.styles?.elements?.[name]) {
nodes.push({
styles: tree.styles?.elements?.[name] ?? {},
selector: selector3,
elementName: name,
// Top level elements that don't use a class name should not receive the
// `:root :where()` wrapper to maintain backwards compatibility.
skipSelectorWrapper: !ELEMENT_CLASS_NAMES[name]
});
}
});
Object.entries(tree.styles?.blocks ?? {}).forEach(
([blockName, node]) => {
const blockStyles = pickStyleAndPseudoKeys(
node,
blockName,
responsiveMediaQueries
);
const typedNode = node;
const variationNodesToAdd = [];
const variationStyleNodesToAdd = [];
if (typedNode?.variations) {
Object.entries(typedNode.variations).forEach(
([variationName, variation]) => {
const typedVariation = variation;
const variationStyles = pickStyleAndPseudoKeys(
typedVariation,
blockName,
responsiveMediaQueries
);
if (typedVariation?.css) {
variationStyles.css = typedVariation.css;
}
const variationSelector = typeof blockSelectors !== "string" ? blockSelectors[blockName]?.styleVariationSelectors?.[variationName] : void 0;
if (variationSelector && typeof blockSelectors !== "string") {
const blockSelector = blockSelectors[blockName];
variationStyleNodesToAdd.push({
styles: variationStyles,
selector: variationSelector,
featureSelectors: blockSelector?.featureSelectors,
fallbackGapValue: blockSelector?.fallbackGapValue,
hasLayoutSupport: blockSelector?.hasLayoutSupport,
isStyleVariation: true,
variationName,
layoutSelector: variationSelector + blockSelector.selector,
layoutHasBlockGapSupport: true,
name: blockName
});
}
Object.entries(
typedVariation?.elements ?? {}
).forEach(([element, elementStyles]) => {
if (elementStyles && import_blocks3.__EXPERIMENTAL_ELEMENTS[element]) {
variationNodesToAdd.push({
styles: elementStyles,
selector: scopeSelector(
variationSelector,
import_blocks3.__EXPERIMENTAL_ELEMENTS[element]
),
elementName: element,
isStyleVariation: true
});
}
});
Object.entries(typedVariation?.blocks ?? {}).forEach(
([
variationBlockName,
variationBlockStyles
]) => {
const variationBlockSelector = typeof blockSelectors !== "string" ? scopeSelector(
variationSelector,
blockSelectors[variationBlockName]?.selector
) : void 0;
const variationDuotoneSelector = typeof blockSelectors !== "string" ? scopeSelector(
variationSelector,
blockSelectors[variationBlockName]?.duotoneSelector
) : void 0;
const variationFeatureSelectors = typeof blockSelectors !== "string" ? scopeFeatureSelectors(
variationSelector,
blockSelectors[variationBlockName]?.featureSelectors ?? {}
) : void 0;
const variationBlockStyleNodes = pickStyleAndPseudoKeys(
variationBlockStyles,
variationBlockName,
responsiveMediaQueries
);
if (variationBlockStyles?.css) {
variationBlockStyleNodes.css = variationBlockStyles.css;
}
if (!variationBlockSelector || typeof blockSelectors === "string") {
return;
}
variationNodesToAdd.push({
selector: variationBlockSelector,
name: variationBlockName,
isStyleVariation: true,
duotoneSelector: variationDuotoneSelector,
featureSelectors: variationFeatureSelectors,
fallbackGapValue: blockSelectors[variationBlockName]?.fallbackGapValue,
hasLayoutSupport: blockSelectors[variationBlockName]?.hasLayoutSupport,
styles: variationBlockStyleNodes
});
Object.entries(
variationBlockStyles.elements ?? {}
).forEach(
([
variationBlockElement,
variationBlockElementStyles
]) => {
if (variationBlockElementStyles && import_blocks3.__EXPERIMENTAL_ELEMENTS[variationBlockElement]) {
variationNodesToAdd.push({
styles: variationBlockElementStyles,
selector: scopeSelector(
variationBlockSelector,
import_blocks3.__EXPERIMENTAL_ELEMENTS[variationBlockElement]
),
elementName: variationBlockElement,
isStyleVariation: true
});
}
}
);
}
);
}
);
}
if (typeof blockSelectors !== "string" && blockSelectors?.[blockName]?.selector) {
nodes.push({
duotoneSelector: blockSelectors[blockName].duotoneSelector,
fallbackGapValue: blockSelectors[blockName].fallbackGapValue,
hasLayoutSupport: blockSelectors[blockName].hasLayoutSupport,
selector: blockSelectors[blockName].selector,
styles: blockStyles,
featureSelectors: blockSelectors[blockName].featureSelectors,
name: blockName
});
}
nodes.push(...variationStyleNodesToAdd);
Object.entries(typedNode?.elements ?? {}).forEach(
([elementName, value]) => {
if (typeof blockSelectors !== "string" && value && blockSelectors?.[blockName] && import_blocks3.__EXPERIMENTAL_ELEMENTS[elementName]) {
nodes.push({
styles: value,
selector: blockSelectors[blockName]?.selector.split(",").map((sel) => {
const elementSelectors = import_blocks3.__EXPERIMENTAL_ELEMENTS[elementName].split(",");
return elementSelectors.map(
(elementSelector) => sel + " " + elementSelector
);
}).join(","),
elementName
});
}
}
);
nodes.push(...variationNodesToAdd);
}
);
return nodes;
};
var getNodesWithSettings = (tree, blockSelectors) => {
const nodes = [];
if (!tree?.settings) {
return nodes;
}
const pickPresets = (treeToPickFrom) => {
let presets2 = {};
PRESET_METADATA.forEach(({ path }) => {
const value = getValueFromObjectPath(treeToPickFrom, path, false);
if (value !== false) {
presets2 = setImmutably(presets2, path, value);
}
});
return presets2;
};
const presets = pickPresets(tree.settings);
const custom = tree.settings?.custom;
if (Object.keys(presets).length > 0 || custom) {
nodes.push({
presets,
custom,
selector: ROOT_CSS_PROPERTIES_SELECTOR
});
}
Object.entries(tree.settings?.blocks ?? {}).forEach(
([blockName, node]) => {
const blockCustom = node.custom;
if (typeof blockSelectors === "string" || !blockSelectors[blockName]) {
return;
}
const blockPresets = pickPresets(node);
if (Object.keys(blockPresets).length > 0 || blockCustom) {
nodes.push({
presets: blockPresets,
custom: blockCustom,
selector: blockSelectors[blockName]?.selector,
featureSelectors: blockSelectors[blockName]?.featureSelectors
});
}
}
);
return nodes;
};
function renderStylesNode(node, {
tree,
useRootPaddingAlign,
disableLayoutStyles,
hasBlockGapSupport,
hasFallbackGapSupport,
disableRootPadding
}) {
const {
selector: selector3,
selectorSuffix,
mediaQuery,
duotoneSelector,
styles,
fallbackGapValue,
hasLayoutSupport: hasLayoutSupport2,
featureSelectors,
layoutSelector,
layoutHasBlockGapSupport,
skipSelectorWrapper,
name,
variationName
} = node;
let ruleset = "";
const effectiveSelector = selectorSuffix ? appendToSelector(selector3, selectorSuffix) : selector3;
if (featureSelectors && typeof featureSelectors !== "string") {
let featureDeclarations = getFeatureDeclarations(
featureSelectors,
styles
);
featureDeclarations = updateParagraphTextIndentSelector(
featureDeclarations,
tree.settings,
name
);
featureDeclarations = updateButtonWidthDeclarations(
featureDeclarations,
tree.settings
);
Object.entries(featureDeclarations).forEach(
([featureSelector, declarations]) => {
if (declarations.length) {
let selectorForRule = variationName ? getBlockStyleVariationFeatureSelector(
variationName,
featureSelector
) : featureSelector;
selectorForRule = selectorSuffix ? appendToSelector(selectorForRule, selectorSuffix) : selectorForRule;
const rules = declarations.join(";");
ruleset += `:root :where(${selectorForRule}){${rules};}`;
}
}
);
}
if (duotoneSelector) {
const duotoneStyles = {};
if (styles?.filter) {
duotoneStyles.filter = styles.filter;
delete styles.filter;
}
const duotoneDeclarations = getStylesDeclarations(duotoneStyles);
if (duotoneDeclarations.length) {
ruleset += `${duotoneSelector}{${duotoneDeclarations.join(
";"
)};}`;
}
}
const selectorForLayout = layoutSelector ?? effectiveSelector;
const hasBlockGapSupportForLayout = layoutHasBlockGapSupport ?? hasBlockGapSupport;
if (!disableLayoutStyles && (ROOT_BLOCK_SELECTOR === selectorForLayout || hasLayoutSupport2)) {
ruleset += getLayoutStyles({
style: styles,
selector: selectorForLayout,
hasBlockGapSupport: hasBlockGapSupportForLayout,
hasFallbackGapSupport,
fallbackGapValue
});
}
const styleDeclarations = getStylesDeclarations(
styles,
effectiveSelector,
useRootPaddingAlign,
tree,
disableRootPadding
);
if (styleDeclarations?.length) {
const generalSelector = skipSelectorWrapper ? effectiveSelector : `:root :where(${effectiveSelector})`;
ruleset += `${generalSelector}{${styleDeclarations.join(";")};}`;
}
if (styles?.css) {
ruleset += processCSSNesting(
styles.css,
`:root :where(${effectiveSelector})`
);
}
if (mediaQuery && ruleset) {
return `${mediaQuery}{${ruleset}}`;
}
return ruleset;
}
var transformToStyles = (tree, blockSelectors, hasBlockGapSupport, hasFallbackGapSupport, disableLayoutStyles = false, disableRootPadding = false, styleOptions = {}) => {
const options = {
blockGap: true,
blockStyles: true,
layoutStyles: true,
marginReset: true,
presets: true,
rootPadding: true,
variationStyles: false,
...styleOptions
};
const normalizedTree = normalizeStyleStateAliases(tree);
const nodesWithStyles = getNodesWithStyles(
normalizedTree,
blockSelectors
);
const nodesWithSettings = getNodesWithSettings(
normalizedTree,
blockSelectors
);
const useRootPaddingAlign = normalizedTree?.settings?.useRootPaddingAwareAlignments;
const { contentSize, wideSize } = normalizedTree?.settings?.layout || {};
const hasBodyStyles = options.marginReset || options.rootPadding || options.layoutStyles;
let ruleset = "";
if (options.presets && (contentSize || wideSize)) {
ruleset += `${ROOT_CSS_PROPERTIES_SELECTOR} {`;
ruleset = contentSize ? ruleset + ` --wp--style--global--content-size: ${contentSize};` : ruleset;
ruleset = wideSize ? ruleset + ` --wp--style--global--wide-size: ${wideSize};` : ruleset;
ruleset += "}";
}
if (hasBodyStyles) {
ruleset += ":where(body) {margin: 0;";
if (options.rootPadding && useRootPaddingAlign) {
ruleset += `padding-right: 0; padding-left: 0; padding-top: var(--wp--style--root--padding-top); padding-bottom: var(--wp--style--root--padding-bottom) }
.has-global-padding { padding-right: var(--wp--style--root--padding-right); padding-left: var(--wp--style--root--padding-left); }
.has-global-padding > .alignfull { margin-right: calc(var(--wp--style--root--padding-right) * -1); margin-left: calc(var(--wp--style--root--padding-left) * -1); }
.has-global-padding :where(:not(.alignfull.is-layout-flow) > .has-global-padding:not(.wp-block-block, .alignfull)) { padding-right: 0; padding-left: 0; }
.has-global-padding :where(:not(.alignfull.is-layout-flow) > .has-global-padding:not(.wp-block-block, .alignfull)) > .alignfull { margin-left: 0; margin-right: 0;
`;
}
ruleset += "}";
}
if (options.blockStyles) {
const responsiveMediaQueries = getResponsiveMediaQueries(tree);
nodesWithStyles.forEach((node) => {
if (node.isStyleVariation && !options.variationStyles) {
return;
}
const responsiveNodes = getResponsiveStyleNodes(
node,
responsiveMediaQueries
);
[
node,
...responsiveNodes,
...getPseudoStyleNodes(node),
...responsiveNodes.flatMap(getPseudoStyleNodes)
].forEach((expandedNode) => {
ruleset += renderStylesNode(expandedNode, {
tree: normalizedTree,
useRootPaddingAlign,
disableLayoutStyles,
hasBlockGapSupport,
hasFallbackGapSupport,
disableRootPadding
});
});
});
}
if (options.layoutStyles) {
ruleset = ruleset + ".wp-site-blocks > .alignleft { float: left; margin-right: 2em; }";
ruleset = ruleset + ".wp-site-blocks > .alignright { float: right; margin-left: 2em; }";
ruleset = ruleset + ".wp-site-blocks > .aligncenter { justify-content: center; margin-left: auto; margin-right: auto; }";
}
if (options.blockGap && hasBlockGapSupport) {
const gapValue = getGapCSSValue(normalizedTree?.styles?.spacing?.blockGap) || "0.5em";
ruleset = ruleset + `:root :where(.wp-site-blocks) > * { margin-block-start: ${gapValue}; margin-block-end: 0; }`;
ruleset = ruleset + ":root :where(.wp-site-blocks) > :first-child { margin-block-start: 0; }";
ruleset = ruleset + ":root :where(.wp-site-blocks) > :last-child { margin-block-end: 0; }";
}
if (options.presets) {
nodesWithSettings.forEach(({ selector: selector3, presets }) => {
if (ROOT_BLOCK_SELECTOR === selector3 || ROOT_CSS_PROPERTIES_SELECTOR === selector3) {
selector3 = "";
}
const classes = getPresetsClasses(selector3, presets);
if (classes.length > 0) {
ruleset += classes;
}
});
}
return ruleset;
};
var getSelectorsConfig = (blockType, rootSelector) => {
if (blockType?.selectors && Object.keys(blockType.selectors).length > 0) {
return blockType.selectors;
}
const config2 = {
root: rootSelector
};
Object.entries(BLOCK_SUPPORT_FEATURE_LEVEL_SELECTORS).forEach(
([featureKey, featureName]) => {
const featureSelector = getBlockSelector(blockType, featureKey);
if (featureSelector) {
config2[featureName] = featureSelector;
}
}
);
return config2;
};
var getBlockSelectors = (blockTypes, variationInstanceId) => {
const { getBlockStyles: getBlockStyles2 } = (0, import_data3.select)(import_blocks3.store);
const result = {};
blockTypes.forEach((blockType) => {
const name = blockType.name;
const selector3 = getBlockSelector(blockType);
if (!selector3) {
return;
}
let duotoneSelector = getBlockSelector(blockType, "filter.duotone");
if (!duotoneSelector) {
const rootSelector = getBlockSelector(blockType);
const duotoneSupport = (0, import_blocks3.getBlockSupport)(
blockType,
"color.__experimentalDuotone",
false
);
if (typeof duotoneSupport === "string" && rootSelector) {
duotoneSelector = scopeSelector(rootSelector, duotoneSupport);
}
}
const hasLayoutSupport2 = !!blockType?.supports?.layout || !!blockType?.supports?.__experimentalLayout;
const fallbackGapValue = (
// @ts-expect-error
blockType?.supports?.spacing?.blockGap?.__experimentalDefault
);
const blockStyleVariations = getBlockStyles2(name);
const styleVariationSelectors = {};
blockStyleVariations?.forEach((variation) => {
const variationSuffix = variationInstanceId ? `-${variationInstanceId}` : "";
const variationName = `${variation.name}${variationSuffix}`;
const styleVariationSelector = getBlockStyleVariationSelector(
variationName,
selector3
);
styleVariationSelectors[variationName] = styleVariationSelector;
});
const featureSelectors = getSelectorsConfig(blockType, selector3);
result[name] = {
duotoneSelector: duotoneSelector ?? void 0,
fallbackGapValue,
featureSelectors: Object.keys(featureSelectors).length ? featureSelectors : void 0,
hasLayoutSupport: hasLayoutSupport2,
name,
selector: selector3,
styleVariationSelectors: blockStyleVariations?.length ? styleVariationSelectors : void 0
};
});
return result;
};
function processCSSNesting(css, blockSelector) {
let processedCSS = "";
if (!css || css.trim() === "") {
return processedCSS;
}
const parts = css.split("&");
parts.forEach((part) => {
if (!part || part.trim() === "") {
return;
}
const isRootCss = !part.includes("{");
if (isRootCss) {
processedCSS += `:root :where(${blockSelector}){${part.trim()}}`;
} else {
const splitPart = part.replace("}", "").split("{");
if (splitPart.length !== 2) {
return;
}
const [nestedSelector, cssValue] = splitPart;
const matches = nestedSelector.match(/([>+~\s]*::[a-zA-Z-]+)/);
const pseudoPart = matches ? matches[1] : "";
const withoutPseudoElement = matches ? nestedSelector.replace(pseudoPart, "").trim() : nestedSelector.trim();
let combinedSelector;
if (withoutPseudoElement === "") {
combinedSelector = blockSelector;
} else {
combinedSelector = nestedSelector.startsWith(" ") ? scopeSelector(blockSelector, withoutPseudoElement) : appendToSelector(blockSelector, withoutPseudoElement);
}
processedCSS += `:root :where(${combinedSelector})${pseudoPart}{${cssValue.trim()}}`;
}
});
return processedCSS;
}
// packages/global-styles-engine/build-module/lock-unlock.mjs
var import_private_apis2 = __toESM(require_private_apis(), 1);
var { lock: lock2, unlock: unlock2 } = (0, import_private_apis2.__dangerousOptInToUnstableAPIsOnlyForCoreModules)(
"I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.",
"@wordpress/global-styles-engine"
);
// packages/global-styles-engine/build-module/private-apis.mjs
var privateApis = {};
lock2(privateApis, {
getResponsiveMediaQueries,
getViewportBreakpoints,
getViewportBreakpointValueInPixels
});
// packages/block-editor/build-module/components/block-visibility/constants.mjs
var import_i18n2 = __toESM(require_i18n(), 1);
var BLOCK_VISIBILITY_VIEWPORTS = {
desktop: {
label: (0, import_i18n2.__)("Desktop"),
icon: desktop_default,
key: "desktop"
},
tablet: {
label: (0, import_i18n2.__)("Tablet"),
icon: tablet_default,
key: "tablet"
},
mobile: {
label: (0, import_i18n2.__)("Mobile"),
icon: mobile_default,
key: "mobile"
}
};
var BLOCK_VISIBILITY_VIEWPORT_ENTRIES = Object.entries(
BLOCK_VISIBILITY_VIEWPORTS
);
// packages/block-editor/build-module/store/get-block-settings.mjs
var import_blocks4 = __toESM(require_blocks(), 1);
var import_hooks = __toESM(require_hooks(), 1);
// packages/block-editor/build-module/utils/object.mjs
function setImmutably2(object, path, value) {
const pathArray = Array.isArray(path) ? [...path] : [path];
const result = Array.isArray(object) ? [...object] : { ...object };
const leaf = pathArray.pop();
let prev = result;
for (const key of pathArray) {
const lvl = prev[key];
prev[key] = prev = Array.isArray(lvl) ? [...lvl] : { ...lvl };
}
prev[leaf] = value;
return result;
}
var getValueFromObjectPath2 = (object, path, defaultValue) => {
const arrayPath = Array.isArray(path) ? path : path.split(".");
let value = object;
arrayPath.forEach((fieldName) => {
value = value?.[fieldName];
});
return value ?? defaultValue;
};
// packages/block-editor/build-module/store/get-block-settings.mjs
var blockedPaths = [
"color",
"border",
"dimensions",
"typography",
"spacing"
];
var deprecatedFlags = {
"color.palette": (settings2) => settings2.colors,
"color.gradients": (settings2) => settings2.gradients,
"color.custom": (settings2) => settings2.disableCustomColors === void 0 ? void 0 : !settings2.disableCustomColors,
"color.customGradient": (settings2) => settings2.disableCustomGradients === void 0 ? void 0 : !settings2.disableCustomGradients,
"typography.fontSizes": (settings2) => settings2.fontSizes,
"typography.customFontSize": (settings2) => settings2.disableCustomFontSizes === void 0 ? void 0 : !settings2.disableCustomFontSizes,
"typography.lineHeight": (settings2) => settings2.enableCustomLineHeight,
"spacing.units": (settings2) => {
if (settings2.enableCustomUnits === void 0) {
return;
}
if (settings2.enableCustomUnits === true) {
return ["px", "em", "rem", "vh", "vw", "%"];
}
return settings2.enableCustomUnits;
},
"spacing.padding": (settings2) => settings2.enableCustomSpacing
};
var prefixedFlags = {
/*
* These were only available in the plugin
* and can be removed when the minimum WordPress version
* for the plugin is 5.9.
*/
"border.customColor": "border.color",
"border.customStyle": "border.style",
"border.customWidth": "border.width",
"typography.customFontStyle": "typography.fontStyle",
"typography.customFontWeight": "typography.fontWeight",
"typography.customLetterSpacing": "typography.letterSpacing",
"typography.customTextDecorations": "typography.textDecoration",
"typography.customTextTransforms": "typography.textTransform",
/*
* These were part of WordPress 5.8 and we need to keep them.
*/
"border.customRadius": "border.radius",
"spacing.customMargin": "spacing.margin",
"spacing.customPadding": "spacing.padding",
"typography.customLineHeight": "typography.lineHeight"
};
var removeCustomPrefixes = (path) => {
return prefixedFlags[path] || path;
};
function getBlockSettings(state, clientId, ...paths) {
const blockName = getBlockName(state, clientId);
const candidates = [];
if (clientId) {
let id = clientId;
do {
const name = getBlockName(state, id);
if ((0, import_blocks4.hasBlockSupport)(name, "__experimentalSettings", false)) {
candidates.push(id);
}
} while (id = state.blocks.parents.get(id));
}
return paths.map((path) => {
if (blockedPaths.includes(path)) {
console.warn(
"Top level useSetting paths are disabled. Please use a subpath to query the information needed."
);
return void 0;
}
let result = (0, import_hooks.applyFilters)(
"blockEditor.useSetting.before",
void 0,
path,
clientId,
blockName
);
if (void 0 !== result) {
return result;
}
const normalizedPath = removeCustomPrefixes(path);
for (const candidateClientId of candidates) {
const candidateAtts = getBlockAttributes(
state,
candidateClientId
);
result = getValueFromObjectPath2(
candidateAtts.settings?.blocks?.[blockName],
normalizedPath
) ?? getValueFromObjectPath2(
candidateAtts.settings,
normalizedPath
);
if (result !== void 0) {
break;
}
}
const settings2 = getSettings(state);
if (result === void 0 && blockName) {
result = getValueFromObjectPath2(
settings2.__experimentalFeatures?.blocks?.[blockName],
normalizedPath
);
}
if (result === void 0) {
result = getValueFromObjectPath2(
settings2.__experimentalFeatures,
normalizedPath
);
}
if (result !== void 0) {
if (import_blocks4.__EXPERIMENTAL_PATHS_WITH_OVERRIDE[normalizedPath]) {
return result.custom ?? result.theme ?? result.default;
}
return result;
}
const deprecatedSettingsValue = deprecatedFlags[normalizedPath]?.(settings2);
if (deprecatedSettingsValue !== void 0) {
return deprecatedSettingsValue;
}
return normalizedPath === "typography.dropCap" ? true : void 0;
});
}
// packages/block-editor/build-module/store/private-selectors.mjs
var { isContentBlock: isContentBlock2 } = unlock(import_blocks5.privateApis);
var { getViewportBreakpoints: getViewportBreakpoints2 } = unlock(privateApis);
function isViewportAvailable(state, viewport) {
if (viewport === BLOCK_VISIBILITY_VIEWPORTS.desktop.key) {
return true;
}
return getViewportBreakpoints2(
getSettings(state)?.__experimentalFeatures?.viewport
)[viewport] !== void 0;
}
function isBlockInterfaceHidden2(state) {
return state.isBlockInterfaceHidden;
}
function getLastInsertedBlocksClientIds(state) {
return state?.lastBlockInserted?.clientIds;
}
function getBlockWithoutAttributes(state, clientId) {
return state.blocks.byClientId.get(clientId);
}
var isBlockSubtreeDisabled = (state, clientId) => {
const isChildSubtreeDisabled = (childClientId) => {
return getBlockEditingMode(state, childClientId) === "disabled" && getBlockOrder(state, childClientId).every(
isChildSubtreeDisabled
);
};
return getBlockOrder(state, clientId).every(isChildSubtreeDisabled);
};
function isContainerInsertableToInContentOnlyMode(state, blockName, rootClientId) {
const isBlockContentBlock = isContentBlock2(blockName);
const rootBlockName = getBlockName(state, rootClientId);
const isContainerContentBlock = isContentBlock2(rootBlockName);
const isRootBlockMain = getSectionRootClientId(state) === rootClientId;
return isRootBlockMain || isContainerContentBlock && isBlockContentBlock;
}
function getClientIdWithClientIdsTreeUnmemoized(state, clientId) {
return {
clientId,
innerBlocks: getClientIdsTreeUnmemoized(state, clientId)
};
}
function getClientIdsTreeUnmemoized(state, rootClientId = "") {
return getBlockOrder(state, rootClientId).map(
(clientId) => getClientIdWithClientIdsTreeUnmemoized(state, clientId)
);
}
var getClientIdWithClientIdsTree = (0, import_data4.createSelector)(
getClientIdWithClientIdsTreeUnmemoized,
(state) => [state.blocks.order]
);
var getClientIdsTree = (0, import_data4.createSelector)(
getClientIdsTreeUnmemoized,
(state) => [state.blocks.order]
);
function getFilteredClientIdsTreeUnmemoized(state, rootClientId, includesBlock) {
const blockOrder = getBlockOrder(state, rootClientId);
const result = [];
for (const clientId of blockOrder) {
const innerBlocks = getFilteredClientIdsTreeUnmemoized(
state,
clientId,
includesBlock
);
if (includesBlock(state, clientId)) {
result.push({ clientId, innerBlocks });
} else {
result.push(...innerBlocks);
}
}
return result;
}
function getEnabledClientIdsTreeUnmemoized(state, rootClientId) {
return getFilteredClientIdsTreeUnmemoized(
state,
rootClientId,
(_state, clientId) => getBlockEditingMode(_state, clientId) !== "disabled"
);
}
function hasExplicitDisabledParent(state, clientId) {
let parent = state.blocks.parents.get(clientId);
while (parent !== void 0) {
const parentBlockEditingMode = state.blocks.blockEditingModes.get(parent);
if (parentBlockEditingMode) {
return parentBlockEditingMode === "disabled";
}
parent = state.blocks.parents.get(parent);
}
return false;
}
function getListViewClientIdsTreeUnmemoized(state, rootClientId) {
return getFilteredClientIdsTreeUnmemoized(
state,
rootClientId,
(_state, clientId) => {
if (getBlockEditingMode(_state, clientId) !== "disabled") {
return true;
}
const explicitBlockEditingMode = _state.blocks.blockEditingModes.get(clientId);
if (explicitBlockEditingMode) {
return explicitBlockEditingMode !== "disabled";
}
if (hasExplicitDisabledParent(_state, clientId)) {
return false;
}
if (_state.editedContentOnlySection) {
if (isWithinEditedContentOnlySection(_state, clientId)) {
return false;
}
const parentSectionBlock = getParentSectionBlock(
_state,
clientId
);
if (!parentSectionBlock) {
return true;
}
if (isContentBlock2(getBlockName(_state, clientId))) {
return true;
}
}
return false;
}
);
}
var getEnabledClientIdsTree = (0, import_data4.createRegistrySelector)(
() => (0, import_data4.createSelector)(getEnabledClientIdsTreeUnmemoized, (state) => [
state.blocks.order,
state.derivedBlockEditingModes,
state.blocks.blockEditingModes
])
);
var getListViewClientIdsTree = (0, import_data4.createRegistrySelector)(
() => (0, import_data4.createSelector)(getListViewClientIdsTreeUnmemoized, (state) => [
state.blocks.order,
state.derivedBlockEditingModes,
state.blocks.blockEditingModes,
state.blocks.parents,
state.blocks.byClientId,
state.blocks.attributes,
state.blockListSettings,
state.editedContentOnlySection,
state.settings
])
);
var getEnabledBlockParents = (0, import_data4.createSelector)(
(state, clientId, ascending = false) => {
return getBlockParents(state, clientId, ascending).filter(
(parent) => getBlockEditingMode(state, parent) !== "disabled"
);
},
(state) => [
state.blocks.parents,
state.blocks.blockEditingModes,
state.settings.templateLock,
state.blockListSettings
]
);
function getRemovalPromptData(state) {
return state.removalPromptData;
}
function getBlockRemovalRules(state) {
return state.blockRemovalRules;
}
var getStyleOverrides = (0, import_data4.createSelector)(
(state) => {
const clientIds = getClientIdsWithDescendants(state);
const clientIdMap = clientIds.reduce((acc, clientId, index2) => {
acc[clientId] = index2;
return acc;
}, {});
return [...state.styleOverrides].sort((overrideA, overrideB) => {
const [, { clientId: clientIdA }] = overrideA;
const [, { clientId: clientIdB }] = overrideB;
const aIndex = clientIdMap[clientIdA] ?? -1;
const bIndex = clientIdMap[clientIdB] ?? -1;
return aIndex - bIndex;
});
},
(state) => [state.blocks.order, state.styleOverrides]
);
function getRegisteredInserterMediaCategories(state) {
return state.registeredInserterMediaCategories;
}
var getInserterMediaCategories = (0, import_data4.createSelector)(
(state) => {
const {
settings: {
inserterMediaCategories,
allowedMimeTypes,
enableOpenverseMediaCategory
},
registeredInserterMediaCategories: registeredInserterMediaCategories2
} = state;
if (!inserterMediaCategories && !registeredInserterMediaCategories2.length || !allowedMimeTypes) {
return;
}
const coreInserterMediaCategoriesNames = inserterMediaCategories?.map(({ name }) => name) || [];
const mergedCategories = [
...inserterMediaCategories || [],
...(registeredInserterMediaCategories2 || []).filter(
({ name }) => !coreInserterMediaCategoriesNames.includes(name)
)
];
return mergedCategories.filter((category) => {
if (!enableOpenverseMediaCategory && category.name === "openverse") {
return false;
}
return Object.values(allowedMimeTypes).some(
(mimeType) => mimeType.startsWith(`${category.mediaType}/`)
);
});
},
(state) => [
state.settings.inserterMediaCategories,
state.settings.allowedMimeTypes,
state.settings.enableOpenverseMediaCategory,
state.registeredInserterMediaCategories
]
);
var hasAllowedPatterns = (0, import_data4.createRegistrySelector)(
(select3) => (0, import_data4.createSelector)(
(state, rootClientId = null) => {
const { getAllPatterns: getAllPatterns2 } = unlock(select3(STORE_NAME));
const patterns = getAllPatterns2();
const { allowedBlockTypes } = getSettings(state);
return patterns.some((pattern) => {
const { inserter = true } = pattern;
if (!inserter) {
return false;
}
const grammar = getGrammar(pattern);
return checkAllowListRecursive(grammar, allowedBlockTypes) && grammar.every(
({ name: blockName }) => canInsertBlockType(state, blockName, rootClientId)
);
});
},
(state, rootClientId) => [
...getAllPatternsDependants(select3)(state),
...getInsertBlockTypeDependants(select3)(state, rootClientId)
]
)
);
var getPatternBySlug = (0, import_data4.createRegistrySelector)(
(select3) => (0, import_data4.createSelector)(
(state, patternName) => {
if (patternName?.startsWith("core/block/")) {
const _id = parseInt(
patternName.slice("core/block/".length),
10
);
const block = unlock(select3(STORE_NAME)).getReusableBlocks().find(({ id }) => id === _id);
if (!block) {
return null;
}
return mapUserPattern(
block,
state.settings[userPatternCategoriesSelectKey]?.(
select3
) ?? state.settings.__experimentalUserPatternCategories
);
}
return [
// This setting is left for back compat.
...state.settings.__experimentalBlockPatterns ?? [],
...state.settings[selectBlockPatternsKey]?.(select3) ?? []
].find(({ name }) => name === patternName);
},
(state, patternName) => patternName?.startsWith("core/block/") ? [
unlock(select3(STORE_NAME)).getReusableBlocks(),
state.settings.__experimentalReusableBlocks
] : [
state.settings.__experimentalBlockPatterns,
state.settings[selectBlockPatternsKey]?.(select3)
]
)
);
var getAllPatterns = (0, import_data4.createRegistrySelector)(
(select3) => (0, import_data4.createSelector)((state) => {
return [
...unlock(select3(STORE_NAME)).getReusableBlocks().map(
(userPattern) => mapUserPattern(
userPattern,
state.settings[userPatternCategoriesSelectKey]?.(
select3
) ?? state.settings.__experimentalUserPatternCategories
)
),
// This setting is left for back compat.
...state.settings.__experimentalBlockPatterns ?? [],
...state.settings[selectBlockPatternsKey]?.(select3) ?? []
].filter(
(x2, index2, arr) => index2 === arr.findIndex((y2) => x2.name === y2.name)
);
}, getAllPatternsDependants(select3))
);
var EMPTY_ARRAY = [];
var getReusableBlocks = (0, import_data4.createRegistrySelector)(
(select3) => (state) => {
const reusableBlocksSelect = state.settings[reusableBlocksSelectKey];
return (reusableBlocksSelect ? reusableBlocksSelect(select3) : state.settings.__experimentalReusableBlocks) ?? EMPTY_ARRAY;
}
);
function getLastFocus(state) {
return state.lastFocus;
}
function isDragging2(state) {
return state.isDragging;
}
function getExpandedBlock(state) {
return state.expandedBlock;
}
var getContentLockingParent = (state, clientId) => {
let current = clientId;
let result;
while (!result && (current = state.blocks.parents.get(current))) {
if (getTemplateLock(state, current) === "contentOnly") {
result = current;
}
}
return result;
};
function isSectionBlockCandidate(state, clientId) {
const blockName = getBlockName(state, clientId);
if (blockName === "core/block") {
return true;
}
const attributes = getBlockAttributes(state, clientId);
const isTemplatePart9 = blockName === "core/template-part";
const isIsolatedEditor = state.settings?.[isIsolatedEditorKey];
const disableContentOnlyForUnsyncedPatterns = state.settings?.disableContentOnlyForUnsyncedPatterns;
const disableContentOnlyForTemplateParts = state.settings?.disableContentOnlyForTemplateParts;
if ((!disableContentOnlyForUnsyncedPatterns && attributes?.metadata?.patternName || isTemplatePart9 && !disableContentOnlyForTemplateParts) && !isIsolatedEditor) {
return true;
}
const hasContentOnlyTemplateLock = getTemplateLock(state, clientId) === "contentOnly";
const rootClientId = getBlockRootClientId(state, clientId);
const hasRootContentOnlyTemplateLock = getTemplateLock(state, rootClientId) === "contentOnly";
if (hasContentOnlyTemplateLock && !hasRootContentOnlyTemplateLock) {
return true;
}
return false;
}
var getParentSectionBlock = (state, clientId) => {
if (isWithinEditedContentOnlySection(state, clientId)) {
return void 0;
}
let current = clientId;
let result;
while (current = state.blocks.parents.get(current)) {
if (isSectionBlockCandidate(state, current)) {
result = current;
}
}
return result;
};
function isSectionBlock(state, clientId) {
if (isWithinEditedContentOnlySection(state, clientId) || getParentSectionBlock(state, clientId)) {
return false;
}
return isSectionBlockCandidate(state, clientId);
}
function getEditedContentOnlySection(state) {
return state.editedContentOnlySection;
}
function isWithinEditedContentOnlySection(state, clientId) {
if (!state.editedContentOnlySection) {
return false;
}
if (state.editedContentOnlySection === clientId) {
return true;
}
let current = clientId;
while (current = state.blocks.parents.get(current)) {
if (state.editedContentOnlySection === current) {
return true;
}
}
return false;
}
var getBlockStyles = (0, import_data4.createSelector)(
(state, clientIds) => clientIds.reduce((styles, clientId) => {
styles[clientId] = state.blocks.attributes.get(clientId)?.style;
return styles;
}, {}),
(state, clientIds) => [
...clientIds.map(
(clientId) => state.blocks.attributes.get(clientId)?.style
)
]
);
function getSectionRootClientId(state) {
return state.settings?.[sectionRootClientIdKey];
}
function isZoomOut(state) {
return state.zoomLevel === "auto-scaled" || state.zoomLevel < 100;
}
function getZoomLevel(state) {
return state.zoomLevel;
}
function getClosestAllowedInsertionPoint(state, name, clientId = "") {
const blockNames = Array.isArray(name) ? name : [name];
const areBlockNamesAllowedInClientId = (id) => blockNames.every(
(currentName) => canInsertBlockType(state, currentName, id)
);
if (!clientId) {
if (areBlockNamesAllowedInClientId(clientId)) {
return clientId;
}
const sectionRootClientId = getSectionRootClientId(state);
if (sectionRootClientId && areBlockNamesAllowedInClientId(sectionRootClientId)) {
return sectionRootClientId;
}
return null;
}
let current = clientId;
while (current !== null && !areBlockNamesAllowedInClientId(current)) {
const parentClientId = getBlockRootClientId(state, current);
current = parentClientId;
}
return current;
}
function getClosestAllowedInsertionPointForPattern(state, pattern, clientId) {
const { allowedBlockTypes } = getSettings(state);
const isAllowed = checkAllowListRecursive(
getGrammar(pattern),
allowedBlockTypes
);
if (!isAllowed) {
return null;
}
const names = getGrammar(pattern).map(({ blockName: name }) => name);
return getClosestAllowedInsertionPoint(state, names, clientId);
}
function getInsertionPoint(state) {
return state.insertionPoint;
}
var isBlockHiddenAnywhere = (state, clientId) => {
const blockName = getBlockName(state, clientId);
if (!(0, import_blocks5.hasBlockSupport)(blockName, "visibility", true)) {
return false;
}
const attributes = state.blocks.attributes.get(clientId);
const blockVisibility2 = attributes?.metadata?.blockVisibility;
if (blockVisibility2 === false) {
return true;
}
if (typeof blockVisibility2?.viewport === "object" && blockVisibility2?.viewport !== null) {
return Object.values(BLOCK_VISIBILITY_VIEWPORTS).some(
(viewport) => isViewportAvailable(state, viewport.key) && blockVisibility2?.viewport?.[viewport.key] === false
);
}
return false;
};
var isBlockHiddenEverywhere = (state, clientId) => {
const blockName = getBlockName(state, clientId);
if (!(0, import_blocks5.hasBlockSupport)(blockName, "visibility", true)) {
return false;
}
const attributes = state.blocks.attributes.get(clientId);
const blockVisibility2 = attributes?.metadata?.blockVisibility;
if (blockVisibility2 === false) {
return true;
}
return false;
};
var isBlockParentHiddenEverywhere = (state, clientId) => {
const parents = getBlockParents(state, clientId);
return parents.some(
(parentId) => isBlockHiddenEverywhere(state, parentId)
);
};
var isBlockHiddenAtViewport = (state, clientId, viewport) => {
if (isBlockHiddenEverywhere(state, clientId)) {
return true;
}
const attributes = state.blocks.attributes.get(clientId);
const blockVisibilityViewport = attributes?.metadata?.blockVisibility?.viewport;
if (typeof blockVisibilityViewport === "object" && blockVisibilityViewport !== null && typeof viewport === "string") {
const viewportKey = viewport.toLowerCase();
return isViewportAvailable(state, viewportKey) && blockVisibilityViewport?.[viewportKey] === false;
}
return false;
};
var isBlockParentHiddenAtViewport = (state, clientId, viewport) => {
const parents = getBlockParents(state, clientId);
return parents.some(
(parentId) => isBlockHiddenAtViewport(state, parentId, viewport)
);
};
function hasBlockSpotlight2(state) {
return !!state.hasBlockSpotlight || !!state.editedContentOnlySection;
}
function isEditLockedBlock(state, clientId) {
const attributes = getBlockAttributes(state, clientId);
return !!attributes?.lock?.edit;
}
function isMoveLockedBlock(state, clientId) {
const attributes = getBlockAttributes(state, clientId);
if (attributes?.lock?.move !== void 0) {
return !!attributes?.lock?.move;
}
const rootClientId = getBlockRootClientId(state, clientId);
const templateLock = getTemplateLock(state, rootClientId);
return templateLock === "all";
}
function isRemoveLockedBlock(state, clientId) {
const attributes = getBlockAttributes(state, clientId);
if (attributes?.lock?.remove !== void 0) {
return !!attributes?.lock?.remove;
}
const rootClientId = getBlockRootClientId(state, clientId);
const templateLock = getTemplateLock(state, rootClientId);
return templateLock === "all" || templateLock === "insert";
}
function isLockedBlock(state, clientId) {
return isEditLockedBlock(state, clientId) || isMoveLockedBlock(state, clientId) || isRemoveLockedBlock(state, clientId);
}
function isListViewContentPanelOpen(state) {
return state.listViewContentPanelOpen;
}
function isListViewPanelOpened(state, clientId) {
if (state.openedListViewPanels?.allOpen) {
return true;
}
return state.openedListViewPanels?.panels?.[clientId] === true;
}
function getListViewExpandRevision(state) {
return state.listViewExpandRevision || 0;
}
function shouldRenderBlockListView(state, clientId) {
const blockName = getBlockName(state, clientId);
if (blockName === "core/navigation") {
return true;
}
if (!(0, import_blocks5.hasBlockSupport)(blockName, "listView")) {
return false;
}
const allowedBlocks = getBlockListSettings(
state,
clientId
)?.allowedBlocks;
const isEmptyAndNoAllowedBlocks = getBlockOrder(state, clientId).length === 0 && (allowedBlocks === false || Array.isArray(allowedBlocks) && allowedBlocks.length === 0);
return !isEmptyAndNoAllowedBlocks;
}
function getViewportModalClientIds(state) {
return state.viewportModalClientIds;
}
function getRequestedInspectorTab(state) {
return state.requestedInspectorTab;
}
var DEFAULT_BLOCK_STYLE_STATE = {
viewport: "default",
pseudo: "default"
};
function getStyleStateViewport(state) {
return state.styleStateViewport ?? DEFAULT_BLOCK_STYLE_STATE.viewport;
}
function isResponsiveEditing2(state) {
return state.isResponsiveEditing;
}
var getSelectedBlockStyleState = (0, import_data4.createSelector)(
(state, clientId) => {
const perBlockState = state.selectedBlockStyleState?.clientId === clientId ? state.selectedBlockStyleState.value ?? DEFAULT_BLOCK_STYLE_STATE : DEFAULT_BLOCK_STYLE_STATE;
return {
...perBlockState,
// The viewport is tracked globally, so inject it here. This way
// consumers receive a single combined state object instead of
// merging the global viewport themselves, and selectors derived
// from this stay consistent.
viewport: getStyleStateViewport(state)
};
},
(state) => [state.styleStateViewport, state.selectedBlockStyleState]
);
function hasSelectedStyleState(state, clientId) {
const selectedState = getSelectedBlockStyleState(state, clientId);
return selectedState.viewport !== DEFAULT_BLOCK_STYLE_STATE.viewport || selectedState.pseudo !== DEFAULT_BLOCK_STYLE_STATE.pseudo;
}
function isSelectedBlockStyleStateShownOnCanvas(state, clientId) {
if (state.selectedBlockStyleState?.clientId !== clientId) {
return true;
}
return state.selectedBlockStyleState.showStateOnCanvas ?? true;
}
// packages/block-editor/build-module/components/inserter/block-patterns-tab/utils.mjs
var import_i18n3 = __toESM(require_i18n(), 1);
var INSERTER_PATTERN_TYPES = {
user: "user",
theme: "theme",
directory: "directory"
};
var INSERTER_SYNC_TYPES = {
full: "fully",
unsynced: "unsynced"
};
var allPatternsCategory = {
name: "allPatterns",
label: (0, import_i18n3._x)("All", "patterns")
};
var myPatternsCategory = {
name: "myPatterns",
label: (0, import_i18n3.__)("My patterns")
};
var starterPatternsCategory = {
name: "core/starter-content",
label: (0, import_i18n3.__)("Starter content")
};
function isPatternFiltered(pattern, sourceFilter, syncFilter) {
const isUserPattern = pattern.name.startsWith("core/block");
const isDirectoryPattern = pattern.source === "core" || pattern.source?.startsWith("pattern-directory");
if (sourceFilter === INSERTER_PATTERN_TYPES.theme && (isUserPattern || isDirectoryPattern)) {
return true;
}
if (sourceFilter === INSERTER_PATTERN_TYPES.directory && (isUserPattern || !isDirectoryPattern)) {
return true;
}
if (sourceFilter === INSERTER_PATTERN_TYPES.user && pattern.type !== INSERTER_PATTERN_TYPES.user) {
return true;
}
if (syncFilter === INSERTER_SYNC_TYPES.full && pattern.syncStatus !== "") {
return true;
}
if (syncFilter === INSERTER_SYNC_TYPES.unsynced && pattern.syncStatus !== "unsynced" && isUserPattern) {
return true;
}
return false;
}
// packages/block-editor/build-module/store/utils.mjs
var isFiltered = /* @__PURE__ */ Symbol("isFiltered");
var parsedPatternCache = /* @__PURE__ */ new WeakMap();
var grammarMapCache = /* @__PURE__ */ new WeakMap();
function mapUserPattern(userPattern, __experimentalUserPatternCategories = []) {
return {
name: `core/block/${userPattern.id}`,
id: userPattern.id,
type: INSERTER_PATTERN_TYPES.user,
title: userPattern.title?.raw,
categories: userPattern.wp_pattern_category?.map((catId) => {
const category = __experimentalUserPatternCategories.find(
({ id }) => id === catId
);
return category ? category.slug : catId;
}),
content: userPattern.content?.raw,
syncStatus: userPattern.wp_pattern_sync_status
};
}
function parsePattern(pattern) {
const blocks2 = (0, import_blocks6.parse)(pattern.content, {
__unstableSkipMigrationLogs: true
});
if (blocks2.length === 1) {
blocks2[0].attributes = {
...blocks2[0].attributes,
metadata: {
...blocks2[0].attributes.metadata || {},
categories: pattern.categories,
patternName: pattern.name,
name: blocks2[0].attributes.metadata?.name || pattern.title
}
};
}
return {
...pattern,
blocks: blocks2
};
}
function getParsedPattern(pattern) {
let parsedPattern = parsedPatternCache.get(pattern);
if (!parsedPattern) {
parsedPattern = parsePattern(pattern);
parsedPatternCache.set(pattern, parsedPattern);
}
return parsedPattern;
}
function getGrammar(pattern) {
let grammarMap = grammarMapCache.get(pattern);
if (!grammarMap) {
grammarMap = (0, import_block_serialization_default_parser.parse)(pattern.content);
grammarMap = grammarMap.filter((block) => block.blockName !== null);
grammarMapCache.set(pattern, grammarMap);
}
return grammarMap;
}
var checkAllowList = (list, item, defaultResult = null) => {
if (typeof list === "boolean") {
return list;
}
if (Array.isArray(list)) {
if (list.includes("core/post-content") && item === null) {
return true;
}
return list.includes(item);
}
return defaultResult;
};
var checkAllowListRecursive = (blocks2, allowedBlockTypes) => {
if (typeof allowedBlockTypes === "boolean") {
return allowedBlockTypes;
}
const blocksQueue = [...blocks2];
while (blocksQueue.length > 0) {
const block = blocksQueue.shift();
const isAllowed = checkAllowList(
allowedBlockTypes,
block.name || block.blockName,
true
);
if (!isAllowed) {
return false;
}
block.innerBlocks?.forEach((innerBlock) => {
blocksQueue.push(innerBlock);
});
}
return true;
};
var getAllPatternsDependants = (select3) => (state) => {
return [
state.settings.__experimentalBlockPatterns,
state.settings[userPatternCategoriesSelectKey]?.(select3) ?? state.settings.__experimentalUserPatternCategories,
state.settings.__experimentalReusableBlocks,
state.settings[selectBlockPatternsKey]?.(select3),
state.blockPatterns,
unlock(select3(STORE_NAME)).getReusableBlocks()
];
};
var getInsertBlockTypeDependants = () => (state, rootClientId) => {
return [
state.blockListSettings.get(rootClientId),
state.blocks.byClientId.get(rootClientId),
state.blocks.order.get(rootClientId || ""),
state.settings.allowedBlockTypes,
state.settings.templateLock,
getBlockEditingMode(state, rootClientId),
getSectionRootClientId(state),
isSectionBlock(state, rootClientId),
getParentSectionBlock(state, rootClientId)
];
};
// packages/block-editor/build-module/utils/sorting.mjs
function isGreater(a2, b2) {
if (typeof a2 === "string" && typeof b2 === "string") {
return a2 > b2;
}
return Number(a2) > Number(b2);
}
var comparator = (field, items, order) => {
return (a2, b2) => {
let cmpA, cmpB;
if (typeof field === "function") {
cmpA = field(a2);
cmpB = field(b2);
} else {
cmpA = a2[field];
cmpB = b2[field];
}
if (isGreater(cmpA, cmpB)) {
return order === "asc" ? 1 : -1;
} else if (isGreater(cmpB, cmpA)) {
return order === "asc" ? -1 : 1;
}
const orderA = items.findIndex((item) => item === a2);
const orderB = items.findIndex((item) => item === b2);
if (orderA > orderB) {
return 1;
} else if (orderB > orderA) {
return -1;
}
return 0;
};
};
function orderBy(items, field, order = "asc") {
return items.concat().sort(comparator(field, items, order));
}
// packages/block-editor/build-module/store/selectors.mjs
var { isContentBlock: isContentBlock3 } = unlock(import_blocks7.privateApis);
var MILLISECONDS_PER_HOUR = 3600 * 1e3;
var MILLISECONDS_PER_DAY = 24 * 3600 * 1e3;
var MILLISECONDS_PER_WEEK = 7 * 24 * 3600 * 1e3;
var EMPTY_ARRAY2 = [];
var EMPTY_SET = /* @__PURE__ */ new Set();
var DEFAULT_INSERTER_OPTIONS = {
[isFiltered]: true
};
function getBlockName(state, clientId) {
const block = state.blocks.byClientId.get(clientId);
return block ? block.name : null;
}
function isBlockValid(state, clientId) {
const block = state.blocks.byClientId.get(clientId);
return !!block && block.isValid;
}
function getBlockAttributes(state, clientId) {
const block = state.blocks.byClientId.get(clientId);
if (!block) {
return null;
}
return state.blocks.attributes.get(clientId);
}
function getBlock(state, clientId) {
if (!state.blocks.byClientId.has(clientId)) {
return null;
}
return state.blocks.tree.get(clientId);
}
var __unstableGetBlockWithoutInnerBlocks = (0, import_data5.createSelector)(
(state, clientId) => {
const block = state.blocks.byClientId.get(clientId);
if (!block) {
return null;
}
return {
...block,
attributes: getBlockAttributes(state, clientId)
};
},
(state, clientId) => [
state.blocks.byClientId.get(clientId),
state.blocks.attributes.get(clientId)
]
);
function getBlocks(state, rootClientId) {
const treeKey = !rootClientId || !areInnerBlocksControlled(state, rootClientId) ? rootClientId || "" : "controlled||" + rootClientId;
return state.blocks.tree.get(treeKey)?.innerBlocks || EMPTY_ARRAY2;
}
function __unstableGetClientIdWithClientIdsTree(state, clientId) {
(0, import_deprecated2.default)(
"wp.data.select( 'core/block-editor' ).__unstableGetClientIdWithClientIdsTree",
{
since: "6.3",
version: "6.5"
}
);
return getClientIdWithClientIdsTree(state, clientId);
}
function __unstableGetClientIdsTree(state, rootClientId) {
(0, import_deprecated2.default)(
"wp.data.select( 'core/block-editor' ).__unstableGetClientIdsTree",
{
since: "6.3",
version: "6.5"
}
);
return getClientIdsTree(state, rootClientId);
}
var getClientIdsOfDescendants = (0, import_data5.createSelector)(
(state, rootIds) => {
rootIds = Array.isArray(rootIds) ? [...rootIds] : [rootIds];
const ids = [];
for (const rootId of rootIds) {
const order = state.blocks.order.get(rootId);
if (order) {
ids.push(...order);
}
}
let index2 = 0;
while (index2 < ids.length) {
const id = ids[index2];
const order = state.blocks.order.get(id);
if (order) {
ids.splice(index2 + 1, 0, ...order);
}
index2++;
}
return ids;
},
(state) => [state.blocks.order]
);
var getClientIdsWithDescendants = (state) => getClientIdsOfDescendants(state, "");
var getGlobalBlockCount = (0, import_data5.createSelector)(
(state, blockName) => {
const clientIds = getClientIdsWithDescendants(state);
if (!blockName) {
return clientIds.length;
}
let count = 0;
for (const clientId of clientIds) {
const block = state.blocks.byClientId.get(clientId);
if (block.name === blockName) {
count++;
}
}
return count;
},
(state) => [state.blocks.order, state.blocks.byClientId]
);
var getBlocksByName = (0, import_data5.createSelector)(
(state, blockName) => {
if (!blockName) {
return EMPTY_ARRAY2;
}
const blockNames = Array.isArray(blockName) ? blockName : [blockName];
const clientIds = getClientIdsWithDescendants(state);
const foundBlocks = clientIds.filter((clientId) => {
const block = state.blocks.byClientId.get(clientId);
return blockNames.includes(block.name);
});
return foundBlocks.length > 0 ? foundBlocks : EMPTY_ARRAY2;
},
(state) => [state.blocks.order, state.blocks.byClientId]
);
function __experimentalGetGlobalBlocksByName(state, blockName) {
(0, import_deprecated2.default)(
"wp.data.select( 'core/block-editor' ).__experimentalGetGlobalBlocksByName",
{
since: "6.5",
alternative: `wp.data.select( 'core/block-editor' ).getBlocksByName`
}
);
return getBlocksByName(state, blockName);
}
var getBlocksByClientId = (0, import_data5.createSelector)(
(state, clientIds) => (Array.isArray(clientIds) ? clientIds : [clientIds]).map(
(clientId) => getBlock(state, clientId)
),
(state, clientIds) => (Array.isArray(clientIds) ? clientIds : [clientIds]).map(
(clientId) => state.blocks.tree.get(clientId)
)
);
var getBlockNamesByClientId = (0, import_data5.createSelector)(
(state, clientIds) => getBlocksByClientId(state, clientIds).filter(Boolean).map((block) => block.name),
(state, clientIds) => getBlocksByClientId(state, clientIds)
);
function getBlockCount(state, rootClientId) {
return getBlockOrder(state, rootClientId).length;
}
function getSelectionStart(state) {
return state.selection.selectionStart;
}
function getSelectionEnd(state) {
return state.selection.selectionEnd;
}
function getBlockSelectionStart(state) {
return state.selection.selectionStart.clientId;
}
function getBlockSelectionEnd(state) {
return state.selection.selectionEnd.clientId;
}
function getSelectedBlockCount(state) {
const multiSelectedBlockCount = getMultiSelectedBlockClientIds(state).length;
if (multiSelectedBlockCount) {
return multiSelectedBlockCount;
}
return state.selection.selectionStart.clientId ? 1 : 0;
}
function hasSelectedBlock(state) {
const { selectionStart, selectionEnd } = state.selection;
return !!selectionStart.clientId && selectionStart.clientId === selectionEnd.clientId;
}
function getSelectedBlockClientId(state) {
const { selectionStart, selectionEnd } = state.selection;
const { clientId } = selectionStart;
if (!clientId || clientId !== selectionEnd.clientId) {
return null;
}
return clientId;
}
function getSelectedBlock(state) {
const clientId = getSelectedBlockClientId(state);
return clientId ? getBlock(state, clientId) : null;
}
function getBlockRootClientId(state, clientId) {
return state.blocks.parents.get(clientId) ?? null;
}
var getBlockParents = (0, import_data5.createSelector)(
(state, clientId, ascending = false) => {
const parents = [];
let current = clientId;
while (current = state.blocks.parents.get(current)) {
parents.push(current);
}
if (!parents.length) {
return EMPTY_ARRAY2;
}
return ascending ? parents : parents.reverse();
},
(state) => [state.blocks.parents]
);
var getBlockParentsByBlockName = (0, import_data5.createSelector)(
(state, clientId, blockName, ascending = false) => {
const parents = getBlockParents(state, clientId, ascending);
const hasName = Array.isArray(blockName) ? (name) => blockName.includes(name) : (name) => blockName === name;
return parents.filter((id) => hasName(getBlockName(state, id)));
},
(state) => [state.blocks.parents]
);
function getBlockHierarchyRootClientId(state, clientId) {
let current = clientId;
let parent;
do {
parent = current;
current = state.blocks.parents.get(current);
} while (current);
return parent;
}
function getLowestCommonAncestorWithSelectedBlock(state, clientId) {
const selectedId = getSelectedBlockClientId(state);
const clientParents = [...getBlockParents(state, clientId), clientId];
const selectedParents = [
...getBlockParents(state, selectedId),
selectedId
];
let lowestCommonAncestor;
const maxDepth = Math.min(clientParents.length, selectedParents.length);
for (let index2 = 0; index2 < maxDepth; index2++) {
if (clientParents[index2] === selectedParents[index2]) {
lowestCommonAncestor = clientParents[index2];
} else {
break;
}
}
return lowestCommonAncestor;
}
function getAdjacentBlockClientId(state, startClientId, modifier = 1) {
if (startClientId === void 0) {
startClientId = getSelectedBlockClientId(state);
}
if (startClientId === void 0) {
if (modifier < 0) {
startClientId = getFirstMultiSelectedBlockClientId(state);
} else {
startClientId = getLastMultiSelectedBlockClientId(state);
}
}
if (!startClientId) {
return null;
}
const rootClientId = getBlockRootClientId(state, startClientId);
if (rootClientId === null) {
return null;
}
const { order } = state.blocks;
const orderSet = order.get(rootClientId);
const index2 = orderSet.indexOf(startClientId);
const nextIndex = index2 + 1 * modifier;
if (nextIndex < 0) {
return null;
}
if (nextIndex === orderSet.length) {
return null;
}
return orderSet[nextIndex];
}
function getPreviousBlockClientId(state, startClientId) {
return getAdjacentBlockClientId(state, startClientId, -1);
}
function getNextBlockClientId(state, startClientId) {
return getAdjacentBlockClientId(state, startClientId, 1);
}
function getSelectedBlocksInitialCaretPosition(state) {
return state.initialPosition;
}
var getSelectedBlockClientIds = (0, import_data5.createSelector)(
(state) => {
const { selectionStart, selectionEnd } = state.selection;
if (!selectionStart.clientId || !selectionEnd.clientId) {
return EMPTY_ARRAY2;
}
if (selectionStart.clientId === selectionEnd.clientId) {
return [selectionStart.clientId];
}
const rootClientId = getBlockRootClientId(
state,
selectionStart.clientId
);
if (rootClientId === null) {
return EMPTY_ARRAY2;
}
const blockOrder = getBlockOrder(state, rootClientId);
const startIndex = blockOrder.indexOf(selectionStart.clientId);
const endIndex = blockOrder.indexOf(selectionEnd.clientId);
if (startIndex > endIndex) {
return blockOrder.slice(endIndex, startIndex + 1);
}
return blockOrder.slice(startIndex, endIndex + 1);
},
(state) => [
state.blocks.order,
state.selection.selectionStart.clientId,
state.selection.selectionEnd.clientId
]
);
function getMultiSelectedBlockClientIds(state) {
const { selectionStart, selectionEnd } = state.selection;
if (selectionStart.clientId === selectionEnd.clientId) {
return EMPTY_ARRAY2;
}
return getSelectedBlockClientIds(state);
}
var getMultiSelectedBlocks = (0, import_data5.createSelector)(
(state) => {
const multiSelectedBlockClientIds = getMultiSelectedBlockClientIds(state);
if (!multiSelectedBlockClientIds.length) {
return EMPTY_ARRAY2;
}
return multiSelectedBlockClientIds.map(
(clientId) => getBlock(state, clientId)
);
},
(state) => [
...getSelectedBlockClientIds.getDependants(state),
state.blocks.byClientId,
state.blocks.order,
state.blocks.attributes
]
);
function getFirstMultiSelectedBlockClientId(state) {
return getMultiSelectedBlockClientIds(state)[0] || null;
}
function getLastMultiSelectedBlockClientId(state) {
const selectedClientIds = getMultiSelectedBlockClientIds(state);
return selectedClientIds[selectedClientIds.length - 1] || null;
}
function isFirstMultiSelectedBlock(state, clientId) {
return getFirstMultiSelectedBlockClientId(state) === clientId;
}
function isBlockMultiSelected(state, clientId) {
return getMultiSelectedBlockClientIds(state).indexOf(clientId) !== -1;
}
var isAncestorMultiSelected = (0, import_data5.createSelector)(
(state, clientId) => {
let ancestorClientId = clientId;
let isMultiSelected = false;
while (ancestorClientId && !isMultiSelected) {
ancestorClientId = getBlockRootClientId(state, ancestorClientId);
isMultiSelected = isBlockMultiSelected(state, ancestorClientId);
}
return isMultiSelected;
},
(state) => [
state.blocks.order,
state.selection.selectionStart.clientId,
state.selection.selectionEnd.clientId
]
);
function getMultiSelectedBlocksStartClientId(state) {
const { selectionStart, selectionEnd } = state.selection;
if (selectionStart.clientId === selectionEnd.clientId) {
return null;
}
return selectionStart.clientId || null;
}
function getMultiSelectedBlocksEndClientId(state) {
const { selectionStart, selectionEnd } = state.selection;
if (selectionStart.clientId === selectionEnd.clientId) {
return null;
}
return selectionEnd.clientId || null;
}
function __unstableIsFullySelected(state) {
const selectionAnchor = getSelectionStart(state);
const selectionFocus = getSelectionEnd(state);
return !selectionAnchor.attributeKey && !selectionFocus.attributeKey && typeof selectionAnchor.offset === "undefined" && typeof selectionFocus.offset === "undefined";
}
function __unstableIsSelectionCollapsed(state) {
const selectionAnchor = getSelectionStart(state);
const selectionFocus = getSelectionEnd(state);
return !!selectionAnchor && !!selectionFocus && selectionAnchor.clientId === selectionFocus.clientId && selectionAnchor.attributeKey === selectionFocus.attributeKey && selectionAnchor.offset === selectionFocus.offset;
}
function __unstableSelectionHasUnmergeableBlock(state) {
return getSelectedBlockClientIds(state).some((clientId) => {
const blockName = getBlockName(state, clientId);
const blockType = (0, import_blocks7.getBlockType)(blockName);
return !blockType.merge;
});
}
function __unstableIsSelectionMergeable(state, isForward) {
const selectionAnchor = getSelectionStart(state);
const selectionFocus = getSelectionEnd(state);
if (selectionAnchor.clientId === selectionFocus.clientId) {
return false;
}
if (!selectionAnchor.attributeKey || !selectionFocus.attributeKey || typeof selectionAnchor.offset === "undefined" || typeof selectionFocus.offset === "undefined") {
return false;
}
const anchorRootClientId = getBlockRootClientId(
state,
selectionAnchor.clientId
);
const focusRootClientId = getBlockRootClientId(
state,
selectionFocus.clientId
);
if (anchorRootClientId !== focusRootClientId) {
return false;
}
const blockOrder = getBlockOrder(state, anchorRootClientId);
const anchorIndex = blockOrder.indexOf(selectionAnchor.clientId);
const focusIndex = blockOrder.indexOf(selectionFocus.clientId);
let selectionStart, selectionEnd;
if (anchorIndex > focusIndex) {
selectionStart = selectionFocus;
selectionEnd = selectionAnchor;
} else {
selectionStart = selectionAnchor;
selectionEnd = selectionFocus;
}
const targetBlockClientId = isForward ? selectionEnd.clientId : selectionStart.clientId;
const blockToMergeClientId = isForward ? selectionStart.clientId : selectionEnd.clientId;
const targetBlockName = getBlockName(state, targetBlockClientId);
const targetBlockType = (0, import_blocks7.getBlockType)(targetBlockName);
if (!targetBlockType.merge) {
return false;
}
const blockToMerge = getBlock(state, blockToMergeClientId);
if (blockToMerge.name === targetBlockName) {
return true;
}
const blocksToMerge = (0, import_blocks7.switchToBlockType)(blockToMerge, targetBlockName);
return blocksToMerge && blocksToMerge.length;
}
var __unstableGetSelectedBlocksWithPartialSelection = (state) => {
const selectionAnchor = getSelectionStart(state);
const selectionFocus = getSelectionEnd(state);
if (selectionAnchor.clientId === selectionFocus.clientId) {
return EMPTY_ARRAY2;
}
if (!selectionAnchor.attributeKey || !selectionFocus.attributeKey || typeof selectionAnchor.offset === "undefined" || typeof selectionFocus.offset === "undefined") {
return EMPTY_ARRAY2;
}
const anchorRootClientId = getBlockRootClientId(
state,
selectionAnchor.clientId
);
const focusRootClientId = getBlockRootClientId(
state,
selectionFocus.clientId
);
if (anchorRootClientId !== focusRootClientId) {
return EMPTY_ARRAY2;
}
const blockOrder = getBlockOrder(state, anchorRootClientId);
const anchorIndex = blockOrder.indexOf(selectionAnchor.clientId);
const focusIndex = blockOrder.indexOf(selectionFocus.clientId);
const [selectionStart, selectionEnd] = anchorIndex > focusIndex ? [selectionFocus, selectionAnchor] : [selectionAnchor, selectionFocus];
const blockA = getBlock(state, selectionStart.clientId);
const blockB = getBlock(state, selectionEnd.clientId);
const htmlA = blockA.attributes[selectionStart.attributeKey];
const htmlB = blockB.attributes[selectionEnd.attributeKey];
let valueA = (0, import_rich_text.create)({ html: htmlA });
let valueB = (0, import_rich_text.create)({ html: htmlB });
valueA = (0, import_rich_text.remove)(valueA, 0, selectionStart.offset);
valueB = (0, import_rich_text.remove)(valueB, selectionEnd.offset, valueB.text.length);
return [
{
...blockA,
attributes: {
...blockA.attributes,
[selectionStart.attributeKey]: (0, import_rich_text.toHTMLString)({
value: valueA
})
}
},
{
...blockB,
attributes: {
...blockB.attributes,
[selectionEnd.attributeKey]: (0, import_rich_text.toHTMLString)({
value: valueB
})
}
}
];
};
function getBlockOrder(state, rootClientId) {
return state.blocks.order.get(rootClientId || "") || EMPTY_ARRAY2;
}
function getBlockIndex(state, clientId) {
const rootClientId = getBlockRootClientId(state, clientId);
return getBlockOrder(state, rootClientId).indexOf(clientId);
}
function isBlockSelected(state, clientId) {
const { selectionStart, selectionEnd } = state.selection;
if (selectionStart.clientId !== selectionEnd.clientId) {
return false;
}
return selectionStart.clientId === clientId;
}
function hasSelectedInnerBlock(state, clientId, deep = false) {
const selectedBlockClientIds = getSelectedBlockClientIds(state);
if (!selectedBlockClientIds.length) {
return false;
}
if (deep) {
return selectedBlockClientIds.some(
(id) => (
// Pass true because we don't care about order and it's more
// performant.
getBlockParents(state, id, true).includes(clientId)
)
);
}
return selectedBlockClientIds.some(
(id) => getBlockRootClientId(state, id) === clientId
);
}
function hasDraggedInnerBlock(state, clientId, deep = false) {
return getBlockOrder(state, clientId).some(
(innerClientId) => isBlockBeingDragged(state, innerClientId) || deep && hasDraggedInnerBlock(state, innerClientId, deep)
);
}
function isBlockWithinSelection(state, clientId) {
if (!clientId) {
return false;
}
const clientIds = getMultiSelectedBlockClientIds(state);
const index2 = clientIds.indexOf(clientId);
return index2 > -1 && index2 < clientIds.length - 1;
}
function hasMultiSelection(state) {
const { selectionStart, selectionEnd } = state.selection;
return selectionStart.clientId !== selectionEnd.clientId;
}
function isMultiSelecting2(state) {
return state.isMultiSelecting;
}
function isSelectionEnabled2(state) {
return state.isSelectionEnabled;
}
function getBlockMode(state, clientId) {
return state.blocksMode[clientId] || "visual";
}
function isTyping2(state) {
return state.isTyping;
}
function isDraggingBlocks(state) {
return !!state.draggedBlocks.length;
}
function getDraggedBlockClientIds(state) {
return state.draggedBlocks;
}
function isBlockBeingDragged(state, clientId) {
return state.draggedBlocks.includes(clientId);
}
function isAncestorBeingDragged(state, clientId) {
if (!isDraggingBlocks(state)) {
return false;
}
const parents = getBlockParents(state, clientId);
return parents.some(
(parentClientId) => isBlockBeingDragged(state, parentClientId)
);
}
function isCaretWithinFormattedText() {
(0, import_deprecated2.default)(
'wp.data.select( "core/block-editor" ).isCaretWithinFormattedText',
{
since: "6.1",
version: "6.3"
}
);
return false;
}
var getBlockInsertionPoint = (0, import_data5.createSelector)(
(state) => {
let rootClientId, index2;
const {
insertionCue: insertionCue2,
selection: { selectionEnd }
} = state;
if (insertionCue2 !== null) {
return insertionCue2;
}
const { clientId } = selectionEnd;
if (clientId) {
rootClientId = getBlockRootClientId(state, clientId) || void 0;
index2 = getBlockIndex(state, selectionEnd.clientId) + 1;
} else {
index2 = getBlockOrder(state).length;
}
return { rootClientId, index: index2 };
},
(state) => [
state.insertionCue,
state.selection.selectionEnd.clientId,
state.blocks.parents,
state.blocks.order
]
);
function isBlockInsertionPointVisible(state) {
return state.insertionCue !== null;
}
function isValidTemplate(state) {
return state.template.isValid;
}
function getTemplate(state) {
return state.settings.template;
}
function getTemplateLock(state, rootClientId) {
if (!rootClientId) {
return state.settings.templateLock ?? false;
}
const blockListTemplateLock = getBlockListSettings(
state,
rootClientId
)?.templateLock;
if (blockListTemplateLock === "contentOnly" && state.editedContentOnlySection === rootClientId) {
return false;
}
return blockListTemplateLock ?? false;
}
var isBlockVisibleInTheInserter = (state, blockNameOrType, rootClientId = null) => {
let blockType;
let blockName;
if (blockNameOrType && "object" === typeof blockNameOrType) {
blockType = blockNameOrType;
blockName = blockNameOrType.name;
} else {
blockType = (0, import_blocks7.getBlockType)(blockNameOrType);
blockName = blockNameOrType;
}
if (!blockType) {
return false;
}
const { allowedBlockTypes } = getSettings(state);
const isBlockAllowedInEditor = checkAllowList(
allowedBlockTypes,
blockName,
true
);
if (!isBlockAllowedInEditor) {
return false;
}
const parents = (Array.isArray(blockType.parent) ? blockType.parent : []).concat(Array.isArray(blockType.ancestor) ? blockType.ancestor : []);
if (parents.length > 0) {
if (parents.includes("core/post-content")) {
return true;
}
let current = rootClientId;
let hasParent = false;
do {
if (parents.includes(getBlockName(state, current))) {
hasParent = true;
break;
}
current = state.blocks.parents.get(current);
} while (current);
return hasParent;
}
return true;
};
var canInsertBlockTypeUnmemoized = (state, blockName, rootClientId = null) => {
if (state.settings.isPreviewMode) {
return false;
}
if (!isBlockVisibleInTheInserter(state, blockName, rootClientId)) {
return false;
}
let blockType;
if (blockName && "object" === typeof blockName) {
blockType = blockName;
blockName = blockType.name;
} else {
blockType = (0, import_blocks7.getBlockType)(blockName);
}
const rootTemplateLock = getTemplateLock(state, rootClientId);
if (rootTemplateLock && rootTemplateLock !== "contentOnly") {
return false;
}
if (isInnerContentRoot(state, rootClientId)) {
return false;
}
const blockEditingMode = getBlockEditingMode(state, rootClientId ?? "");
const isParentSectionBlock = !!isSectionBlock(state, rootClientId);
const sectionClientId = isParentSectionBlock ? rootClientId : getParentSectionBlock(state, rootClientId);
const isWithinSection = !!sectionClientId;
if (blockEditingMode === "disabled" && (!isWithinSection || blockName !== (0, import_blocks7.getDefaultBlockName)())) {
return false;
}
const parentBlockListSettings = getBlockListSettings(state, rootClientId);
if (rootClientId && parentBlockListSettings === void 0) {
return false;
}
const isContentRoleBlock = isContentBlock3(blockName);
if (isWithinSection && !isContentRoleBlock) {
return false;
}
if (isWithinSection && getBlockName(state, sectionClientId) === "core/block") {
return false;
}
if (isWithinSection && (isParentSectionBlock || blockEditingMode === "contentOnly" || blockEditingMode === "disabled") && !isContainerInsertableToInContentOnlyMode(
state,
blockName,
rootClientId
)) {
const defaultBlockName = (0, import_blocks7.getDefaultBlockName)();
if (blockName === defaultBlockName) {
const existingBlocks = getBlockOrder(state, rootClientId);
const hasDefaultBlock = existingBlocks.some(
(clientId) => getBlockName(state, clientId) === defaultBlockName
);
if (!hasDefaultBlock) {
return false;
}
} else {
return false;
}
}
const parentName = getBlockName(state, rootClientId);
const parentBlockType = (0, import_blocks7.getBlockType)(parentName);
const parentAllowedChildBlocks = parentBlockType?.allowedBlocks;
let hasParentAllowedBlock = checkAllowList(
parentAllowedChildBlocks,
blockName
);
if (hasParentAllowedBlock !== false) {
const parentAllowedBlocks = parentBlockListSettings?.allowedBlocks;
const hasParentListAllowedBlock = checkAllowList(
parentAllowedBlocks,
blockName
);
if (hasParentListAllowedBlock !== null) {
hasParentAllowedBlock = hasParentListAllowedBlock;
}
}
const blockAllowedParentBlocks = blockType.parent;
const hasBlockAllowedParent = checkAllowList(
blockAllowedParentBlocks,
parentName
);
let hasBlockAllowedAncestor = true;
const blockAllowedAncestorBlocks = blockType.ancestor;
if (blockAllowedAncestorBlocks) {
const ancestors = [
rootClientId,
...getBlockParents(state, rootClientId)
];
hasBlockAllowedAncestor = ancestors.some(
(ancestorClientId) => checkAllowList(
blockAllowedAncestorBlocks,
getBlockName(state, ancestorClientId)
)
);
}
const canInsert = hasBlockAllowedAncestor && (hasParentAllowedBlock === null && hasBlockAllowedParent === null || hasParentAllowedBlock === true || hasBlockAllowedParent === true);
if (!canInsert) {
return canInsert;
}
return (0, import_hooks2.applyFilters)(
"blockEditor.__unstableCanInsertBlockType",
canInsert,
blockType,
rootClientId,
{
// Pass bound selectors of the current registry. If we're in a nested
// context, the data will differ from the one selected from the root
// registry.
getBlock: getBlock.bind(null, state),
getBlockParentsByBlockName: getBlockParentsByBlockName.bind(
null,
state
)
}
);
};
var canInsertBlockType = (0, import_data5.createRegistrySelector)(
(select3) => (0, import_data5.createSelector)(
canInsertBlockTypeUnmemoized,
(state, blockName, rootClientId) => getInsertBlockTypeDependants(select3)(state, rootClientId)
)
);
function canInsertBlocks(state, clientIds, rootClientId = null) {
return clientIds.every(
(id) => canInsertBlockType(state, getBlockName(state, id), rootClientId)
);
}
function isInnerContentRoot(state, rootClientId) {
return !!rootClientId && getBlockName(state, rootClientId) === "core/html";
}
function canRemoveBlock(state, clientId) {
if (state.settings.isPreviewMode) {
return false;
}
if (isInnerContentRoot(state, getBlockRootClientId(state, clientId))) {
return false;
}
const attributes = getBlockAttributes(state, clientId);
if (attributes === null) {
return true;
}
if (attributes.lock?.remove !== void 0) {
return !attributes.lock.remove;
}
const rootClientId = getBlockRootClientId(state, clientId);
const rootTemplateLock = getTemplateLock(state, rootClientId);
if (rootTemplateLock && rootTemplateLock !== "contentOnly") {
return false;
}
const isParentSectionBlock = !!isSectionBlock(state, rootClientId);
const sectionClientId = isParentSectionBlock ? rootClientId : getParentSectionBlock(state, rootClientId);
const isWithinSection = !!sectionClientId;
const isContentRoleBlock = isContentBlock3(
getBlockName(state, clientId)
);
if (isWithinSection && !isContentRoleBlock) {
return false;
}
if (isWithinSection && getBlockName(state, sectionClientId) === "core/block") {
return false;
}
const rootBlockEditingMode = getBlockEditingMode(state, rootClientId);
const blockName = getBlockName(state, clientId);
const defaultBlockName = (0, import_blocks7.getDefaultBlockName)();
if (isWithinSection && (isParentSectionBlock || blockName === defaultBlockName || rootBlockEditingMode === "contentOnly") && !isContainerInsertableToInContentOnlyMode(
state,
getBlockName(state, clientId),
rootClientId
)) {
if (blockName === defaultBlockName) {
const existingBlocks = getBlockOrder(state, rootClientId);
const defaultBlocks = existingBlocks.filter(
(id) => getBlockName(state, id) === defaultBlockName
);
if (defaultBlocks.length > 1) {
return true;
}
return false;
}
return false;
}
return rootBlockEditingMode !== "disabled";
}
function canRemoveBlocks(state, clientIds) {
return clientIds.every((clientId) => canRemoveBlock(state, clientId));
}
function canMoveBlock(state, clientId) {
if (state.settings.isPreviewMode) {
return false;
}
if (isInnerContentRoot(state, getBlockRootClientId(state, clientId))) {
return false;
}
const attributes = getBlockAttributes(state, clientId);
if (attributes === null) {
return true;
}
if (attributes.lock?.move !== void 0) {
return !attributes.lock.move;
}
const rootClientId = getBlockRootClientId(state, clientId);
const rootTemplateLock = getTemplateLock(state, rootClientId);
if (rootTemplateLock === "all") {
return false;
}
const isBlockWithinSection = !!getParentSectionBlock(state, clientId);
const isContentRoleBlock = isContentBlock3(
getBlockName(state, clientId)
);
if (isBlockWithinSection && !isContentRoleBlock) {
return false;
}
const isParentSectionBlock = !!isSectionBlock(state, rootClientId);
const rootBlockEditingMode = getBlockEditingMode(state, rootClientId);
if (isBlockWithinSection && (isParentSectionBlock || rootBlockEditingMode === "contentOnly") && !isContainerInsertableToInContentOnlyMode(
state,
getBlockName(state, clientId),
rootClientId
)) {
return false;
}
return getBlockEditingMode(state, rootClientId) !== "disabled";
}
function canMoveBlocks(state, clientIds) {
return clientIds.every((clientId) => canMoveBlock(state, clientId));
}
function canEditBlock(state, clientId) {
if (state.settings.isPreviewMode) {
return false;
}
const attributes = getBlockAttributes(state, clientId);
if (attributes === null) {
return true;
}
const { lock: lock5 } = attributes;
return !lock5?.edit;
}
function canLockBlockType(state, nameOrType) {
if (state.settings.isPreviewMode) {
return false;
}
if (!(0, import_blocks7.hasBlockSupport)(nameOrType, "lock", true)) {
return false;
}
return !!state.settings?.canLockBlocks;
}
function getInsertUsage(state, id) {
return state.preferences.insertUsage?.[id] ?? null;
}
var canIncludeBlockTypeInInserter = (state, blockType, rootClientId) => {
if (!(0, import_blocks7.hasBlockSupport)(blockType, "inserter", true)) {
return false;
}
return canInsertBlockTypeUnmemoized(state, blockType.name, rootClientId);
};
var getItemFromVariation = (state, item) => (variation) => {
const variationId = `${item.id}/${variation.name}`;
const { time, count = 0 } = getInsertUsage(state, variationId) || {};
return {
...item,
id: variationId,
icon: variation.icon || item.icon,
title: variation.title || item.title,
description: variation.description || item.description,
category: variation.category || item.category,
// If `example` is explicitly undefined for the variation, the preview will not be shown.
example: variation.hasOwnProperty("example") ? variation.example : item.example,
initialAttributes: {
...item.initialAttributes,
...variation.attributes
},
innerBlocks: variation.innerBlocks,
innerContent: variation.innerContent,
keywords: variation.keywords || item.keywords,
frecency: calculateFrecency(time, count),
// Pass through search-only flag for block-scope variations.
isSearchOnly: variation.isSearchOnly
};
};
var calculateFrecency = (time, count) => {
if (!time) {
return count;
}
const duration = Date.now() - time;
switch (true) {
case duration < MILLISECONDS_PER_HOUR:
return count * 4;
case duration < MILLISECONDS_PER_DAY:
return count * 2;
case duration < MILLISECONDS_PER_WEEK:
return count / 2;
default:
return count / 4;
}
};
var buildBlockTypeItem = (state, { buildScope = "inserter" }) => (blockType) => {
const id = blockType.name;
let isDisabled = false;
if (!(0, import_blocks7.hasBlockSupport)(blockType.name, "multiple", true)) {
isDisabled = getBlocksByClientId(
state,
getClientIdsWithDescendants(state)
).some(({ name }) => name === blockType.name);
}
const { time, count = 0 } = getInsertUsage(state, id) || {};
const blockItemBase = {
id,
name: blockType.name,
title: blockType.title,
icon: blockType.icon,
isDisabled,
frecency: calculateFrecency(time, count)
};
if (buildScope === "transform") {
return blockItemBase;
}
const inserterVariations = (0, import_blocks7.getBlockVariations)(
blockType.name,
"inserter"
);
const blockVariations = (0, import_blocks7.getBlockVariations)(blockType.name, "block");
const allVariations = [
...inserterVariations,
// Built-in heading level variations have block scope but allow
// insertion via slash inserter.
// See https://github.com/WordPress/gutenberg/issues/74233.
...blockVariations.filter(
(variation) => blockType.name === "core/heading" && ["h1", "h2", "h3", "h4", "h5", "h6"].includes(
variation.name
)
).map((variation) => ({
...variation,
isSearchOnly: true
}))
];
return {
...blockItemBase,
initialAttributes: {},
description: blockType.description,
category: blockType.category,
keywords: blockType.keywords,
parent: blockType.parent,
ancestor: blockType.ancestor,
variations: allVariations,
example: blockType.example,
utility: 1
// Deprecated.
};
};
var buildBlockVariationItem = (state, item) => (variation) => {
const variationId = `${item.id}/${variation.name}`;
const { time, count = 0 } = getInsertUsage(state, variationId) || {};
return {
...item,
id: variationId,
icon: variation.icon || item.icon,
title: variation.title || item.title,
frecency: calculateFrecency(time, count),
variationName: variation.name
};
};
var getInserterItems = (0, import_data5.createRegistrySelector)(
(select3) => (0, import_data5.createSelector)(
(state, rootClientId = null, options = DEFAULT_INSERTER_OPTIONS) => {
const buildReusableBlockInserterItem = (reusableBlock) => {
const icon = !reusableBlock.wp_pattern_sync_status ? {
src: symbol_default,
foreground: "var(--wp-block-synced-color)"
} : symbol_default;
const userPattern = mapUserPattern(reusableBlock);
const { time, count = 0 } = getInsertUsage(state, userPattern.name) || {};
const frecency = calculateFrecency(time, count);
return {
id: userPattern.name,
name: "core/block",
initialAttributes: { ref: reusableBlock.id },
title: userPattern.title,
icon,
category: "reusable",
keywords: ["reusable"],
isDisabled: false,
utility: 1,
// Deprecated.
frecency,
content: userPattern.content,
get blocks() {
return getParsedPattern(userPattern).blocks;
},
syncStatus: userPattern.syncStatus
};
};
const patternInserterItems = canInsertBlockTypeUnmemoized(
state,
"core/block",
rootClientId
) ? unlock(select3(STORE_NAME)).getReusableBlocks().map(buildReusableBlockInserterItem) : [];
const buildBlockTypeInserterItem = buildBlockTypeItem(state, {
buildScope: "inserter"
});
let blockTypeInserterItems = (0, import_blocks7.getBlockTypes)().filter(
(blockType) => (0, import_blocks7.hasBlockSupport)(blockType, "inserter", true)
).map(buildBlockTypeInserterItem);
if (options[isFiltered] !== false) {
blockTypeInserterItems = blockTypeInserterItems.filter(
(blockType) => canIncludeBlockTypeInInserter(
state,
blockType,
rootClientId
)
);
} else {
const { getClosestAllowedInsertionPoint: getClosestAllowedInsertionPoint2 } = unlock(
select3(STORE_NAME)
);
blockTypeInserterItems = blockTypeInserterItems.filter(
(blockType) => isBlockVisibleInTheInserter(
state,
blockType,
rootClientId
) && getClosestAllowedInsertionPoint2(
blockType.name,
rootClientId
) !== null
).map((blockType) => ({
...blockType,
isAllowedInCurrentRoot: canIncludeBlockTypeInInserter(
state,
blockType,
rootClientId
)
}));
}
const items = blockTypeInserterItems.reduce(
(accumulator, item) => {
const { variations = [] } = item;
if (!variations.some(({ isDefault }) => isDefault)) {
accumulator.push(item);
}
if (variations.length) {
const variationMapper = getItemFromVariation(
state,
item
);
accumulator.push(
...variations.map(variationMapper)
);
}
return accumulator;
},
[]
);
const groupByType = (blocks2, block) => {
const { core, noncore } = blocks2;
const type = block.name.startsWith("core/") ? core : noncore;
type.push(block);
return blocks2;
};
const { core: coreItems, noncore: nonCoreItems } = items.reduce(
groupByType,
{ core: [], noncore: [] }
);
const sortedBlockTypes = [...coreItems, ...nonCoreItems];
return [...sortedBlockTypes, ...patternInserterItems];
},
(state, rootClientId) => [
(0, import_blocks7.getBlockTypes)(),
unlock(select3(STORE_NAME)).getReusableBlocks(),
state.blocks.order,
state.preferences.insertUsage,
...getInsertBlockTypeDependants(select3)(state, rootClientId)
]
)
);
var getBlockTransformItems = (0, import_data5.createRegistrySelector)(
(select3) => (0, import_data5.createSelector)(
(state, blocks2, rootClientId = null) => {
const normalizedBlocks = Array.isArray(blocks2) ? blocks2 : [blocks2];
const buildBlockTypeTransformItem = buildBlockTypeItem(state, {
buildScope: "transform"
});
const blockTypeTransformItems = (0, import_blocks7.getBlockTypes)().filter(
(blockType) => canIncludeBlockTypeInInserter(
state,
blockType,
rootClientId
)
).map(buildBlockTypeTransformItem);
const itemsByName = Object.fromEntries(
Object.entries(blockTypeTransformItems).map(
([, value]) => [value.name, value]
)
);
const possibleTransforms = (0, import_blocks7.getPossibleBlockTransformations)(
normalizedBlocks
).reduce((accumulator, block) => {
const item = itemsByName[block?.name];
if (!item) {
return accumulator;
}
const { variationName } = block;
if (!variationName) {
accumulator.push(item);
return accumulator;
}
const variation = (0, import_blocks7.getBlockVariations)(
item.name,
"transform"
)?.find(({ name }) => name === variationName);
if (!variation) {
accumulator.push(item);
return accumulator;
}
accumulator.push(
buildBlockVariationItem(state, item)(variation)
);
return accumulator;
}, []);
return orderBy(
possibleTransforms,
(block) => block.frecency,
"desc"
);
},
(state, blocks2, rootClientId) => [
(0, import_blocks7.getBlockTypes)(),
state.preferences.insertUsage,
...getInsertBlockTypeDependants(select3)(state, rootClientId)
]
)
);
var hasInserterItems = (state, rootClientId = null) => {
const hasBlockType = (0, import_blocks7.getBlockTypes)().some(
(blockType) => canIncludeBlockTypeInInserter(state, blockType, rootClientId)
);
if (hasBlockType) {
return true;
}
const hasReusableBlock = canInsertBlockTypeUnmemoized(
state,
"core/block",
rootClientId
);
return hasReusableBlock;
};
var getAllowedBlocks = (0, import_data5.createRegistrySelector)(
(select3) => (0, import_data5.createSelector)(
(state, rootClientId = null) => {
if (!rootClientId) {
return;
}
const blockTypes = (0, import_blocks7.getBlockTypes)().filter(
(blockType) => canIncludeBlockTypeInInserter(state, blockType, rootClientId)
);
const hasReusableBlock = canInsertBlockTypeUnmemoized(
state,
"core/block",
rootClientId
);
if (hasReusableBlock) {
blockTypes.push("core/block");
}
return blockTypes;
},
(state, rootClientId) => [
(0, import_blocks7.getBlockTypes)(),
...getInsertBlockTypeDependants(select3)(state, rootClientId)
]
)
);
var __experimentalGetAllowedBlocks = (0, import_data5.createSelector)(
(state, rootClientId = null) => {
(0, import_deprecated2.default)(
'wp.data.select( "core/block-editor" ).__experimentalGetAllowedBlocks',
{
alternative: 'wp.data.select( "core/block-editor" ).getAllowedBlocks',
since: "6.2",
version: "6.4"
}
);
return getAllowedBlocks(state, rootClientId);
},
(state, rootClientId) => getAllowedBlocks.getDependants(state, rootClientId)
);
function getDirectInsertBlock(state, rootClientId = null) {
if (!rootClientId) {
return;
}
const { defaultBlock, directInsert } = state.blockListSettings.get(rootClientId) ?? {};
if (!defaultBlock || !directInsert) {
return;
}
return defaultBlock;
}
function __experimentalGetDirectInsertBlock(state, rootClientId = null) {
(0, import_deprecated2.default)(
'wp.data.select( "core/block-editor" ).__experimentalGetDirectInsertBlock',
{
alternative: 'wp.data.select( "core/block-editor" ).getDirectInsertBlock',
since: "6.3",
version: "6.4"
}
);
return getDirectInsertBlock(state, rootClientId);
}
var __experimentalGetParsedPattern = (0, import_data5.createRegistrySelector)(
(select3) => (state, patternName) => {
const pattern = unlock(select3(STORE_NAME)).getPatternBySlug(
patternName
);
return pattern ? getParsedPattern(pattern) : null;
}
);
var getAllowedPatternsDependants = (select3) => (state, rootClientId) => [
...getAllPatternsDependants(select3)(state),
...getInsertBlockTypeDependants(select3)(state, rootClientId)
];
var patternsWithParsedBlocks = /* @__PURE__ */ new WeakMap();
function enhancePatternWithParsedBlocks(pattern) {
let enhancedPattern = patternsWithParsedBlocks.get(pattern);
if (!enhancedPattern) {
enhancedPattern = {
...pattern,
get blocks() {
return getParsedPattern(pattern).blocks;
}
};
patternsWithParsedBlocks.set(pattern, enhancedPattern);
}
return enhancedPattern;
}
var __experimentalGetAllowedPatterns = (0, import_data5.createRegistrySelector)(
(select3) => {
return (0, import_data5.createSelector)(
(state, rootClientId = null, options = DEFAULT_INSERTER_OPTIONS) => {
const { getAllPatterns: getAllPatterns2 } = unlock(select3(STORE_NAME));
const patterns = getAllPatterns2();
const { allowedBlockTypes } = getSettings(state);
const parsedPatterns = patterns.filter(({ inserter = true }) => !!inserter).map(enhancePatternWithParsedBlocks);
const availableParsedPatterns = parsedPatterns.filter(
(pattern) => checkAllowListRecursive(
getGrammar(pattern),
allowedBlockTypes
)
);
const patternsAllowed = availableParsedPatterns.filter(
(pattern) => getGrammar(pattern).every(
({ blockName: name }) => options[isFiltered] !== false ? canInsertBlockType(
state,
name,
rootClientId
) : isBlockVisibleInTheInserter(
state,
name,
rootClientId
)
)
);
return patternsAllowed;
},
getAllowedPatternsDependants(select3)
);
}
);
var getPatternsByBlockTypes = (0, import_data5.createRegistrySelector)(
(select3) => (0, import_data5.createSelector)(
(state, blockNames, rootClientId = null) => {
if (!blockNames) {
return EMPTY_ARRAY2;
}
const patterns = select3(STORE_NAME).__experimentalGetAllowedPatterns(
rootClientId
);
const normalizedBlockNames = Array.isArray(blockNames) ? blockNames : [blockNames];
const filteredPatterns = patterns.filter(
(pattern) => pattern?.blockTypes?.some?.(
(blockName) => normalizedBlockNames.includes(blockName)
)
);
if (filteredPatterns.length === 0) {
return EMPTY_ARRAY2;
}
return filteredPatterns;
},
(state, blockNames, rootClientId) => getAllowedPatternsDependants(select3)(state, rootClientId)
)
);
var __experimentalGetPatternsByBlockTypes = (0, import_data5.createRegistrySelector)(
(select3) => {
(0, import_deprecated2.default)(
'wp.data.select( "core/block-editor" ).__experimentalGetPatternsByBlockTypes',
{
alternative: 'wp.data.select( "core/block-editor" ).getPatternsByBlockTypes',
since: "6.2",
version: "6.4"
}
);
return select3(STORE_NAME).getPatternsByBlockTypes;
}
);
var __experimentalGetPatternTransformItems = (0, import_data5.createRegistrySelector)(
(select3) => (0, import_data5.createSelector)(
(state, blocks2, rootClientId = null) => {
if (!blocks2) {
return EMPTY_ARRAY2;
}
if (blocks2.some(
({ clientId, innerBlocks }) => innerBlocks.length || areInnerBlocksControlled(state, clientId)
)) {
return EMPTY_ARRAY2;
}
const selectedBlockNames = Array.from(
new Set(blocks2.map(({ name }) => name))
);
return select3(STORE_NAME).getPatternsByBlockTypes(
selectedBlockNames,
rootClientId
);
},
(state, blocks2, rootClientId) => getAllowedPatternsDependants(select3)(state, rootClientId)
)
);
function getBlockListSettings(state, clientId) {
return state.blockListSettings.get(clientId);
}
function getSettings(state) {
return state.settings;
}
function isLastBlockChangePersistent(state) {
return state.blocks.isPersistentChange;
}
function __unstableGetLastBlockChangeHistoryMode(state) {
if (state.blocks.lastBlockChangeHistoryMode) {
return state.blocks.lastBlockChangeHistoryMode;
}
return state.blocks.isPersistentChange === false ? "merge" : "persistent";
}
var __experimentalGetBlockListSettingsForBlocks = (0, import_data5.createSelector)(
(state, clientIds = []) => {
const blockListSettingsForBlocks = {};
for (const clientId of clientIds) {
const settings2 = getBlockListSettings(state, clientId);
if (settings2) {
blockListSettingsForBlocks[clientId] = settings2;
}
}
return blockListSettingsForBlocks;
},
(state) => [state.blockListSettings]
);
var __experimentalGetReusableBlockTitle = (0, import_data5.createRegistrySelector)(
(select3) => (0, import_data5.createSelector)(
(state, ref) => {
(0, import_deprecated2.default)(
"wp.data.select( 'core/block-editor' ).__experimentalGetReusableBlockTitle",
{
since: "6.6",
version: "6.8"
}
);
const reusableBlock = unlock(select3(STORE_NAME)).getReusableBlocks().find((block) => block.id === ref);
if (!reusableBlock) {
return null;
}
return reusableBlock.title?.raw;
},
() => [unlock(select3(STORE_NAME)).getReusableBlocks()]
)
);
function __unstableIsLastBlockChangeIgnored(state) {
return state.blocks.isIgnoredChange;
}
function __experimentalGetLastBlockAttributeChanges(state) {
return state.lastBlockAttributesChange;
}
function hasBlockMovingClientId() {
(0, import_deprecated2.default)(
'wp.data.select( "core/block-editor" ).hasBlockMovingClientId',
{
since: "6.7",
hint: "Block moving mode feature has been removed"
}
);
return false;
}
function didAutomaticChange(state) {
return !!state.automaticChangeStatus;
}
function isBlockHighlighted(state, clientId) {
return state.highlightedBlock === clientId;
}
function areInnerBlocksControlled(state, clientId) {
return state.blocks.controlledInnerBlocks.has(clientId);
}
var __experimentalGetActiveBlockIdByBlockNames = (0, import_data5.createSelector)(
(state, validBlockNames) => {
if (!validBlockNames.length) {
return null;
}
const selectedBlockClientId = getSelectedBlockClientId(state);
if (validBlockNames.includes(
getBlockName(state, selectedBlockClientId)
)) {
return selectedBlockClientId;
}
const multiSelectedBlockClientIds = getMultiSelectedBlockClientIds(state);
const entityAreaParents = getBlockParentsByBlockName(
state,
selectedBlockClientId || multiSelectedBlockClientIds[0],
validBlockNames
);
if (entityAreaParents) {
return entityAreaParents[entityAreaParents.length - 1];
}
return null;
},
(state, validBlockNames) => [
state.selection.selectionStart.clientId,
state.selection.selectionEnd.clientId,
validBlockNames
]
);
function wasBlockJustInserted(state, clientId, source) {
const { lastBlockInserted: lastBlockInserted2 } = state;
return lastBlockInserted2.clientIds?.includes(clientId) && lastBlockInserted2.source === source;
}
function isBlockVisible(state, clientId) {
return state.blockVisibility?.[clientId] ?? true;
}
function getHoveredBlockClientId() {
(0, import_deprecated2.default)(
"wp.data.select( 'core/block-editor' ).getHoveredBlockClientId",
{
since: "6.9",
version: "7.1"
}
);
return void 0;
}
var __unstableGetVisibleBlocks = (0, import_data5.createSelector)(
(state) => {
const visibleBlocks = new Set(
Object.keys(state.blockVisibility).filter(
(key) => state.blockVisibility[key]
)
);
if (visibleBlocks.size === 0) {
return EMPTY_SET;
}
return visibleBlocks;
},
(state) => [state.blockVisibility]
);
function __unstableHasActiveBlockOverlayActive(state, clientId) {
if (getBlockEditingMode(state, clientId) !== "default") {
return false;
}
if (!canEditBlock(state, clientId)) {
return true;
}
if (isZoomOut(state)) {
const sectionRootClientId = getSectionRootClientId(state);
if (sectionRootClientId) {
const sectionClientIds = getBlockOrder(
state,
sectionRootClientId
);
if (sectionClientIds?.includes(clientId)) {
return true;
}
} else if (clientId && !getBlockRootClientId(state, clientId)) {
return true;
}
}
const blockSupportDisable = (0, import_blocks7.hasBlockSupport)(
getBlockName(state, clientId),
"__experimentalDisableBlockOverlay",
false
);
const shouldEnableIfUnselected = blockSupportDisable ? false : areInnerBlocksControlled(state, clientId);
return shouldEnableIfUnselected && !isBlockSelected(state, clientId) && !hasSelectedInnerBlock(state, clientId, true);
}
function __unstableIsWithinBlockOverlay(state, clientId) {
let parent = state.blocks.parents.get(clientId);
while (!!parent) {
if (__unstableHasActiveBlockOverlayActive(state, parent)) {
return true;
}
parent = state.blocks.parents.get(parent);
}
return false;
}
function getBlockEditingMode(state, clientId = "") {
if (clientId === null) {
clientId = "";
}
if (state.derivedBlockEditingModes?.has(clientId)) {
return state.derivedBlockEditingModes.get(clientId);
}
if (state.blocks.blockEditingModes.has(clientId)) {
return state.blocks.blockEditingModes.get(clientId);
}
return "default";
}
var isUngroupable = (0, import_data5.createRegistrySelector)(
(select3) => (state, clientId = "") => {
const _clientId = clientId || getSelectedBlockClientId(state);
if (!_clientId) {
return false;
}
if (isSectionBlock(state, _clientId)) {
return false;
}
const { getGroupingBlockName } = select3(import_blocks7.store);
const block = getBlock(state, _clientId);
const groupingBlockName = getGroupingBlockName();
const _isUngroupable = block && (block.name === groupingBlockName || (0, import_blocks7.getBlockType)(block.name)?.transforms?.ungroup) && !!block.innerBlocks.length;
return _isUngroupable && canRemoveBlock(state, _clientId);
}
);
var isGroupable = (0, import_data5.createRegistrySelector)(
(select3) => (state, clientIds = EMPTY_ARRAY2) => {
const { getGroupingBlockName } = select3(import_blocks7.store);
const groupingBlockName = getGroupingBlockName();
const _clientIds = clientIds?.length ? clientIds : getSelectedBlockClientIds(state);
const rootClientId = _clientIds?.length ? getBlockRootClientId(state, _clientIds[0]) : void 0;
const groupingBlockAvailable = canInsertBlockType(
state,
groupingBlockName,
rootClientId
);
const _isGroupable = groupingBlockAvailable && _clientIds.length;
return _isGroupable && canRemoveBlocks(state, _clientIds);
}
);
var __unstableGetContentLockingParent = (state, clientId) => {
(0, import_deprecated2.default)(
"wp.data.select( 'core/block-editor' ).__unstableGetContentLockingParent",
{
since: "6.1",
version: "6.7"
}
);
return getContentLockingParent(state, clientId);
};
function __unstableGetTemporarilyEditingAsBlocks(state) {
(0, import_deprecated2.default)(
"wp.data.select( 'core/block-editor' ).__unstableGetTemporarilyEditingAsBlocks",
{
since: "6.1",
version: "6.7"
}
);
return getEditedContentOnlySection(state);
}
// packages/block-editor/build-module/store/private-actions.mjs
var private_actions_exports = {};
__export(private_actions_exports, {
__experimentalUpdateSettings: () => __experimentalUpdateSettings,
clearBlockRemovalPrompt: () => clearBlockRemovalPrompt,
clearRequestedInspectorTab: () => clearRequestedInspectorTab,
closeListViewContentPanel: () => closeListViewContentPanel,
deleteStyleOverride: () => deleteStyleOverride,
editContentOnlySection: () => editContentOnlySection,
ensureDefaultBlock: () => ensureDefaultBlock,
expandBlock: () => expandBlock,
hideBlockInterface: () => hideBlockInterface,
hideViewportModal: () => hideViewportModal,
openListViewContentPanel: () => openListViewContentPanel,
privateRemoveBlocks: () => privateRemoveBlocks,
requestInspectorTab: () => requestInspectorTab,
resetZoomLevel: () => resetZoomLevel,
setBlockRemovalRules: () => setBlockRemovalRules,
setInsertionPoint: () => setInsertionPoint,
setLastFocus: () => setLastFocus,
setResponsiveEditing: () => setResponsiveEditing,
setSelectedBlockStyleState: () => setSelectedBlockStyleState,
setSelectedBlockStyleStateCanvasPreview: () => setSelectedBlockStyleStateCanvasPreview,
setStyleOverride: () => setStyleOverride,
setStyleStateViewport: () => setStyleStateViewport,
setZoomLevel: () => setZoomLevel,
showBlockInterface: () => showBlockInterface,
showViewportModal: () => showViewportModal,
startDragging: () => startDragging,
stopDragging: () => stopDragging,
stopEditingContentOnlySection: () => stopEditingContentOnlySection,
toggleBlockSpotlight: () => toggleBlockSpotlight
});
var import_deprecated3 = __toESM(require_deprecated(), 1);
var import_a11y2 = __toESM(require_a11y(), 1);
var import_i18n4 = __toESM(require_i18n(), 1);
var castArray = (maybeArray) => Array.isArray(maybeArray) ? maybeArray : [maybeArray];
var privateSettings = [
"inserterMediaCategories",
"blockInspectorAnimation",
"mediaSideload"
];
function __experimentalUpdateSettings(settings2, { stripExperimentalSettings = false, reset = false } = {}) {
let incomingSettings = settings2;
if (Object.hasOwn(incomingSettings, "__unstableIsPreviewMode")) {
(0, import_deprecated3.default)(
"__unstableIsPreviewMode argument in wp.data.dispatch('core/block-editor').updateSettings",
{
since: "6.8",
alternative: "isPreviewMode"
}
);
incomingSettings = { ...incomingSettings };
incomingSettings.isPreviewMode = incomingSettings.__unstableIsPreviewMode;
delete incomingSettings.__unstableIsPreviewMode;
}
let cleanSettings = incomingSettings;
if (stripExperimentalSettings) {
cleanSettings = {};
for (const key in incomingSettings) {
if (!privateSettings.includes(key)) {
cleanSettings[key] = incomingSettings[key];
}
}
}
return {
type: "UPDATE_SETTINGS",
settings: cleanSettings,
reset
};
}
function hideBlockInterface() {
return {
type: "HIDE_BLOCK_INTERFACE"
};
}
function showBlockInterface() {
return {
type: "SHOW_BLOCK_INTERFACE"
};
}
var privateRemoveBlocks = (clientIds, selectPrevious = true, forceRemove = false) => ({ select: select3, dispatch, registry }) => {
if (!clientIds || !clientIds.length) {
return;
}
clientIds = castArray(clientIds);
const canRemoveBlocks2 = select3.canRemoveBlocks(clientIds);
if (!canRemoveBlocks2) {
return;
}
const rules = !forceRemove && select3.getBlockRemovalRules();
if (rules) {
let flattenBlocks22 = function(blocks2) {
const result = [];
const stack = [...blocks2];
while (stack.length) {
const { innerBlocks, ...block } = stack.shift();
stack.push(...innerBlocks);
result.push(block);
}
return result;
};
var flattenBlocks2 = flattenBlocks22;
const blockList = clientIds.map(select3.getBlock);
const flattenedBlocks = flattenBlocks22(blockList);
let message2;
for (const rule of rules) {
message2 = rule.callback(flattenedBlocks);
if (message2) {
dispatch(
displayBlockRemovalPrompt(
clientIds,
selectPrevious,
message2
)
);
return;
}
}
}
if (selectPrevious) {
dispatch.selectPreviousBlock(clientIds[0], selectPrevious);
}
registry.batch(() => {
dispatch({ type: "REMOVE_BLOCKS", clientIds });
dispatch(ensureDefaultBlock());
});
};
var ensureDefaultBlock = () => ({ select: select3, dispatch }) => {
const count = select3.getBlockCount();
if (count > 0) {
return;
}
const { __unstableHasCustomAppender } = select3.getSettings();
if (__unstableHasCustomAppender) {
return;
}
dispatch.insertDefaultBlock();
};
function displayBlockRemovalPrompt(clientIds, selectPrevious, message2) {
return {
type: "DISPLAY_BLOCK_REMOVAL_PROMPT",
clientIds,
selectPrevious,
message: message2
};
}
function clearBlockRemovalPrompt() {
return {
type: "CLEAR_BLOCK_REMOVAL_PROMPT"
};
}
function setBlockRemovalRules(rules = false) {
return {
type: "SET_BLOCK_REMOVAL_RULES",
rules
};
}
function setStyleOverride(id, style) {
return {
type: "SET_STYLE_OVERRIDE",
id,
style
};
}
function deleteStyleOverride(id) {
return {
type: "DELETE_STYLE_OVERRIDE",
id
};
}
function setLastFocus(lastFocus2 = null) {
return {
type: "LAST_FOCUS",
lastFocus: lastFocus2
};
}
function startDragging() {
return {
type: "START_DRAGGING"
};
}
function stopDragging() {
return {
type: "STOP_DRAGGING"
};
}
function expandBlock(clientId) {
return {
type: "SET_BLOCK_EXPANDED_IN_LIST_VIEW",
clientId
};
}
function setInsertionPoint(value) {
return {
type: "SET_INSERTION_POINT",
value
};
}
function editContentOnlySection(clientId) {
return {
type: "EDIT_CONTENT_ONLY_SECTION",
clientId
};
}
function stopEditingContentOnlySection() {
return {
type: "EDIT_CONTENT_ONLY_SECTION"
};
}
var setZoomLevel = (zoom = 100) => ({ select: select3, dispatch }) => {
if (zoom !== 100) {
const firstSelectedClientId = select3.getBlockSelectionStart();
const sectionRootClientId = select3.getSectionRootClientId();
if (firstSelectedClientId) {
let sectionClientId;
if (sectionRootClientId) {
const sectionClientIds = select3.getBlockOrder(sectionRootClientId);
if (sectionClientIds?.includes(firstSelectedClientId)) {
sectionClientId = firstSelectedClientId;
} else {
sectionClientId = select3.getBlockParents(firstSelectedClientId).find(
(parent) => sectionClientIds.includes(parent)
);
}
} else {
sectionClientId = select3.getBlockHierarchyRootClientId(
firstSelectedClientId
);
}
if (sectionClientId) {
dispatch.selectBlock(sectionClientId);
} else {
dispatch.clearSelectedBlock();
}
(0, import_a11y2.speak)((0, import_i18n4.__)("You are currently in zoom-out mode."));
}
}
dispatch({
type: "SET_ZOOM_LEVEL",
zoom
});
};
function resetZoomLevel() {
return {
type: "RESET_ZOOM_LEVEL"
};
}
function toggleBlockSpotlight(clientId, hasBlockSpotlight3) {
return {
type: "TOGGLE_BLOCK_SPOTLIGHT",
clientId,
hasBlockSpotlight: hasBlockSpotlight3
};
}
function openListViewContentPanel() {
return {
type: "OPEN_LIST_VIEW_CONTENT_PANEL"
};
}
function closeListViewContentPanel() {
return {
type: "CLOSE_LIST_VIEW_CONTENT_PANEL"
};
}
function showViewportModal(clientIds) {
return {
type: "SHOW_VIEWPORT_MODAL",
clientIds
};
}
function hideViewportModal() {
return {
type: "HIDE_VIEWPORT_MODAL"
};
}
function requestInspectorTab(tabName, options = {}) {
return {
type: "REQUEST_INSPECTOR_TAB",
tabName,
options
};
}
function clearRequestedInspectorTab() {
return {
type: "CLEAR_REQUESTED_INSPECTOR_TAB"
};
}
function setSelectedBlockStyleState(clientId, value) {
return {
type: "SET_SELECTED_BLOCK_STYLE_STATE",
clientId,
value
};
}
function setSelectedBlockStyleStateCanvasPreview(clientId, value) {
return {
type: "SET_SELECTED_BLOCK_STYLE_STATE_CANVAS_PREVIEW",
clientId,
value
};
}
function setStyleStateViewport(viewport) {
return {
type: "SET_STYLE_STATE_VIEWPORT",
viewport
};
}
function setResponsiveEditing(enabled) {
return {
type: "SET_RESPONSIVE_EDITING",
enabled
};
}
// packages/block-editor/build-module/store/actions.mjs
var actions_exports = {};
__export(actions_exports, {
__unstableDeleteSelection: () => __unstableDeleteSelection,
__unstableExpandSelection: () => __unstableExpandSelection,
__unstableIncrementListViewExpandRevision: () => __unstableIncrementListViewExpandRevision,
__unstableMarkAutomaticChange: () => __unstableMarkAutomaticChange,
__unstableMarkLastChangeAsPersistent: () => __unstableMarkLastChangeAsPersistent,
__unstableMarkNextChangeAsNotPersistent: () => __unstableMarkNextChangeAsNotPersistent,
__unstableSaveReusableBlock: () => __unstableSaveReusableBlock,
__unstableSetAllListViewPanelsOpen: () => __unstableSetAllListViewPanelsOpen,
__unstableSetEditorMode: () => __unstableSetEditorMode,
__unstableSetOpenListViewPanel: () => __unstableSetOpenListViewPanel,
__unstableSetTemporarilyEditingAsBlocks: () => __unstableSetTemporarilyEditingAsBlocks,
__unstableSplitSelection: () => __unstableSplitSelection,
__unstableToggleListViewPanel: () => __unstableToggleListViewPanel,
clearSelectedBlock: () => clearSelectedBlock,
duplicateBlocks: () => duplicateBlocks,
enterFormattedText: () => enterFormattedText,
exitFormattedText: () => exitFormattedText,
flashBlock: () => flashBlock,
hideInsertionPoint: () => hideInsertionPoint,
hoverBlock: () => hoverBlock,
insertAfterBlock: () => insertAfterBlock,
insertBeforeBlock: () => insertBeforeBlock,
insertBlock: () => insertBlock,
insertBlocks: () => insertBlocks,
insertDefaultBlock: () => insertDefaultBlock,
mergeBlocks: () => mergeBlocks,
moveBlockToPosition: () => moveBlockToPosition,
moveBlocksDown: () => moveBlocksDown,
moveBlocksToPosition: () => moveBlocksToPosition,
moveBlocksUp: () => moveBlocksUp,
multiSelect: () => multiSelect,
receiveBlocks: () => receiveBlocks,
registerInserterMediaCategory: () => registerInserterMediaCategory,
removeBlock: () => removeBlock,
removeBlocks: () => removeBlocks,
replaceBlock: () => replaceBlock,
replaceBlocks: () => replaceBlocks,
replaceInnerBlocks: () => replaceInnerBlocks,
resetBlocks: () => resetBlocks,
resetSelection: () => resetSelection,
selectBlock: () => selectBlock,
selectNextBlock: () => selectNextBlock,
selectPreviousBlock: () => selectPreviousBlock,
selectionChange: () => selectionChange,
setBlockEditingMode: () => setBlockEditingMode,
setBlockMovingClientId: () => setBlockMovingClientId,
setBlockVisibility: () => setBlockVisibility,
setHasControlledInnerBlocks: () => setHasControlledInnerBlocks,
setTemplateValidity: () => setTemplateValidity,
showInsertionPoint: () => showInsertionPoint,
startDraggingBlocks: () => startDraggingBlocks,
startMultiSelect: () => startMultiSelect,
startTyping: () => startTyping,
stopDraggingBlocks: () => stopDraggingBlocks,
stopMultiSelect: () => stopMultiSelect,
stopTyping: () => stopTyping,
synchronizeTemplate: () => synchronizeTemplate,
toggleBlockHighlight: () => toggleBlockHighlight,
toggleBlockMode: () => toggleBlockMode,
toggleSelection: () => toggleSelection,
unsetBlockEditingMode: () => unsetBlockEditingMode,
updateBlock: () => updateBlock,
updateBlockAttributes: () => updateBlockAttributes,
updateBlockListSettings: () => updateBlockListSettings,
updateSettings: () => updateSettings,
validateBlocksToTemplate: () => validateBlocksToTemplate
});
var import_blocks8 = __toESM(require_blocks(), 1);
var import_a11y3 = __toESM(require_a11y(), 1);
var import_i18n5 = __toESM(require_i18n(), 1);
var import_notices = __toESM(require_notices(), 1);
var import_rich_text3 = __toESM(require_rich_text(), 1);
var import_deprecated4 = __toESM(require_deprecated(), 1);
var import_preferences = __toESM(require_preferences(), 1);
// packages/block-editor/build-module/utils/selection.mjs
var import_rich_text2 = __toESM(require_rich_text(), 1);
var START_OF_SELECTED_AREA = "\x86";
function retrieveSelectedAttribute(blockAttributes) {
if (!blockAttributes) {
return;
}
return Object.keys(blockAttributes).find((name) => {
const value = blockAttributes[name];
return (typeof value === "string" || value instanceof import_rich_text2.RichTextData) && // To do: refactor this to use rich text's selection instead, so we
// no longer have to use on this hack inserting a special character.
value.toString().indexOf(START_OF_SELECTED_AREA) !== -1;
});
}
function findRichTextAttributeKey(blockType) {
for (const [key, value] of Object.entries(blockType.attributes)) {
if (value.source === "rich-text" || value.source === "html") {
return key;
}
}
return void 0;
}
// packages/block-editor/build-module/store/actions.mjs
var castArray2 = (maybeArray) => Array.isArray(maybeArray) ? maybeArray : [maybeArray];
var resetBlocks = (blocks2) => ({ dispatch }) => {
dispatch({ type: "RESET_BLOCKS", blocks: blocks2 });
dispatch(validateBlocksToTemplate(blocks2));
};
var validateBlocksToTemplate = (blocks2) => ({ select: select3, dispatch }) => {
const template2 = select3.getTemplate();
const templateLock = select3.getTemplateLock();
const isBlocksValidToTemplate = !template2 || templateLock !== "all" || (0, import_blocks8.doBlocksMatchTemplate)(blocks2, template2);
const isValidTemplate2 = select3.isValidTemplate();
if (isBlocksValidToTemplate !== isValidTemplate2) {
dispatch.setTemplateValidity(isBlocksValidToTemplate);
return isBlocksValidToTemplate;
}
};
function resetSelection(selectionStart, selectionEnd, initialPosition2) {
return {
type: "RESET_SELECTION",
selectionStart,
selectionEnd,
initialPosition: initialPosition2
};
}
function receiveBlocks(blocks2) {
(0, import_deprecated4.default)('wp.data.dispatch( "core/block-editor" ).receiveBlocks', {
since: "5.9",
alternative: "resetBlocks or insertBlocks"
});
return {
type: "RECEIVE_BLOCKS",
blocks: blocks2
};
}
function updateBlockAttributes(clientIds, attributes, options = { uniqueByBlock: false }) {
if (typeof options === "boolean") {
options = { uniqueByBlock: options };
}
return {
type: "UPDATE_BLOCK_ATTRIBUTES",
clientIds: castArray2(clientIds),
attributes,
options
};
}
function updateBlock(clientId, updates) {
return {
type: "UPDATE_BLOCK",
clientId,
updates
};
}
function selectBlock(clientId, initialPosition2 = 0) {
return {
type: "SELECT_BLOCK",
initialPosition: initialPosition2,
clientId
};
}
function hoverBlock() {
(0, import_deprecated4.default)('wp.data.dispatch( "core/block-editor" ).hoverBlock', {
since: "6.9",
version: "7.1"
});
return {
type: "DO_NOTHING"
};
}
var selectPreviousBlock = (clientId, fallbackToParent = false) => ({ select: select3, dispatch }) => {
const previousBlockClientId = select3.getPreviousBlockClientId(clientId);
if (previousBlockClientId) {
dispatch.selectBlock(previousBlockClientId, -1);
} else if (fallbackToParent) {
const firstParentClientId = select3.getBlockRootClientId(clientId);
if (firstParentClientId) {
dispatch.selectBlock(firstParentClientId, -1);
} else {
const nextBlockClientId = select3.getNextBlockClientId(clientId);
if (nextBlockClientId) {
dispatch.selectBlock(nextBlockClientId, 0);
}
}
}
};
var selectNextBlock = (clientId) => ({ select: select3, dispatch }) => {
const nextBlockClientId = select3.getNextBlockClientId(clientId);
if (nextBlockClientId) {
dispatch.selectBlock(nextBlockClientId);
}
};
function startMultiSelect() {
return {
type: "START_MULTI_SELECT"
};
}
function stopMultiSelect() {
return {
type: "STOP_MULTI_SELECT"
};
}
var multiSelect = (start2, end, __experimentalInitialPosition = 0) => ({ select: select3, dispatch }) => {
const startBlockRootClientId = select3.getBlockRootClientId(start2);
const endBlockRootClientId = select3.getBlockRootClientId(end);
if (startBlockRootClientId !== endBlockRootClientId) {
return;
}
dispatch({
type: "MULTI_SELECT",
start: start2,
end,
initialPosition: __experimentalInitialPosition
});
const blockCount = select3.getSelectedBlockCount();
(0, import_a11y3.speak)(
(0, import_i18n5.sprintf)(
/* translators: %s: number of selected blocks */
(0, import_i18n5._n)("%s block selected.", "%s blocks selected.", blockCount),
blockCount
),
"assertive"
);
};
function clearSelectedBlock() {
return {
type: "CLEAR_SELECTED_BLOCK"
};
}
function toggleSelection(isSelectionEnabled3 = true) {
return {
type: "TOGGLE_SELECTION",
isSelectionEnabled: isSelectionEnabled3
};
}
var replaceBlocks = (clientIds, blocks2, indexToSelect, initialPosition2 = 0, meta) => ({ select: select3, dispatch, registry }) => {
clientIds = castArray2(clientIds);
blocks2 = castArray2(blocks2);
const rootClientId = select3.getBlockRootClientId(clientIds[0]);
for (let index2 = 0; index2 < blocks2.length; index2++) {
const block = blocks2[index2];
const canInsertBlock = select3.canInsertBlockType(
block.name,
rootClientId
);
if (!canInsertBlock) {
return;
}
}
registry.batch(() => {
dispatch({
type: "REPLACE_BLOCKS",
clientIds,
blocks: blocks2,
time: Date.now(),
indexToSelect,
initialPosition: initialPosition2,
meta
});
dispatch.ensureDefaultBlock();
});
};
function replaceBlock(clientId, block) {
return replaceBlocks(clientId, block);
}
var createOnMove = (type) => (clientIds, rootClientId) => ({ select: select3, dispatch }) => {
const canMoveBlocks2 = select3.canMoveBlocks(clientIds);
if (!canMoveBlocks2) {
return;
}
dispatch({ type, clientIds: castArray2(clientIds), rootClientId });
};
var moveBlocksDown = createOnMove("MOVE_BLOCKS_DOWN");
var moveBlocksUp = createOnMove("MOVE_BLOCKS_UP");
var moveBlocksToPosition = (clientIds, fromRootClientId = "", toRootClientId = "", index2) => ({ select: select3, dispatch }) => {
const canMoveBlocks2 = select3.canMoveBlocks(clientIds);
if (!canMoveBlocks2) {
return;
}
if (fromRootClientId !== toRootClientId) {
const canRemoveBlocks2 = select3.canRemoveBlocks(clientIds);
if (!canRemoveBlocks2) {
return;
}
const canInsertBlocks2 = select3.canInsertBlocks(
clientIds,
toRootClientId
);
if (!canInsertBlocks2) {
return;
}
}
dispatch({
type: "MOVE_BLOCKS_TO_POSITION",
fromRootClientId,
toRootClientId,
clientIds,
index: index2
});
};
function moveBlockToPosition(clientId, fromRootClientId = "", toRootClientId = "", index2) {
return moveBlocksToPosition(
[clientId],
fromRootClientId,
toRootClientId,
index2
);
}
function insertBlock(block, index2, rootClientId, updateSelection, initialPosition2, meta) {
return insertBlocks(
[block],
index2,
rootClientId,
updateSelection,
initialPosition2,
meta
);
}
var insertBlocks = (blocks2, index2, rootClientId, updateSelection = true, initialPosition2 = 0, meta) => ({ select: select3, dispatch }) => {
if (initialPosition2 !== null && typeof initialPosition2 === "object") {
meta = initialPosition2;
initialPosition2 = 0;
(0, import_deprecated4.default)(
"meta argument in wp.data.dispatch('core/block-editor')",
{
since: "5.8",
hint: "The meta argument is now the 6th argument of the function"
}
);
}
blocks2 = castArray2(blocks2);
const allowedBlocks = [];
for (const block of blocks2) {
const isValid2 = select3.canInsertBlockType(
block.name,
rootClientId
);
if (isValid2) {
allowedBlocks.push(block);
}
}
if (allowedBlocks.length) {
dispatch({
type: "INSERT_BLOCKS",
blocks: allowedBlocks,
index: index2,
rootClientId,
time: Date.now(),
updateSelection,
initialPosition: updateSelection ? initialPosition2 : null,
meta
});
}
};
function showInsertionPoint(rootClientId, index2, __unstableOptions = {}) {
const { __unstableWithInserter, operation, nearestSide } = __unstableOptions;
return {
type: "SHOW_INSERTION_POINT",
rootClientId,
index: index2,
__unstableWithInserter,
operation,
nearestSide
};
}
var hideInsertionPoint = () => ({ select: select3, dispatch }) => {
if (!select3.isBlockInsertionPointVisible()) {
return;
}
dispatch({
type: "HIDE_INSERTION_POINT"
});
};
function setTemplateValidity(isValid2) {
return {
type: "SET_TEMPLATE_VALIDITY",
isValid: isValid2
};
}
var synchronizeTemplate = () => ({ select: select3, dispatch }) => {
dispatch({ type: "SYNCHRONIZE_TEMPLATE" });
const blocks2 = select3.getBlocks();
const template2 = select3.getTemplate();
const updatedBlockList = (0, import_blocks8.synchronizeBlocksWithTemplate)(
blocks2,
template2
);
dispatch.resetBlocks(updatedBlockList);
};
var __unstableDeleteSelection = (isForward) => ({ registry, select: select3, dispatch }) => {
const selectionAnchor = select3.getSelectionStart();
const selectionFocus = select3.getSelectionEnd();
if (selectionAnchor.clientId === selectionFocus.clientId) {
return;
}
if (!selectionAnchor.attributeKey || !selectionFocus.attributeKey || typeof selectionAnchor.offset === "undefined" || typeof selectionFocus.offset === "undefined") {
return false;
}
const anchorRootClientId = select3.getBlockRootClientId(
selectionAnchor.clientId
);
const focusRootClientId = select3.getBlockRootClientId(
selectionFocus.clientId
);
if (anchorRootClientId !== focusRootClientId) {
return;
}
const blockOrder = select3.getBlockOrder(anchorRootClientId);
const anchorIndex = blockOrder.indexOf(selectionAnchor.clientId);
const focusIndex = blockOrder.indexOf(selectionFocus.clientId);
let selectionStart, selectionEnd;
if (anchorIndex > focusIndex) {
selectionStart = selectionFocus;
selectionEnd = selectionAnchor;
} else {
selectionStart = selectionAnchor;
selectionEnd = selectionFocus;
}
const targetSelection = isForward ? selectionEnd : selectionStart;
const targetBlock = select3.getBlock(targetSelection.clientId);
const targetBlockType = (0, import_blocks8.getBlockType)(targetBlock.name);
if (!targetBlockType.merge) {
return;
}
const selectionA = selectionStart;
const selectionB = selectionEnd;
const blockA = select3.getBlock(selectionA.clientId);
const blockB = select3.getBlock(selectionB.clientId);
const htmlA = blockA.attributes[selectionA.attributeKey];
const htmlB = blockB.attributes[selectionB.attributeKey];
let valueA = (0, import_rich_text3.create)({ html: htmlA });
let valueB = (0, import_rich_text3.create)({ html: htmlB });
valueA = (0, import_rich_text3.remove)(valueA, selectionA.offset, valueA.text.length);
valueB = (0, import_rich_text3.insert)(valueB, START_OF_SELECTED_AREA, 0, selectionB.offset);
const cloneA = (0, import_blocks8.cloneBlock)(blockA, {
[selectionA.attributeKey]: (0, import_rich_text3.toHTMLString)({ value: valueA })
});
const cloneB = (0, import_blocks8.cloneBlock)(blockB, {
[selectionB.attributeKey]: (0, import_rich_text3.toHTMLString)({ value: valueB })
});
const followingBlock = isForward ? cloneA : cloneB;
const blocksWithTheSameType = blockA.name === blockB.name ? [followingBlock] : (0, import_blocks8.switchToBlockType)(followingBlock, targetBlockType.name);
if (!blocksWithTheSameType || !blocksWithTheSameType.length) {
return;
}
let updatedAttributes;
if (isForward) {
const blockToMerge = blocksWithTheSameType.pop();
updatedAttributes = targetBlockType.merge(
blockToMerge.attributes,
cloneB.attributes
);
} else {
const blockToMerge = blocksWithTheSameType.shift();
updatedAttributes = targetBlockType.merge(
cloneA.attributes,
blockToMerge.attributes
);
}
const newAttributeKey = retrieveSelectedAttribute(updatedAttributes);
const convertedHtml = updatedAttributes[newAttributeKey];
const convertedValue = (0, import_rich_text3.create)({ html: convertedHtml });
const newOffset = convertedValue.text.indexOf(START_OF_SELECTED_AREA);
const newValue = (0, import_rich_text3.remove)(convertedValue, newOffset, newOffset + 1);
const newHtml = (0, import_rich_text3.toHTMLString)({ value: newValue });
updatedAttributes[newAttributeKey] = newHtml;
const selectedBlockClientIds = select3.getSelectedBlockClientIds();
const replacement = [
...isForward ? blocksWithTheSameType : [],
{
// Preserve the original client ID.
...targetBlock,
attributes: {
...targetBlock.attributes,
...updatedAttributes
},
// Block A's inner blocks sit inside the selection; only B's survive.
innerBlocks: blockB.innerBlocks
},
...isForward ? [] : blocksWithTheSameType
];
registry.batch(() => {
dispatch.selectionChange(
targetBlock.clientId,
newAttributeKey,
newOffset,
newOffset
);
dispatch.replaceBlocks(
selectedBlockClientIds,
replacement,
0,
// If we don't pass the `indexToSelect` it will default to the last block.
select3.getSelectedBlocksInitialCaretPosition()
);
});
};
var __unstableSplitSelection = (blocks2 = []) => ({ registry, select: select3, dispatch }) => {
const selectionAnchor = select3.getSelectionStart();
const selectionFocus = select3.getSelectionEnd();
const anchorRootClientId = select3.getBlockRootClientId(
selectionAnchor.clientId
);
const focusRootClientId = select3.getBlockRootClientId(
selectionFocus.clientId
);
if (anchorRootClientId !== focusRootClientId) {
return;
}
const blockOrder = select3.getBlockOrder(anchorRootClientId);
const anchorIndex = blockOrder.indexOf(selectionAnchor.clientId);
const focusIndex = blockOrder.indexOf(selectionFocus.clientId);
let selectionStart, selectionEnd;
if (anchorIndex > focusIndex) {
selectionStart = selectionFocus;
selectionEnd = selectionAnchor;
} else {
selectionStart = selectionAnchor;
selectionEnd = selectionFocus;
}
const selectionA = selectionStart;
const selectionB = selectionEnd;
const blockA = select3.getBlock(selectionA.clientId);
const blockB = select3.getBlock(selectionB.clientId);
const blockAType = (0, import_blocks8.getBlockType)(blockA.name);
const blockBType = (0, import_blocks8.getBlockType)(blockB.name);
const attributeKeyA = typeof selectionA.attributeKey === "string" ? selectionA.attributeKey : findRichTextAttributeKey(blockAType);
const attributeKeyB = typeof selectionB.attributeKey === "string" ? selectionB.attributeKey : findRichTextAttributeKey(blockBType);
const blockAttributes = select3.getBlockAttributes(
selectionA.clientId
);
const bindings = blockAttributes?.metadata?.bindings;
if (bindings?.[attributeKeyA]) {
if (blocks2.length) {
const { createWarningNotice } = registry.dispatch(import_notices.store);
createWarningNotice(
(0, import_i18n5.__)(
"Blocks can't be inserted into other blocks with bindings"
),
{
type: "snackbar"
}
);
return;
}
dispatch.insertAfterBlock(selectionA.clientId);
return;
}
if (!attributeKeyA || !attributeKeyB || typeof selectionAnchor.offset === "undefined" || typeof selectionFocus.offset === "undefined") {
return;
}
if (selectionA.clientId === selectionB.clientId && attributeKeyA === attributeKeyB && selectionA.offset === selectionB.offset) {
if (blocks2.length) {
if ((0, import_blocks8.isUnmodifiedDefaultBlock)(blockA, "content")) {
dispatch.replaceBlocks(
[selectionA.clientId],
blocks2,
blocks2.length - 1,
-1
);
return;
}
} else if (!select3.getBlockOrder(selectionA.clientId).length) {
let createEmpty2 = function() {
const defaultBlockName2 = (0, import_blocks8.getDefaultBlockName)();
return select3.canInsertBlockType(
defaultBlockName2,
anchorRootClientId
) ? (0, import_blocks8.createBlock)(defaultBlockName2) : (0, import_blocks8.createBlock)(
select3.getBlockName(selectionA.clientId)
);
};
var createEmpty = createEmpty2;
const length = blockAttributes[attributeKeyA].length;
if (selectionA.offset === 0 && length) {
dispatch.insertBlocks(
[createEmpty2()],
select3.getBlockIndex(selectionA.clientId),
anchorRootClientId,
false
);
return;
}
if (selectionA.offset === length) {
dispatch.insertBlocks(
[createEmpty2()],
select3.getBlockIndex(selectionA.clientId) + 1,
anchorRootClientId
);
return;
}
}
}
const htmlA = blockA.attributes[attributeKeyA];
const htmlB = blockB.attributes[attributeKeyB];
let valueA = (0, import_rich_text3.create)({ html: htmlA });
let valueB = (0, import_rich_text3.create)({ html: htmlB });
valueA = (0, import_rich_text3.remove)(valueA, selectionA.offset, valueA.text.length);
valueB = (0, import_rich_text3.remove)(valueB, 0, selectionB.offset);
let head = {
// Preserve the original client ID.
...blockA,
// If both start and end are the same, should only copy innerBlocks
// once.
innerBlocks: blockA.clientId === blockB.clientId ? [] : blockA.innerBlocks,
attributes: {
...blockA.attributes,
[attributeKeyA]: (0, import_rich_text3.toHTMLString)({ value: valueA })
}
};
let tail = {
...blockB,
// Only preserve the original client ID if the end is different.
clientId: blockA.clientId === blockB.clientId ? (0, import_blocks8.createBlock)(blockB.name).clientId : blockB.clientId,
attributes: {
...blockB.attributes,
[attributeKeyB]: (0, import_rich_text3.toHTMLString)({ value: valueB })
}
};
const defaultBlockName = (0, import_blocks8.getDefaultBlockName)();
if (
// A block is only split when the selection is within the same
// block.
blockA.clientId === blockB.clientId && defaultBlockName && tail.name !== defaultBlockName && select3.canInsertBlockType(defaultBlockName, anchorRootClientId)
) {
const switched = (0, import_blocks8.switchToBlockType)(tail, defaultBlockName);
if (switched?.length === 1) {
tail = switched[0];
}
}
if (!blocks2.length) {
dispatch.replaceBlocks(select3.getSelectedBlockClientIds(), [
head,
tail
]);
return;
}
let selection2;
const output = [];
const clonedBlocks = [...blocks2];
const firstBlock = clonedBlocks.shift();
const headType = (0, import_blocks8.getBlockType)(head.name);
const firstBlocks = headType.merge && firstBlock.name === headType.name ? [firstBlock] : (0, import_blocks8.switchToBlockType)(firstBlock, headType.name);
if (firstBlocks?.length) {
const first = firstBlocks.shift();
head = {
...head,
attributes: {
...head.attributes,
...headType.merge(head.attributes, first.attributes)
}
};
output.push(head);
selection2 = {
clientId: head.clientId,
attributeKey: attributeKeyA,
offset: (0, import_rich_text3.create)({ html: head.attributes[attributeKeyA] }).text.length
};
clonedBlocks.unshift(...firstBlocks);
} else {
if (!(0, import_blocks8.isUnmodifiedBlock)(head)) {
output.push(head);
}
output.push(firstBlock);
}
const lastBlock = clonedBlocks.pop();
const tailType = (0, import_blocks8.getBlockType)(tail.name);
if (clonedBlocks.length) {
output.push(...clonedBlocks);
}
if (lastBlock) {
const lastBlocks = tailType.merge && tailType.name === lastBlock.name ? [lastBlock] : (0, import_blocks8.switchToBlockType)(lastBlock, tailType.name);
if (lastBlocks?.length) {
const last = lastBlocks.pop();
output.push({
...tail,
attributes: {
...tail.attributes,
...tailType.merge(last.attributes, tail.attributes)
}
});
output.push(...lastBlocks);
selection2 = {
clientId: tail.clientId,
attributeKey: attributeKeyB,
offset: (0, import_rich_text3.create)({
html: last.attributes[attributeKeyB]
}).text.length
};
} else {
output.push(lastBlock);
if (!(0, import_blocks8.isUnmodifiedBlock)(tail)) {
output.push(tail);
}
}
} else if (!(0, import_blocks8.isUnmodifiedBlock)(tail)) {
output.push(tail);
}
registry.batch(() => {
dispatch.replaceBlocks(
select3.getSelectedBlockClientIds(),
output,
output.length - 1,
0
);
if (selection2) {
dispatch.selectionChange(
selection2.clientId,
selection2.attributeKey,
selection2.offset,
selection2.offset
);
}
});
};
var __unstableExpandSelection = () => ({ select: select3, dispatch }) => {
const selectionAnchor = select3.getSelectionStart();
const selectionFocus = select3.getSelectionEnd();
dispatch.selectionChange({
start: { clientId: selectionAnchor.clientId },
end: { clientId: selectionFocus.clientId }
});
};
var mergeBlocks = (firstBlockClientId, secondBlockClientId) => ({ registry, select: select3, dispatch }) => {
const clientIdA = firstBlockClientId;
const clientIdB = secondBlockClientId;
const blockA = select3.getBlock(clientIdA);
const blockAType = (0, import_blocks8.getBlockType)(blockA.name);
if (!blockAType || select3.getBlockEditingMode(clientIdA) === "disabled" || select3.getBlockEditingMode(clientIdB) === "disabled") {
return;
}
const blockB = select3.getBlock(clientIdB);
if (!blockAType.merge && (0, import_blocks8.getBlockSupport)(blockA.name, "__experimentalOnMerge")) {
const blocksWithTheSameType2 = (0, import_blocks8.switchToBlockType)(
blockB,
blockAType.name
);
if (blocksWithTheSameType2?.length !== 1) {
dispatch.selectBlock(blockA.clientId);
return;
}
const [blockWithSameType] = blocksWithTheSameType2;
if (blockWithSameType.innerBlocks.length < 1) {
dispatch.selectBlock(blockA.clientId);
return;
}
registry.batch(() => {
dispatch.insertBlocks(
blockWithSameType.innerBlocks,
void 0,
clientIdA
);
dispatch.removeBlock(clientIdB);
dispatch.selectBlock(
blockWithSameType.innerBlocks[0].clientId
);
const nextBlockClientId = select3.getNextBlockClientId(clientIdA);
if (nextBlockClientId && select3.getBlockName(clientIdA) === select3.getBlockName(nextBlockClientId)) {
const rootAttributes = select3.getBlockAttributes(clientIdA);
const previousRootAttributes = select3.getBlockAttributes(nextBlockClientId);
if (Object.keys(rootAttributes).every(
(key) => rootAttributes[key] === previousRootAttributes[key]
)) {
dispatch.moveBlocksToPosition(
select3.getBlockOrder(nextBlockClientId),
nextBlockClientId,
clientIdA
);
dispatch.removeBlock(nextBlockClientId, false);
}
}
});
return;
}
if ((0, import_blocks8.isUnmodifiedDefaultBlock)(blockA)) {
dispatch.removeBlock(
clientIdA,
select3.isBlockSelected(clientIdA)
);
return;
}
if ((0, import_blocks8.isUnmodifiedDefaultBlock)(blockB)) {
dispatch.removeBlock(
clientIdB,
select3.isBlockSelected(clientIdB)
);
return;
}
if (!blockAType.merge) {
if ((0, import_blocks8.isUnmodifiedBlock)(blockB, "content")) {
dispatch.removeBlock(
clientIdB,
select3.isBlockSelected(clientIdB)
);
} else {
dispatch.selectBlock(blockA.clientId);
}
return;
}
const blockBType = (0, import_blocks8.getBlockType)(blockB.name);
const { clientId, attributeKey, offset: offset4 } = select3.getSelectionStart();
const selectedBlockType = clientId === clientIdA ? blockAType : blockBType;
const attributeDefinition = selectedBlockType.attributes[attributeKey];
const canRestoreTextSelection = (clientId === clientIdA || clientId === clientIdB) && attributeKey !== void 0 && offset4 !== void 0 && // We cannot restore text selection if the RichText identifier
// is not a defined block attribute key. This can be the case if the
// fallback instance ID is used to store selection (and no RichText
// identifier is set), or when the identifier is wrong.
!!attributeDefinition;
if (!attributeDefinition) {
if (typeof attributeKey === "number") {
window.console.error(
`RichText needs an identifier prop that is the block attribute key of the attribute it controls. Its type is expected to be a string, but was ${typeof attributeKey}`
);
} else {
window.console.error(
"The RichText identifier prop does not match any attributes defined by the block."
);
}
}
const cloneA = (0, import_blocks8.cloneBlock)(blockA);
const cloneB = (0, import_blocks8.cloneBlock)(blockB);
if (canRestoreTextSelection) {
const selectedBlock = clientId === clientIdA ? cloneA : cloneB;
const html = selectedBlock.attributes[attributeKey];
const value = (0, import_rich_text3.insert)(
(0, import_rich_text3.create)({ html }),
START_OF_SELECTED_AREA,
offset4,
offset4
);
selectedBlock.attributes[attributeKey] = (0, import_rich_text3.toHTMLString)({
value
});
}
const blocksWithTheSameType = blockA.name === blockB.name ? [cloneB] : (0, import_blocks8.switchToBlockType)(cloneB, blockA.name);
if (!blocksWithTheSameType || !blocksWithTheSameType.length) {
return;
}
const updatedAttributes = blockAType.merge(
cloneA.attributes,
blocksWithTheSameType[0].attributes
);
if (canRestoreTextSelection) {
const newAttributeKey = retrieveSelectedAttribute(updatedAttributes);
const convertedHtml = updatedAttributes[newAttributeKey];
const convertedValue = (0, import_rich_text3.create)({ html: convertedHtml });
const newOffset = convertedValue.text.indexOf(
START_OF_SELECTED_AREA
);
const newValue = (0, import_rich_text3.remove)(convertedValue, newOffset, newOffset + 1);
const newHtml = (0, import_rich_text3.toHTMLString)({ value: newValue });
updatedAttributes[newAttributeKey] = newHtml;
dispatch.selectionChange(
blockA.clientId,
newAttributeKey,
newOffset,
newOffset
);
}
dispatch.replaceBlocks(
[blockA.clientId, blockB.clientId],
[
{
...blockA,
attributes: {
...blockA.attributes,
...updatedAttributes
}
},
...blocksWithTheSameType.slice(1)
],
0
// If we don't pass the `indexToSelect` it will default to the last block.
);
};
var removeBlocks = (clientIds, selectPrevious = true) => privateRemoveBlocks(clientIds, selectPrevious);
function removeBlock(clientId, selectPrevious) {
return removeBlocks([clientId], selectPrevious);
}
function replaceInnerBlocks(rootClientId, blocks2, updateSelection = false, initialPosition2 = 0) {
return {
type: "REPLACE_INNER_BLOCKS",
rootClientId,
blocks: blocks2,
updateSelection,
initialPosition: updateSelection ? initialPosition2 : null,
time: Date.now()
};
}
function toggleBlockMode(clientId) {
return {
type: "TOGGLE_BLOCK_MODE",
clientId
};
}
function startTyping() {
return {
type: "START_TYPING"
};
}
function stopTyping() {
return {
type: "STOP_TYPING"
};
}
function startDraggingBlocks(clientIds = []) {
return {
type: "START_DRAGGING_BLOCKS",
clientIds
};
}
function stopDraggingBlocks() {
return {
type: "STOP_DRAGGING_BLOCKS"
};
}
function enterFormattedText() {
(0, import_deprecated4.default)('wp.data.dispatch( "core/block-editor" ).enterFormattedText', {
since: "6.1",
version: "6.3"
});
return {
type: "DO_NOTHING"
};
}
function exitFormattedText() {
(0, import_deprecated4.default)('wp.data.dispatch( "core/block-editor" ).exitFormattedText', {
since: "6.1",
version: "6.3"
});
return {
type: "DO_NOTHING"
};
}
function selectionChange(clientId, attributeKey, startOffset, endOffset) {
if (typeof clientId === "string") {
return {
type: "SELECTION_CHANGE",
clientId,
attributeKey,
startOffset,
endOffset
};
}
return { type: "SELECTION_CHANGE", ...clientId };
}
var insertDefaultBlock = (attributes, rootClientId, index2) => ({ dispatch }) => {
const defaultBlockName = (0, import_blocks8.getDefaultBlockName)();
if (!defaultBlockName) {
return;
}
const block = (0, import_blocks8.createBlock)(defaultBlockName, attributes);
return dispatch.insertBlock(block, index2, rootClientId);
};
function updateBlockListSettings(clientId, settings2) {
return {
type: "UPDATE_BLOCK_LIST_SETTINGS",
clientId,
settings: settings2
};
}
function updateSettings(settings2) {
return __experimentalUpdateSettings(settings2, {
stripExperimentalSettings: true
});
}
function __unstableSaveReusableBlock() {
(0, import_deprecated4.default)(
'wp.data.dispatch( "core/block-editor" ).__unstableSaveReusableBlock',
{
since: "7.1"
}
);
return {
type: "DO_NOTHING"
};
}
function __unstableMarkLastChangeAsPersistent() {
return { type: "MARK_LAST_CHANGE_AS_PERSISTENT" };
}
function __unstableMarkNextChangeAsNotPersistent({
history = "merge"
} = {}) {
return { type: "MARK_NEXT_CHANGE_AS_NOT_PERSISTENT", history };
}
var __unstableMarkAutomaticChange = () => ({ dispatch }) => {
dispatch({ type: "MARK_AUTOMATIC_CHANGE" });
const { requestIdleCallback = (cb) => setTimeout(cb, 100) } = window;
requestIdleCallback(() => {
dispatch({ type: "MARK_AUTOMATIC_CHANGE_FINAL" });
});
};
var __unstableSetEditorMode = (mode2) => ({ registry }) => {
registry.dispatch(import_preferences.store).set("core", "editorTool", mode2);
if (mode2 === "navigation") {
(0, import_a11y3.speak)((0, import_i18n5.__)("You are currently in Write mode."));
} else if (mode2 === "edit") {
(0, import_a11y3.speak)((0, import_i18n5.__)("You are currently in Design mode."));
}
};
function setBlockMovingClientId() {
(0, import_deprecated4.default)(
'wp.data.dispatch( "core/block-editor" ).setBlockMovingClientId',
{
since: "6.7",
hint: "Block moving mode feature has been removed"
}
);
return {
type: "DO_NOTHING"
};
}
var duplicateBlocks = (clientIds, updateSelection = true) => ({ select: select3, dispatch }) => {
if (!clientIds || !clientIds.length) {
return;
}
const blocks2 = select3.getBlocksByClientId(clientIds);
if (blocks2.some((block) => !block)) {
return;
}
const blockNames = blocks2.map((block) => block.name);
if (blockNames.some(
(blockName) => !(0, import_blocks8.hasBlockSupport)(blockName, "multiple", true)
)) {
return;
}
const rootClientId = select3.getBlockRootClientId(clientIds[0]);
const clientIdsArray = castArray2(clientIds);
const lastSelectedIndex = select3.getBlockIndex(
clientIdsArray[clientIdsArray.length - 1]
);
const clonedBlocks = blocks2.map(
(block) => (0, import_blocks8.cloneSanitizedBlock)(block)
);
dispatch.insertBlocks(
clonedBlocks,
lastSelectedIndex + 1,
rootClientId,
updateSelection
);
if (clonedBlocks.length > 1 && updateSelection) {
dispatch.multiSelect(
clonedBlocks[0].clientId,
clonedBlocks[clonedBlocks.length - 1].clientId
);
}
return clonedBlocks.map((block) => block.clientId);
};
var insertBeforeBlock = (clientId) => ({ select: select3, dispatch }) => {
if (!clientId) {
return;
}
const rootClientId = select3.getBlockRootClientId(clientId);
const blockIndex = select3.getBlockIndex(clientId);
const { defaultBlock: directInsertBlock } = rootClientId ? select3.getBlockListSettings(rootClientId) ?? {} : {};
if (!directInsertBlock) {
return dispatch.insertDefaultBlock({}, rootClientId, blockIndex);
}
const copiedAttributes = {};
if (directInsertBlock.attributesToCopy) {
const attributes = select3.getBlockAttributes(clientId);
directInsertBlock.attributesToCopy.forEach((key) => {
if (attributes[key]) {
copiedAttributes[key] = attributes[key];
}
});
}
const block = (0, import_blocks8.createBlock)(directInsertBlock.name, {
...directInsertBlock.attributes,
...copiedAttributes
});
return dispatch.insertBlock(block, blockIndex, rootClientId);
};
var insertAfterBlock = (clientId) => ({ select: select3, dispatch }) => {
if (!clientId) {
return;
}
const rootClientId = select3.getBlockRootClientId(clientId);
const blockIndex = select3.getBlockIndex(clientId);
const { defaultBlock: directInsertBlock } = rootClientId ? select3.getBlockListSettings(rootClientId) ?? {} : {};
if (!directInsertBlock) {
return dispatch.insertDefaultBlock(
{},
rootClientId,
blockIndex + 1
);
}
const copiedAttributes = {};
if (directInsertBlock.attributesToCopy) {
const attributes = select3.getBlockAttributes(clientId);
directInsertBlock.attributesToCopy.forEach((key) => {
if (attributes[key]) {
copiedAttributes[key] = attributes[key];
}
});
}
const block = (0, import_blocks8.createBlock)(directInsertBlock.name, {
...directInsertBlock.attributes,
...copiedAttributes
});
return dispatch.insertBlock(block, blockIndex + 1, rootClientId);
};
function toggleBlockHighlight(clientId, isHighlighted) {
return {
type: "TOGGLE_BLOCK_HIGHLIGHT",
clientId,
isHighlighted
};
}
var flashBlock = (clientId, timeout = 150) => async ({ dispatch }) => {
dispatch(toggleBlockHighlight(clientId, true));
await new Promise((resolve) => setTimeout(resolve, timeout));
dispatch(toggleBlockHighlight(clientId, false));
};
function setHasControlledInnerBlocks(clientId, hasControlledInnerBlocks) {
return {
type: "SET_HAS_CONTROLLED_INNER_BLOCKS",
hasControlledInnerBlocks,
clientId
};
}
function setBlockVisibility(updates) {
return {
type: "SET_BLOCK_VISIBILITY",
updates
};
}
function __unstableSetTemporarilyEditingAsBlocks(clientId) {
(0, import_deprecated4.default)(
"wp.data.dispatch( 'core/block-editor' ).__unstableSetTemporarilyEditingAsBlocks",
{
since: "7.0"
}
);
return editContentOnlySection(clientId);
}
var registerInserterMediaCategory = (category) => ({ select: select3, dispatch }) => {
if (!category || typeof category !== "object") {
console.error(
"Category should be an `InserterMediaCategory` object."
);
return;
}
if (!category.name) {
console.error(
"Category should have a `name` that should be unique among all media categories."
);
return;
}
if (!category.labels?.name) {
console.error("Category should have a `labels.name`.");
return;
}
if (!["image", "audio", "video"].includes(category.mediaType)) {
console.error(
"Category should have `mediaType` property that is one of `image|audio|video`."
);
return;
}
if (!category.fetch || typeof category.fetch !== "function") {
console.error(
"Category should have a `fetch` function defined with the following signature `(InserterMediaRequest) => Promise<InserterMediaItem[]|InserterMediaResponse>`."
);
return;
}
const registeredInserterMediaCategories2 = select3.getRegisteredInserterMediaCategories();
if (registeredInserterMediaCategories2.some(
({ name }) => name === category.name
)) {
console.error(
`A category is already registered with the same name: "${category.name}".`
);
return;
}
if (registeredInserterMediaCategories2.some(
({ labels: { name } = {} }) => name === category.labels?.name
)) {
console.error(
`A category is already registered with the same labels.name: "${category.labels.name}".`
);
return;
}
dispatch({
type: "REGISTER_INSERTER_MEDIA_CATEGORY",
category: { ...category, isExternalResource: true }
});
};
function setBlockEditingMode(clientId = "", mode2) {
return {
type: "SET_BLOCK_EDITING_MODE",
clientId,
mode: mode2
};
}
function unsetBlockEditingMode(clientId = "") {
return {
type: "UNSET_BLOCK_EDITING_MODE",
clientId
};
}
function __unstableSetOpenListViewPanel(clientId) {
return {
type: "SET_OPEN_LIST_VIEW_PANEL",
clientId
};
}
function __unstableSetAllListViewPanelsOpen() {
return {
type: "SET_ALL_LIST_VIEW_PANELS_OPEN"
};
}
function __unstableToggleListViewPanel(clientId, isOpen) {
return {
type: "TOGGLE_LIST_VIEW_PANEL",
clientId,
isOpen
};
}
function __unstableIncrementListViewExpandRevision() {
return {
type: "INCREMENT_LIST_VIEW_EXPAND_REVISION"
};
}
// packages/block-editor/build-module/store/index.mjs
var storeConfig = {
reducer: reducer_default,
selectors: selectors_exports,
actions: actions_exports
};
var store = (0, import_data6.createReduxStore)(STORE_NAME, {
...storeConfig,
persist: ["preferences"]
});
var registeredStore = (0, import_data6.registerStore)(STORE_NAME, {
...storeConfig,
persist: ["preferences"]
});
unlock(registeredStore).registerPrivateActions(private_actions_exports);
unlock(registeredStore).registerPrivateSelectors(private_selectors_exports);
unlock(store).registerPrivateActions(private_actions_exports);
unlock(store).registerPrivateSelectors(private_selectors_exports);
// packages/block-editor/build-module/components/warning/index.mjs
var import_components3 = __toESM(require_components(), 1);
var import_i18n6 = __toESM(require_i18n(), 1);
var import_jsx_runtime119 = __toESM(require_jsx_runtime(), 1);
function Warning({ className, actions, children, secondaryActions }) {
return /* @__PURE__ */ (0, import_jsx_runtime119.jsx)("div", { style: { display: "contents", all: "initial" }, children: /* @__PURE__ */ (0, import_jsx_runtime119.jsx)("div", { className: clsx_default(className, "block-editor-warning"), children: /* @__PURE__ */ (0, import_jsx_runtime119.jsxs)("div", { className: "block-editor-warning__contents", children: [
/* @__PURE__ */ (0, import_jsx_runtime119.jsx)("p", { className: "block-editor-warning__message", children }),
(actions?.length > 0 || secondaryActions) && /* @__PURE__ */ (0, import_jsx_runtime119.jsxs)("div", { className: "block-editor-warning__actions", children: [
actions?.length > 0 && actions.map((action, i2) => /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(
"span",
{
className: "block-editor-warning__action",
children: action
},
i2
)),
secondaryActions && /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(
import_components3.DropdownMenu,
{
className: "block-editor-warning__secondary",
icon: more_vertical_default,
label: (0, import_i18n6.__)("More options"),
popoverProps: {
placement: "bottom-end",
className: "block-editor-warning__dropdown"
},
noIcons: true,
children: () => /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(import_components3.MenuGroup, { children: secondaryActions.map(
(item, pos) => /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(
import_components3.MenuItem,
{
onClick: item.onClick,
children: item.title
},
pos
)
) })
}
)
] })
] }) }) });
}
var warning_default = Warning;
// packages/block-editor/build-module/components/block-edit/multiple-usage-warning.mjs
var import_jsx_runtime120 = __toESM(require_jsx_runtime(), 1);
function MultipleUsageWarning({
originalBlockClientId,
name,
onReplace
}) {
const { selectBlock: selectBlock2 } = (0, import_data7.useDispatch)(store);
const blockType = (0, import_blocks9.getBlockType)(name);
return /* @__PURE__ */ (0, import_jsx_runtime120.jsxs)(
warning_default,
{
actions: [
/* @__PURE__ */ (0, import_jsx_runtime120.jsx)(
import_components4.Button,
{
__next40pxDefaultSize: true,
variant: "secondary",
onClick: () => selectBlock2(originalBlockClientId),
children: (0, import_i18n7.__)("Find original")
},
"find-original"
),
/* @__PURE__ */ (0, import_jsx_runtime120.jsx)(
import_components4.Button,
{
__next40pxDefaultSize: true,
variant: "secondary",
onClick: () => onReplace([]),
children: (0, import_i18n7.__)("Remove")
},
"remove"
)
],
children: [
/* @__PURE__ */ (0, import_jsx_runtime120.jsxs)("strong", { children: [
blockType?.title,
": "
] }),
(0, import_i18n7.__)("This block can only be used once.")
]
}
);
}
// packages/block-editor/build-module/components/block-edit/index.mjs
var import_jsx_runtime121 = __toESM(require_jsx_runtime(), 1);
function BlockEdit({
mayDisplayControls,
mayDisplayParentControls,
mayDisplayPatternEditingControls,
blockEditingMode,
isPreviewMode,
// The remaining props are passed through the BlockEdit filters and are thus
// public API!
...props
}) {
const {
name,
isSelected,
clientId,
attributes = {},
__unstableLayoutClassNames
} = props;
const { layout = null, metadata = {} } = attributes;
const { bindings } = metadata;
const layoutSupport = (0, import_blocks10.hasBlockSupport)(name, "layout", false) || (0, import_blocks10.hasBlockSupport)(name, "__experimentalLayout", false);
const parentBlockEditContext = useBlockEditContext();
const isInListViewBlockSupportTree = !!parentBlockEditContext[isInListViewBlockSupportTreeKey] || (0, import_blocks10.hasBlockSupport)(name, "listView") || name === "core/navigation";
const { originalBlockClientId } = (0, import_element6.useContext)(PrivateBlockContext);
return /* @__PURE__ */ (0, import_jsx_runtime121.jsxs)(
Provider,
{
value: (0, import_element6.useMemo)(
() => ({
name,
isSelected,
clientId,
layout: layoutSupport ? layout : null,
__unstableLayoutClassNames,
// We use symbols in favour of an __unstable prefix to avoid
// usage outside of the package (this context is exposed).
[mayDisplayControlsKey]: mayDisplayControls,
[mayDisplayParentControlsKey]: mayDisplayParentControls,
[mayDisplayPatternEditingControlsKey]: mayDisplayPatternEditingControls && blockEditingMode !== "disabled",
[blockEditingModeKey]: blockEditingMode,
[blockBindingsKey]: bindings,
[isPreviewModeKey]: isPreviewMode,
[isInListViewBlockSupportTreeKey]: isInListViewBlockSupportTree
}),
[
name,
isSelected,
clientId,
layoutSupport,
layout,
__unstableLayoutClassNames,
mayDisplayControls,
mayDisplayParentControls,
mayDisplayPatternEditingControls,
blockEditingMode,
bindings,
isPreviewMode,
isInListViewBlockSupportTree
]
),
children: [
/* @__PURE__ */ (0, import_jsx_runtime121.jsx)(edit_default, { ...props }),
originalBlockClientId && /* @__PURE__ */ (0, import_jsx_runtime121.jsx)(
MultipleUsageWarning,
{
originalBlockClientId,
name,
onReplace: props.onReplace
}
)
]
}
);
}
// packages/block-editor/build-module/components/use-settings/index.mjs
function useSettings(...paths) {
const { clientId = null } = useBlockEditContext();
return (0, import_data8.useSelect)(
(select3) => unlock(select3(store)).getBlockSettings(
clientId,
...paths
),
[clientId, ...paths]
);
}
function useSetting(path) {
(0, import_deprecated5.default)("wp.blockEditor.useSetting", {
since: "6.5",
alternative: "wp.blockEditor.useSettings",
note: "The new useSettings function can retrieve multiple settings at once, with better performance."
});
const [value] = useSettings(path);
return value;
}
// packages/block-editor/build-module/components/colors/with-colors.mjs
var import_jsx_runtime122 = __toESM(require_jsx_runtime(), 1);
var { kebabCase: kebabCase3 } = unlock(import_components5.privateApis);
var upperFirst = ([firstLetter, ...rest]) => firstLetter.toUpperCase() + rest.join("");
var withCustomColorPalette = (colorsArray) => (0, import_compose2.createHigherOrderComponent)(
(WrappedComponent) => function WithCustomColorPalette(props) {
return /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(WrappedComponent, { ...props, colors: colorsArray });
},
"withCustomColorPalette"
);
var withEditorColorPalette = () => (0, import_compose2.createHigherOrderComponent)(
(WrappedComponent) => function WithEditorColorPalette(props) {
const [userPalette, themePalette, defaultPalette] = useSettings(
"color.palette.custom",
"color.palette.theme",
"color.palette.default"
);
const allColors = (0, import_element7.useMemo)(
() => [
...userPalette || [],
...themePalette || [],
...defaultPalette || []
],
[userPalette, themePalette, defaultPalette]
);
return /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(WrappedComponent, { ...props, colors: allColors });
},
"withEditorColorPalette"
);
function createColorHOC(colorTypes, withColorPalette) {
const colorMap = colorTypes.reduce((colorObject, colorType) => {
return {
...colorObject,
...typeof colorType === "string" ? { [colorType]: kebabCase3(colorType) } : colorType
};
}, {});
return (0, import_compose2.compose)([
withColorPalette,
(WrappedComponent) => {
return class WithColors extends import_element7.Component {
constructor(props) {
super(props);
this.setters = this.createSetters();
this.colorUtils = {
getMostReadableColor: this.getMostReadableColor.bind(this)
};
this.state = {};
}
getMostReadableColor(colorValue) {
const { colors: colors2 } = this.props;
return getMostReadableColor(colors2, colorValue);
}
createSetters() {
return Object.keys(colorMap).reduce(
(settersAccumulator, colorAttributeName) => {
const upperFirstColorAttributeName = upperFirst(colorAttributeName);
const customColorAttributeName = `custom${upperFirstColorAttributeName}`;
settersAccumulator[`set${upperFirstColorAttributeName}`] = this.createSetColor(
colorAttributeName,
customColorAttributeName
);
return settersAccumulator;
},
{}
);
}
createSetColor(colorAttributeName, customColorAttributeName) {
return (colorValue) => {
const colorObject = getColorObjectByColorValue(
this.props.colors,
colorValue
);
this.props.setAttributes({
[colorAttributeName]: colorObject && colorObject.slug ? colorObject.slug : void 0,
[customColorAttributeName]: colorObject && colorObject.slug ? void 0 : colorValue
});
};
}
static getDerivedStateFromProps({ attributes, colors: colors2 }, previousState) {
return Object.entries(colorMap).reduce(
(newState, [colorAttributeName, colorContext]) => {
const colorObject = getColorObjectByAttributeValues(
colors2,
attributes[colorAttributeName],
attributes[`custom${upperFirst(
colorAttributeName
)}`]
);
const previousColorObject = previousState[colorAttributeName];
const previousColor = previousColorObject?.color;
if (previousColor === colorObject.color && previousColorObject) {
newState[colorAttributeName] = previousColorObject;
} else {
newState[colorAttributeName] = {
...colorObject,
class: getColorClassName(
colorContext,
colorObject.slug
)
};
}
return newState;
},
{}
);
}
render() {
return /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(
WrappedComponent,
{
...{
...this.props,
colors: void 0,
...this.state,
...this.setters,
colorUtils: this.colorUtils
}
}
);
}
};
}
]);
}
function createCustomColorsHOC(colorsArray) {
return (...colorTypes) => {
const withColorPalette = withCustomColorPalette(colorsArray);
return (0, import_compose2.createHigherOrderComponent)(
createColorHOC(colorTypes, withColorPalette),
"withCustomColors"
);
};
}
function withColors(...colorTypes) {
const withColorPalette = withEditorColorPalette();
return (0, import_compose2.createHigherOrderComponent)(
createColorHOC(colorTypes, withColorPalette),
"withColors"
);
}
// packages/block-editor/build-module/components/gradients/use-gradient.mjs
var import_element8 = __toESM(require_element(), 1);
var import_data9 = __toESM(require_data(), 1);
function __experimentalGetGradientClass(gradientSlug) {
if (!gradientSlug) {
return void 0;
}
return `has-${gradientSlug}-gradient-background`;
}
function getGradientValueBySlug(gradients, slug) {
const gradient = gradients?.find((g2) => g2.slug === slug);
return gradient && gradient.gradient;
}
function __experimentalGetGradientObjectByGradientValue(gradients, value) {
const gradient = gradients?.find((g2) => g2.gradient === value);
return gradient;
}
function getGradientSlugByValue(gradients, value) {
const gradient = __experimentalGetGradientObjectByGradientValue(
gradients,
value
);
return gradient && gradient.slug;
}
function useGradient({
gradientAttribute = "gradient",
customGradientAttribute = "customGradient"
} = {}) {
const { clientId } = useBlockEditContext();
const [
userGradientPalette,
themeGradientPalette,
defaultGradientPalette
] = useSettings(
"color.gradients.custom",
"color.gradients.theme",
"color.gradients.default"
);
const allGradients = (0, import_element8.useMemo)(
() => [
...userGradientPalette || [],
...themeGradientPalette || [],
...defaultGradientPalette || []
],
[userGradientPalette, themeGradientPalette, defaultGradientPalette]
);
const { gradient, customGradient } = (0, import_data9.useSelect)(
(select3) => {
const { getBlockAttributes: getBlockAttributes3 } = select3(store);
const attributes = getBlockAttributes3(clientId) || {};
return {
customGradient: attributes[customGradientAttribute],
gradient: attributes[gradientAttribute]
};
},
[clientId, gradientAttribute, customGradientAttribute]
);
const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data9.useDispatch)(store);
const setGradient = (0, import_element8.useCallback)(
(newGradientValue) => {
const slug = getGradientSlugByValue(
allGradients,
newGradientValue
);
if (slug) {
updateBlockAttributes2(clientId, {
[gradientAttribute]: slug,
[customGradientAttribute]: void 0
});
return;
}
updateBlockAttributes2(clientId, {
[gradientAttribute]: void 0,
[customGradientAttribute]: newGradientValue
});
},
[allGradients, clientId, updateBlockAttributes2]
);
const gradientClass = __experimentalGetGradientClass(gradient);
let gradientValue;
if (gradient) {
gradientValue = getGradientValueBySlug(allGradients, gradient);
} else {
gradientValue = customGradient;
}
return { gradientClass, gradientValue, setGradient };
}
// packages/block-editor/build-module/components/font-sizes/utils.mjs
var import_components6 = __toESM(require_components(), 1);
var { kebabCase: kebabCase4 } = unlock(import_components6.privateApis);
var getFontSize = (fontSizes, fontSizeAttribute, customFontSizeAttribute) => {
if (fontSizeAttribute) {
const fontSizeObject = fontSizes?.find(
({ slug }) => slug === fontSizeAttribute
);
if (fontSizeObject) {
return fontSizeObject;
}
}
return {
size: customFontSizeAttribute
};
};
function getFontSizeObjectByValue(fontSizes, value) {
const fontSizeObject = fontSizes?.find(({ size: size4 }) => size4 === value);
if (fontSizeObject) {
return fontSizeObject;
}
return {
size: value
};
}
function getFontSizeClass(fontSizeSlug) {
if (!fontSizeSlug) {
return;
}
return `has-${kebabCase4(fontSizeSlug)}-font-size`;
}
// packages/block-editor/build-module/components/font-sizes/fluid-utils.mjs
var DEFAULT_MAXIMUM_VIEWPORT_WIDTH2 = "1600px";
var DEFAULT_MINIMUM_VIEWPORT_WIDTH2 = "320px";
var DEFAULT_SCALE_FACTOR2 = 1;
var DEFAULT_MINIMUM_FONT_SIZE_FACTOR_MIN2 = 0.25;
var DEFAULT_MINIMUM_FONT_SIZE_FACTOR_MAX2 = 0.75;
var DEFAULT_MINIMUM_FONT_SIZE_LIMIT2 = "14px";
function getComputedFluidTypographyValue2({
minimumFontSize,
maximumFontSize,
fontSize,
minimumViewportWidth = DEFAULT_MINIMUM_VIEWPORT_WIDTH2,
maximumViewportWidth = DEFAULT_MAXIMUM_VIEWPORT_WIDTH2,
scaleFactor = DEFAULT_SCALE_FACTOR2,
minimumFontSizeLimit
}) {
minimumFontSizeLimit = !!getTypographyValueAndUnit2(minimumFontSizeLimit) ? minimumFontSizeLimit : DEFAULT_MINIMUM_FONT_SIZE_LIMIT2;
if (fontSize) {
const fontSizeParsed = getTypographyValueAndUnit2(fontSize);
if (!fontSizeParsed?.unit) {
return null;
}
const minimumFontSizeLimitParsed = getTypographyValueAndUnit2(
minimumFontSizeLimit,
{
coerceTo: fontSizeParsed.unit
}
);
if (!!minimumFontSizeLimitParsed?.value && !minimumFontSize && !maximumFontSize) {
if (fontSizeParsed?.value <= minimumFontSizeLimitParsed?.value) {
return null;
}
}
if (!maximumFontSize) {
maximumFontSize = `${fontSizeParsed.value}${fontSizeParsed.unit}`;
}
if (!minimumFontSize) {
const fontSizeValueInPx = fontSizeParsed.unit === "px" ? fontSizeParsed.value : fontSizeParsed.value * 16;
const minimumFontSizeFactor = Math.min(
Math.max(
1 - 0.075 * Math.log2(fontSizeValueInPx),
DEFAULT_MINIMUM_FONT_SIZE_FACTOR_MIN2
),
DEFAULT_MINIMUM_FONT_SIZE_FACTOR_MAX2
);
const calculatedMinimumFontSize = roundToPrecision2(
fontSizeParsed.value * minimumFontSizeFactor,
3
);
if (!!minimumFontSizeLimitParsed?.value && calculatedMinimumFontSize < minimumFontSizeLimitParsed?.value) {
minimumFontSize = `${minimumFontSizeLimitParsed.value}${minimumFontSizeLimitParsed.unit}`;
} else {
minimumFontSize = `${calculatedMinimumFontSize}${fontSizeParsed.unit}`;
}
}
}
const minimumFontSizeParsed = getTypographyValueAndUnit2(minimumFontSize);
const fontSizeUnit = minimumFontSizeParsed?.unit || "rem";
const maximumFontSizeParsed = getTypographyValueAndUnit2(maximumFontSize, {
coerceTo: fontSizeUnit
});
if (!minimumFontSizeParsed || !maximumFontSizeParsed) {
return null;
}
const minimumFontSizeRem = getTypographyValueAndUnit2(minimumFontSize, {
coerceTo: "rem"
});
const maximumViewportWidthParsed = getTypographyValueAndUnit2(
maximumViewportWidth,
{ coerceTo: fontSizeUnit }
);
const minimumViewportWidthParsed = getTypographyValueAndUnit2(
minimumViewportWidth,
{ coerceTo: fontSizeUnit }
);
if (!maximumViewportWidthParsed || !minimumViewportWidthParsed || !minimumFontSizeRem) {
return null;
}
const linearDenominator = maximumViewportWidthParsed.value - minimumViewportWidthParsed.value;
if (!linearDenominator) {
return null;
}
const minViewportWidthOffsetValue = roundToPrecision2(
minimumViewportWidthParsed.value / 100,
3
);
const viewportWidthOffset = roundToPrecision2(minViewportWidthOffsetValue, 3) + fontSizeUnit;
const linearFactor = 100 * ((maximumFontSizeParsed.value - minimumFontSizeParsed.value) / linearDenominator);
const linearFactorScaled = roundToPrecision2(
(linearFactor || 1) * scaleFactor,
3
);
const fluidTargetFontSize = `${minimumFontSizeRem.value}${minimumFontSizeRem.unit} + ((1vw - ${viewportWidthOffset}) * ${linearFactorScaled})`;
return `clamp(${minimumFontSize}, ${fluidTargetFontSize}, ${maximumFontSize})`;
}
function getTypographyValueAndUnit2(rawValue, options = {}) {
if (typeof rawValue !== "string" && typeof rawValue !== "number") {
return null;
}
if (isFinite(rawValue)) {
rawValue = `${rawValue}px`;
}
const { coerceTo, rootSizeValue, acceptableUnits } = {
coerceTo: "",
// Default browser font size. Later we could inject some JS to compute this `getComputedStyle( document.querySelector( "html" ) ).fontSize`.
rootSizeValue: 16,
acceptableUnits: ["rem", "px", "em"],
...options
};
const acceptableUnitsGroup = acceptableUnits?.join("|");
const regexUnits = new RegExp(
`^(\\d*\\.?\\d+)(${acceptableUnitsGroup}){1,1}$`
);
const matches = rawValue.match(regexUnits);
if (!matches || matches.length < 3) {
return null;
}
let [, value, unit] = matches;
let returnValue = parseFloat(value);
if ("px" === coerceTo && ("em" === unit || "rem" === unit)) {
returnValue = returnValue * rootSizeValue;
unit = coerceTo;
}
if ("px" === unit && ("em" === coerceTo || "rem" === coerceTo)) {
returnValue = returnValue / rootSizeValue;
unit = coerceTo;
}
if (("em" === coerceTo || "rem" === coerceTo) && ("em" === unit || "rem" === unit)) {
unit = coerceTo;
}
return {
value: roundToPrecision2(returnValue, 3),
unit
};
}
function roundToPrecision2(value, digits = 3) {
const base = Math.pow(10, digits);
return Number.isFinite(value) ? parseFloat(Math.round(value * base) / base) : void 0;
}
// packages/block-editor/build-module/components/font-sizes/font-size-picker.mjs
var import_components7 = __toESM(require_components(), 1);
var import_jsx_runtime123 = __toESM(require_jsx_runtime(), 1);
function FontSizePicker(props) {
const [fontSizes, customFontSize] = useSettings(
"typography.fontSizes",
"typography.customFontSize"
);
return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(
import_components7.FontSizePicker,
{
...props,
fontSizes,
disableCustomFontSizes: !customFontSize
}
);
}
var font_size_picker_default = FontSizePicker;
// packages/block-editor/build-module/components/font-sizes/with-font-sizes.mjs
var import_compose3 = __toESM(require_compose(), 1);
var import_element9 = __toESM(require_element(), 1);
var import_jsx_runtime124 = __toESM(require_jsx_runtime(), 1);
var DEFAULT_FONT_SIZES = [];
var upperFirst2 = ([firstLetter, ...rest]) => firstLetter.toUpperCase() + rest.join("");
var with_font_sizes_default = (...fontSizeNames) => {
const fontSizeAttributeNames = fontSizeNames.reduce(
(fontSizeAttributeNamesAccumulator, fontSizeAttributeName) => {
fontSizeAttributeNamesAccumulator[fontSizeAttributeName] = `custom${upperFirst2(fontSizeAttributeName)}`;
return fontSizeAttributeNamesAccumulator;
},
{}
);
return (0, import_compose3.createHigherOrderComponent)(
(0, import_compose3.compose)([
(0, import_compose3.createHigherOrderComponent)(
(WrappedComponent) => function WithFontSizesInner(props) {
const [fontSizes] = useSettings(
"typography.fontSizes"
);
return /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(
WrappedComponent,
{
...props,
fontSizes: fontSizes || DEFAULT_FONT_SIZES
}
);
},
"withFontSizes"
),
(WrappedComponent) => {
return class WithFontSizes extends import_element9.Component {
constructor(props) {
super(props);
this.setters = this.createSetters();
this.state = {};
}
createSetters() {
return Object.entries(fontSizeAttributeNames).reduce(
(settersAccumulator, [
fontSizeAttributeName,
customFontSizeAttributeName
]) => {
const upperFirstFontSizeAttributeName = upperFirst2(fontSizeAttributeName);
settersAccumulator[`set${upperFirstFontSizeAttributeName}`] = this.createSetFontSize(
fontSizeAttributeName,
customFontSizeAttributeName
);
return settersAccumulator;
},
{}
);
}
createSetFontSize(fontSizeAttributeName, customFontSizeAttributeName) {
return (fontSizeValue) => {
const fontSizeObject = this.props.fontSizes?.find(
({ size: size4 }) => size4 === Number(fontSizeValue)
);
this.props.setAttributes({
[fontSizeAttributeName]: fontSizeObject && fontSizeObject.slug ? fontSizeObject.slug : void 0,
[customFontSizeAttributeName]: fontSizeObject && fontSizeObject.slug ? void 0 : fontSizeValue
});
};
}
static getDerivedStateFromProps({ attributes, fontSizes }, previousState) {
const didAttributesChange = (customFontSizeAttributeName, fontSizeAttributeName) => {
if (previousState[fontSizeAttributeName]) {
if (attributes[fontSizeAttributeName]) {
return attributes[fontSizeAttributeName] !== previousState[fontSizeAttributeName].slug;
}
return previousState[fontSizeAttributeName].size !== attributes[customFontSizeAttributeName];
}
return true;
};
if (!Object.values(fontSizeAttributeNames).some(
didAttributesChange
)) {
return null;
}
const newState = Object.entries(
fontSizeAttributeNames
).filter(
([key, value]) => didAttributesChange(value, key)
).reduce(
(newStateAccumulator, [
fontSizeAttributeName,
customFontSizeAttributeName
]) => {
const fontSizeAttributeValue = attributes[fontSizeAttributeName];
const fontSizeObject = getFontSize(
fontSizes,
fontSizeAttributeValue,
attributes[customFontSizeAttributeName]
);
newStateAccumulator[fontSizeAttributeName] = {
...fontSizeObject,
class: getFontSizeClass(
fontSizeAttributeValue
)
};
return newStateAccumulator;
},
{}
);
return {
...previousState,
...newState
};
}
render() {
return /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(
WrappedComponent,
{
...{
...this.props,
fontSizes: void 0,
...this.state,
...this.setters
}
}
);
}
};
}
]),
"withFontSizes"
);
};
// packages/block-editor/build-module/components/alignment-control/ui.mjs
var import_i18n8 = __toESM(require_i18n(), 1);
var import_components8 = __toESM(require_components(), 1);
var import_jsx_runtime125 = __toESM(require_jsx_runtime(), 1);
var DEFAULT_ALIGNMENT_CONTROLS = [
{
icon: align_left_default,
title: (0, import_i18n8.__)("Align text left"),
align: "left"
},
{
icon: align_center_default,
title: (0, import_i18n8.__)("Align text center"),
align: "center"
},
{
icon: align_right_default,
title: (0, import_i18n8.__)("Align text right"),
align: "right"
}
];
var POPOVER_PROPS = {
placement: "bottom-start"
};
function AlignmentUI({
value,
onChange,
alignmentControls = DEFAULT_ALIGNMENT_CONTROLS,
label = (0, import_i18n8.__)("Align text"),
description = (0, import_i18n8.__)("Change text alignment"),
isCollapsed: isCollapsed3 = true,
isToolbar
}) {
function applyOrUnset(align) {
return () => onChange(value === align ? void 0 : align);
}
const activeAlignment = alignmentControls.find(
(control) => control.align === value
);
function setIcon() {
if (activeAlignment) {
return activeAlignment.icon;
}
return (0, import_i18n8.isRTL)() ? align_right_default : align_left_default;
}
const UIComponent = isToolbar ? import_components8.ToolbarGroup : import_components8.ToolbarDropdownMenu;
const extraProps = isToolbar ? { isCollapsed: isCollapsed3 } : {
toggleProps: {
description
},
popoverProps: POPOVER_PROPS
};
return /* @__PURE__ */ (0, import_jsx_runtime125.jsx)(
UIComponent,
{
icon: setIcon(),
label,
controls: alignmentControls.map((control) => {
const { align } = control;
const isActive = value === align;
return {
...control,
isActive,
role: isCollapsed3 ? "menuitemradio" : void 0,
onClick: applyOrUnset(align)
};
}),
...extraProps
}
);
}
var ui_default = AlignmentUI;
// packages/block-editor/build-module/components/alignment-control/index.mjs
var import_jsx_runtime126 = __toESM(require_jsx_runtime(), 1);
var AlignmentControl = (props) => {
return /* @__PURE__ */ (0, import_jsx_runtime126.jsx)(ui_default, { ...props, isToolbar: false });
};
var AlignmentToolbar = (props) => {
return /* @__PURE__ */ (0, import_jsx_runtime126.jsx)(ui_default, { ...props, isToolbar: true });
};
// packages/block-editor/build-module/components/autocomplete/index.mjs
var import_hooks3 = __toESM(require_hooks(), 1);
var import_components10 = __toESM(require_components(), 1);
var import_element13 = __toESM(require_element(), 1);
var import_blocks13 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/autocompleters/block.mjs
var import_data11 = __toESM(require_data(), 1);
var import_blocks12 = __toESM(require_blocks(), 1);
var import_element12 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/inserter/search-items.mjs
var import_remove_accents = __toESM(require_remove_accents(), 1);
// node_modules/tslib/tslib.es6.mjs
var extendStatics = function(d2, b2) {
extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d3, b3) {
d3.__proto__ = b3;
} || function(d3, b3) {
for (var p2 in b3) if (Object.prototype.hasOwnProperty.call(b3, p2)) d3[p2] = b3[p2];
};
return extendStatics(d2, b2);
};
function __extends(d2, b2) {
if (typeof b2 !== "function" && b2 !== null)
throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null");
extendStatics(d2, b2);
function __231() {
this.constructor = d2;
}
d2.prototype = b2 === null ? Object.create(b2) : (__231.prototype = b2.prototype, new __231());
}
var __assign = function() {
__assign = Object.assign || function __assign2(t3) {
for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
s2 = arguments[i2];
for (var p2 in s2) if (Object.prototype.hasOwnProperty.call(s2, p2)) t3[p2] = s2[p2];
}
return t3;
};
return __assign.apply(this, arguments);
};
// node_modules/lower-case/dist.es2015/index.js
function lowerCase(str) {
return str.toLowerCase();
}
// node_modules/no-case/dist.es2015/index.js
var DEFAULT_SPLIT_REGEXP = [/([a-z0-9])([A-Z])/g, /([A-Z])([A-Z][a-z])/g];
var DEFAULT_STRIP_REGEXP = /[^A-Z0-9]+/gi;
function noCase(input, options) {
if (options === void 0) {
options = {};
}
var _a = options.splitRegexp, splitRegexp2 = _a === void 0 ? DEFAULT_SPLIT_REGEXP : _a, _b = options.stripRegexp, stripRegexp2 = _b === void 0 ? DEFAULT_STRIP_REGEXP : _b, _c = options.transform, transform = _c === void 0 ? lowerCase : _c, _d = options.delimiter, delimiter = _d === void 0 ? " " : _d;
var result = replace(replace(input, splitRegexp2, "$1\0$2"), stripRegexp2, "\0");
var start2 = 0;
var end = result.length;
while (result.charAt(start2) === "\0")
start2++;
while (result.charAt(end - 1) === "\0")
end--;
return result.slice(start2, end).split("\0").map(transform).join(delimiter);
}
function replace(input, re, value) {
if (re instanceof RegExp)
return input.replace(re, value);
return re.reduce(function(input2, re2) {
return input2.replace(re2, value);
}, input);
}
// packages/block-editor/build-module/components/inserter/search-items.mjs
var defaultGetName = (item) => item.name || "";
var defaultGetTitle = (item) => item.title;
var defaultGetDescription = (item) => item.description || "";
var defaultGetKeywords = (item) => item.keywords || [];
var defaultGetCategory = (item) => item.category;
var defaultGetCollection = () => null;
var splitRegexp = [
/([\p{Ll}\p{Lo}\p{N}])([\p{Lu}\p{Lt}])/gu,
// One lowercase or digit, followed by one uppercase.
/([\p{Lu}\p{Lt}])([\p{Lu}\p{Lt}][\p{Ll}\p{Lo}])/gu
// One uppercase followed by one uppercase and one lowercase.
];
var stripRegexp = new RegExp("(\\p{C}|\\p{P}|\\p{S})+", "giu");
var extractedWords = /* @__PURE__ */ new Map();
var normalizedStrings = /* @__PURE__ */ new Map();
function extractWords(input = "") {
if (extractedWords.has(input)) {
return extractedWords.get(input);
}
const result = noCase(input, {
splitRegexp,
stripRegexp
}).split(" ").filter(Boolean);
extractedWords.set(input, result);
return result;
}
function normalizeString(input = "") {
if (normalizedStrings.has(input)) {
return normalizedStrings.get(input);
}
let result = (0, import_remove_accents.default)(input);
result = result.replace(/^\//, "");
result = result.toLowerCase();
normalizedStrings.set(input, result);
return result;
}
var getNormalizedSearchTerms = (input = "") => {
return extractWords(normalizeString(input));
};
var removeMatchingTerms = (unmatchedTerms, unprocessedTerms) => {
return unmatchedTerms.filter(
(term) => !getNormalizedSearchTerms(unprocessedTerms).some(
(unprocessedTerm) => unprocessedTerm.includes(term)
)
);
};
var searchBlockItems = (items, categories, collections, searchInput) => {
const normalizedSearchTerms = getNormalizedSearchTerms(searchInput);
if (normalizedSearchTerms.length === 0) {
return items;
}
const config2 = {
getCategory: (item) => categories.find(({ slug }) => slug === item.category)?.title,
getCollection: (item) => collections[item.name.split("/")[0]]?.title
};
return searchItems(items, searchInput, config2);
};
var searchItems = (items = [], searchInput = "", config2 = {}) => {
const normalizedSearchTerms = getNormalizedSearchTerms(searchInput);
if (normalizedSearchTerms.length === 0) {
return items;
}
const rankedItems = items.map((item) => {
return [item, getItemSearchRank(item, searchInput, config2)];
}).filter(([, rank]) => rank > 0);
rankedItems.sort(([, rank1], [, rank2]) => rank2 - rank1);
return rankedItems.map(([item]) => item);
};
function getItemSearchRank(item, searchTerm, config2 = {}) {
const {
getName = defaultGetName,
getTitle = defaultGetTitle,
getDescription = defaultGetDescription,
getKeywords = defaultGetKeywords,
getCategory = defaultGetCategory,
getCollection = defaultGetCollection
} = config2;
const name = getName(item);
const title = getTitle(item);
const description = getDescription(item);
const keywords = getKeywords(item);
const category = getCategory(item);
const collection = getCollection(item);
const normalizedSearchInput = normalizeString(searchTerm);
const normalizedTitle = normalizeString(title);
let rank = 0;
if (normalizedSearchInput === normalizedTitle) {
rank += 30;
} else if (normalizedTitle.startsWith(normalizedSearchInput)) {
rank += 20;
} else {
const terms = [
name,
title,
description,
...keywords,
category,
collection
].join(" ");
const normalizedSearchTerms = extractWords(normalizedSearchInput);
const unmatchedTerms = removeMatchingTerms(
normalizedSearchTerms,
terms
);
if (unmatchedTerms.length === 0) {
rank += 10;
}
}
if (rank !== 0 && name.startsWith("core/")) {
const isCoreBlockVariation = name !== item.id;
rank += isCoreBlockVariation ? 1 : 2;
}
return rank;
}
// packages/block-editor/build-module/components/inserter/hooks/use-block-types-state.mjs
var import_blocks11 = __toESM(require_blocks(), 1);
var import_data10 = __toESM(require_data(), 1);
var import_element10 = __toESM(require_element(), 1);
var import_notices2 = __toESM(require_notices(), 1);
var import_i18n9 = __toESM(require_i18n(), 1);
var useBlockTypesState = (rootClientId, onInsert, isQuick) => {
const options = (0, import_element10.useMemo)(
() => ({ [isFiltered]: !!isQuick }),
[isQuick]
);
const [items] = (0, import_data10.useSelect)(
(select3) => [
select3(store).getInserterItems(
rootClientId,
options
)
],
[rootClientId, options]
);
const { getClosestAllowedInsertionPoint: getClosestAllowedInsertionPoint2 } = unlock(
(0, import_data10.useSelect)(store)
);
const { createErrorNotice } = (0, import_data10.useDispatch)(import_notices2.store);
const [categories, collections] = (0, import_data10.useSelect)((select3) => {
const { getCategories, getCollections } = select3(import_blocks11.store);
return [getCategories(), getCollections()];
}, []);
const onSelectItem = (0, import_element10.useCallback)(
({
name,
initialAttributes,
innerBlocks,
innerContent,
syncStatus,
content
}, shouldFocusBlock) => {
const destinationClientId = getClosestAllowedInsertionPoint2(
name,
rootClientId
);
if (destinationClientId === null) {
const title = (0, import_blocks11.getBlockType)(name)?.title ?? name;
createErrorNotice(
(0, import_i18n9.sprintf)(
/* translators: %s: block pattern title. */
(0, import_i18n9.__)(`Block "%s" can't be inserted.`),
title
),
{
type: "snackbar",
id: "inserter-notice"
}
);
return;
}
const insertedBlock = syncStatus === "unsynced" ? (0, import_blocks11.parse)(content, {
__unstableSkipMigrationLogs: true
}) : (0, import_blocks11.createBlock)(
name,
initialAttributes,
(0, import_blocks11.createBlocksFromInnerBlocksTemplate)(innerBlocks),
innerContent
);
onInsert(
insertedBlock,
void 0,
shouldFocusBlock,
destinationClientId
);
},
[
getClosestAllowedInsertionPoint2,
rootClientId,
onInsert,
createErrorNotice
]
);
return [items, categories, collections, onSelectItem];
};
var use_block_types_state_default = useBlockTypesState;
// packages/block-editor/build-module/components/block-icon/index.mjs
var import_components9 = __toESM(require_components(), 1);
var import_element11 = __toESM(require_element(), 1);
var import_jsx_runtime127 = __toESM(require_jsx_runtime(), 1);
function BlockIcon({ icon, showColors = false, className, context }) {
if (icon?.src === "block-default") {
icon = {
src: block_default_default
};
}
const renderedIcon = /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(
import_components9.Icon,
{
icon: icon && icon.src ? icon.src : icon,
context
}
);
const style = showColors ? {
backgroundColor: icon && icon.background,
color: icon && icon.foreground
} : {};
return /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(
"span",
{
style,
className: clsx_default("block-editor-block-icon", className, {
"has-colors": showColors
}),
children: renderedIcon
}
);
}
var block_icon_default = (0, import_element11.memo)(BlockIcon);
// packages/block-editor/build-module/utils/order-inserter-block-items.mjs
var orderInserterBlockItems = (items, priority2) => {
if (!priority2) {
return items;
}
items.sort(({ id: aName }, { id: bName }) => {
let aIndex = priority2.indexOf(aName);
let bIndex = priority2.indexOf(bName);
if (aIndex < 0) {
aIndex = priority2.length;
}
if (bIndex < 0) {
bIndex = priority2.length;
}
return aIndex - bIndex;
});
return items;
};
// packages/block-editor/build-module/autocompleters/block.mjs
var import_jsx_runtime128 = __toESM(require_jsx_runtime(), 1);
var noop = () => {
};
var SHOWN_BLOCK_TYPES = 9;
function createBlockCompleter() {
return {
name: "blocks",
className: "block-editor-autocompleters__block",
triggerPrefix: "/",
useItems(filterValue) {
const { rootClientId, selectedBlockId, prioritizedBlocks } = (0, import_data11.useSelect)((select3) => {
const {
getSelectedBlockClientId: getSelectedBlockClientId2,
getBlock: getBlock2,
getBlockListSettings: getBlockListSettings2,
getBlockRootClientId: getBlockRootClientId2
} = select3(store);
const { getActiveBlockVariation } = select3(import_blocks12.store);
const selectedBlockClientId = getSelectedBlockClientId2();
const { name: blockName, attributes } = getBlock2(
selectedBlockClientId
);
const activeBlockVariation = getActiveBlockVariation(
blockName,
attributes
);
const _rootClientId = getBlockRootClientId2(
selectedBlockClientId
);
return {
selectedBlockId: activeBlockVariation ? `${blockName}/${activeBlockVariation.name}` : blockName,
rootClientId: _rootClientId,
prioritizedBlocks: getBlockListSettings2(_rootClientId)?.prioritizedInserterBlocks
};
}, []);
const [items, categories, collections] = use_block_types_state_default(
rootClientId,
noop,
true
);
const filteredItems = (0, import_element12.useMemo)(() => {
const initialFilteredItems = !!filterValue.trim() ? searchBlockItems(
items,
categories,
collections,
filterValue
) : orderInserterBlockItems(
orderBy(items, "frecency", "desc"),
prioritizedBlocks
);
return initialFilteredItems.filter((item) => item.id !== selectedBlockId).slice(0, SHOWN_BLOCK_TYPES);
}, [
filterValue,
selectedBlockId,
items,
categories,
collections,
prioritizedBlocks
]);
const options = (0, import_element12.useMemo)(
() => filteredItems.map((blockItem) => {
const { title, icon, isDisabled } = blockItem;
return {
key: `block-${blockItem.id}`,
value: blockItem,
label: /* @__PURE__ */ (0, import_jsx_runtime128.jsxs)(import_jsx_runtime128.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime128.jsx)(
block_icon_default,
{
icon,
showColors: true
},
"icon"
),
title
] }),
isDisabled
};
}),
[filteredItems]
);
return [options];
},
allowContext(before, after) {
return !(/\S/.test(before) || /\S/.test(after));
},
getOptionCompletion(inserterItem) {
const {
name,
initialAttributes,
innerBlocks,
innerContent,
syncStatus,
blocks: blocks2
} = inserterItem;
return {
action: "replace",
value: syncStatus === "unsynced" ? (blocks2 ?? []).map(
(block) => (0, import_blocks12.cloneBlock)(block)
) : (0, import_blocks12.createBlock)(
name,
initialAttributes,
(0, import_blocks12.createBlocksFromInnerBlocksTemplate)(
innerBlocks
),
innerContent
)
};
}
};
}
var block_default = createBlockCompleter();
// packages/block-editor/build-module/components/autocomplete/index.mjs
var import_jsx_runtime129 = __toESM(require_jsx_runtime(), 1);
var EMPTY_ARRAY3 = [];
function useCompleters({ completers = EMPTY_ARRAY3 }) {
const { name } = useBlockEditContext();
return (0, import_element13.useMemo)(() => {
let filteredCompleters = [...completers];
if (name === (0, import_blocks13.getDefaultBlockName)() || (0, import_blocks13.getBlockSupport)(name, "__experimentalSlashInserter", false)) {
filteredCompleters = [...filteredCompleters, block_default];
}
if ((0, import_hooks3.hasFilter)("editor.Autocomplete.completers")) {
if (filteredCompleters === completers) {
filteredCompleters = filteredCompleters.map(
(completer) => ({ ...completer })
);
}
filteredCompleters = (0, import_hooks3.applyFilters)(
"editor.Autocomplete.completers",
filteredCompleters,
name
);
}
return filteredCompleters;
}, [completers, name]);
}
function useBlockEditorAutocompleteProps(props) {
return (0, import_components10.__unstableUseAutocompleteProps)({
...props,
completers: useCompleters(props)
});
}
function BlockEditorAutocomplete(props) {
return /* @__PURE__ */ (0, import_jsx_runtime129.jsx)(import_components10.Autocomplete, { ...props, completers: useCompleters(props) });
}
var autocomplete_default = BlockEditorAutocomplete;
// packages/block-editor/build-module/components/block-alignment-control/ui.mjs
var import_i18n17 = __toESM(require_i18n(), 1);
var import_components16 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/block-alignment-control/use-available-alignments.mjs
var import_data12 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/block-list/layout.mjs
var import_element15 = __toESM(require_element(), 1);
// packages/block-editor/build-module/layouts/flex.mjs
var import_i18n12 = __toESM(require_i18n(), 1);
var import_components11 = __toESM(require_components(), 1);
// packages/block-editor/build-module/layouts/utils.mjs
var import_i18n10 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/layouts/definitions.mjs
var LAYOUT_DEFINITIONS2 = {
default: {
name: "default",
slug: "flow",
className: "is-layout-flow",
baseStyles: [
{
selector: " > .alignleft",
rules: {
float: "left",
"margin-inline-start": "0",
"margin-inline-end": "2em"
}
},
{
selector: " > .alignright",
rules: {
float: "right",
"margin-inline-start": "2em",
"margin-inline-end": "0"
}
},
{
selector: " > .aligncenter",
rules: {
"margin-left": "auto !important",
"margin-right": "auto !important"
}
}
],
spacingStyles: [
{
selector: " > :first-child",
rules: {
"margin-block-start": "0"
}
},
{
selector: " > :last-child",
rules: {
"margin-block-end": "0"
}
},
{
selector: " > *",
rules: {
"margin-block-start": null,
"margin-block-end": "0"
}
}
]
},
constrained: {
name: "constrained",
slug: "constrained",
className: "is-layout-constrained",
baseStyles: [
{
selector: " > .alignleft",
rules: {
float: "left",
"margin-inline-start": "0",
"margin-inline-end": "2em"
}
},
{
selector: " > .alignright",
rules: {
float: "right",
"margin-inline-start": "2em",
"margin-inline-end": "0"
}
},
{
selector: " > .aligncenter",
rules: {
"margin-left": "auto !important",
"margin-right": "auto !important"
}
},
{
selector: " > :where(:not(.alignleft):not(.alignright):not(.alignfull))",
rules: {
"max-width": "var(--wp--style--global--content-size)",
"margin-left": "auto !important",
"margin-right": "auto !important"
}
},
{
selector: " > .alignwide",
rules: {
"max-width": "var(--wp--style--global--wide-size)"
}
}
],
spacingStyles: [
{
selector: " > :first-child",
rules: {
"margin-block-start": "0"
}
},
{
selector: " > :last-child",
rules: {
"margin-block-end": "0"
}
},
{
selector: " > *",
rules: {
"margin-block-start": null,
"margin-block-end": "0"
}
}
]
},
flex: {
name: "flex",
slug: "flex",
className: "is-layout-flex",
displayMode: "flex",
baseStyles: [
{
selector: "",
rules: {
"flex-wrap": "wrap",
"align-items": "center"
}
},
{
selector: " > :is(*, div)",
// :is(*, div) instead of just * increases the specificity by 001.
rules: {
margin: "0"
}
}
],
spacingStyles: [
{
selector: "",
rules: {
gap: null
}
}
]
},
grid: {
name: "grid",
slug: "grid",
className: "is-layout-grid",
displayMode: "grid",
baseStyles: [
{
selector: " > :is(*, div)",
// :is(*, div) instead of just * increases the specificity by 001.
rules: {
margin: "0"
}
}
],
spacingStyles: [
{
selector: "",
rules: {
gap: null
}
}
]
}
};
// packages/block-editor/build-module/layouts/utils.mjs
function appendSelectors(selectors4, append = "") {
return selectors4.split(",").map(
(subselector) => `${subselector}${append ? ` ${append}` : ""}`
).join(",");
}
function getBlockGapCSS(selector3, layoutDefinitions = LAYOUT_DEFINITIONS2, layoutType, blockGapValue) {
let output = "";
if (layoutDefinitions?.[layoutType]?.spacingStyles?.length && blockGapValue) {
layoutDefinitions[layoutType].spacingStyles.forEach((gapStyle) => {
output += `${appendSelectors(
selector3,
gapStyle.selector.trim()
)} { `;
output += Object.entries(gapStyle.rules).map(
([cssProperty, value]) => `${cssProperty}: ${value ? value : blockGapValue}`
).join("; ");
output += "; }";
});
}
return output;
}
function getAlignmentsInfo(layout) {
const { contentSize, wideSize, type = "default" } = layout;
const alignmentInfo = {};
const sizeRegex = /^(?!0)\d+(px|em|rem|vw|vh|%|svw|lvw|dvw|svh|lvh|dvh|vi|svi|lvi|dvi|vb|svb|lvb|dvb|vmin|svmin|lvmin|dvmin|vmax|svmax|lvmax|dvmax)?$/i;
if (sizeRegex.test(contentSize) && type === "constrained") {
alignmentInfo.none = (0, import_i18n10.sprintf)((0, import_i18n10.__)("Max %s wide"), contentSize);
}
if (sizeRegex.test(wideSize)) {
alignmentInfo.wide = (0, import_i18n10.sprintf)((0, import_i18n10.__)("Max %s wide"), wideSize);
}
return alignmentInfo;
}
// packages/block-editor/build-module/components/spacing-sizes-control/utils.mjs
var import_i18n11 = __toESM(require_i18n(), 1);
var RANGE_CONTROL_MAX_SIZE = 8;
var ALL_SIDES = ["top", "bottom", "left", "right"];
var DEFAULT_VALUES = {
top: void 0,
right: void 0,
bottom: void 0,
left: void 0
};
var ICONS = {
custom: sides_all_default,
axial: sides_all_default,
horizontal: sides_horizontal_default,
vertical: sides_vertical_default,
top: sides_top_default,
right: sides_right_default,
bottom: sides_bottom_default,
left: sides_left_default
};
var LABELS = {
default: (0, import_i18n11.__)("Spacing control"),
top: (0, import_i18n11.__)("Top"),
bottom: (0, import_i18n11.__)("Bottom"),
left: (0, import_i18n11.__)("Left"),
right: (0, import_i18n11.__)("Right"),
mixed: (0, import_i18n11.__)("Mixed"),
vertical: (0, import_i18n11.__)("Vertical"),
horizontal: (0, import_i18n11.__)("Horizontal"),
axial: (0, import_i18n11.__)("Horizontal & vertical"),
custom: (0, import_i18n11.__)("Custom")
};
var VIEWS = {
axial: "axial",
top: "top",
right: "right",
bottom: "bottom",
left: "left",
custom: "custom"
};
function isValueSpacingPreset(value) {
if (!value?.includes) {
return false;
}
return value === "0" || value.includes("var:preset|spacing|");
}
function getCustomValueFromPreset(value, spacingSizes) {
if (!isValueSpacingPreset(value)) {
return value;
}
const slug = getSpacingPresetSlug(value);
const spacingSize = spacingSizes.find(
(size4) => String(size4.slug) === slug
);
return spacingSize?.size;
}
function getPresetValueFromCustomValue(value, spacingSizes) {
if (!value || isValueSpacingPreset(value) || value === "0") {
return value;
}
const spacingMatch = spacingSizes.find(
(size4) => String(size4.size) === String(value)
);
if (spacingMatch?.slug) {
return `var:preset|spacing|${spacingMatch.slug}`;
}
return value;
}
function getSpacingPresetCssVar2(value) {
if (!value) {
return;
}
const slug = value.match(/var:preset\|spacing\|(.+)/);
if (!slug) {
return value;
}
return `var(--wp--preset--spacing--${slug[1]})`;
}
function getSpacingPresetSlug(value) {
if (!value) {
return;
}
if (value === "0" || value === "default") {
return value;
}
const slug = value.match(/var:preset\|spacing\|(.+)/);
return slug ? slug[1] : void 0;
}
function hasAxisSupport(sides2, axis) {
if (!sides2 || !sides2.length) {
return false;
}
const hasHorizontalSupport = sides2.includes("horizontal") || sides2.includes("left") && sides2.includes("right");
const hasVerticalSupport = sides2.includes("vertical") || sides2.includes("top") && sides2.includes("bottom");
if (axis === "horizontal") {
return hasHorizontalSupport;
}
if (axis === "vertical") {
return hasVerticalSupport;
}
return hasHorizontalSupport || hasVerticalSupport;
}
function hasBalancedSidesSupport(sides2 = []) {
const counts = { top: 0, right: 0, bottom: 0, left: 0 };
sides2.forEach((side) => counts[side] += 1);
return (counts.top + counts.bottom) % 2 === 0 && (counts.left + counts.right) % 2 === 0;
}
function getInitialView(values = {}, sides2) {
const { top, right, bottom, left } = values;
const sideValues = [top, right, bottom, left].filter(Boolean);
const hasMatchingAxialValues = top === bottom && left === right && (!!top || !!left);
const hasNoValuesAndBalancedSides = !sideValues.length && hasBalancedSidesSupport(sides2);
const hasOnlyAxialSides = sides2?.includes("horizontal") && sides2?.includes("vertical") && sides2?.length === 2;
if (hasAxisSupport(sides2) && (hasMatchingAxialValues || hasNoValuesAndBalancedSides)) {
return VIEWS.axial;
}
if (hasOnlyAxialSides && sideValues.length === 1) {
let side;
Object.entries(values).some(([key, value]) => {
side = key;
return value !== void 0;
});
return side;
}
if (sides2?.length === 1 && !sideValues.length) {
return sides2[0];
}
return VIEWS.custom;
}
// packages/block-editor/build-module/hooks/gap.mjs
function getGapBoxControlValueFromStyle2(blockGapValue) {
if (!blockGapValue) {
return null;
}
const isValueString = typeof blockGapValue === "string";
return {
top: isValueString ? blockGapValue : blockGapValue?.top,
left: isValueString ? blockGapValue : blockGapValue?.left
};
}
function getGapCSSValue2(blockGapValue, defaultValue = "0") {
const blockGapBoxControlValue = getGapBoxControlValueFromStyle2(blockGapValue);
if (!blockGapBoxControlValue) {
return null;
}
const row = getSpacingPresetCssVar2(blockGapBoxControlValue?.top) || defaultValue;
const column = getSpacingPresetCssVar2(blockGapBoxControlValue?.left) || defaultValue;
return row === column ? row : `${row} ${column}`;
}
// packages/block-editor/build-module/layouts/flex.mjs
var import_jsx_runtime130 = __toESM(require_jsx_runtime(), 1);
var justifyContentMap = {
left: "flex-start",
right: "flex-end",
center: "center",
"space-between": "space-between"
};
var alignItemsMap = {
left: "flex-start",
right: "flex-end",
center: "center",
stretch: "stretch"
};
var verticalAlignmentMap = {
top: "flex-start",
center: "center",
bottom: "flex-end",
stretch: "stretch",
"space-between": "space-between"
};
var defaultAlignments = {
horizontal: "center",
vertical: "top"
};
var verticalAlignmentOptions = {
top: {
icon: justify_top_default,
label: (0, import_i18n12._x)("Align top", "Block vertical alignment setting")
},
center: {
icon: justify_center_vertical_default,
label: (0, import_i18n12._x)("Align middle", "Block vertical alignment setting")
},
bottom: {
icon: justify_bottom_default,
label: (0, import_i18n12._x)("Align bottom", "Block vertical alignment setting")
},
stretch: {
icon: justify_stretch_vertical_default,
label: (0, import_i18n12._x)("Stretch to fill", "Block vertical alignment setting")
},
"space-between": {
icon: justify_space_between_vertical_default,
label: (0, import_i18n12._x)("Space between", "Block vertical alignment setting")
}
};
var flexWrapOptions = ["wrap", "nowrap"];
var flex_default = {
name: "flex",
label: (0, import_i18n12.__)("Flex"),
inspectorControls: function FlexLayoutInspectorControls({
layout = {},
onChange,
layoutBlockSupport = {},
resetLayout = {},
clientId
}) {
const {
allowOrientation = true,
allowJustification = true,
allowVerticalAlignment = true,
allowWrap = true
} = layoutBlockSupport;
const hasLayoutValue = (key, defaultValue) => (layout?.[key] ?? defaultValue) !== (resetLayout?.[key] ?? defaultValue);
const hasJustificationValue = () => hasLayoutValue("justifyContent", "left");
const hasVerticalAlignmentValue = () => hasLayoutValue(
"verticalAlignment",
getDefaultVerticalAlignment(layout)
);
const hasOrientationValue = () => hasLayoutValue("orientation", "horizontal");
const hasWrapValue = () => hasLayoutValue("flexWrap", "wrap");
const resetJustification = () => onChange(
cleanEmptyObject({
...layout,
justifyContent: resetLayout?.justifyContent
})
);
const resetVerticalAlignment = () => onChange(
cleanEmptyObject({
...layout,
verticalAlignment: getCompatibleVerticalAlignment(
resetLayout?.verticalAlignment,
layout?.orientation
)
})
);
const resetOrientation = () => {
const { verticalAlignment, justifyContent } = layout;
const nextOrientation = resetLayout?.orientation;
const isHorizontal = !nextOrientation || nextOrientation === "horizontal";
onChange(
cleanEmptyObject({
...layout,
orientation: nextOrientation,
verticalAlignment: resetLayout?.verticalAlignment ?? (isHorizontal && verticalAlignment === "space-between" ? "center" : verticalAlignment),
justifyContent: resetLayout?.justifyContent ?? (isHorizontal && justifyContent === "stretch" ? "left" : justifyContent)
})
);
};
const resetWrap = () => onChange(
cleanEmptyObject({
...layout,
flexWrap: resetLayout?.flexWrap
})
);
return /* @__PURE__ */ (0, import_jsx_runtime130.jsxs)(import_jsx_runtime130.Fragment, { children: [
(allowJustification || allowOrientation) && /* @__PURE__ */ (0, import_jsx_runtime130.jsxs)(
import_components11.Flex,
{
align: "flex-start",
className: "block-editor-hooks__flex-layout-controls",
gap: 4,
justify: "flex-start",
children: [
allowJustification && /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
import_components11.__experimentalToolsPanelItem,
{
label: (0, import_i18n12.__)("Justification"),
hasValue: hasJustificationValue,
onDeselect: resetJustification,
isShownByDefault: true,
panelId: clientId,
children: /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
FlexLayoutJustifyContentControl,
{
layout,
onChange
}
)
}
),
allowOrientation && /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
import_components11.__experimentalToolsPanelItem,
{
label: (0, import_i18n12.__)("Orientation"),
hasValue: hasOrientationValue,
onDeselect: resetOrientation,
isShownByDefault: true,
panelId: clientId,
children: /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
OrientationControl,
{
layout,
onChange
}
)
}
)
]
}
),
allowVerticalAlignment && /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
import_components11.__experimentalToolsPanelItem,
{
label: (0, import_i18n12.__)("Alignment"),
hasValue: hasVerticalAlignmentValue,
onDeselect: resetVerticalAlignment,
panelId: clientId,
children: /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
FlexLayoutVerticalAlignmentControl,
{
layout,
onChange
}
)
}
),
allowWrap && /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
import_components11.__experimentalToolsPanelItem,
{
label: (0, import_i18n12.__)("Wrapping"),
hasValue: hasWrapValue,
onDeselect: resetWrap,
panelId: clientId,
children: /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
FlexWrapControl,
{
layout,
onChange
}
)
}
)
] });
},
toolBarControls: function FlexLayoutToolbarControls({
layout = {},
onChange,
layoutBlockSupport,
controlsGroup = "block"
}) {
const { allowVerticalAlignment = true, allowJustification = true } = layoutBlockSupport;
if (!allowJustification && !allowVerticalAlignment) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime130.jsxs)(
block_controls_default,
{
group: controlsGroup,
__experimentalShareWithChildBlocks: true,
children: [
allowJustification && /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
FlexLayoutJustifyContentControl,
{
layout,
onChange,
isToolbar: true
}
),
allowVerticalAlignment && /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
FlexLayoutVerticalAlignmentControl,
{
layout,
onChange,
isToolbar: true
}
)
]
}
);
},
getLayoutStyle: function getLayoutStyle({
selector: selector3,
layout = {},
viewportOverrides,
style,
blockName,
hasBlockGapSupport,
globalBlockGapValue,
layoutDefinitions = LAYOUT_DEFINITIONS2
}) {
const hasViewportOverrides = viewportOverrides !== void 0;
const effectiveLayout = hasViewportOverrides ? { ...layout, ...viewportOverrides } : layout;
const hasViewportOverride = (key) => Object.hasOwn(viewportOverrides || {}, key);
const { orientation = "horizontal" } = effectiveLayout;
let fallbackGapValue = "0.5em";
if (globalBlockGapValue) {
const gapBox = getGapBoxControlValueFromStyle2(globalBlockGapValue);
fallbackGapValue = getSpacingPresetCssVar2(gapBox?.left) || getSpacingPresetCssVar2(gapBox?.top) || "0.5em";
}
const blockGapValue = style?.spacing?.blockGap && !shouldSkipSerialization(blockName, "spacing", "blockGap") ? getGapCSSValue2(style?.spacing?.blockGap, fallbackGapValue) : void 0;
const hasBlockGapOverride = !hasViewportOverrides || Object.hasOwn(style?.spacing || {}, "blockGap");
const justifyContent = justifyContentMap[effectiveLayout.justifyContent];
const flexWrap = flexWrapOptions.includes(effectiveLayout.flexWrap) ? effectiveLayout.flexWrap : "wrap";
const verticalAlignment = verticalAlignmentMap[effectiveLayout.verticalAlignment];
const alignItems = alignItemsMap[effectiveLayout.justifyContent] || alignItemsMap.left;
let output = "";
const rules = [];
const shouldOutputFlexWrap = !hasViewportOverrides || hasViewportOverride("flexWrap");
const shouldOutputFlexOrientation = !hasViewportOverrides || hasViewportOverride("orientation");
const shouldOutputFlexJustification = !hasViewportOverrides || hasViewportOverride("justifyContent") || hasViewportOverride("orientation");
const shouldOutputFlexAlignment = !hasViewportOverrides || hasViewportOverride("verticalAlignment") || hasViewportOverride("orientation");
if (shouldOutputFlexWrap && flexWrap && flexWrap !== "wrap") {
rules.push(`flex-wrap: ${flexWrap}`);
}
if (orientation === "horizontal") {
if (shouldOutputFlexAlignment && verticalAlignment) {
rules.push(`align-items: ${verticalAlignment}`);
}
if (shouldOutputFlexJustification && justifyContent) {
rules.push(`justify-content: ${justifyContent}`);
}
} else {
if (shouldOutputFlexAlignment && verticalAlignment) {
rules.push(`justify-content: ${verticalAlignment}`);
}
if (shouldOutputFlexOrientation) {
rules.push("flex-direction: column");
}
if (shouldOutputFlexJustification) {
rules.push(`align-items: ${alignItems}`);
}
}
if (rules.length) {
output = `${appendSelectors(selector3)} {
${rules.join("; ")};
}`;
}
if (hasBlockGapSupport && hasBlockGapOverride && blockGapValue) {
output += getBlockGapCSS(
selector3,
layoutDefinitions,
"flex",
blockGapValue
);
}
return output;
},
getOrientation(layout) {
const { orientation = "horizontal" } = layout;
return orientation;
},
getAlignments() {
return [];
}
};
function getDefaultVerticalAlignment({ orientation = "horizontal" } = {}) {
return orientation === "horizontal" ? defaultAlignments.horizontal : defaultAlignments.vertical;
}
function getCompatibleVerticalAlignment(verticalAlignment, orientation) {
if (orientation === "horizontal" && verticalAlignment === "space-between" || orientation === "vertical" && verticalAlignment === "stretch") {
return void 0;
}
return verticalAlignment;
}
function getVerticalAlignmentControls(orientation) {
return orientation === "horizontal" ? ["top", "center", "bottom", "stretch"] : ["top", "center", "bottom", "space-between"];
}
function FlexLayoutVerticalAlignmentControl({
layout,
onChange,
isToolbar = false
}) {
const { orientation = "horizontal" } = layout;
const { verticalAlignment = getDefaultVerticalAlignment(layout) } = layout;
const onVerticalAlignmentChange = (value) => {
onChange({
...layout,
verticalAlignment: value
});
};
const controls = getVerticalAlignmentControls(orientation);
if (isToolbar) {
return /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
BlockVerticalAlignmentControl,
{
onChange: onVerticalAlignmentChange,
value: verticalAlignment,
controls
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
import_components11.__experimentalToggleGroupControl,
{
label: (0, import_i18n12.__)("Alignment"),
onChange: onVerticalAlignmentChange,
value: verticalAlignment,
className: "block-editor-hooks__flex-layout-alignment-controls",
children: controls.map((control) => {
const { icon, label } = verticalAlignmentOptions[control];
return /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
import_components11.__experimentalToggleGroupControlOptionIcon,
{
value: control,
icon,
label
},
control
);
})
}
);
}
var POPOVER_PROPS2 = {
placement: "bottom-start"
};
function FlexLayoutJustifyContentControl({
layout,
onChange,
isToolbar = false
}) {
const { justifyContent = "left", orientation = "horizontal" } = layout;
const onJustificationChange = (value) => {
onChange({
...layout,
justifyContent: value
});
};
const allowedControls = ["left", "center", "right"];
if (orientation === "horizontal") {
allowedControls.push("space-between");
} else {
allowedControls.push("stretch");
}
if (isToolbar) {
return /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
JustifyContentControl,
{
allowedControls,
value: justifyContent,
onChange: onJustificationChange,
popoverProps: POPOVER_PROPS2
}
);
}
const justificationOptions = [
{
value: "left",
icon: justify_left_default,
label: (0, import_i18n12.__)("Justify items left")
},
{
value: "center",
icon: justify_center_default,
label: (0, import_i18n12.__)("Justify items center")
},
{
value: "right",
icon: justify_right_default,
label: (0, import_i18n12.__)("Justify items right")
}
];
if (orientation === "horizontal") {
justificationOptions.push({
value: "space-between",
icon: justify_space_between_default,
label: (0, import_i18n12.__)("Space between items")
});
} else {
justificationOptions.push({
value: "stretch",
icon: justify_stretch_default,
label: (0, import_i18n12.__)("Stretch items")
});
}
return /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
import_components11.__experimentalToggleGroupControl,
{
label: (0, import_i18n12.__)("Justification"),
value: justifyContent,
onChange: onJustificationChange,
className: "block-editor-hooks__flex-layout-justification-controls",
children: justificationOptions.map(({ value, icon, label }) => {
return /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
import_components11.__experimentalToggleGroupControlOptionIcon,
{
value,
icon,
label
},
value
);
})
}
);
}
function FlexWrapControl({ layout, onChange }) {
const { flexWrap = "wrap" } = layout;
return /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
import_components11.ToggleControl,
{
label: (0, import_i18n12.__)("Allow to wrap to multiple lines"),
onChange: (value) => {
onChange({
...layout,
flexWrap: value ? "wrap" : "nowrap"
});
},
checked: flexWrap === "wrap"
}
);
}
function OrientationControl({ layout, onChange }) {
const {
orientation = "horizontal",
verticalAlignment,
justifyContent
} = layout;
return /* @__PURE__ */ (0, import_jsx_runtime130.jsxs)(
import_components11.__experimentalToggleGroupControl,
{
className: "block-editor-hooks__flex-layout-orientation-controls",
label: (0, import_i18n12.__)("Orientation"),
value: orientation,
onChange: (value) => {
let newVerticalAlignment = verticalAlignment;
let newJustification = justifyContent;
if (value === "horizontal") {
if (verticalAlignment === "space-between") {
newVerticalAlignment = "center";
}
if (justifyContent === "stretch") {
newJustification = "left";
}
} else {
if (verticalAlignment === "stretch") {
newVerticalAlignment = "top";
}
if (justifyContent === "space-between") {
newJustification = "left";
}
}
return onChange({
...layout,
orientation: value,
verticalAlignment: newVerticalAlignment,
justifyContent: newJustification
});
},
children: [
/* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
import_components11.__experimentalToggleGroupControlOptionIcon,
{
icon: arrow_right_default,
value: "horizontal",
label: (0, import_i18n12.__)("Horizontal")
}
),
/* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
import_components11.__experimentalToggleGroupControlOptionIcon,
{
icon: arrow_down_default,
value: "vertical",
label: (0, import_i18n12.__)("Vertical")
}
)
]
}
);
}
// packages/block-editor/build-module/layouts/flow.mjs
var import_i18n13 = __toESM(require_i18n(), 1);
var flow_default = {
name: "default",
label: (0, import_i18n13.__)("Flow"),
inspectorControls: function DefaultLayoutInspectorControls() {
return null;
},
toolBarControls: function DefaultLayoutToolbarControls() {
return null;
},
getLayoutStyle: function getLayoutStyle2({
selector: selector3,
style,
blockName,
hasBlockGapSupport,
layoutDefinitions = LAYOUT_DEFINITIONS2
}) {
const blockGapStyleValue = getGapCSSValue2(style?.spacing?.blockGap);
let blockGapValue = "";
if (!shouldSkipSerialization(blockName, "spacing", "blockGap")) {
if (blockGapStyleValue?.top) {
blockGapValue = getGapCSSValue2(blockGapStyleValue?.top);
} else if (typeof blockGapStyleValue === "string") {
blockGapValue = getGapCSSValue2(blockGapStyleValue);
}
}
let output = "";
if (hasBlockGapSupport && blockGapValue) {
output += getBlockGapCSS(
selector3,
layoutDefinitions,
"default",
blockGapValue
);
}
return output;
},
getOrientation() {
return "vertical";
},
getAlignments(layout, isBlockBasedTheme) {
const alignmentInfo = getAlignmentsInfo(layout);
if (layout.alignments !== void 0) {
if (!layout.alignments.includes("none")) {
layout.alignments.unshift("none");
}
return layout.alignments.map((alignment) => ({
name: alignment,
info: alignmentInfo[alignment]
}));
}
const alignments = [
{ name: "left" },
{ name: "center" },
{ name: "right" }
];
if (!isBlockBasedTheme) {
const { contentSize, wideSize } = layout;
if (contentSize) {
alignments.unshift({ name: "full" });
}
if (wideSize) {
alignments.unshift({
name: "wide",
info: alignmentInfo.wide
});
}
}
alignments.unshift({ name: "none", info: alignmentInfo.none });
return alignments;
}
};
// packages/block-editor/build-module/layouts/constrained.mjs
var import_components13 = __toESM(require_components(), 1);
var import_i18n14 = __toESM(require_i18n(), 1);
var import_style_engine3 = __toESM(require_style_engine(), 1);
var import_jsx_runtime131 = __toESM(require_jsx_runtime(), 1);
var GLOBAL_CONTENT_SIZE = "var(--wp--style--global--content-size, none)";
var GLOBAL_WIDE_SIZE = "var(--wp--style--global--wide-size, none)";
var constrained_default = {
name: "constrained",
label: (0, import_i18n14.__)("Constrained"),
inspectorControls: function DefaultLayoutInspectorControls2({
layout,
onChange,
layoutBlockSupport = {},
resetLayout = {},
clientId
}) {
const { wideSize, contentSize, justifyContent = "center" } = layout;
const {
allowJustification = true,
allowCustomContentAndWideSize = true
} = layoutBlockSupport;
const onJustificationChange = (value) => {
onChange({
...layout,
justifyContent: value
});
};
const justificationOptions = [
{
value: "left",
icon: justify_left_default,
label: (0, import_i18n14.__)("Justify items left")
},
{
value: "center",
icon: justify_center_default,
label: (0, import_i18n14.__)("Justify items center")
},
{
value: "right",
icon: justify_right_default,
label: (0, import_i18n14.__)("Justify items right")
}
];
const [availableUnits] = useSettings("spacing.units");
const units2 = (0, import_components13.__experimentalUseCustomUnits)({
availableUnits: availableUnits || ["%", "px", "em", "rem", "vw"]
});
const hasLayoutValue = (key, defaultValue) => (layout?.[key] ?? defaultValue) !== (resetLayout?.[key] ?? defaultValue);
const resetContentSize = () => onChange(
cleanEmptyObject({
...layout,
contentSize: resetLayout?.contentSize
})
);
const resetWideSize = () => onChange(
cleanEmptyObject({
...layout,
wideSize: resetLayout?.wideSize
})
);
const resetJustification = () => onChange(
cleanEmptyObject({
...layout,
justifyContent: resetLayout?.justifyContent
})
);
const hasContentSizeValue = () => hasLayoutValue("contentSize");
const hasWideSizeValue = () => hasLayoutValue("wideSize");
const hasJustificationValue = () => hasLayoutValue("justifyContent", "center");
return /* @__PURE__ */ (0, import_jsx_runtime131.jsxs)(import_jsx_runtime131.Fragment, { children: [
allowCustomContentAndWideSize && /* @__PURE__ */ (0, import_jsx_runtime131.jsxs)(import_jsx_runtime131.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
import_components13.__experimentalToolsPanelItem,
{
label: (0, import_i18n14.__)("Content width"),
hasValue: hasContentSizeValue,
onDeselect: resetContentSize,
panelId: clientId,
children: /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
import_components13.__experimentalUnitControl,
{
label: (0, import_i18n14.__)("Content width"),
labelPosition: "top",
value: contentSize === null ? "" : contentSize || wideSize || "",
onChange: (nextWidth) => {
nextWidth = 0 > parseFloat(nextWidth) ? "0" : nextWidth;
onChange({
...layout,
contentSize: nextWidth !== "" ? nextWidth : void 0
});
},
units: units2,
prefix: /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(import_components13.__experimentalInputControlPrefixWrapper, { variant: "icon", children: /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(icon_default, { icon: align_none_default }) })
}
)
}
),
/* @__PURE__ */ (0, import_jsx_runtime131.jsxs)(
import_components13.__experimentalToolsPanelItem,
{
label: (0, import_i18n14.__)("Wide width"),
hasValue: hasWideSizeValue,
onDeselect: resetWideSize,
panelId: clientId,
children: [
/* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
import_components13.__experimentalUnitControl,
{
label: (0, import_i18n14.__)("Wide width"),
labelPosition: "top",
value: wideSize === null ? "" : wideSize || contentSize || "",
onChange: (nextWidth) => {
nextWidth = 0 > parseFloat(nextWidth) ? "0" : nextWidth;
onChange({
...layout,
wideSize: nextWidth !== "" ? nextWidth : void 0
});
},
units: units2,
prefix: /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(import_components13.__experimentalInputControlPrefixWrapper, { variant: "icon", children: /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(icon_default, { icon: stretch_wide_default }) })
}
),
/* @__PURE__ */ (0, import_jsx_runtime131.jsx)("p", { className: "block-editor-hooks__layout-constrained-helptext", children: (0, import_i18n14.__)(
"Customize the width for all elements that are assigned to the center or wide columns."
) })
]
}
)
] }),
allowJustification && /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
import_components13.__experimentalToolsPanelItem,
{
label: (0, import_i18n14.__)("Justification"),
hasValue: hasJustificationValue,
onDeselect: resetJustification,
panelId: clientId,
children: /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
import_components13.__experimentalToggleGroupControl,
{
label: (0, import_i18n14.__)("Justification"),
value: justifyContent,
onChange: onJustificationChange,
children: justificationOptions.map(
({ value, icon, label }) => {
return /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
import_components13.__experimentalToggleGroupControlOptionIcon,
{
value,
icon,
label
},
value
);
}
)
}
)
}
)
] });
},
toolBarControls: function DefaultLayoutToolbarControls2({
layout = {},
onChange,
layoutBlockSupport,
controlsGroup = "block"
}) {
const { allowJustification = true } = layoutBlockSupport;
if (!allowJustification) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
block_controls_default,
{
group: controlsGroup,
__experimentalShareWithChildBlocks: true,
children: /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
DefaultLayoutJustifyContentControl,
{
layout,
onChange
}
)
}
);
},
getLayoutStyle: function getLayoutStyle3({
selector: selector3,
layout = {},
viewportOverrides,
style,
blockName,
hasBlockGapSupport,
layoutDefinitions = LAYOUT_DEFINITIONS2
}) {
const hasViewportOverrides = viewportOverrides !== void 0;
const effectiveLayout = hasViewportOverrides ? { ...layout, ...viewportOverrides } : layout;
const hasViewportOverride = (key) => Object.hasOwn(viewportOverrides || {}, key);
const { contentSize, wideSize, justifyContent } = effectiveLayout;
const blockGapStyleValue = getGapCSSValue2(style?.spacing?.blockGap);
const hasBlockGapOverride = !hasViewportOverrides || Object.hasOwn(style?.spacing || {}, "blockGap");
const hasBlockSpacingOverride = !hasViewportOverrides || Object.hasOwn(style?.spacing || {}, "padding");
let blockGapValue = "";
if (!shouldSkipSerialization(blockName, "spacing", "blockGap")) {
if (blockGapStyleValue?.top) {
blockGapValue = getGapCSSValue2(blockGapStyleValue?.top);
} else if (typeof blockGapStyleValue === "string") {
blockGapValue = getGapCSSValue2(blockGapStyleValue);
}
}
const marginLeft = justifyContent === "left" ? "0 !important" : "auto !important";
const marginRight = justifyContent === "right" ? "0 !important" : "auto !important";
const hasJustificationOverride = hasViewportOverrides && hasViewportOverride("justifyContent");
const hasContentSizeOverride = hasViewportOverrides && hasViewportOverride("contentSize");
const hasWideSizeOverride = hasViewportOverrides && hasViewportOverride("wideSize");
const shouldOutputConstrainedSizes = !hasViewportOverrides || hasContentSizeOverride || hasWideSizeOverride;
const isResettingConstrainedSizes = hasViewportOverrides && (hasContentSizeOverride && !contentSize || hasWideSizeOverride && !wideSize);
const contentMaxWidth = contentSize || (wideSize && !hasContentSizeOverride ? wideSize : GLOBAL_CONTENT_SIZE);
const wideMaxWidth = wideSize || (contentSize && !hasWideSizeOverride ? contentSize : GLOBAL_WIDE_SIZE);
const constrainedSizeDeclarations = [
`max-width: ${contentMaxWidth}`
];
if (!hasViewportOverrides || hasJustificationOverride) {
constrainedSizeDeclarations.push(
`margin-left: ${marginLeft}`,
`margin-right: ${marginRight}`
);
}
let output = shouldOutputConstrainedSizes && (!!contentSize || !!wideSize || isResettingConstrainedSizes) ? `
${appendSelectors(
selector3,
"> :where(:not(.alignleft):not(.alignright):not(.alignfull))"
)} {
${constrainedSizeDeclarations.join("; ")};
}
${appendSelectors(selector3, "> .alignwide")} {
max-width: ${wideMaxWidth};
}
${appendSelectors(selector3, "> .alignfull")} {
max-width: none;
}
` : "";
if (hasJustificationOverride && !shouldOutputConstrainedSizes) {
output += `${appendSelectors(
selector3,
"> :where(:not(.alignleft):not(.alignright):not(.alignfull))"
)}
{ margin-left: ${marginLeft}; margin-right: ${marginRight}; }`;
} else if (!hasViewportOverrides) {
if (justifyContent === "left") {
output += `${appendSelectors(
selector3,
"> :where(:not(.alignleft):not(.alignright):not(.alignfull))"
)}
{ margin-left: ${marginLeft}; }`;
} else if (justifyContent === "right") {
output += `${appendSelectors(
selector3,
"> :where(:not(.alignleft):not(.alignright):not(.alignfull))"
)}
{ margin-right: ${marginRight}; }`;
}
}
if (hasBlockSpacingOverride && style?.spacing?.padding) {
const paddingValues = (0, import_style_engine3.getCSSRules)(style);
paddingValues.forEach((rule) => {
if (rule.key === "paddingRight") {
const paddingRightValue = rule.value === "0" ? "0px" : rule.value;
output += `
${appendSelectors(selector3, "> .alignfull")} {
margin-right: calc(${paddingRightValue} * -1);
}
`;
} else if (rule.key === "paddingLeft") {
const paddingLeftValue = rule.value === "0" ? "0px" : rule.value;
output += `
${appendSelectors(selector3, "> .alignfull")} {
margin-left: calc(${paddingLeftValue} * -1);
}
`;
}
});
}
if (hasBlockGapSupport && hasBlockGapOverride && blockGapValue) {
output += getBlockGapCSS(
selector3,
layoutDefinitions,
"constrained",
blockGapValue
);
}
return output;
},
getOrientation() {
return "vertical";
},
getAlignments(layout) {
const alignmentInfo = getAlignmentsInfo(layout);
if (layout.alignments !== void 0) {
if (!layout.alignments.includes("none")) {
layout.alignments.unshift("none");
}
return layout.alignments.map((alignment) => ({
name: alignment,
info: alignmentInfo[alignment]
}));
}
const { contentSize, wideSize } = layout;
const alignments = [
{ name: "left" },
{ name: "center" },
{ name: "right" }
];
if (contentSize) {
alignments.unshift({ name: "full" });
}
if (wideSize) {
alignments.unshift({ name: "wide", info: alignmentInfo.wide });
}
alignments.unshift({ name: "none", info: alignmentInfo.none });
return alignments;
}
};
var POPOVER_PROPS3 = {
placement: "bottom-start"
};
function DefaultLayoutJustifyContentControl({ layout, onChange }) {
const { justifyContent = "center" } = layout;
const onJustificationChange = (value) => {
onChange({
...layout,
justifyContent: value
});
};
const allowedControls = ["left", "center", "right"];
return /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
JustifyContentControl,
{
allowedControls,
value: justifyContent,
onChange: onJustificationChange,
popoverProps: POPOVER_PROPS3
}
);
}
// packages/block-editor/build-module/layouts/grid.mjs
var import_i18n15 = __toESM(require_i18n(), 1);
var import_components15 = __toESM(require_components(), 1);
var import_element14 = __toESM(require_element(), 1);
var import_jsx_runtime132 = __toESM(require_jsx_runtime(), 1);
var RANGE_CONTROL_MAX_VALUES = {
px: 600,
"%": 100,
vw: 100,
vh: 100,
em: 38,
rem: 38,
svw: 100,
lvw: 100,
dvw: 100,
svh: 100,
lvh: 100,
dvh: 100,
vi: 100,
svi: 100,
lvi: 100,
dvi: 100,
vb: 100,
svb: 100,
lvb: 100,
dvb: 100,
vmin: 100,
svmin: 100,
lvmin: 100,
dvmin: 100,
vmax: 100,
svmax: 100,
lvmax: 100,
dvmax: 100
};
var units = [
{ value: "px", label: "px", default: 0 },
{ value: "rem", label: "rem", default: 0 },
{ value: "em", label: "em", default: 0 }
];
var grid_default2 = {
name: "grid",
label: (0, import_i18n15.__)("Grid"),
inspectorControls: function GridLayoutInspectorControls({
layout = {},
onChange,
layoutBlockSupport = {},
resetLayout = {},
clientId
}) {
const { allowSizingOnChildren = false } = layoutBlockSupport;
const showColumnsControl = true;
const showMinWidthControl = !layout?.isManualPlacement || window.__experimentalEnableGridInteractivity;
const showFillControl = !layout?.isManualPlacement;
const defaultColumnCount = layout.isManualPlacement ? 3 : void 0;
const hasLayoutValue = (key, defaultValue) => (layout?.[key] ?? defaultValue) !== (resetLayout?.[key] ?? defaultValue);
const hasGridTypeValue = () => hasLayoutValue("isManualPlacement", false);
const hasColumnsAndRowsValue = () => hasLayoutValue("columnCount", defaultColumnCount) || hasLayoutValue("rowCount");
const hasMinimumColumnWidthValue = () => hasLayoutValue("minimumColumnWidth");
const hasFillValue = () => hasLayoutValue("autoFit", false);
const resetGridType = () => onChange(
cleanEmptyObject({
...layout,
isManualPlacement: resetLayout?.isManualPlacement,
rowCount: resetLayout?.rowCount,
minimumColumnWidth: resetLayout?.minimumColumnWidth
})
);
const resetColumnsAndRows = () => onChange(
cleanEmptyObject({
...layout,
columnCount: resetLayout?.columnCount ?? defaultColumnCount,
rowCount: resetLayout?.rowCount
})
);
const resetMinimumColumnWidth = () => onChange(
cleanEmptyObject({
...layout,
minimumColumnWidth: resetLayout?.minimumColumnWidth
})
);
const resetFill = () => onChange(
cleanEmptyObject({
...layout,
autoFit: resetLayout?.autoFit
})
);
return /* @__PURE__ */ (0, import_jsx_runtime132.jsxs)(import_jsx_runtime132.Fragment, { children: [
window.__experimentalEnableGridInteractivity && /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(
import_components15.__experimentalToolsPanelItem,
{
label: (0, import_i18n15.__)("Grid item position"),
hasValue: hasGridTypeValue,
onDeselect: resetGridType,
isShownByDefault: true,
panelId: clientId,
children: /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(
GridLayoutTypeControl,
{
layout,
onChange
}
)
}
),
showColumnsControl && /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(
import_components15.__experimentalToolsPanelItem,
{
label: (0, import_i18n15.__)("Columns and rows"),
hasValue: hasColumnsAndRowsValue,
onDeselect: resetColumnsAndRows,
isShownByDefault: true,
panelId: clientId,
children: /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(
GridLayoutColumnsAndRowsControl,
{
layout,
onChange,
allowSizingOnChildren
}
)
}
),
showMinWidthControl && /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(
import_components15.__experimentalToolsPanelItem,
{
label: (0, import_i18n15.__)("Min. column width"),
hasValue: hasMinimumColumnWidthValue,
onDeselect: resetMinimumColumnWidth,
isShownByDefault: true,
panelId: clientId,
children: /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(
GridLayoutMinimumWidthControl,
{
layout,
onChange
}
)
}
),
showFillControl && /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(
import_components15.__experimentalToolsPanelItem,
{
label: (0, import_i18n15.__)("Fill available space"),
hasValue: hasFillValue,
onDeselect: resetFill,
panelId: clientId,
children: /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(
GridLayoutFillControl,
{
layout,
onChange
}
)
}
)
] });
},
toolBarControls: function GridLayoutToolbarControls() {
return null;
},
getLayoutStyle: function getLayoutStyle4({
selector: selector3,
layout = {},
viewportOverrides,
style,
blockName,
hasBlockGapSupport,
globalBlockGapValue,
layoutDefinitions = LAYOUT_DEFINITIONS2
}) {
const hasViewportOverrides = viewportOverrides !== void 0;
const effectiveLayout = hasViewportOverrides ? { ...layout, ...viewportOverrides } : layout;
const hasViewportOverride = (key) => Object.hasOwn(viewportOverrides || {}, key);
const {
minimumColumnWidth = null,
columnCount = null,
rowCount = null,
autoFit = false
} = effectiveLayout;
const autoPlacement4 = autoFit ? "auto-fit" : "auto-fill";
if (true) {
if (minimumColumnWidth && typeof minimumColumnWidth !== "string") {
throw new Error("minimumColumnWidth must be a string");
}
if (columnCount && typeof columnCount !== "number") {
throw new Error("columnCount must be a number");
}
if (rowCount && typeof rowCount !== "number") {
throw new Error("rowCount must be a number");
}
if (autoFit && typeof autoFit !== "boolean") {
throw new Error("autoFit must be a boolean");
}
}
let fallbackGapValue = "1.2rem";
if (globalBlockGapValue) {
const gapBox = getGapBoxControlValueFromStyle2(globalBlockGapValue);
fallbackGapValue = getSpacingPresetCssVar2(gapBox?.left) || getSpacingPresetCssVar2(gapBox?.top) || "1.2rem";
}
const blockGapValue = style?.spacing?.blockGap && !shouldSkipSerialization(blockName, "spacing", "blockGap") ? getGapCSSValue2(style?.spacing?.blockGap, fallbackGapValue) : void 0;
const hasBlockGapOverride = !hasViewportOverrides || Object.hasOwn(style?.spacing || {}, "blockGap");
let output = "";
const rules = [];
const shouldOutputGridColumns = !hasViewportOverrides || hasViewportOverride("minimumColumnWidth") || hasViewportOverride("columnCount") || hasViewportOverride("autoFit") || hasBlockGapOverride && minimumColumnWidth && columnCount > 0;
const shouldOutputGridRows = (!hasViewportOverrides || hasViewportOverride("rowCount")) && columnCount && rowCount;
if (shouldOutputGridColumns && minimumColumnWidth && columnCount > 0) {
let blockGapToUse = blockGapValue || fallbackGapValue;
if (blockGapToUse === "0" || blockGapToUse === 0) {
blockGapToUse = "0px";
}
const maxValue = `max(min( ${minimumColumnWidth}, 100%), ( 100% - (${blockGapToUse}*${columnCount - 1}) ) / ${columnCount})`;
rules.push(
`grid-template-columns: repeat(${autoPlacement4}, minmax(${maxValue}, 1fr))`
);
} else if (shouldOutputGridColumns && columnCount) {
rules.push(
`grid-template-columns: repeat(${columnCount}, minmax(0, 1fr))`
);
} else if (shouldOutputGridColumns) {
rules.push(
`grid-template-columns: repeat(${autoPlacement4}, minmax(min(${minimumColumnWidth || "12rem"}, 100%), 1fr))`
);
}
if (shouldOutputGridColumns) {
const baseHasContainerType = !layout?.columnCount || layout?.columnCount && layout?.minimumColumnWidth;
const needsContainerType = !columnCount || minimumColumnWidth;
if (needsContainerType && (!hasViewportOverrides || !baseHasContainerType)) {
rules.push("container-type: inline-size");
}
}
if (shouldOutputGridRows) {
rules.push(
`grid-template-rows: repeat(${rowCount}, minmax(1rem, auto))`
);
}
if (rules.length) {
output = `${appendSelectors(selector3)} { ${rules.join(
"; "
)}; }`;
}
if (hasBlockGapSupport && hasBlockGapOverride && blockGapValue) {
output += getBlockGapCSS(
selector3,
layoutDefinitions,
"grid",
blockGapValue
);
}
return output;
},
getOrientation() {
return "horizontal";
},
getAlignments() {
return [];
}
};
function GridLayoutMinimumWidthControl({ layout, onChange }) {
const { minimumColumnWidth, columnCount, isManualPlacement } = layout;
const defaultValue = isManualPlacement || columnCount ? null : "12rem";
const value = minimumColumnWidth || defaultValue;
const [quantity, unit = "rem"] = (0, import_components15.__experimentalParseQuantityAndUnitFromRawValue)(value);
const handleSliderChange = (next) => {
onChange({
...layout,
minimumColumnWidth: [next, unit].join("")
});
};
const handleUnitChange = (newUnit) => {
let newValue;
if (["em", "rem"].includes(newUnit) && unit === "px") {
newValue = (quantity / 16).toFixed(2) + newUnit;
} else if (["em", "rem"].includes(unit) && newUnit === "px") {
newValue = Math.round(quantity * 16) + newUnit;
}
onChange({
...layout,
minimumColumnWidth: newValue
});
};
return /* @__PURE__ */ (0, import_jsx_runtime132.jsxs)("fieldset", { className: "block-editor-hooks__grid-layout-minimum-width-control", children: [
/* @__PURE__ */ (0, import_jsx_runtime132.jsx)(import_components15.BaseControl.VisualLabel, { as: "legend", children: (0, import_i18n15.__)("Min. column width") }),
/* @__PURE__ */ (0, import_jsx_runtime132.jsxs)(import_components15.Flex, { gap: 4, children: [
/* @__PURE__ */ (0, import_jsx_runtime132.jsx)(import_components15.FlexItem, { isBlock: true, children: /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(
import_components15.__experimentalUnitControl,
{
onChange: (newValue) => {
onChange({
...layout,
minimumColumnWidth: newValue === "" ? void 0 : newValue
});
},
onUnitChange: handleUnitChange,
value,
units,
min: 0,
label: (0, import_i18n15.__)("Minimum column width"),
hideLabelFromVision: true
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime132.jsx)(import_components15.FlexItem, { isBlock: true, children: /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(
import_components15.RangeControl,
{
onChange: handleSliderChange,
value: quantity || 0,
min: 0,
max: RANGE_CONTROL_MAX_VALUES[unit] || 600,
withInputField: false,
label: (0, import_i18n15.__)("Minimum column width"),
hideLabelFromVision: true
}
) })
] }),
/* @__PURE__ */ (0, import_jsx_runtime132.jsx)("p", { className: "components-base-control__help", children: (0, import_i18n15.__)(
"Columns will wrap to fewer per row when they can no longer maintain the minimum width."
) })
] });
}
function GridLayoutColumnsAndRowsControl({
layout,
onChange,
allowSizingOnChildren
}) {
const defaultColumnCount = void 0;
const {
columnCount = defaultColumnCount,
rowCount,
isManualPlacement
} = layout;
return /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(import_jsx_runtime132.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime132.jsxs)("fieldset", { className: "block-editor-hooks__grid-layout-columns-and-rows-controls", children: [
!isManualPlacement && /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(import_components15.BaseControl.VisualLabel, { as: "legend", children: (0, import_i18n15.__)("Max. columns") }),
/* @__PURE__ */ (0, import_jsx_runtime132.jsxs)(import_components15.Flex, { gap: 4, children: [
/* @__PURE__ */ (0, import_jsx_runtime132.jsx)(import_components15.FlexItem, { isBlock: true, children: /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(
import_components15.__experimentalNumberControl,
{
onChange: (value) => {
const defaultNewColumnCount = isManualPlacement ? 1 : void 0;
const newColumnCount = value === "" || value === "0" ? defaultNewColumnCount : parseInt(value, 10);
onChange({
...layout,
columnCount: newColumnCount
});
},
value: columnCount ?? "",
min: 1,
label: (0, import_i18n15.__)("Columns"),
hideLabelFromVision: !isManualPlacement
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime132.jsx)(import_components15.FlexItem, { isBlock: true, children: allowSizingOnChildren && isManualPlacement ? /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(
import_components15.__experimentalNumberControl,
{
onChange: (value) => {
const newRowCount = value === "" || value === "0" ? 1 : parseInt(value, 10);
onChange({
...layout,
rowCount: newRowCount
});
},
value: rowCount,
min: 1,
label: (0, import_i18n15.__)("Rows")
}
) : /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(
import_components15.RangeControl,
{
value: columnCount ?? 1,
onChange: (value) => onChange({
...layout,
columnCount: value === "" || value === "0" ? 1 : value
}),
min: 1,
max: 16,
withInputField: false,
label: (0, import_i18n15.__)("Columns"),
hideLabelFromVision: true
}
) })
] })
] }) });
}
function GridLayoutFillControl({ layout, onChange }) {
const { autoFit = false } = layout;
return /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(
import_components15.ToggleControl,
{
label: (0, import_i18n15.__)("Fill available space"),
help: (0, import_i18n15.__)(
"Stretch columns to fill the available space, instead of leaving gaps when there are too few items to fill a row."
),
checked: autoFit,
onChange: (value) => onChange({
...layout,
autoFit: value
})
}
);
}
function GridLayoutTypeControl({ layout, onChange }) {
const { columnCount, rowCount, minimumColumnWidth, isManualPlacement } = layout;
const [tempColumnCount, setTempColumnCount] = (0, import_element14.useState)(
columnCount || 3
);
const [tempRowCount, setTempRowCount] = (0, import_element14.useState)(rowCount);
const [tempMinimumColumnWidth, setTempMinimumColumnWidth] = (0, import_element14.useState)(
minimumColumnWidth || "12rem"
);
const gridPlacement = isManualPlacement ? "manual" : "auto";
const onChangeType = (value) => {
if (value === "manual") {
setTempMinimumColumnWidth(minimumColumnWidth || "12rem");
} else {
setTempColumnCount(columnCount || 3);
setTempRowCount(rowCount);
}
onChange({
...layout,
columnCount: value === "manual" ? tempColumnCount : tempColumnCount,
rowCount: value === "manual" ? tempRowCount : void 0,
isManualPlacement: value === "manual" ? true : void 0,
minimumColumnWidth: value === "auto" ? tempMinimumColumnWidth : null
});
};
const helpText2 = gridPlacement === "manual" ? (0, import_i18n15.__)(
"Grid items can be manually placed in any position on the grid."
) : (0, import_i18n15.__)(
"Grid items are placed automatically depending on their order."
);
return /* @__PURE__ */ (0, import_jsx_runtime132.jsxs)(
import_components15.__experimentalToggleGroupControl,
{
label: (0, import_i18n15.__)("Grid item position"),
value: gridPlacement,
onChange: onChangeType,
isBlock: true,
help: helpText2,
children: [
/* @__PURE__ */ (0, import_jsx_runtime132.jsx)(
import_components15.__experimentalToggleGroupControlOption,
{
value: "auto",
label: (0, import_i18n15.__)("Auto")
},
"auto"
),
/* @__PURE__ */ (0, import_jsx_runtime132.jsx)(
import_components15.__experimentalToggleGroupControlOption,
{
value: "manual",
label: (0, import_i18n15.__)("Manual")
},
"manual"
)
]
}
);
}
// packages/block-editor/build-module/layouts/index.mjs
var layoutTypes = [flow_default, flex_default, constrained_default, grid_default2];
function getLayoutType(name = "default") {
return layoutTypes.find((layoutType) => layoutType.name === name);
}
function getLayoutTypes() {
return layoutTypes;
}
// packages/block-editor/build-module/components/block-list/layout.mjs
var import_jsx_runtime133 = __toESM(require_jsx_runtime(), 1);
var defaultLayout = { type: "default" };
var Layout = (0, import_element15.createContext)(defaultLayout);
Layout.displayName = "BlockLayoutContext";
var LayoutProvider = Layout.Provider;
function useLayout() {
return (0, import_element15.useContext)(Layout);
}
function LayoutStyle({ layout = {}, css, ...props }) {
const layoutType = getLayoutType(layout.type);
const [blockGapSupport] = useSettings("spacing.blockGap");
const hasBlockGapSupport = blockGapSupport !== null;
if (layoutType) {
if (css) {
return /* @__PURE__ */ (0, import_jsx_runtime133.jsx)("style", { children: css });
}
const layoutStyle = layoutType.getLayoutStyle?.({
hasBlockGapSupport,
layout,
...props
});
if (layoutStyle) {
return /* @__PURE__ */ (0, import_jsx_runtime133.jsx)("style", { children: layoutStyle });
}
}
return null;
}
// packages/block-editor/build-module/components/block-alignment-control/use-available-alignments.mjs
var EMPTY_ARRAY4 = [];
var DEFAULT_CONTROLS = ["none", "left", "center", "right", "wide", "full"];
var WIDE_CONTROLS = ["wide", "full"];
function useAvailableAlignments(controls = DEFAULT_CONTROLS) {
if (!controls.includes("none")) {
controls = ["none", ...controls];
}
const isNoneOnly = controls.length === 1 && controls[0] === "none";
const [wideControlsEnabled, themeSupportsLayout, isBlockBasedTheme] = (0, import_data12.useSelect)(
(select3) => {
if (isNoneOnly) {
return [false, false, false];
}
const settings2 = select3(store).getSettings();
return [
settings2.alignWide ?? false,
settings2.supportsLayout,
settings2.__unstableIsBlockBasedTheme
];
},
[isNoneOnly]
);
const layout = useLayout();
if (isNoneOnly) {
return EMPTY_ARRAY4;
}
const layoutType = getLayoutType(layout?.type);
if (themeSupportsLayout) {
const layoutAlignments = layoutType.getAlignments(
layout,
isBlockBasedTheme
);
const alignments2 = layoutAlignments.filter(
(alignment) => controls.includes(alignment.name)
);
if (alignments2.length === 1 && alignments2[0].name === "none") {
return EMPTY_ARRAY4;
}
return alignments2;
}
if (layoutType.name !== "default" && layoutType.name !== "constrained") {
return EMPTY_ARRAY4;
}
const alignments = controls.filter((control) => {
if (layout.alignments) {
return layout.alignments.includes(control);
}
if (!wideControlsEnabled && WIDE_CONTROLS.includes(control)) {
return false;
}
return DEFAULT_CONTROLS.includes(control);
}).map((name) => ({ name }));
if (alignments.length === 1 && alignments[0].name === "none") {
return EMPTY_ARRAY4;
}
return alignments;
}
// packages/block-editor/build-module/components/block-alignment-control/constants.mjs
var import_i18n16 = __toESM(require_i18n(), 1);
var BLOCK_ALIGNMENTS_CONTROLS = {
none: {
icon: align_none_default,
title: (0, import_i18n16._x)("None", "Alignment option")
},
left: {
icon: position_left_default,
title: (0, import_i18n16.__)("Align left")
},
center: {
icon: position_center_default,
title: (0, import_i18n16.__)("Align center")
},
right: {
icon: position_right_default,
title: (0, import_i18n16.__)("Align right")
},
wide: {
icon: stretch_wide_default,
title: (0, import_i18n16.__)("Wide width")
},
full: {
icon: stretch_full_width_default,
title: (0, import_i18n16.__)("Full width")
}
};
var DEFAULT_CONTROL = "none";
// packages/block-editor/build-module/components/block-alignment-control/ui.mjs
var import_jsx_runtime134 = __toESM(require_jsx_runtime(), 1);
function BlockAlignmentUI({
value,
onChange,
controls,
isToolbar,
isCollapsed: isCollapsed3 = true
}) {
const enabledControls = useAvailableAlignments(controls);
const hasEnabledControls = !!enabledControls.length;
if (!hasEnabledControls) {
return null;
}
function onChangeAlignment(align) {
onChange([value, "none"].includes(align) ? void 0 : align);
}
const activeAlignmentControl = BLOCK_ALIGNMENTS_CONTROLS[value];
const defaultAlignmentControl = BLOCK_ALIGNMENTS_CONTROLS[DEFAULT_CONTROL];
const UIComponent = isToolbar ? import_components16.ToolbarGroup : import_components16.ToolbarDropdownMenu;
const commonProps = {
icon: activeAlignmentControl ? activeAlignmentControl.icon : defaultAlignmentControl.icon,
label: (0, import_i18n17.__)("Align")
};
const extraProps = isToolbar ? {
isCollapsed: isCollapsed3,
controls: enabledControls.map(({ name: controlName }) => {
return {
...BLOCK_ALIGNMENTS_CONTROLS[controlName],
isActive: value === controlName || !value && controlName === "none",
role: isCollapsed3 ? "menuitemradio" : void 0,
onClick: () => onChangeAlignment(controlName)
};
})
} : {
toggleProps: { description: (0, import_i18n17.__)("Change alignment") },
children: ({ onClose }) => {
return /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(import_jsx_runtime134.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(import_components16.MenuGroup, { className: "block-editor-block-alignment-control__menu-group", children: enabledControls.map(
({ name: controlName, info }) => {
const { icon, title } = BLOCK_ALIGNMENTS_CONTROLS[controlName];
const isSelected = controlName === value || !value && controlName === "none";
return /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
import_components16.MenuItem,
{
icon,
iconPosition: "left",
className: clsx_default(
"components-dropdown-menu__menu-item",
{
"is-active": isSelected
}
),
isSelected,
onClick: () => {
onChangeAlignment(
controlName
);
onClose();
},
role: "menuitemradio",
info,
children: title
},
controlName
);
}
) }) });
}
};
return /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(UIComponent, { ...commonProps, ...extraProps });
}
var ui_default2 = BlockAlignmentUI;
// packages/block-editor/build-module/components/block-alignment-control/index.mjs
var import_jsx_runtime135 = __toESM(require_jsx_runtime(), 1);
var BlockAlignmentControl = (props) => {
return /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(ui_default2, { ...props, isToolbar: false });
};
var BlockAlignmentToolbar = (props) => {
return /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(ui_default2, { ...props, isToolbar: true });
};
// packages/block-editor/build-module/components/block-bindings/attribute-control.mjs
var import_es63 = __toESM(require_es6(), 1);
var import_i18n18 = __toESM(require_i18n(), 1);
var import_blocks15 = __toESM(require_blocks(), 1);
var import_components18 = __toESM(require_components(), 1);
var import_data15 = __toESM(require_data(), 1);
var import_element17 = __toESM(require_element(), 1);
var import_compose5 = __toESM(require_compose(), 1);
// packages/block-editor/build-module/components/block-bindings/source-fields-list.mjs
var import_es62 = __toESM(require_es6(), 1);
var import_blocks14 = __toESM(require_blocks(), 1);
var import_components17 = __toESM(require_components(), 1);
var import_data14 = __toESM(require_data(), 1);
var import_element16 = __toESM(require_element(), 1);
var import_compose4 = __toESM(require_compose(), 1);
// packages/block-editor/build-module/components/block-bindings/use-block-bindings-utils.mjs
var import_data13 = __toESM(require_data(), 1);
function isObjectEmpty(object) {
return !object || Object.keys(object).length === 0;
}
function useBlockBindingsUtils(clientId) {
const { clientId: contextClientId } = useBlockEditContext();
const blockClientId = clientId || contextClientId;
const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data13.useDispatch)(store);
const { getBlockAttributes: getBlockAttributes3 } = (0, import_data13.useRegistry)().select(store);
const updateBlockBindings = (bindings) => {
const { metadata: { bindings: currentBindings, ...metadata } = {} } = getBlockAttributes3(blockClientId);
const newBindings = { ...currentBindings };
Object.entries(bindings).forEach(([attribute, binding]) => {
if (!binding && newBindings[attribute]) {
delete newBindings[attribute];
return;
}
newBindings[attribute] = binding;
});
const newMetadata = {
...metadata,
bindings: newBindings
};
if (isObjectEmpty(newMetadata.bindings)) {
delete newMetadata.bindings;
}
updateBlockAttributes2(blockClientId, {
metadata: isObjectEmpty(newMetadata) ? void 0 : newMetadata
});
};
const removeAllBlockBindings = () => {
const { metadata: { bindings, ...metadata } = {} } = getBlockAttributes3(blockClientId);
updateBlockAttributes2(blockClientId, {
metadata: isObjectEmpty(metadata) ? void 0 : metadata
});
};
return { updateBlockBindings, removeAllBlockBindings };
}
// packages/block-editor/build-module/components/block-bindings/source-fields-list.mjs
var import_jsx_runtime136 = __toESM(require_jsx_runtime(), 1);
var { Menu } = unlock(import_components17.privateApis);
function BlockBindingsSourceFieldsListItem({
args,
attribute,
field,
source,
sourceKey
}) {
const itemBindings = (0, import_element16.useMemo)(
() => ({
source: sourceKey,
args: field.args || {
key: field.key
}
}),
[field.args, field.key, sourceKey]
);
const blockContext = (0, import_element16.useContext)(block_context_default);
const values = (0, import_data14.useSelect)(
(select3) => source.getValues({
select: select3,
context: blockContext,
bindings: {
[attribute]: itemBindings
}
}),
[attribute, blockContext, itemBindings, source]
);
const { updateBlockBindings } = useBlockBindingsUtils();
return /* @__PURE__ */ (0, import_jsx_runtime136.jsxs)(
Menu.CheckboxItem,
{
onChange: () => {
const isCurrentlySelected = (0, import_es62.default)(args, field.args) ?? // Deprecate key dependency in 7.0.
field.key === args?.key;
if (isCurrentlySelected) {
updateBlockBindings({
[attribute]: void 0
});
} else {
updateBlockBindings({
[attribute]: itemBindings
});
}
},
name: attribute + "-binding",
value: values[attribute],
checked: (0, import_es62.default)(args, field.args) ?? // Deprecate key dependency in 7.0.
field.key === args?.key,
children: [
/* @__PURE__ */ (0, import_jsx_runtime136.jsx)(Menu.ItemLabel, { children: field.label }),
/* @__PURE__ */ (0, import_jsx_runtime136.jsx)(Menu.ItemHelpText, { children: values[attribute] })
]
}
);
}
function BlockBindingsSourceFieldsList({
args,
attribute,
sourceKey,
fields
}) {
const isMobile = (0, import_compose4.useViewportMatch)("medium", "<");
if (!fields || fields.length === 0) {
return null;
}
const source = (0, import_blocks14.getBlockBindingsSource)(sourceKey);
return /* @__PURE__ */ (0, import_jsx_runtime136.jsxs)(
Menu,
{
placement: isMobile ? "bottom-start" : "left-start",
children: [
/* @__PURE__ */ (0, import_jsx_runtime136.jsx)(Menu.SubmenuTriggerItem, { children: /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(Menu.ItemLabel, { children: source.label }) }),
/* @__PURE__ */ (0, import_jsx_runtime136.jsx)(Menu.Popover, { gutter: 8, children: /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(Menu.Group, { children: fields.map((field) => /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
BlockBindingsSourceFieldsListItem,
{
args,
attribute,
field,
source,
sourceKey
},
sourceKey + JSON.stringify(field.args) || field.key
)) }) })
]
},
sourceKey
);
}
// packages/block-editor/build-module/components/block-bindings/attribute-control.mjs
var import_jsx_runtime137 = __toESM(require_jsx_runtime(), 1);
var { Menu: Menu2 } = unlock(import_components18.privateApis);
function BlockBindingsAttributeControl({
attribute,
binding,
blockName
}) {
const { updateBlockBindings } = useBlockBindingsUtils();
const isMobile = (0, import_compose5.useViewportMatch)("medium", "<");
const blockContext = (0, import_element17.useContext)(block_context_default);
const compatibleFields = (0, import_data15.useSelect)(
(select3) => {
const {
getAllBlockBindingsSources,
getBlockBindingsSourceFieldsList,
getBlockType: getBlockType29
} = unlock(select3(import_blocks15.store));
const _attribute = getBlockType29(blockName).attributes?.[attribute];
if (_attribute?.enum) {
return {};
}
const attributeType = _attribute?.type === "rich-text" ? "string" : _attribute?.type;
const sourceFields = {};
Object.entries(getAllBlockBindingsSources()).forEach(
([sourceName, source2]) => {
const fieldsList = getBlockBindingsSourceFieldsList(
source2,
blockContext
);
if (!fieldsList?.length) {
return;
}
const compatibleFieldsList = fieldsList.filter(
(field) => field.type === attributeType
);
if (compatibleFieldsList.length) {
sourceFields[sourceName] = compatibleFieldsList;
}
}
);
return sourceFields;
},
[attribute, blockName, blockContext]
);
const { canUpdateBlockBindings } = (0, import_data15.useSelect)((select3) => ({
canUpdateBlockBindings: select3(store).getSettings().canUpdateBlockBindings
}));
const hasCompatibleFields = Object.keys(compatibleFields).length > 0;
const isAttributeReadOnly = !canUpdateBlockBindings || !hasCompatibleFields;
const { source: boundSourceName, args } = binding || {};
const source = (0, import_blocks15.getBlockBindingsSource)(boundSourceName);
let displayText;
let isValid2 = true;
if (binding === void 0) {
if (!hasCompatibleFields) {
displayText = (0, import_i18n18.__)("No sources available");
} else {
displayText = (0, import_i18n18.__)("Not connected");
}
isValid2 = true;
} else if (!source) {
isValid2 = false;
displayText = (0, import_i18n18.__)("Source not registered");
} else {
displayText = compatibleFields?.[boundSourceName]?.find(
(field) => (0, import_es63.default)(field.args, args)
)?.label || source?.label || boundSourceName;
}
return /* @__PURE__ */ (0, import_jsx_runtime137.jsx)(
import_components18.__experimentalToolsPanelItem,
{
hasValue: () => !!binding,
label: attribute,
onDeselect: !!hasCompatibleFields && (() => {
updateBlockBindings({
[attribute]: void 0
});
}),
children: /* @__PURE__ */ (0, import_jsx_runtime137.jsxs)(Menu2, { placement: isMobile ? "bottom-start" : "left-start", children: [
/* @__PURE__ */ (0, import_jsx_runtime137.jsx)(
Menu2.TriggerButton,
{
render: /* @__PURE__ */ (0, import_jsx_runtime137.jsx)(import_components18.__experimentalItem, {}),
disabled: !hasCompatibleFields,
children: /* @__PURE__ */ (0, import_jsx_runtime137.jsxs)(
import_components18.__experimentalVStack,
{
className: "block-editor-bindings__item",
spacing: 0,
children: [
/* @__PURE__ */ (0, import_jsx_runtime137.jsx)(import_components18.__experimentalText, { truncate: true, children: attribute }),
/* @__PURE__ */ (0, import_jsx_runtime137.jsx)(
import_components18.__experimentalText,
{
truncate: true,
variant: isValid2 ? "muted" : void 0,
isDestructive: !isValid2,
children: displayText
}
)
]
}
)
}
),
!isAttributeReadOnly && /* @__PURE__ */ (0, import_jsx_runtime137.jsx)(Menu2.Popover, { gutter: isMobile ? 8 : 36, children: /* @__PURE__ */ (0, import_jsx_runtime137.jsx)(
Menu2,
{
placement: isMobile ? "bottom-start" : "left-start",
children: Object.entries(compatibleFields).map(
([sourceKey, fields]) => /* @__PURE__ */ (0, import_jsx_runtime137.jsx)(
BlockBindingsSourceFieldsList,
{
args: binding?.args,
attribute,
sourceKey,
fields
},
sourceKey
)
)
}
) })
] })
}
);
}
// packages/block-editor/build-module/components/block-full-height-alignment-control/index.mjs
var import_i18n19 = __toESM(require_i18n(), 1);
var import_components19 = __toESM(require_components(), 1);
var import_jsx_runtime138 = __toESM(require_jsx_runtime(), 1);
function BlockFullHeightAlignmentControl({
isActive,
label = (0, import_i18n19.__)("Full height"),
onToggle,
isDisabled
}) {
return /* @__PURE__ */ (0, import_jsx_runtime138.jsx)(
import_components19.ToolbarButton,
{
isActive,
icon: full_height_default,
label,
onClick: () => onToggle(!isActive),
disabled: isDisabled
}
);
}
var block_full_height_alignment_control_default = BlockFullHeightAlignmentControl;
// packages/block-editor/build-module/components/block-alignment-matrix-control/index.mjs
var import_i18n20 = __toESM(require_i18n(), 1);
var import_keycodes = __toESM(require_keycodes(), 1);
var import_components20 = __toESM(require_components(), 1);
var import_jsx_runtime139 = __toESM(require_jsx_runtime(), 1);
var noop2 = () => {
};
function BlockAlignmentMatrixControl(props) {
const {
label = (0, import_i18n20.__)("Change matrix alignment"),
onChange = noop2,
value = "center",
isDisabled
} = props;
const icon = /* @__PURE__ */ (0, import_jsx_runtime139.jsx)(import_components20.AlignmentMatrixControl.Icon, { value });
return /* @__PURE__ */ (0, import_jsx_runtime139.jsx)(
import_components20.Dropdown,
{
popoverProps: { placement: "bottom-start" },
renderToggle: ({ onToggle, isOpen }) => {
const openOnArrowDown = (event) => {
if (!isOpen && event.keyCode === import_keycodes.DOWN) {
event.preventDefault();
onToggle();
}
};
return /* @__PURE__ */ (0, import_jsx_runtime139.jsx)(
import_components20.ToolbarButton,
{
onClick: onToggle,
"aria-haspopup": "true",
"aria-expanded": isOpen,
onKeyDown: openOnArrowDown,
label,
icon,
showTooltip: true,
disabled: isDisabled
}
);
},
renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime139.jsx)(import_components20.AlignmentMatrixControl, { onChange, value })
}
);
}
var block_alignment_matrix_control_default = BlockAlignmentMatrixControl;
// packages/block-editor/build-module/components/block-breadcrumb/index.mjs
var import_components21 = __toESM(require_components(), 1);
var import_data17 = __toESM(require_data(), 1);
var import_i18n21 = __toESM(require_i18n(), 1);
var import_element20 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/block-title/use-block-display-title.mjs
var import_data16 = __toESM(require_data(), 1);
var import_blocks16 = __toESM(require_blocks(), 1);
function useBlockDisplayTitle({
clientId,
maximumLength,
context
}) {
const blockTitle = (0, import_data16.useSelect)(
(select3) => {
if (!clientId) {
return null;
}
const { getBlockName: getBlockName2, getBlockAttributes: getBlockAttributes3, getBlock: getBlock2 } = select3(store);
const { getBlockType: getBlockType29, getActiveBlockVariation } = select3(import_blocks16.store);
const blockName = getBlockName2(clientId);
const blockType = getBlockType29(blockName);
if (!blockType) {
return null;
}
const attributes = getBlockAttributes3(clientId);
const label = (0, import_blocks16.__experimentalGetBlockLabel)(blockType, attributes, context);
if (label !== blockType.title) {
return label;
}
const match2 = getActiveBlockVariation(
blockName,
attributes,
void 0,
getBlock2?.(clientId)?.innerContent
);
return match2?.title || blockType.title;
},
[clientId, context]
);
if (!blockTitle) {
return null;
}
if (maximumLength && maximumLength > 0 && blockTitle.length > maximumLength) {
const omission = "...";
return blockTitle.slice(0, maximumLength - omission.length) + omission;
}
return blockTitle;
}
// packages/block-editor/build-module/components/block-title/index.mjs
function BlockTitle({ clientId, maximumLength, context }) {
return useBlockDisplayTitle({ clientId, maximumLength, context });
}
// packages/block-editor/build-module/components/block-list/use-block-props/use-block-refs.mjs
var import_element19 = __toESM(require_element(), 1);
var import_compose7 = __toESM(require_compose(), 1);
// packages/block-editor/build-module/components/provider/block-refs-provider.mjs
var import_element18 = __toESM(require_element(), 1);
var import_compose6 = __toESM(require_compose(), 1);
var import_jsx_runtime140 = __toESM(require_jsx_runtime(), 1);
var BlockRefs = (0, import_element18.createContext)({ refsMap: (0, import_compose6.observableMap)() });
BlockRefs.displayName = "BlockRefsContext";
function BlockRefsProvider({ children }) {
const value = (0, import_element18.useMemo)(() => ({ refsMap: (0, import_compose6.observableMap)() }), []);
return /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(BlockRefs.Provider, { value, children });
}
// packages/block-editor/build-module/components/block-list/use-block-props/use-block-refs.mjs
function useBlockRefProvider(clientId) {
const { refsMap } = (0, import_element19.useContext)(BlockRefs);
return (0, import_compose7.useRefEffect)(
(element) => {
refsMap.set(clientId, element);
return () => refsMap.delete(clientId);
},
[clientId]
);
}
function assignRef(ref, value) {
if (typeof ref === "function") {
ref(value);
} else if (ref) {
ref.current = value;
}
}
function useBlockElementRef(clientId, ref) {
const { refsMap } = (0, import_element19.useContext)(BlockRefs);
(0, import_element19.useLayoutEffect)(() => {
assignRef(ref, refsMap.get(clientId));
const unsubscribe = refsMap.subscribe(
clientId,
() => assignRef(ref, refsMap.get(clientId))
);
return () => {
unsubscribe();
assignRef(ref, null);
};
}, [refsMap, clientId, ref]);
}
function useBlockElement(clientId) {
const [blockElement, setBlockElement] = (0, import_element19.useState)(null);
useBlockElementRef(clientId, setBlockElement);
return blockElement;
}
// packages/block-editor/build-module/utils/get-editor-region.mjs
function getEditorRegion(editor) {
if (!editor) {
return null;
}
const editorCanvas = Array.from(
document.querySelectorAll(
'iframe[name="editor-canvas"]'
).values()
).find((iframe) => {
const iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
return iframeDocument === editor.ownerDocument;
}) ?? editor;
return editorCanvas?.closest('[role="region"]') ?? editorCanvas;
}
// packages/block-editor/build-module/components/block-breadcrumb/index.mjs
var import_jsx_runtime141 = __toESM(require_jsx_runtime(), 1);
function BlockBreadcrumb({ rootLabelText }) {
const { selectBlock: selectBlock2, clearSelectedBlock: clearSelectedBlock2 } = (0, import_data17.useDispatch)(store);
const { clientId, parents, hasSelection } = (0, import_data17.useSelect)((select3) => {
const {
getSelectionStart: getSelectionStart2,
getSelectedBlockClientId: getSelectedBlockClientId2,
getEnabledBlockParents: getEnabledBlockParents2
} = unlock(select3(store));
const selectedBlockClientId = getSelectedBlockClientId2();
return {
parents: getEnabledBlockParents2(selectedBlockClientId),
clientId: selectedBlockClientId,
hasSelection: !!getSelectionStart2().clientId
};
}, []);
const rootLabel = rootLabelText || (0, import_i18n21._x)("Document", "noun, breadcrumb");
const blockRef = (0, import_element20.useRef)();
useBlockElementRef(clientId, blockRef);
return /* @__PURE__ */ (0, import_jsx_runtime141.jsxs)(
"ul",
{
className: "block-editor-block-breadcrumb",
role: "list",
"aria-label": (0, import_i18n21.__)("Block breadcrumb"),
children: [
/* @__PURE__ */ (0, import_jsx_runtime141.jsxs)(
"li",
{
className: !hasSelection ? "block-editor-block-breadcrumb__current" : void 0,
"aria-current": !hasSelection ? "true" : void 0,
children: [
hasSelection && /* @__PURE__ */ (0, import_jsx_runtime141.jsx)(
import_components21.Button,
{
size: "small",
className: "block-editor-block-breadcrumb__button",
onClick: () => {
const blockEditor = blockRef.current?.closest(
".editor-styles-wrapper"
);
clearSelectedBlock2();
getEditorRegion(blockEditor)?.focus();
},
children: rootLabel
}
),
!hasSelection && /* @__PURE__ */ (0, import_jsx_runtime141.jsx)("span", { children: rootLabel }),
!!clientId && /* @__PURE__ */ (0, import_jsx_runtime141.jsx)(
icon_default,
{
icon: chevron_right_small_default,
className: "block-editor-block-breadcrumb__separator"
}
)
]
}
),
parents.map((parentClientId) => /* @__PURE__ */ (0, import_jsx_runtime141.jsxs)("li", { children: [
/* @__PURE__ */ (0, import_jsx_runtime141.jsx)(
import_components21.Button,
{
size: "small",
className: "block-editor-block-breadcrumb__button",
onClick: () => selectBlock2(parentClientId),
children: /* @__PURE__ */ (0, import_jsx_runtime141.jsx)(
BlockTitle,
{
clientId: parentClientId,
maximumLength: 35,
context: "breadcrumb"
}
)
}
),
/* @__PURE__ */ (0, import_jsx_runtime141.jsx)(
icon_default,
{
icon: chevron_right_small_default,
className: "block-editor-block-breadcrumb__separator"
}
)
] }, parentClientId)),
!!clientId && /* @__PURE__ */ (0, import_jsx_runtime141.jsx)(
"li",
{
className: "block-editor-block-breadcrumb__current",
"aria-current": "true",
children: /* @__PURE__ */ (0, import_jsx_runtime141.jsx)(
BlockTitle,
{
clientId,
maximumLength: 35,
context: "breadcrumb"
}
)
}
)
]
}
);
}
var block_breadcrumb_default = BlockBreadcrumb;
// packages/block-editor/build-module/components/block-content-overlay/index.mjs
var import_data18 = __toESM(require_data(), 1);
function useBlockOverlayActive(clientId) {
return (0, import_data18.useSelect)(
(select3) => {
const { __unstableHasActiveBlockOverlayActive: __unstableHasActiveBlockOverlayActive2 } = select3(store);
return __unstableHasActiveBlockOverlayActive2(clientId);
},
[clientId]
);
}
// packages/block-editor/build-module/components/block-canvas/index.mjs
var import_compose69 = __toESM(require_compose(), 1);
var import_element178 = __toESM(require_element(), 1);
var import_data126 = __toESM(require_data(), 1);
var import_components116 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/block-list/index.mjs
var import_data80 = __toESM(require_data(), 1);
var import_compose56 = __toESM(require_compose(), 1);
var import_element141 = __toESM(require_element(), 1);
var import_blocks47 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/components/block-list/block.mjs
var import_element31 = __toESM(require_element(), 1);
var import_blocks24 = __toESM(require_blocks(), 1);
var import_components28 = __toESM(require_components(), 1);
var import_data30 = __toESM(require_data(), 1);
var import_compose17 = __toESM(require_compose(), 1);
var import_dom9 = __toESM(require_dom(), 1);
// packages/block-editor/build-module/components/block-list/block-invalid-warning.mjs
var import_i18n23 = __toESM(require_i18n(), 1);
var import_components23 = __toESM(require_components(), 1);
var import_element22 = __toESM(require_element(), 1);
var import_blocks18 = __toESM(require_blocks(), 1);
var import_data19 = __toESM(require_data(), 1);
// node_modules/diff/libesm/diff/base.js
var Diff = class {
diff(oldStr, newStr, options = {}) {
let callback;
if (typeof options === "function") {
callback = options;
options = {};
} else if ("callback" in options) {
callback = options.callback;
}
const oldString = this.castInput(oldStr, options);
const newString = this.castInput(newStr, options);
const oldTokens = this.removeEmpty(this.tokenize(oldString, options));
const newTokens = this.removeEmpty(this.tokenize(newString, options));
return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);
}
diffWithOptionsObj(oldTokens, newTokens, options, callback) {
var _a;
const done = (value) => {
value = this.postProcess(value, options);
if (callback) {
setTimeout(function() {
callback(value);
}, 0);
return void 0;
} else {
return value;
}
};
const newLen = newTokens.length, oldLen = oldTokens.length;
let editLength = 1;
let maxEditLength = newLen + oldLen;
if (options.maxEditLength != null) {
maxEditLength = Math.min(maxEditLength, options.maxEditLength);
}
const maxExecutionTime = (_a = options.timeout) !== null && _a !== void 0 ? _a : Infinity;
const abortAfterTimestamp = Date.now() + maxExecutionTime;
const bestPath = [{ oldPos: -1, lastComponent: void 0 }];
let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options);
if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens));
}
let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;
const execEditLength = () => {
for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {
let basePath;
const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1];
if (removePath) {
bestPath[diagonalPath - 1] = void 0;
}
let canAdd = false;
if (addPath) {
const addPathNewPos = addPath.oldPos - diagonalPath;
canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;
}
const canRemove = removePath && removePath.oldPos + 1 < oldLen;
if (!canAdd && !canRemove) {
bestPath[diagonalPath] = void 0;
continue;
}
if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) {
basePath = this.addToPath(addPath, true, false, 0, options);
} else {
basePath = this.addToPath(removePath, false, true, 1, options);
}
newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options);
if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true;
} else {
bestPath[diagonalPath] = basePath;
if (basePath.oldPos + 1 >= oldLen) {
maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);
}
if (newPos + 1 >= newLen) {
minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);
}
}
}
editLength++;
};
if (callback) {
(function exec() {
setTimeout(function() {
if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {
return callback(void 0);
}
if (!execEditLength()) {
exec();
}
}, 0);
})();
} else {
while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {
const ret = execEditLength();
if (ret) {
return ret;
}
}
}
}
addToPath(path, added, removed, oldPosInc, options) {
const last = path.lastComponent;
if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
return {
oldPos: path.oldPos + oldPosInc,
lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
};
} else {
return {
oldPos: path.oldPos + oldPosInc,
lastComponent: { count: 1, added, removed, previousComponent: last }
};
}
}
extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) {
const newLen = newTokens.length, oldLen = oldTokens.length;
let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;
while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) {
newPos++;
oldPos++;
commonCount++;
if (options.oneChangePerToken) {
basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false };
}
}
if (commonCount && !options.oneChangePerToken) {
basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false };
}
basePath.oldPos = oldPos;
return newPos;
}
equals(left, right, options) {
if (options.comparator) {
return options.comparator(left, right);
} else {
return left === right || !!options.ignoreCase && left.toLowerCase() === right.toLowerCase();
}
}
removeEmpty(array) {
const ret = [];
for (let i2 = 0; i2 < array.length; i2++) {
if (array[i2]) {
ret.push(array[i2]);
}
}
return ret;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
castInput(value, options) {
return value;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
tokenize(value, options) {
return Array.from(value);
}
join(chars) {
return chars.join("");
}
postProcess(changeObjects, options) {
return changeObjects;
}
get useLongestToken() {
return false;
}
buildValues(lastComponent, newTokens, oldTokens) {
const components = [];
let nextComponent;
while (lastComponent) {
components.push(lastComponent);
nextComponent = lastComponent.previousComponent;
delete lastComponent.previousComponent;
lastComponent = nextComponent;
}
components.reverse();
const componentLen = components.length;
let componentPos = 0, newPos = 0, oldPos = 0;
for (; componentPos < componentLen; componentPos++) {
const component = components[componentPos];
if (!component.removed) {
if (!component.added && this.useLongestToken) {
let value = newTokens.slice(newPos, newPos + component.count);
value = value.map(function(value2, i2) {
const oldValue = oldTokens[oldPos + i2];
return oldValue.length > value2.length ? oldValue : value2;
});
component.value = this.join(value);
} else {
component.value = this.join(newTokens.slice(newPos, newPos + component.count));
}
newPos += component.count;
if (!component.added) {
oldPos += component.count;
}
} else {
component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count));
oldPos += component.count;
}
}
return components;
}
};
// node_modules/diff/libesm/diff/character.js
var CharacterDiff = class extends Diff {
};
var characterDiff = new CharacterDiff();
function diffChars(oldStr, newStr, options) {
return characterDiff.diff(oldStr, newStr, options);
}
// packages/block-editor/build-module/components/block-compare/index.mjs
var import_i18n22 = __toESM(require_i18n(), 1);
var import_blocks17 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/components/block-compare/block-view.mjs
var import_components22 = __toESM(require_components(), 1);
var import_element21 = __toESM(require_element(), 1);
var import_dom = __toESM(require_dom(), 1);
var import_jsx_runtime142 = __toESM(require_jsx_runtime(), 1);
function BlockView({
title,
rawContent,
renderedContent,
action,
actionText,
className
}) {
return /* @__PURE__ */ (0, import_jsx_runtime142.jsxs)("div", { className, children: [
/* @__PURE__ */ (0, import_jsx_runtime142.jsxs)("div", { className: "block-editor-block-compare__content", children: [
/* @__PURE__ */ (0, import_jsx_runtime142.jsx)("h2", { className: "block-editor-block-compare__heading", children: title }),
/* @__PURE__ */ (0, import_jsx_runtime142.jsx)("div", { className: "block-editor-block-compare__html", children: rawContent }),
/* @__PURE__ */ (0, import_jsx_runtime142.jsx)("div", { className: "block-editor-block-compare__preview edit-post-visual-editor", children: /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(import_element21.RawHTML, { children: (0, import_dom.safeHTML)(renderedContent) }) })
] }),
/* @__PURE__ */ (0, import_jsx_runtime142.jsx)("div", { className: "block-editor-block-compare__action", children: /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
import_components22.Button,
{
__next40pxDefaultSize: true,
variant: "secondary",
tabIndex: "0",
onClick: action,
children: actionText
}
) })
] });
}
// packages/block-editor/build-module/components/block-compare/index.mjs
var import_jsx_runtime143 = __toESM(require_jsx_runtime(), 1);
function BlockCompare({
block,
onKeep,
onConvert,
convertor,
convertButtonText
}) {
function getDifference(originalContent, newContent) {
const difference2 = diffChars(originalContent, newContent);
return difference2.map((item, pos) => {
const classes = clsx_default({
"block-editor-block-compare__added": item.added,
"block-editor-block-compare__removed": item.removed
});
return /* @__PURE__ */ (0, import_jsx_runtime143.jsx)("span", { className: classes, children: item.value }, pos);
});
}
function getConvertedContent(convertedBlock) {
const newBlocks = Array.isArray(convertedBlock) ? convertedBlock : [convertedBlock];
const newContent = newBlocks.map(
(item) => (0, import_blocks17.getSaveContent)(item.name, item.attributes, item.innerBlocks)
);
return newContent.join("");
}
const converted = getConvertedContent(convertor(block));
const difference = getDifference(block.originalContent, converted);
return /* @__PURE__ */ (0, import_jsx_runtime143.jsxs)("div", { className: "block-editor-block-compare__wrapper", children: [
/* @__PURE__ */ (0, import_jsx_runtime143.jsx)(
BlockView,
{
title: (0, import_i18n22.__)("Current"),
className: "block-editor-block-compare__current",
action: onKeep,
actionText: (0, import_i18n22.__)("Convert to HTML"),
rawContent: block.originalContent,
renderedContent: block.originalContent
}
),
/* @__PURE__ */ (0, import_jsx_runtime143.jsx)(
BlockView,
{
title: (0, import_i18n22.__)("After Conversion"),
className: "block-editor-block-compare__converted",
action: onConvert,
actionText: convertButtonText,
rawContent: difference,
renderedContent: converted
}
)
] });
}
var block_compare_default = BlockCompare;
// packages/block-editor/build-module/components/block-list/block-invalid-warning.mjs
var import_jsx_runtime144 = __toESM(require_jsx_runtime(), 1);
var blockToBlocks = (block) => (0, import_blocks18.rawHandler)({
HTML: block.originalContent
});
function BlockInvalidWarning({ clientId }) {
const { block, canInsertHTMLBlock } = (0, import_data19.useSelect)(
(select3) => {
const { canInsertBlockType: canInsertBlockType2, getBlock: getBlock2, getBlockRootClientId: getBlockRootClientId2 } = select3(store);
const rootClientId = getBlockRootClientId2(clientId);
return {
block: getBlock2(clientId),
canInsertHTMLBlock: canInsertBlockType2(
"core/html",
rootClientId
)
};
},
[clientId]
);
const { replaceBlock: replaceBlock2 } = (0, import_data19.useDispatch)(store);
const [compare2, setCompare] = (0, import_element22.useState)(false);
const onCompareClose = (0, import_element22.useCallback)(() => setCompare(false), []);
const convert = (0, import_element22.useMemo)(
() => ({
toHTML() {
const htmlBlock = (0, import_blocks18.createBlock)(
"core/html",
{},
[],
[block.originalContent]
);
return replaceBlock2(block.clientId, htmlBlock);
},
toBlocks() {
const newBlocks = blockToBlocks(block);
return replaceBlock2(block.clientId, newBlocks);
},
toRecoveredBlock() {
const recoveredBlock = (0, import_blocks18.createBlock)(
block.name,
block.attributes,
block.innerBlocks
);
return replaceBlock2(block.clientId, recoveredBlock);
}
}),
[block, replaceBlock2]
);
const secondaryActions = (0, import_element22.useMemo)(
() => [
{
// translators: Button to fix block content
title: (0, import_i18n23._x)("Resolve", "imperative verb"),
onClick: () => setCompare(true)
},
canInsertHTMLBlock && {
title: (0, import_i18n23.__)("Convert to HTML"),
onClick: convert.toHTML
}
].filter(Boolean),
[canInsertHTMLBlock, convert]
);
return /* @__PURE__ */ (0, import_jsx_runtime144.jsxs)(import_jsx_runtime144.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime144.jsx)(
warning_default,
{
actions: [
/* @__PURE__ */ (0, import_jsx_runtime144.jsx)(
import_components23.Button,
{
__next40pxDefaultSize: true,
onClick: convert.toRecoveredBlock,
variant: "primary",
children: (0, import_i18n23.__)("Attempt recovery")
},
"recover"
)
],
secondaryActions,
children: (0, import_i18n23.__)("Block contains unexpected or invalid content.")
}
),
compare2 && /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(
import_components23.Modal,
{
title: (
// translators: Dialog title to fix block content
(0, import_i18n23.__)("Resolve Block")
),
onRequestClose: onCompareClose,
className: "block-editor-block-compare",
children: /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(
block_compare_default,
{
block,
onKeep: convert.toHTML,
onConvert: convert.toBlocks,
convertor: blockToBlocks,
convertButtonText: (0, import_i18n23.__)("Convert to Blocks")
}
)
}
)
] });
}
// packages/block-editor/build-module/components/block-list/block-crash-warning.mjs
var import_i18n24 = __toESM(require_i18n(), 1);
var import_jsx_runtime145 = __toESM(require_jsx_runtime(), 1);
var warning = /* @__PURE__ */ (0, import_jsx_runtime145.jsx)(warning_default, { className: "block-editor-block-list__block-crash-warning", children: (0, import_i18n24.__)("This block has encountered an error and cannot be previewed.") });
function BlockCrashWarning() {
return warning;
}
// packages/block-editor/build-module/components/block-list/block-crash-boundary.mjs
var import_element23 = __toESM(require_element(), 1);
var BlockCrashBoundary = class extends import_element23.Component {
constructor() {
super(...arguments);
this.state = {
hasError: false
};
}
componentDidCatch() {
this.setState({
hasError: true
});
}
render() {
if (this.state.hasError) {
return this.props.fallback;
}
return this.props.children;
}
};
var block_crash_boundary_default = BlockCrashBoundary;
// packages/block-editor/build-module/components/block-list/block-html.mjs
var import_react_autosize_textarea = __toESM(require_lib(), 1);
var import_element24 = __toESM(require_element(), 1);
var import_data20 = __toESM(require_data(), 1);
var import_blocks19 = __toESM(require_blocks(), 1);
var import_jsx_runtime146 = __toESM(require_jsx_runtime(), 1);
function BlockHTML({ clientId }) {
const [html, setHtml] = (0, import_element24.useState)("");
const block = (0, import_data20.useSelect)(
(select3) => select3(store).getBlock(clientId),
[clientId]
);
const { updateBlock: updateBlock2 } = (0, import_data20.useDispatch)(store);
const blockContent = (0, import_element24.useMemo)(
() => block ? (0, import_blocks19.getBlockContent)(block) : "",
[block]
);
const onChange = () => {
const blockType = (0, import_blocks19.getBlockType)(block.name);
if (!blockType) {
return;
}
const attributes = (0, import_blocks19.getBlockAttributes)(
blockType,
html,
block.attributes
);
const content = html ? html : (0, import_blocks19.getSaveContent)(blockType, attributes);
const [isValid2] = html ? (0, import_blocks19.validateBlock)({
...block,
attributes,
originalContent: content
}) : [true];
updateBlock2(clientId, {
attributes,
originalContent: content,
isValid: isValid2
});
if (!html) {
setHtml(content);
}
};
(0, import_element24.useEffect)(() => {
setHtml(blockContent);
}, [blockContent]);
return /* @__PURE__ */ (0, import_jsx_runtime146.jsx)(
import_react_autosize_textarea.default,
{
className: "block-editor-block-list__block-html-textarea",
value: html,
onBlur: onChange,
onChange: (event) => setHtml(event.target.value)
}
);
}
var block_html_default = BlockHTML;
// packages/block-editor/build-module/components/block-list/use-block-props/index.mjs
var import_element30 = __toESM(require_element(), 1);
var import_i18n31 = __toESM(require_i18n(), 1);
var import_blocks23 = __toESM(require_blocks(), 1);
var import_compose16 = __toESM(require_compose(), 1);
var import_warning4 = __toESM(require_warning(), 1);
// node_modules/@react-spring/rafz/dist/react-spring-rafz.esm.js
var updateQueue = makeQueue();
var raf = (fn) => schedule(fn, updateQueue);
var writeQueue = makeQueue();
raf.write = (fn) => schedule(fn, writeQueue);
var onStartQueue = makeQueue();
raf.onStart = (fn) => schedule(fn, onStartQueue);
var onFrameQueue = makeQueue();
raf.onFrame = (fn) => schedule(fn, onFrameQueue);
var onFinishQueue = makeQueue();
raf.onFinish = (fn) => schedule(fn, onFinishQueue);
var timeouts = [];
raf.setTimeout = (handler, ms) => {
let time = raf.now() + ms;
let cancel = () => {
let i2 = timeouts.findIndex((t3) => t3.cancel == cancel);
if (~i2) timeouts.splice(i2, 1);
pendingCount -= ~i2 ? 1 : 0;
};
let timeout = {
time,
handler,
cancel
};
timeouts.splice(findTimeout(time), 0, timeout);
pendingCount += 1;
start();
return timeout;
};
var findTimeout = (time) => ~(~timeouts.findIndex((t3) => t3.time > time) || ~timeouts.length);
raf.cancel = (fn) => {
onStartQueue.delete(fn);
onFrameQueue.delete(fn);
onFinishQueue.delete(fn);
updateQueue.delete(fn);
writeQueue.delete(fn);
};
raf.sync = (fn) => {
sync = true;
raf.batchedUpdates(fn);
sync = false;
};
raf.throttle = (fn) => {
let lastArgs;
function queuedFn() {
try {
fn(...lastArgs);
} finally {
lastArgs = null;
}
}
function throttled(...args) {
lastArgs = args;
raf.onStart(queuedFn);
}
throttled.handler = fn;
throttled.cancel = () => {
onStartQueue.delete(queuedFn);
lastArgs = null;
};
return throttled;
};
var nativeRaf = typeof window != "undefined" ? window.requestAnimationFrame : () => {
};
raf.use = (impl) => nativeRaf = impl;
raf.now = typeof performance != "undefined" ? () => performance.now() : Date.now;
raf.batchedUpdates = (fn) => fn();
raf.catch = console.error;
raf.frameLoop = "always";
raf.advance = () => {
if (raf.frameLoop !== "demand") {
console.warn("Cannot call the manual advancement of rafz whilst frameLoop is not set as demand");
} else {
update();
}
};
var ts = -1;
var pendingCount = 0;
var sync = false;
function schedule(fn, queue) {
if (sync) {
queue.delete(fn);
fn(0);
} else {
queue.add(fn);
start();
}
}
function start() {
if (ts < 0) {
ts = 0;
if (raf.frameLoop !== "demand") {
nativeRaf(loop);
}
}
}
function stop() {
ts = -1;
}
function loop() {
if (~ts) {
nativeRaf(loop);
raf.batchedUpdates(update);
}
}
function update() {
let prevTs = ts;
ts = raf.now();
let count = findTimeout(ts);
if (count) {
eachSafely(timeouts.splice(0, count), (t3) => t3.handler());
pendingCount -= count;
}
if (!pendingCount) {
stop();
return;
}
onStartQueue.flush();
updateQueue.flush(prevTs ? Math.min(64, ts - prevTs) : 16.667);
onFrameQueue.flush();
writeQueue.flush();
onFinishQueue.flush();
}
function makeQueue() {
let next = /* @__PURE__ */ new Set();
let current = next;
return {
add(fn) {
pendingCount += current == next && !next.has(fn) ? 1 : 0;
next.add(fn);
},
delete(fn) {
pendingCount -= current == next && next.has(fn) ? 1 : 0;
return next.delete(fn);
},
flush(arg) {
if (current.size) {
next = /* @__PURE__ */ new Set();
pendingCount -= current.size;
eachSafely(current, (fn) => fn(arg) && next.add(fn));
pendingCount += next.size;
current = next;
}
}
};
}
function eachSafely(values, each2) {
values.forEach((value) => {
try {
each2(value);
} catch (e2) {
raf.catch(e2);
}
});
}
// node_modules/@react-spring/shared/dist/react-spring-shared.esm.js
var import_react = __toESM(require_react());
function noop3() {
}
var defineHidden = (obj, key, value) => Object.defineProperty(obj, key, {
value,
writable: true,
configurable: true
});
var is = {
arr: Array.isArray,
obj: (a2) => !!a2 && a2.constructor.name === "Object",
fun: (a2) => typeof a2 === "function",
str: (a2) => typeof a2 === "string",
num: (a2) => typeof a2 === "number",
und: (a2) => a2 === void 0
};
function isEqual(a2, b2) {
if (is.arr(a2)) {
if (!is.arr(b2) || a2.length !== b2.length) return false;
for (let i2 = 0; i2 < a2.length; i2++) {
if (a2[i2] !== b2[i2]) return false;
}
return true;
}
return a2 === b2;
}
var each = (obj, fn) => obj.forEach(fn);
function eachProp(obj, fn, ctx2) {
if (is.arr(obj)) {
for (let i2 = 0; i2 < obj.length; i2++) {
fn.call(ctx2, obj[i2], `${i2}`);
}
return;
}
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
fn.call(ctx2, obj[key], key);
}
}
}
var toArray = (a2) => is.und(a2) ? [] : is.arr(a2) ? a2 : [a2];
function flush(queue, iterator) {
if (queue.size) {
const items = Array.from(queue);
queue.clear();
each(items, iterator);
}
}
var flushCalls = (queue, ...args) => flush(queue, (fn) => fn(...args));
var isSSR = () => typeof window === "undefined" || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent);
var createStringInterpolator$1;
var to;
var colors$1 = null;
var skipAnimation = false;
var willAdvance = noop3;
var assign = (globals2) => {
if (globals2.to) to = globals2.to;
if (globals2.now) raf.now = globals2.now;
if (globals2.colors !== void 0) colors$1 = globals2.colors;
if (globals2.skipAnimation != null) skipAnimation = globals2.skipAnimation;
if (globals2.createStringInterpolator) createStringInterpolator$1 = globals2.createStringInterpolator;
if (globals2.requestAnimationFrame) raf.use(globals2.requestAnimationFrame);
if (globals2.batchedUpdates) raf.batchedUpdates = globals2.batchedUpdates;
if (globals2.willAdvance) willAdvance = globals2.willAdvance;
if (globals2.frameLoop) raf.frameLoop = globals2.frameLoop;
};
var globals = /* @__PURE__ */ Object.freeze({
__proto__: null,
get createStringInterpolator() {
return createStringInterpolator$1;
},
get to() {
return to;
},
get colors() {
return colors$1;
},
get skipAnimation() {
return skipAnimation;
},
get willAdvance() {
return willAdvance;
},
assign
});
var startQueue = /* @__PURE__ */ new Set();
var currentFrame = [];
var prevFrame = [];
var priority = 0;
var frameLoop = {
get idle() {
return !startQueue.size && !currentFrame.length;
},
start(animation) {
if (priority > animation.priority) {
startQueue.add(animation);
raf.onStart(flushStartQueue);
} else {
startSafely(animation);
raf(advance);
}
},
advance,
sort(animation) {
if (priority) {
raf.onFrame(() => frameLoop.sort(animation));
} else {
const prevIndex = currentFrame.indexOf(animation);
if (~prevIndex) {
currentFrame.splice(prevIndex, 1);
startUnsafely(animation);
}
}
},
clear() {
currentFrame = [];
startQueue.clear();
}
};
function flushStartQueue() {
startQueue.forEach(startSafely);
startQueue.clear();
raf(advance);
}
function startSafely(animation) {
if (!currentFrame.includes(animation)) startUnsafely(animation);
}
function startUnsafely(animation) {
currentFrame.splice(findIndex(currentFrame, (other) => other.priority > animation.priority), 0, animation);
}
function advance(dt) {
const nextFrame = prevFrame;
for (let i2 = 0; i2 < currentFrame.length; i2++) {
const animation = currentFrame[i2];
priority = animation.priority;
if (!animation.idle) {
willAdvance(animation);
animation.advance(dt);
if (!animation.idle) {
nextFrame.push(animation);
}
}
}
priority = 0;
prevFrame = currentFrame;
prevFrame.length = 0;
currentFrame = nextFrame;
return currentFrame.length > 0;
}
function findIndex(arr, test) {
const index2 = arr.findIndex(test);
return index2 < 0 ? arr.length : index2;
}
var colors = {
transparent: 0,
aliceblue: 4042850303,
antiquewhite: 4209760255,
aqua: 16777215,
aquamarine: 2147472639,
azure: 4043309055,
beige: 4126530815,
bisque: 4293182719,
black: 255,
blanchedalmond: 4293643775,
blue: 65535,
blueviolet: 2318131967,
brown: 2771004159,
burlywood: 3736635391,
burntsienna: 3934150143,
cadetblue: 1604231423,
chartreuse: 2147418367,
chocolate: 3530104575,
coral: 4286533887,
cornflowerblue: 1687547391,
cornsilk: 4294499583,
crimson: 3692313855,
cyan: 16777215,
darkblue: 35839,
darkcyan: 9145343,
darkgoldenrod: 3095792639,
darkgray: 2846468607,
darkgreen: 6553855,
darkgrey: 2846468607,
darkkhaki: 3182914559,
darkmagenta: 2332068863,
darkolivegreen: 1433087999,
darkorange: 4287365375,
darkorchid: 2570243327,
darkred: 2332033279,
darksalmon: 3918953215,
darkseagreen: 2411499519,
darkslateblue: 1211993087,
darkslategray: 793726975,
darkslategrey: 793726975,
darkturquoise: 13554175,
darkviolet: 2483082239,
deeppink: 4279538687,
deepskyblue: 12582911,
dimgray: 1768516095,
dimgrey: 1768516095,
dodgerblue: 512819199,
firebrick: 2988581631,
floralwhite: 4294635775,
forestgreen: 579543807,
fuchsia: 4278255615,
gainsboro: 3705462015,
ghostwhite: 4177068031,
gold: 4292280575,
goldenrod: 3668254975,
gray: 2155905279,
green: 8388863,
greenyellow: 2919182335,
grey: 2155905279,
honeydew: 4043305215,
hotpink: 4285117695,
indianred: 3445382399,
indigo: 1258324735,
ivory: 4294963455,
khaki: 4041641215,
lavender: 3873897215,
lavenderblush: 4293981695,
lawngreen: 2096890111,
lemonchiffon: 4294626815,
lightblue: 2916673279,
lightcoral: 4034953471,
lightcyan: 3774873599,
lightgoldenrodyellow: 4210742015,
lightgray: 3553874943,
lightgreen: 2431553791,
lightgrey: 3553874943,
lightpink: 4290167295,
lightsalmon: 4288707327,
lightseagreen: 548580095,
lightskyblue: 2278488831,
lightslategray: 2005441023,
lightslategrey: 2005441023,
lightsteelblue: 2965692159,
lightyellow: 4294959359,
lime: 16711935,
limegreen: 852308735,
linen: 4210091775,
magenta: 4278255615,
maroon: 2147483903,
mediumaquamarine: 1724754687,
mediumblue: 52735,
mediumorchid: 3126187007,
mediumpurple: 2473647103,
mediumseagreen: 1018393087,
mediumslateblue: 2070474495,
mediumspringgreen: 16423679,
mediumturquoise: 1221709055,
mediumvioletred: 3340076543,
midnightblue: 421097727,
mintcream: 4127193855,
mistyrose: 4293190143,
moccasin: 4293178879,
navajowhite: 4292783615,
navy: 33023,
oldlace: 4260751103,
olive: 2155872511,
olivedrab: 1804477439,
orange: 4289003775,
orangered: 4282712319,
orchid: 3664828159,
palegoldenrod: 4008225535,
palegreen: 2566625535,
paleturquoise: 2951671551,
palevioletred: 3681588223,
papayawhip: 4293907967,
peachpuff: 4292524543,
peru: 3448061951,
pink: 4290825215,
plum: 3718307327,
powderblue: 2967529215,
purple: 2147516671,
rebeccapurple: 1714657791,
red: 4278190335,
rosybrown: 3163525119,
royalblue: 1097458175,
saddlebrown: 2336560127,
salmon: 4202722047,
sandybrown: 4104413439,
seagreen: 780883967,
seashell: 4294307583,
sienna: 2689740287,
silver: 3233857791,
skyblue: 2278484991,
slateblue: 1784335871,
slategray: 1887473919,
slategrey: 1887473919,
snow: 4294638335,
springgreen: 16744447,
steelblue: 1182971135,
tan: 3535047935,
teal: 8421631,
thistle: 3636451583,
tomato: 4284696575,
turquoise: 1088475391,
violet: 4001558271,
wheat: 4125012991,
white: 4294967295,
whitesmoke: 4126537215,
yellow: 4294902015,
yellowgreen: 2597139199
};
var NUMBER = "[-+]?\\d*\\.?\\d+";
var PERCENTAGE = NUMBER + "%";
function call(...parts) {
return "\\(\\s*(" + parts.join(")\\s*,\\s*(") + ")\\s*\\)";
}
var rgb = new RegExp("rgb" + call(NUMBER, NUMBER, NUMBER));
var rgba = new RegExp("rgba" + call(NUMBER, NUMBER, NUMBER, NUMBER));
var hsl = new RegExp("hsl" + call(NUMBER, PERCENTAGE, PERCENTAGE));
var hsla = new RegExp("hsla" + call(NUMBER, PERCENTAGE, PERCENTAGE, NUMBER));
var hex3 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/;
var hex4 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/;
var hex6 = /^#([0-9a-fA-F]{6})$/;
var hex8 = /^#([0-9a-fA-F]{8})$/;
function normalizeColor(color) {
let match2;
if (typeof color === "number") {
return color >>> 0 === color && color >= 0 && color <= 4294967295 ? color : null;
}
if (match2 = hex6.exec(color)) return parseInt(match2[1] + "ff", 16) >>> 0;
if (colors$1 && colors$1[color] !== void 0) {
return colors$1[color];
}
if (match2 = rgb.exec(color)) {
return (parse255(match2[1]) << 24 | parse255(match2[2]) << 16 | parse255(match2[3]) << 8 | 255) >>> 0;
}
if (match2 = rgba.exec(color)) {
return (parse255(match2[1]) << 24 | parse255(match2[2]) << 16 | parse255(match2[3]) << 8 | parse1(match2[4])) >>> 0;
}
if (match2 = hex3.exec(color)) {
return parseInt(match2[1] + match2[1] + match2[2] + match2[2] + match2[3] + match2[3] + "ff", 16) >>> 0;
}
if (match2 = hex8.exec(color)) return parseInt(match2[1], 16) >>> 0;
if (match2 = hex4.exec(color)) {
return parseInt(match2[1] + match2[1] + match2[2] + match2[2] + match2[3] + match2[3] + match2[4] + match2[4], 16) >>> 0;
}
if (match2 = hsl.exec(color)) {
return (hslToRgb(parse360(match2[1]), parsePercentage(match2[2]), parsePercentage(match2[3])) | 255) >>> 0;
}
if (match2 = hsla.exec(color)) {
return (hslToRgb(parse360(match2[1]), parsePercentage(match2[2]), parsePercentage(match2[3])) | parse1(match2[4])) >>> 0;
}
return null;
}
function hue2rgb(p2, q, t3) {
if (t3 < 0) t3 += 1;
if (t3 > 1) t3 -= 1;
if (t3 < 1 / 6) return p2 + (q - p2) * 6 * t3;
if (t3 < 1 / 2) return q;
if (t3 < 2 / 3) return p2 + (q - p2) * (2 / 3 - t3) * 6;
return p2;
}
function hslToRgb(h2, s2, l2) {
const q = l2 < 0.5 ? l2 * (1 + s2) : l2 + s2 - l2 * s2;
const p2 = 2 * l2 - q;
const r3 = hue2rgb(p2, q, h2 + 1 / 3);
const g2 = hue2rgb(p2, q, h2);
const b2 = hue2rgb(p2, q, h2 - 1 / 3);
return Math.round(r3 * 255) << 24 | Math.round(g2 * 255) << 16 | Math.round(b2 * 255) << 8;
}
function parse255(str) {
const int = parseInt(str, 10);
if (int < 0) return 0;
if (int > 255) return 255;
return int;
}
function parse360(str) {
const int = parseFloat(str);
return (int % 360 + 360) % 360 / 360;
}
function parse1(str) {
const num = parseFloat(str);
if (num < 0) return 0;
if (num > 1) return 255;
return Math.round(num * 255);
}
function parsePercentage(str) {
const int = parseFloat(str);
if (int < 0) return 0;
if (int > 100) return 1;
return int / 100;
}
function colorToRgba(input) {
let int32Color = normalizeColor(input);
if (int32Color === null) return input;
int32Color = int32Color || 0;
let r3 = (int32Color & 4278190080) >>> 24;
let g2 = (int32Color & 16711680) >>> 16;
let b2 = (int32Color & 65280) >>> 8;
let a2 = (int32Color & 255) / 255;
return `rgba(${r3}, ${g2}, ${b2}, ${a2})`;
}
var createInterpolator = (range2, output, extrapolate) => {
if (is.fun(range2)) {
return range2;
}
if (is.arr(range2)) {
return createInterpolator({
range: range2,
output,
extrapolate
});
}
if (is.str(range2.output[0])) {
return createStringInterpolator$1(range2);
}
const config2 = range2;
const outputRange = config2.output;
const inputRange = config2.range || [0, 1];
const extrapolateLeft = config2.extrapolateLeft || config2.extrapolate || "extend";
const extrapolateRight = config2.extrapolateRight || config2.extrapolate || "extend";
const easing = config2.easing || ((t3) => t3);
return (input) => {
const range3 = findRange(input, inputRange);
return interpolate(input, inputRange[range3], inputRange[range3 + 1], outputRange[range3], outputRange[range3 + 1], easing, extrapolateLeft, extrapolateRight, config2.map);
};
};
function interpolate(input, inputMin, inputMax, outputMin, outputMax, easing, extrapolateLeft, extrapolateRight, map) {
let result = map ? map(input) : input;
if (result < inputMin) {
if (extrapolateLeft === "identity") return result;
else if (extrapolateLeft === "clamp") result = inputMin;
}
if (result > inputMax) {
if (extrapolateRight === "identity") return result;
else if (extrapolateRight === "clamp") result = inputMax;
}
if (outputMin === outputMax) return outputMin;
if (inputMin === inputMax) return input <= inputMin ? outputMin : outputMax;
if (inputMin === -Infinity) result = -result;
else if (inputMax === Infinity) result = result - inputMin;
else result = (result - inputMin) / (inputMax - inputMin);
result = easing(result);
if (outputMin === -Infinity) result = -result;
else if (outputMax === Infinity) result = result + outputMin;
else result = result * (outputMax - outputMin) + outputMin;
return result;
}
function findRange(input, inputRange) {
for (var i2 = 1; i2 < inputRange.length - 1; ++i2) if (inputRange[i2] >= input) break;
return i2 - 1;
}
function _extends() {
_extends = Object.assign ? Object.assign.bind() : function(target) {
for (var i2 = 1; i2 < arguments.length; i2++) {
var source = arguments[i2];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
var $get = /* @__PURE__ */ Symbol.for("FluidValue.get");
var $observers = /* @__PURE__ */ Symbol.for("FluidValue.observers");
var hasFluidValue = (arg) => Boolean(arg && arg[$get]);
var getFluidValue = (arg) => arg && arg[$get] ? arg[$get]() : arg;
var getFluidObservers = (target) => target[$observers] || null;
function callFluidObserver(observer, event) {
if (observer.eventObserved) {
observer.eventObserved(event);
} else {
observer(event);
}
}
function callFluidObservers(target, event) {
let observers = target[$observers];
if (observers) {
observers.forEach((observer) => {
callFluidObserver(observer, event);
});
}
}
var FluidValue = class {
constructor(get) {
this[$get] = void 0;
this[$observers] = void 0;
if (!get && !(get = this.get)) {
throw Error("Unknown getter");
}
setFluidGetter(this, get);
}
};
var setFluidGetter = (target, get) => setHidden(target, $get, get);
function addFluidObserver(target, observer) {
if (target[$get]) {
let observers = target[$observers];
if (!observers) {
setHidden(target, $observers, observers = /* @__PURE__ */ new Set());
}
if (!observers.has(observer)) {
observers.add(observer);
if (target.observerAdded) {
target.observerAdded(observers.size, observer);
}
}
}
return observer;
}
function removeFluidObserver(target, observer) {
let observers = target[$observers];
if (observers && observers.has(observer)) {
const count = observers.size - 1;
if (count) {
observers.delete(observer);
} else {
target[$observers] = null;
}
if (target.observerRemoved) {
target.observerRemoved(count, observer);
}
}
}
var setHidden = (target, key, value) => Object.defineProperty(target, key, {
value,
writable: true,
configurable: true
});
var numberRegex = /[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
var colorRegex = /(#(?:[0-9a-f]{2}){2,4}|(#[0-9a-f]{3})|(rgb|hsl)a?\((-?\d+%?[,\s]+){2,3}\s*[\d\.]+%?\))/gi;
var unitRegex = new RegExp(`(${numberRegex.source})(%|[a-z]+)`, "i");
var rgbaRegex = /rgba\(([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+)\)/gi;
var cssVariableRegex = /var\((--[a-zA-Z0-9-_]+),? ?([a-zA-Z0-9 ()%#.,-]+)?\)/;
var variableToRgba = (input) => {
const [token, fallback] = parseCSSVariable(input);
if (!token || isSSR()) {
return input;
}
const value = window.getComputedStyle(document.documentElement).getPropertyValue(token);
if (value) {
return value.trim();
} else if (fallback && fallback.startsWith("--")) {
const _value = window.getComputedStyle(document.documentElement).getPropertyValue(fallback);
if (_value) {
return _value;
} else {
return input;
}
} else if (fallback && cssVariableRegex.test(fallback)) {
return variableToRgba(fallback);
} else if (fallback) {
return fallback;
}
return input;
};
var parseCSSVariable = (current) => {
const match2 = cssVariableRegex.exec(current);
if (!match2) return [,];
const [, token, fallback] = match2;
return [token, fallback];
};
var namedColorRegex;
var rgbaRound = (_, p1, p2, p3, p4) => `rgba(${Math.round(p1)}, ${Math.round(p2)}, ${Math.round(p3)}, ${p4})`;
var createStringInterpolator = (config2) => {
if (!namedColorRegex) namedColorRegex = colors$1 ? new RegExp(`(${Object.keys(colors$1).join("|")})(?!\\w)`, "g") : /^\b$/;
const output = config2.output.map((value) => {
return getFluidValue(value).replace(cssVariableRegex, variableToRgba).replace(colorRegex, colorToRgba).replace(namedColorRegex, colorToRgba);
});
const keyframes = output.map((value) => value.match(numberRegex).map(Number));
const outputRanges = keyframes[0].map((_, i2) => keyframes.map((values) => {
if (!(i2 in values)) {
throw Error('The arity of each "output" value must be equal');
}
return values[i2];
}));
const interpolators = outputRanges.map((output2) => createInterpolator(_extends({}, config2, {
output: output2
})));
return (input) => {
var _output$find;
const missingUnit = !unitRegex.test(output[0]) && ((_output$find = output.find((value) => unitRegex.test(value))) == null ? void 0 : _output$find.replace(numberRegex, ""));
let i2 = 0;
return output[0].replace(numberRegex, () => `${interpolators[i2++](input)}${missingUnit || ""}`).replace(rgbaRegex, rgbaRound);
};
};
var prefix = "react-spring: ";
var once = (fn) => {
const func = fn;
let called = false;
if (typeof func != "function") {
throw new TypeError(`${prefix}once requires a function parameter`);
}
return (...args) => {
if (!called) {
func(...args);
called = true;
}
};
};
var warnInterpolate = once(console.warn);
function deprecateInterpolate() {
warnInterpolate(`${prefix}The "interpolate" function is deprecated in v9 (use "to" instead)`);
}
var warnDirectCall = once(console.warn);
function isAnimatedString(value) {
return is.str(value) && (value[0] == "#" || /\d/.test(value) || !isSSR() && cssVariableRegex.test(value) || value in (colors$1 || {}));
}
var useIsomorphicLayoutEffect = isSSR() ? import_react.useEffect : import_react.useLayoutEffect;
var useIsMounted = () => {
const isMounted = (0, import_react.useRef)(false);
useIsomorphicLayoutEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
}, []);
return isMounted;
};
function useForceUpdate() {
const update4 = (0, import_react.useState)()[1];
const isMounted = useIsMounted();
return () => {
if (isMounted.current) {
update4(Math.random());
}
};
}
function useMemoOne(getResult, inputs) {
const [initial2] = (0, import_react.useState)(() => ({
inputs,
result: getResult()
}));
const committed = (0, import_react.useRef)();
const prevCache = committed.current;
let cache = prevCache;
if (cache) {
const useCache = Boolean(inputs && cache.inputs && areInputsEqual(inputs, cache.inputs));
if (!useCache) {
cache = {
inputs,
result: getResult()
};
}
} else {
cache = initial2;
}
(0, import_react.useEffect)(() => {
committed.current = cache;
if (prevCache == initial2) {
initial2.inputs = initial2.result = void 0;
}
}, [cache]);
return cache.result;
}
function areInputsEqual(next, prev) {
if (next.length !== prev.length) {
return false;
}
for (let i2 = 0; i2 < next.length; i2++) {
if (next[i2] !== prev[i2]) {
return false;
}
}
return true;
}
var useOnce = (effect) => (0, import_react.useEffect)(effect, emptyDeps);
var emptyDeps = [];
// node_modules/@react-spring/core/dist/react-spring-core.esm.js
var React2 = __toESM(require_react());
var import_react3 = __toESM(require_react());
// node_modules/@react-spring/animated/dist/react-spring-animated.esm.js
var React = __toESM(require_react());
var import_react2 = __toESM(require_react());
var $node = /* @__PURE__ */ Symbol.for("Animated:node");
var isAnimated = (value) => !!value && value[$node] === value;
var getAnimated = (owner) => owner && owner[$node];
var setAnimated = (owner, node) => defineHidden(owner, $node, node);
var getPayload = (owner) => owner && owner[$node] && owner[$node].getPayload();
var Animated = class {
constructor() {
this.payload = void 0;
setAnimated(this, this);
}
getPayload() {
return this.payload || [];
}
};
var AnimatedValue = class _AnimatedValue extends Animated {
constructor(_value) {
super();
this.done = true;
this.elapsedTime = void 0;
this.lastPosition = void 0;
this.lastVelocity = void 0;
this.v0 = void 0;
this.durationProgress = 0;
this._value = _value;
if (is.num(this._value)) {
this.lastPosition = this._value;
}
}
static create(value) {
return new _AnimatedValue(value);
}
getPayload() {
return [this];
}
getValue() {
return this._value;
}
setValue(value, step) {
if (is.num(value)) {
this.lastPosition = value;
if (step) {
value = Math.round(value / step) * step;
if (this.done) {
this.lastPosition = value;
}
}
}
if (this._value === value) {
return false;
}
this._value = value;
return true;
}
reset() {
const {
done
} = this;
this.done = false;
if (is.num(this._value)) {
this.elapsedTime = 0;
this.durationProgress = 0;
this.lastPosition = this._value;
if (done) this.lastVelocity = null;
this.v0 = null;
}
}
};
var AnimatedString = class _AnimatedString extends AnimatedValue {
constructor(value) {
super(0);
this._string = null;
this._toString = void 0;
this._toString = createInterpolator({
output: [value, value]
});
}
static create(value) {
return new _AnimatedString(value);
}
getValue() {
let value = this._string;
return value == null ? this._string = this._toString(this._value) : value;
}
setValue(value) {
if (is.str(value)) {
if (value == this._string) {
return false;
}
this._string = value;
this._value = 1;
} else if (super.setValue(value)) {
this._string = null;
} else {
return false;
}
return true;
}
reset(goal) {
if (goal) {
this._toString = createInterpolator({
output: [this.getValue(), goal]
});
}
this._value = 0;
super.reset();
}
};
var TreeContext = {
dependencies: null
};
var AnimatedObject = class extends Animated {
constructor(source) {
super();
this.source = source;
this.setValue(source);
}
getValue(animated2) {
const values = {};
eachProp(this.source, (source, key) => {
if (isAnimated(source)) {
values[key] = source.getValue(animated2);
} else if (hasFluidValue(source)) {
values[key] = getFluidValue(source);
} else if (!animated2) {
values[key] = source;
}
});
return values;
}
setValue(source) {
this.source = source;
this.payload = this._makePayload(source);
}
reset() {
if (this.payload) {
each(this.payload, (node) => node.reset());
}
}
_makePayload(source) {
if (source) {
const payload = /* @__PURE__ */ new Set();
eachProp(source, this._addToPayload, payload);
return Array.from(payload);
}
}
_addToPayload(source) {
if (TreeContext.dependencies && hasFluidValue(source)) {
TreeContext.dependencies.add(source);
}
const payload = getPayload(source);
if (payload) {
each(payload, (node) => this.add(node));
}
}
};
var AnimatedArray = class _AnimatedArray extends AnimatedObject {
constructor(source) {
super(source);
}
static create(source) {
return new _AnimatedArray(source);
}
getValue() {
return this.source.map((node) => node.getValue());
}
setValue(source) {
const payload = this.getPayload();
if (source.length == payload.length) {
return payload.map((node, i2) => node.setValue(source[i2])).some(Boolean);
}
super.setValue(source.map(makeAnimated));
return true;
}
};
function makeAnimated(value) {
const nodeType = isAnimatedString(value) ? AnimatedString : AnimatedValue;
return nodeType.create(value);
}
function getAnimatedType(value) {
const parentNode = getAnimated(value);
return parentNode ? parentNode.constructor : is.arr(value) ? AnimatedArray : isAnimatedString(value) ? AnimatedString : AnimatedValue;
}
function _extends2() {
_extends2 = Object.assign ? Object.assign.bind() : function(target) {
for (var i2 = 1; i2 < arguments.length; i2++) {
var source = arguments[i2];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends2.apply(this, arguments);
}
var withAnimated = (Component6, host2) => {
const hasInstance = !is.fun(Component6) || Component6.prototype && Component6.prototype.isReactComponent;
return (0, import_react2.forwardRef)((givenProps, givenRef) => {
const instanceRef = (0, import_react2.useRef)(null);
const ref = hasInstance && (0, import_react2.useCallback)((value) => {
instanceRef.current = updateRef(givenRef, value);
}, [givenRef]);
const [props, deps] = getAnimatedState(givenProps, host2);
const forceUpdate = useForceUpdate();
const callback = () => {
const instance = instanceRef.current;
if (hasInstance && !instance) {
return;
}
const didUpdate = instance ? host2.applyAnimatedValues(instance, props.getValue(true)) : false;
if (didUpdate === false) {
forceUpdate();
}
};
const observer = new PropsObserver(callback, deps);
const observerRef = (0, import_react2.useRef)();
useIsomorphicLayoutEffect(() => {
observerRef.current = observer;
each(deps, (dep) => addFluidObserver(dep, observer));
return () => {
if (observerRef.current) {
each(observerRef.current.deps, (dep) => removeFluidObserver(dep, observerRef.current));
raf.cancel(observerRef.current.update);
}
};
});
(0, import_react2.useEffect)(callback, []);
useOnce(() => () => {
const observer2 = observerRef.current;
each(observer2.deps, (dep) => removeFluidObserver(dep, observer2));
});
const usedProps = host2.getComponentProps(props.getValue());
return React.createElement(Component6, _extends2({}, usedProps, {
ref
}));
});
};
var PropsObserver = class {
constructor(update4, deps) {
this.update = update4;
this.deps = deps;
}
eventObserved(event) {
if (event.type == "change") {
raf.write(this.update);
}
}
};
function getAnimatedState(props, host2) {
const dependencies = /* @__PURE__ */ new Set();
TreeContext.dependencies = dependencies;
if (props.style) props = _extends2({}, props, {
style: host2.createAnimatedStyle(props.style)
});
props = new AnimatedObject(props);
TreeContext.dependencies = null;
return [props, dependencies];
}
function updateRef(ref, value) {
if (ref) {
if (is.fun(ref)) ref(value);
else ref.current = value;
}
return value;
}
var cacheKey = /* @__PURE__ */ Symbol.for("AnimatedComponent");
var createHost = (components, {
applyAnimatedValues: _applyAnimatedValues = () => false,
createAnimatedStyle: _createAnimatedStyle = (style) => new AnimatedObject(style),
getComponentProps: _getComponentProps = (props) => props
} = {}) => {
const hostConfig = {
applyAnimatedValues: _applyAnimatedValues,
createAnimatedStyle: _createAnimatedStyle,
getComponentProps: _getComponentProps
};
const animated2 = (Component6) => {
const displayName = getDisplayName(Component6) || "Anonymous";
if (is.str(Component6)) {
Component6 = animated2[Component6] || (animated2[Component6] = withAnimated(Component6, hostConfig));
} else {
Component6 = Component6[cacheKey] || (Component6[cacheKey] = withAnimated(Component6, hostConfig));
}
Component6.displayName = `Animated(${displayName})`;
return Component6;
};
eachProp(components, (Component6, key) => {
if (is.arr(components)) {
key = getDisplayName(Component6);
}
animated2[key] = animated2(Component6);
});
return {
animated: animated2
};
};
var getDisplayName = (arg) => is.str(arg) ? arg : arg && is.str(arg.displayName) ? arg.displayName : is.fun(arg) && arg.name || null;
// node_modules/@react-spring/core/dist/react-spring-core.esm.js
function _extends3() {
_extends3 = Object.assign ? Object.assign.bind() : function(target) {
for (var i2 = 1; i2 < arguments.length; i2++) {
var source = arguments[i2];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends3.apply(this, arguments);
}
function callProp(value, ...args) {
return is.fun(value) ? value(...args) : value;
}
var matchProp = (value, key) => value === true || !!(key && value && (is.fun(value) ? value(key) : toArray(value).includes(key)));
var resolveProp = (prop, key) => is.obj(prop) ? key && prop[key] : prop;
var getDefaultProp = (props, key) => props.default === true ? props[key] : props.default ? props.default[key] : void 0;
var noopTransform = (value) => value;
var getDefaultProps = (props, transform = noopTransform) => {
let keys = DEFAULT_PROPS;
if (props.default && props.default !== true) {
props = props.default;
keys = Object.keys(props);
}
const defaults2 = {};
for (const key of keys) {
const value = transform(props[key], key);
if (!is.und(value)) {
defaults2[key] = value;
}
}
return defaults2;
};
var DEFAULT_PROPS = ["config", "onProps", "onStart", "onChange", "onPause", "onResume", "onRest"];
var RESERVED_PROPS = {
config: 1,
from: 1,
to: 1,
ref: 1,
loop: 1,
reset: 1,
pause: 1,
cancel: 1,
reverse: 1,
immediate: 1,
default: 1,
delay: 1,
onProps: 1,
onStart: 1,
onChange: 1,
onPause: 1,
onResume: 1,
onRest: 1,
onResolve: 1,
items: 1,
trail: 1,
sort: 1,
expires: 1,
initial: 1,
enter: 1,
update: 1,
leave: 1,
children: 1,
onDestroyed: 1,
keys: 1,
callId: 1,
parentId: 1
};
function getForwardProps(props) {
const forward = {};
let count = 0;
eachProp(props, (value, prop) => {
if (!RESERVED_PROPS[prop]) {
forward[prop] = value;
count++;
}
});
if (count) {
return forward;
}
}
function inferTo(props) {
const to2 = getForwardProps(props);
if (to2) {
const out = {
to: to2
};
eachProp(props, (val, key) => key in to2 || (out[key] = val));
return out;
}
return _extends3({}, props);
}
function computeGoal(value) {
value = getFluidValue(value);
return is.arr(value) ? value.map(computeGoal) : isAnimatedString(value) ? globals.createStringInterpolator({
range: [0, 1],
output: [value, value]
})(1) : value;
}
function isAsyncTo(to2) {
return is.fun(to2) || is.arr(to2) && is.obj(to2[0]);
}
var config = {
default: {
tension: 170,
friction: 26
},
gentle: {
tension: 120,
friction: 14
},
wobbly: {
tension: 180,
friction: 12
},
stiff: {
tension: 210,
friction: 20
},
slow: {
tension: 280,
friction: 60
},
molasses: {
tension: 280,
friction: 120
}
};
var c1 = 1.70158;
var c2 = c1 * 1.525;
var c3 = c1 + 1;
var c4 = 2 * Math.PI / 3;
var c5 = 2 * Math.PI / 4.5;
var bounceOut = (x2) => {
const n1 = 7.5625;
const d1 = 2.75;
if (x2 < 1 / d1) {
return n1 * x2 * x2;
} else if (x2 < 2 / d1) {
return n1 * (x2 -= 1.5 / d1) * x2 + 0.75;
} else if (x2 < 2.5 / d1) {
return n1 * (x2 -= 2.25 / d1) * x2 + 0.9375;
} else {
return n1 * (x2 -= 2.625 / d1) * x2 + 0.984375;
}
};
var easings = {
linear: (x2) => x2,
easeInQuad: (x2) => x2 * x2,
easeOutQuad: (x2) => 1 - (1 - x2) * (1 - x2),
easeInOutQuad: (x2) => x2 < 0.5 ? 2 * x2 * x2 : 1 - Math.pow(-2 * x2 + 2, 2) / 2,
easeInCubic: (x2) => x2 * x2 * x2,
easeOutCubic: (x2) => 1 - Math.pow(1 - x2, 3),
easeInOutCubic: (x2) => x2 < 0.5 ? 4 * x2 * x2 * x2 : 1 - Math.pow(-2 * x2 + 2, 3) / 2,
easeInQuart: (x2) => x2 * x2 * x2 * x2,
easeOutQuart: (x2) => 1 - Math.pow(1 - x2, 4),
easeInOutQuart: (x2) => x2 < 0.5 ? 8 * x2 * x2 * x2 * x2 : 1 - Math.pow(-2 * x2 + 2, 4) / 2,
easeInQuint: (x2) => x2 * x2 * x2 * x2 * x2,
easeOutQuint: (x2) => 1 - Math.pow(1 - x2, 5),
easeInOutQuint: (x2) => x2 < 0.5 ? 16 * x2 * x2 * x2 * x2 * x2 : 1 - Math.pow(-2 * x2 + 2, 5) / 2,
easeInSine: (x2) => 1 - Math.cos(x2 * Math.PI / 2),
easeOutSine: (x2) => Math.sin(x2 * Math.PI / 2),
easeInOutSine: (x2) => -(Math.cos(Math.PI * x2) - 1) / 2,
easeInExpo: (x2) => x2 === 0 ? 0 : Math.pow(2, 10 * x2 - 10),
easeOutExpo: (x2) => x2 === 1 ? 1 : 1 - Math.pow(2, -10 * x2),
easeInOutExpo: (x2) => x2 === 0 ? 0 : x2 === 1 ? 1 : x2 < 0.5 ? Math.pow(2, 20 * x2 - 10) / 2 : (2 - Math.pow(2, -20 * x2 + 10)) / 2,
easeInCirc: (x2) => 1 - Math.sqrt(1 - Math.pow(x2, 2)),
easeOutCirc: (x2) => Math.sqrt(1 - Math.pow(x2 - 1, 2)),
easeInOutCirc: (x2) => x2 < 0.5 ? (1 - Math.sqrt(1 - Math.pow(2 * x2, 2))) / 2 : (Math.sqrt(1 - Math.pow(-2 * x2 + 2, 2)) + 1) / 2,
easeInBack: (x2) => c3 * x2 * x2 * x2 - c1 * x2 * x2,
easeOutBack: (x2) => 1 + c3 * Math.pow(x2 - 1, 3) + c1 * Math.pow(x2 - 1, 2),
easeInOutBack: (x2) => x2 < 0.5 ? Math.pow(2 * x2, 2) * ((c2 + 1) * 2 * x2 - c2) / 2 : (Math.pow(2 * x2 - 2, 2) * ((c2 + 1) * (x2 * 2 - 2) + c2) + 2) / 2,
easeInElastic: (x2) => x2 === 0 ? 0 : x2 === 1 ? 1 : -Math.pow(2, 10 * x2 - 10) * Math.sin((x2 * 10 - 10.75) * c4),
easeOutElastic: (x2) => x2 === 0 ? 0 : x2 === 1 ? 1 : Math.pow(2, -10 * x2) * Math.sin((x2 * 10 - 0.75) * c4) + 1,
easeInOutElastic: (x2) => x2 === 0 ? 0 : x2 === 1 ? 1 : x2 < 0.5 ? -(Math.pow(2, 20 * x2 - 10) * Math.sin((20 * x2 - 11.125) * c5)) / 2 : Math.pow(2, -20 * x2 + 10) * Math.sin((20 * x2 - 11.125) * c5) / 2 + 1,
easeInBounce: (x2) => 1 - bounceOut(1 - x2),
easeOutBounce: bounceOut,
easeInOutBounce: (x2) => x2 < 0.5 ? (1 - bounceOut(1 - 2 * x2)) / 2 : (1 + bounceOut(2 * x2 - 1)) / 2
};
var defaults = _extends3({}, config.default, {
mass: 1,
damping: 1,
easing: easings.linear,
clamp: false
});
var AnimationConfig = class {
constructor() {
this.tension = void 0;
this.friction = void 0;
this.frequency = void 0;
this.damping = void 0;
this.mass = void 0;
this.velocity = 0;
this.restVelocity = void 0;
this.precision = void 0;
this.progress = void 0;
this.duration = void 0;
this.easing = void 0;
this.clamp = void 0;
this.bounce = void 0;
this.decay = void 0;
this.round = void 0;
Object.assign(this, defaults);
}
};
function mergeConfig(config2, newConfig, defaultConfig) {
if (defaultConfig) {
defaultConfig = _extends3({}, defaultConfig);
sanitizeConfig(defaultConfig, newConfig);
newConfig = _extends3({}, defaultConfig, newConfig);
}
sanitizeConfig(config2, newConfig);
Object.assign(config2, newConfig);
for (const key in defaults) {
if (config2[key] == null) {
config2[key] = defaults[key];
}
}
let {
mass,
frequency,
damping
} = config2;
if (!is.und(frequency)) {
if (frequency < 0.01) frequency = 0.01;
if (damping < 0) damping = 0;
config2.tension = Math.pow(2 * Math.PI / frequency, 2) * mass;
config2.friction = 4 * Math.PI * damping * mass / frequency;
}
return config2;
}
function sanitizeConfig(config2, props) {
if (!is.und(props.decay)) {
config2.duration = void 0;
} else {
const isTensionConfig = !is.und(props.tension) || !is.und(props.friction);
if (isTensionConfig || !is.und(props.frequency) || !is.und(props.damping) || !is.und(props.mass)) {
config2.duration = void 0;
config2.decay = void 0;
}
if (isTensionConfig) {
config2.frequency = void 0;
}
}
}
var emptyArray = [];
var Animation = class {
constructor() {
this.changed = false;
this.values = emptyArray;
this.toValues = null;
this.fromValues = emptyArray;
this.to = void 0;
this.from = void 0;
this.config = new AnimationConfig();
this.immediate = false;
}
};
function scheduleProps(callId, {
key,
props,
defaultProps,
state,
actions
}) {
return new Promise((resolve, reject) => {
var _props$cancel;
let delay;
let timeout;
let cancel = matchProp((_props$cancel = props.cancel) != null ? _props$cancel : defaultProps == null ? void 0 : defaultProps.cancel, key);
if (cancel) {
onStart();
} else {
if (!is.und(props.pause)) {
state.paused = matchProp(props.pause, key);
}
let pause = defaultProps == null ? void 0 : defaultProps.pause;
if (pause !== true) {
pause = state.paused || matchProp(pause, key);
}
delay = callProp(props.delay || 0, key);
if (pause) {
state.resumeQueue.add(onResume);
actions.pause();
} else {
actions.resume();
onResume();
}
}
function onPause() {
state.resumeQueue.add(onResume);
state.timeouts.delete(timeout);
timeout.cancel();
delay = timeout.time - raf.now();
}
function onResume() {
if (delay > 0 && !globals.skipAnimation) {
state.delayed = true;
timeout = raf.setTimeout(onStart, delay);
state.pauseQueue.add(onPause);
state.timeouts.add(timeout);
} else {
onStart();
}
}
function onStart() {
if (state.delayed) {
state.delayed = false;
}
state.pauseQueue.delete(onPause);
state.timeouts.delete(timeout);
if (callId <= (state.cancelId || 0)) {
cancel = true;
}
try {
actions.start(_extends3({}, props, {
callId,
cancel
}), resolve);
} catch (err) {
reject(err);
}
}
});
}
var getCombinedResult = (target, results) => results.length == 1 ? results[0] : results.some((result) => result.cancelled) ? getCancelledResult(target.get()) : results.every((result) => result.noop) ? getNoopResult(target.get()) : getFinishedResult(target.get(), results.every((result) => result.finished));
var getNoopResult = (value) => ({
value,
noop: true,
finished: true,
cancelled: false
});
var getFinishedResult = (value, finished, cancelled = false) => ({
value,
finished,
cancelled
});
var getCancelledResult = (value) => ({
value,
cancelled: true,
finished: false
});
function runAsync(to2, props, state, target) {
const {
callId,
parentId,
onRest
} = props;
const {
asyncTo: prevTo,
promise: prevPromise
} = state;
if (!parentId && to2 === prevTo && !props.reset) {
return prevPromise;
}
return state.promise = (async () => {
state.asyncId = callId;
state.asyncTo = to2;
const defaultProps = getDefaultProps(props, (value, key) => key === "onRest" ? void 0 : value);
let preventBail;
let bail;
const bailPromise = new Promise((resolve, reject) => (preventBail = resolve, bail = reject));
const bailIfEnded = (bailSignal) => {
const bailResult = callId <= (state.cancelId || 0) && getCancelledResult(target) || callId !== state.asyncId && getFinishedResult(target, false);
if (bailResult) {
bailSignal.result = bailResult;
bail(bailSignal);
throw bailSignal;
}
};
const animate = (arg1, arg2) => {
const bailSignal = new BailSignal();
const skipAnimationSignal = new SkipAniamtionSignal();
return (async () => {
if (globals.skipAnimation) {
stopAsync(state);
skipAnimationSignal.result = getFinishedResult(target, false);
bail(skipAnimationSignal);
throw skipAnimationSignal;
}
bailIfEnded(bailSignal);
const props2 = is.obj(arg1) ? _extends3({}, arg1) : _extends3({}, arg2, {
to: arg1
});
props2.parentId = callId;
eachProp(defaultProps, (value, key) => {
if (is.und(props2[key])) {
props2[key] = value;
}
});
const result2 = await target.start(props2);
bailIfEnded(bailSignal);
if (state.paused) {
await new Promise((resume) => {
state.resumeQueue.add(resume);
});
}
return result2;
})();
};
let result;
if (globals.skipAnimation) {
stopAsync(state);
return getFinishedResult(target, false);
}
try {
let animating;
if (is.arr(to2)) {
animating = (async (queue) => {
for (const props2 of queue) {
await animate(props2);
}
})(to2);
} else {
animating = Promise.resolve(to2(animate, target.stop.bind(target)));
}
await Promise.all([animating.then(preventBail), bailPromise]);
result = getFinishedResult(target.get(), true, false);
} catch (err) {
if (err instanceof BailSignal) {
result = err.result;
} else if (err instanceof SkipAniamtionSignal) {
result = err.result;
} else {
throw err;
}
} finally {
if (callId == state.asyncId) {
state.asyncId = parentId;
state.asyncTo = parentId ? prevTo : void 0;
state.promise = parentId ? prevPromise : void 0;
}
}
if (is.fun(onRest)) {
raf.batchedUpdates(() => {
onRest(result, target, target.item);
});
}
return result;
})();
}
function stopAsync(state, cancelId) {
flush(state.timeouts, (t3) => t3.cancel());
state.pauseQueue.clear();
state.resumeQueue.clear();
state.asyncId = state.asyncTo = state.promise = void 0;
if (cancelId) state.cancelId = cancelId;
}
var BailSignal = class extends Error {
constructor() {
super("An async animation has been interrupted. You see this error because you forgot to use `await` or `.catch(...)` on its returned promise.");
this.result = void 0;
}
};
var SkipAniamtionSignal = class extends Error {
constructor() {
super("SkipAnimationSignal");
this.result = void 0;
}
};
var isFrameValue = (value) => value instanceof FrameValue;
var nextId$1 = 1;
var FrameValue = class extends FluidValue {
constructor(...args) {
super(...args);
this.id = nextId$1++;
this.key = void 0;
this._priority = 0;
}
get priority() {
return this._priority;
}
set priority(priority2) {
if (this._priority != priority2) {
this._priority = priority2;
this._onPriorityChange(priority2);
}
}
get() {
const node = getAnimated(this);
return node && node.getValue();
}
to(...args) {
return globals.to(this, args);
}
interpolate(...args) {
deprecateInterpolate();
return globals.to(this, args);
}
toJSON() {
return this.get();
}
observerAdded(count) {
if (count == 1) this._attach();
}
observerRemoved(count) {
if (count == 0) this._detach();
}
_attach() {
}
_detach() {
}
_onChange(value, idle = false) {
callFluidObservers(this, {
type: "change",
parent: this,
value,
idle
});
}
_onPriorityChange(priority2) {
if (!this.idle) {
frameLoop.sort(this);
}
callFluidObservers(this, {
type: "priority",
parent: this,
priority: priority2
});
}
};
var $P = /* @__PURE__ */ Symbol.for("SpringPhase");
var HAS_ANIMATED = 1;
var IS_ANIMATING = 2;
var IS_PAUSED = 4;
var hasAnimated = (target) => (target[$P] & HAS_ANIMATED) > 0;
var isAnimating = (target) => (target[$P] & IS_ANIMATING) > 0;
var isPaused = (target) => (target[$P] & IS_PAUSED) > 0;
var setActiveBit = (target, active) => active ? target[$P] |= IS_ANIMATING | HAS_ANIMATED : target[$P] &= ~IS_ANIMATING;
var setPausedBit = (target, paused) => paused ? target[$P] |= IS_PAUSED : target[$P] &= ~IS_PAUSED;
var SpringValue = class extends FrameValue {
constructor(arg1, arg2) {
super();
this.key = void 0;
this.animation = new Animation();
this.queue = void 0;
this.defaultProps = {};
this._state = {
paused: false,
delayed: false,
pauseQueue: /* @__PURE__ */ new Set(),
resumeQueue: /* @__PURE__ */ new Set(),
timeouts: /* @__PURE__ */ new Set()
};
this._pendingCalls = /* @__PURE__ */ new Set();
this._lastCallId = 0;
this._lastToId = 0;
this._memoizedDuration = 0;
if (!is.und(arg1) || !is.und(arg2)) {
const props = is.obj(arg1) ? _extends3({}, arg1) : _extends3({}, arg2, {
from: arg1
});
if (is.und(props.default)) {
props.default = true;
}
this.start(props);
}
}
get idle() {
return !(isAnimating(this) || this._state.asyncTo) || isPaused(this);
}
get goal() {
return getFluidValue(this.animation.to);
}
get velocity() {
const node = getAnimated(this);
return node instanceof AnimatedValue ? node.lastVelocity || 0 : node.getPayload().map((node2) => node2.lastVelocity || 0);
}
get hasAnimated() {
return hasAnimated(this);
}
get isAnimating() {
return isAnimating(this);
}
get isPaused() {
return isPaused(this);
}
get isDelayed() {
return this._state.delayed;
}
advance(dt) {
let idle = true;
let changed = false;
const anim = this.animation;
let {
config: config2,
toValues
} = anim;
const payload = getPayload(anim.to);
if (!payload && hasFluidValue(anim.to)) {
toValues = toArray(getFluidValue(anim.to));
}
anim.values.forEach((node2, i2) => {
if (node2.done) return;
const to2 = node2.constructor == AnimatedString ? 1 : payload ? payload[i2].lastPosition : toValues[i2];
let finished = anim.immediate;
let position = to2;
if (!finished) {
position = node2.lastPosition;
if (config2.tension <= 0) {
node2.done = true;
return;
}
let elapsed = node2.elapsedTime += dt;
const from = anim.fromValues[i2];
const v0 = node2.v0 != null ? node2.v0 : node2.v0 = is.arr(config2.velocity) ? config2.velocity[i2] : config2.velocity;
let velocity;
const precision = config2.precision || (from == to2 ? 5e-3 : Math.min(1, Math.abs(to2 - from) * 1e-3));
if (!is.und(config2.duration)) {
let p2 = 1;
if (config2.duration > 0) {
if (this._memoizedDuration !== config2.duration) {
this._memoizedDuration = config2.duration;
if (node2.durationProgress > 0) {
node2.elapsedTime = config2.duration * node2.durationProgress;
elapsed = node2.elapsedTime += dt;
}
}
p2 = (config2.progress || 0) + elapsed / this._memoizedDuration;
p2 = p2 > 1 ? 1 : p2 < 0 ? 0 : p2;
node2.durationProgress = p2;
}
position = from + config2.easing(p2) * (to2 - from);
velocity = (position - node2.lastPosition) / dt;
finished = p2 == 1;
} else if (config2.decay) {
const decay = config2.decay === true ? 0.998 : config2.decay;
const e2 = Math.exp(-(1 - decay) * elapsed);
position = from + v0 / (1 - decay) * (1 - e2);
finished = Math.abs(node2.lastPosition - position) <= precision;
velocity = v0 * e2;
} else {
velocity = node2.lastVelocity == null ? v0 : node2.lastVelocity;
const restVelocity = config2.restVelocity || precision / 10;
const bounceFactor = config2.clamp ? 0 : config2.bounce;
const canBounce = !is.und(bounceFactor);
const isGrowing = from == to2 ? node2.v0 > 0 : from < to2;
let isMoving;
let isBouncing = false;
const step = 1;
const numSteps = Math.ceil(dt / step);
for (let n2 = 0; n2 < numSteps; ++n2) {
isMoving = Math.abs(velocity) > restVelocity;
if (!isMoving) {
finished = Math.abs(to2 - position) <= precision;
if (finished) {
break;
}
}
if (canBounce) {
isBouncing = position == to2 || position > to2 == isGrowing;
if (isBouncing) {
velocity = -velocity * bounceFactor;
position = to2;
}
}
const springForce = -config2.tension * 1e-6 * (position - to2);
const dampingForce = -config2.friction * 1e-3 * velocity;
const acceleration = (springForce + dampingForce) / config2.mass;
velocity = velocity + acceleration * step;
position = position + velocity * step;
}
}
node2.lastVelocity = velocity;
if (Number.isNaN(position)) {
console.warn(`Got NaN while animating:`, this);
finished = true;
}
}
if (payload && !payload[i2].done) {
finished = false;
}
if (finished) {
node2.done = true;
} else {
idle = false;
}
if (node2.setValue(position, config2.round)) {
changed = true;
}
});
const node = getAnimated(this);
const currVal = node.getValue();
if (idle) {
const finalVal = getFluidValue(anim.to);
if ((currVal !== finalVal || changed) && !config2.decay) {
node.setValue(finalVal);
this._onChange(finalVal);
} else if (changed && config2.decay) {
this._onChange(currVal);
}
this._stop();
} else if (changed) {
this._onChange(currVal);
}
}
set(value) {
raf.batchedUpdates(() => {
this._stop();
this._focus(value);
this._set(value);
});
return this;
}
pause() {
this._update({
pause: true
});
}
resume() {
this._update({
pause: false
});
}
finish() {
if (isAnimating(this)) {
const {
to: to2,
config: config2
} = this.animation;
raf.batchedUpdates(() => {
this._onStart();
if (!config2.decay) {
this._set(to2, false);
}
this._stop();
});
}
return this;
}
update(props) {
const queue = this.queue || (this.queue = []);
queue.push(props);
return this;
}
start(to2, arg2) {
let queue;
if (!is.und(to2)) {
queue = [is.obj(to2) ? to2 : _extends3({}, arg2, {
to: to2
})];
} else {
queue = this.queue || [];
this.queue = [];
}
return Promise.all(queue.map((props) => {
const up = this._update(props);
return up;
})).then((results) => getCombinedResult(this, results));
}
stop(cancel) {
const {
to: to2
} = this.animation;
this._focus(this.get());
stopAsync(this._state, cancel && this._lastCallId);
raf.batchedUpdates(() => this._stop(to2, cancel));
return this;
}
reset() {
this._update({
reset: true
});
}
eventObserved(event) {
if (event.type == "change") {
this._start();
} else if (event.type == "priority") {
this.priority = event.priority + 1;
}
}
_prepareNode(props) {
const key = this.key || "";
let {
to: to2,
from
} = props;
to2 = is.obj(to2) ? to2[key] : to2;
if (to2 == null || isAsyncTo(to2)) {
to2 = void 0;
}
from = is.obj(from) ? from[key] : from;
if (from == null) {
from = void 0;
}
const range2 = {
to: to2,
from
};
if (!hasAnimated(this)) {
if (props.reverse) [to2, from] = [from, to2];
from = getFluidValue(from);
if (!is.und(from)) {
this._set(from);
} else if (!getAnimated(this)) {
this._set(to2);
}
}
return range2;
}
_update(_ref, isLoop) {
let props = _extends3({}, _ref);
const {
key,
defaultProps
} = this;
if (props.default) Object.assign(defaultProps, getDefaultProps(props, (value, prop) => /^on/.test(prop) ? resolveProp(value, key) : value));
mergeActiveFn(this, props, "onProps");
sendEvent(this, "onProps", props, this);
const range2 = this._prepareNode(props);
if (Object.isFrozen(this)) {
throw Error("Cannot animate a `SpringValue` object that is frozen. Did you forget to pass your component to `animated(...)` before animating its props?");
}
const state = this._state;
return scheduleProps(++this._lastCallId, {
key,
props,
defaultProps,
state,
actions: {
pause: () => {
if (!isPaused(this)) {
setPausedBit(this, true);
flushCalls(state.pauseQueue);
sendEvent(this, "onPause", getFinishedResult(this, checkFinished(this, this.animation.to)), this);
}
},
resume: () => {
if (isPaused(this)) {
setPausedBit(this, false);
if (isAnimating(this)) {
this._resume();
}
flushCalls(state.resumeQueue);
sendEvent(this, "onResume", getFinishedResult(this, checkFinished(this, this.animation.to)), this);
}
},
start: this._merge.bind(this, range2)
}
}).then((result) => {
if (props.loop && result.finished && !(isLoop && result.noop)) {
const nextProps = createLoopUpdate(props);
if (nextProps) {
return this._update(nextProps, true);
}
}
return result;
});
}
_merge(range2, props, resolve) {
if (props.cancel) {
this.stop(true);
return resolve(getCancelledResult(this));
}
const hasToProp = !is.und(range2.to);
const hasFromProp = !is.und(range2.from);
if (hasToProp || hasFromProp) {
if (props.callId > this._lastToId) {
this._lastToId = props.callId;
} else {
return resolve(getCancelledResult(this));
}
}
const {
key,
defaultProps,
animation: anim
} = this;
const {
to: prevTo,
from: prevFrom
} = anim;
let {
to: to2 = prevTo,
from = prevFrom
} = range2;
if (hasFromProp && !hasToProp && (!props.default || is.und(to2))) {
to2 = from;
}
if (props.reverse) [to2, from] = [from, to2];
const hasFromChanged = !isEqual(from, prevFrom);
if (hasFromChanged) {
anim.from = from;
}
from = getFluidValue(from);
const hasToChanged = !isEqual(to2, prevTo);
if (hasToChanged) {
this._focus(to2);
}
const hasAsyncTo = isAsyncTo(props.to);
const {
config: config2
} = anim;
const {
decay,
velocity
} = config2;
if (hasToProp || hasFromProp) {
config2.velocity = 0;
}
if (props.config && !hasAsyncTo) {
mergeConfig(config2, callProp(props.config, key), props.config !== defaultProps.config ? callProp(defaultProps.config, key) : void 0);
}
let node = getAnimated(this);
if (!node || is.und(to2)) {
return resolve(getFinishedResult(this, true));
}
const reset = is.und(props.reset) ? hasFromProp && !props.default : !is.und(from) && matchProp(props.reset, key);
const value = reset ? from : this.get();
const goal = computeGoal(to2);
const isAnimatable = is.num(goal) || is.arr(goal) || isAnimatedString(goal);
const immediate = !hasAsyncTo && (!isAnimatable || matchProp(defaultProps.immediate || props.immediate, key));
if (hasToChanged) {
const nodeType = getAnimatedType(to2);
if (nodeType !== node.constructor) {
if (immediate) {
node = this._set(goal);
} else throw Error(`Cannot animate between ${node.constructor.name} and ${nodeType.name}, as the "to" prop suggests`);
}
}
const goalType = node.constructor;
let started = hasFluidValue(to2);
let finished = false;
if (!started) {
const hasValueChanged = reset || !hasAnimated(this) && hasFromChanged;
if (hasToChanged || hasValueChanged) {
finished = isEqual(computeGoal(value), goal);
started = !finished;
}
if (!isEqual(anim.immediate, immediate) && !immediate || !isEqual(config2.decay, decay) || !isEqual(config2.velocity, velocity)) {
started = true;
}
}
if (finished && isAnimating(this)) {
if (anim.changed && !reset) {
started = true;
} else if (!started) {
this._stop(prevTo);
}
}
if (!hasAsyncTo) {
if (started || hasFluidValue(prevTo)) {
anim.values = node.getPayload();
anim.toValues = hasFluidValue(to2) ? null : goalType == AnimatedString ? [1] : toArray(goal);
}
if (anim.immediate != immediate) {
anim.immediate = immediate;
if (!immediate && !reset) {
this._set(prevTo);
}
}
if (started) {
const {
onRest
} = anim;
each(ACTIVE_EVENTS, (type) => mergeActiveFn(this, props, type));
const result = getFinishedResult(this, checkFinished(this, prevTo));
flushCalls(this._pendingCalls, result);
this._pendingCalls.add(resolve);
if (anim.changed) raf.batchedUpdates(() => {
anim.changed = !reset;
onRest == null ? void 0 : onRest(result, this);
if (reset) {
callProp(defaultProps.onRest, result);
} else {
anim.onStart == null ? void 0 : anim.onStart(result, this);
}
});
}
}
if (reset) {
this._set(value);
}
if (hasAsyncTo) {
resolve(runAsync(props.to, props, this._state, this));
} else if (started) {
this._start();
} else if (isAnimating(this) && !hasToChanged) {
this._pendingCalls.add(resolve);
} else {
resolve(getNoopResult(value));
}
}
_focus(value) {
const anim = this.animation;
if (value !== anim.to) {
if (getFluidObservers(this)) {
this._detach();
}
anim.to = value;
if (getFluidObservers(this)) {
this._attach();
}
}
}
_attach() {
let priority2 = 0;
const {
to: to2
} = this.animation;
if (hasFluidValue(to2)) {
addFluidObserver(to2, this);
if (isFrameValue(to2)) {
priority2 = to2.priority + 1;
}
}
this.priority = priority2;
}
_detach() {
const {
to: to2
} = this.animation;
if (hasFluidValue(to2)) {
removeFluidObserver(to2, this);
}
}
_set(arg, idle = true) {
const value = getFluidValue(arg);
if (!is.und(value)) {
const oldNode = getAnimated(this);
if (!oldNode || !isEqual(value, oldNode.getValue())) {
const nodeType = getAnimatedType(value);
if (!oldNode || oldNode.constructor != nodeType) {
setAnimated(this, nodeType.create(value));
} else {
oldNode.setValue(value);
}
if (oldNode) {
raf.batchedUpdates(() => {
this._onChange(value, idle);
});
}
}
}
return getAnimated(this);
}
_onStart() {
const anim = this.animation;
if (!anim.changed) {
anim.changed = true;
sendEvent(this, "onStart", getFinishedResult(this, checkFinished(this, anim.to)), this);
}
}
_onChange(value, idle) {
if (!idle) {
this._onStart();
callProp(this.animation.onChange, value, this);
}
callProp(this.defaultProps.onChange, value, this);
super._onChange(value, idle);
}
_start() {
const anim = this.animation;
getAnimated(this).reset(getFluidValue(anim.to));
if (!anim.immediate) {
anim.fromValues = anim.values.map((node) => node.lastPosition);
}
if (!isAnimating(this)) {
setActiveBit(this, true);
if (!isPaused(this)) {
this._resume();
}
}
}
_resume() {
if (globals.skipAnimation) {
this.finish();
} else {
frameLoop.start(this);
}
}
_stop(goal, cancel) {
if (isAnimating(this)) {
setActiveBit(this, false);
const anim = this.animation;
each(anim.values, (node) => {
node.done = true;
});
if (anim.toValues) {
anim.onChange = anim.onPause = anim.onResume = void 0;
}
callFluidObservers(this, {
type: "idle",
parent: this
});
const result = cancel ? getCancelledResult(this.get()) : getFinishedResult(this.get(), checkFinished(this, goal != null ? goal : anim.to));
flushCalls(this._pendingCalls, result);
if (anim.changed) {
anim.changed = false;
sendEvent(this, "onRest", result, this);
}
}
}
};
function checkFinished(target, to2) {
const goal = computeGoal(to2);
const value = computeGoal(target.get());
return isEqual(value, goal);
}
function createLoopUpdate(props, loop2 = props.loop, to2 = props.to) {
let loopRet = callProp(loop2);
if (loopRet) {
const overrides = loopRet !== true && inferTo(loopRet);
const reverse = (overrides || props).reverse;
const reset = !overrides || overrides.reset;
return createUpdate(_extends3({}, props, {
loop: loop2,
default: false,
pause: void 0,
to: !reverse || isAsyncTo(to2) ? to2 : void 0,
from: reset ? props.from : void 0,
reset
}, overrides));
}
}
function createUpdate(props) {
const {
to: to2,
from
} = props = inferTo(props);
const keys = /* @__PURE__ */ new Set();
if (is.obj(to2)) findDefined(to2, keys);
if (is.obj(from)) findDefined(from, keys);
props.keys = keys.size ? Array.from(keys) : null;
return props;
}
function findDefined(values, keys) {
eachProp(values, (value, key) => value != null && keys.add(key));
}
var ACTIVE_EVENTS = ["onStart", "onRest", "onChange", "onPause", "onResume"];
function mergeActiveFn(target, props, type) {
target.animation[type] = props[type] !== getDefaultProp(props, type) ? resolveProp(props[type], target.key) : void 0;
}
function sendEvent(target, type, ...args) {
var _target$animation$typ, _target$animation, _target$defaultProps$, _target$defaultProps;
(_target$animation$typ = (_target$animation = target.animation)[type]) == null ? void 0 : _target$animation$typ.call(_target$animation, ...args);
(_target$defaultProps$ = (_target$defaultProps = target.defaultProps)[type]) == null ? void 0 : _target$defaultProps$.call(_target$defaultProps, ...args);
}
var BATCHED_EVENTS = ["onStart", "onChange", "onRest"];
var nextId = 1;
var Controller = class {
constructor(props, flush2) {
this.id = nextId++;
this.springs = {};
this.queue = [];
this.ref = void 0;
this._flush = void 0;
this._initialProps = void 0;
this._lastAsyncId = 0;
this._active = /* @__PURE__ */ new Set();
this._changed = /* @__PURE__ */ new Set();
this._started = false;
this._item = void 0;
this._state = {
paused: false,
pauseQueue: /* @__PURE__ */ new Set(),
resumeQueue: /* @__PURE__ */ new Set(),
timeouts: /* @__PURE__ */ new Set()
};
this._events = {
onStart: /* @__PURE__ */ new Map(),
onChange: /* @__PURE__ */ new Map(),
onRest: /* @__PURE__ */ new Map()
};
this._onFrame = this._onFrame.bind(this);
if (flush2) {
this._flush = flush2;
}
if (props) {
this.start(_extends3({
default: true
}, props));
}
}
get idle() {
return !this._state.asyncTo && Object.values(this.springs).every((spring) => {
return spring.idle && !spring.isDelayed && !spring.isPaused;
});
}
get item() {
return this._item;
}
set item(item) {
this._item = item;
}
get() {
const values = {};
this.each((spring, key) => values[key] = spring.get());
return values;
}
set(values) {
for (const key in values) {
const value = values[key];
if (!is.und(value)) {
this.springs[key].set(value);
}
}
}
update(props) {
if (props) {
this.queue.push(createUpdate(props));
}
return this;
}
start(props) {
let {
queue
} = this;
if (props) {
queue = toArray(props).map(createUpdate);
} else {
this.queue = [];
}
if (this._flush) {
return this._flush(this, queue);
}
prepareKeys(this, queue);
return flushUpdateQueue(this, queue);
}
stop(arg, keys) {
if (arg !== !!arg) {
keys = arg;
}
if (keys) {
const springs = this.springs;
each(toArray(keys), (key) => springs[key].stop(!!arg));
} else {
stopAsync(this._state, this._lastAsyncId);
this.each((spring) => spring.stop(!!arg));
}
return this;
}
pause(keys) {
if (is.und(keys)) {
this.start({
pause: true
});
} else {
const springs = this.springs;
each(toArray(keys), (key) => springs[key].pause());
}
return this;
}
resume(keys) {
if (is.und(keys)) {
this.start({
pause: false
});
} else {
const springs = this.springs;
each(toArray(keys), (key) => springs[key].resume());
}
return this;
}
each(iterator) {
eachProp(this.springs, iterator);
}
_onFrame() {
const {
onStart,
onChange,
onRest
} = this._events;
const active = this._active.size > 0;
const changed = this._changed.size > 0;
if (active && !this._started || changed && !this._started) {
this._started = true;
flush(onStart, ([onStart2, result]) => {
result.value = this.get();
onStart2(result, this, this._item);
});
}
const idle = !active && this._started;
const values = changed || idle && onRest.size ? this.get() : null;
if (changed && onChange.size) {
flush(onChange, ([onChange2, result]) => {
result.value = values;
onChange2(result, this, this._item);
});
}
if (idle) {
this._started = false;
flush(onRest, ([onRest2, result]) => {
result.value = values;
onRest2(result, this, this._item);
});
}
}
eventObserved(event) {
if (event.type == "change") {
this._changed.add(event.parent);
if (!event.idle) {
this._active.add(event.parent);
}
} else if (event.type == "idle") {
this._active.delete(event.parent);
} else return;
raf.onFrame(this._onFrame);
}
};
function flushUpdateQueue(ctrl, queue) {
return Promise.all(queue.map((props) => flushUpdate(ctrl, props))).then((results) => getCombinedResult(ctrl, results));
}
async function flushUpdate(ctrl, props, isLoop) {
const {
keys,
to: to2,
from,
loop: loop2,
onRest,
onResolve
} = props;
const defaults2 = is.obj(props.default) && props.default;
if (loop2) {
props.loop = false;
}
if (to2 === false) props.to = null;
if (from === false) props.from = null;
const asyncTo = is.arr(to2) || is.fun(to2) ? to2 : void 0;
if (asyncTo) {
props.to = void 0;
props.onRest = void 0;
if (defaults2) {
defaults2.onRest = void 0;
}
} else {
each(BATCHED_EVENTS, (key) => {
const handler = props[key];
if (is.fun(handler)) {
const queue = ctrl["_events"][key];
props[key] = ({
finished,
cancelled
}) => {
const result2 = queue.get(handler);
if (result2) {
if (!finished) result2.finished = false;
if (cancelled) result2.cancelled = true;
} else {
queue.set(handler, {
value: null,
finished: finished || false,
cancelled: cancelled || false
});
}
};
if (defaults2) {
defaults2[key] = props[key];
}
}
});
}
const state = ctrl["_state"];
if (props.pause === !state.paused) {
state.paused = props.pause;
flushCalls(props.pause ? state.pauseQueue : state.resumeQueue);
} else if (state.paused) {
props.pause = true;
}
const promises = (keys || Object.keys(ctrl.springs)).map((key) => ctrl.springs[key].start(props));
const cancel = props.cancel === true || getDefaultProp(props, "cancel") === true;
if (asyncTo || cancel && state.asyncId) {
promises.push(scheduleProps(++ctrl["_lastAsyncId"], {
props,
state,
actions: {
pause: noop3,
resume: noop3,
start(props2, resolve) {
if (cancel) {
stopAsync(state, ctrl["_lastAsyncId"]);
resolve(getCancelledResult(ctrl));
} else {
props2.onRest = onRest;
resolve(runAsync(asyncTo, props2, state, ctrl));
}
}
}
}));
}
if (state.paused) {
await new Promise((resume) => {
state.resumeQueue.add(resume);
});
}
const result = getCombinedResult(ctrl, await Promise.all(promises));
if (loop2 && result.finished && !(isLoop && result.noop)) {
const nextProps = createLoopUpdate(props, loop2, to2);
if (nextProps) {
prepareKeys(ctrl, [nextProps]);
return flushUpdate(ctrl, nextProps, true);
}
}
if (onResolve) {
raf.batchedUpdates(() => onResolve(result, ctrl, ctrl.item));
}
return result;
}
function createSpring(key, observer) {
const spring = new SpringValue();
spring.key = key;
if (observer) {
addFluidObserver(spring, observer);
}
return spring;
}
function prepareSprings(springs, props, create6) {
if (props.keys) {
each(props.keys, (key) => {
const spring = springs[key] || (springs[key] = create6(key));
spring["_prepareNode"](props);
});
}
}
function prepareKeys(ctrl, queue) {
each(queue, (props) => {
prepareSprings(ctrl.springs, props, (key) => {
return createSpring(key, ctrl);
});
});
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i2;
for (i2 = 0; i2 < sourceKeys.length; i2++) {
key = sourceKeys[i2];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
var _excluded$3 = ["children"];
var SpringContext = (_ref) => {
let {
children
} = _ref, props = _objectWithoutPropertiesLoose(_ref, _excluded$3);
const inherited = (0, import_react3.useContext)(ctx);
const pause = props.pause || !!inherited.pause, immediate = props.immediate || !!inherited.immediate;
props = useMemoOne(() => ({
pause,
immediate
}), [pause, immediate]);
const {
Provider: Provider3
} = ctx;
return React2.createElement(Provider3, {
value: props
}, children);
};
var ctx = makeContext(SpringContext, {});
SpringContext.Provider = ctx.Provider;
SpringContext.Consumer = ctx.Consumer;
function makeContext(target, init) {
Object.assign(target, React2.createContext(init));
target.Provider._context = target;
target.Consumer._context = target;
return target;
}
var TransitionPhase;
(function(TransitionPhase2) {
TransitionPhase2["MOUNT"] = "mount";
TransitionPhase2["ENTER"] = "enter";
TransitionPhase2["UPDATE"] = "update";
TransitionPhase2["LEAVE"] = "leave";
})(TransitionPhase || (TransitionPhase = {}));
var Interpolation = class extends FrameValue {
constructor(source, args) {
super();
this.key = void 0;
this.idle = true;
this.calc = void 0;
this._active = /* @__PURE__ */ new Set();
this.source = source;
this.calc = createInterpolator(...args);
const value = this._get();
const nodeType = getAnimatedType(value);
setAnimated(this, nodeType.create(value));
}
advance(_dt) {
const value = this._get();
const oldValue = this.get();
if (!isEqual(value, oldValue)) {
getAnimated(this).setValue(value);
this._onChange(value, this.idle);
}
if (!this.idle && checkIdle(this._active)) {
becomeIdle(this);
}
}
_get() {
const inputs = is.arr(this.source) ? this.source.map(getFluidValue) : toArray(getFluidValue(this.source));
return this.calc(...inputs);
}
_start() {
if (this.idle && !checkIdle(this._active)) {
this.idle = false;
each(getPayload(this), (node) => {
node.done = false;
});
if (globals.skipAnimation) {
raf.batchedUpdates(() => this.advance());
becomeIdle(this);
} else {
frameLoop.start(this);
}
}
}
_attach() {
let priority2 = 1;
each(toArray(this.source), (source) => {
if (hasFluidValue(source)) {
addFluidObserver(source, this);
}
if (isFrameValue(source)) {
if (!source.idle) {
this._active.add(source);
}
priority2 = Math.max(priority2, source.priority + 1);
}
});
this.priority = priority2;
this._start();
}
_detach() {
each(toArray(this.source), (source) => {
if (hasFluidValue(source)) {
removeFluidObserver(source, this);
}
});
this._active.clear();
becomeIdle(this);
}
eventObserved(event) {
if (event.type == "change") {
if (event.idle) {
this.advance();
} else {
this._active.add(event.parent);
this._start();
}
} else if (event.type == "idle") {
this._active.delete(event.parent);
} else if (event.type == "priority") {
this.priority = toArray(this.source).reduce((highest, parent) => Math.max(highest, (isFrameValue(parent) ? parent.priority : 0) + 1), 0);
}
}
};
function isIdle(source) {
return source.idle !== false;
}
function checkIdle(active) {
return !active.size || Array.from(active).every(isIdle);
}
function becomeIdle(self) {
if (!self.idle) {
self.idle = true;
each(getPayload(self), (node) => {
node.done = true;
});
callFluidObservers(self, {
type: "idle",
parent: self
});
}
}
globals.assign({
createStringInterpolator,
to: (source, args) => new Interpolation(source, args)
});
var update2 = frameLoop.advance;
// node_modules/@react-spring/web/dist/react-spring-web.esm.js
var import_react_dom = __toESM(require_react_dom());
function _objectWithoutPropertiesLoose2(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i2;
for (i2 = 0; i2 < sourceKeys.length; i2++) {
key = sourceKeys[i2];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
var _excluded$2 = ["style", "children", "scrollTop", "scrollLeft"];
var isCustomPropRE = /^--/;
function dangerousStyleValue(name, value) {
if (value == null || typeof value === "boolean" || value === "") return "";
if (typeof value === "number" && value !== 0 && !isCustomPropRE.test(name) && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) return value + "px";
return ("" + value).trim();
}
var attributeCache = {};
function applyAnimatedValues(instance, props) {
if (!instance.nodeType || !instance.setAttribute) {
return false;
}
const isFilterElement = instance.nodeName === "filter" || instance.parentNode && instance.parentNode.nodeName === "filter";
const _ref = props, {
style,
children,
scrollTop,
scrollLeft
} = _ref, attributes = _objectWithoutPropertiesLoose2(_ref, _excluded$2);
const values = Object.values(attributes);
const names = Object.keys(attributes).map((name) => isFilterElement || instance.hasAttribute(name) ? name : attributeCache[name] || (attributeCache[name] = name.replace(/([A-Z])/g, (n2) => "-" + n2.toLowerCase())));
if (children !== void 0) {
instance.textContent = children;
}
for (let name in style) {
if (style.hasOwnProperty(name)) {
const value = dangerousStyleValue(name, style[name]);
if (isCustomPropRE.test(name)) {
instance.style.setProperty(name, value);
} else {
instance.style[name] = value;
}
}
}
names.forEach((name, i2) => {
instance.setAttribute(name, values[i2]);
});
if (scrollTop !== void 0) {
instance.scrollTop = scrollTop;
}
if (scrollLeft !== void 0) {
instance.scrollLeft = scrollLeft;
}
}
var isUnitlessNumber = {
animationIterationCount: true,
borderImageOutset: true,
borderImageSlice: true,
borderImageWidth: true,
boxFlex: true,
boxFlexGroup: true,
boxOrdinalGroup: true,
columnCount: true,
columns: true,
flex: true,
flexGrow: true,
flexPositive: true,
flexShrink: true,
flexNegative: true,
flexOrder: true,
gridRow: true,
gridRowEnd: true,
gridRowSpan: true,
gridRowStart: true,
gridColumn: true,
gridColumnEnd: true,
gridColumnSpan: true,
gridColumnStart: true,
fontWeight: true,
lineClamp: true,
lineHeight: true,
opacity: true,
order: true,
orphans: true,
tabSize: true,
widows: true,
zIndex: true,
zoom: true,
fillOpacity: true,
floodOpacity: true,
stopOpacity: true,
strokeDasharray: true,
strokeDashoffset: true,
strokeMiterlimit: true,
strokeOpacity: true,
strokeWidth: true
};
var prefixKey = (prefix2, key) => prefix2 + key.charAt(0).toUpperCase() + key.substring(1);
var prefixes = ["Webkit", "Ms", "Moz", "O"];
isUnitlessNumber = Object.keys(isUnitlessNumber).reduce((acc, prop) => {
prefixes.forEach((prefix2) => acc[prefixKey(prefix2, prop)] = acc[prop]);
return acc;
}, isUnitlessNumber);
var _excluded$1 = ["x", "y", "z"];
var domTransforms = /^(matrix|translate|scale|rotate|skew)/;
var pxTransforms = /^(translate)/;
var degTransforms = /^(rotate|skew)/;
var addUnit = (value, unit) => is.num(value) && value !== 0 ? value + unit : value;
var isValueIdentity = (value, id) => is.arr(value) ? value.every((v2) => isValueIdentity(v2, id)) : is.num(value) ? value === id : parseFloat(value) === id;
var AnimatedStyle = class extends AnimatedObject {
constructor(_ref) {
let {
x: x2,
y: y2,
z
} = _ref, style = _objectWithoutPropertiesLoose2(_ref, _excluded$1);
const inputs = [];
const transforms = [];
if (x2 || y2 || z) {
inputs.push([x2 || 0, y2 || 0, z || 0]);
transforms.push((xyz) => [`translate3d(${xyz.map((v2) => addUnit(v2, "px")).join(",")})`, isValueIdentity(xyz, 0)]);
}
eachProp(style, (value, key) => {
if (key === "transform") {
inputs.push([value || ""]);
transforms.push((transform) => [transform, transform === ""]);
} else if (domTransforms.test(key)) {
delete style[key];
if (is.und(value)) return;
const unit = pxTransforms.test(key) ? "px" : degTransforms.test(key) ? "deg" : "";
inputs.push(toArray(value));
transforms.push(key === "rotate3d" ? ([x3, y3, z2, deg]) => [`rotate3d(${x3},${y3},${z2},${addUnit(deg, unit)})`, isValueIdentity(deg, 0)] : (input) => [`${key}(${input.map((v2) => addUnit(v2, unit)).join(",")})`, isValueIdentity(input, key.startsWith("scale") ? 1 : 0)]);
}
});
if (inputs.length) {
style.transform = new FluidTransform(inputs, transforms);
}
super(style);
}
};
var FluidTransform = class extends FluidValue {
constructor(inputs, transforms) {
super();
this._value = null;
this.inputs = inputs;
this.transforms = transforms;
}
get() {
return this._value || (this._value = this._get());
}
_get() {
let transform = "";
let identity2 = true;
each(this.inputs, (input, i2) => {
const arg1 = getFluidValue(input[0]);
const [t3, id] = this.transforms[i2](is.arr(arg1) ? arg1 : input.map(getFluidValue));
transform += " " + t3;
identity2 = identity2 && id;
});
return identity2 ? "none" : transform;
}
observerAdded(count) {
if (count == 1) each(this.inputs, (input) => each(input, (value) => hasFluidValue(value) && addFluidObserver(value, this)));
}
observerRemoved(count) {
if (count == 0) each(this.inputs, (input) => each(input, (value) => hasFluidValue(value) && removeFluidObserver(value, this)));
}
eventObserved(event) {
if (event.type == "change") {
this._value = null;
}
callFluidObservers(this, event);
}
};
var primitives = ["a", "abbr", "address", "area", "article", "aside", "audio", "b", "base", "bdi", "bdo", "big", "blockquote", "body", "br", "button", "canvas", "caption", "cite", "code", "col", "colgroup", "data", "datalist", "dd", "del", "details", "dfn", "dialog", "div", "dl", "dt", "em", "embed", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "iframe", "img", "input", "ins", "kbd", "keygen", "label", "legend", "li", "link", "main", "map", "mark", "menu", "menuitem", "meta", "meter", "nav", "noscript", "object", "ol", "optgroup", "option", "output", "p", "param", "picture", "pre", "progress", "q", "rp", "rt", "ruby", "s", "samp", "script", "section", "select", "small", "source", "span", "strong", "style", "sub", "summary", "sup", "table", "tbody", "td", "textarea", "tfoot", "th", "thead", "time", "title", "tr", "track", "u", "ul", "var", "video", "wbr", "circle", "clipPath", "defs", "ellipse", "foreignObject", "g", "image", "line", "linearGradient", "mask", "path", "pattern", "polygon", "polyline", "radialGradient", "rect", "stop", "svg", "text", "tspan"];
var _excluded = ["scrollTop", "scrollLeft"];
globals.assign({
batchedUpdates: import_react_dom.unstable_batchedUpdates,
createStringInterpolator,
colors
});
var host = createHost(primitives, {
applyAnimatedValues,
createAnimatedStyle: (style) => new AnimatedStyle(style),
getComponentProps: (_ref) => {
let props = _objectWithoutPropertiesLoose2(_ref, _excluded);
return props;
}
});
var animated = host.animated;
// packages/block-editor/build-module/components/use-moving-animation/index.mjs
var import_element25 = __toESM(require_element(), 1);
var import_dom2 = __toESM(require_dom(), 1);
var import_data21 = __toESM(require_data(), 1);
var BLOCK_ANIMATION_THRESHOLD = 200;
function getAbsolutePosition(element) {
return {
top: element.offsetTop,
left: element.offsetLeft
};
}
function useMovingAnimation({ triggerAnimationOnChange, clientId }) {
const ref = (0, import_element25.useRef)();
const {
isTyping: isTyping3,
getGlobalBlockCount: getGlobalBlockCount2,
isBlockSelected: isBlockSelected2,
isFirstMultiSelectedBlock: isFirstMultiSelectedBlock2,
isBlockMultiSelected: isBlockMultiSelected2,
isAncestorMultiSelected: isAncestorMultiSelected2,
isDraggingBlocks: isDraggingBlocks2
} = (0, import_data21.useSelect)(store);
const { previous, prevRect } = (0, import_element25.useMemo)(
() => ({
previous: ref.current && getAbsolutePosition(ref.current),
prevRect: ref.current && ref.current.getBoundingClientRect()
}),
[triggerAnimationOnChange]
);
(0, import_element25.useLayoutEffect)(() => {
if (!previous || !ref.current) {
return;
}
const scrollContainer = (0, import_dom2.getScrollContainer)(ref.current);
const isSelected = isBlockSelected2(clientId);
const adjustScrolling = isSelected || isFirstMultiSelectedBlock2(clientId);
const isDragging3 = isDraggingBlocks2();
function preserveScrollPosition() {
if (isDragging3) {
return;
}
if (adjustScrolling && prevRect) {
const blockRect = ref.current.getBoundingClientRect();
const diff = blockRect.top - prevRect.top;
if (diff) {
scrollContainer.scrollTop += diff;
}
}
}
const disableAnimation = window.matchMedia("(prefers-reduced-motion: reduce)").matches || isTyping3() || getGlobalBlockCount2() > BLOCK_ANIMATION_THRESHOLD;
if (disableAnimation) {
preserveScrollPosition();
return;
}
const isPartOfSelection = isSelected || isBlockMultiSelected2(clientId) || isAncestorMultiSelected2(clientId);
if (isPartOfSelection && isDragging3) {
return;
}
const zIndex = isPartOfSelection ? "1" : "";
const controller = new Controller({
x: 0,
y: 0,
config: { mass: 5, tension: 2e3, friction: 200 },
onChange({ value }) {
if (!ref.current) {
return;
}
let { x: x22, y: y22 } = value;
x22 = Math.round(x22);
y22 = Math.round(y22);
const finishedMoving = x22 === 0 && y22 === 0;
ref.current.style.transformOrigin = "center center";
ref.current.style.transform = finishedMoving ? null : `translate3d(${x22}px,${y22}px,0)`;
ref.current.style.zIndex = zIndex;
preserveScrollPosition();
}
});
ref.current.style.transform = void 0;
const destination = getAbsolutePosition(ref.current);
const x2 = Math.round(previous.left - destination.left);
const y2 = Math.round(previous.top - destination.top);
controller.start({ x: 0, y: 0, from: { x: x2, y: y2 } });
return () => {
controller.stop();
controller.set({ x: 0, y: 0 });
};
}, [
previous,
prevRect,
clientId,
isTyping3,
getGlobalBlockCount2,
isBlockSelected2,
isFirstMultiSelectedBlock2,
isBlockMultiSelected2,
isAncestorMultiSelected2,
isDraggingBlocks2
]);
return ref;
}
var use_moving_animation_default = useMovingAnimation;
// packages/block-editor/build-module/components/block-list/use-block-props/use-focus-first-element.mjs
var import_element26 = __toESM(require_element(), 1);
var import_dom3 = __toESM(require_dom(), 1);
var import_data22 = __toESM(require_data(), 1);
// packages/block-editor/build-module/utils/dom.mjs
var BLOCK_SELECTOR = ".block-editor-block-list__block";
var APPENDER_SELECTOR = ".block-list-appender";
var BLOCK_APPENDER_CLASS = ".block-editor-button-block-appender";
function isInSameBlock(a2, b2) {
return a2.closest(BLOCK_SELECTOR) === b2.closest(BLOCK_SELECTOR);
}
function isInsideRootBlock(blockElement, element) {
const parentBlock = element.closest(
[BLOCK_SELECTOR, APPENDER_SELECTOR, BLOCK_APPENDER_CLASS].join(",")
);
return parentBlock === blockElement;
}
function getSelectionEditableElement(selection2, root) {
const { anchorNode, focusNode } = selection2;
if (!anchorNode || !focusNode) {
return;
}
const element = anchorNode.nodeType === anchorNode.ELEMENT_NODE ? anchorNode : anchorNode.parentElement;
const editable = element?.closest('[contenteditable="true"]');
if (!editable || editable === root || !editable.contains(focusNode)) {
return;
}
return editable;
}
function getBlockClientId(node) {
while (node && node.nodeType !== node.ELEMENT_NODE) {
node = node.parentNode;
}
if (!node) {
return;
}
const elementNode = node;
const blockNode = elementNode.closest(BLOCK_SELECTOR);
if (!blockNode) {
return;
}
return blockNode.id.slice("block-".length);
}
function rectUnion(rect1, rect2) {
const left = Math.min(rect1.left, rect2.left);
const right = Math.max(rect1.right, rect2.right);
const bottom = Math.max(rect1.bottom, rect2.bottom);
const top = Math.min(rect1.top, rect2.top);
return new window.DOMRectReadOnly(left, top, right - left, bottom - top);
}
function isElementVisible(element) {
const viewport = element.ownerDocument.defaultView;
if (!viewport) {
return false;
}
if (element.hasAttribute("data-visually-hidden")) {
return false;
}
const bounds = element.getBoundingClientRect();
if (bounds.width === 0 || bounds.height === 0) {
return false;
}
if (element.checkVisibility) {
return element.checkVisibility?.({
opacityProperty: true,
contentVisibilityAuto: true,
visibilityProperty: true
});
}
const style = viewport.getComputedStyle(element);
if (style.display === "none" || style.visibility === "hidden" || style.opacity === "0") {
return false;
}
return true;
}
function isScrollable(element) {
const style = window.getComputedStyle(element);
return style.overflowX === "auto" || style.overflowX === "scroll" || style.overflowY === "auto" || style.overflowY === "scroll";
}
var WITH_OVERFLOW_ELEMENT_BLOCKS = ["core/navigation"];
function getElementBounds(element) {
const viewport = element.ownerDocument.defaultView;
if (!viewport) {
return new window.DOMRectReadOnly();
}
let bounds = element.getBoundingClientRect();
const dataType = element.getAttribute("data-type");
if (dataType && WITH_OVERFLOW_ELEMENT_BLOCKS.includes(dataType)) {
const stack = [element];
let currentElement;
while (currentElement = stack.pop()) {
if (!isScrollable(currentElement)) {
for (const child of currentElement.children) {
if (isElementVisible(child)) {
const childBounds = child.getBoundingClientRect();
bounds = rectUnion(bounds, childBounds);
stack.push(child);
}
}
}
}
}
const left = Math.max(bounds.left, 0);
const right = Math.min(bounds.right, viewport.innerWidth);
bounds = new window.DOMRectReadOnly(
left,
bounds.top,
right - left,
bounds.height
);
return bounds;
}
// packages/block-editor/build-module/components/block-list/use-block-props/use-focus-first-element.mjs
function useFocusFirstElement({ clientId, initialPosition: initialPosition2 }) {
const ref = (0, import_element26.useRef)();
const { isBlockSelected: isBlockSelected2, isMultiSelecting: isMultiSelecting3, isZoomOut: isZoomOut2, getSelectionStart: getSelectionStart2 } = unlock((0, import_data22.useSelect)(store));
(0, import_element26.useEffect)(() => {
if (!isBlockSelected2(clientId) || isMultiSelecting3() || isZoomOut2()) {
return;
}
if (initialPosition2 === void 0 || initialPosition2 === null) {
return;
}
if (!ref.current) {
return;
}
const { ownerDocument: ownerDocument2 } = ref.current;
if (isInsideRootBlock(ref.current, ownerDocument2.activeElement)) {
return;
}
const textInputs = import_dom3.focus.tabbable.find(ref.current).filter((node) => (0, import_dom3.isTextField)(node));
const isReverse = -1 === initialPosition2;
const target = textInputs[isReverse ? textInputs.length - 1 : 0] || ref.current;
if (!isInsideRootBlock(ref.current, target)) {
ref.current.focus();
return;
}
if (!ref.current.getAttribute("contenteditable")) {
const focusElement = import_dom3.focus.tabbable.findNext(ref.current);
if (focusElement && isInsideRootBlock(ref.current, focusElement) && (0, import_dom3.isFormElement)(focusElement)) {
focusElement.focus();
return;
}
}
const { activeElement: activeElement2 } = ownerDocument2;
const selection2 = ownerDocument2.defaultView.getSelection();
const { clientId: selectionClientId, offset: offset4 } = getSelectionStart2();
const hasCaret = activeElement2?.isContentEditable && activeElement2.contains(target) && !!selection2.anchorNode && target.contains(selection2.anchorNode);
const isDeliberate = initialPosition2 === 0 || offset4 !== void 0 && selectionClientId === clientId;
if (!(hasCaret && isDeliberate)) {
(0, import_dom3.placeCaretAtHorizontalEdge)(target, isReverse);
}
}, [initialPosition2, clientId]);
return ref;
}
// packages/block-editor/build-module/components/block-list/use-block-props/use-is-hovered.mjs
var import_compose8 = __toESM(require_compose(), 1);
var { subscribeDelegatedListener } = unlock(import_compose8.privateApis);
function useIsHovered({ isEnabled = true } = {}) {
return (0, import_compose8.useRefEffect)(
(node) => {
if (!isEnabled) {
return;
}
function listener(event) {
if (event.defaultPrevented) {
return;
}
event.preventDefault();
node.classList.toggle(
"is-hovered",
event.type === "mouseover"
);
}
const unsubscribeOut = subscribeDelegatedListener(
node,
"mouseout",
listener
);
const unsubscribeOver = subscribeDelegatedListener(
node,
"mouseover",
listener
);
return () => {
unsubscribeOut();
unsubscribeOver();
node.classList.remove("is-hovered");
};
},
[isEnabled]
);
}
// packages/block-editor/build-module/components/block-list/use-block-props/use-focus-handler.mjs
var import_data23 = __toESM(require_data(), 1);
var import_compose9 = __toESM(require_compose(), 1);
// packages/block-editor/build-module/components/writing-flow/utils.mjs
var import_i18n25 = __toESM(require_i18n(), 1);
var import_dom6 = __toESM(require_dom(), 1);
var import_blocks20 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/utils/pasting.mjs
var import_dom5 = __toESM(require_dom(), 1);
function removeWindowsFragments(html) {
const startStr = "<!--StartFragment-->";
const startIdx = html.indexOf(startStr);
if (startIdx > -1) {
html = html.substring(startIdx + startStr.length);
} else {
return html;
}
const endStr = "<!--EndFragment-->";
const endIdx = html.indexOf(endStr);
if (endIdx > -1) {
html = html.substring(0, endIdx);
}
return html;
}
function removeCharsetMetaTag(html) {
const metaTag = `<meta charset='utf-8'>`;
if (html.startsWith(metaTag)) {
return html.slice(metaTag.length);
}
return html;
}
function getPasteEventData({
clipboardData
}) {
let plainText = "";
let html = "";
try {
plainText = clipboardData.getData("text/plain");
html = clipboardData.getData("text/html");
} catch {
return;
}
html = removeWindowsFragments(html);
html = removeCharsetMetaTag(html);
const files = (0, import_dom5.getFilesFromDataTransfer)(clipboardData);
if (files.length && !shouldDismissPastedFiles(files, html)) {
return { files };
}
return { html, plainText, files: [] };
}
function shouldDismissPastedFiles(files, html) {
if (html && files?.length === 1 && files[0].type.indexOf("image/") === 0) {
const IMAGE_TAG = /<\s*img\b/gi;
if (html.match(IMAGE_TAG)?.length !== 1) {
return true;
}
const IMG_WITH_LOCAL_SRC = /<\s*img\b[^>]*\bsrc="file:\/\//i;
if (html.match(IMG_WITH_LOCAL_SRC)) {
return true;
}
}
return false;
}
// packages/block-editor/build-module/components/writing-flow/utils.mjs
var requiresWrapperOnCopy = /* @__PURE__ */ Symbol("requiresWrapperOnCopy");
function setClipboardBlocks(event, blocks2, registry) {
let _blocks = blocks2;
const [firstBlock] = blocks2;
if (firstBlock) {
const firstBlockType = registry.select(import_blocks20.store).getBlockType(firstBlock.name);
if (firstBlockType[requiresWrapperOnCopy]) {
const { getBlockRootClientId: getBlockRootClientId2, getBlockName: getBlockName2, getBlockAttributes: getBlockAttributes3 } = registry.select(store);
const wrapperBlockClientId = getBlockRootClientId2(
firstBlock.clientId
);
const wrapperBlockName = getBlockName2(wrapperBlockClientId);
if (wrapperBlockName) {
_blocks = (0, import_blocks20.createBlock)(
wrapperBlockName,
getBlockAttributes3(wrapperBlockClientId),
_blocks
);
}
}
}
const serialized = (0, import_blocks20.serialize)(_blocks);
event.clipboardData.setData("text/plain", toPlainText(serialized));
event.clipboardData.setData("text/html", serialized);
}
function getPasteBlocks(event, canUserUseUnfilteredHTML) {
const { plainText, html, files } = getPasteEventData(event);
let blocks2 = [];
if (files.length) {
const fromTransforms = (0, import_blocks20.getBlockTransforms)("from");
blocks2 = files.reduce((accumulator, file) => {
const transformation = (0, import_blocks20.findTransform)(
fromTransforms,
(transform) => transform.type === "files" && transform.isMatch([file])
);
if (transformation) {
accumulator.push(transformation.transform([file]));
}
return accumulator;
}, []).flat();
} else {
blocks2 = (0, import_blocks20.pasteHandler)({
HTML: html,
plainText,
mode: "BLOCKS",
canUserUseUnfilteredHTML
});
}
return blocks2;
}
function toPlainText(html) {
html = html.replace(/<br>/g, "\n");
const plainText = (0, import_dom6.__unstableStripHTML)(html).trim();
return plainText.replace(/\n\n+/g, "\n\n");
}
var shiftClickInProgress = false;
function setShiftClickInProgress(value) {
shiftClickInProgress = value;
}
function isShiftClickInProgress() {
return shiftClickInProgress;
}
function setContentEditableWrapper(node, value, { focus: focus10 = true } = {}) {
if (node.contentEditable === String(value)) {
return value;
}
node.contentEditable = value;
if (!value) {
node.removeAttribute("role");
node.removeAttribute("aria-multiline");
node.removeAttribute("aria-label");
return false;
}
if (!node.isContentEditable) {
node.removeAttribute("contenteditable");
return false;
}
node.setAttribute("role", "textbox");
node.setAttribute("aria-multiline", "true");
node.setAttribute("aria-label", (0, import_i18n25.__)("Editor canvas"));
if (focus10) {
node.focus();
}
return true;
}
// packages/block-editor/build-module/components/block-list/use-block-props/use-focus-handler.mjs
var { subscribeDelegatedListener: subscribeDelegatedListener2 } = unlock(import_compose9.privateApis);
function useFocusHandler(clientId) {
const { isBlockSelected: isBlockSelected2, isBlockMultiSelected: isBlockMultiSelected2 } = (0, import_data23.useSelect)(store);
const { selectBlock: selectBlock2, selectionChange: selectionChange2 } = (0, import_data23.useDispatch)(store);
return (0, import_compose9.useRefEffect)(
(node) => {
function onFocus(event) {
if (isBlockSelected2(clientId)) {
if (!event.target.isContentEditable) {
selectionChange2(clientId);
}
return;
}
if (isShiftClickInProgress()) {
return;
}
if (isBlockMultiSelected2(clientId)) {
return;
}
if (!isInsideRootBlock(node, event.target)) {
return;
}
if (event.target.isContentEditable) {
selectBlock2(clientId, null);
return;
}
selectBlock2(clientId);
}
return subscribeDelegatedListener2(node, "focusin", onFocus);
},
[isBlockSelected2, selectBlock2]
);
}
// packages/block-editor/build-module/components/block-list/use-block-props/use-selected-block-event-handlers.mjs
var import_blocks21 = __toESM(require_blocks(), 1);
var import_dom8 = __toESM(require_dom(), 1);
var import_keycodes2 = __toESM(require_keycodes(), 1);
var import_data24 = __toESM(require_data(), 1);
var import_compose10 = __toESM(require_compose(), 1);
function isColorTransparent(color) {
return !color || color === "transparent" || color === "rgba(0, 0, 0, 0)";
}
function useEventHandlers({ clientId, isSelected }) {
const {
getBlockRootClientId: getBlockRootClientId2,
isZoomOut: isZoomOut2,
hasMultiSelection: hasMultiSelection2,
isSectionBlock: isSectionBlock2,
editedContentOnlySection: editedContentOnlySection2,
getBlock: getBlock2
} = unlock((0, import_data24.useSelect)(store));
const {
insertAfterBlock: insertAfterBlock2,
removeBlock: removeBlock2,
resetZoomLevel: resetZoomLevel2,
startDraggingBlocks: startDraggingBlocks2,
stopDraggingBlocks: stopDraggingBlocks2,
editContentOnlySection: editContentOnlySection2
} = unlock((0, import_data24.useDispatch)(store));
return (0, import_compose10.useRefEffect)(
(node) => {
if (!isSelected) {
return;
}
function onKeyDown(event) {
const { keyCode, target } = event;
if (keyCode !== import_keycodes2.ENTER && keyCode !== import_keycodes2.BACKSPACE && keyCode !== import_keycodes2.DELETE) {
return;
}
if (target !== node || (0, import_dom8.isTextField)(target)) {
return;
}
event.preventDefault();
if (keyCode === import_keycodes2.ENTER && isZoomOut2()) {
resetZoomLevel2();
} else if (keyCode === import_keycodes2.ENTER) {
insertAfterBlock2(clientId);
} else {
removeBlock2(clientId);
}
}
function onDragStart(event) {
if (node !== event.target || node.isContentEditable || node.ownerDocument.activeElement !== node || hasMultiSelection2()) {
event.preventDefault();
return;
}
const data = JSON.stringify({
type: "block",
srcClientIds: [clientId],
srcRootClientId: getBlockRootClientId2(clientId)
});
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.clearData();
event.dataTransfer.setData("wp-blocks", data);
const { ownerDocument: ownerDocument2 } = node;
const { defaultView } = ownerDocument2;
const selection2 = defaultView.getSelection();
selection2.removeAllRanges();
const dragElement = ownerDocument2.createElement("div");
dragElement.style.width = "1px";
dragElement.style.height = "1px";
dragElement.style.position = "fixed";
dragElement.style.visibility = "hidden";
ownerDocument2.body.appendChild(dragElement);
event.dataTransfer.setDragImage(dragElement, 0, 0);
const rect = node.getBoundingClientRect();
const id = node.id;
const clone = node.cloneNode();
clone.style.display = "none";
node.id = null;
node.after(clone);
let _scale = 1;
{
let parentElement = node;
while (parentElement = parentElement.parentElement) {
const { scale } = defaultView.getComputedStyle(parentElement);
if (scale && scale !== "none") {
_scale = parseFloat(scale);
break;
}
}
}
const inverted = 1 / _scale;
const originalNodeProperties = {};
for (const property of [
"transform",
"transformOrigin",
"transition",
"zIndex",
"position",
"top",
"left",
"pointerEvents",
"opacity",
"backgroundColor"
]) {
originalNodeProperties[property] = node.style[property];
}
const originScrollTop = defaultView.scrollY;
const originScrollLeft = defaultView.scrollX;
const originClientX = event.clientX;
const originClientY = event.clientY;
node.style.position = "relative";
node.style.top = `${0}px`;
node.style.left = `${0}px`;
const originX = event.clientX - rect.left;
const originY = event.clientY - rect.top;
const dragScale = rect.height > 200 ? 200 / rect.height : 1;
node.style.zIndex = "1000";
node.style.transformOrigin = `${originX * inverted}px ${originY * inverted}px`;
node.style.transition = "transform 0.2s ease-out";
node.style.transform = `scale(${dragScale})`;
node.style.opacity = "0.9";
if (isColorTransparent(
defaultView.getComputedStyle(node).backgroundColor
)) {
let bgColor = "transparent";
let parentElement = node;
while (parentElement = parentElement.parentElement) {
const { backgroundColor } = defaultView.getComputedStyle(parentElement);
if (!isColorTransparent(backgroundColor)) {
bgColor = backgroundColor;
break;
}
}
node.style.backgroundColor = bgColor;
}
let hasStarted = false;
let lastClientX = originClientX;
let lastClientY = originClientY;
function dragOver(e2) {
if (e2.clientX === lastClientX && e2.clientY === lastClientY) {
return;
}
lastClientX = e2.clientX;
lastClientY = e2.clientY;
over();
}
function over() {
if (!hasStarted) {
hasStarted = true;
node.style.pointerEvents = "none";
}
const pointerYDelta = lastClientY - originClientY;
const pointerXDelta = lastClientX - originClientX;
const scrollTop = defaultView.scrollY;
const scrollLeft = defaultView.scrollX;
const scrollTopDelta = scrollTop - originScrollTop;
const scrollLeftDelta = scrollLeft - originScrollLeft;
const topDelta = pointerYDelta + scrollTopDelta;
const leftDelta = pointerXDelta + scrollLeftDelta;
node.style.top = `${topDelta * inverted}px`;
node.style.left = `${leftDelta * inverted}px`;
}
function end() {
ownerDocument2.removeEventListener("dragover", dragOver);
ownerDocument2.removeEventListener("dragend", end);
ownerDocument2.removeEventListener("drop", end);
ownerDocument2.removeEventListener("scroll", over);
for (const [property, value] of Object.entries(
originalNodeProperties
)) {
node.style[property] = value;
}
clone.remove();
node.id = id;
dragElement.remove();
stopDraggingBlocks2();
document.body.classList.remove(
"is-dragging-components-draggable"
);
ownerDocument2.documentElement.classList.remove(
"is-dragging"
);
}
ownerDocument2.addEventListener("dragover", dragOver);
ownerDocument2.addEventListener("dragend", end);
ownerDocument2.addEventListener("drop", end);
ownerDocument2.addEventListener("scroll", over);
startDraggingBlocks2([clientId]);
document.body.classList.add(
"is-dragging-components-draggable"
);
ownerDocument2.documentElement.classList.add("is-dragging");
}
node.addEventListener("keydown", onKeyDown);
node.addEventListener("dragstart", onDragStart);
function onDoubleClick(event) {
const isSection = isSectionBlock2(clientId);
const block = getBlock2(clientId);
const isSyncedPattern = (0, import_blocks21.isReusableBlock)(block);
const isTemplatePartBlock = (0, import_blocks21.isTemplatePart)(block);
const isAlreadyEditing = editedContentOnlySection2 === clientId;
if (!isSection || isAlreadyEditing || isSyncedPattern || isTemplatePartBlock) {
return;
}
event.preventDefault();
editContentOnlySection2(clientId);
}
node.addEventListener("dblclick", onDoubleClick);
return () => {
node.removeEventListener("keydown", onKeyDown);
node.removeEventListener("dragstart", onDragStart);
node.removeEventListener("dblclick", onDoubleClick);
};
},
[
clientId,
isSelected,
getBlockRootClientId2,
getBlock2,
import_blocks21.isReusableBlock,
import_blocks21.isTemplatePart,
insertAfterBlock2,
removeBlock2,
isZoomOut2,
resetZoomLevel2,
hasMultiSelection2,
startDraggingBlocks2,
stopDraggingBlocks2,
isSectionBlock2,
editedContentOnlySection2,
editContentOnlySection2
]
);
}
// packages/block-editor/build-module/components/block-list/use-block-props/use-intersection-observer.mjs
var import_compose11 = __toESM(require_compose(), 1);
var import_element27 = __toESM(require_element(), 1);
function useIntersectionObserver() {
const observer = (0, import_element27.useContext)(IntersectionObserver2);
return (0, import_compose11.useRefEffect)(
(node) => {
if (observer) {
observer.observe(node);
return () => {
observer.unobserve(node);
};
}
},
[observer]
);
}
// packages/block-editor/build-module/components/block-list/use-block-props/use-scroll-into-view.mjs
var import_compose12 = __toESM(require_compose(), 1);
function useScrollIntoView({ isSelected }) {
const prefersReducedMotion = (0, import_compose12.useReducedMotion)();
return (0, import_compose12.useRefEffect)(
(node) => {
if (isSelected) {
const { ownerDocument: ownerDocument2 } = node;
const { defaultView } = ownerDocument2;
if (!defaultView.IntersectionObserver) {
return;
}
const observer = new defaultView.IntersectionObserver(
(entries) => {
if (!entries[0].isIntersecting) {
node.scrollIntoView({
behavior: prefersReducedMotion ? "instant" : "smooth"
});
}
observer.disconnect();
}
);
observer.observe(node);
return () => {
observer.disconnect();
};
}
},
[isSelected]
);
}
// packages/block-editor/build-module/components/use-flash-editable-blocks/index.mjs
var import_compose13 = __toESM(require_compose(), 1);
var import_data25 = __toESM(require_data(), 1);
function useFlashEditableBlocks({
clientId = "",
isEnabled = true
} = {}) {
const { getEnabledClientIdsTree: getEnabledClientIdsTree2 } = unlock((0, import_data25.useSelect)(store));
return (0, import_compose13.useRefEffect)(
(element) => {
if (!isEnabled) {
return;
}
const flashEditableBlocks = () => {
getEnabledClientIdsTree2(clientId).forEach(
({ clientId: id }) => {
const block = element.querySelector(
`[data-block="${id}"]`
);
if (!block) {
return;
}
block.classList.remove("has-editable-outline");
block.offsetWidth;
block.classList.add("has-editable-outline");
}
);
};
const handleClick = (event) => {
const shouldFlash = event.target === element || event.target.classList.contains("is-root-container");
if (!shouldFlash) {
return;
}
if (event.defaultPrevented) {
return;
}
event.preventDefault();
flashEditableBlocks();
};
element.addEventListener("click", handleClick);
return () => element.removeEventListener("click", handleClick);
},
[isEnabled]
);
}
// packages/block-editor/build-module/components/block-list/use-block-props/use-firefox-draggable-compatibility.mjs
var import_compose14 = __toESM(require_compose(), 1);
var nodesByDocument = /* @__PURE__ */ new Map();
function add(doc, node) {
let set3 = nodesByDocument.get(doc);
if (!set3) {
set3 = /* @__PURE__ */ new Set();
nodesByDocument.set(doc, set3);
doc.addEventListener("pointerdown", down);
}
set3.add(node);
}
function remove3(doc, node) {
const set3 = nodesByDocument.get(doc);
if (set3) {
set3.delete(node);
restore(node);
if (set3.size === 0) {
nodesByDocument.delete(doc);
doc.removeEventListener("pointerdown", down);
}
}
}
function restore(node) {
const prevDraggable = node.getAttribute("data-draggable");
if (prevDraggable) {
node.removeAttribute("data-draggable");
if (prevDraggable === "true" && !node.getAttribute("draggable")) {
node.setAttribute("draggable", "true");
}
}
}
function down(event) {
const { target } = event;
const { ownerDocument: ownerDocument2, isContentEditable, tagName } = target;
const isInputOrTextArea = ["INPUT", "TEXTAREA"].includes(tagName);
const nodes = nodesByDocument.get(ownerDocument2);
if (isContentEditable || isInputOrTextArea) {
for (const node of nodes) {
if (node.getAttribute("draggable") === "true" && node.contains(target)) {
node.removeAttribute("draggable");
node.setAttribute("data-draggable", "true");
}
}
} else {
for (const node of nodes) {
restore(node);
}
}
}
function useFirefoxDraggableCompatibility() {
return (0, import_compose14.useRefEffect)((node) => {
add(node.ownerDocument, node);
return () => {
remove3(node.ownerDocument, node);
};
}, []);
}
// packages/block-editor/build-module/components/block-visibility/modal.mjs
var import_i18n27 = __toESM(require_i18n(), 1);
var import_element28 = __toESM(require_element(), 1);
var import_components24 = __toESM(require_components(), 1);
var import_data26 = __toESM(require_data(), 1);
var import_keyboard_shortcuts = __toESM(require_keyboard_shortcuts(), 1);
var import_notices3 = __toESM(require_notices(), 1);
// packages/block-editor/build-module/components/block-visibility/utils.mjs
var import_i18n26 = __toESM(require_i18n(), 1);
var { getViewportBreakpoints: getViewportBreakpoints3 } = unlock(privateApis);
function getBlockVisibilityViewportEntries(viewportSettings) {
const breakpoints = getViewportBreakpoints3(viewportSettings);
return BLOCK_VISIBILITY_VIEWPORT_ENTRIES.filter(
([viewport]) => (viewport !== BLOCK_VISIBILITY_VIEWPORTS.tablet.key || breakpoints.tablet !== void 0) && (viewport !== BLOCK_VISIBILITY_VIEWPORTS.mobile.key || breakpoints.mobile !== void 0)
);
}
function isBlockHiddenForViewport(block, viewport) {
if (!block) {
return false;
}
const blockVisibility2 = block.attributes?.metadata?.blockVisibility;
if (blockVisibility2 === true) {
return false;
}
if ("object" !== typeof blockVisibility2) {
return false;
}
const viewportConfig = blockVisibility2.viewport;
if (!viewportConfig || "object" !== typeof viewportConfig) {
return false;
}
if (!BLOCK_VISIBILITY_VIEWPORT_ENTRIES.some(
([, { key }]) => key === viewport
)) {
return false;
}
return viewportConfig[viewport] === false;
}
function getViewportCheckboxState(blocks2, viewport) {
if (!blocks2?.length) {
return false;
}
const hiddenCount = blocks2.filter(
(block) => isBlockHiddenForViewport(block, viewport)
).length;
if (hiddenCount === 0) {
return false;
}
if (hiddenCount === blocks2.length) {
return true;
}
return null;
}
function getHideEverywhereCheckboxState(blocks2) {
if (!blocks2?.length) {
return false;
}
const hiddenEverywhereCount = blocks2.filter(
(block) => block && block.attributes?.metadata?.blockVisibility === false
).length;
if (hiddenEverywhereCount === 0) {
return false;
}
if (hiddenEverywhereCount === blocks2.length) {
return true;
}
return null;
}
function getBlockVisibilityLabel(blockVisibility2, viewportSettings) {
if (!blockVisibility2 && blockVisibility2 !== false) {
return null;
}
if (blockVisibility2 === false) {
return (0, import_i18n26.__)("Block is hidden");
}
if (blockVisibility2?.viewport) {
const hiddenViewports = getBlockVisibilityViewportEntries(
viewportSettings
).filter(
([key]) => blockVisibility2.viewport?.[key] === false
).map(([, viewport]) => viewport.label);
if (hiddenViewports.length > 0) {
return (0, import_i18n26.sprintf)(
/* translators: %s: comma-separated list of viewport names (Desktop, Tablet, Mobile) */
(0, import_i18n26.__)("Block is hidden on %s"),
hiddenViewports.join(", ")
);
}
}
return null;
}
// packages/block-editor/build-module/components/block-visibility/modal.mjs
var import_jsx_runtime147 = __toESM(require_jsx_runtime(), 1);
var DEFAULT_VIEWPORT_CHECKBOX_VALUES = {
[BLOCK_VISIBILITY_VIEWPORTS.mobile.key]: false,
[BLOCK_VISIBILITY_VIEWPORTS.tablet.key]: false,
[BLOCK_VISIBILITY_VIEWPORTS.desktop.key]: false
};
var EMPTY_BLOCKS = [];
function BlockVisibilityModal({ clientIds, onClose }) {
const { createSuccessNotice } = (0, import_data26.useDispatch)(import_notices3.store);
const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data26.useDispatch)(store);
const blocks2 = (0, import_data26.useSelect)(
(select3) => select3(store).getBlocksByClientId(clientIds) ?? EMPTY_BLOCKS,
[clientIds]
);
const listViewShortcut = (0, import_data26.useSelect)((select3) => {
return select3(import_keyboard_shortcuts.store).getShortcutRepresentation(
"core/editor/toggle-list-view"
);
}, []);
const viewportSettings = (0, import_data26.useSelect)(
(select3) => select3(store).getSettings().__experimentalFeatures?.viewport,
[]
);
const viewportEntries = (0, import_element28.useMemo)(
() => getBlockVisibilityViewportEntries(viewportSettings),
[viewportSettings]
);
const initialViewportValues = (0, import_element28.useMemo)(() => {
if (blocks2?.length === 0) {
return {
hideEverywhere: false,
viewportChecked: {}
};
}
const viewportValues = {};
viewportEntries.forEach(([, { key }]) => {
viewportValues[key] = getViewportCheckboxState(blocks2, key);
});
return {
hideEverywhere: getHideEverywhereCheckboxState(blocks2),
viewportChecked: viewportValues
};
}, [blocks2, viewportEntries]);
const [viewportChecked, setViewportChecked] = (0, import_element28.useState)(
initialViewportValues?.viewportChecked ?? {}
);
const [hideEverywhere, setHideEverywhere] = (0, import_element28.useState)(
initialViewportValues?.hideEverywhere ?? false
);
const handleViewportCheckboxChange = (0, import_element28.useCallback)(
(viewport, isChecked) => {
setViewportChecked({
...viewportChecked,
[viewport]: isChecked
});
},
[viewportChecked]
);
const noticeMessage = (0, import_element28.useMemo)(() => {
if (!hideEverywhere) {
return (0, import_i18n27.sprintf)(
// translators: %s: The shortcut key to access the List View.
(0, import_i18n27.__)(
"Block visibility settings updated. You can access them via the List View (%s)."
),
listViewShortcut
);
}
const message2 = blocks2?.length > 1 ? (
// translators: %s: The shortcut key to access the List View.
(0, import_i18n27.__)(
"Blocks hidden. You can access them via the List View (%s)."
)
) : (
// translators: %s: The shortcut key to access the List View.
(0, import_i18n27.__)(
"Block hidden. You can access it via the List View (%s)."
)
);
return (0, import_i18n27.sprintf)(message2, listViewShortcut);
}, [hideEverywhere, blocks2?.length, listViewShortcut]);
const isAnyViewportChecked = (0, import_element28.useMemo)(
() => Object.values(viewportChecked).some(
(checked) => checked === true || checked === null
),
[viewportChecked]
);
const isDirty = (0, import_element28.useMemo)(() => {
if (hideEverywhere !== initialViewportValues.hideEverywhere) {
return true;
}
return viewportEntries.some(
([, { key }]) => viewportChecked[key] !== initialViewportValues.viewportChecked[key]
);
}, [
hideEverywhere,
viewportChecked,
initialViewportValues,
viewportEntries
]);
const hasIndeterminateValues = (0, import_element28.useMemo)(() => {
if (hideEverywhere === null) {
return true;
}
return Object.values(viewportChecked).some(
(checked) => checked === null
);
}, [hideEverywhere, viewportChecked]);
const handleSubmit = (0, import_element28.useCallback)(
(event) => {
event.preventDefault();
const newVisibility = hideEverywhere ? false : {
viewport: viewportEntries.reduce(
(acc, [, { key }]) => {
if (viewportChecked[key]) {
acc[key] = false;
}
return acc;
},
{}
)
};
const attributesByClientId = Object.fromEntries(
blocks2.map(({ clientId, attributes }) => [
clientId,
{
metadata: cleanEmptyObject({
...attributes?.metadata,
blockVisibility: newVisibility
})
}
])
);
updateBlockAttributes2(clientIds, attributesByClientId, {
uniqueByBlock: true
});
createSuccessNotice(noticeMessage, {
id: hideEverywhere ? "block-visibility-hidden" : "block-visibility-viewports-updated",
type: "snackbar"
});
onClose();
},
[
blocks2,
clientIds,
createSuccessNotice,
hideEverywhere,
noticeMessage,
onClose,
updateBlockAttributes2,
viewportEntries,
viewportChecked
]
);
const hasMultipleBlocks = blocks2?.length > 1;
return /* @__PURE__ */ (0, import_jsx_runtime147.jsx)(
import_components24.Modal,
{
title: clientIds?.length > 1 ? (0, import_i18n27.__)("Hide blocks") : (0, import_i18n27.__)("Hide block"),
onRequestClose: onClose,
overlayClassName: "block-editor-block-visibility-modal",
size: "small",
children: /* @__PURE__ */ (0, import_jsx_runtime147.jsxs)("form", { onSubmit: handleSubmit, children: [
/* @__PURE__ */ (0, import_jsx_runtime147.jsxs)("fieldset", { children: [
/* @__PURE__ */ (0, import_jsx_runtime147.jsx)("legend", { children: hasMultipleBlocks ? (0, import_i18n27.__)(
"Select the viewport sizes for which you want to hide the blocks. Changes will apply to all selected blocks."
) : (0, import_i18n27.__)(
"Select the viewport size for which you want to hide the block."
) }),
/* @__PURE__ */ (0, import_jsx_runtime147.jsx)("ul", { className: "block-editor-block-visibility-modal__options", children: /* @__PURE__ */ (0, import_jsx_runtime147.jsxs)("li", { className: "block-editor-block-visibility-modal__options-item block-editor-block-visibility-modal__options-item--everywhere", children: [
/* @__PURE__ */ (0, import_jsx_runtime147.jsx)(
import_components24.CheckboxControl,
{
className: "block-editor-block-visibility-modal__options-checkbox--everywhere",
label: (0, import_i18n27.__)("Omit from published content"),
checked: hideEverywhere === true,
indeterminate: hideEverywhere === null,
onChange: (checked) => {
setHideEverywhere(checked);
setViewportChecked(
DEFAULT_VIEWPORT_CHECKBOX_VALUES
);
}
}
),
hideEverywhere !== true && /* @__PURE__ */ (0, import_jsx_runtime147.jsx)("ul", { className: "block-editor-block-visibility-modal__sub-options", children: viewportEntries.map(
([, { label, icon, key }]) => /* @__PURE__ */ (0, import_jsx_runtime147.jsxs)(
"li",
{
className: "block-editor-block-visibility-modal__options-item",
children: [
/* @__PURE__ */ (0, import_jsx_runtime147.jsx)(
import_components24.CheckboxControl,
{
label: (0, import_i18n27.sprintf)(
// translators: %s: The viewport name.
(0, import_i18n27.__)("Hide on %s"),
label
),
checked: viewportChecked[key] ?? false,
indeterminate: viewportChecked[key] === null,
onChange: (checked) => handleViewportCheckboxChange(
key,
checked
)
}
),
/* @__PURE__ */ (0, import_jsx_runtime147.jsx)(
import_components24.Icon,
{
icon,
className: clsx_default({
"block-editor-block-visibility-modal__options-icon--checked": viewportChecked[key]
})
}
)
]
},
key
)
) })
] }) }),
hasMultipleBlocks && hasIndeterminateValues && /* @__PURE__ */ (0, import_jsx_runtime147.jsx)("p", { className: "block-editor-block-visibility-modal__description", children: (0, import_i18n27.__)(
"Selected blocks have different visibility settings. The checkboxes show an indeterminate state when settings differ."
) }),
!hasMultipleBlocks && hideEverywhere === true && /* @__PURE__ */ (0, import_jsx_runtime147.jsx)("p", { className: "block-editor-block-visibility-modal__description", children: (0, import_i18n27.sprintf)(
// translators: %s: The shortcut key to access the List View.
(0, import_i18n27.__)(
"Block will be hidden in the editor, and omitted from the published markup on the frontend. You can configure it again by selecting it in the List View (%s)."
),
listViewShortcut
) }),
!hasMultipleBlocks && !hideEverywhere && isAnyViewportChecked && /* @__PURE__ */ (0, import_jsx_runtime147.jsx)("p", { className: "block-editor-block-visibility-modal__description", children: (0, import_element28.createInterpolateElement)(
(0, import_i18n27.sprintf)(
// translators: %s: The shortcut key to access the List View
(0, import_i18n27.__)(
"Block will be hidden according to the selected viewports. It will be <strong>included in the published markup on the frontend</strong>. You can configure it again by selecting it in the List View (%s)."
),
listViewShortcut
),
{
strong: /* @__PURE__ */ (0, import_jsx_runtime147.jsx)("strong", {})
}
) })
] }),
/* @__PURE__ */ (0, import_jsx_runtime147.jsxs)(
import_components24.Flex,
{
className: "block-editor-block-visibility-modal__actions",
justify: "flex-end",
expanded: false,
children: [
/* @__PURE__ */ (0, import_jsx_runtime147.jsx)(import_components24.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime147.jsx)(
import_components24.Button,
{
variant: "tertiary",
onClick: onClose,
__next40pxDefaultSize: true,
children: (0, import_i18n27.__)("Cancel")
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime147.jsx)(import_components24.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime147.jsx)(
import_components24.Button,
{
variant: "primary",
type: "submit",
disabled: !isDirty,
accessibleWhenDisabled: true,
__next40pxDefaultSize: true,
children: (0, import_i18n27.__)("Apply")
}
) })
]
}
)
] })
}
);
}
// packages/block-editor/build-module/components/block-visibility/use-block-visibility.mjs
var import_compose15 = __toESM(require_compose(), 1);
var { getViewportBreakpoints: getViewportBreakpoints4 } = unlock(privateApis);
function useBlockVisibility(options = {}) {
const {
blockVisibility: blockVisibility2 = void 0,
deviceType = BLOCK_VISIBILITY_VIEWPORTS.desktop.key,
viewportSettings,
view = window
} = options;
const viewportBreakpoints = getViewportBreakpoints4(viewportSettings);
const mobileMediaQuery = viewportBreakpoints.mobile ? `(width <= ${viewportBreakpoints.mobile})` : void 0;
const isMobileViewport = (0, import_compose15.useMediaQuery)(mobileMediaQuery, view);
let tabletMediaQuery;
if (viewportBreakpoints.tablet) {
tabletMediaQuery = viewportBreakpoints.mobile ? `(${viewportBreakpoints.mobile} < width <= ${viewportBreakpoints.tablet})` : `(width <= ${viewportBreakpoints.tablet})`;
}
const isTabletViewport = (0, import_compose15.useMediaQuery)(tabletMediaQuery, view);
let currentViewport;
if (deviceType === BLOCK_VISIBILITY_VIEWPORTS.mobile.key && viewportBreakpoints.mobile) {
currentViewport = BLOCK_VISIBILITY_VIEWPORTS.mobile.key;
} else if (deviceType === BLOCK_VISIBILITY_VIEWPORTS.tablet.key && viewportBreakpoints.tablet) {
currentViewport = BLOCK_VISIBILITY_VIEWPORTS.tablet.key;
} else if (isMobileViewport) {
currentViewport = BLOCK_VISIBILITY_VIEWPORTS.mobile.key;
} else if (isTabletViewport && viewportBreakpoints.tablet) {
currentViewport = BLOCK_VISIBILITY_VIEWPORTS.tablet.key;
} else {
currentViewport = BLOCK_VISIBILITY_VIEWPORTS.desktop.key;
}
const isBlockCurrentlyHidden = blockVisibility2 === false || blockVisibility2?.viewport?.[currentViewport] === false;
return { isBlockCurrentlyHidden, currentViewport };
}
// packages/block-editor/build-module/components/block-visibility/viewport-toolbar.mjs
var import_i18n28 = __toESM(require_i18n(), 1);
var import_components25 = __toESM(require_components(), 1);
var import_element29 = __toESM(require_element(), 1);
var import_blocks22 = __toESM(require_blocks(), 1);
var import_data27 = __toESM(require_data(), 1);
var import_jsx_runtime148 = __toESM(require_jsx_runtime(), 1);
function BlockVisibilityViewportToolbar({ clientIds }) {
const hasBlockVisibilityButtonShownRef = (0, import_element29.useRef)(false);
const [blockVisibility2] = useSettings("blockVisibility.allowEditing");
const { canToggleBlockVisibility, areBlocksHiddenAnywhere } = (0, import_data27.useSelect)(
(select3) => {
const { getBlocksByClientId: getBlocksByClientId2, getBlockName: getBlockName2, isBlockHiddenAnywhere: isBlockHiddenAnywhere2 } = unlock(select3(store));
const _blocks = getBlocksByClientId2(clientIds);
return {
canToggleBlockVisibility: _blocks.every(
({ clientId }) => (0, import_blocks22.hasBlockSupport)(
getBlockName2(clientId),
"visibility",
true
)
),
areBlocksHiddenAnywhere: clientIds?.every(
(clientId) => isBlockHiddenAnywhere2(clientId)
)
};
},
[clientIds]
);
const blockEditorDispatch = (0, import_data27.useDispatch)(store);
(0, import_element29.useEffect)(() => {
if (areBlocksHiddenAnywhere) {
hasBlockVisibilityButtonShownRef.current = true;
}
}, [areBlocksHiddenAnywhere]);
if (blockVisibility2 === false) {
return null;
}
if (!areBlocksHiddenAnywhere && !hasBlockVisibilityButtonShownRef.current) {
return null;
}
const { showViewportModal: showViewportModal2 } = unlock(blockEditorDispatch);
return /* @__PURE__ */ (0, import_jsx_runtime148.jsx)(import_components25.ToolbarGroup, { className: "block-editor-block-visibility-toolbar", children: /* @__PURE__ */ (0, import_jsx_runtime148.jsx)(
import_components25.ToolbarButton,
{
disabled: !canToggleBlockVisibility,
icon: areBlocksHiddenAnywhere ? unseen_default : seen_default,
label: areBlocksHiddenAnywhere ? (0, import_i18n28.__)("Hidden") : (0, import_i18n28.__)("Visible"),
onClick: () => showViewportModal2(clientIds),
"aria-haspopup": "dialog"
}
) });
}
// packages/block-editor/build-module/components/block-visibility/viewport-menu-item.mjs
var import_i18n29 = __toESM(require_i18n(), 1);
var import_components26 = __toESM(require_components(), 1);
var import_data28 = __toESM(require_data(), 1);
var import_keyboard_shortcuts2 = __toESM(require_keyboard_shortcuts(), 1);
var import_jsx_runtime149 = __toESM(require_jsx_runtime(), 1);
function BlockVisibilityViewportMenuItem({ clientIds }) {
const [blockVisibility2] = useSettings("blockVisibility.allowEditing");
const { areBlocksHiddenAnywhere, shortcut } = (0, import_data28.useSelect)(
(select3) => {
const { isBlockHiddenAnywhere: isBlockHiddenAnywhere2 } = unlock(
select3(store)
);
return {
areBlocksHiddenAnywhere: clientIds?.every(
(clientId) => isBlockHiddenAnywhere2(clientId)
),
shortcut: select3(
import_keyboard_shortcuts2.store
).getShortcutRepresentation(
"core/block-editor/toggle-block-visibility"
)
};
},
[clientIds]
);
const dispatch = (0, import_data28.useDispatch)(store);
if (blockVisibility2 === false) {
return null;
}
const { showViewportModal: showViewportModal2 } = unlock(dispatch);
return /* @__PURE__ */ (0, import_jsx_runtime149.jsx)(
import_components26.MenuItem,
{
onClick: () => showViewportModal2(clientIds),
shortcut,
children: areBlocksHiddenAnywhere ? (0, import_i18n29.__)("Show") : (0, import_i18n29.__)("Hide")
}
);
}
// packages/block-editor/build-module/components/block-visibility/viewport-visibility-info.mjs
var import_components27 = __toESM(require_components(), 1);
var import_data29 = __toESM(require_data(), 1);
var import_i18n30 = __toESM(require_i18n(), 1);
var import_jsx_runtime150 = __toESM(require_jsx_runtime(), 1);
var { Badge: WCBadge } = unlock(import_components27.privateApis);
var DEFAULT_VISIBILITY_STATE = {
currentBlockVisibility: void 0,
hasParentHiddenEverywhere: false,
selectedDeviceType: BLOCK_VISIBILITY_VIEWPORTS.desktop.key
};
function ViewportVisibilityInfo({ clientId }) {
const {
currentBlockVisibility,
selectedDeviceType,
viewportSettings,
hasParentHiddenEverywhere
} = (0, import_data29.useSelect)(
(select3) => {
if (!clientId) {
return DEFAULT_VISIBILITY_STATE;
}
const {
getBlockAttributes: getBlockAttributes3,
isBlockParentHiddenEverywhere: isBlockParentHiddenEverywhere2,
getSettings: getSettings7
} = unlock(select3(store));
const settings2 = getSettings7();
return {
currentBlockVisibility: getBlockAttributes3(clientId)?.metadata?.blockVisibility,
selectedDeviceType: settings2?.[deviceTypeKey]?.toLowerCase() || BLOCK_VISIBILITY_VIEWPORTS.desktop.key,
viewportSettings: settings2?.__experimentalFeatures?.viewport,
hasParentHiddenEverywhere: isBlockParentHiddenEverywhere2(clientId)
};
},
[clientId]
);
const blockElement = useBlockElement(clientId);
const rawCanvasView = blockElement?.ownerDocument?.defaultView;
const canvasView = rawCanvasView === null ? void 0 : rawCanvasView;
const { isBlockCurrentlyHidden, currentViewport } = useBlockVisibility({
blockVisibility: currentBlockVisibility,
deviceType: selectedDeviceType,
viewportSettings,
view: canvasView
});
const isBlockParentHiddenAtViewport2 = (0, import_data29.useSelect)(
(select3) => {
if (!clientId || !currentViewport) {
return false;
}
return unlock(
select3(store)
).isBlockParentHiddenAtViewport(clientId, currentViewport);
},
[clientId, currentViewport]
);
if (!(isBlockCurrentlyHidden || hasParentHiddenEverywhere || isBlockParentHiddenAtViewport2)) {
return null;
}
let label;
if (isBlockCurrentlyHidden) {
if (currentBlockVisibility === false) {
label = (0, import_i18n30.__)("Block is hidden");
} else {
const viewportLabel = BLOCK_VISIBILITY_VIEWPORTS[currentViewport]?.label || currentViewport;
label = (0, import_i18n30.sprintf)(
/* translators: %s: viewport name (Desktop, Tablet, Mobile) */
(0, import_i18n30.__)("Block is hidden on %s"),
viewportLabel
);
}
}
if (hasParentHiddenEverywhere) {
label = (0, import_i18n30.__)("Parent block is hidden");
} else if (isBlockParentHiddenAtViewport2) {
const viewportLabel = BLOCK_VISIBILITY_VIEWPORTS[currentViewport]?.label || currentViewport;
label = (0, import_i18n30.sprintf)(
/* translators: %s: viewport name (Desktop, Tablet, Mobile) */
(0, import_i18n30.__)("Parent block is hidden on %s"),
viewportLabel
);
}
return /* @__PURE__ */ (0, import_jsx_runtime150.jsx)(WCBadge, { className: "block-editor-block-visibility-info", children: /* @__PURE__ */ (0, import_jsx_runtime150.jsxs)(import_components27.__experimentalHStack, { spacing: 2, justify: "start", children: [
/* @__PURE__ */ (0, import_jsx_runtime150.jsx)(import_components27.Icon, { icon: unseen_default }),
/* @__PURE__ */ (0, import_jsx_runtime150.jsx)(import_components27.__experimentalText, { children: label })
] }) });
}
// packages/block-editor/build-module/components/block-list/use-block-props/index.mjs
function useBlockProps(props = {}, { __unstableIsHtml } = {}) {
const {
clientId,
className,
wrapperProps = {},
isAligned,
index: index2,
mode: mode2,
name,
blockApiVersion,
blockTitle,
isSelected,
isSubtreeDisabled,
hasOverlay,
initialPosition: initialPosition2,
blockEditingMode,
isHighlighted,
isMultiSelected,
isPartiallySelected,
isReusable,
isDragging: isDragging3,
hasChildSelected,
isEditingDisabled,
hasEditableOutline,
isEditingContentOnlySection,
defaultClassName,
isSectionBlock: isSectionBlock2,
isWithinSectionBlock,
canMove,
blockVisibility: blockVisibility2,
deviceType,
viewportSettings
} = (0, import_element30.useContext)(PrivateBlockContext);
const defaultViewRef = (0, import_compose16.useRefEffect)((element) => {
if (element) {
const { ownerDocument: ownerDocument2 } = element;
const { defaultView } = ownerDocument2;
defaultViewRef.current = defaultView;
}
}, []);
const blockLabel = (0, import_i18n31.sprintf)((0, import_i18n31.__)("Block: %s"), blockTitle);
const htmlSuffix = mode2 === "html" && !__unstableIsHtml ? "-visual" : "";
const ffDragRef = useFirefoxDraggableCompatibility();
const isHoverEnabled = !isWithinSectionBlock;
const mergedRefs = (0, import_compose16.useMergeRefs)([
props.ref,
defaultViewRef,
useFocusFirstElement({ clientId, initialPosition: initialPosition2 }),
useBlockRefProvider(clientId),
useFocusHandler(clientId),
useEventHandlers({ clientId, isSelected }),
useIsHovered({ isEnabled: isHoverEnabled }),
useIntersectionObserver(),
use_moving_animation_default({ triggerAnimationOnChange: index2, clientId }),
(0, import_compose16.useDisabled)({ isDisabled: !hasOverlay }),
useFlashEditableBlocks({
clientId,
isEnabled: isSectionBlock2
}),
useScrollIntoView({ isSelected }),
canMove ? ffDragRef : void 0
]);
const blockEditContext = useBlockEditContext();
const hasBlockBindings = !!blockEditContext[blockBindingsKey];
const bindingsStyle = hasBlockBindings ? {
"--wp-admin-theme-color": "var(--wp-block-synced-color)",
"--wp-admin-theme-color--rgb": "var(--wp-block-synced-color--rgb)"
} : {};
const { isBlockCurrentlyHidden } = useBlockVisibility({
blockVisibility: blockVisibility2,
deviceType,
viewportSettings,
view: defaultViewRef.current
});
if (blockApiVersion < 2 && clientId === blockEditContext.clientId) {
(0, import_warning4.default)(
`Block type "${name}" must support API version 2 or higher to work correctly with "useBlockProps" method.`
);
}
let hasNegativeMargin = false;
if (wrapperProps?.style?.marginTop?.charAt(0) === "-" || wrapperProps?.style?.marginBottom?.charAt(0) === "-" || wrapperProps?.style?.marginLeft?.charAt(0) === "-" || wrapperProps?.style?.marginRight?.charAt(0) === "-") {
hasNegativeMargin = true;
}
return {
tabIndex: blockEditingMode === "disabled" ? -1 : 0,
draggable: canMove && !hasChildSelected ? true : void 0,
...wrapperProps,
...props,
ref: mergedRefs,
id: `block-${clientId}${htmlSuffix}`,
role: "document",
"aria-label": blockLabel,
"data-block": clientId,
"data-type": name,
"data-title": blockTitle,
inert: isSubtreeDisabled ? "true" : void 0,
className: clsx_default(
"block-editor-block-list__block",
{
// The wp-block className is important for editor styles.
"wp-block": !isAligned,
"has-block-overlay": hasOverlay,
"is-selected": isSelected,
"is-highlighted": isHighlighted,
"is-multi-selected": isMultiSelected,
"is-partially-selected": isPartiallySelected,
"is-reusable": isReusable,
"is-dragging": isDragging3,
"has-child-selected": hasChildSelected,
"is-editing-disabled": isEditingDisabled,
"has-editable-outline": hasEditableOutline,
"has-negative-margin": hasNegativeMargin,
"is-editing-content-only-section": isEditingContentOnlySection,
"is-block-hidden": isBlockCurrentlyHidden
},
className,
props.className,
wrapperProps.className,
defaultClassName
),
style: { ...wrapperProps.style, ...props.style, ...bindingsStyle }
};
}
useBlockProps.save = import_blocks23.__unstableGetBlockProps;
// packages/block-editor/build-module/components/block-list/block.mjs
var import_jsx_runtime151 = __toESM(require_jsx_runtime(), 1);
function mergeWrapperProps(propsA, propsB) {
const newProps = {
...propsA,
...propsB
};
if (propsA?.hasOwnProperty("className") && propsB?.hasOwnProperty("className")) {
newProps.className = clsx_default(propsA.className, propsB.className);
}
if (propsA?.hasOwnProperty("style") && propsB?.hasOwnProperty("style")) {
newProps.style = { ...propsA.style, ...propsB.style };
}
return newProps;
}
function Block({ children, isHtml, ...props }) {
return /* @__PURE__ */ (0, import_jsx_runtime151.jsx)("div", { ...useBlockProps(props, { __unstableIsHtml: isHtml }), children });
}
function BlockListBlock({
block: { __unstableBlockSource },
mode: mode2,
isLocked,
canRemove,
clientId,
isSelected,
isSelectionEnabled: isSelectionEnabled3,
className,
__unstableLayoutClassNames: layoutClassNames,
name,
isValid: isValid2,
attributes,
wrapperProps,
setAttributes,
onReplace,
onRemove,
onInsertBlocksAfter,
onMerge,
toggleSelection: toggleSelection2
}) {
const {
mayDisplayControls,
mayDisplayParentControls,
isSelectionWithinCurrentSection,
themeSupportsLayout,
...context
} = (0, import_element31.useContext)(PrivateBlockContext);
const parentLayout = useLayout() || {};
let blockEdit = /* @__PURE__ */ (0, import_jsx_runtime151.jsx)(
BlockEdit,
{
name,
isSelected,
attributes,
setAttributes,
insertBlocksAfter: isLocked ? void 0 : onInsertBlocksAfter,
onReplace: canRemove ? onReplace : void 0,
onRemove: canRemove ? onRemove : void 0,
mergeBlocks: canRemove ? onMerge : void 0,
clientId,
isSelectionEnabled: isSelectionEnabled3,
toggleSelection: toggleSelection2,
__unstableLayoutClassNames: layoutClassNames,
__unstableParentLayout: Object.keys(parentLayout).length ? parentLayout : void 0,
mayDisplayControls,
mayDisplayParentControls,
mayDisplayPatternEditingControls: isSelectionWithinCurrentSection,
blockEditingMode: context.blockEditingMode,
isPreviewMode: context.isPreviewMode
}
);
const blockType = (0, import_blocks24.getBlockType)(name);
if (blockType?.getEditWrapperProps) {
wrapperProps = mergeWrapperProps(
wrapperProps,
blockType.getEditWrapperProps(attributes)
);
}
const isAligned = wrapperProps && !!wrapperProps["data-align"] && !themeSupportsLayout;
const isSticky = className?.includes("is-position-sticky");
if (isAligned) {
blockEdit = /* @__PURE__ */ (0, import_jsx_runtime151.jsx)(
"div",
{
className: clsx_default("wp-block", isSticky && className),
"data-align": wrapperProps["data-align"],
children: blockEdit
}
);
}
let block;
if (!isValid2) {
const saveContent = __unstableBlockSource ? (0, import_blocks24.serializeRawBlock)(__unstableBlockSource) : (0, import_blocks24.getSaveContent)(blockType, attributes);
block = /* @__PURE__ */ (0, import_jsx_runtime151.jsxs)(Block, { className: "has-warning", children: [
/* @__PURE__ */ (0, import_jsx_runtime151.jsx)(BlockInvalidWarning, { clientId }),
/* @__PURE__ */ (0, import_jsx_runtime151.jsx)(import_element31.RawHTML, { children: (0, import_dom9.safeHTML)(saveContent) })
] });
} else if (mode2 === "html") {
block = /* @__PURE__ */ (0, import_jsx_runtime151.jsxs)(import_jsx_runtime151.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime151.jsx)("div", { style: { display: "none" }, children: blockEdit }),
/* @__PURE__ */ (0, import_jsx_runtime151.jsx)(Block, { isHtml: true, children: /* @__PURE__ */ (0, import_jsx_runtime151.jsx)(block_html_default, { clientId }) })
] });
} else if (blockType?.apiVersion > 1) {
block = blockEdit;
} else {
block = /* @__PURE__ */ (0, import_jsx_runtime151.jsx)(Block, { children: blockEdit });
}
const { "data-align": dataAlign, ...restWrapperProps } = wrapperProps ?? {};
const updatedWrapperProps = {
...restWrapperProps,
className: clsx_default(
restWrapperProps.className,
dataAlign && themeSupportsLayout && `align${dataAlign}`,
!(dataAlign && isSticky) && className
)
};
return /* @__PURE__ */ (0, import_jsx_runtime151.jsx)(
PrivateBlockContext.Provider,
{
value: {
wrapperProps: updatedWrapperProps,
isAligned,
isSelectionWithinCurrentSection,
...context
},
children: /* @__PURE__ */ (0, import_jsx_runtime151.jsx)(
block_crash_boundary_default,
{
fallback: /* @__PURE__ */ (0, import_jsx_runtime151.jsx)(Block, { className: "has-warning", children: /* @__PURE__ */ (0, import_jsx_runtime151.jsx)(BlockCrashWarning, {}) }),
children: block
}
)
}
);
}
var applyWithDispatch = (0, import_data30.withDispatch)((dispatch, ownProps, registry) => {
const {
updateBlockAttributes: updateBlockAttributes2,
insertBlocks: insertBlocks2,
mergeBlocks: mergeBlocks2,
replaceBlocks: replaceBlocks2,
toggleSelection: toggleSelection2,
__unstableMarkLastChangeAsPersistent: __unstableMarkLastChangeAsPersistent2,
moveBlocksToPosition: moveBlocksToPosition2,
removeBlock: removeBlock2,
selectBlock: selectBlock2
} = dispatch(store);
return {
setAttributes(nextAttributes) {
const { getMultiSelectedBlockClientIds: getMultiSelectedBlockClientIds2 } = registry.select(store);
const multiSelectedBlockClientIds = getMultiSelectedBlockClientIds2();
const { clientId, attributes } = ownProps;
const clientIds = multiSelectedBlockClientIds.length ? multiSelectedBlockClientIds : [clientId];
const newAttributes = typeof nextAttributes === "function" ? nextAttributes(attributes) : nextAttributes;
updateBlockAttributes2(clientIds, newAttributes);
},
onInsertBlocks(blocks2, index2) {
const { rootClientId } = ownProps;
insertBlocks2(blocks2, index2, rootClientId);
},
onInsertBlocksAfter(blocks2) {
const { clientId, rootClientId } = ownProps;
const { getBlockIndex: getBlockIndex2 } = registry.select(store);
const index2 = getBlockIndex2(clientId);
insertBlocks2(blocks2, index2 + 1, rootClientId);
},
onMerge(forward) {
const { clientId, rootClientId } = ownProps;
const {
getPreviousBlockClientId: getPreviousBlockClientId2,
getNextBlockClientId: getNextBlockClientId2,
getBlock: getBlock2,
getBlockAttributes: getBlockAttributes3,
getBlockName: getBlockName2,
getBlockOrder: getBlockOrder2,
getBlockIndex: getBlockIndex2,
getBlockRootClientId: getBlockRootClientId2,
canInsertBlockType: canInsertBlockType2
} = registry.select(store);
function switchToDefaultOrRemove() {
const block = getBlock2(clientId);
const defaultBlockName = (0, import_blocks24.getDefaultBlockName)();
const defaultBlockType = (0, import_blocks24.getBlockType)(defaultBlockName);
if (getBlockName2(clientId) !== defaultBlockName) {
const replacement = (0, import_blocks24.switchToBlockType)(
block,
defaultBlockName
);
if (replacement && replacement.length) {
replaceBlocks2(clientId, replacement);
}
} else if ((0, import_blocks24.isUnmodifiedDefaultBlock)(block)) {
const nextBlockClientId = getNextBlockClientId2(clientId);
if (nextBlockClientId) {
registry.batch(() => {
removeBlock2(clientId);
selectBlock2(nextBlockClientId);
});
}
} else if (defaultBlockType.merge) {
const attributes = defaultBlockType.merge(
{},
block.attributes
);
replaceBlocks2(
[clientId],
[(0, import_blocks24.createBlock)(defaultBlockName, attributes)]
);
}
}
function moveFirstItemUp(_clientId, changeSelection = true) {
const wrapperBlockName = getBlockName2(_clientId);
const wrapperBlockType = (0, import_blocks24.getBlockType)(wrapperBlockName);
const isTextualWrapper = wrapperBlockType.category === "text";
const targetRootClientId = getBlockRootClientId2(_clientId);
const blockOrder = getBlockOrder2(_clientId);
const [firstClientId] = blockOrder;
if (blockOrder.length === 1 && (0, import_blocks24.isUnmodifiedBlock)(getBlock2(firstClientId))) {
removeBlock2(_clientId);
} else if (isTextualWrapper) {
registry.batch(() => {
if (canInsertBlockType2(
getBlockName2(firstClientId),
targetRootClientId
)) {
moveBlocksToPosition2(
[firstClientId],
_clientId,
targetRootClientId,
getBlockIndex2(_clientId)
);
} else {
const replacement = (0, import_blocks24.switchToBlockType)(
getBlock2(firstClientId),
(0, import_blocks24.getDefaultBlockName)()
);
if (replacement && replacement.length && replacement.every(
(block) => canInsertBlockType2(
block.name,
targetRootClientId
)
)) {
insertBlocks2(
replacement,
getBlockIndex2(_clientId),
targetRootClientId,
changeSelection
);
removeBlock2(firstClientId, false);
} else {
switchToDefaultOrRemove();
}
}
if (!getBlockOrder2(_clientId).length && (0, import_blocks24.isUnmodifiedBlock)(getBlock2(_clientId))) {
removeBlock2(_clientId, false);
}
});
} else {
switchToDefaultOrRemove();
}
}
if (forward) {
if (rootClientId) {
const nextRootClientId = getNextBlockClientId2(rootClientId);
if (nextRootClientId) {
if (getBlockName2(rootClientId) === getBlockName2(nextRootClientId)) {
const rootAttributes = getBlockAttributes3(rootClientId);
const previousRootAttributes = getBlockAttributes3(nextRootClientId);
if (Object.keys(rootAttributes).every(
(key) => rootAttributes[key] === previousRootAttributes[key]
)) {
registry.batch(() => {
moveBlocksToPosition2(
getBlockOrder2(nextRootClientId),
nextRootClientId,
rootClientId
);
removeBlock2(nextRootClientId, false);
});
return;
}
} else {
mergeBlocks2(rootClientId, nextRootClientId);
return;
}
}
}
const nextBlockClientId = getNextBlockClientId2(clientId);
if (!nextBlockClientId) {
return;
}
if (getBlockOrder2(nextBlockClientId).length) {
moveFirstItemUp(nextBlockClientId, false);
} else {
mergeBlocks2(clientId, nextBlockClientId);
}
} else {
const previousBlockClientId = getPreviousBlockClientId2(clientId);
if (previousBlockClientId) {
mergeBlocks2(previousBlockClientId, clientId);
} else if (rootClientId) {
const previousRootClientId = getPreviousBlockClientId2(rootClientId);
if (previousRootClientId && getBlockName2(rootClientId) === getBlockName2(previousRootClientId)) {
const rootAttributes = getBlockAttributes3(rootClientId);
const previousRootAttributes = getBlockAttributes3(previousRootClientId);
if (Object.keys(rootAttributes).every(
(key) => rootAttributes[key] === previousRootAttributes[key]
)) {
registry.batch(() => {
moveBlocksToPosition2(
getBlockOrder2(rootClientId),
rootClientId,
previousRootClientId
);
removeBlock2(rootClientId, false);
});
return;
}
}
moveFirstItemUp(rootClientId);
} else {
switchToDefaultOrRemove();
}
}
},
onReplace(blocks2, indexToSelect, initialPosition2) {
if (blocks2.length && !(0, import_blocks24.isUnmodifiedDefaultBlock)(blocks2[blocks2.length - 1])) {
__unstableMarkLastChangeAsPersistent2();
}
const replacementBlocks = blocks2?.length === 1 && Array.isArray(blocks2[0]) ? blocks2[0] : blocks2;
replaceBlocks2(
[ownProps.clientId],
replacementBlocks,
indexToSelect,
initialPosition2
);
},
onRemove() {
removeBlock2(ownProps.clientId);
},
toggleSelection(selectionEnabled) {
toggleSelection2(selectionEnabled);
}
};
});
BlockListBlock = (0, import_compose17.compose)(
applyWithDispatch,
(0, import_components28.withFilters)("editor.BlockListBlock")
)(BlockListBlock);
function BlockListBlockProvider(props) {
const { clientId, rootClientId } = props;
const selectedProps = (0, import_data30.useSelect)(
(select3) => {
const {
isBlockSelected: isBlockSelected2,
getBlockMode: getBlockMode2,
isSelectionEnabled: isSelectionEnabled22,
getTemplateLock: getTemplateLock2,
isSectionBlock: _isSectionBlock,
getParentSectionBlock: getParentSectionBlock2,
getBlockWithoutAttributes: getBlockWithoutAttributes2,
getBlockAttributes: getBlockAttributes3,
canRemoveBlock: canRemoveBlock2,
canMoveBlock: canMoveBlock2,
getSettings: getSettings7,
getEditedContentOnlySection: getEditedContentOnlySection2,
getBlockEditingMode: getBlockEditingMode2,
getBlockName: getBlockName2,
isFirstMultiSelectedBlock: isFirstMultiSelectedBlock2,
getMultiSelectedBlockClientIds: getMultiSelectedBlockClientIds2,
hasSelectedInnerBlock: hasSelectedInnerBlock2,
getBlocksByName: getBlocksByName2,
getBlockIndex: getBlockIndex2,
isBlockMultiSelected: isBlockMultiSelected2,
isBlockSubtreeDisabled: isBlockSubtreeDisabled2,
isBlockHighlighted: isBlockHighlighted2,
__unstableIsFullySelected: __unstableIsFullySelected2,
__unstableSelectionHasUnmergeableBlock: __unstableSelectionHasUnmergeableBlock2,
isBlockBeingDragged: isBlockBeingDragged2,
isDragging: isDragging22,
__unstableHasActiveBlockOverlayActive: __unstableHasActiveBlockOverlayActive2,
getSelectedBlocksInitialCaretPosition: getSelectedBlocksInitialCaretPosition2
} = unlock(select3(store));
const blockWithoutAttributes = getBlockWithoutAttributes2(clientId);
if (!blockWithoutAttributes) {
return;
}
const {
hasBlockSupport: _hasBlockSupport,
getActiveBlockVariation
} = select3(import_blocks24.store);
const attributes2 = getBlockAttributes3(clientId);
const { name: blockName, isValid: isValid22 } = blockWithoutAttributes;
const blockType2 = (0, import_blocks24.getBlockType)(blockName);
const settings2 = getSettings7();
const {
supportsLayout,
isPreviewMode: isPreviewMode2,
__experimentalBlockBindingsSupportedAttributes
} = settings2;
const bindableAttributes2 = __experimentalBlockBindingsSupportedAttributes?.[blockName];
const blockVisibility22 = attributes2?.metadata?.blockVisibility;
const deviceType2 = settings2?.[deviceTypeKey]?.toLowerCase() || "desktop";
const viewportSettings2 = settings2?.__experimentalFeatures?.viewport;
const hasLightBlockWrapper = blockType2?.apiVersion > 1;
const isMultiSelected2 = isBlockMultiSelected2(clientId);
const blockEditingMode2 = getBlockEditingMode2(clientId);
const previewContext = {
isPreviewMode: isPreviewMode2,
blockWithoutAttributes,
name: blockName,
attributes: attributes2,
isValid: isValid22,
themeSupportsLayout: supportsLayout,
index: getBlockIndex2(clientId),
isReusable: (0, import_blocks24.isReusableBlock)(blockType2),
className: hasLightBlockWrapper ? attributes2.className : void 0,
defaultClassName: hasLightBlockWrapper ? (0, import_blocks24.getBlockDefaultClassName)(blockName) : void 0,
blockTitle: blockType2?.title,
bindableAttributes: bindableAttributes2,
blockVisibility: blockVisibility22,
deviceType: deviceType2,
viewportSettings: viewportSettings2,
isMultiSelected: isMultiSelected2,
blockEditingMode: blockEditingMode2,
isEditingDisabled: blockEditingMode2 === "disabled"
};
if (isPreviewMode2) {
return previewContext;
}
const _isSelected = isBlockSelected2(clientId);
const canRemove2 = canRemoveBlock2(clientId);
const canMove2 = canMoveBlock2(clientId);
const match2 = getActiveBlockVariation(blockName, attributes2);
const checkDeep = true;
const isAncestorOfSelectedBlock = hasSelectedInnerBlock2(
clientId,
checkDeep
);
const sectionBlockClientId = _isSectionBlock(clientId) ? clientId : getParentSectionBlock2(clientId);
const multiple = (0, import_blocks24.hasBlockSupport)(blockName, "multiple", true);
const blocksWithSameName = multiple ? [] : getBlocksByName2(blockName);
const isInvalid = blocksWithSameName.length && blocksWithSameName[0] !== clientId;
return {
...previewContext,
mode: getBlockMode2(clientId),
isSelectionEnabled: isSelectionEnabled22(),
isLocked: !!getTemplateLock2(rootClientId),
isSectionBlock: _isSectionBlock(clientId),
isWithinSectionBlock: !!sectionBlockClientId,
isSelectionWithinCurrentSection: isBlockSelected2(sectionBlockClientId) || hasSelectedInnerBlock2(sectionBlockClientId, checkDeep),
blockType: blockType2,
canRemove: canRemove2,
canMove: canMove2,
isSelected: _isSelected,
isEditingContentOnlySection: getEditedContentOnlySection2() === clientId,
blockEditingMode: blockEditingMode2,
mayDisplayControls: _isSelected || isFirstMultiSelectedBlock2(clientId) && getMultiSelectedBlockClientIds2().every(
(id) => getBlockName2(id) === blockName
),
mayDisplayParentControls: _hasBlockSupport(
getBlockName2(clientId),
"__experimentalExposeControlsToChildren",
false
) && hasSelectedInnerBlock2(clientId),
blockApiVersion: blockType2?.apiVersion || 1,
blockTitle: match2?.title || blockType2?.title,
isSubtreeDisabled: blockEditingMode2 === "disabled" && isBlockSubtreeDisabled2(clientId),
hasOverlay: __unstableHasActiveBlockOverlayActive2(clientId) && !isDragging22(),
initialPosition: _isSelected ? getSelectedBlocksInitialCaretPosition2() : void 0,
isHighlighted: isBlockHighlighted2(clientId),
isMultiSelected: isMultiSelected2,
isPartiallySelected: isMultiSelected2 && !__unstableIsFullySelected2() && !__unstableSelectionHasUnmergeableBlock2(),
isDragging: isBlockBeingDragged2(clientId),
hasChildSelected: isAncestorOfSelectedBlock,
isEditingDisabled: blockEditingMode2 === "disabled",
hasEditableOutline: blockEditingMode2 !== "disabled" && getBlockEditingMode2(rootClientId) === "disabled",
originalBlockClientId: isInvalid ? blocksWithSameName[0] : false,
blockVisibility: blockVisibility22,
deviceType: deviceType2,
viewportSettings: viewportSettings2
};
},
[clientId, rootClientId]
);
const defaultViewRef = (0, import_compose17.useRefEffect)((element) => {
if (element) {
const { ownerDocument: ownerDocument2 } = element;
const { defaultView } = ownerDocument2;
defaultViewRef.current = defaultView;
}
}, []);
const { isBlockCurrentlyHidden } = useBlockVisibility({
blockVisibility: selectedProps?.blockVisibility,
deviceType: selectedProps?.deviceType,
viewportSettings: selectedProps?.viewportSettings,
view: defaultViewRef.current
});
const block = (0, import_element31.useMemo)(
() => ({
...selectedProps?.blockWithoutAttributes,
attributes: selectedProps?.attributes
}),
[selectedProps?.blockWithoutAttributes, selectedProps?.attributes]
);
if (!selectedProps) {
return null;
}
const {
isPreviewMode,
// Fill values that end up as a public API and may not be defined in
// preview mode.
mode: mode2 = "visual",
isSelectionEnabled: isSelectionEnabled3 = false,
isLocked = false,
canRemove = false,
canMove = false,
name,
attributes,
isValid: isValid2,
isSelected = false,
themeSupportsLayout,
isEditingContentOnlySection,
blockEditingMode,
mayDisplayControls,
mayDisplayParentControls,
index: index2,
blockApiVersion,
blockType,
blockTitle,
isSubtreeDisabled,
hasOverlay,
initialPosition: initialPosition2,
isHighlighted,
isMultiSelected,
isPartiallySelected,
isReusable,
isDragging: isDragging3,
hasChildSelected,
isSectionBlock: isSectionBlock2,
isWithinSectionBlock,
isSelectionWithinCurrentSection,
isEditingDisabled,
hasEditableOutline,
className,
defaultClassName,
originalBlockClientId,
bindableAttributes,
blockVisibility: blockVisibility2,
deviceType,
viewportSettings
} = selectedProps;
const privateContext = {
isPreviewMode,
clientId,
className,
index: index2,
mode: mode2,
name,
blockApiVersion,
blockType,
blockTitle,
isSelected,
isSubtreeDisabled,
hasOverlay,
initialPosition: initialPosition2,
blockEditingMode,
isHighlighted,
isMultiSelected,
isPartiallySelected,
isReusable,
isDragging: isDragging3,
hasChildSelected,
isSectionBlock: isSectionBlock2,
isWithinSectionBlock,
isSelectionWithinCurrentSection,
isEditingDisabled,
hasEditableOutline,
isEditingContentOnlySection,
defaultClassName,
mayDisplayControls,
mayDisplayParentControls,
originalBlockClientId,
themeSupportsLayout,
canMove,
isBlockCurrentlyHidden,
bindableAttributes,
blockVisibility: blockVisibility2,
deviceType,
viewportSettings
};
if (isBlockCurrentlyHidden && !isSelected && !isMultiSelected && !hasChildSelected) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime151.jsx)(PrivateBlockContext.Provider, { value: privateContext, children: /* @__PURE__ */ (0, import_jsx_runtime151.jsx)(
BlockListBlock,
{
...props,
...{
mode: mode2,
isSelectionEnabled: isSelectionEnabled3,
isLocked,
canRemove,
canMove,
// Users of the editor.BlockListBlock filter used to be able
// to access the block prop. Ideally these blocks would rely
// on the clientId prop only. This is kept for backward
// compatibility reasons.
block,
name,
attributes,
isValid: isValid2,
isSelected
}
}
) });
}
var block_default2 = (0, import_element31.memo)(BlockListBlockProvider);
// packages/block-editor/build-module/components/block-list-appender/index.mjs
var import_data67 = __toESM(require_data(), 1);
var import_blocks41 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/components/default-block-appender/index.mjs
var import_i18n65 = __toESM(require_i18n(), 1);
var import_html_entities = __toESM(require_html_entities(), 1);
var import_data66 = __toESM(require_data(), 1);
var import_keycodes9 = __toESM(require_keycodes(), 1);
// packages/block-editor/build-module/components/inserter/index.mjs
var import_a11y10 = __toESM(require_a11y(), 1);
var import_i18n64 = __toESM(require_i18n(), 1);
var import_components61 = __toESM(require_components(), 1);
var import_data65 = __toESM(require_data(), 1);
var import_blocks40 = __toESM(require_blocks(), 1);
var import_element128 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/inserter/menu.mjs
var import_element126 = __toESM(require_element(), 1);
var import_components59 = __toESM(require_components(), 1);
// packages/ui/build-module/badge/badge.mjs
var import_element46 = __toESM(require_element(), 1);
// node_modules/@base-ui/utils/useControlled.mjs
var React3 = __toESM(require_react(), 1);
// node_modules/@base-ui/utils/error.mjs
var set;
if (true) {
set = /* @__PURE__ */ new Set();
}
function error(...messages2) {
if (true) {
const messageKey = messages2.join(" ");
if (!set.has(messageKey)) {
set.add(messageKey);
console.error(`Base UI: ${messageKey}`);
}
}
}
// node_modules/@base-ui/utils/useControlled.mjs
function useControlled({
controlled,
default: defaultProp,
name,
state = "value"
}) {
const {
current: isControlled
} = React3.useRef(controlled !== void 0);
const [valueState, setValue] = React3.useState(defaultProp);
const value = isControlled ? controlled : valueState;
if (true) {
React3.useEffect(() => {
if (isControlled !== (controlled !== void 0)) {
error([`A component is changing the ${isControlled ? "" : "un"}controlled ${state} state of ${name} to be ${isControlled ? "un" : ""}controlled.`, "Elements should not switch from uncontrolled to controlled (or vice versa).", `Decide between using a controlled or uncontrolled ${name} element for the lifetime of the component.`, "The nature of the state is determined during the first render. It's considered controlled if the value is not `undefined`.", "More info: https://fb.me/react-controlled-components"].join("\n"));
}
}, [state, name, controlled]);
const {
current: defaultValue
} = React3.useRef(defaultProp);
React3.useEffect(() => {
if (!isControlled && serializeToDevModeString(defaultValue) !== serializeToDevModeString(defaultProp)) {
error([`A component is changing the default ${state} state of an uncontrolled ${name} after being initialized. To suppress this warning opt to use a controlled ${name}.`].join("\n"));
}
}, [defaultProp]);
}
const setValueIfUncontrolled = React3.useCallback((newValue) => {
if (!isControlled) {
setValue(newValue);
}
}, []);
return [value, setValueIfUncontrolled];
}
function serializeToDevModeString(input) {
let nextId2 = 0;
const seen = /* @__PURE__ */ new WeakMap();
try {
const result = JSON.stringify(input, function replacer(key, value) {
if (key === "_owner" && this != null && typeof this === "object" && "$$typeof" in this) {
return void 0;
}
if (typeof value === "bigint") {
return `__bigint__:${value}`;
}
if (value !== null && typeof value === "object") {
const id = seen.get(value);
if (id !== void 0) {
return `__object__:${id}`;
}
seen.set(value, nextId2);
nextId2 += 1;
}
return value;
});
return result ?? `__top__:${typeof input}`;
} catch {
return "__unserializable__";
}
}
// node_modules/@base-ui/utils/safeReact.mjs
var React4 = __toESM(require_react(), 1);
var SafeReact = {
...React4
};
// node_modules/@base-ui/utils/useRefWithInit.mjs
var React5 = __toESM(require_react(), 1);
var UNINITIALIZED = {};
function useRefWithInit(init, initArg) {
const ref = React5.useRef(UNINITIALIZED);
if (ref.current === UNINITIALIZED) {
ref.current = init(initArg);
}
return ref;
}
// node_modules/@base-ui/utils/useStableCallback.mjs
var useInsertionEffect = SafeReact.useInsertionEffect;
var useSafeInsertionEffect = (
// React 17 doesn't have useInsertionEffect.
useInsertionEffect && // Preact replaces useInsertionEffect with useLayoutEffect and fires too late.
useInsertionEffect !== SafeReact.useLayoutEffect ? useInsertionEffect : (fn) => fn()
);
function useStableCallback(callback) {
const stable = useRefWithInit(createStableCallback).current;
stable.next = callback;
useSafeInsertionEffect(stable.effect);
return stable.trampoline;
}
function createStableCallback() {
const stable = {
next: void 0,
callback: assertNotCalled,
trampoline: (...args) => stable.callback?.(...args),
effect: () => {
stable.callback = stable.next;
}
};
return stable;
}
function assertNotCalled() {
if (true) {
throw (
/* minify-error-disabled */
new Error("Base UI: Cannot call an event handler while rendering.")
);
}
}
// node_modules/@base-ui/utils/useIsoLayoutEffect.mjs
var React6 = __toESM(require_react(), 1);
var noop4 = () => {
};
var useIsoLayoutEffect = typeof document !== "undefined" ? React6.useLayoutEffect : noop4;
// node_modules/@base-ui/utils/warn.mjs
var set2;
if (true) {
set2 = /* @__PURE__ */ new Set();
}
function warn(...messages2) {
if (true) {
const messageKey = messages2.join(" ");
if (!set2.has(messageKey)) {
set2.add(messageKey);
console.warn(`Base UI: ${messageKey}`);
}
}
}
// node_modules/@base-ui/react/internals/composite/list/CompositeList.mjs
var React8 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/internals/composite/list/CompositeListContext.mjs
var React7 = __toESM(require_react(), 1);
var CompositeListContext = /* @__PURE__ */ React7.createContext({
register: () => {
},
unregister: () => {
},
subscribeMapChange: () => {
return () => {
};
},
elementsRef: {
current: []
},
nextIndexRef: {
current: 0
}
});
if (true) CompositeListContext.displayName = "CompositeListContext";
function useCompositeListContext() {
return React7.useContext(CompositeListContext);
}
// node_modules/@base-ui/react/internals/composite/list/CompositeList.mjs
var import_jsx_runtime152 = __toESM(require_jsx_runtime(), 1);
function CompositeList(props) {
const {
children,
elementsRef,
labelsRef,
onMapChange: onMapChangeProp
} = props;
const onMapChange = useStableCallback(onMapChangeProp);
const nextIndexRef = React8.useRef(0);
const listeners = useRefWithInit(createListeners).current;
const map = useRefWithInit(createMap).current;
const [mapTick, setMapTick] = React8.useState(0);
const lastTickRef = React8.useRef(mapTick);
const register2 = useStableCallback((node, metadata) => {
map.set(node, metadata ?? null);
lastTickRef.current += 1;
setMapTick(lastTickRef.current);
});
const unregister = useStableCallback((node) => {
map.delete(node);
lastTickRef.current += 1;
setMapTick(lastTickRef.current);
});
const sortedMap = React8.useMemo(() => {
disableEslintWarning(mapTick);
const newMap = /* @__PURE__ */ new Map();
const sortedNodes = Array.from(map.keys()).filter((node) => node.isConnected).sort(sortByDocumentPosition);
sortedNodes.forEach((node, index2) => {
const metadata = map.get(node) ?? {};
newMap.set(node, {
...metadata,
index: index2
});
});
return newMap;
}, [map, mapTick]);
useIsoLayoutEffect(() => {
if (typeof MutationObserver !== "function" || sortedMap.size === 0) {
return void 0;
}
const mutationObserver = new MutationObserver((entries) => {
const diff = /* @__PURE__ */ new Set();
const updateDiff = (node) => diff.has(node) ? diff.delete(node) : diff.add(node);
entries.forEach((entry) => {
entry.removedNodes.forEach(updateDiff);
entry.addedNodes.forEach(updateDiff);
});
if (diff.size === 0) {
lastTickRef.current += 1;
setMapTick(lastTickRef.current);
}
});
sortedMap.forEach((_, node) => {
if (node.parentElement) {
mutationObserver.observe(node.parentElement, {
childList: true
});
}
});
return () => {
mutationObserver.disconnect();
};
}, [sortedMap]);
useIsoLayoutEffect(() => {
const shouldUpdateLengths = lastTickRef.current === mapTick;
if (shouldUpdateLengths) {
if (elementsRef.current.length !== sortedMap.size) {
elementsRef.current.length = sortedMap.size;
}
if (labelsRef && labelsRef.current.length !== sortedMap.size) {
labelsRef.current.length = sortedMap.size;
}
nextIndexRef.current = sortedMap.size;
}
onMapChange(sortedMap);
}, [onMapChange, sortedMap, elementsRef, labelsRef, mapTick]);
useIsoLayoutEffect(() => {
return () => {
elementsRef.current = [];
};
}, [elementsRef]);
useIsoLayoutEffect(() => {
return () => {
if (labelsRef) {
labelsRef.current = [];
}
};
}, [labelsRef]);
const subscribeMapChange = useStableCallback((fn) => {
listeners.add(fn);
return () => {
listeners.delete(fn);
};
});
useIsoLayoutEffect(() => {
listeners.forEach((l2) => l2(sortedMap));
}, [listeners, sortedMap]);
const contextValue = React8.useMemo(() => ({
register: register2,
unregister,
subscribeMapChange,
elementsRef,
labelsRef,
nextIndexRef
}), [register2, unregister, subscribeMapChange, elementsRef, labelsRef, nextIndexRef]);
return /* @__PURE__ */ (0, import_jsx_runtime152.jsx)(CompositeListContext.Provider, {
value: contextValue,
children
});
}
function createMap() {
return /* @__PURE__ */ new Map();
}
function createListeners() {
return /* @__PURE__ */ new Set();
}
function sortByDocumentPosition(a2, b2) {
const position = a2.compareDocumentPosition(b2);
if (position & Node.DOCUMENT_POSITION_FOLLOWING || position & Node.DOCUMENT_POSITION_CONTAINED_BY) {
return -1;
}
if (position & Node.DOCUMENT_POSITION_PRECEDING || position & Node.DOCUMENT_POSITION_CONTAINS) {
return 1;
}
return 0;
}
function disableEslintWarning(_) {
}
// node_modules/@base-ui/react/internals/direction-context/DirectionContext.mjs
var React9 = __toESM(require_react(), 1);
var DirectionContext = /* @__PURE__ */ React9.createContext(void 0);
if (true) DirectionContext.displayName = "DirectionContext";
function useDirection() {
const context = React9.useContext(DirectionContext);
return context?.direction ?? "ltr";
}
// node_modules/@base-ui/react/internals/useRenderElement.mjs
var React12 = __toESM(require_react(), 1);
// node_modules/@base-ui/utils/useMergedRefs.mjs
function useMergedRefs(a2, b2, c6, d2) {
const forkRef = useRefWithInit(createForkRef).current;
if (didChange(forkRef, a2, b2, c6, d2)) {
update3(forkRef, [a2, b2, c6, d2]);
}
return forkRef.callback;
}
function useMergedRefsN(refs) {
const forkRef = useRefWithInit(createForkRef).current;
if (didChangeN(forkRef, refs)) {
update3(forkRef, refs);
}
return forkRef.callback;
}
function createForkRef() {
return {
callback: null,
cleanup: null,
refs: []
};
}
function didChange(forkRef, a2, b2, c6, d2) {
return forkRef.refs[0] !== a2 || forkRef.refs[1] !== b2 || forkRef.refs[2] !== c6 || forkRef.refs[3] !== d2;
}
function didChangeN(forkRef, newRefs) {
return forkRef.refs.length !== newRefs.length || forkRef.refs.some((ref, index2) => ref !== newRefs[index2]);
}
function update3(forkRef, refs) {
forkRef.refs = refs;
if (refs.every((ref) => ref == null)) {
forkRef.callback = null;
return;
}
forkRef.callback = (instance) => {
if (forkRef.cleanup) {
forkRef.cleanup();
forkRef.cleanup = null;
}
if (instance != null) {
const cleanupCallbacks = Array(refs.length).fill(null);
for (let i2 = 0; i2 < refs.length; i2 += 1) {
const ref = refs[i2];
if (ref == null) {
continue;
}
switch (typeof ref) {
case "function": {
const refCleanup = ref(instance);
if (typeof refCleanup === "function") {
cleanupCallbacks[i2] = refCleanup;
}
break;
}
case "object": {
ref.current = instance;
break;
}
default:
}
}
forkRef.cleanup = () => {
for (let i2 = 0; i2 < refs.length; i2 += 1) {
const ref = refs[i2];
if (ref == null) {
continue;
}
switch (typeof ref) {
case "function": {
const cleanupCallback = cleanupCallbacks[i2];
if (typeof cleanupCallback === "function") {
cleanupCallback();
} else {
ref(null);
}
break;
}
case "object": {
ref.current = null;
break;
}
default:
}
}
};
}
};
}
// node_modules/@base-ui/utils/getReactElementRef.mjs
var React11 = __toESM(require_react(), 1);
// node_modules/@base-ui/utils/reactVersion.mjs
var React10 = __toESM(require_react(), 1);
var majorVersion = parseInt(React10.version, 10);
function isReactVersionAtLeast(reactVersionToCheck) {
return majorVersion >= reactVersionToCheck;
}
// node_modules/@base-ui/utils/getReactElementRef.mjs
function getReactElementRef(element) {
if (!/* @__PURE__ */ React11.isValidElement(element)) {
return null;
}
const reactElement = element;
const propsWithRef = reactElement.props;
return (isReactVersionAtLeast(19) ? propsWithRef?.ref : reactElement.ref) ?? null;
}
// node_modules/@base-ui/utils/mergeObjects.mjs
function mergeObjects(a2, b2) {
if (a2 && !b2) {
return a2;
}
if (!a2 && b2) {
return b2;
}
if (a2 || b2) {
return {
...a2,
...b2
};
}
return void 0;
}
// node_modules/@base-ui/utils/empty.mjs
function NOOP() {
}
var EMPTY_ARRAY5 = Object.freeze([]);
var EMPTY_OBJECT = Object.freeze({});
// node_modules/@base-ui/react/internals/getStateAttributesProps.mjs
function getStateAttributesProps(state, customMapping) {
const props = {};
for (const key in state) {
const value = state[key];
if (customMapping?.hasOwnProperty(key)) {
const customProps = customMapping[key](value);
if (customProps != null) {
Object.assign(props, customProps);
}
continue;
}
if (value === true) {
props[`data-${key.toLowerCase()}`] = "";
} else if (value) {
props[`data-${key.toLowerCase()}`] = value.toString();
}
}
return props;
}
// node_modules/@base-ui/react/utils/resolveClassName.mjs
function resolveClassName(className, state) {
return typeof className === "function" ? className(state) : className;
}
// node_modules/@base-ui/react/utils/resolveStyle.mjs
function resolveStyle(style, state) {
return typeof style === "function" ? style(state) : style;
}
// node_modules/@base-ui/react/merge-props/mergeProps.mjs
var EMPTY_PROPS = {};
function mergeProps(a2, b2, c6, d2, e2) {
if (!c6 && !d2 && !e2 && !a2) {
return createInitialMergedProps(b2);
}
let merged = createInitialMergedProps(a2);
if (b2) {
merged = mergeInto(merged, b2);
}
if (c6) {
merged = mergeInto(merged, c6);
}
if (d2) {
merged = mergeInto(merged, d2);
}
if (e2) {
merged = mergeInto(merged, e2);
}
return merged;
}
function mergePropsN(props) {
if (props.length === 0) {
return EMPTY_PROPS;
}
if (props.length === 1) {
return createInitialMergedProps(props[0]);
}
let merged = createInitialMergedProps(props[0]);
for (let i2 = 1; i2 < props.length; i2 += 1) {
merged = mergeInto(merged, props[i2]);
}
return merged;
}
function createInitialMergedProps(inputProps) {
if (isPropsGetter(inputProps)) {
return {
...resolvePropsGetter(inputProps, EMPTY_PROPS)
};
}
return copyInitialProps(inputProps);
}
function mergeInto(merged, inputProps) {
if (isPropsGetter(inputProps)) {
return resolvePropsGetter(inputProps, merged);
}
return mutablyMergeInto(merged, inputProps);
}
function copyInitialProps(inputProps) {
const copiedProps = {
...inputProps
};
for (const propName in copiedProps) {
const propValue = copiedProps[propName];
if (isEventHandler(propName, propValue)) {
copiedProps[propName] = wrapEventHandler(propValue);
}
}
return copiedProps;
}
function mutablyMergeInto(mergedProps, externalProps) {
if (!externalProps) {
return mergedProps;
}
for (const propName in externalProps) {
const externalPropValue = externalProps[propName];
switch (propName) {
case "style": {
mergedProps[propName] = mergeObjects(mergedProps.style, externalPropValue);
break;
}
case "className": {
mergedProps[propName] = mergeClassNames(mergedProps.className, externalPropValue);
break;
}
default: {
if (isEventHandler(propName, externalPropValue)) {
mergedProps[propName] = mergeEventHandlers(mergedProps[propName], externalPropValue);
} else {
mergedProps[propName] = externalPropValue;
}
}
}
}
return mergedProps;
}
function isEventHandler(key, value) {
const code0 = key.charCodeAt(0);
const code1 = key.charCodeAt(1);
const code2 = key.charCodeAt(2);
return code0 === 111 && code1 === 110 && code2 >= 65 && code2 <= 90 && (typeof value === "function" || typeof value === "undefined");
}
function isPropsGetter(inputProps) {
return typeof inputProps === "function";
}
function resolvePropsGetter(inputProps, previousProps) {
if (isPropsGetter(inputProps)) {
return inputProps(previousProps);
}
return inputProps ?? EMPTY_PROPS;
}
function mergeEventHandlers(ourHandler, theirHandler) {
if (!theirHandler) {
return ourHandler;
}
if (!ourHandler) {
return wrapEventHandler(theirHandler);
}
return (...args) => {
const event = args[0];
if (isSyntheticEvent(event)) {
const baseUIEvent = event;
makeEventPreventable(baseUIEvent);
const result2 = theirHandler(...args);
if (!baseUIEvent.baseUIHandlerPrevented) {
ourHandler?.(...args);
}
return result2;
}
const result = theirHandler(...args);
ourHandler?.(...args);
return result;
};
}
function wrapEventHandler(handler) {
if (!handler) {
return handler;
}
return (...args) => {
const event = args[0];
if (isSyntheticEvent(event)) {
makeEventPreventable(event);
}
return handler(...args);
};
}
function makeEventPreventable(event) {
event.preventBaseUIHandler = () => {
event.baseUIHandlerPrevented = true;
};
return event;
}
function mergeClassNames(ourClassName, theirClassName) {
if (theirClassName) {
if (ourClassName) {
return theirClassName + " " + ourClassName;
}
return theirClassName;
}
return ourClassName;
}
function isSyntheticEvent(event) {
return event != null && typeof event === "object" && "nativeEvent" in event;
}
// node_modules/@base-ui/react/internals/useRenderElement.mjs
var import_react4 = __toESM(require_react(), 1);
function useRenderElement(element, componentProps, params = {}) {
const renderProp = componentProps.render;
const outProps = useRenderElementProps(componentProps, params);
if (params.enabled === false) {
return null;
}
const state = params.state ?? EMPTY_OBJECT;
return evaluateRenderProp(element, renderProp, outProps, state);
}
function useRenderElementProps(componentProps, params = {}) {
const {
className: classNameProp,
style: styleProp,
render: renderProp
} = componentProps;
const {
state = EMPTY_OBJECT,
ref,
props,
stateAttributesMapping: stateAttributesMapping10,
enabled = true
} = params;
const className = enabled ? resolveClassName(classNameProp, state) : void 0;
const style = enabled ? resolveStyle(styleProp, state) : void 0;
const stateProps = enabled ? getStateAttributesProps(state, stateAttributesMapping10) : EMPTY_OBJECT;
const resolvedProps = enabled && props ? resolveRenderFunctionProps(props) : void 0;
const outProps = enabled ? mergeObjects(stateProps, resolvedProps) ?? {} : EMPTY_OBJECT;
if (typeof document !== "undefined") {
if (!enabled) {
useMergedRefs(null, null);
} else if (Array.isArray(ref)) {
outProps.ref = useMergedRefsN([outProps.ref, getReactElementRef(renderProp), ...ref]);
} else {
outProps.ref = useMergedRefs(outProps.ref, getReactElementRef(renderProp), ref);
}
}
if (!enabled) {
return EMPTY_OBJECT;
}
if (className !== void 0) {
outProps.className = mergeClassNames(outProps.className, className);
}
if (style !== void 0) {
outProps.style = mergeObjects(outProps.style, style);
}
return outProps;
}
function resolveRenderFunctionProps(props) {
if (Array.isArray(props)) {
return mergePropsN(props);
}
return mergeProps(void 0, props);
}
var REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy");
var COMPONENT_IDENTIFIER_PATTERN = /^[A-Z][A-Za-z0-9$]*$/;
var LOWERCASE_CHARACTER_PATTERN = /[a-z]/;
function evaluateRenderProp(element, render4, props, state) {
if (render4) {
if (typeof render4 === "function") {
if (true) {
warnIfRenderPropLooksLikeComponent(render4);
}
return render4(props, state);
}
const mergedProps = mergeProps(props, render4.props);
mergedProps.ref = props.ref;
let newElement = render4;
if (newElement?.$$typeof === REACT_LAZY_TYPE) {
const children = React12.Children.toArray(render4);
newElement = children[0];
}
if (true) {
if (!/* @__PURE__ */ React12.isValidElement(newElement)) {
throw new Error(["Base UI: The `render` prop was provided an invalid React element as `React.isValidElement(render)` is `false`.", "A valid React element must be provided to the `render` prop because it is cloned with props to replace the default element.", "https://base-ui.com/r/invalid-render-prop"].join("\n"));
}
}
return /* @__PURE__ */ React12.cloneElement(newElement, mergedProps);
}
if (element) {
if (typeof element === "string") {
return renderTag(element, props);
}
}
throw new Error(true ? "Base UI: Render element or function are not defined." : formatErrorMessage_default(8));
}
function warnIfRenderPropLooksLikeComponent(renderFn) {
const functionName = renderFn.name;
if (functionName.length === 0) {
return;
}
if (!COMPONENT_IDENTIFIER_PATTERN.test(functionName)) {
return;
}
if (!LOWERCASE_CHARACTER_PATTERN.test(functionName)) {
return;
}
warn(`The \`render\` prop received a function named \`${functionName}\` that starts with an uppercase letter.`, "This usually means a React component was passed directly as `render={Component}`.", "Base UI calls `render` as a plain function, which can break the Rules of Hooks during reconciliation.", "If this is an intentional render callback, rename it to start with a lowercase letter.", "Use `render={<Component />}` or `render={(props) => <Component {...props} />}` instead.", "https://base-ui.com/r/invalid-render-prop");
}
function renderTag(Tag, props) {
if (Tag === "button") {
return /* @__PURE__ */ (0, import_react4.createElement)("button", {
type: "button",
...props,
key: props.key
});
}
if (Tag === "img") {
return /* @__PURE__ */ (0, import_react4.createElement)("img", {
alt: "",
...props,
key: props.key
});
}
return /* @__PURE__ */ React12.createElement(Tag, props);
}
// node_modules/@base-ui/utils/useId.mjs
var React13 = __toESM(require_react(), 1);
var globalId = 0;
function useGlobalId(idOverride, prefix2 = "mui") {
const [defaultId, setDefaultId] = React13.useState(idOverride);
const id = idOverride || defaultId;
React13.useEffect(() => {
if (defaultId == null) {
globalId += 1;
setDefaultId(`${prefix2}-${globalId}`);
}
}, [defaultId, prefix2]);
return id;
}
var maybeReactUseId = SafeReact.useId;
function useId(idOverride, prefix2) {
if (maybeReactUseId !== void 0) {
const reactId = maybeReactUseId();
return idOverride ?? (prefix2 ? `${prefix2}-${reactId}` : reactId);
}
return useGlobalId(idOverride, prefix2);
}
// node_modules/@base-ui/react/internals/useBaseUiId.mjs
function useBaseUiId(idOverride) {
return useId(idOverride, "base-ui");
}
// node_modules/@base-ui/react/collapsible/root/useCollapsibleRoot.mjs
var React16 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/internals/reason-parts.mjs
var reason_parts_exports = {};
__export(reason_parts_exports, {
cancelOpen: () => cancelOpen,
chipRemovePress: () => chipRemovePress,
clearPress: () => clearPress,
closePress: () => closePress,
closeWatcher: () => closeWatcher,
decrementPress: () => decrementPress,
disabled: () => disabled,
drag: () => drag,
escapeKey: () => escapeKey,
focusOut: () => focusOut,
imperativeAction: () => imperativeAction,
incrementPress: () => incrementPress,
initial: () => initial,
inputBlur: () => inputBlur,
inputChange: () => inputChange,
inputClear: () => inputClear,
inputPaste: () => inputPaste,
inputPress: () => inputPress,
itemPress: () => itemPress,
keyboard: () => keyboard,
linkPress: () => linkPress,
listNavigation: () => listNavigation,
missing: () => missing,
none: () => none,
outsidePress: () => outsidePress,
pointer: () => pointer,
scrub: () => scrub,
siblingOpen: () => siblingOpen,
swipe: () => swipe,
trackPress: () => trackPress,
triggerFocus: () => triggerFocus,
triggerHover: () => triggerHover,
triggerPress: () => triggerPress,
wheel: () => wheel,
windowResize: () => windowResize
});
var none = "none";
var triggerPress = "trigger-press";
var triggerHover = "trigger-hover";
var triggerFocus = "trigger-focus";
var outsidePress = "outside-press";
var itemPress = "item-press";
var closePress = "close-press";
var linkPress = "link-press";
var clearPress = "clear-press";
var chipRemovePress = "chip-remove-press";
var trackPress = "track-press";
var incrementPress = "increment-press";
var decrementPress = "decrement-press";
var inputChange = "input-change";
var inputClear = "input-clear";
var inputBlur = "input-blur";
var inputPaste = "input-paste";
var inputPress = "input-press";
var focusOut = "focus-out";
var escapeKey = "escape-key";
var closeWatcher = "close-watcher";
var listNavigation = "list-navigation";
var keyboard = "keyboard";
var pointer = "pointer";
var drag = "drag";
var wheel = "wheel";
var scrub = "scrub";
var cancelOpen = "cancel-open";
var siblingOpen = "sibling-open";
var disabled = "disabled";
var missing = "missing";
var initial = "initial";
var imperativeAction = "imperative-action";
var swipe = "swipe";
var windowResize = "window-resize";
// node_modules/@base-ui/react/internals/createBaseUIEventDetails.mjs
function createChangeEventDetails(reason, event, trigger, customProperties) {
let canceled = false;
let allowPropagation = false;
const custom = customProperties ?? EMPTY_OBJECT;
const details = {
reason,
event: event ?? new Event("base-ui"),
cancel() {
canceled = true;
},
allowPropagation() {
allowPropagation = true;
},
get isCanceled() {
return canceled;
},
get isPropagationAllowed() {
return allowPropagation;
},
trigger,
...custom
};
return details;
}
// node_modules/@base-ui/react/internals/useTransitionStatus.mjs
var React15 = __toESM(require_react(), 1);
// node_modules/@base-ui/utils/useOnMount.mjs
var React14 = __toESM(require_react(), 1);
var EMPTY = [];
function useOnMount(fn) {
React14.useEffect(fn, EMPTY);
}
// node_modules/@base-ui/utils/useAnimationFrame.mjs
var EMPTY2 = null;
var LAST_RAF = globalThis.requestAnimationFrame;
var Scheduler = class {
/* This implementation uses an array as a backing data-structure for frame callbacks.
* It allows `O(1)` callback cancelling by inserting a `null` in the array, though it
* never calls the native `cancelAnimationFrame` if there are no frames left. This can
* be much more efficient if there is a call pattern that alterns as
* "request-cancel-request-cancel-…".
* But in the case of "request-request-…-cancel-cancel-…", it leaves the final animation
* frame to run anyway. We turn that frame into a `O(1)` no-op via `callbacksCount`. */
callbacks = [];
callbacksCount = 0;
nextId = 1;
startId = 1;
isScheduled = false;
tick = (timestamp) => {
this.isScheduled = false;
const currentCallbacks = this.callbacks;
const currentCallbacksCount = this.callbacksCount;
this.callbacks = [];
this.callbacksCount = 0;
this.startId = this.nextId;
if (currentCallbacksCount > 0) {
for (let i2 = 0; i2 < currentCallbacks.length; i2 += 1) {
currentCallbacks[i2]?.(timestamp);
}
}
};
request(fn) {
const id = this.nextId;
this.nextId += 1;
this.callbacks.push(fn);
this.callbacksCount += 1;
const didRAFChange = LAST_RAF !== requestAnimationFrame && (LAST_RAF = requestAnimationFrame, true);
if (!this.isScheduled || didRAFChange) {
requestAnimationFrame(this.tick);
this.isScheduled = true;
}
return id;
}
cancel(id) {
const index2 = id - this.startId;
if (index2 < 0 || index2 >= this.callbacks.length) {
return;
}
this.callbacks[index2] = null;
this.callbacksCount -= 1;
}
};
var scheduler = new Scheduler();
var AnimationFrame = class _AnimationFrame {
static create() {
return new _AnimationFrame();
}
static request(fn) {
return scheduler.request(fn);
}
static cancel(id) {
return scheduler.cancel(id);
}
currentId = EMPTY2;
/**
* Executes `fn` after `delay`, clearing any previously scheduled call.
*/
request(fn) {
this.cancel();
this.currentId = scheduler.request(() => {
this.currentId = EMPTY2;
fn();
});
}
cancel = () => {
if (this.currentId !== EMPTY2) {
scheduler.cancel(this.currentId);
this.currentId = EMPTY2;
}
};
disposeEffect = () => {
return this.cancel;
};
};
function useAnimationFrame() {
const timeout = useRefWithInit(AnimationFrame.create).current;
useOnMount(timeout.disposeEffect);
return timeout;
}
// node_modules/@base-ui/react/internals/useTransitionStatus.mjs
function useTransitionStatus(open, enableIdleState = false, deferEndingState = false) {
const [transitionStatus, setTransitionStatus] = React15.useState(open && enableIdleState ? "idle" : void 0);
const [mounted, setMounted] = React15.useState(open);
if (open && !mounted) {
setMounted(true);
setTransitionStatus("starting");
}
if (!open && mounted && transitionStatus !== "ending" && !deferEndingState) {
setTransitionStatus("ending");
}
if (!open && !mounted && transitionStatus === "ending") {
setTransitionStatus(void 0);
}
useIsoLayoutEffect(() => {
if (!open && mounted && transitionStatus !== "ending" && deferEndingState) {
const frame = AnimationFrame.request(() => {
setTransitionStatus("ending");
});
return () => {
AnimationFrame.cancel(frame);
};
}
return void 0;
}, [open, mounted, transitionStatus, deferEndingState]);
useIsoLayoutEffect(() => {
if (!open || enableIdleState) {
return void 0;
}
const frame = AnimationFrame.request(() => {
setTransitionStatus(void 0);
});
return () => {
AnimationFrame.cancel(frame);
};
}, [enableIdleState, open]);
useIsoLayoutEffect(() => {
if (!open || !enableIdleState) {
return void 0;
}
if (open && mounted && transitionStatus !== "idle") {
setTransitionStatus("starting");
}
const frame = AnimationFrame.request(() => {
setTransitionStatus("idle");
});
return () => {
AnimationFrame.cancel(frame);
};
}, [enableIdleState, open, mounted, transitionStatus]);
return {
mounted,
setMounted,
transitionStatus
};
}
// node_modules/@base-ui/react/collapsible/root/useCollapsibleRoot.mjs
function useCollapsibleRoot(parameters) {
const {
open: openParam,
defaultOpen,
onOpenChange,
disabled: disabled2
} = parameters;
const [open, setOpen] = useControlled({
controlled: openParam,
default: defaultOpen,
name: "Collapsible",
state: "open"
});
const {
mounted,
setMounted,
transitionStatus
} = useTransitionStatus(open, true, true);
const defaultPanelId = useBaseUiId();
const [panelIdState, setPanelIdState] = React16.useState();
const panelId = panelIdState ?? defaultPanelId;
const handleTrigger = useStableCallback((event) => {
const nextOpen = !open;
const eventDetails = createChangeEventDetails(reason_parts_exports.triggerPress, event.nativeEvent);
onOpenChange(nextOpen, eventDetails);
if (eventDetails.isCanceled) {
return;
}
setOpen(nextOpen);
});
return React16.useMemo(() => ({
disabled: disabled2,
handleTrigger,
mounted,
open,
panelId,
setMounted,
setOpen,
setPanelIdState,
transitionStatus
}), [disabled2, handleTrigger, mounted, open, panelId, setMounted, setOpen, setPanelIdState, transitionStatus]);
}
// node_modules/@base-ui/react/collapsible/root/CollapsibleRootContext.mjs
var React17 = __toESM(require_react(), 1);
var CollapsibleRootContext = /* @__PURE__ */ React17.createContext(void 0);
if (true) CollapsibleRootContext.displayName = "CollapsibleRootContext";
function useCollapsibleRootContext() {
const context = React17.useContext(CollapsibleRootContext);
if (context === void 0) {
throw new Error(true ? "Base UI: CollapsibleRootContext is missing. Collapsible parts must be placed within <Collapsible.Root>." : formatErrorMessage_default(15));
}
return context;
}
// node_modules/@base-ui/react/internals/composite/list/useCompositeListItem.mjs
var React18 = __toESM(require_react(), 1);
var IndexGuessBehavior = /* @__PURE__ */ (function(IndexGuessBehavior2) {
IndexGuessBehavior2[IndexGuessBehavior2["None"] = 0] = "None";
IndexGuessBehavior2[IndexGuessBehavior2["GuessFromOrder"] = 1] = "GuessFromOrder";
return IndexGuessBehavior2;
})({});
function useCompositeListItem(params = {}) {
const {
label,
metadata,
textRef,
indexGuessBehavior,
index: externalIndex
} = params;
const {
register: register2,
unregister,
subscribeMapChange,
elementsRef,
labelsRef,
nextIndexRef
} = useCompositeListContext();
const indexRef = React18.useRef(-1);
const [index2, setIndex] = React18.useState(externalIndex ?? (indexGuessBehavior === IndexGuessBehavior.GuessFromOrder ? () => {
if (indexRef.current === -1) {
const newIndex = nextIndexRef.current;
nextIndexRef.current += 1;
indexRef.current = newIndex;
}
return indexRef.current;
} : -1));
const componentRef = React18.useRef(null);
const ref = React18.useCallback((node) => {
componentRef.current = node;
if (index2 !== -1 && node !== null) {
elementsRef.current[index2] = node;
if (labelsRef) {
const isLabelDefined = label !== void 0;
labelsRef.current[index2] = isLabelDefined ? label : textRef?.current?.textContent ?? node.textContent;
}
}
}, [index2, elementsRef, labelsRef, label, textRef]);
useIsoLayoutEffect(() => {
if (externalIndex != null) {
return void 0;
}
const node = componentRef.current;
if (node) {
register2(node, metadata);
return () => {
unregister(node);
};
}
return void 0;
}, [externalIndex, register2, unregister, metadata]);
useIsoLayoutEffect(() => {
if (externalIndex != null) {
return void 0;
}
return subscribeMapChange((map) => {
const i2 = componentRef.current ? map.get(componentRef.current)?.index : null;
if (i2 != null) {
setIndex(i2);
}
});
}, [externalIndex, subscribeMapChange, setIndex]);
return {
ref,
index: index2
};
}
// node_modules/@base-ui/react/internals/stateAttributesMapping.mjs
var TransitionStatusDataAttributes = /* @__PURE__ */ (function(TransitionStatusDataAttributes2) {
TransitionStatusDataAttributes2["startingStyle"] = "data-starting-style";
TransitionStatusDataAttributes2["endingStyle"] = "data-ending-style";
return TransitionStatusDataAttributes2;
})({});
var STARTING_HOOK = {
[TransitionStatusDataAttributes.startingStyle]: ""
};
var ENDING_HOOK = {
[TransitionStatusDataAttributes.endingStyle]: ""
};
var transitionStatusMapping = {
transitionStatus(value) {
if (value === "starting") {
return STARTING_HOOK;
}
if (value === "ending") {
return ENDING_HOOK;
}
return null;
}
};
// node_modules/@base-ui/react/collapsible/panel/CollapsiblePanelDataAttributes.mjs
var CollapsiblePanelDataAttributes = (function(CollapsiblePanelDataAttributes2) {
CollapsiblePanelDataAttributes2["open"] = "data-open";
CollapsiblePanelDataAttributes2["closed"] = "data-closed";
CollapsiblePanelDataAttributes2[CollapsiblePanelDataAttributes2["startingStyle"] = TransitionStatusDataAttributes.startingStyle] = "startingStyle";
CollapsiblePanelDataAttributes2[CollapsiblePanelDataAttributes2["endingStyle"] = TransitionStatusDataAttributes.endingStyle] = "endingStyle";
return CollapsiblePanelDataAttributes2;
})({});
// node_modules/@base-ui/react/collapsible/trigger/CollapsibleTriggerDataAttributes.mjs
var CollapsibleTriggerDataAttributes = /* @__PURE__ */ (function(CollapsibleTriggerDataAttributes2) {
CollapsibleTriggerDataAttributes2["panelOpen"] = "data-panel-open";
return CollapsibleTriggerDataAttributes2;
})({});
// node_modules/@base-ui/react/utils/collapsibleOpenStateMapping.mjs
var PANEL_OPEN_HOOK = {
[CollapsiblePanelDataAttributes.open]: ""
};
var PANEL_CLOSED_HOOK = {
[CollapsiblePanelDataAttributes.closed]: ""
};
var triggerOpenStateMapping = {
open(value) {
if (value) {
return {
[CollapsibleTriggerDataAttributes.panelOpen]: ""
};
}
return null;
}
};
var collapsibleOpenStateMapping = {
open(value) {
if (value) {
return PANEL_OPEN_HOOK;
}
return PANEL_CLOSED_HOOK;
}
};
// node_modules/@base-ui/react/internals/use-button/useButton.mjs
var React21 = __toESM(require_react(), 1);
// node_modules/@floating-ui/utils/dist/floating-ui.utils.dom.mjs
function hasWindow() {
return typeof window !== "undefined";
}
function getNodeName(node) {
if (isNode(node)) {
return (node.nodeName || "").toLowerCase();
}
return "#document";
}
function getWindow(node) {
var _node$ownerDocument;
return (node == null || (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;
}
function getDocumentElement(node) {
var _ref;
return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement;
}
function isNode(value) {
if (!hasWindow()) {
return false;
}
return value instanceof Node || value instanceof getWindow(value).Node;
}
function isElement(value) {
if (!hasWindow()) {
return false;
}
return value instanceof Element || value instanceof getWindow(value).Element;
}
function isHTMLElement(value) {
if (!hasWindow()) {
return false;
}
return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement;
}
function isShadowRoot(value) {
if (!hasWindow() || typeof ShadowRoot === "undefined") {
return false;
}
return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot;
}
function isOverflowElement(element) {
const {
overflow,
overflowX,
overflowY,
display
} = getComputedStyle2(element);
return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && display !== "inline" && display !== "contents";
}
function isTableElement(element) {
return /^(table|td|th)$/.test(getNodeName(element));
}
function isTopLayer(element) {
try {
if (element.matches(":popover-open")) {
return true;
}
} catch (_e) {
}
try {
return element.matches(":modal");
} catch (_e) {
return false;
}
}
var willChangeRe = /transform|translate|scale|rotate|perspective|filter/;
var containRe = /paint|layout|strict|content/;
var isNotNone = (value) => !!value && value !== "none";
var isWebKitValue;
function isContainingBlock(elementOrCss) {
const css = isElement(elementOrCss) ? getComputedStyle2(elementOrCss) : elementOrCss;
return isNotNone(css.transform) || isNotNone(css.translate) || isNotNone(css.scale) || isNotNone(css.rotate) || isNotNone(css.perspective) || !isWebKit() && (isNotNone(css.backdropFilter) || isNotNone(css.filter)) || willChangeRe.test(css.willChange || "") || containRe.test(css.contain || "");
}
function getContainingBlock(element) {
let currentNode = getParentNode(element);
while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) {
if (isContainingBlock(currentNode)) {
return currentNode;
} else if (isTopLayer(currentNode)) {
return null;
}
currentNode = getParentNode(currentNode);
}
return null;
}
function isWebKit() {
if (isWebKitValue == null) {
isWebKitValue = typeof CSS !== "undefined" && CSS.supports && CSS.supports("-webkit-backdrop-filter", "none");
}
return isWebKitValue;
}
function isLastTraversableNode(node) {
return /^(html|body|#document)$/.test(getNodeName(node));
}
function getComputedStyle2(element) {
return getWindow(element).getComputedStyle(element);
}
function getNodeScroll(element) {
if (isElement(element)) {
return {
scrollLeft: element.scrollLeft,
scrollTop: element.scrollTop
};
}
return {
scrollLeft: element.scrollX,
scrollTop: element.scrollY
};
}
function getParentNode(node) {
if (getNodeName(node) === "html") {
return node;
}
const result = (
// Step into the shadow DOM of the parent of a slotted node.
node.assignedSlot || // DOM Element detected.
node.parentNode || // ShadowRoot detected.
isShadowRoot(node) && node.host || // Fallback.
getDocumentElement(node)
);
return isShadowRoot(result) ? result.host : result;
}
function getNearestOverflowAncestor(node) {
const parentNode = getParentNode(node);
if (isLastTraversableNode(parentNode)) {
return node.ownerDocument ? node.ownerDocument.body : node.body;
}
if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) {
return parentNode;
}
return getNearestOverflowAncestor(parentNode);
}
function getOverflowAncestors(node, list, traverseIframes) {
var _node$ownerDocument2;
if (list === void 0) {
list = [];
}
if (traverseIframes === void 0) {
traverseIframes = true;
}
const scrollableAncestor = getNearestOverflowAncestor(node);
const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body);
const win = getWindow(scrollableAncestor);
if (isBody) {
const frameElement = getFrameElement(win);
return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], frameElement && traverseIframes ? getOverflowAncestors(frameElement) : []);
} else {
return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes));
}
}
function getFrameElement(win) {
return win.parent && Object.getPrototypeOf(win.parent) ? win.frameElement : null;
}
// node_modules/@base-ui/react/internals/composite/root/CompositeRootContext.mjs
var React19 = __toESM(require_react(), 1);
var CompositeRootContext = /* @__PURE__ */ React19.createContext(void 0);
if (true) CompositeRootContext.displayName = "CompositeRootContext";
function useCompositeRootContext(optional = false) {
const context = React19.useContext(CompositeRootContext);
if (context === void 0 && !optional) {
throw new Error(true ? "Base UI: CompositeRootContext is missing. Composite parts must be placed within <Composite.Root>." : formatErrorMessage_default(16));
}
return context;
}
// node_modules/@base-ui/react/utils/useFocusableWhenDisabled.mjs
var React20 = __toESM(require_react(), 1);
function useFocusableWhenDisabled(parameters) {
const {
focusableWhenDisabled,
disabled: disabled2,
composite = false,
tabIndex: tabIndexProp = 0,
isNativeButton
} = parameters;
const isFocusableComposite = composite && focusableWhenDisabled !== false;
const isNonFocusableComposite = composite && focusableWhenDisabled === false;
const props = React20.useMemo(() => {
const additionalProps = {
// allow Tabbing away from focusableWhenDisabled elements
onKeyDown(event) {
if (disabled2 && focusableWhenDisabled && event.key !== "Tab") {
event.preventDefault();
}
}
};
if (!composite) {
additionalProps.tabIndex = tabIndexProp;
if (!isNativeButton && disabled2) {
additionalProps.tabIndex = focusableWhenDisabled ? tabIndexProp : -1;
}
}
if (isNativeButton && (focusableWhenDisabled || isFocusableComposite) || !isNativeButton && disabled2) {
additionalProps["aria-disabled"] = disabled2;
}
if (isNativeButton && (!focusableWhenDisabled || isNonFocusableComposite)) {
additionalProps.disabled = disabled2;
}
return additionalProps;
}, [composite, disabled2, focusableWhenDisabled, isFocusableComposite, isNonFocusableComposite, isNativeButton, tabIndexProp]);
return {
props
};
}
// node_modules/@base-ui/react/internals/use-button/useButton.mjs
function useButton(parameters = {}) {
const {
disabled: disabled2 = false,
focusableWhenDisabled,
tabIndex = 0,
native: isNativeButton = true,
composite: compositeProp
} = parameters;
const elementRef = React21.useRef(null);
const compositeRootContext = useCompositeRootContext(true);
const isCompositeItem = compositeProp ?? compositeRootContext !== void 0;
const {
props: focusableWhenDisabledProps
} = useFocusableWhenDisabled({
focusableWhenDisabled,
disabled: disabled2,
composite: isCompositeItem,
tabIndex,
isNativeButton
});
if (true) {
React21.useEffect(() => {
if (!elementRef.current) {
return;
}
const isButtonTag = isButtonElement(elementRef.current);
if (isNativeButton) {
if (!isButtonTag) {
const ownerStackMessage = SafeReact.captureOwnerStack?.() || "";
const message2 = "A component that acts as a button expected a native <button> because the `nativeButton` prop is true. Rendering a non-<button> removes native button semantics, which can impact forms and accessibility. Use a real <button> in the `render` prop, or set `nativeButton` to `false`.";
error(`${message2}${ownerStackMessage}`);
}
} else if (isButtonTag) {
const ownerStackMessage = SafeReact.captureOwnerStack?.() || "";
const message2 = "A component that acts as a button expected a non-<button> because the `nativeButton` prop is false. Rendering a <button> keeps native behavior while Base UI applies non-native attributes and handlers, which can add unintended extra attributes (such as `role` or `aria-disabled`). Use a non-<button> in the `render` prop, or set `nativeButton` to `true`.";
error(`${message2}${ownerStackMessage}`);
}
}, [isNativeButton]);
}
const updateDisabled = React21.useCallback(() => {
const element = elementRef.current;
if (!isButtonElement(element)) {
return;
}
if (isCompositeItem && disabled2 && focusableWhenDisabledProps.disabled === void 0 && element.disabled) {
element.disabled = false;
}
}, [disabled2, focusableWhenDisabledProps.disabled, isCompositeItem]);
useIsoLayoutEffect(updateDisabled, [updateDisabled]);
const getButtonProps = React21.useCallback((externalProps = {}) => {
const {
onClick: externalOnClick,
onMouseDown: externalOnMouseDown,
onKeyUp: externalOnKeyUp,
onKeyDown: externalOnKeyDown,
onPointerDown: externalOnPointerDown,
...otherExternalProps
} = externalProps;
return mergeProps({
onClick(event) {
if (disabled2) {
event.preventDefault();
return;
}
externalOnClick?.(event);
},
onMouseDown(event) {
if (!disabled2) {
externalOnMouseDown?.(event);
}
},
onKeyDown(event) {
if (disabled2) {
return;
}
makeEventPreventable(event);
externalOnKeyDown?.(event);
if (event.baseUIHandlerPrevented) {
return;
}
const isCurrentTarget = event.target === event.currentTarget;
const currentTarget = event.currentTarget;
const isButton = isButtonElement(currentTarget);
const isLink = !isNativeButton && isValidLinkElement(currentTarget);
const shouldClick = isCurrentTarget && (isNativeButton ? isButton : !isLink);
const isEnterKey = event.key === "Enter";
const isSpaceKey = event.key === " ";
const role = currentTarget.getAttribute("role");
const isTextNavigationRole = role?.startsWith("menuitem") || role === "option" || role === "gridcell";
if (isCurrentTarget && isCompositeItem && isSpaceKey) {
if (event.defaultPrevented && isTextNavigationRole) {
return;
}
event.preventDefault();
if (isLink || isNativeButton && isButton) {
currentTarget.click();
event.preventBaseUIHandler();
} else if (shouldClick) {
externalOnClick?.(event);
event.preventBaseUIHandler();
}
return;
}
if (shouldClick) {
if (!isNativeButton && (isSpaceKey || isEnterKey)) {
event.preventDefault();
}
if (!isNativeButton && isEnterKey) {
externalOnClick?.(event);
}
}
},
onKeyUp(event) {
if (disabled2) {
return;
}
makeEventPreventable(event);
externalOnKeyUp?.(event);
if (event.target === event.currentTarget && isNativeButton && isCompositeItem && isButtonElement(event.currentTarget) && event.key === " ") {
event.preventDefault();
return;
}
if (event.baseUIHandlerPrevented) {
return;
}
if (event.target === event.currentTarget && !isNativeButton && !isCompositeItem && event.key === " ") {
externalOnClick?.(event);
}
},
onPointerDown(event) {
if (disabled2) {
event.preventDefault();
return;
}
externalOnPointerDown?.(event);
}
}, isNativeButton ? {
type: "button"
} : {
role: "button"
}, focusableWhenDisabledProps, otherExternalProps);
}, [disabled2, focusableWhenDisabledProps, isCompositeItem, isNativeButton]);
const buttonRef = useStableCallback((element) => {
elementRef.current = element;
updateDisabled();
});
return {
getButtonProps,
buttonRef
};
}
function isButtonElement(elem) {
return isHTMLElement(elem) && elem.tagName === "BUTTON";
}
function isValidLinkElement(elem) {
return Boolean(elem?.tagName === "A" && elem?.href);
}
// node_modules/@base-ui/react/collapsible/panel/useCollapsiblePanel.mjs
var React23 = __toESM(require_react(), 1);
// node_modules/@base-ui/utils/addEventListener.mjs
function addEventListener(target, type, listener, options) {
target.addEventListener(type, listener, options);
return () => {
target.removeEventListener(type, listener, options);
};
}
// node_modules/@base-ui/utils/useValueAsRef.mjs
function useValueAsRef(value) {
const latest = useRefWithInit(createLatestRef, value).current;
latest.next = value;
useIsoLayoutEffect(latest.effect);
return latest;
}
function createLatestRef(value) {
const latest = {
current: value,
next: value,
effect: () => {
latest.current = latest.next;
}
};
return latest;
}
// node_modules/@base-ui/utils/owner.mjs
function ownerDocument(node) {
return node?.ownerDocument || document;
}
// node_modules/@base-ui/react/internals/useOpenChangeComplete.mjs
var React22 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/internals/useAnimationsFinished.mjs
var ReactDOM = __toESM(require_react_dom(), 1);
// node_modules/@base-ui/react/utils/resolveRef.mjs
function resolveRef(maybeRef) {
if (maybeRef == null) {
return maybeRef;
}
return "current" in maybeRef ? maybeRef.current : maybeRef;
}
// node_modules/@base-ui/react/internals/useAnimationsFinished.mjs
function useAnimationsFinished(elementOrRef, waitForStartingStyleRemoved = false, treatAbortedAsFinished = true) {
const frame = useAnimationFrame();
return useStableCallback((fnToExecute, signal = null) => {
frame.cancel();
const element = resolveRef(elementOrRef);
if (element == null) {
return;
}
const resolvedElement = element;
const done = () => {
ReactDOM.flushSync(fnToExecute);
};
if (typeof resolvedElement.getAnimations !== "function" || globalThis.BASE_UI_ANIMATIONS_DISABLED) {
fnToExecute();
return;
}
function exec() {
Promise.all(resolvedElement.getAnimations().map((animation) => animation.finished)).then(() => {
if (!signal?.aborted) {
done();
}
}).catch(() => {
if (treatAbortedAsFinished) {
if (!signal?.aborted) {
done();
}
return;
}
const currentAnimations = resolvedElement.getAnimations();
if (!signal?.aborted && currentAnimations.length > 0 && currentAnimations.some((animation) => animation.pending || animation.playState !== "finished")) {
exec();
}
});
}
if (waitForStartingStyleRemoved) {
const startingStyleAttribute = TransitionStatusDataAttributes.startingStyle;
if (!resolvedElement.hasAttribute(startingStyleAttribute)) {
frame.request(exec);
return;
}
const attributeObserver = new MutationObserver(() => {
if (!resolvedElement.hasAttribute(startingStyleAttribute)) {
attributeObserver.disconnect();
exec();
}
});
attributeObserver.observe(resolvedElement, {
attributes: true,
attributeFilter: [startingStyleAttribute]
});
signal?.addEventListener("abort", () => attributeObserver.disconnect(), {
once: true
});
return;
}
frame.request(exec);
});
}
// node_modules/@base-ui/react/internals/useOpenChangeComplete.mjs
function useOpenChangeComplete(parameters) {
const {
enabled = true,
open,
ref,
onComplete: onCompleteParam
} = parameters;
const onComplete = useStableCallback(onCompleteParam);
const runOnceAnimationsFinish = useAnimationsFinished(ref, open, false);
React22.useEffect(() => {
if (!enabled) {
return void 0;
}
const abortController = new AbortController();
runOnceAnimationsFinish(onComplete, abortController.signal);
return () => {
abortController.abort();
};
}, [enabled, open, onComplete, runOnceAnimationsFinish]);
}
// node_modules/@base-ui/react/collapsible/panel/useCollapsiblePanel.mjs
var EMPTY_DIMENSIONS = {
height: void 0,
width: void 0
};
function useCollapsiblePanel(parameters) {
const {
externalRef,
hiddenUntilFound,
id: idParam,
keepMounted,
mounted,
onOpenChange,
open,
setMounted,
setOpen,
transitionStatus
} = parameters;
const panelRef = React23.useRef(null);
const animationTypeRef = React23.useRef(null);
const [dimensions, setDimensionsUnwrapped] = React23.useState(EMPTY_DIMENSIONS);
const lastMeasuredDimensionsRef = React23.useRef(EMPTY_DIMENSIONS);
const shouldSkipNextOpenRef = React23.useRef(false);
const shouldPreventMountAnimationRef = React23.useRef(open);
const shouldPreventActivityResumeAnimationRef = React23.useRef(false);
const [forcePanelIdle, setForcePanelIdle] = React23.useState(false);
const pendingTemporaryStyleRestoreRef = React23.useRef(null);
const mergedPanelRef = useMergedRefs(externalRef, panelRef);
const latestStateRef = useValueAsRef({
mounted,
open
});
const runOnceCloseAnimationsFinish = useAnimationsFinished(panelRef, false, false);
const hidden = !open && !mounted;
const panelTransitionStatus = forcePanelIdle ? "idle" : transitionStatus;
const shouldPreventOpenAnimation = open && // These 2 refs are safe to read in render, they are only written from committed
// layout/effect paths and gate one-shot motion suppression for the next open
// lifecycle. They intentionally expose the last committed motion snapshot.
(shouldPreventMountAnimationRef.current || shouldPreventActivityResumeAnimationRef.current);
const renderedDimensions = !open && mounted && // These 2 refs are also safe to read in render, both hold the last committed
// animation mode and measurement. This fallback only restores a previously
// measured pixel size after the live dimensions state has been reset back to `auto`.
animationTypeRef.current === "css-animation" && dimensions.height === void 0 && dimensions.width === void 0 ? lastMeasuredDimensionsRef.current : dimensions;
const shouldPersistHiddenTransitionStyles = hiddenUntilFound && hidden && animationTypeRef.current !== "css-animation";
const setDimensions = useStableCallback((nextDimensions, shouldCacheMeasurement = true) => {
if (shouldCacheMeasurement) {
lastMeasuredDimensionsRef.current = nextDimensions;
}
setDimensionsUnwrapped(nextDimensions);
});
const restorePendingTemporaryStyle = useStableCallback(() => {
pendingTemporaryStyleRestoreRef.current?.();
pendingTemporaryStyleRestoreRef.current = null;
});
const setPendingTemporaryStyleRestore = useStableCallback((restore2) => {
restorePendingTemporaryStyle();
pendingTemporaryStyleRestoreRef.current = () => {
pendingTemporaryStyleRestoreRef.current = null;
restore2();
};
});
const markActivityResumeAnimationSuppressed = useStableCallback(() => {
if (open && mounted && animationTypeRef.current === "css-animation") {
shouldPreventActivityResumeAnimationRef.current = true;
}
});
useIsoLayoutEffect(() => {
if (!forcePanelIdle || transitionStatus === "starting") {
return;
}
setForcePanelIdle(false);
}, [forcePanelIdle, transitionStatus]);
React23.useEffect(() => {
return () => {
markActivityResumeAnimationSuppressed();
restorePendingTemporaryStyle();
};
}, [markActivityResumeAnimationSuppressed, restorePendingTemporaryStyle]);
useIsoLayoutEffect(() => {
const panel = panelRef.current;
if (!panel) {
return void 0;
}
if (!open && pendingTemporaryStyleRestoreRef.current) {
restorePendingTemporaryStyle();
}
const animationType = getAnimationType(panel, shouldPreventOpenAnimation);
animationTypeRef.current = animationType;
if (open && transitionStatus === "idle" && shouldPreventMountAnimationRef.current && animationType === "css-animation") {
lastMeasuredDimensionsRef.current = getDimensions(panel);
return void 0;
}
if (open && transitionStatus === "starting") {
const skipNextOpen = shouldSkipNextOpenRef.current;
shouldSkipNextOpenRef.current = false;
if (animationType === "none") {
setDimensions(getDimensions(panel));
setForcePanelIdle(true);
return void 0;
}
if (animationType === "css-transition") {
const restoreLayoutStyles = resetLayoutStyles(panel);
setDimensions(getDimensions(panel));
if (!skipNextOpen) {
return restoreLayoutStyles;
}
const restoreTransitionDuration = setTemporaryStyle(panel, "transition-duration", "0s");
setPendingTemporaryStyleRestore(restoreTransitionDuration);
setForcePanelIdle(true);
return restoreLayoutStyles;
}
if (animationType === "css-animation") {
setDimensions(getDimensions(panel));
if (!skipNextOpen) {
const restoreAnimationName2 = setTemporaryStyle(panel, "animation-name", "none");
restoreAnimationName2();
return void 0;
}
const restoreAnimationName = setTemporaryStyle(panel, "animation-name", "none");
const restoreAnimationDuration = setTemporaryStyle(panel, "animation-duration", "0s");
restoreAnimationName();
setPendingTemporaryStyleRestore(restoreAnimationDuration);
setForcePanelIdle(true);
return void 0;
}
}
if (!open && mounted && (transitionStatus === "idle" || transitionStatus === "starting")) {
shouldPreventMountAnimationRef.current = false;
shouldPreventActivityResumeAnimationRef.current = false;
if (animationType === "none") {
setDimensions(EMPTY_DIMENSIONS, false);
setMounted(false);
return void 0;
}
setDimensions(getDimensions(panel));
return void 0;
}
if (transitionStatus !== "ending") {
return void 0;
}
if (animationType === "none") {
setMounted(false);
return void 0;
}
const nextDimensions = getDimensions(panel);
const hasMeasuredSize = (nextDimensions.height ?? 0) > 0 || (nextDimensions.width ?? 0) > 0;
if (!hasMeasuredSize) {
setMounted(false);
return void 0;
}
setDimensions(nextDimensions);
if (animationType === "css-animation") {
const restoreAnimationName = setTemporaryStyle(panel, "animation-name", "none");
restoreAnimationName();
}
return void 0;
}, [mounted, open, restorePendingTemporaryStyle, setDimensions, setMounted, setPendingTemporaryStyleRestore, shouldPreventOpenAnimation, transitionStatus]);
useOpenChangeComplete({
enabled: open && mounted && panelTransitionStatus === "idle",
open: true,
ref: panelRef,
onComplete() {
if (!open) {
return;
}
setDimensions(EMPTY_DIMENSIONS, false);
}
});
React23.useEffect(() => {
if (open || !mounted || panelTransitionStatus !== "ending") {
return void 0;
}
const panel = panelRef.current;
if (!panel) {
return void 0;
}
const abortController = new AbortController();
let endingStyleFrame = -1;
function handleComplete() {
if (latestStateRef.current.open) {
return;
}
setMounted(false);
setDimensions(EMPTY_DIMENSIONS, false);
}
endingStyleFrame = AnimationFrame.request(() => {
if (!abortController.signal.aborted) {
runOnceCloseAnimationsFinish(handleComplete, abortController.signal);
}
});
return () => {
AnimationFrame.cancel(endingStyleFrame);
abortController.abort();
};
}, [latestStateRef, mounted, open, panelTransitionStatus, runOnceCloseAnimationsFinish, setDimensions, setMounted]);
useIsoLayoutEffect(() => {
const panel = panelRef.current;
if (!panel || !hiddenUntilFound || !hidden) {
return;
}
panel.setAttribute("hidden", "until-found");
}, [hidden, hiddenUntilFound]);
React23.useEffect(function registerBeforeMatchListener() {
const panel = panelRef.current;
if (!panel) {
return void 0;
}
function handleBeforeMatch(event) {
const eventDetails = createChangeEventDetails(reason_parts_exports.none, event);
onOpenChange(true, eventDetails);
if (eventDetails.isCanceled) {
return;
}
shouldSkipNextOpenRef.current = true;
setOpen(true);
}
return addEventListener(panel, "beforematch", handleBeforeMatch);
}, [onOpenChange, setOpen]);
const shouldRender = keepMounted || hiddenUntilFound || mounted || open;
return {
height: renderedDimensions.height,
props: {
...shouldPersistHiddenTransitionStyles ? {
[CollapsiblePanelDataAttributes.startingStyle]: ""
} : void 0,
hidden,
id: idParam
},
ref: mergedPanelRef,
shouldPreventOpenAnimation,
shouldRender,
transitionStatus: panelTransitionStatus,
width: renderedDimensions.width
};
}
function getDimensions(element) {
return {
height: element.scrollHeight,
width: element.scrollWidth
};
}
function getAnimationType(element, hasSuppressedMountAnimation = false) {
const panelStyles = getWindow(element).getComputedStyle(element);
const hasAnimation = (panelStyles.animationName.split(",").map((name) => name.trim()).some((name) => name !== "" && name !== "none") || hasSuppressedMountAnimation) && hasNonZeroDuration(panelStyles.animationDuration);
const hasTransition = hasNonZeroDuration(panelStyles.transitionDuration);
if (hasAnimation && hasTransition) {
if (true) {
warn("CSS transitions and CSS animations both detected on Collapsible or Accordion panel.", "Only one of either animation type should be used.");
}
return "css-transition";
}
if (hasTransition) {
return "css-transition";
}
if (hasAnimation) {
return "css-animation";
}
return "none";
}
function hasNonZeroDuration(value) {
return value.split(",").map((part) => part.trim()).some((part) => part !== "" && Number.parseFloat(part) > 0);
}
function setTemporaryStyle(element, property, value) {
const previousValue = element.style.getPropertyValue(property);
const previousPriority = element.style.getPropertyPriority(property);
element.style.setProperty(property, value);
return () => {
if (previousValue === "") {
element.style.removeProperty(property);
return;
}
element.style.setProperty(property, previousValue, previousPriority);
};
}
function resetLayoutStyles(element) {
const originalLayoutStyles = {
"justify-content": element.style.justifyContent,
"align-items": element.style.alignItems,
"align-content": element.style.alignContent,
"justify-items": element.style.justifyItems
};
Object.keys(originalLayoutStyles).forEach((key) => {
element.style.setProperty(key, "initial", "important");
});
function restoreLayoutStyles() {
Object.entries(originalLayoutStyles).forEach(([key, value]) => {
if (value === "") {
element.style.removeProperty(key);
return;
}
element.style.setProperty(key, value);
});
}
const frame = AnimationFrame.request(restoreLayoutStyles);
return () => {
AnimationFrame.cancel(frame);
restoreLayoutStyles();
};
}
// node_modules/@base-ui/utils/useOnFirstRender.mjs
var React24 = __toESM(require_react(), 1);
function useOnFirstRender(fn) {
const ref = React24.useRef(true);
if (ref.current) {
ref.current = false;
fn();
}
}
// node_modules/@base-ui/utils/platform/parts.mjs
var parts_exports = {};
__export(parts_exports, {
engine: () => engine_exports,
env: () => env_exports,
os: () => os_exports,
screenReader: () => screen_reader_exports
});
// node_modules/@base-ui/utils/platform/os.mjs
var os_exports = {};
__export(os_exports, {
android: () => android,
apple: () => apple,
ios: () => ios,
linux: () => linux,
mac: () => mac,
windows: () => windows
});
// node_modules/@base-ui/utils/platform/shared.mjs
function readRawData() {
if (typeof navigator === "undefined") {
return {
userAgent: "",
platform: "",
maxTouchPoints: 0
};
}
if (true) {
const uaData = navigator.userAgentData;
if (uaData && Array.isArray(uaData.brands)) {
return {
userAgent: uaData.brands.map(({
brand,
version: version2
}) => `${brand}/${version2}`).join(" "),
platform: uaData.platform ?? navigator.platform ?? "",
maxTouchPoints: navigator.maxTouchPoints ?? 0
};
}
}
return {
userAgent: navigator.userAgent,
platform: navigator.platform ?? "",
maxTouchPoints: navigator.maxTouchPoints ?? 0
};
}
var {
userAgent,
platform,
maxTouchPoints
} = readRawData();
var lowerUserAgent = userAgent.toLowerCase();
var lowerPlatform = platform.toLowerCase();
// node_modules/@base-ui/utils/platform/os.mjs
var ios = /^i(os$|p)/.test(lowerPlatform) || lowerPlatform === "macintel" && maxTouchPoints > 1;
var ANDROID_STRING = "android";
var android = lowerPlatform === ANDROID_STRING || lowerUserAgent.includes(ANDROID_STRING);
var mac = !ios && lowerPlatform.startsWith("mac");
var windows = lowerPlatform.startsWith("win");
var linux = !android && /^(linux|chrome os)/.test(lowerPlatform);
var apple = mac || ios;
// node_modules/@base-ui/utils/platform/engine.mjs
var engine_exports = {};
__export(engine_exports, {
blink: () => blink,
gecko: () => gecko,
webkit: () => webkit
});
var webkit = typeof CSS !== "undefined" && !!CSS.supports?.("-webkit-backdrop-filter:none");
var gecko = !webkit && lowerUserAgent.includes("firefox");
var blink = !webkit && lowerUserAgent.includes("chrom");
// node_modules/@base-ui/utils/platform/screen-reader.mjs
var screen_reader_exports = {};
__export(screen_reader_exports, {
voiceOver: () => voiceOver
});
var voiceOver = apple;
// node_modules/@base-ui/utils/platform/env.mjs
var env_exports = {};
__export(env_exports, {
jsdom: () => jsdom
});
var jsdom = /jsdom|happydom/.test(lowerUserAgent);
// node_modules/@base-ui/utils/useTimeout.mjs
var EMPTY3 = 0;
var Timeout = class _Timeout {
static create() {
return new _Timeout();
}
currentId = EMPTY3;
/**
* Executes `fn` after `delay`, clearing any previously scheduled call.
*/
start(delay, fn) {
this.clear();
this.currentId = setTimeout(() => {
this.currentId = EMPTY3;
fn();
}, delay);
}
isStarted() {
return this.currentId !== EMPTY3;
}
clear = () => {
if (this.currentId !== EMPTY3) {
clearTimeout(this.currentId);
this.currentId = EMPTY3;
}
};
disposeEffect = () => {
return this.clear;
};
};
function useTimeout() {
const timeout = useRefWithInit(Timeout.create).current;
useOnMount(timeout.disposeEffect);
return timeout;
}
// node_modules/@base-ui/utils/useScrollLock.mjs
var originalHtmlStyles = {};
var originalBodyStyles = {};
var originalHtmlScrollBehavior = "";
function hasInsetScrollbars(referenceElement) {
if (typeof document === "undefined") {
return false;
}
const doc = ownerDocument(referenceElement);
const win = getWindow(doc);
return win.innerWidth - doc.documentElement.clientWidth > 0;
}
function supportsStableScrollbarGutter(referenceElement) {
const supported = typeof CSS !== "undefined" && CSS.supports && CSS.supports("scrollbar-gutter", "stable");
if (!supported || typeof document === "undefined") {
return false;
}
const doc = ownerDocument(referenceElement);
const html = doc.documentElement;
const body = doc.body;
const scrollContainer = isOverflowElement(html) ? html : body;
const originalScrollContainerOverflowY = scrollContainer.style.overflowY;
const originalHtmlStyleGutter = html.style.scrollbarGutter;
html.style.scrollbarGutter = "stable";
scrollContainer.style.overflowY = "scroll";
const before = scrollContainer.offsetWidth;
scrollContainer.style.overflowY = "hidden";
const after = scrollContainer.offsetWidth;
scrollContainer.style.overflowY = originalScrollContainerOverflowY;
html.style.scrollbarGutter = originalHtmlStyleGutter;
return before === after;
}
function preventScrollOverlayScrollbars(referenceElement) {
const doc = ownerDocument(referenceElement);
const html = doc.documentElement;
const body = doc.body;
const elementToLock = isOverflowElement(html) ? html : body;
const originalElementToLockStyles = {
overflowY: elementToLock.style.overflowY,
overflowX: elementToLock.style.overflowX
};
Object.assign(elementToLock.style, {
overflowY: "hidden",
overflowX: "hidden"
});
return () => {
Object.assign(elementToLock.style, originalElementToLockStyles);
};
}
function preventScrollInsetScrollbars(referenceElement) {
const doc = ownerDocument(referenceElement);
const html = doc.documentElement;
const body = doc.body;
const win = getWindow(html);
let scrollTop = 0;
let scrollLeft = 0;
let updateGutterOnly = false;
const resizeFrame = AnimationFrame.create();
if (parts_exports.engine.webkit && (win.visualViewport?.scale ?? 1) !== 1) {
return () => {
};
}
function lockScroll() {
const htmlStyles = win.getComputedStyle(html);
const bodyStyles = win.getComputedStyle(body);
const htmlScrollbarGutterValue = htmlStyles.scrollbarGutter || "";
const hasBothEdges = htmlScrollbarGutterValue.includes("both-edges");
const scrollbarGutterValue = hasBothEdges ? "stable both-edges" : "stable";
scrollTop = html.scrollTop;
scrollLeft = html.scrollLeft;
originalHtmlStyles = {
scrollbarGutter: html.style.scrollbarGutter,
overflowY: html.style.overflowY,
overflowX: html.style.overflowX
};
originalHtmlScrollBehavior = html.style.scrollBehavior;
originalBodyStyles = {
position: body.style.position,
height: body.style.height,
width: body.style.width,
boxSizing: body.style.boxSizing,
overflowY: body.style.overflowY,
overflowX: body.style.overflowX,
scrollBehavior: body.style.scrollBehavior
};
const isScrollableY = html.scrollHeight > html.clientHeight;
const isScrollableX = html.scrollWidth > html.clientWidth;
const hasConstantOverflowY = htmlStyles.overflowY === "scroll" || bodyStyles.overflowY === "scroll";
const hasConstantOverflowX = htmlStyles.overflowX === "scroll" || bodyStyles.overflowX === "scroll";
const scrollbarWidth = Math.max(0, win.innerWidth - body.clientWidth);
const scrollbarHeight = Math.max(0, win.innerHeight - body.clientHeight);
const marginY = parseFloat(bodyStyles.marginTop) + parseFloat(bodyStyles.marginBottom);
const marginX = parseFloat(bodyStyles.marginLeft) + parseFloat(bodyStyles.marginRight);
const elementToLock = isOverflowElement(html) ? html : body;
updateGutterOnly = supportsStableScrollbarGutter(referenceElement);
if (updateGutterOnly) {
html.style.scrollbarGutter = scrollbarGutterValue;
elementToLock.style.overflowY = "hidden";
elementToLock.style.overflowX = "hidden";
return;
}
Object.assign(html.style, {
scrollbarGutter: scrollbarGutterValue,
overflowY: "hidden",
overflowX: "hidden"
});
if (isScrollableY || hasConstantOverflowY) {
html.style.overflowY = "scroll";
}
if (isScrollableX || hasConstantOverflowX) {
html.style.overflowX = "scroll";
}
Object.assign(body.style, {
position: "relative",
height: marginY || scrollbarHeight ? `calc(100dvh - ${marginY + scrollbarHeight}px)` : "100dvh",
width: marginX || scrollbarWidth ? `calc(100vw - ${marginX + scrollbarWidth}px)` : "100vw",
boxSizing: "border-box",
overflow: "hidden",
scrollBehavior: "unset"
});
body.scrollTop = scrollTop;
body.scrollLeft = scrollLeft;
html.setAttribute("data-base-ui-scroll-locked", "");
html.style.scrollBehavior = "unset";
}
function cleanup() {
Object.assign(html.style, originalHtmlStyles);
Object.assign(body.style, originalBodyStyles);
if (!updateGutterOnly) {
html.scrollTop = scrollTop;
html.scrollLeft = scrollLeft;
html.removeAttribute("data-base-ui-scroll-locked");
html.style.scrollBehavior = originalHtmlScrollBehavior;
}
}
function handleResize() {
cleanup();
resizeFrame.request(lockScroll);
}
lockScroll();
const unsubscribeResize = addEventListener(win, "resize", handleResize);
return () => {
resizeFrame.cancel();
cleanup();
if (typeof win.removeEventListener === "function") {
unsubscribeResize();
}
};
}
var ScrollLocker = class {
lockCount = 0;
restore = null;
timeoutLock = Timeout.create();
timeoutUnlock = Timeout.create();
acquire(referenceElement) {
this.lockCount += 1;
if (this.lockCount === 1 && this.restore === null) {
this.timeoutLock.start(0, () => this.lock(referenceElement));
}
return this.release;
}
release = () => {
this.lockCount -= 1;
if (this.lockCount === 0 && this.restore) {
this.timeoutUnlock.start(0, this.unlock);
}
};
unlock = () => {
if (this.lockCount === 0 && this.restore) {
this.restore?.();
this.restore = null;
}
};
lock(referenceElement) {
if (this.lockCount === 0 || this.restore !== null) {
return;
}
const doc = ownerDocument(referenceElement);
const html = doc.documentElement;
const htmlOverflowY = getWindow(html).getComputedStyle(html).overflowY;
if (htmlOverflowY === "hidden" || htmlOverflowY === "clip") {
this.restore = NOOP;
return;
}
const hasOverlayScrollbars = parts_exports.os.ios || !hasInsetScrollbars(referenceElement);
this.restore = hasOverlayScrollbars ? preventScrollOverlayScrollbars(referenceElement) : preventScrollInsetScrollbars(referenceElement);
}
};
var SCROLL_LOCKER = new ScrollLocker();
function useScrollLock(enabled = true, referenceElement = null) {
useIsoLayoutEffect(() => {
if (!enabled) {
return void 0;
}
return SCROLL_LOCKER.acquire(referenceElement);
}, [enabled, referenceElement]);
}
// node_modules/@base-ui/react/floating-ui-react/components/FloatingDelayGroup.mjs
var React25 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/floating-ui-react/utils/event.mjs
function stopEvent(event) {
event.preventDefault();
event.stopPropagation();
}
function isReactEvent(event) {
return "nativeEvent" in event;
}
function isVirtualClick(event) {
if (event.pointerType === "" && event.isTrusted) {
return true;
}
if (parts_exports.os.android && event.pointerType) {
return event.type === "click" && event.buttons === 1;
}
return event.detail === 0 && !event.pointerType;
}
function isVirtualPointerEvent(event) {
if (parts_exports.env.jsdom) {
return false;
}
return !parts_exports.os.android && event.width === 0 && event.height === 0 || parts_exports.os.android && event.width === 1 && event.height === 1 && event.pressure === 0 && event.detail === 0 && event.pointerType === "mouse" || // iOS VoiceOver returns 0.333• for width/height.
event.width < 1 && event.height < 1 && event.pressure === 0 && event.detail === 0 && event.pointerType === "touch";
}
function isMouseLikePointerType(pointerType, strict) {
const values = ["mouse", "pen"];
if (!strict) {
values.push("", void 0);
}
return values.includes(pointerType);
}
function isClickLikeEvent(event) {
const type = event.type;
return type === "click" || type === "mousedown" || type === "keydown" || type === "keyup";
}
// node_modules/@base-ui/react/floating-ui-react/utils/constants.mjs
var FOCUSABLE_ATTRIBUTE = "data-base-ui-focusable";
var TYPEABLE_SELECTOR = "input:not([type='hidden']):not([disabled]),[contenteditable]:not([contenteditable='false']),textarea:not([disabled])";
var ARROW_LEFT = "ArrowLeft";
var ARROW_RIGHT = "ArrowRight";
var ARROW_UP = "ArrowUp";
var ARROW_DOWN = "ArrowDown";
// node_modules/@base-ui/react/internals/shadowDom.mjs
function activeElement(doc) {
let element = doc.activeElement;
while (element?.shadowRoot?.activeElement != null) {
element = element.shadowRoot.activeElement;
}
return element;
}
function contains(parent, child) {
if (!parent || !child) {
return false;
}
const rootNode = child.getRootNode?.();
if (parent.contains(child)) {
return true;
}
if (rootNode && isShadowRoot(rootNode)) {
let next = child;
while (next) {
if (parent === next) {
return true;
}
next = next.parentNode || next.host;
}
}
return false;
}
function getTarget(event) {
if ("composedPath" in event) {
return event.composedPath()[0];
}
return event.target;
}
// node_modules/@base-ui/react/floating-ui-react/utils/element.mjs
function isTargetInsideEnabledTrigger(target, triggerElements) {
if (!isElement(target)) {
return false;
}
const targetElement = target;
if (triggerElements.hasElement(targetElement)) {
return !targetElement.hasAttribute("data-trigger-disabled");
}
for (const [, trigger] of triggerElements.entries()) {
if (contains(trigger, targetElement)) {
return !trigger.hasAttribute("data-trigger-disabled");
}
}
return false;
}
function isEventTargetWithin(event, node) {
if (node == null) {
return false;
}
if ("composedPath" in event) {
return event.composedPath().includes(node);
}
const eventAgain = event;
return eventAgain.target != null && node.contains(eventAgain.target);
}
function isRootElement(element) {
return element.matches("html,body");
}
function isTypeableElement(element) {
return isHTMLElement(element) && element.matches(TYPEABLE_SELECTOR);
}
function isInteractiveElement(element) {
return element?.closest(`button,a[href],[role="button"],select,[tabindex]:not([tabindex="-1"]),${TYPEABLE_SELECTOR}`) != null;
}
function isTypeableCombobox(element) {
if (!element) {
return false;
}
return element.getAttribute("role") === "combobox" && isTypeableElement(element);
}
function matchesFocusVisible(element) {
if (!element || parts_exports.env.jsdom) {
return true;
}
try {
return element.matches(":focus-visible");
} catch (_e) {
return true;
}
}
function getFloatingFocusElement(floatingElement) {
if (!floatingElement) {
return null;
}
return floatingElement.hasAttribute(FOCUSABLE_ATTRIBUTE) ? floatingElement : floatingElement.querySelector(`[${FOCUSABLE_ATTRIBUTE}]`) || floatingElement;
}
// node_modules/@base-ui/react/floating-ui-react/hooks/useHoverShared.mjs
function resolveValue(value, pointerType) {
if (pointerType != null && !isMouseLikePointerType(pointerType)) {
return 0;
}
if (typeof value === "function") {
return value();
}
return value;
}
function getDelay(value, prop, pointerType) {
const result = resolveValue(value, pointerType);
if (typeof result === "number") {
return result;
}
return result?.[prop];
}
function getRestMs(value) {
if (typeof value === "function") {
return value();
}
return value;
}
function isClickLikeOpenEvent(openEventType, interactedInside) {
return interactedInside || openEventType === "click" || openEventType === "mousedown";
}
function isHoverOpenEvent(openEventType) {
return openEventType?.includes("mouse") && openEventType !== "mousedown";
}
// node_modules/@base-ui/react/floating-ui-react/components/FloatingDelayGroup.mjs
var import_jsx_runtime153 = __toESM(require_jsx_runtime(), 1);
var FloatingDelayGroupContext = /* @__PURE__ */ React25.createContext({
hasProvider: false,
timeoutMs: 0,
delayRef: {
current: 0
},
initialDelayRef: {
current: 0
},
timeout: new Timeout(),
currentIdRef: {
current: null
},
currentContextRef: {
current: null
}
});
if (true) FloatingDelayGroupContext.displayName = "FloatingDelayGroupContext";
function resetDelayRef(delayRef, initialDelayRef) {
delayRef.current = initialDelayRef.current;
}
function FloatingDelayGroup(props) {
const {
children,
delay,
timeoutMs = 0
} = props;
const delayRef = React25.useRef(delay);
const initialDelayRef = React25.useRef(delay);
const currentIdRef = React25.useRef(null);
const currentContextRef = React25.useRef(null);
const timeout = useTimeout();
useIsoLayoutEffect(() => {
initialDelayRef.current = delay;
if (!currentIdRef.current) {
delayRef.current = delay;
return;
}
delayRef.current = {
open: getDelay(delayRef.current, "open"),
close: getDelay(delay, "close")
};
}, [delay, currentIdRef, delayRef, initialDelayRef]);
return /* @__PURE__ */ (0, import_jsx_runtime153.jsx)(FloatingDelayGroupContext.Provider, {
value: React25.useMemo(() => ({
hasProvider: true,
delayRef,
initialDelayRef,
currentIdRef,
timeoutMs,
currentContextRef,
timeout
}), [timeoutMs, timeout]),
children
});
}
function useDelayGroup(context, options = {
open: false
}) {
const {
open
} = options;
const store2 = "rootStore" in context ? context.rootStore : context;
const floatingId = store2.useState("floatingId");
const groupContext = React25.useContext(FloatingDelayGroupContext);
const {
currentIdRef,
delayRef,
timeoutMs,
initialDelayRef,
currentContextRef,
hasProvider,
timeout
} = groupContext;
const [isInstantPhase, setIsInstantPhase] = React25.useState(false);
const openRef = React25.useRef(open);
const isUnmountedRef = React25.useRef(false);
useIsoLayoutEffect(() => {
openRef.current = open;
}, [open]);
useIsoLayoutEffect(() => {
return () => {
isUnmountedRef.current = true;
};
}, []);
useIsoLayoutEffect(() => {
function unset() {
if (!isUnmountedRef.current) {
setIsInstantPhase(false);
}
currentContextRef.current?.setIsInstantPhase(false);
currentIdRef.current = null;
currentContextRef.current = null;
delayRef.current = initialDelayRef.current;
timeout.clear();
}
if (!currentIdRef.current) {
return void 0;
}
if (!open && currentIdRef.current === floatingId) {
setIsInstantPhase(false);
if (timeoutMs) {
const closingId = floatingId;
timeout.start(timeoutMs, () => {
if (store2.select("open") || currentIdRef.current && currentIdRef.current !== closingId) {
return;
}
unset();
});
return () => {
if (openRef.current || currentIdRef.current !== closingId) {
timeout.clear();
}
};
}
unset();
}
return void 0;
}, [open, floatingId, currentIdRef, delayRef, timeoutMs, initialDelayRef, currentContextRef, timeout, store2]);
useIsoLayoutEffect(() => {
if (!open) {
return;
}
const prevContext = currentContextRef.current;
const prevId = currentIdRef.current;
timeout.clear();
currentContextRef.current = {
onOpenChange: store2.setOpen,
setIsInstantPhase
};
currentIdRef.current = floatingId;
delayRef.current = {
open: 0,
close: getDelay(initialDelayRef.current, "close")
};
if (prevId !== null && prevId !== floatingId) {
setIsInstantPhase(true);
prevContext?.setIsInstantPhase(true);
prevContext?.onOpenChange(false, createChangeEventDetails(reason_parts_exports.none));
} else {
setIsInstantPhase(false);
prevContext?.setIsInstantPhase(false);
}
}, [open, floatingId, store2, currentIdRef, delayRef, initialDelayRef, currentContextRef, timeout]);
useIsoLayoutEffect(() => {
return () => {
if (currentIdRef.current === floatingId) {
currentContextRef.current = null;
if (!openRef.current) {
return;
}
currentIdRef.current = null;
resetDelayRef(delayRef, initialDelayRef);
timeout.clear();
}
};
}, [currentContextRef, currentIdRef, delayRef, floatingId, initialDelayRef, timeout]);
return React25.useMemo(() => ({
hasProvider,
delayRef,
isInstantPhase
}), [hasProvider, delayRef, isInstantPhase]);
}
// node_modules/@base-ui/react/floating-ui-react/components/FloatingFocusManager.mjs
var React29 = __toESM(require_react(), 1);
// node_modules/@base-ui/utils/mergeCleanups.mjs
function mergeCleanups(...cleanups) {
return () => {
for (let i2 = 0; i2 < cleanups.length; i2 += 1) {
const cleanup = cleanups[i2];
if (cleanup) {
cleanup();
}
}
};
}
// node_modules/@base-ui/react/utils/FocusGuard.mjs
var React26 = __toESM(require_react(), 1);
// node_modules/@base-ui/utils/visuallyHidden.mjs
var visuallyHiddenBase = {
clipPath: "inset(50%)",
overflow: "hidden",
whiteSpace: "nowrap",
border: 0,
padding: 0,
width: 1,
height: 1,
margin: -1
};
var visuallyHidden = {
...visuallyHiddenBase,
position: "fixed",
top: 0,
left: 0
};
var visuallyHiddenInput = {
...visuallyHiddenBase,
position: "absolute"
};
// node_modules/@base-ui/react/utils/FocusGuard.mjs
var import_jsx_runtime154 = __toESM(require_jsx_runtime(), 1);
var FocusGuard = /* @__PURE__ */ React26.forwardRef(function FocusGuard2(props, ref) {
const [role, setRole] = React26.useState();
useIsoLayoutEffect(() => {
if (parts_exports.screenReader.voiceOver && parts_exports.engine.webkit) {
setRole("button");
}
}, []);
const restProps = {
tabIndex: 0,
// Role is only for VoiceOver
role
};
return /* @__PURE__ */ (0, import_jsx_runtime154.jsx)("span", {
...props,
ref,
style: visuallyHidden,
"aria-hidden": role ? void 0 : true,
...restProps,
"data-base-ui-focus-guard": ""
});
});
if (true) FocusGuard.displayName = "FocusGuard";
// node_modules/@floating-ui/utils/dist/floating-ui.utils.mjs
var sides = ["top", "right", "bottom", "left"];
var min = Math.min;
var max = Math.max;
var round = Math.round;
var floor = Math.floor;
var createCoords = (v2) => ({
x: v2,
y: v2
});
var oppositeSideMap = {
left: "right",
right: "left",
bottom: "top",
top: "bottom"
};
function clamp(start2, value, end) {
return max(start2, min(value, end));
}
function evaluate(value, param) {
return typeof value === "function" ? value(param) : value;
}
function getSide(placement) {
return placement.split("-")[0];
}
function getAlignment(placement) {
return placement.split("-")[1];
}
function getOppositeAxis(axis) {
return axis === "x" ? "y" : "x";
}
function getAxisLength(axis) {
return axis === "y" ? "height" : "width";
}
function getSideAxis(placement) {
const firstChar = placement[0];
return firstChar === "t" || firstChar === "b" ? "y" : "x";
}
function getAlignmentAxis(placement) {
return getOppositeAxis(getSideAxis(placement));
}
function getAlignmentSides(placement, rects, rtl) {
if (rtl === void 0) {
rtl = false;
}
const alignment = getAlignment(placement);
const alignmentAxis = getAlignmentAxis(placement);
const length = getAxisLength(alignmentAxis);
let mainAlignmentSide = alignmentAxis === "x" ? alignment === (rtl ? "end" : "start") ? "right" : "left" : alignment === "start" ? "bottom" : "top";
if (rects.reference[length] > rects.floating[length]) {
mainAlignmentSide = getOppositePlacement(mainAlignmentSide);
}
return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)];
}
function getExpandedPlacements(placement) {
const oppositePlacement = getOppositePlacement(placement);
return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)];
}
function getOppositeAlignmentPlacement(placement) {
return placement.includes("start") ? placement.replace("start", "end") : placement.replace("end", "start");
}
var lrPlacement = ["left", "right"];
var rlPlacement = ["right", "left"];
var tbPlacement = ["top", "bottom"];
var btPlacement = ["bottom", "top"];
function getSideList(side, isStart, rtl) {
switch (side) {
case "top":
case "bottom":
if (rtl) return isStart ? rlPlacement : lrPlacement;
return isStart ? lrPlacement : rlPlacement;
case "left":
case "right":
return isStart ? tbPlacement : btPlacement;
default:
return [];
}
}
function getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) {
const alignment = getAlignment(placement);
let list = getSideList(getSide(placement), direction === "start", rtl);
if (alignment) {
list = list.map((side) => side + "-" + alignment);
if (flipAlignment) {
list = list.concat(list.map(getOppositeAlignmentPlacement));
}
}
return list;
}
function getOppositePlacement(placement) {
const side = getSide(placement);
return oppositeSideMap[side] + placement.slice(side.length);
}
function expandPaddingObject(padding) {
return {
top: 0,
right: 0,
bottom: 0,
left: 0,
...padding
};
}
function getPaddingObject(padding) {
return typeof padding !== "number" ? expandPaddingObject(padding) : {
top: padding,
right: padding,
bottom: padding,
left: padding
};
}
function rectToClientRect(rect) {
const {
x: x2,
y: y2,
width,
height
} = rect;
return {
width,
height,
top: y2,
left: x2,
right: x2 + width,
bottom: y2 + height,
x: x2,
y: y2
};
}
// node_modules/@base-ui/react/floating-ui-react/utils/composite.mjs
function isIndexOutOfListBounds(list, index2) {
return index2 < 0 || index2 >= list.length;
}
function getMinListIndex(listRef, disabledIndices) {
return findNonDisabledListIndex(listRef.current, {
disabledIndices
});
}
function getMaxListIndex(listRef, disabledIndices) {
return findNonDisabledListIndex(listRef.current, {
decrement: true,
startingIndex: listRef.current.length,
disabledIndices
});
}
function findNonDisabledListIndex(list, {
startingIndex = -1,
decrement = false,
disabledIndices,
amount = 1
} = {}) {
let index2 = startingIndex;
do {
index2 += decrement ? -amount : amount;
} while (index2 >= 0 && index2 <= list.length - 1 && isListIndexDisabled(list, index2, disabledIndices));
return index2;
}
function isListIndexDisabled(list, index2, disabledIndices) {
const isExplicitlyDisabled = typeof disabledIndices === "function" ? disabledIndices(index2) : disabledIndices?.includes(index2) ?? false;
if (isExplicitlyDisabled) {
return true;
}
const element = list[index2];
if (!element) {
return false;
}
if (!isElementVisible2(element)) {
return true;
}
return !disabledIndices && (element.hasAttribute("disabled") || element.getAttribute("aria-disabled") === "true");
}
function isHiddenByStyles(styles) {
return styles.visibility === "hidden" || styles.visibility === "collapse";
}
function isElementVisible2(element, styles = element ? getComputedStyle2(element) : null) {
if (!element || !element.isConnected || !styles || isHiddenByStyles(styles)) {
return false;
}
if (typeof element.checkVisibility === "function") {
return element.checkVisibility();
}
return styles.display !== "none" && styles.display !== "contents";
}
// node_modules/@base-ui/react/floating-ui-react/utils/tabbable.mjs
var CANDIDATE_SELECTOR = 'a[href],button,input,select,textarea,summary,details,iframe,object,embed,[tabindex],[contenteditable]:not([contenteditable="false"]),audio[controls],video[controls]';
function getParentElement(element) {
const assignedSlot = element.assignedSlot;
if (assignedSlot) {
return assignedSlot;
}
if (element.parentElement) {
return element.parentElement;
}
const rootNode = element.getRootNode();
return isShadowRoot(rootNode) ? rootNode.host : null;
}
function getDetailsSummary(details) {
for (const child of Array.from(details.children)) {
if (getNodeName(child) === "summary") {
return child;
}
}
return null;
}
function isWithinOpenDetailsSummary(element, details) {
const summary = getDetailsSummary(details);
return !!summary && (element === summary || contains(summary, element));
}
function isFocusableCandidate(element) {
const nodeName = element ? getNodeName(element) : "";
return element != null && element.matches(CANDIDATE_SELECTOR) && (nodeName !== "summary" || element.parentElement != null && getNodeName(element.parentElement) === "details" && getDetailsSummary(element.parentElement) === element) && (nodeName !== "details" || getDetailsSummary(element) == null) && (nodeName !== "input" || element.type !== "hidden");
}
function isFocusableElement(element) {
if (!isFocusableCandidate(element) || !element.isConnected || element.matches(":disabled")) {
return false;
}
for (let current = element; current; current = getParentElement(current)) {
const isAncestor = current !== element;
const isSlot = getNodeName(current) === "slot";
if (current.hasAttribute("inert")) {
return false;
}
if (isAncestor && getNodeName(current) === "details" && !current.open && !isWithinOpenDetailsSummary(element, current) || current.hasAttribute("hidden") || !isSlot && !isVisibleInTabbableTree(current, isAncestor)) {
return false;
}
}
return true;
}
function isVisibleInTabbableTree(element, isAncestor) {
const styles = getComputedStyle2(element);
if (!isAncestor) {
return isElementVisible2(element, styles);
}
return styles.display !== "none";
}
function getTabIndex(element) {
const tabIndex = element.tabIndex;
if (tabIndex < 0) {
const nodeName = getNodeName(element);
if (nodeName === "details" || nodeName === "audio" || nodeName === "video" || isHTMLElement(element) && element.isContentEditable) {
return 0;
}
}
return tabIndex;
}
function getNamedRadioInput(element) {
if (getNodeName(element) !== "input") {
return null;
}
const input = element;
return input.type === "radio" && input.name !== "" ? input : null;
}
function isTabbableRadio(element, candidates) {
const input = getNamedRadioInput(element);
if (!input) {
return true;
}
const checkedRadio = candidates.find((candidate) => {
const radio = getNamedRadioInput(candidate);
return radio?.name === input.name && radio.form === input.form && radio.checked;
});
if (checkedRadio) {
return checkedRadio === input;
}
return candidates.find((candidate) => {
const radio = getNamedRadioInput(candidate);
return radio?.name === input.name && radio.form === input.form;
}) === input;
}
function getComposedChildren(container) {
if (isHTMLElement(container) && getNodeName(container) === "slot") {
const assignedElements = container.assignedElements({
flatten: true
});
if (assignedElements.length > 0) {
return assignedElements;
}
}
if (isHTMLElement(container) && container.shadowRoot) {
return Array.from(container.shadowRoot.children);
}
return Array.from(container.children);
}
function appendCandidates(container, list) {
getComposedChildren(container).forEach((child) => {
if (isFocusableCandidate(child)) {
list.push(child);
}
appendCandidates(child, list);
});
}
function appendMatchingElements(container, selector3, list) {
getComposedChildren(container).forEach((child) => {
if (isHTMLElement(child) && child.matches(selector3)) {
list.push(child);
}
appendMatchingElements(child, selector3, list);
});
}
function isTabbable(element) {
return isFocusableElement(element) && getTabIndex(element) >= 0;
}
function focusable(container) {
const candidates = [];
appendCandidates(container, candidates);
return candidates.filter(isFocusableElement);
}
function tabbable(container) {
const candidates = focusable(container);
return candidates.filter((element) => getTabIndex(element) >= 0 && isTabbableRadio(element, candidates));
}
function getTabbableIn(container, dir) {
const list = tabbable(container);
const len = list.length;
if (len === 0) {
return void 0;
}
const active = activeElement(ownerDocument(container));
const index2 = list.indexOf(active);
const nextIndex = index2 === -1 ? dir === 1 ? 0 : len - 1 : index2 + dir;
return list[nextIndex];
}
function getNextTabbable(referenceElement) {
return getTabbableIn(ownerDocument(referenceElement).body, 1) || referenceElement;
}
function getPreviousTabbable(referenceElement) {
return getTabbableIn(ownerDocument(referenceElement).body, -1) || referenceElement;
}
function isOutsideEvent(event, container) {
const containerElement = container || event.currentTarget;
const relatedTarget = event.relatedTarget;
return !relatedTarget || !contains(containerElement, relatedTarget);
}
function disableFocusInside(container) {
const tabbableElements = tabbable(container);
tabbableElements.forEach((element) => {
element.dataset.tabindex = element.getAttribute("tabindex") || "";
element.setAttribute("tabindex", "-1");
});
}
function enableFocusInside(container) {
const elements = [];
appendMatchingElements(container, "[data-tabindex]", elements);
elements.forEach((element) => {
const tabindex = element.dataset.tabindex;
delete element.dataset.tabindex;
if (tabindex) {
element.setAttribute("tabindex", tabindex);
} else {
element.removeAttribute("tabindex");
}
});
}
// node_modules/@base-ui/react/floating-ui-react/utils/nodes.mjs
function getNodeChildren(nodes, id, onlyOpenChildren = true) {
const directChildren = nodes.filter((node) => node.parentId === id);
return directChildren.flatMap((child) => [...!onlyOpenChildren || child.context?.open ? [child] : [], ...getNodeChildren(nodes, child.id, onlyOpenChildren)]);
}
function getNodeAncestors(nodes, id) {
let allAncestors = [];
let currentParentId = nodes.find((node) => node.id === id)?.parentId;
while (currentParentId) {
const currentNode = nodes.find((node) => node.id === currentParentId);
currentParentId = currentNode?.parentId;
if (currentNode) {
allAncestors = allAncestors.concat(currentNode);
}
}
return allAncestors;
}
// node_modules/@base-ui/react/floating-ui-react/utils/createAttribute.mjs
function createAttribute(name) {
return `data-base-ui-${name}`;
}
// node_modules/@base-ui/react/floating-ui-react/utils/enqueueFocus.mjs
var rafId = 0;
function enqueueFocus(el, options = {}) {
const {
preventScroll = false,
sync: sync2 = false,
shouldFocus
} = options;
cancelAnimationFrame(rafId);
function exec() {
if (shouldFocus && !shouldFocus()) {
return;
}
el?.focus({
preventScroll
});
}
if (sync2) {
exec();
return NOOP;
}
const currentRafId = requestAnimationFrame(exec);
rafId = currentRafId;
return () => {
if (rafId === currentRafId) {
cancelAnimationFrame(currentRafId);
rafId = 0;
}
};
}
// node_modules/@base-ui/react/floating-ui-react/utils/markOthers.mjs
var counters = {
inert: /* @__PURE__ */ new WeakMap(),
"aria-hidden": /* @__PURE__ */ new WeakMap()
};
var markerName = "data-base-ui-inert";
var uncontrolledElementsSets = {
inert: /* @__PURE__ */ new WeakSet(),
"aria-hidden": /* @__PURE__ */ new WeakSet()
};
var markerCounterMap = /* @__PURE__ */ new WeakMap();
var lockCount = 0;
function getUncontrolledElementsSet(controlAttribute) {
return uncontrolledElementsSets[controlAttribute];
}
function unwrapHost(node) {
if (!node) {
return null;
}
return isShadowRoot(node) ? node.host : unwrapHost(node.parentNode);
}
var correctElements = (parent, targets) => targets.map((target) => {
if (parent.contains(target)) {
return target;
}
const correctedTarget = unwrapHost(target);
if (parent.contains(correctedTarget)) {
return correctedTarget;
}
return null;
}).filter((x2) => x2 != null);
var buildKeepSet = (targets) => {
const keep = /* @__PURE__ */ new Set();
targets.forEach((target) => {
let node = target;
while (node && !keep.has(node)) {
keep.add(node);
node = node.parentNode;
}
});
return keep;
};
var collectOutsideElements = (root, keepElements, stopElements) => {
const outside = [];
const walk = (parent) => {
if (!parent || stopElements.has(parent)) {
return;
}
Array.from(parent.children).forEach((node) => {
if (getNodeName(node) === "script") {
return;
}
if (keepElements.has(node)) {
walk(node);
} else {
outside.push(node);
}
});
};
walk(root);
return outside;
};
function applyAttributeToOthers(uncorrectedAvoidElements, body, ariaHidden, inert, {
mark = true
}) {
let controlAttribute = null;
if (inert) {
controlAttribute = "inert";
} else if (ariaHidden) {
controlAttribute = "aria-hidden";
}
let counterMap = null;
let uncontrolledElementsSet = null;
const avoidElements = correctElements(body, uncorrectedAvoidElements);
const markerTargets = mark ? collectOutsideElements(body, buildKeepSet(avoidElements), new Set(avoidElements)) : [];
const hiddenElements = [];
const markedElements = [];
if (controlAttribute) {
const map = counters[controlAttribute];
const currentUncontrolledElementsSet = getUncontrolledElementsSet(controlAttribute);
uncontrolledElementsSet = currentUncontrolledElementsSet;
counterMap = map;
const ariaLiveElements = correctElements(body, Array.from(body.querySelectorAll("[aria-live]")));
const controlElements = avoidElements.concat(ariaLiveElements);
const controlTargets = collectOutsideElements(body, buildKeepSet(controlElements), new Set(controlElements));
controlTargets.forEach((node) => {
const attr2 = node.getAttribute(controlAttribute);
const alreadyHidden = attr2 !== null && attr2 !== "false";
const counterValue = (map.get(node) || 0) + 1;
map.set(node, counterValue);
hiddenElements.push(node);
if (counterValue === 1 && alreadyHidden) {
currentUncontrolledElementsSet.add(node);
}
if (!alreadyHidden) {
node.setAttribute(controlAttribute, controlAttribute === "inert" ? "" : "true");
}
});
}
if (mark) {
markerTargets.forEach((node) => {
const markerValue = (markerCounterMap.get(node) || 0) + 1;
markerCounterMap.set(node, markerValue);
markedElements.push(node);
if (markerValue === 1) {
node.setAttribute(markerName, "");
}
});
}
lockCount += 1;
return () => {
if (counterMap) {
hiddenElements.forEach((element) => {
const currentCounterValue = counterMap.get(element) || 0;
const counterValue = currentCounterValue - 1;
counterMap.set(element, counterValue);
if (!counterValue) {
if (!uncontrolledElementsSet?.has(element) && controlAttribute) {
element.removeAttribute(controlAttribute);
}
uncontrolledElementsSet?.delete(element);
}
});
}
if (mark) {
markedElements.forEach((element) => {
const markerValue = (markerCounterMap.get(element) || 0) - 1;
markerCounterMap.set(element, markerValue);
if (!markerValue) {
element.removeAttribute(markerName);
}
});
}
lockCount -= 1;
if (!lockCount) {
counters.inert = /* @__PURE__ */ new WeakMap();
counters["aria-hidden"] = /* @__PURE__ */ new WeakMap();
uncontrolledElementsSets.inert = /* @__PURE__ */ new WeakSet();
uncontrolledElementsSets["aria-hidden"] = /* @__PURE__ */ new WeakSet();
markerCounterMap = /* @__PURE__ */ new WeakMap();
}
};
}
function markOthers(avoidElements, options = {}) {
const {
ariaHidden = false,
inert = false,
mark = true
} = options;
const body = ownerDocument(avoidElements[0]).body;
return applyAttributeToOthers(avoidElements, body, ariaHidden, inert, {
mark
});
}
// node_modules/@base-ui/react/floating-ui-react/components/FloatingPortal.mjs
var React27 = __toESM(require_react(), 1);
var ReactDOM2 = __toESM(require_react_dom(), 1);
// node_modules/@base-ui/react/internals/constants.mjs
var DISABLED_TRANSITIONS_STYLE = {
style: {
transition: "none"
}
};
var CLICK_TRIGGER_IDENTIFIER = "data-base-ui-click-trigger";
var BASE_UI_SWIPE_IGNORE_ATTRIBUTE = "data-base-ui-swipe-ignore";
var LEGACY_SWIPE_IGNORE_ATTRIBUTE = "data-swipe-ignore";
var BASE_UI_SWIPE_IGNORE_SELECTOR = `[${BASE_UI_SWIPE_IGNORE_ATTRIBUTE}]`;
var LEGACY_SWIPE_IGNORE_SELECTOR = `[${LEGACY_SWIPE_IGNORE_ATTRIBUTE}]`;
var DROPDOWN_COLLISION_AVOIDANCE = {
fallbackAxisSide: "none"
};
var POPUP_COLLISION_AVOIDANCE = {
fallbackAxisSide: "end"
};
var ownerVisuallyHidden = {
clipPath: "inset(50%)",
position: "fixed",
top: 0,
left: 0
};
// node_modules/@base-ui/react/floating-ui-react/components/FloatingPortal.mjs
var import_jsx_runtime155 = __toESM(require_jsx_runtime(), 1);
var PortalContext = /* @__PURE__ */ React27.createContext(null);
if (true) PortalContext.displayName = "PortalContext";
var usePortalContext = () => React27.useContext(PortalContext);
var attr = createAttribute("portal");
function useFloatingPortalNode(props = {}) {
const {
ref,
container: containerProp,
componentProps = EMPTY_OBJECT,
elementProps
} = props;
const uniqueId2 = useId();
const portalContext = usePortalContext();
const parentPortalNode = portalContext?.portalNode;
const [containerElement, setContainerElement] = React27.useState(null);
const [portalNode, setPortalNode] = React27.useState(null);
const setPortalNodeRef = useStableCallback((node) => {
if (node !== null) {
setPortalNode(node);
}
});
const containerRef = React27.useRef(null);
useIsoLayoutEffect(() => {
if (containerProp === null) {
if (containerRef.current) {
containerRef.current = null;
setPortalNode(null);
setContainerElement(null);
}
return;
}
if (uniqueId2 == null) {
return;
}
const resolvedContainer = (containerProp && (isNode(containerProp) ? containerProp : containerProp.current)) ?? parentPortalNode ?? document.body;
if (resolvedContainer == null) {
if (containerRef.current) {
containerRef.current = null;
setPortalNode(null);
setContainerElement(null);
}
return;
}
if (containerRef.current !== resolvedContainer) {
containerRef.current = resolvedContainer;
setPortalNode(null);
setContainerElement(resolvedContainer);
}
}, [containerProp, parentPortalNode, uniqueId2]);
const portalElement = useRenderElement("div", componentProps, {
ref: [ref, setPortalNodeRef],
props: [{
id: uniqueId2,
[attr]: ""
}, elementProps]
});
const portalSubtree = containerElement && portalElement ? /* @__PURE__ */ ReactDOM2.createPortal(portalElement, containerElement) : null;
return {
portalNode,
portalSubtree
};
}
var FloatingPortal = /* @__PURE__ */ React27.forwardRef(function FloatingPortal2(componentProps, forwardedRef) {
const {
render: render4,
className,
style,
children,
container,
renderGuards,
...elementProps
} = componentProps;
const {
portalNode,
portalSubtree
} = useFloatingPortalNode({
container,
ref: forwardedRef,
componentProps,
elementProps
});
const beforeOutsideRef = React27.useRef(null);
const afterOutsideRef = React27.useRef(null);
const beforeInsideRef = React27.useRef(null);
const afterInsideRef = React27.useRef(null);
const [focusManagerState, setFocusManagerState] = React27.useState(null);
const focusInsideDisabledRef = React27.useRef(false);
const modal = focusManagerState?.modal;
const open = focusManagerState?.open;
const shouldRenderGuards = typeof renderGuards === "boolean" ? renderGuards : !!focusManagerState && !focusManagerState.modal && focusManagerState.open && !!portalNode;
React27.useEffect(() => {
if (!portalNode || modal) {
return void 0;
}
function onFocus(event) {
if (portalNode && event.relatedTarget && isOutsideEvent(event)) {
if (event.type === "focusin") {
if (focusInsideDisabledRef.current) {
enableFocusInside(portalNode);
focusInsideDisabledRef.current = false;
}
} else {
disableFocusInside(portalNode);
focusInsideDisabledRef.current = true;
}
}
}
return mergeCleanups(addEventListener(portalNode, "focusin", onFocus, true), addEventListener(portalNode, "focusout", onFocus, true));
}, [portalNode, modal]);
useIsoLayoutEffect(() => {
if (!portalNode || open !== true || !focusInsideDisabledRef.current) {
return;
}
enableFocusInside(portalNode);
focusInsideDisabledRef.current = false;
}, [open, portalNode]);
const portalContextValue = React27.useMemo(() => ({
beforeOutsideRef,
afterOutsideRef,
beforeInsideRef,
afterInsideRef,
portalNode,
setFocusManagerState
}), [portalNode]);
return /* @__PURE__ */ (0, import_jsx_runtime155.jsxs)(React27.Fragment, {
children: [portalSubtree, /* @__PURE__ */ (0, import_jsx_runtime155.jsxs)(PortalContext.Provider, {
value: portalContextValue,
children: [shouldRenderGuards && portalNode && /* @__PURE__ */ (0, import_jsx_runtime155.jsx)(FocusGuard, {
"data-type": "outside",
ref: beforeOutsideRef,
onFocus: (event) => {
if (isOutsideEvent(event, portalNode)) {
beforeInsideRef.current?.focus();
} else {
const domReference = focusManagerState ? focusManagerState.domReference : null;
const prevTabbable = getPreviousTabbable(domReference);
prevTabbable?.focus();
}
}
}), shouldRenderGuards && portalNode && /* @__PURE__ */ (0, import_jsx_runtime155.jsx)("span", {
"aria-owns": portalNode.id,
style: ownerVisuallyHidden
}), portalNode && /* @__PURE__ */ ReactDOM2.createPortal(children, portalNode), shouldRenderGuards && portalNode && /* @__PURE__ */ (0, import_jsx_runtime155.jsx)(FocusGuard, {
"data-type": "outside",
ref: afterOutsideRef,
onFocus: (event) => {
if (isOutsideEvent(event, portalNode)) {
afterInsideRef.current?.focus();
} else {
const domReference = focusManagerState ? focusManagerState.domReference : null;
const nextTabbable = getNextTabbable(domReference);
nextTabbable?.focus();
if (focusManagerState?.closeOnFocusOut) {
focusManagerState?.onOpenChange(false, createChangeEventDetails(reason_parts_exports.focusOut, event.nativeEvent));
}
}
}
})]
})]
});
});
if (true) FloatingPortal.displayName = "FloatingPortal";
// node_modules/@base-ui/react/floating-ui-react/components/FloatingTree.mjs
var React28 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/floating-ui-react/utils/createEventEmitter.mjs
function createEventEmitter() {
const map = /* @__PURE__ */ new Map();
return {
emit(event, data) {
map.get(event)?.forEach((listener) => listener(data));
},
on(event, listener) {
if (!map.has(event)) {
map.set(event, /* @__PURE__ */ new Set());
}
map.get(event).add(listener);
},
off(event, listener) {
map.get(event)?.delete(listener);
}
};
}
// node_modules/@base-ui/react/floating-ui-react/components/FloatingTree.mjs
var import_jsx_runtime156 = __toESM(require_jsx_runtime(), 1);
var FloatingNodeContext = /* @__PURE__ */ React28.createContext(null);
if (true) FloatingNodeContext.displayName = "FloatingNodeContext";
var FloatingTreeContext = /* @__PURE__ */ React28.createContext(null);
if (true) FloatingTreeContext.displayName = "FloatingTreeContext";
var useFloatingParentNodeId = () => React28.useContext(FloatingNodeContext)?.id || null;
var useFloatingTree = (externalTree) => {
const contextTree = React28.useContext(FloatingTreeContext);
return externalTree ?? contextTree;
};
// node_modules/@base-ui/react/floating-ui-react/components/FloatingFocusManager.mjs
var import_jsx_runtime157 = __toESM(require_jsx_runtime(), 1);
function getEventType(event, lastInteractionType) {
const win = getWindow(getTarget(event));
if (event instanceof win.KeyboardEvent) {
return "keyboard";
}
if (event instanceof win.FocusEvent) {
return lastInteractionType || "keyboard";
}
if ("pointerType" in event) {
return event.pointerType || "keyboard";
}
if ("touches" in event) {
return "touch";
}
if (event instanceof win.MouseEvent) {
return lastInteractionType || (event.detail === 0 ? "keyboard" : "mouse");
}
return "";
}
var LIST_LIMIT = 20;
var previouslyFocusedElements = [];
function clearDisconnectedPreviouslyFocusedElements() {
previouslyFocusedElements = previouslyFocusedElements.filter((entry) => {
return entry.deref()?.isConnected;
});
}
function addPreviouslyFocusedElement(element) {
clearDisconnectedPreviouslyFocusedElements();
if (element && getNodeName(element) !== "body") {
previouslyFocusedElements.push(new WeakRef(element));
if (previouslyFocusedElements.length > LIST_LIMIT) {
previouslyFocusedElements = previouslyFocusedElements.slice(-LIST_LIMIT);
}
}
}
function getPreviouslyFocusedElement() {
clearDisconnectedPreviouslyFocusedElements();
return previouslyFocusedElements[previouslyFocusedElements.length - 1]?.deref();
}
function getFirstTabbableElement(container) {
if (!container) {
return null;
}
if (isTabbable(container)) {
return container;
}
return tabbable(container)[0] || container;
}
function handleTabIndex(floatingFocusElement) {
if (floatingFocusElement.hasAttribute("tabindex") && !floatingFocusElement.hasAttribute("data-tabindex")) {
return;
}
if (!floatingFocusElement.getAttribute("role")?.includes("dialog")) {
return;
}
const focusableElements = focusable(floatingFocusElement);
const tabbableContent = focusableElements.filter((element) => {
const dataTabIndex = element.getAttribute("data-tabindex") || "";
return isTabbable(element) || element.hasAttribute("data-tabindex") && !dataTabIndex.startsWith("-");
});
const tabIndex = floatingFocusElement.getAttribute("tabindex");
if (tabbableContent.length === 0) {
if (tabIndex !== "0") {
floatingFocusElement.setAttribute("tabindex", "0");
floatingFocusElement.setAttribute("data-tabindex", "0");
}
} else if (tabIndex !== "-1" || floatingFocusElement.hasAttribute("data-tabindex") && floatingFocusElement.getAttribute("data-tabindex") !== "-1") {
floatingFocusElement.setAttribute("tabindex", "-1");
floatingFocusElement.setAttribute("data-tabindex", "-1");
}
}
function FloatingFocusManager(props) {
const {
context,
children,
disabled: disabled2 = false,
initialFocus = true,
returnFocus = true,
restoreFocus = false,
modal = true,
closeOnFocusOut = true,
openInteractionType = "",
nextFocusableElement,
previousFocusableElement,
beforeContentFocusGuardRef,
externalTree,
getInsideElements
} = props;
const store2 = "rootStore" in context ? context.rootStore : context;
const open = store2.useState("open");
const domReference = store2.useState("domReferenceElement");
const floating = store2.useState("floatingElement");
const {
events,
dataRef
} = store2.context;
const getNodeId = useStableCallback(() => dataRef.current.floatingContext?.nodeId);
const ignoreInitialFocus = initialFocus === false;
const isUntrappedTypeableCombobox = isTypeableCombobox(domReference) && ignoreInitialFocus;
const initialFocusRef = useValueAsRef(initialFocus);
const returnFocusRef = useValueAsRef(returnFocus);
const openInteractionTypeRef = useValueAsRef(openInteractionType);
const openRef = useValueAsRef(open);
const tree = useFloatingTree(externalTree);
const portalContext = usePortalContext();
const preventReturnFocusRef = React29.useRef(false);
const isPointerDownRef = React29.useRef(false);
const pointerDownOutsideRef = React29.useRef(false);
const lastFocusedTabbableRef = React29.useRef(null);
const closeTypeRef = React29.useRef("");
const lastInteractionTypeRef = React29.useRef("");
const beforeGuardRef = React29.useRef(null);
const afterGuardRef = React29.useRef(null);
const mergedBeforeGuardRef = useMergedRefs(beforeGuardRef, beforeContentFocusGuardRef, portalContext?.beforeInsideRef);
const mergedAfterGuardRef = useMergedRefs(afterGuardRef, portalContext?.afterInsideRef);
const blurTimeout = useTimeout();
const pointerDownTimeout = useTimeout();
const restoreFocusFrame = useAnimationFrame();
const isInsidePortal = portalContext != null;
const floatingFocusElement = getFloatingFocusElement(floating);
const getTabbableContent = useStableCallback((container = floatingFocusElement) => {
return container ? tabbable(container) : [];
});
const getResolvedInsideElements = useStableCallback(() => getInsideElements?.().filter((element) => element != null) ?? []);
React29.useEffect(() => {
if (disabled2 || !modal) {
return void 0;
}
function onKeyDown(event) {
if (event.key === "Tab") {
if (contains(floatingFocusElement, activeElement(ownerDocument(floatingFocusElement))) && getTabbableContent().length === 0 && !isUntrappedTypeableCombobox) {
stopEvent(event);
}
}
}
const doc = ownerDocument(floatingFocusElement);
return addEventListener(doc, "keydown", onKeyDown);
}, [disabled2, floatingFocusElement, modal, isUntrappedTypeableCombobox, getTabbableContent]);
React29.useEffect(() => {
if (disabled2 || !open) {
return void 0;
}
const doc = ownerDocument(floatingFocusElement);
function clearPointerDownOutside() {
pointerDownOutsideRef.current = false;
}
function onPointerDown(event) {
const target = getTarget(event);
const insideElements = getResolvedInsideElements();
const pointerTargetInside = contains(floating, target) || contains(domReference, target) || contains(portalContext?.portalNode, target) || insideElements.some((element) => element === target || contains(element, target));
pointerDownOutsideRef.current = !pointerTargetInside;
lastInteractionTypeRef.current = event.pointerType || "keyboard";
if (target?.closest(`[${CLICK_TRIGGER_IDENTIFIER}]`)) {
isPointerDownRef.current = true;
pointerDownTimeout.start(0, () => {
isPointerDownRef.current = false;
});
}
}
function onKeyDown() {
lastInteractionTypeRef.current = "keyboard";
}
return mergeCleanups(
addEventListener(doc, "pointerdown", onPointerDown, true),
addEventListener(doc, "pointerup", clearPointerDownOutside, true),
addEventListener(doc, "pointercancel", clearPointerDownOutside, true),
addEventListener(doc, "keydown", onKeyDown, true),
// Avoid a stale `true` leaking into the next open (e.g. keep-mounted popups)
// if the popup dismissed between pointerdown and pointerup.
clearPointerDownOutside
);
}, [disabled2, floating, domReference, floatingFocusElement, open, portalContext, pointerDownTimeout, getResolvedInsideElements]);
React29.useEffect(() => {
if (disabled2 || !closeOnFocusOut) {
return void 0;
}
const doc = ownerDocument(floatingFocusElement);
function handlePointerDown() {
isPointerDownRef.current = true;
pointerDownTimeout.start(0, () => {
isPointerDownRef.current = false;
});
}
function handleFocusIn(event) {
const target = getTarget(event);
if (isTabbable(target)) {
lastFocusedTabbableRef.current = target;
}
}
function handleFocusOutside(event) {
const relatedTarget = event.relatedTarget;
const currentTarget = event.currentTarget;
const target = getTarget(event);
if (modal && relatedTarget == null && target != null && contains(floating, target)) {
addPreviouslyFocusedElement(target);
}
queueMicrotask(() => {
const nodeId = getNodeId();
const triggers = store2.context.triggerElements;
const insideElements = getResolvedInsideElements();
const isRelatedFocusGuard = relatedTarget?.hasAttribute(createAttribute("focus-guard")) && [beforeGuardRef.current, afterGuardRef.current, portalContext?.beforeInsideRef.current, portalContext?.afterInsideRef.current, portalContext?.beforeOutsideRef.current, portalContext?.afterOutsideRef.current, resolveRef(previousFocusableElement), resolveRef(nextFocusableElement)].includes(relatedTarget);
const movedToUnrelatedNode = !(contains(domReference, relatedTarget) || contains(floating, relatedTarget) || contains(relatedTarget, floating) || contains(portalContext?.portalNode, relatedTarget) || insideElements.some((element) => element === relatedTarget || contains(element, relatedTarget)) || relatedTarget != null && triggers.hasElement(relatedTarget) || triggers.hasMatchingElement((trigger) => contains(trigger, relatedTarget)) || isRelatedFocusGuard || tree && (getNodeChildren(tree.nodesRef.current, nodeId).find((node) => contains(node.context?.elements.floating, relatedTarget) || contains(node.context?.elements.domReference, relatedTarget)) || getNodeAncestors(tree.nodesRef.current, nodeId).find((node) => [node.context?.elements.floating, getFloatingFocusElement(node.context?.elements.floating)].includes(relatedTarget) || node.context?.elements.domReference === relatedTarget)));
if (currentTarget === domReference && floatingFocusElement) {
handleTabIndex(floatingFocusElement);
}
if (restoreFocus && currentTarget !== domReference && !isElementVisible2(target) && activeElement(doc) === doc.body) {
if (isHTMLElement(floatingFocusElement)) {
floatingFocusElement.focus();
if (restoreFocus === "popup") {
restoreFocusFrame.request(() => {
floatingFocusElement.focus();
});
return;
}
}
const tabbableContent = getTabbableContent();
const prevTabbable = lastFocusedTabbableRef.current;
const nodeToFocus = (prevTabbable && tabbableContent.includes(prevTabbable) ? prevTabbable : null) || tabbableContent[tabbableContent.length - 1] || floatingFocusElement;
if (isHTMLElement(nodeToFocus)) {
nodeToFocus.focus();
}
}
if (dataRef.current.insideReactTree) {
dataRef.current.insideReactTree = false;
return;
}
if ((isUntrappedTypeableCombobox ? true : !modal) && relatedTarget && movedToUnrelatedNode && !isPointerDownRef.current && // Fix React 18 Strict Mode returnFocus due to double rendering.
// For an "untrapped" typeable combobox (input role=combobox with
// initialFocus=false), re-opening the popup and tabbing out should still close it even
// when the previously focused element (e.g. the next tabbable outside the popup) is
// focused again. Otherwise, the popup remains open on the second Tab sequence:
// click input -> Tab (closes) -> click input -> Tab.
// Allow closing when `isUntrappedTypeableCombobox` regardless of the previously focused element.
(isUntrappedTypeableCombobox || relatedTarget !== getPreviouslyFocusedElement())) {
preventReturnFocusRef.current = true;
store2.setOpen(false, createChangeEventDetails(reason_parts_exports.focusOut, event));
}
});
}
function markInsideReactTree() {
if (pointerDownOutsideRef.current) {
return;
}
dataRef.current.insideReactTree = true;
blurTimeout.start(0, () => {
dataRef.current.insideReactTree = false;
});
}
const domReferenceElement = isHTMLElement(domReference) ? domReference : null;
if (!floating && !domReferenceElement) {
return void 0;
}
return mergeCleanups(domReferenceElement && addEventListener(domReferenceElement, "focusout", handleFocusOutside), domReferenceElement && addEventListener(domReferenceElement, "pointerdown", handlePointerDown), floating && addEventListener(floating, "focusin", handleFocusIn), floating && addEventListener(floating, "focusout", handleFocusOutside), floating && portalContext && addEventListener(floating, "focusout", markInsideReactTree, true));
}, [disabled2, domReference, floating, floatingFocusElement, modal, tree, portalContext, store2, closeOnFocusOut, restoreFocus, getTabbableContent, isUntrappedTypeableCombobox, getNodeId, dataRef, blurTimeout, pointerDownTimeout, restoreFocusFrame, nextFocusableElement, previousFocusableElement, getResolvedInsideElements]);
React29.useEffect(() => {
if (disabled2 || !floating || !open) {
return void 0;
}
const portalNodes = Array.from(portalContext?.portalNode?.querySelectorAll(`[${createAttribute("portal")}]`) || []);
const ancestors = tree ? getNodeAncestors(tree.nodesRef.current, getNodeId()) : [];
const rootAncestorComboboxDomReference = ancestors.find((node) => isTypeableCombobox(node.context?.elements.domReference || null))?.context?.elements.domReference;
const controlInsideElements = [floating, ...portalNodes, beforeGuardRef.current, afterGuardRef.current, portalContext?.beforeOutsideRef.current, portalContext?.afterOutsideRef.current, ...getResolvedInsideElements()];
const insideElements = [...controlInsideElements, rootAncestorComboboxDomReference, resolveRef(previousFocusableElement), resolveRef(nextFocusableElement), isUntrappedTypeableCombobox ? domReference : null].filter((x2) => x2 != null);
const ariaHiddenCleanup = markOthers(insideElements, {
ariaHidden: modal || isUntrappedTypeableCombobox,
mark: false
});
const markerInsideElements = [floating, ...portalNodes].filter((x2) => x2 != null);
const markerCleanup = markOthers(markerInsideElements);
return () => {
markerCleanup();
ariaHiddenCleanup();
};
}, [open, disabled2, domReference, floating, modal, portalContext, isUntrappedTypeableCombobox, tree, getNodeId, nextFocusableElement, previousFocusableElement, getResolvedInsideElements]);
useIsoLayoutEffect(() => {
if (!open || disabled2 || !isHTMLElement(floatingFocusElement)) {
return;
}
const doc = ownerDocument(floatingFocusElement);
const previouslyFocusedElement = activeElement(doc);
queueMicrotask(() => {
const initialFocusValueOrFn = initialFocusRef.current;
const resolvedInitialFocus = typeof initialFocusValueOrFn === "function" ? initialFocusValueOrFn(openInteractionTypeRef.current || "") : initialFocusValueOrFn;
if (resolvedInitialFocus === void 0 || resolvedInitialFocus === false) {
return;
}
const focusAlreadyInsideFloatingEl = contains(floatingFocusElement, previouslyFocusedElement);
if (focusAlreadyInsideFloatingEl) {
return;
}
let focusableElements = null;
const getDefaultFocusElement = () => {
if (focusableElements == null) {
focusableElements = getTabbableContent(floatingFocusElement);
}
return focusableElements[0] || floatingFocusElement;
};
let elToFocus;
if (resolvedInitialFocus === true || resolvedInitialFocus === null) {
elToFocus = getDefaultFocusElement();
} else {
elToFocus = resolveRef(resolvedInitialFocus);
}
elToFocus = elToFocus || getDefaultFocusElement();
const hadFocusInside = contains(floatingFocusElement, activeElement(doc));
enqueueFocus(elToFocus, {
preventScroll: elToFocus === floatingFocusElement,
shouldFocus() {
if (!openRef.current) {
return false;
}
if (hadFocusInside) {
return true;
}
const currentActiveElement = activeElement(doc);
const focusMovedInside = currentActiveElement !== elToFocus && contains(floatingFocusElement, currentActiveElement);
return !focusMovedInside;
}
});
});
}, [disabled2, open, floatingFocusElement, getTabbableContent, initialFocusRef, openInteractionTypeRef, openRef]);
useIsoLayoutEffect(() => {
if (disabled2 || !floatingFocusElement) {
return void 0;
}
const doc = ownerDocument(floatingFocusElement);
const elementFocusedBeforeOpen = activeElement(doc);
const preferPreviousFocus = openInteractionTypeRef.current == null;
addPreviouslyFocusedElement(elementFocusedBeforeOpen);
function onOpenChangeLocal(details) {
if (!details.open) {
closeTypeRef.current = getEventType(details.nativeEvent, lastInteractionTypeRef.current);
}
if (details.reason === reason_parts_exports.triggerHover && details.nativeEvent.type === "mouseleave") {
preventReturnFocusRef.current = true;
}
if (details.reason !== reason_parts_exports.outsidePress) {
return;
}
if (details.nested) {
preventReturnFocusRef.current = false;
} else if (isVirtualClick(details.nativeEvent) || isVirtualPointerEvent(details.nativeEvent)) {
preventReturnFocusRef.current = false;
} else {
let isPreventScrollSupported = false;
ownerDocument(floatingFocusElement).createElement("div").focus({
get preventScroll() {
isPreventScrollSupported = true;
return false;
}
});
if (isPreventScrollSupported) {
preventReturnFocusRef.current = false;
} else {
preventReturnFocusRef.current = true;
}
}
}
events.on("openchange", onOpenChangeLocal);
function getReturnElement() {
const returnFocusValueOrFn = returnFocusRef.current;
let resolvedReturnFocusValue = typeof returnFocusValueOrFn === "function" ? returnFocusValueOrFn(closeTypeRef.current) : returnFocusValueOrFn;
if (resolvedReturnFocusValue === void 0 || resolvedReturnFocusValue === false) {
return null;
}
if (resolvedReturnFocusValue === null) {
resolvedReturnFocusValue = true;
}
const referenceReturnElement = domReference?.isConnected ? domReference : null;
const previousReturnElement = elementFocusedBeforeOpen?.isConnected && getNodeName(elementFocusedBeforeOpen) !== "body" ? elementFocusedBeforeOpen : null;
let defaultReturnElement = preferPreviousFocus ? previousReturnElement || referenceReturnElement : referenceReturnElement || previousReturnElement;
if (!defaultReturnElement) {
defaultReturnElement = getPreviouslyFocusedElement() || null;
}
if (typeof resolvedReturnFocusValue === "boolean") {
return defaultReturnElement;
}
return resolveRef(resolvedReturnFocusValue) || defaultReturnElement || null;
}
return () => {
events.off("openchange", onOpenChangeLocal);
const activeEl = activeElement(doc);
const insideElements = getResolvedInsideElements();
const isFocusInsideFloatingTree = contains(floating, activeEl) || insideElements.some((element) => element === activeEl || contains(element, activeEl)) || tree && getNodeChildren(tree.nodesRef.current, getNodeId(), false).some((node) => contains(node.context?.elements.floating, activeEl));
const returnFocusValueOrFn = returnFocusRef.current;
const returnElement = getReturnElement();
queueMicrotask(() => {
const tabbableReturnElement = getFirstTabbableElement(returnElement);
const hasExplicitReturnFocus = typeof returnFocusValueOrFn !== "boolean";
if (returnFocusValueOrFn && !preventReturnFocusRef.current && isHTMLElement(tabbableReturnElement) && // If the focus moved somewhere else after mount, avoid returning focus
// since it likely entered a different element which should be
// respected: https://github.com/floating-ui/floating-ui/issues/2607
(!hasExplicitReturnFocus && tabbableReturnElement !== activeEl && activeEl !== doc.body ? isFocusInsideFloatingTree : true)) {
tabbableReturnElement.focus({
preventScroll: true
});
}
preventReturnFocusRef.current = false;
});
};
}, [disabled2, floating, floatingFocusElement, returnFocusRef, openInteractionTypeRef, events, tree, domReference, getNodeId, getResolvedInsideElements]);
useIsoLayoutEffect(() => {
if (!parts_exports.engine.webkit || open || !floating) {
return;
}
const activeEl = activeElement(ownerDocument(floating));
if (!isHTMLElement(activeEl) || !isTypeableElement(activeEl)) {
return;
}
if (contains(floating, activeEl)) {
activeEl.blur();
}
}, [open, floating]);
useIsoLayoutEffect(() => {
if (disabled2 || !portalContext) {
return void 0;
}
portalContext.setFocusManagerState({
modal,
closeOnFocusOut,
open,
onOpenChange: store2.setOpen,
domReference
});
return () => {
portalContext.setFocusManagerState(null);
};
}, [disabled2, portalContext, modal, open, store2, closeOnFocusOut, domReference]);
useIsoLayoutEffect(() => {
if (disabled2 || !floatingFocusElement) {
return void 0;
}
handleTabIndex(floatingFocusElement);
return () => {
queueMicrotask(clearDisconnectedPreviouslyFocusedElements);
};
}, [disabled2, floatingFocusElement]);
const shouldRenderGuards = !disabled2 && (modal ? !isUntrappedTypeableCombobox : true) && (isInsidePortal || modal);
return /* @__PURE__ */ (0, import_jsx_runtime157.jsxs)(React29.Fragment, {
children: [shouldRenderGuards && /* @__PURE__ */ (0, import_jsx_runtime157.jsx)(FocusGuard, {
"data-type": "inside",
ref: mergedBeforeGuardRef,
onFocus: (event) => {
if (modal) {
const els = getTabbableContent();
enqueueFocus(els[els.length - 1]);
} else if (portalContext?.portalNode) {
preventReturnFocusRef.current = false;
if (isOutsideEvent(event, portalContext.portalNode)) {
const nextTabbable = getNextTabbable(domReference);
nextTabbable?.focus();
} else {
resolveRef(previousFocusableElement ?? portalContext.beforeOutsideRef)?.focus();
}
}
}
}), children, shouldRenderGuards && /* @__PURE__ */ (0, import_jsx_runtime157.jsx)(FocusGuard, {
"data-type": "inside",
ref: mergedAfterGuardRef,
onFocus: (event) => {
if (modal) {
enqueueFocus(getTabbableContent()[0]);
} else if (portalContext?.portalNode) {
if (closeOnFocusOut) {
preventReturnFocusRef.current = true;
}
if (isOutsideEvent(event, portalContext.portalNode)) {
const prevTabbable = getPreviousTabbable(domReference);
prevTabbable?.focus();
} else {
resolveRef(nextFocusableElement ?? portalContext.afterOutsideRef)?.focus();
}
}
}
})]
});
}
// node_modules/@base-ui/react/floating-ui-react/hooks/useClick.mjs
var React30 = __toESM(require_react(), 1);
function useClick(context, props = {}) {
const {
enabled = true,
event: eventOption = "click",
toggle = true,
ignoreMouse = false,
stickIfOpen = true,
touchOpenDelay = 0,
reason = reason_parts_exports.triggerPress
} = props;
const store2 = "rootStore" in context ? context.rootStore : context;
const dataRef = store2.context.dataRef;
const pointerTypeRef = React30.useRef(void 0);
const frame = useAnimationFrame();
const touchOpenTimeout = useTimeout();
const reference = React30.useMemo(() => {
function setOpenWithTouchDelay(nextOpen, nativeEvent, target, pointerType) {
const details = createChangeEventDetails(reason, nativeEvent, target);
if (nextOpen && pointerType === "touch" && touchOpenDelay > 0) {
touchOpenTimeout.start(touchOpenDelay, () => {
store2.setOpen(true, details);
});
} else {
store2.setOpen(nextOpen, details);
}
}
function getNextOpen(open, currentTarget, isClickLikeOpenEvent2) {
const openEvent = dataRef.current.openEvent;
const hasClickedOnInactiveTrigger = store2.select("domReferenceElement") !== currentTarget;
if (open && hasClickedOnInactiveTrigger) {
return true;
}
if (!open) {
return true;
}
if (!toggle) {
return true;
}
if (openEvent && stickIfOpen) {
return !isClickLikeOpenEvent2(openEvent.type);
}
return false;
}
return {
onPointerDown(event) {
pointerTypeRef.current = event.pointerType;
},
onMouseDown(event) {
const pointerType = pointerTypeRef.current;
const nativeEvent = event.nativeEvent;
const open = store2.select("open");
if (event.button !== 0 || eventOption === "click" || isMouseLikePointerType(pointerType, true) && ignoreMouse) {
return;
}
const nextOpen = getNextOpen(open, event.currentTarget, (openEventType) => openEventType === "click" || openEventType === "mousedown");
const target = getTarget(nativeEvent);
if (isTypeableElement(target)) {
setOpenWithTouchDelay(nextOpen, nativeEvent, target, pointerType);
return;
}
const eventCurrentTarget = event.currentTarget;
frame.request(() => {
setOpenWithTouchDelay(nextOpen, nativeEvent, eventCurrentTarget, pointerType);
});
},
onClick(event) {
if (eventOption === "mousedown-only") {
return;
}
const pointerType = pointerTypeRef.current;
if (eventOption === "mousedown" && pointerType) {
pointerTypeRef.current = void 0;
return;
}
if (isMouseLikePointerType(pointerType, true) && ignoreMouse) {
return;
}
const open = store2.select("open");
const nextOpen = getNextOpen(open, event.currentTarget, (openEventType) => openEventType === "click" || openEventType === "mousedown" || openEventType === "keydown" || openEventType === "keyup");
setOpenWithTouchDelay(nextOpen, event.nativeEvent, event.currentTarget, pointerType);
},
onKeyDown() {
pointerTypeRef.current = void 0;
}
};
}, [dataRef, eventOption, ignoreMouse, reason, store2, stickIfOpen, toggle, frame, touchOpenTimeout, touchOpenDelay]);
return React30.useMemo(() => enabled ? {
reference
} : EMPTY_OBJECT, [enabled, reference]);
}
// node_modules/@base-ui/react/floating-ui-react/hooks/useClientPoint.mjs
var React31 = __toESM(require_react(), 1);
function createVirtualElement(domElement, data) {
let offsetX = null;
let offsetY = null;
let isAutoUpdateEvent = false;
return {
contextElement: domElement || void 0,
getBoundingClientRect() {
const domRect = domElement?.getBoundingClientRect() || {
width: 0,
height: 0,
x: 0,
y: 0
};
const isXAxis = data.axis === "x" || data.axis === "both";
const isYAxis = data.axis === "y" || data.axis === "both";
const canTrackCursorOnAutoUpdate = ["mouseenter", "mousemove"].includes(data.dataRef.current.openEvent?.type || "") && data.pointerType !== "touch";
let width = domRect.width;
let height = domRect.height;
let x2 = domRect.x;
let y2 = domRect.y;
if (offsetX == null && data.x && isXAxis) {
offsetX = domRect.x - data.x;
}
if (offsetY == null && data.y && isYAxis) {
offsetY = domRect.y - data.y;
}
x2 -= offsetX || 0;
y2 -= offsetY || 0;
width = 0;
height = 0;
if (!isAutoUpdateEvent || canTrackCursorOnAutoUpdate) {
width = data.axis === "y" ? domRect.width : 0;
height = data.axis === "x" ? domRect.height : 0;
x2 = isXAxis && data.x != null ? data.x : x2;
y2 = isYAxis && data.y != null ? data.y : y2;
} else if (isAutoUpdateEvent && !canTrackCursorOnAutoUpdate) {
height = data.axis === "x" ? domRect.height : height;
width = data.axis === "y" ? domRect.width : width;
}
isAutoUpdateEvent = true;
return {
width,
height,
x: x2,
y: y2,
top: y2,
right: x2 + width,
bottom: y2 + height,
left: x2
};
}
};
}
function isMouseBasedEvent(event) {
return event != null && event.clientX != null;
}
function useClientPoint(context, props = {}) {
const {
enabled = true,
axis = "both"
} = props;
const store2 = "rootStore" in context ? context.rootStore : context;
const open = store2.useState("open");
const floating = store2.useState("floatingElement");
const domReference = store2.useState("domReferenceElement");
const dataRef = store2.context.dataRef;
const initialRef = React31.useRef(false);
const cleanupListenerRef = React31.useRef(null);
const [pointerType, setPointerType] = React31.useState();
const [reactive, setReactive] = React31.useState([]);
const resetReference = useStableCallback((reference2) => {
store2.set("positionReference", reference2);
});
const setReference = useStableCallback((newX, newY, referenceElement) => {
if (initialRef.current) {
return;
}
if (dataRef.current.openEvent && !isMouseBasedEvent(dataRef.current.openEvent)) {
return;
}
store2.set("positionReference", createVirtualElement(referenceElement ?? domReference, {
x: newX,
y: newY,
axis,
dataRef,
pointerType
}));
});
const handleReferenceEnterOrMove = useStableCallback((event) => {
if (!open) {
setReference(event.clientX, event.clientY, event.currentTarget);
} else if (!cleanupListenerRef.current) {
setReference(event.clientX, event.clientY, event.currentTarget);
setReactive([]);
}
});
const openCheck = isMouseLikePointerType(pointerType) ? floating : open;
React31.useEffect(() => {
if (!enabled) {
resetReference(domReference);
return void 0;
}
if (!openCheck) {
return void 0;
}
function cleanupListener() {
cleanupListenerRef.current?.();
cleanupListenerRef.current = null;
}
const win = getWindow(floating);
function handleMouseMove(event) {
const target = getTarget(event);
if (!contains(floating, target)) {
setReference(event.clientX, event.clientY);
} else {
cleanupListener();
}
}
if (!dataRef.current.openEvent || isMouseBasedEvent(dataRef.current.openEvent)) {
cleanupListenerRef.current = addEventListener(win, "mousemove", handleMouseMove);
} else {
resetReference(domReference);
}
return cleanupListener;
}, [openCheck, enabled, floating, dataRef, domReference, store2, setReference, resetReference, reactive]);
React31.useEffect(() => () => {
store2.set("positionReference", null);
}, [store2]);
React31.useEffect(() => {
if (enabled && !floating) {
initialRef.current = false;
}
}, [enabled, floating]);
React31.useEffect(() => {
if (!enabled && open) {
initialRef.current = true;
}
}, [enabled, open]);
const reference = React31.useMemo(() => {
function setPointerTypeRef(event) {
setPointerType(event.pointerType);
}
return {
onPointerDown: setPointerTypeRef,
onPointerEnter: setPointerTypeRef,
onMouseMove: handleReferenceEnterOrMove,
onMouseEnter: handleReferenceEnterOrMove
};
}, [handleReferenceEnterOrMove]);
return React31.useMemo(() => enabled ? {
reference,
trigger: reference
} : {}, [enabled, reference]);
}
// node_modules/@base-ui/react/floating-ui-react/hooks/useDismiss.mjs
var React32 = __toESM(require_react(), 1);
function alwaysFalse() {
return false;
}
function normalizeProp(normalizable) {
return {
escapeKey: typeof normalizable === "boolean" ? normalizable : normalizable?.escapeKey ?? false,
outsidePress: typeof normalizable === "boolean" ? normalizable : normalizable?.outsidePress ?? true
};
}
function useDismiss(context, props = {}) {
const {
enabled = true,
escapeKey: escapeKey2 = true,
outsidePress: outsidePressProp = true,
outsidePressEvent = "sloppy",
referencePress = alwaysFalse,
bubbles,
externalTree
} = props;
const store2 = "rootStore" in context ? context.rootStore : context;
const open = store2.useState("open");
const floatingElement = store2.useState("floatingElement");
const {
dataRef
} = store2.context;
const tree = useFloatingTree(externalTree);
const outsidePressFn = useStableCallback(typeof outsidePressProp === "function" ? outsidePressProp : () => false);
const outsidePress2 = typeof outsidePressProp === "function" ? outsidePressFn : outsidePressProp;
const outsidePressEnabled = outsidePress2 !== false;
const getOutsidePressEventProp = useStableCallback(() => outsidePressEvent);
const {
escapeKey: escapeKeyBubbles,
outsidePress: outsidePressBubbles
} = normalizeProp(bubbles);
const pressStartedInsideRef = React32.useRef(false);
const pressStartPreventedRef = React32.useRef(false);
const suppressNextOutsideClickRef = React32.useRef(false);
const isComposingRef = React32.useRef(false);
const currentPointerTypeRef = React32.useRef("");
const touchStateRef = React32.useRef(null);
const cancelDismissOnEndTimeout = useTimeout();
const clearInsideReactTreeTimeout = useTimeout();
const clearInsideReactTree = useStableCallback(() => {
clearInsideReactTreeTimeout.clear();
dataRef.current.insideReactTree = false;
});
const hasBlockingChild = useStableCallback((bubbleKey) => {
const nodeId = dataRef.current.floatingContext?.nodeId;
const children = tree ? getNodeChildren(tree.nodesRef.current, nodeId) : [];
return children.some((child) => child.context?.open && !child.context.dataRef.current[bubbleKey]);
});
const isEventWithinOwnElements = useStableCallback((event) => {
return isEventTargetWithin(event, store2.select("floatingElement")) || isEventTargetWithin(event, store2.select("domReferenceElement"));
});
const closeOnReferencePress = useStableCallback((event) => {
if (!referencePress()) {
return;
}
store2.setOpen(false, createChangeEventDetails(reason_parts_exports.triggerPress, event.nativeEvent));
});
const closeOnEscapeKeyDown = useStableCallback((event) => {
if (!open || !enabled || !escapeKey2 || event.key !== "Escape") {
return;
}
if (isComposingRef.current) {
return;
}
if (!escapeKeyBubbles && hasBlockingChild("__escapeKeyBubbles")) {
return;
}
const native = isReactEvent(event) ? event.nativeEvent : event;
const eventDetails = createChangeEventDetails(reason_parts_exports.escapeKey, native);
store2.setOpen(false, eventDetails);
if (!eventDetails.isCanceled) {
event.preventDefault();
}
if (!escapeKeyBubbles && !eventDetails.isPropagationAllowed) {
event.stopPropagation();
}
});
const markInsideReactTree = useStableCallback(() => {
dataRef.current.insideReactTree = true;
clearInsideReactTreeTimeout.start(0, clearInsideReactTree);
});
const markPressStartedInsideReactTree = useStableCallback((event) => {
if (!open || !enabled || event.button !== 0) {
return;
}
const target = getTarget(event.nativeEvent);
if (!contains(store2.select("floatingElement"), target)) {
return;
}
if (!pressStartedInsideRef.current) {
pressStartedInsideRef.current = true;
pressStartPreventedRef.current = false;
}
});
const markInsidePressStartPrevented = useStableCallback((event) => {
if (!open || !enabled) {
return;
}
if (!(event.defaultPrevented || event.nativeEvent.defaultPrevented)) {
return;
}
if (pressStartedInsideRef.current) {
pressStartPreventedRef.current = true;
}
});
React32.useEffect(() => {
if (!open || !enabled) {
return void 0;
}
dataRef.current.__escapeKeyBubbles = escapeKeyBubbles;
dataRef.current.__outsidePressBubbles = outsidePressBubbles;
const compositionTimeout = new Timeout();
const preventedPressSuppressionTimeout = new Timeout();
function handleCompositionStart() {
compositionTimeout.clear();
isComposingRef.current = true;
}
function handleCompositionEnd() {
compositionTimeout.start(
// 0ms or 1ms don't work in Safari. 5ms appears to consistently work.
// Only apply to WebKit for the test to remain 0ms.
parts_exports.engine.webkit ? 5 : 0,
() => {
isComposingRef.current = false;
}
);
}
function suppressImmediateOutsideClickAfterPreventedStart() {
suppressNextOutsideClickRef.current = true;
preventedPressSuppressionTimeout.start(0, () => {
suppressNextOutsideClickRef.current = false;
});
}
function resetPressStartState() {
pressStartedInsideRef.current = false;
pressStartPreventedRef.current = false;
}
function getOutsidePressEvent() {
const type = currentPointerTypeRef.current;
const computedType = type === "pen" || !type ? "mouse" : type;
const outsidePressEventValue = getOutsidePressEventProp();
const resolved = typeof outsidePressEventValue === "function" ? outsidePressEventValue() : outsidePressEventValue;
if (typeof resolved === "string") {
return resolved;
}
return resolved[computedType];
}
function shouldIgnoreEvent(event) {
const computedOutsidePressEvent = getOutsidePressEvent();
return computedOutsidePressEvent === "intentional" && event.type !== "click" || computedOutsidePressEvent === "sloppy" && event.type === "click";
}
function isEventWithinFloatingTree(event) {
const nodeId = dataRef.current.floatingContext?.nodeId;
const targetIsInsideChildren = tree && getNodeChildren(tree.nodesRef.current, nodeId).some((node) => isEventTargetWithin(event, node.context?.elements.floating));
return isEventWithinOwnElements(event) || targetIsInsideChildren;
}
function closeOnPressOutside(event) {
if (shouldIgnoreEvent(event)) {
if (event.type !== "click" && !isEventWithinOwnElements(event)) {
preventedPressSuppressionTimeout.clear();
suppressNextOutsideClickRef.current = false;
}
clearInsideReactTree();
return;
}
if (dataRef.current.insideReactTree) {
clearInsideReactTree();
return;
}
const target = getTarget(event);
const inertSelector = `[${createAttribute("inert")}]`;
const targetRoot = isElement(target) ? target.getRootNode() : null;
const markers = Array.from((isShadowRoot(targetRoot) ? targetRoot : ownerDocument(store2.select("floatingElement"))).querySelectorAll(inertSelector));
const triggers = store2.context.triggerElements;
if (target && (triggers.hasElement(target) || triggers.hasMatchingElement((trigger) => contains(trigger, target)))) {
return;
}
let targetRootAncestor = isElement(target) ? target : null;
while (targetRootAncestor && !isLastTraversableNode(targetRootAncestor)) {
const nextParent = getParentNode(targetRootAncestor);
if (isLastTraversableNode(nextParent) || !isElement(nextParent)) {
break;
}
targetRootAncestor = nextParent;
}
if (markers.length && isElement(target) && !isRootElement(target) && // Clicked on a direct ancestor (e.g. FloatingOverlay).
!contains(target, store2.select("floatingElement")) && // If the target root element contains none of the markers, then the
// element was injected after the floating element rendered.
markers.every((marker) => !contains(targetRootAncestor, marker))) {
return;
}
if (isHTMLElement(target) && !("touches" in event)) {
const lastTraversableNode = isLastTraversableNode(target);
const style = getComputedStyle2(target);
const scrollRe = /auto|scroll/;
const isScrollableX = lastTraversableNode || scrollRe.test(style.overflowX);
const isScrollableY = lastTraversableNode || scrollRe.test(style.overflowY);
const canScrollX = isScrollableX && target.clientWidth > 0 && target.scrollWidth > target.clientWidth;
const canScrollY = isScrollableY && target.clientHeight > 0 && target.scrollHeight > target.clientHeight;
const isRTL18 = style.direction === "rtl";
const pressedVerticalScrollbar = canScrollY && (isRTL18 ? event.offsetX <= target.offsetWidth - target.clientWidth : event.offsetX > target.clientWidth);
const pressedHorizontalScrollbar = canScrollX && event.offsetY > target.clientHeight;
if (pressedVerticalScrollbar || pressedHorizontalScrollbar) {
return;
}
}
if (isEventWithinFloatingTree(event)) {
return;
}
if (getOutsidePressEvent() === "intentional" && suppressNextOutsideClickRef.current) {
preventedPressSuppressionTimeout.clear();
suppressNextOutsideClickRef.current = false;
return;
}
if (typeof outsidePress2 === "function" && !outsidePress2(event)) {
return;
}
if (hasBlockingChild("__outsidePressBubbles")) {
return;
}
store2.setOpen(false, createChangeEventDetails(reason_parts_exports.outsidePress, event));
clearInsideReactTree();
}
function handlePointerDown(event) {
if (getOutsidePressEvent() !== "sloppy" || event.pointerType === "touch" || !store2.select("open") || !enabled || isEventWithinOwnElements(event)) {
return;
}
closeOnPressOutside(event);
}
function handleTouchStart(event) {
if (getOutsidePressEvent() !== "sloppy" || !store2.select("open") || !enabled || isEventWithinOwnElements(event)) {
return;
}
const touch = event.touches[0];
if (touch) {
touchStateRef.current = {
startTime: Date.now(),
startX: touch.clientX,
startY: touch.clientY,
dismissOnTouchEnd: false,
dismissOnMouseDown: true
};
cancelDismissOnEndTimeout.start(1e3, () => {
if (touchStateRef.current) {
touchStateRef.current.dismissOnTouchEnd = false;
touchStateRef.current.dismissOnMouseDown = false;
}
});
}
}
function addTargetEventListenerOnce(event, listener) {
const target = getTarget(event);
if (!target) {
return;
}
const unsubscribe2 = addEventListener(target, event.type, () => {
listener(event);
unsubscribe2();
});
}
function handleTouchStartCapture(event) {
currentPointerTypeRef.current = "touch";
addTargetEventListenerOnce(event, handleTouchStart);
}
function closeOnPressOutsideCapture(event) {
cancelDismissOnEndTimeout.clear();
if (event.type === "pointerdown") {
currentPointerTypeRef.current = event.pointerType;
}
if (event.type === "mousedown" && touchStateRef.current && !touchStateRef.current.dismissOnMouseDown) {
return;
}
addTargetEventListenerOnce(event, (targetEvent) => {
if (targetEvent.type === "pointerdown") {
handlePointerDown(targetEvent);
} else {
closeOnPressOutside(targetEvent);
}
});
}
function handlePressEndCapture(event) {
if (!pressStartedInsideRef.current) {
return;
}
const pressStartedInsideDefaultPrevented = pressStartPreventedRef.current;
resetPressStartState();
if (getOutsidePressEvent() !== "intentional") {
return;
}
if (event.type === "pointercancel") {
if (pressStartedInsideDefaultPrevented) {
suppressImmediateOutsideClickAfterPreventedStart();
}
return;
}
if (isEventWithinFloatingTree(event)) {
return;
}
if (pressStartedInsideDefaultPrevented) {
suppressImmediateOutsideClickAfterPreventedStart();
return;
}
if (typeof outsidePress2 === "function" && !outsidePress2(event)) {
return;
}
preventedPressSuppressionTimeout.clear();
suppressNextOutsideClickRef.current = true;
clearInsideReactTree();
}
function handleTouchMove(event) {
if (getOutsidePressEvent() !== "sloppy" || !touchStateRef.current || isEventWithinOwnElements(event)) {
return;
}
const touch = event.touches[0];
if (!touch) {
return;
}
const deltaX = Math.abs(touch.clientX - touchStateRef.current.startX);
const deltaY = Math.abs(touch.clientY - touchStateRef.current.startY);
const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
if (distance > 5) {
touchStateRef.current.dismissOnTouchEnd = true;
}
if (distance > 10) {
closeOnPressOutside(event);
cancelDismissOnEndTimeout.clear();
touchStateRef.current = null;
}
}
function handleTouchMoveCapture(event) {
addTargetEventListenerOnce(event, handleTouchMove);
}
function handleTouchEnd(event) {
if (getOutsidePressEvent() !== "sloppy" || !touchStateRef.current || isEventWithinOwnElements(event)) {
return;
}
if (touchStateRef.current.dismissOnTouchEnd) {
closeOnPressOutside(event);
}
cancelDismissOnEndTimeout.clear();
touchStateRef.current = null;
}
function handleTouchEndCapture(event) {
addTargetEventListenerOnce(event, handleTouchEnd);
}
const doc = ownerDocument(floatingElement);
const unsubscribe = mergeCleanups(escapeKey2 && mergeCleanups(addEventListener(doc, "keydown", closeOnEscapeKeyDown), addEventListener(doc, "compositionstart", handleCompositionStart), addEventListener(doc, "compositionend", handleCompositionEnd)), outsidePressEnabled && mergeCleanups(addEventListener(doc, "click", closeOnPressOutsideCapture, true), addEventListener(doc, "pointerdown", closeOnPressOutsideCapture, true), addEventListener(doc, "pointerup", handlePressEndCapture, true), addEventListener(doc, "pointercancel", handlePressEndCapture, true), addEventListener(doc, "mousedown", closeOnPressOutsideCapture, true), addEventListener(doc, "mouseup", handlePressEndCapture, true), addEventListener(doc, "touchstart", handleTouchStartCapture, true), addEventListener(doc, "touchmove", handleTouchMoveCapture, true), addEventListener(doc, "touchend", handleTouchEndCapture, true)));
return () => {
unsubscribe();
compositionTimeout.clear();
preventedPressSuppressionTimeout.clear();
resetPressStartState();
suppressNextOutsideClickRef.current = false;
};
}, [dataRef, floatingElement, escapeKey2, outsidePressEnabled, outsidePress2, open, enabled, escapeKeyBubbles, outsidePressBubbles, closeOnEscapeKeyDown, clearInsideReactTree, getOutsidePressEventProp, hasBlockingChild, isEventWithinOwnElements, tree, store2, cancelDismissOnEndTimeout]);
React32.useEffect(clearInsideReactTree, [outsidePress2, clearInsideReactTree]);
const reference = React32.useMemo(() => ({
onKeyDown: closeOnEscapeKeyDown,
onPointerDown: closeOnReferencePress,
onClick: closeOnReferencePress
}), [closeOnEscapeKeyDown, closeOnReferencePress]);
const floating = React32.useMemo(() => ({
onKeyDown: closeOnEscapeKeyDown,
// `onMouseDown` may be blocked if `event.preventDefault()` is called in
// `onPointerDown`, such as with <NumberField.ScrubArea>.
// See https://github.com/mui/base-ui/pull/3379
onPointerDown: markInsidePressStartPrevented,
onMouseDown: markInsidePressStartPrevented,
onClickCapture: markInsideReactTree,
onMouseDownCapture(event) {
markInsideReactTree();
markPressStartedInsideReactTree(event);
},
onPointerDownCapture(event) {
markInsideReactTree();
markPressStartedInsideReactTree(event);
},
onMouseUpCapture: markInsideReactTree,
onTouchEndCapture: markInsideReactTree,
onTouchMoveCapture: markInsideReactTree
}), [closeOnEscapeKeyDown, markInsideReactTree, markPressStartedInsideReactTree, markInsidePressStartPrevented]);
return React32.useMemo(() => enabled ? {
reference,
floating,
trigger: reference
} : {}, [enabled, reference, floating]);
}
// node_modules/@base-ui/react/floating-ui-react/hooks/useFloating.mjs
var React39 = __toESM(require_react(), 1);
// node_modules/@floating-ui/core/dist/floating-ui.core.mjs
function computeCoordsFromPlacement(_ref, placement, rtl) {
let {
reference,
floating
} = _ref;
const sideAxis = getSideAxis(placement);
const alignmentAxis = getAlignmentAxis(placement);
const alignLength = getAxisLength(alignmentAxis);
const side = getSide(placement);
const isVertical = sideAxis === "y";
const commonX = reference.x + reference.width / 2 - floating.width / 2;
const commonY = reference.y + reference.height / 2 - floating.height / 2;
const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2;
let coords;
switch (side) {
case "top":
coords = {
x: commonX,
y: reference.y - floating.height
};
break;
case "bottom":
coords = {
x: commonX,
y: reference.y + reference.height
};
break;
case "right":
coords = {
x: reference.x + reference.width,
y: commonY
};
break;
case "left":
coords = {
x: reference.x - floating.width,
y: commonY
};
break;
default:
coords = {
x: reference.x,
y: reference.y
};
}
switch (getAlignment(placement)) {
case "start":
coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1);
break;
case "end":
coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1);
break;
}
return coords;
}
async function detectOverflow(state, options) {
var _await$platform$isEle;
if (options === void 0) {
options = {};
}
const {
x: x2,
y: y2,
platform: platform3,
rects,
elements,
strategy
} = state;
const {
boundary = "clippingAncestors",
rootBoundary = "viewport",
elementContext = "floating",
altBoundary = false,
padding = 0
} = evaluate(options, state);
const paddingObject = getPaddingObject(padding);
const altContext = elementContext === "floating" ? "reference" : "floating";
const element = elements[altBoundary ? altContext : elementContext];
const clippingClientRect = rectToClientRect(await platform3.getClippingRect({
element: ((_await$platform$isEle = await (platform3.isElement == null ? void 0 : platform3.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || await (platform3.getDocumentElement == null ? void 0 : platform3.getDocumentElement(elements.floating)),
boundary,
rootBoundary,
strategy
}));
const rect = elementContext === "floating" ? {
x: x2,
y: y2,
width: rects.floating.width,
height: rects.floating.height
} : rects.reference;
const offsetParent = await (platform3.getOffsetParent == null ? void 0 : platform3.getOffsetParent(elements.floating));
const offsetScale = await (platform3.isElement == null ? void 0 : platform3.isElement(offsetParent)) ? await (platform3.getScale == null ? void 0 : platform3.getScale(offsetParent)) || {
x: 1,
y: 1
} : {
x: 1,
y: 1
};
const elementClientRect = rectToClientRect(platform3.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform3.convertOffsetParentRelativeRectToViewportRelativeRect({
elements,
rect,
offsetParent,
strategy
}) : rect);
return {
top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y,
bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y,
left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x,
right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x
};
}
var MAX_RESET_COUNT = 50;
var computePosition = async (reference, floating, config2) => {
const {
placement = "bottom",
strategy = "absolute",
middleware = [],
platform: platform3
} = config2;
const platformWithDetectOverflow = platform3.detectOverflow ? platform3 : {
...platform3,
detectOverflow
};
const rtl = await (platform3.isRTL == null ? void 0 : platform3.isRTL(floating));
let rects = await platform3.getElementRects({
reference,
floating,
strategy
});
let {
x: x2,
y: y2
} = computeCoordsFromPlacement(rects, placement, rtl);
let statefulPlacement = placement;
let resetCount = 0;
const middlewareData = {};
for (let i2 = 0; i2 < middleware.length; i2++) {
const currentMiddleware = middleware[i2];
if (!currentMiddleware) {
continue;
}
const {
name,
fn
} = currentMiddleware;
const {
x: nextX,
y: nextY,
data,
reset
} = await fn({
x: x2,
y: y2,
initialPlacement: placement,
placement: statefulPlacement,
strategy,
middlewareData,
rects,
platform: platformWithDetectOverflow,
elements: {
reference,
floating
}
});
x2 = nextX != null ? nextX : x2;
y2 = nextY != null ? nextY : y2;
middlewareData[name] = {
...middlewareData[name],
...data
};
if (reset && resetCount < MAX_RESET_COUNT) {
resetCount++;
if (typeof reset === "object") {
if (reset.placement) {
statefulPlacement = reset.placement;
}
if (reset.rects) {
rects = reset.rects === true ? await platform3.getElementRects({
reference,
floating,
strategy
}) : reset.rects;
}
({
x: x2,
y: y2
} = computeCoordsFromPlacement(rects, statefulPlacement, rtl));
}
i2 = -1;
}
}
return {
x: x2,
y: y2,
placement: statefulPlacement,
strategy,
middlewareData
};
};
var flip = function(options) {
if (options === void 0) {
options = {};
}
return {
name: "flip",
options,
async fn(state) {
var _middlewareData$arrow, _middlewareData$flip;
const {
placement,
middlewareData,
rects,
initialPlacement,
platform: platform3,
elements
} = state;
const {
mainAxis: checkMainAxis = true,
crossAxis: checkCrossAxis = true,
fallbackPlacements: specifiedFallbackPlacements,
fallbackStrategy = "bestFit",
fallbackAxisSideDirection = "none",
flipAlignment = true,
...detectOverflowOptions
} = evaluate(options, state);
if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
return {};
}
const side = getSide(placement);
const initialSideAxis = getSideAxis(initialPlacement);
const isBasePlacement = getSide(initialPlacement) === initialPlacement;
const rtl = await (platform3.isRTL == null ? void 0 : platform3.isRTL(elements.floating));
const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement));
const hasFallbackAxisSideDirection = fallbackAxisSideDirection !== "none";
if (!specifiedFallbackPlacements && hasFallbackAxisSideDirection) {
fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl));
}
const placements2 = [initialPlacement, ...fallbackPlacements];
const overflow = await platform3.detectOverflow(state, detectOverflowOptions);
const overflows = [];
let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || [];
if (checkMainAxis) {
overflows.push(overflow[side]);
}
if (checkCrossAxis) {
const sides2 = getAlignmentSides(placement, rects, rtl);
overflows.push(overflow[sides2[0]], overflow[sides2[1]]);
}
overflowsData = [...overflowsData, {
placement,
overflows
}];
if (!overflows.every((side2) => side2 <= 0)) {
var _middlewareData$flip2, _overflowsData$filter;
const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1;
const nextPlacement = placements2[nextIndex];
if (nextPlacement) {
const ignoreCrossAxisOverflow = checkCrossAxis === "alignment" ? initialSideAxis !== getSideAxis(nextPlacement) : false;
if (!ignoreCrossAxisOverflow || // We leave the current main axis only if every placement on that axis
// overflows the main axis.
overflowsData.every((d2) => getSideAxis(d2.placement) === initialSideAxis ? d2.overflows[0] > 0 : true)) {
return {
data: {
index: nextIndex,
overflows: overflowsData
},
reset: {
placement: nextPlacement
}
};
}
}
let resetPlacement = (_overflowsData$filter = overflowsData.filter((d2) => d2.overflows[0] <= 0).sort((a2, b2) => a2.overflows[1] - b2.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement;
if (!resetPlacement) {
switch (fallbackStrategy) {
case "bestFit": {
var _overflowsData$filter2;
const placement2 = (_overflowsData$filter2 = overflowsData.filter((d2) => {
if (hasFallbackAxisSideDirection) {
const currentSideAxis = getSideAxis(d2.placement);
return currentSideAxis === initialSideAxis || // Create a bias to the `y` side axis due to horizontal
// reading directions favoring greater width.
currentSideAxis === "y";
}
return true;
}).map((d2) => [d2.placement, d2.overflows.filter((overflow2) => overflow2 > 0).reduce((acc, overflow2) => acc + overflow2, 0)]).sort((a2, b2) => a2[1] - b2[1])[0]) == null ? void 0 : _overflowsData$filter2[0];
if (placement2) {
resetPlacement = placement2;
}
break;
}
case "initialPlacement":
resetPlacement = initialPlacement;
break;
}
}
if (placement !== resetPlacement) {
return {
reset: {
placement: resetPlacement
}
};
}
}
return {};
}
};
};
function getSideOffsets(overflow, rect) {
return {
top: overflow.top - rect.height,
right: overflow.right - rect.width,
bottom: overflow.bottom - rect.height,
left: overflow.left - rect.width
};
}
function isAnySideFullyClipped(overflow) {
return sides.some((side) => overflow[side] >= 0);
}
var hide = function(options) {
if (options === void 0) {
options = {};
}
return {
name: "hide",
options,
async fn(state) {
const {
rects,
platform: platform3
} = state;
const {
strategy = "referenceHidden",
...detectOverflowOptions
} = evaluate(options, state);
switch (strategy) {
case "referenceHidden": {
const overflow = await platform3.detectOverflow(state, {
...detectOverflowOptions,
elementContext: "reference"
});
const offsets = getSideOffsets(overflow, rects.reference);
return {
data: {
referenceHiddenOffsets: offsets,
referenceHidden: isAnySideFullyClipped(offsets)
}
};
}
case "escaped": {
const overflow = await platform3.detectOverflow(state, {
...detectOverflowOptions,
altBoundary: true
});
const offsets = getSideOffsets(overflow, rects.floating);
return {
data: {
escapedOffsets: offsets,
escaped: isAnySideFullyClipped(offsets)
}
};
}
default: {
return {};
}
}
}
};
};
var originSides = /* @__PURE__ */ new Set(["left", "top"]);
async function convertValueToCoords(state, options) {
const {
placement,
platform: platform3,
elements
} = state;
const rtl = await (platform3.isRTL == null ? void 0 : platform3.isRTL(elements.floating));
const side = getSide(placement);
const alignment = getAlignment(placement);
const isVertical = getSideAxis(placement) === "y";
const mainAxisMulti = originSides.has(side) ? -1 : 1;
const crossAxisMulti = rtl && isVertical ? -1 : 1;
const rawValue = evaluate(options, state);
let {
mainAxis,
crossAxis,
alignmentAxis
} = typeof rawValue === "number" ? {
mainAxis: rawValue,
crossAxis: 0,
alignmentAxis: null
} : {
mainAxis: rawValue.mainAxis || 0,
crossAxis: rawValue.crossAxis || 0,
alignmentAxis: rawValue.alignmentAxis
};
if (alignment && typeof alignmentAxis === "number") {
crossAxis = alignment === "end" ? alignmentAxis * -1 : alignmentAxis;
}
return isVertical ? {
x: crossAxis * crossAxisMulti,
y: mainAxis * mainAxisMulti
} : {
x: mainAxis * mainAxisMulti,
y: crossAxis * crossAxisMulti
};
}
var offset = function(options) {
if (options === void 0) {
options = 0;
}
return {
name: "offset",
options,
async fn(state) {
var _middlewareData$offse, _middlewareData$arrow;
const {
x: x2,
y: y2,
placement,
middlewareData
} = state;
const diffCoords = await convertValueToCoords(state, options);
if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
return {};
}
return {
x: x2 + diffCoords.x,
y: y2 + diffCoords.y,
data: {
...diffCoords,
placement
}
};
}
};
};
var shift = function(options) {
if (options === void 0) {
options = {};
}
return {
name: "shift",
options,
async fn(state) {
const {
x: x2,
y: y2,
placement,
platform: platform3
} = state;
const {
mainAxis: checkMainAxis = true,
crossAxis: checkCrossAxis = false,
limiter = {
fn: (_ref) => {
let {
x: x3,
y: y3
} = _ref;
return {
x: x3,
y: y3
};
}
},
...detectOverflowOptions
} = evaluate(options, state);
const coords = {
x: x2,
y: y2
};
const overflow = await platform3.detectOverflow(state, detectOverflowOptions);
const crossAxis = getSideAxis(getSide(placement));
const mainAxis = getOppositeAxis(crossAxis);
let mainAxisCoord = coords[mainAxis];
let crossAxisCoord = coords[crossAxis];
if (checkMainAxis) {
const minSide = mainAxis === "y" ? "top" : "left";
const maxSide = mainAxis === "y" ? "bottom" : "right";
const min2 = mainAxisCoord + overflow[minSide];
const max2 = mainAxisCoord - overflow[maxSide];
mainAxisCoord = clamp(min2, mainAxisCoord, max2);
}
if (checkCrossAxis) {
const minSide = crossAxis === "y" ? "top" : "left";
const maxSide = crossAxis === "y" ? "bottom" : "right";
const min2 = crossAxisCoord + overflow[minSide];
const max2 = crossAxisCoord - overflow[maxSide];
crossAxisCoord = clamp(min2, crossAxisCoord, max2);
}
const limitedCoords = limiter.fn({
...state,
[mainAxis]: mainAxisCoord,
[crossAxis]: crossAxisCoord
});
return {
...limitedCoords,
data: {
x: limitedCoords.x - x2,
y: limitedCoords.y - y2,
enabled: {
[mainAxis]: checkMainAxis,
[crossAxis]: checkCrossAxis
}
}
};
}
};
};
var limitShift = function(options) {
if (options === void 0) {
options = {};
}
return {
options,
fn(state) {
const {
x: x2,
y: y2,
placement,
rects,
middlewareData
} = state;
const {
offset: offset4 = 0,
mainAxis: checkMainAxis = true,
crossAxis: checkCrossAxis = true
} = evaluate(options, state);
const coords = {
x: x2,
y: y2
};
const crossAxis = getSideAxis(placement);
const mainAxis = getOppositeAxis(crossAxis);
let mainAxisCoord = coords[mainAxis];
let crossAxisCoord = coords[crossAxis];
const rawOffset = evaluate(offset4, state);
const computedOffset = typeof rawOffset === "number" ? {
mainAxis: rawOffset,
crossAxis: 0
} : {
mainAxis: 0,
crossAxis: 0,
...rawOffset
};
if (checkMainAxis) {
const len = mainAxis === "y" ? "height" : "width";
const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis;
const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis;
if (mainAxisCoord < limitMin) {
mainAxisCoord = limitMin;
} else if (mainAxisCoord > limitMax) {
mainAxisCoord = limitMax;
}
}
if (checkCrossAxis) {
var _middlewareData$offse, _middlewareData$offse2;
const len = mainAxis === "y" ? "width" : "height";
const isOriginSide = originSides.has(getSide(placement));
const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis);
const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0);
if (crossAxisCoord < limitMin) {
crossAxisCoord = limitMin;
} else if (crossAxisCoord > limitMax) {
crossAxisCoord = limitMax;
}
}
return {
[mainAxis]: mainAxisCoord,
[crossAxis]: crossAxisCoord
};
}
};
};
var size = function(options) {
if (options === void 0) {
options = {};
}
return {
name: "size",
options,
async fn(state) {
var _state$middlewareData, _state$middlewareData2;
const {
placement,
rects,
platform: platform3,
elements
} = state;
const {
apply = () => {
},
...detectOverflowOptions
} = evaluate(options, state);
const overflow = await platform3.detectOverflow(state, detectOverflowOptions);
const side = getSide(placement);
const alignment = getAlignment(placement);
const isYAxis = getSideAxis(placement) === "y";
const {
width,
height
} = rects.floating;
let heightSide;
let widthSide;
if (side === "top" || side === "bottom") {
heightSide = side;
widthSide = alignment === (await (platform3.isRTL == null ? void 0 : platform3.isRTL(elements.floating)) ? "start" : "end") ? "left" : "right";
} else {
widthSide = side;
heightSide = alignment === "end" ? "top" : "bottom";
}
const maximumClippingHeight = height - overflow.top - overflow.bottom;
const maximumClippingWidth = width - overflow.left - overflow.right;
const overflowAvailableHeight = min(height - overflow[heightSide], maximumClippingHeight);
const overflowAvailableWidth = min(width - overflow[widthSide], maximumClippingWidth);
const noShift = !state.middlewareData.shift;
let availableHeight = overflowAvailableHeight;
let availableWidth = overflowAvailableWidth;
if ((_state$middlewareData = state.middlewareData.shift) != null && _state$middlewareData.enabled.x) {
availableWidth = maximumClippingWidth;
}
if ((_state$middlewareData2 = state.middlewareData.shift) != null && _state$middlewareData2.enabled.y) {
availableHeight = maximumClippingHeight;
}
if (noShift && !alignment) {
const xMin = max(overflow.left, 0);
const xMax = max(overflow.right, 0);
const yMin = max(overflow.top, 0);
const yMax = max(overflow.bottom, 0);
if (isYAxis) {
availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right));
} else {
availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom));
}
}
await apply({
...state,
availableWidth,
availableHeight
});
const nextDimensions = await platform3.getDimensions(elements.floating);
if (width !== nextDimensions.width || height !== nextDimensions.height) {
return {
reset: {
rects: true
}
};
}
return {};
}
};
};
// node_modules/@floating-ui/dom/dist/floating-ui.dom.mjs
function getCssDimensions(element) {
const css = getComputedStyle2(element);
let width = parseFloat(css.width) || 0;
let height = parseFloat(css.height) || 0;
const hasOffset = isHTMLElement(element);
const offsetWidth = hasOffset ? element.offsetWidth : width;
const offsetHeight = hasOffset ? element.offsetHeight : height;
const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight;
if (shouldFallback) {
width = offsetWidth;
height = offsetHeight;
}
return {
width,
height,
$: shouldFallback
};
}
function unwrapElement(element) {
return !isElement(element) ? element.contextElement : element;
}
function getScale(element) {
const domElement = unwrapElement(element);
if (!isHTMLElement(domElement)) {
return createCoords(1);
}
const rect = domElement.getBoundingClientRect();
const {
width,
height,
$: $2
} = getCssDimensions(domElement);
let x2 = ($2 ? round(rect.width) : rect.width) / width;
let y2 = ($2 ? round(rect.height) : rect.height) / height;
if (!x2 || !Number.isFinite(x2)) {
x2 = 1;
}
if (!y2 || !Number.isFinite(y2)) {
y2 = 1;
}
return {
x: x2,
y: y2
};
}
var noOffsets = /* @__PURE__ */ createCoords(0);
function getVisualOffsets(element) {
const win = getWindow(element);
if (!isWebKit() || !win.visualViewport) {
return noOffsets;
}
return {
x: win.visualViewport.offsetLeft,
y: win.visualViewport.offsetTop
};
}
function shouldAddVisualOffsets(element, isFixed, floatingOffsetParent) {
if (isFixed === void 0) {
isFixed = false;
}
if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow(element)) {
return false;
}
return isFixed;
}
function getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) {
if (includeScale === void 0) {
includeScale = false;
}
if (isFixedStrategy === void 0) {
isFixedStrategy = false;
}
const clientRect = element.getBoundingClientRect();
const domElement = unwrapElement(element);
let scale = createCoords(1);
if (includeScale) {
if (offsetParent) {
if (isElement(offsetParent)) {
scale = getScale(offsetParent);
}
} else {
scale = getScale(element);
}
}
const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0);
let x2 = (clientRect.left + visualOffsets.x) / scale.x;
let y2 = (clientRect.top + visualOffsets.y) / scale.y;
let width = clientRect.width / scale.x;
let height = clientRect.height / scale.y;
if (domElement) {
const win = getWindow(domElement);
const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent;
let currentWin = win;
let currentIFrame = getFrameElement(currentWin);
while (currentIFrame && offsetParent && offsetWin !== currentWin) {
const iframeScale = getScale(currentIFrame);
const iframeRect = currentIFrame.getBoundingClientRect();
const css = getComputedStyle2(currentIFrame);
const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x;
const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y;
x2 *= iframeScale.x;
y2 *= iframeScale.y;
width *= iframeScale.x;
height *= iframeScale.y;
x2 += left;
y2 += top;
currentWin = getWindow(currentIFrame);
currentIFrame = getFrameElement(currentWin);
}
}
return rectToClientRect({
width,
height,
x: x2,
y: y2
});
}
function getWindowScrollBarX(element, rect) {
const leftScroll = getNodeScroll(element).scrollLeft;
if (!rect) {
return getBoundingClientRect(getDocumentElement(element)).left + leftScroll;
}
return rect.left + leftScroll;
}
function getHTMLOffset(documentElement, scroll) {
const htmlRect = documentElement.getBoundingClientRect();
const x2 = htmlRect.left + scroll.scrollLeft - getWindowScrollBarX(documentElement, htmlRect);
const y2 = htmlRect.top + scroll.scrollTop;
return {
x: x2,
y: y2
};
}
function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) {
let {
elements,
rect,
offsetParent,
strategy
} = _ref;
const isFixed = strategy === "fixed";
const documentElement = getDocumentElement(offsetParent);
const topLayer = elements ? isTopLayer(elements.floating) : false;
if (offsetParent === documentElement || topLayer && isFixed) {
return rect;
}
let scroll = {
scrollLeft: 0,
scrollTop: 0
};
let scale = createCoords(1);
const offsets = createCoords(0);
const isOffsetParentAnElement = isHTMLElement(offsetParent);
if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
if (getNodeName(offsetParent) !== "body" || isOverflowElement(documentElement)) {
scroll = getNodeScroll(offsetParent);
}
if (isOffsetParentAnElement) {
const offsetRect = getBoundingClientRect(offsetParent);
scale = getScale(offsetParent);
offsets.x = offsetRect.x + offsetParent.clientLeft;
offsets.y = offsetRect.y + offsetParent.clientTop;
}
}
const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);
return {
width: rect.width * scale.x,
height: rect.height * scale.y,
x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x + htmlOffset.x,
y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y + htmlOffset.y
};
}
function getClientRects(element) {
return Array.from(element.getClientRects());
}
function getDocumentRect(element) {
const html = getDocumentElement(element);
const scroll = getNodeScroll(element);
const body = element.ownerDocument.body;
const width = max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth);
const height = max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight);
let x2 = -scroll.scrollLeft + getWindowScrollBarX(element);
const y2 = -scroll.scrollTop;
if (getComputedStyle2(body).direction === "rtl") {
x2 += max(html.clientWidth, body.clientWidth) - width;
}
return {
width,
height,
x: x2,
y: y2
};
}
var SCROLLBAR_MAX = 25;
function getViewportRect(element, strategy) {
const win = getWindow(element);
const html = getDocumentElement(element);
const visualViewport = win.visualViewport;
let width = html.clientWidth;
let height = html.clientHeight;
let x2 = 0;
let y2 = 0;
if (visualViewport) {
width = visualViewport.width;
height = visualViewport.height;
const visualViewportBased = isWebKit();
if (!visualViewportBased || visualViewportBased && strategy === "fixed") {
x2 = visualViewport.offsetLeft;
y2 = visualViewport.offsetTop;
}
}
const windowScrollbarX = getWindowScrollBarX(html);
if (windowScrollbarX <= 0) {
const doc = html.ownerDocument;
const body = doc.body;
const bodyStyles = getComputedStyle(body);
const bodyMarginInline = doc.compatMode === "CSS1Compat" ? parseFloat(bodyStyles.marginLeft) + parseFloat(bodyStyles.marginRight) || 0 : 0;
const clippingStableScrollbarWidth = Math.abs(html.clientWidth - body.clientWidth - bodyMarginInline);
if (clippingStableScrollbarWidth <= SCROLLBAR_MAX) {
width -= clippingStableScrollbarWidth;
}
} else if (windowScrollbarX <= SCROLLBAR_MAX) {
width += windowScrollbarX;
}
return {
width,
height,
x: x2,
y: y2
};
}
function getInnerBoundingClientRect(element, strategy) {
const clientRect = getBoundingClientRect(element, true, strategy === "fixed");
const top = clientRect.top + element.clientTop;
const left = clientRect.left + element.clientLeft;
const scale = isHTMLElement(element) ? getScale(element) : createCoords(1);
const width = element.clientWidth * scale.x;
const height = element.clientHeight * scale.y;
const x2 = left * scale.x;
const y2 = top * scale.y;
return {
width,
height,
x: x2,
y: y2
};
}
function getClientRectFromClippingAncestor(element, clippingAncestor, strategy) {
let rect;
if (clippingAncestor === "viewport") {
rect = getViewportRect(element, strategy);
} else if (clippingAncestor === "document") {
rect = getDocumentRect(getDocumentElement(element));
} else if (isElement(clippingAncestor)) {
rect = getInnerBoundingClientRect(clippingAncestor, strategy);
} else {
const visualOffsets = getVisualOffsets(element);
rect = {
x: clippingAncestor.x - visualOffsets.x,
y: clippingAncestor.y - visualOffsets.y,
width: clippingAncestor.width,
height: clippingAncestor.height
};
}
return rectToClientRect(rect);
}
function hasFixedPositionAncestor(element, stopNode) {
const parentNode = getParentNode(element);
if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) {
return false;
}
return getComputedStyle2(parentNode).position === "fixed" || hasFixedPositionAncestor(parentNode, stopNode);
}
function getClippingElementAncestors(element, cache) {
const cachedResult = cache.get(element);
if (cachedResult) {
return cachedResult;
}
let result = getOverflowAncestors(element, [], false).filter((el) => isElement(el) && getNodeName(el) !== "body");
let currentContainingBlockComputedStyle = null;
const elementIsFixed = getComputedStyle2(element).position === "fixed";
let currentNode = elementIsFixed ? getParentNode(element) : element;
while (isElement(currentNode) && !isLastTraversableNode(currentNode)) {
const computedStyle = getComputedStyle2(currentNode);
const currentNodeIsContaining = isContainingBlock(currentNode);
if (!currentNodeIsContaining && computedStyle.position === "fixed") {
currentContainingBlockComputedStyle = null;
}
const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === "static" && !!currentContainingBlockComputedStyle && (currentContainingBlockComputedStyle.position === "absolute" || currentContainingBlockComputedStyle.position === "fixed") || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode);
if (shouldDropCurrentNode) {
result = result.filter((ancestor) => ancestor !== currentNode);
} else {
currentContainingBlockComputedStyle = computedStyle;
}
currentNode = getParentNode(currentNode);
}
cache.set(element, result);
return result;
}
function getClippingRect(_ref) {
let {
element,
boundary,
rootBoundary,
strategy
} = _ref;
const elementClippingAncestors = boundary === "clippingAncestors" ? isTopLayer(element) ? [] : getClippingElementAncestors(element, this._c) : [].concat(boundary);
const clippingAncestors = [...elementClippingAncestors, rootBoundary];
const firstRect = getClientRectFromClippingAncestor(element, clippingAncestors[0], strategy);
let top = firstRect.top;
let right = firstRect.right;
let bottom = firstRect.bottom;
let left = firstRect.left;
for (let i2 = 1; i2 < clippingAncestors.length; i2++) {
const rect = getClientRectFromClippingAncestor(element, clippingAncestors[i2], strategy);
top = max(rect.top, top);
right = min(rect.right, right);
bottom = min(rect.bottom, bottom);
left = max(rect.left, left);
}
return {
width: right - left,
height: bottom - top,
x: left,
y: top
};
}
function getDimensions2(element) {
const {
width,
height
} = getCssDimensions(element);
return {
width,
height
};
}
function getRectRelativeToOffsetParent(element, offsetParent, strategy) {
const isOffsetParentAnElement = isHTMLElement(offsetParent);
const documentElement = getDocumentElement(offsetParent);
const isFixed = strategy === "fixed";
const rect = getBoundingClientRect(element, true, isFixed, offsetParent);
let scroll = {
scrollLeft: 0,
scrollTop: 0
};
const offsets = createCoords(0);
function setLeftRTLScrollbarOffset() {
offsets.x = getWindowScrollBarX(documentElement);
}
if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
if (getNodeName(offsetParent) !== "body" || isOverflowElement(documentElement)) {
scroll = getNodeScroll(offsetParent);
}
if (isOffsetParentAnElement) {
const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent);
offsets.x = offsetRect.x + offsetParent.clientLeft;
offsets.y = offsetRect.y + offsetParent.clientTop;
} else if (documentElement) {
setLeftRTLScrollbarOffset();
}
}
if (isFixed && !isOffsetParentAnElement && documentElement) {
setLeftRTLScrollbarOffset();
}
const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);
const x2 = rect.left + scroll.scrollLeft - offsets.x - htmlOffset.x;
const y2 = rect.top + scroll.scrollTop - offsets.y - htmlOffset.y;
return {
x: x2,
y: y2,
width: rect.width,
height: rect.height
};
}
function isStaticPositioned(element) {
return getComputedStyle2(element).position === "static";
}
function getTrueOffsetParent(element, polyfill) {
if (!isHTMLElement(element) || getComputedStyle2(element).position === "fixed") {
return null;
}
if (polyfill) {
return polyfill(element);
}
let rawOffsetParent = element.offsetParent;
if (getDocumentElement(element) === rawOffsetParent) {
rawOffsetParent = rawOffsetParent.ownerDocument.body;
}
return rawOffsetParent;
}
function getOffsetParent(element, polyfill) {
const win = getWindow(element);
if (isTopLayer(element)) {
return win;
}
if (!isHTMLElement(element)) {
let svgOffsetParent = getParentNode(element);
while (svgOffsetParent && !isLastTraversableNode(svgOffsetParent)) {
if (isElement(svgOffsetParent) && !isStaticPositioned(svgOffsetParent)) {
return svgOffsetParent;
}
svgOffsetParent = getParentNode(svgOffsetParent);
}
return win;
}
let offsetParent = getTrueOffsetParent(element, polyfill);
while (offsetParent && isTableElement(offsetParent) && isStaticPositioned(offsetParent)) {
offsetParent = getTrueOffsetParent(offsetParent, polyfill);
}
if (offsetParent && isLastTraversableNode(offsetParent) && isStaticPositioned(offsetParent) && !isContainingBlock(offsetParent)) {
return win;
}
return offsetParent || getContainingBlock(element) || win;
}
var getElementRects = async function(data) {
const getOffsetParentFn = this.getOffsetParent || getOffsetParent;
const getDimensionsFn = this.getDimensions;
const floatingDimensions = await getDimensionsFn(data.floating);
return {
reference: getRectRelativeToOffsetParent(data.reference, await getOffsetParentFn(data.floating), data.strategy),
floating: {
x: 0,
y: 0,
width: floatingDimensions.width,
height: floatingDimensions.height
}
};
};
function isRTL2(element) {
return getComputedStyle2(element).direction === "rtl";
}
var platform2 = {
convertOffsetParentRelativeRectToViewportRelativeRect,
getDocumentElement,
getClippingRect,
getOffsetParent,
getElementRects,
getClientRects,
getDimensions: getDimensions2,
getScale,
isElement,
isRTL: isRTL2
};
function rectsAreEqual(a2, b2) {
return a2.x === b2.x && a2.y === b2.y && a2.width === b2.width && a2.height === b2.height;
}
function observeMove(element, onMove) {
let io = null;
let timeoutId;
const root = getDocumentElement(element);
function cleanup() {
var _io;
clearTimeout(timeoutId);
(_io = io) == null || _io.disconnect();
io = null;
}
function refresh(skip, threshold) {
if (skip === void 0) {
skip = false;
}
if (threshold === void 0) {
threshold = 1;
}
cleanup();
const elementRectForRootMargin = element.getBoundingClientRect();
const {
left,
top,
width,
height
} = elementRectForRootMargin;
if (!skip) {
onMove();
}
if (!width || !height) {
return;
}
const insetTop = floor(top);
const insetRight = floor(root.clientWidth - (left + width));
const insetBottom = floor(root.clientHeight - (top + height));
const insetLeft = floor(left);
const rootMargin = -insetTop + "px " + -insetRight + "px " + -insetBottom + "px " + -insetLeft + "px";
const options = {
rootMargin,
threshold: max(0, min(1, threshold)) || 1
};
let isFirstUpdate = true;
function handleObserve(entries) {
const ratio = entries[0].intersectionRatio;
if (ratio !== threshold) {
if (!isFirstUpdate) {
return refresh();
}
if (!ratio) {
timeoutId = setTimeout(() => {
refresh(false, 1e-7);
}, 1e3);
} else {
refresh(false, ratio);
}
}
if (ratio === 1 && !rectsAreEqual(elementRectForRootMargin, element.getBoundingClientRect())) {
refresh();
}
isFirstUpdate = false;
}
try {
io = new IntersectionObserver(handleObserve, {
...options,
// Handle <iframe>s
root: root.ownerDocument
});
} catch (_e) {
io = new IntersectionObserver(handleObserve, options);
}
io.observe(element);
}
refresh(true);
return cleanup;
}
function autoUpdate(reference, floating, update4, options) {
if (options === void 0) {
options = {};
}
const {
ancestorScroll = true,
ancestorResize = true,
elementResize = typeof ResizeObserver === "function",
layoutShift = typeof IntersectionObserver === "function",
animationFrame = false
} = options;
const referenceEl = unwrapElement(reference);
const ancestors = ancestorScroll || ancestorResize ? [...referenceEl ? getOverflowAncestors(referenceEl) : [], ...floating ? getOverflowAncestors(floating) : []] : [];
ancestors.forEach((ancestor) => {
ancestorScroll && ancestor.addEventListener("scroll", update4, {
passive: true
});
ancestorResize && ancestor.addEventListener("resize", update4);
});
const cleanupIo = referenceEl && layoutShift ? observeMove(referenceEl, update4) : null;
let reobserveFrame = -1;
let resizeObserver = null;
if (elementResize) {
resizeObserver = new ResizeObserver((_ref) => {
let [firstEntry] = _ref;
if (firstEntry && firstEntry.target === referenceEl && resizeObserver && floating) {
resizeObserver.unobserve(floating);
cancelAnimationFrame(reobserveFrame);
reobserveFrame = requestAnimationFrame(() => {
var _resizeObserver;
(_resizeObserver = resizeObserver) == null || _resizeObserver.observe(floating);
});
}
update4();
});
if (referenceEl && !animationFrame) {
resizeObserver.observe(referenceEl);
}
if (floating) {
resizeObserver.observe(floating);
}
}
let frameId;
let prevRefRect = animationFrame ? getBoundingClientRect(reference) : null;
if (animationFrame) {
frameLoop2();
}
function frameLoop2() {
const nextRefRect = getBoundingClientRect(reference);
if (prevRefRect && !rectsAreEqual(prevRefRect, nextRefRect)) {
update4();
}
prevRefRect = nextRefRect;
frameId = requestAnimationFrame(frameLoop2);
}
update4();
return () => {
var _resizeObserver2;
ancestors.forEach((ancestor) => {
ancestorScroll && ancestor.removeEventListener("scroll", update4);
ancestorResize && ancestor.removeEventListener("resize", update4);
});
cleanupIo == null || cleanupIo();
(_resizeObserver2 = resizeObserver) == null || _resizeObserver2.disconnect();
resizeObserver = null;
if (animationFrame) {
cancelAnimationFrame(frameId);
}
};
}
var offset2 = offset;
var shift2 = shift;
var flip2 = flip;
var size2 = size;
var hide2 = hide;
var limitShift2 = limitShift;
var computePosition2 = (reference, floating, options) => {
const cache = /* @__PURE__ */ new Map();
const mergedOptions = {
platform: platform2,
...options
};
const platformWithCache = {
...mergedOptions.platform,
_c: cache
};
return computePosition(reference, floating, {
...mergedOptions,
platform: platformWithCache
});
};
// node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.mjs
var React33 = __toESM(require_react(), 1);
var import_react5 = __toESM(require_react(), 1);
var ReactDOM3 = __toESM(require_react_dom(), 1);
var isClient = typeof document !== "undefined";
var noop5 = function noop6() {
};
var index = isClient ? import_react5.useLayoutEffect : noop5;
function deepEqual(a2, b2) {
if (a2 === b2) {
return true;
}
if (typeof a2 !== typeof b2) {
return false;
}
if (typeof a2 === "function" && a2.toString() === b2.toString()) {
return true;
}
let length;
let i2;
let keys;
if (a2 && b2 && typeof a2 === "object") {
if (Array.isArray(a2)) {
length = a2.length;
if (length !== b2.length) return false;
for (i2 = length; i2-- !== 0; ) {
if (!deepEqual(a2[i2], b2[i2])) {
return false;
}
}
return true;
}
keys = Object.keys(a2);
length = keys.length;
if (length !== Object.keys(b2).length) {
return false;
}
for (i2 = length; i2-- !== 0; ) {
if (!{}.hasOwnProperty.call(b2, keys[i2])) {
return false;
}
}
for (i2 = length; i2-- !== 0; ) {
const key = keys[i2];
if (key === "_owner" && a2.$$typeof) {
continue;
}
if (!deepEqual(a2[key], b2[key])) {
return false;
}
}
return true;
}
return a2 !== a2 && b2 !== b2;
}
function getDPR(element) {
if (typeof window === "undefined") {
return 1;
}
const win = element.ownerDocument.defaultView || window;
return win.devicePixelRatio || 1;
}
function roundByDPR(element, value) {
const dpr = getDPR(element);
return Math.round(value * dpr) / dpr;
}
function useLatestRef(value) {
const ref = React33.useRef(value);
index(() => {
ref.current = value;
});
return ref;
}
function useFloating(options) {
if (options === void 0) {
options = {};
}
const {
placement = "bottom",
strategy = "absolute",
middleware = [],
platform: platform3,
elements: {
reference: externalReference,
floating: externalFloating
} = {},
transform = true,
whileElementsMounted,
open
} = options;
const [data, setData] = React33.useState({
x: 0,
y: 0,
strategy,
placement,
middlewareData: {},
isPositioned: false
});
const [latestMiddleware, setLatestMiddleware] = React33.useState(middleware);
if (!deepEqual(latestMiddleware, middleware)) {
setLatestMiddleware(middleware);
}
const [_reference, _setReference] = React33.useState(null);
const [_floating, _setFloating] = React33.useState(null);
const setReference = React33.useCallback((node) => {
if (node !== referenceRef.current) {
referenceRef.current = node;
_setReference(node);
}
}, []);
const setFloating = React33.useCallback((node) => {
if (node !== floatingRef.current) {
floatingRef.current = node;
_setFloating(node);
}
}, []);
const referenceEl = externalReference || _reference;
const floatingEl = externalFloating || _floating;
const referenceRef = React33.useRef(null);
const floatingRef = React33.useRef(null);
const dataRef = React33.useRef(data);
const hasWhileElementsMounted = whileElementsMounted != null;
const whileElementsMountedRef = useLatestRef(whileElementsMounted);
const platformRef = useLatestRef(platform3);
const openRef = useLatestRef(open);
const update4 = React33.useCallback(() => {
if (!referenceRef.current || !floatingRef.current) {
return;
}
const config2 = {
placement,
strategy,
middleware: latestMiddleware
};
if (platformRef.current) {
config2.platform = platformRef.current;
}
computePosition2(referenceRef.current, floatingRef.current, config2).then((data2) => {
const fullData = {
...data2,
// The floating element's position may be recomputed while it's closed
// but still mounted (such as when transitioning out). To ensure
// `isPositioned` will be `false` initially on the next open, avoid
// setting it to `true` when `open === false` (must be specified).
isPositioned: openRef.current !== false
};
if (isMountedRef.current && !deepEqual(dataRef.current, fullData)) {
dataRef.current = fullData;
ReactDOM3.flushSync(() => {
setData(fullData);
});
}
});
}, [latestMiddleware, placement, strategy, platformRef, openRef]);
index(() => {
if (open === false && dataRef.current.isPositioned) {
dataRef.current.isPositioned = false;
setData((data2) => ({
...data2,
isPositioned: false
}));
}
}, [open]);
const isMountedRef = React33.useRef(false);
index(() => {
isMountedRef.current = true;
return () => {
isMountedRef.current = false;
};
}, []);
index(() => {
if (referenceEl) referenceRef.current = referenceEl;
if (floatingEl) floatingRef.current = floatingEl;
if (referenceEl && floatingEl) {
if (whileElementsMountedRef.current) {
return whileElementsMountedRef.current(referenceEl, floatingEl, update4);
}
update4();
}
}, [referenceEl, floatingEl, update4, whileElementsMountedRef, hasWhileElementsMounted]);
const refs = React33.useMemo(() => ({
reference: referenceRef,
floating: floatingRef,
setReference,
setFloating
}), [setReference, setFloating]);
const elements = React33.useMemo(() => ({
reference: referenceEl,
floating: floatingEl
}), [referenceEl, floatingEl]);
const floatingStyles = React33.useMemo(() => {
const initialStyles = {
position: strategy,
left: 0,
top: 0
};
if (!elements.floating) {
return initialStyles;
}
const x2 = roundByDPR(elements.floating, data.x);
const y2 = roundByDPR(elements.floating, data.y);
if (transform) {
return {
...initialStyles,
transform: "translate(" + x2 + "px, " + y2 + "px)",
...getDPR(elements.floating) >= 1.5 && {
willChange: "transform"
}
};
}
return {
position: strategy,
left: x2,
top: y2
};
}, [strategy, transform, elements.floating, data.x, data.y]);
return React33.useMemo(() => ({
...data,
update: update4,
refs,
elements,
floatingStyles
}), [data, update4, refs, elements, floatingStyles]);
}
var offset3 = (options, deps) => {
const result = offset2(options);
return {
name: result.name,
fn: result.fn,
options: [options, deps]
};
};
var shift3 = (options, deps) => {
const result = shift2(options);
return {
name: result.name,
fn: result.fn,
options: [options, deps]
};
};
var limitShift3 = (options, deps) => {
const result = limitShift2(options);
return {
fn: result.fn,
options: [options, deps]
};
};
var flip3 = (options, deps) => {
const result = flip2(options);
return {
name: result.name,
fn: result.fn,
options: [options, deps]
};
};
var size3 = (options, deps) => {
const result = size2(options);
return {
name: result.name,
fn: result.fn,
options: [options, deps]
};
};
var hide3 = (options, deps) => {
const result = hide2(options);
return {
name: result.name,
fn: result.fn,
options: [options, deps]
};
};
// node_modules/@base-ui/react/utils/popups/popupStoreUtils.mjs
var React38 = __toESM(require_react(), 1);
var ReactDOM4 = __toESM(require_react_dom(), 1);
// node_modules/@base-ui/react/floating-ui-react/hooks/useSyncedFloatingRootContext.mjs
var React37 = __toESM(require_react(), 1);
// node_modules/@base-ui/utils/store/createSelector.mjs
var createSelector3 = (a2, b2, c6, d2, e2, f2, ...other) => {
if (other.length > 0) {
throw new Error(true ? "Unsupported number of selectors" : formatErrorMessage_default(1));
}
let selector3;
if (a2 && b2 && c6 && d2 && e2 && f2) {
selector3 = (state, a1, a22, a3) => {
const va = a2(state, a1, a22, a3);
const vb = b2(state, a1, a22, a3);
const vc = c6(state, a1, a22, a3);
const vd = d2(state, a1, a22, a3);
const ve = e2(state, a1, a22, a3);
return f2(va, vb, vc, vd, ve, a1, a22, a3);
};
} else if (a2 && b2 && c6 && d2 && e2) {
selector3 = (state, a1, a22, a3) => {
const va = a2(state, a1, a22, a3);
const vb = b2(state, a1, a22, a3);
const vc = c6(state, a1, a22, a3);
const vd = d2(state, a1, a22, a3);
return e2(va, vb, vc, vd, a1, a22, a3);
};
} else if (a2 && b2 && c6 && d2) {
selector3 = (state, a1, a22, a3) => {
const va = a2(state, a1, a22, a3);
const vb = b2(state, a1, a22, a3);
const vc = c6(state, a1, a22, a3);
return d2(va, vb, vc, a1, a22, a3);
};
} else if (a2 && b2 && c6) {
selector3 = (state, a1, a22, a3) => {
const va = a2(state, a1, a22, a3);
const vb = b2(state, a1, a22, a3);
return c6(va, vb, a1, a22, a3);
};
} else if (a2 && b2) {
selector3 = (state, a1, a22, a3) => {
const va = a2(state, a1, a22, a3);
return b2(va, a1, a22, a3);
};
} else if (a2) {
selector3 = a2;
} else {
throw (
/* minify-error-disabled */
new Error("Missing arguments")
);
}
return selector3;
};
// node_modules/@base-ui/utils/store/useStore.mjs
var React35 = __toESM(require_react(), 1);
var import_shim = __toESM(require_shim(), 1);
var import_with_selector = __toESM(require_with_selector(), 1);
// node_modules/@base-ui/utils/fastHooks.mjs
var React34 = __toESM(require_react(), 1);
var hooks = [];
var currentInstance = void 0;
function getInstance() {
return currentInstance;
}
function register(hook) {
hooks.push(hook);
}
function fastComponent(fn) {
const FastComponent = (props, forwardedRef) => {
const instance = useRefWithInit(createInstance).current;
let result;
try {
currentInstance = instance;
for (const hook of hooks) {
hook.before(instance);
}
result = fn(props, forwardedRef);
for (const hook of hooks) {
hook.after(instance);
}
instance.didInitialize = true;
} finally {
currentInstance = void 0;
}
return result;
};
FastComponent.displayName = fn.displayName || fn.name;
return FastComponent;
}
function fastComponentRef(fn) {
return /* @__PURE__ */ React34.forwardRef(fastComponent(fn));
}
function createInstance() {
return {
didInitialize: false
};
}
// node_modules/@base-ui/utils/store/useStore.mjs
var canUseRawUseSyncExternalStore = isReactVersionAtLeast(19);
var useStoreImplementation = canUseRawUseSyncExternalStore ? useStoreFast : useStoreLegacy;
function useStore(store2, selector3, a1, a2, a3) {
return useStoreImplementation(store2, selector3, a1, a2, a3);
}
function useStoreR19(store2, selector3, a1, a2, a3) {
const getSelection = React35.useCallback(() => selector3(store2.getSnapshot(), a1, a2, a3), [store2, selector3, a1, a2, a3]);
return (0, import_shim.useSyncExternalStore)(store2.subscribe, getSelection, getSelection);
}
register({
before(instance) {
instance.syncIndex = 0;
if (!instance.didInitialize) {
instance.syncTick = 1;
instance.syncHooks = [];
instance.didChangeStore = true;
instance.getSnapshot = () => {
let didChange2 = false;
for (let i2 = 0; i2 < instance.syncHooks.length; i2 += 1) {
const hook = instance.syncHooks[i2];
const value = hook.selector(hook.store.state, hook.a1, hook.a2, hook.a3);
if (!Object.is(hook.value, value)) {
didChange2 = true;
hook.value = value;
}
}
if (didChange2) {
instance.syncTick += 1;
}
return instance.syncTick;
};
}
},
after(instance) {
if (instance.syncHooks.length > 0) {
if (instance.didChangeStore) {
instance.didChangeStore = false;
instance.subscribe = (onStoreChange) => {
const stores = /* @__PURE__ */ new Set();
for (const hook of instance.syncHooks) {
stores.add(hook.store);
}
const unsubscribes = [];
for (const store2 of stores) {
unsubscribes.push(store2.subscribe(onStoreChange));
}
return () => {
for (const unsubscribe of unsubscribes) {
unsubscribe();
}
};
};
}
(0, import_shim.useSyncExternalStore)(instance.subscribe, instance.getSnapshot, instance.getSnapshot);
}
}
});
function useStoreFast(store2, selector3, a1, a2, a3) {
const instance = getInstance();
if (!instance) {
return useStoreR19(store2, selector3, a1, a2, a3);
}
const index2 = instance.syncIndex;
instance.syncIndex += 1;
let hook;
if (!instance.didInitialize) {
hook = {
store: store2,
selector: selector3,
a1,
a2,
a3,
value: selector3(store2.getSnapshot(), a1, a2, a3)
};
instance.syncHooks.push(hook);
} else {
hook = instance.syncHooks[index2];
if (hook.store !== store2 || hook.selector !== selector3 || !Object.is(hook.a1, a1) || !Object.is(hook.a2, a2) || !Object.is(hook.a3, a3)) {
if (hook.store !== store2) {
instance.didChangeStore = true;
}
hook.store = store2;
hook.selector = selector3;
hook.a1 = a1;
hook.a2 = a2;
hook.a3 = a3;
hook.value = selector3(store2.getSnapshot(), a1, a2, a3);
}
}
return hook.value;
}
function useStoreLegacy(store2, selector3, a1, a2, a3) {
return (0, import_with_selector.useSyncExternalStoreWithSelector)(store2.subscribe, store2.getSnapshot, store2.getSnapshot, (state) => selector3(state, a1, a2, a3));
}
// node_modules/@base-ui/utils/store/Store.mjs
var Store = class {
/**
* The current state of the store.
* This property is updated immediately when the state changes as a result of calling {@link setState}, {@link update}, or {@link set}.
* To subscribe to state changes, use the {@link useState} method. The value returned by {@link useState} is updated after the component renders (similarly to React's useState).
* The values can be used directly (to avoid subscribing to the store) in effects or event handlers.
*
* Do not modify properties in state directly. Instead, use the provided methods to ensure proper state management and listener notification.
*/
// Internal state to handle recursive `setState()` calls
constructor(state) {
this.state = state;
this.listeners = /* @__PURE__ */ new Set();
this.updateTick = 0;
}
/**
* Registers a listener that will be called whenever the store's state changes.
*
* @param fn The listener function to be called on state changes.
* @returns A function to unsubscribe the listener.
*/
subscribe = (fn) => {
this.listeners.add(fn);
return () => {
this.listeners.delete(fn);
};
};
/**
* Returns the current state of the store.
*/
getSnapshot = () => {
return this.state;
};
/**
* Updates the entire store's state and notifies all registered listeners.
*
* @param newState The new state to set for the store.
*/
setState(newState) {
if (this.state === newState) {
return;
}
this.state = newState;
this.updateTick += 1;
const currentTick = this.updateTick;
for (const listener of this.listeners) {
if (currentTick !== this.updateTick) {
return;
}
listener(newState);
}
}
/**
* Merges the provided changes into the current state and notifies listeners if there are changes.
*
* @param changes An object containing the changes to apply to the current state.
*/
update(changes) {
for (const key in changes) {
if (!Object.is(this.state[key], changes[key])) {
this.setState({
...this.state,
...changes
});
return;
}
}
}
/**
* Sets a specific key in the store's state to a new value and notifies listeners if the value has changed.
*
* @param key The key in the store's state to update.
* @param value The new value to set for the specified key.
*/
set(key, value) {
if (!Object.is(this.state[key], value)) {
this.setState({
...this.state,
[key]: value
});
}
}
/**
* Gives the state a new reference and updates all registered listeners.
*/
notifyAll() {
const newState = {
...this.state
};
this.setState(newState);
}
use(selector3, a1, a2, a3) {
return useStore(this, selector3, a1, a2, a3);
}
};
// node_modules/@base-ui/utils/store/ReactStore.mjs
var React36 = __toESM(require_react(), 1);
var ReactStore = class extends Store {
/**
* Creates a new ReactStore instance.
*
* @param state Initial state of the store.
* @param context Non-reactive context values.
* @param selectors Optional selectors for use with `useState`.
*/
constructor(state, context = {}, selectors4) {
super(state);
this.context = context;
this.selectors = selectors4;
}
/**
* Non-reactive values such as refs, callbacks, etc.
*/
/**
* Synchronizes a single external value into the store.
*
* Note that the while the value in `state` is updated immediately, the value returned
* by `useState` is updated before the next render (similarly to React's `useState`).
*/
useSyncedValue(key, value) {
React36.useDebugValue(key);
const store2 = this;
useIsoLayoutEffect(() => {
if (store2.state[key] !== value) {
store2.set(key, value);
}
}, [store2, key, value]);
}
/**
* Synchronizes a single external value into the store and
* cleans it up (sets to `undefined`) on unmount.
*
* Note that the while the value in `state` is updated immediately, the value returned
* by `useState` is updated before the next render (similarly to React's `useState`).
*/
useSyncedValueWithCleanup(key, value) {
const store2 = this;
useIsoLayoutEffect(() => {
if (store2.state[key] !== value) {
store2.set(key, value);
}
return () => {
store2.set(key, void 0);
};
}, [store2, key, value]);
}
/**
* Synchronizes multiple external values into the store.
*
* Note that the while the values in `state` are updated immediately, the values returned
* by `useState` are updated before the next render (similarly to React's `useState`).
*/
useSyncedValues(statePart) {
const store2 = this;
if (true) {
React36.useDebugValue(statePart, (p2) => Object.keys(p2));
const keys = React36.useRef(Object.keys(statePart)).current;
const nextKeys = Object.keys(statePart);
if (keys.length !== nextKeys.length || keys.some((key, index2) => key !== nextKeys[index2])) {
console.error("ReactStore.useSyncedValues expects the same prop keys on every render. Keys should be stable.");
}
}
const dependencies = Object.values(statePart);
useIsoLayoutEffect(() => {
store2.update(statePart);
}, [store2, ...dependencies]);
}
/**
* Registers a controllable prop pair (`controlled`, `defaultValue`) for a specific key. If `controlled`
* is non-undefined, the store's state at `key` is updated to match `controlled`.
*/
useControlledProp(key, controlled) {
React36.useDebugValue(key);
const store2 = this;
const isControlled = controlled !== void 0;
useIsoLayoutEffect(() => {
if (isControlled && !Object.is(store2.state[key], controlled)) {
store2.setState({
...store2.state,
[key]: controlled
});
}
}, [store2, key, controlled, isControlled]);
if (true) {
const cache = this.controlledValues ??= /* @__PURE__ */ new Map();
if (!cache.has(key)) {
cache.set(key, isControlled);
}
const previouslyControlled = cache.get(key);
if (previouslyControlled !== void 0 && previouslyControlled !== isControlled) {
console.error(`A component is changing the ${isControlled ? "" : "un"}controlled state of ${key.toString()} to be ${isControlled ? "un" : ""}controlled. Elements should not switch from uncontrolled to controlled (or vice versa).`);
}
}
}
/** Gets the current value from the store using a selector with the provided key.
*
* @param key Key of the selector to use.
*/
select(key, a1, a2, a3) {
const selector3 = this.selectors[key];
return selector3(this.state, a1, a2, a3);
}
/**
* Returns a value from the store's state using a selector function.
* Used to subscribe to specific parts of the state.
* This methods causes a rerender whenever the selected state changes.
*
* @param key Key of the selector to use.
*/
useState(key, a1, a2, a3) {
React36.useDebugValue(key);
return useStore(this, this.selectors[key], a1, a2, a3);
}
/**
* Wraps a function with `useStableCallback` to ensure it has a stable reference
* and assigns it to the context.
*
* @param key Key of the event callback. Must be a function in the context.
* @param fn Function to assign.
*/
useContextCallback(key, fn) {
React36.useDebugValue(key);
const stableFunction = useStableCallback(fn ?? NOOP);
this.context[key] = stableFunction;
}
/**
* Returns a stable setter function for a specific key in the store's state.
* It's commonly used to pass as a ref callback to React elements.
*
* @param key Key of the state to set.
*/
useStateSetter(key) {
const ref = React36.useRef(void 0);
if (ref.current === void 0) {
ref.current = (value) => {
this.set(key, value);
};
}
return ref.current;
}
/**
* Observes changes derived from the store's selectors and calls the listener when the selected value changes.
*
* @param key Key of the selector to observe.
* @param listener Listener function called when the selector result changes.
*/
observe(selector3, listener) {
let selectFn;
if (typeof selector3 === "function") {
selectFn = selector3;
} else {
selectFn = this.selectors[selector3];
}
let prevValue = selectFn(this.state);
listener(prevValue, prevValue, this);
return this.subscribe((nextState) => {
const nextValue = selectFn(nextState);
if (!Object.is(prevValue, nextValue)) {
const oldValue = prevValue;
prevValue = nextValue;
listener(nextValue, oldValue, this);
}
});
}
};
// node_modules/@base-ui/react/floating-ui-react/components/FloatingRootStore.mjs
var selectors = {
open: createSelector3((state) => state.open),
transitionStatus: createSelector3((state) => state.transitionStatus),
domReferenceElement: createSelector3((state) => state.domReferenceElement),
referenceElement: createSelector3((state) => state.positionReference ?? state.referenceElement),
floatingElement: createSelector3((state) => state.floatingElement),
floatingId: createSelector3((state) => state.floatingId)
};
var FloatingRootStore = class extends ReactStore {
constructor(options) {
const {
syncOnly,
nested,
onOpenChange,
triggerElements,
...initialState
} = options;
super({
...initialState,
positionReference: initialState.referenceElement,
domReferenceElement: initialState.referenceElement
}, {
onOpenChange,
dataRef: {
current: {}
},
events: createEventEmitter(),
nested,
triggerElements
}, selectors);
this.syncOnly = syncOnly;
}
/**
* Syncs the event used by hover logic to distinguish hover-open from click-like interaction.
*/
syncOpenEvent = (newOpen, event) => {
if (!newOpen || !this.state.open || // Prevent a pending hover-open from overwriting a click-open event, while allowing
// click events to upgrade a hover-open.
event != null && isClickLikeEvent(event)) {
this.context.dataRef.current.openEvent = newOpen ? event : void 0;
}
};
/**
* Runs the root-owned side effects for an open state change.
*/
dispatchOpenChange = (newOpen, eventDetails) => {
this.syncOpenEvent(newOpen, eventDetails.event);
const details = {
open: newOpen,
reason: eventDetails.reason,
nativeEvent: eventDetails.event,
nested: this.context.nested,
triggerElement: eventDetails.trigger
};
this.context.events.emit("openchange", details);
};
/**
* Emits the `openchange` event through the internal event emitter and calls the `onOpenChange` handler with the provided arguments.
*
* @param newOpen The new open state.
* @param eventDetails Details about the event that triggered the open state change.
*/
setOpen = (newOpen, eventDetails) => {
if (this.syncOnly) {
this.context.onOpenChange?.(newOpen, eventDetails);
return;
}
this.dispatchOpenChange(newOpen, eventDetails);
this.context.onOpenChange?.(newOpen, eventDetails);
};
};
// node_modules/@base-ui/react/floating-ui-react/hooks/useSyncedFloatingRootContext.mjs
function useSyncedFloatingRootContext(options) {
const {
popupStore,
treatPopupAsFloatingElement = false,
floatingRootContext: floatingRootContextProp,
floatingId,
nested,
onOpenChange
} = options;
const open = popupStore.useState("open");
const referenceElement = popupStore.useState("activeTriggerElement");
const floatingElement = popupStore.useState(treatPopupAsFloatingElement ? "popupElement" : "positionerElement");
const triggerElements = popupStore.context.triggerElements;
const handleOpenChange = onOpenChange;
const internalStoreRef = React37.useRef(null);
if (floatingRootContextProp === void 0 && internalStoreRef.current === null) {
internalStoreRef.current = new FloatingRootStore({
open,
transitionStatus: void 0,
referenceElement,
floatingElement,
triggerElements,
onOpenChange: handleOpenChange,
floatingId,
syncOnly: true,
nested
});
}
const store2 = floatingRootContextProp ?? internalStoreRef.current;
popupStore.useSyncedValue("floatingId", floatingId);
useIsoLayoutEffect(() => {
const valuesToSync = {
open,
floatingId,
referenceElement,
floatingElement
};
if (isElement(referenceElement)) {
valuesToSync.domReferenceElement = referenceElement;
}
if (store2.state.positionReference === store2.state.referenceElement) {
valuesToSync.positionReference = referenceElement;
}
store2.update(valuesToSync);
}, [open, floatingId, referenceElement, floatingElement, store2]);
store2.context.onOpenChange = handleOpenChange;
store2.context.nested = nested;
return store2;
}
// node_modules/@base-ui/react/utils/popups/popupStoreUtils.mjs
var FOCUSABLE_POPUP_PROPS = {
tabIndex: -1,
[FOCUSABLE_ATTRIBUTE]: ""
};
function usePopupStore(externalStore, createStore, treatPopupAsFloatingElement = false) {
const floatingId = useId();
const nested = useFloatingParentNodeId() != null;
const internalStoreRef = React38.useRef(null);
if (externalStore === void 0 && internalStoreRef.current === null) {
internalStoreRef.current = createStore(floatingId, nested);
}
const store2 = externalStore ?? internalStoreRef.current;
useSyncedFloatingRootContext({
popupStore: store2,
treatPopupAsFloatingElement,
floatingRootContext: store2.state.floatingRootContext,
floatingId,
nested,
onOpenChange: store2.setOpen
});
return {
store: store2,
internalStore: internalStoreRef.current
};
}
function useTriggerRegistration(id, store2) {
const registeredElementIdRef = React38.useRef(null);
const registeredElementRef = React38.useRef(null);
return React38.useCallback((element) => {
if (id === void 0) {
return;
}
let shouldSyncTriggerCount = false;
if (registeredElementIdRef.current !== null) {
const registeredId = registeredElementIdRef.current;
const registeredElement = registeredElementRef.current;
const currentElement = store2.context.triggerElements.getById(registeredId);
if (registeredElement && currentElement === registeredElement) {
store2.context.triggerElements.delete(registeredId);
shouldSyncTriggerCount = true;
}
registeredElementIdRef.current = null;
registeredElementRef.current = null;
}
if (element !== null) {
registeredElementIdRef.current = id;
registeredElementRef.current = element;
store2.context.triggerElements.add(id, element);
shouldSyncTriggerCount = true;
}
if (shouldSyncTriggerCount) {
const triggerCount = store2.context.triggerElements.size;
if (store2.select("open") && store2.state.triggerCount !== triggerCount) {
store2.set("triggerCount", triggerCount);
}
}
}, [store2, id]);
}
function setPopupOpenState(state, open, trigger, preventUnmountOnClose = false) {
if (open) {
state.preventUnmountingOnClose = false;
} else if (preventUnmountOnClose) {
state.preventUnmountingOnClose = true;
}
const triggerId = trigger?.id ?? null;
if (triggerId || open) {
state.activeTriggerId = triggerId;
state.activeTriggerElement = trigger ?? null;
}
}
function attachPreventUnmountOnClose(eventDetails) {
let preventUnmountOnClose = false;
eventDetails.preventUnmountOnClose = () => {
preventUnmountOnClose = true;
};
return () => preventUnmountOnClose;
}
function applyPopupOpenChange(store2, nextOpen, eventDetails, options = {}) {
const reason = eventDetails.reason;
const isHover = reason === reason_parts_exports.triggerHover;
const isFocusOpen = nextOpen && reason === reason_parts_exports.triggerFocus;
const isDismissClose = !nextOpen && (reason === reason_parts_exports.triggerPress || reason === reason_parts_exports.escapeKey);
const shouldPreventUnmountOnClose = attachPreventUnmountOnClose(eventDetails);
store2.context.onOpenChange?.(nextOpen, eventDetails);
if (eventDetails.isCanceled) {
return;
}
options.onBeforeDispatch?.();
store2.state.floatingRootContext.dispatchOpenChange(nextOpen, eventDetails);
const changeState = () => {
const updatedState = {
...options.extraState,
open: nextOpen
};
if (isFocusOpen) {
updatedState.instantType = "focus";
} else if (isDismissClose) {
updatedState.instantType = "dismiss";
} else if (isHover) {
updatedState.instantType = void 0;
}
setPopupOpenState(updatedState, nextOpen, eventDetails.trigger, shouldPreventUnmountOnClose());
store2.update(updatedState);
};
if (isHover) {
ReactDOM4.flushSync(changeState);
} else {
changeState();
}
}
function useInitialOpenSync(store2, openProp, defaultOpen, defaultTriggerId) {
useOnFirstRender(() => {
if (openProp === void 0 && store2.state.open === false && defaultOpen) {
store2.state = {
...store2.state,
open: true,
activeTriggerId: defaultTriggerId,
preventUnmountingOnClose: false
};
}
});
}
function useTriggerDataForwarding(triggerId, triggerElementRef, store2, stateUpdates) {
const isMountedByThisTrigger = store2.useState("isMountedByTrigger", triggerId);
const baseRegisterTrigger = useTriggerRegistration(triggerId, store2);
const registerTrigger = useStableCallback((element) => {
baseRegisterTrigger(element);
if (!element) {
return;
}
const open = store2.select("open");
const activeTriggerId = store2.select("activeTriggerId");
if (activeTriggerId === triggerId) {
store2.update({
activeTriggerElement: element,
...open ? stateUpdates : null
});
return;
}
if (activeTriggerId == null && open) {
store2.update({
activeTriggerId: triggerId,
activeTriggerElement: element,
...stateUpdates
});
}
});
useIsoLayoutEffect(() => {
if (isMountedByThisTrigger) {
store2.update({
activeTriggerElement: triggerElementRef.current,
...stateUpdates
});
}
}, [isMountedByThisTrigger, store2, triggerElementRef, ...Object.values(stateUpdates)]);
return {
registerTrigger,
isMountedByThisTrigger
};
}
function useImplicitActiveTrigger(store2, options = {}) {
const {
closeOnActiveTriggerUnmount = false
} = options;
const open = store2.useState("open");
const reactiveTriggerCount = store2.useState("triggerCount");
useIsoLayoutEffect(() => {
if (!open) {
if (store2.state.triggerCount !== 0) {
store2.set("triggerCount", 0);
}
return;
}
const triggerCount = store2.context.triggerElements.size;
const stateUpdates = {};
if (store2.state.triggerCount !== triggerCount) {
stateUpdates.triggerCount = triggerCount;
}
const activeTriggerId = store2.select("activeTriggerId");
let lostActiveTriggerId = null;
if (activeTriggerId) {
const activeTriggerElement = store2.context.triggerElements.getById(activeTriggerId);
if (!activeTriggerElement) {
lostActiveTriggerId = activeTriggerId;
} else if (activeTriggerElement !== store2.state.activeTriggerElement) {
stateUpdates.activeTriggerElement = activeTriggerElement;
}
}
if (!lostActiveTriggerId && !activeTriggerId && triggerCount === 1) {
const iteratorResult = store2.context.triggerElements.entries().next();
if (!iteratorResult.done) {
const [implicitTriggerId, implicitTriggerElement] = iteratorResult.value;
stateUpdates.activeTriggerId = implicitTriggerId;
stateUpdates.activeTriggerElement = implicitTriggerElement;
}
}
if (stateUpdates.triggerCount !== void 0 || stateUpdates.activeTriggerId !== void 0 || stateUpdates.activeTriggerElement !== void 0) {
store2.update(stateUpdates);
}
if (lostActiveTriggerId) {
if (closeOnActiveTriggerUnmount) {
queueMicrotask(() => {
if (store2.select("open") && store2.select("activeTriggerId") === lostActiveTriggerId && !store2.context.triggerElements.getById(lostActiveTriggerId)) {
const eventDetails = createChangeEventDetails(reason_parts_exports.none);
store2.setOpen(false, eventDetails);
if (!eventDetails.isCanceled) {
store2.update({
activeTriggerId: null,
activeTriggerElement: null
});
}
}
});
}
}
}, [open, store2, reactiveTriggerCount, closeOnActiveTriggerUnmount]);
}
function useOpenStateTransitions(open, store2, onUnmount) {
const {
mounted,
setMounted,
transitionStatus
} = useTransitionStatus(open);
const preventUnmountingOnClose = store2.useState("preventUnmountingOnClose");
const syncedPreventUnmountingOnClose = open ? false : preventUnmountingOnClose;
store2.useSyncedValues({
mounted,
transitionStatus,
preventUnmountingOnClose: syncedPreventUnmountingOnClose
});
const forceUnmount = useStableCallback(() => {
setMounted(false);
store2.update({
activeTriggerId: null,
activeTriggerElement: null,
mounted: false,
preventUnmountingOnClose: false
});
onUnmount?.();
store2.context.onOpenChangeComplete?.(false);
});
useOpenChangeComplete({
enabled: mounted && !open && !syncedPreventUnmountingOnClose,
open,
ref: store2.context.popupRef,
onComplete() {
if (!open) {
forceUnmount();
}
}
});
return {
forceUnmount,
transitionStatus
};
}
function usePopupInteractionProps(store2, statePart) {
store2.useSyncedValues(statePart);
useIsoLayoutEffect(() => () => {
store2.update({
activeTriggerProps: EMPTY_OBJECT,
inactiveTriggerProps: EMPTY_OBJECT,
popupProps: EMPTY_OBJECT
});
}, [store2]);
}
// node_modules/@base-ui/react/utils/popups/popupTriggerMap.mjs
var PopupTriggerMap = class {
constructor() {
this.elementsSet = /* @__PURE__ */ new Set();
this.idMap = /* @__PURE__ */ new Map();
}
/**
* Adds a trigger element with the given ID.
*
* Note: The provided element is assumed to not be registered under multiple IDs.
*/
add(id, element) {
const existingElement = this.idMap.get(id);
if (existingElement === element) {
return;
}
if (existingElement !== void 0) {
this.elementsSet.delete(existingElement);
}
this.elementsSet.add(element);
this.idMap.set(id, element);
if (true) {
if (this.elementsSet.size !== this.idMap.size) {
throw new Error("Base UI: A trigger element cannot be registered under multiple IDs in PopupTriggerMap.");
}
}
}
/**
* Removes the trigger element with the given ID.
*/
delete(id) {
const element = this.idMap.get(id);
if (element) {
this.elementsSet.delete(element);
this.idMap.delete(id);
}
}
/**
* Whether the given element is registered as a trigger.
*/
hasElement(element) {
return this.elementsSet.has(element);
}
/**
* Whether there is a registered trigger element matching the given predicate.
*/
hasMatchingElement(predicate) {
for (const element of this.elementsSet) {
if (predicate(element)) {
return true;
}
}
return false;
}
/**
* Returns the trigger element associated with the given ID, or undefined if no such element exists.
*/
getById(id) {
return this.idMap.get(id);
}
/**
* Returns an iterable of all registered trigger entries, where each entry is a tuple of [id, element].
*/
entries() {
return this.idMap.entries();
}
/**
* Returns an iterable of all registered trigger elements.
*/
elements() {
return this.elementsSet.values();
}
/**
* Returns the number of registered trigger elements.
*/
get size() {
return this.idMap.size;
}
};
// node_modules/@base-ui/react/floating-ui-react/utils/getEmptyRootContext.mjs
function getEmptyRootContext() {
return new FloatingRootStore({
open: false,
transitionStatus: void 0,
floatingElement: null,
referenceElement: null,
triggerElements: new PopupTriggerMap(),
floatingId: void 0,
syncOnly: false,
nested: false,
onOpenChange: void 0
});
}
// node_modules/@base-ui/react/utils/popups/store.mjs
function createInitialPopupStoreState() {
return {
open: false,
openProp: void 0,
mounted: false,
transitionStatus: void 0,
floatingRootContext: getEmptyRootContext(),
floatingId: void 0,
triggerCount: 0,
preventUnmountingOnClose: false,
payload: void 0,
activeTriggerId: null,
activeTriggerElement: null,
triggerIdProp: void 0,
popupElement: null,
positionerElement: null,
activeTriggerProps: EMPTY_OBJECT,
inactiveTriggerProps: EMPTY_OBJECT,
popupProps: EMPTY_OBJECT
};
}
function createPopupFloatingRootContext(triggerElements, floatingId, nested = false) {
return new FloatingRootStore({
open: false,
transitionStatus: void 0,
floatingElement: null,
referenceElement: null,
triggerElements,
floatingId,
syncOnly: true,
nested,
onOpenChange: void 0
});
}
var activeTriggerIdSelector = createSelector3((state) => state.triggerIdProp ?? state.activeTriggerId);
var openSelector = createSelector3((state) => state.openProp ?? state.open);
var popupIdSelector = createSelector3((state) => {
const popupId = state.popupElement?.id ?? state.floatingId;
return popupId || void 0;
});
function triggerOwnsOpenPopup(state, triggerId) {
return triggerId !== void 0 && openSelector(state) && activeTriggerIdSelector(state) === triggerId;
}
function triggerOwnsOpenPopupOrIsOnlyTrigger(state, triggerId) {
if (triggerOwnsOpenPopup(state, triggerId)) {
return true;
}
return triggerId !== void 0 && openSelector(state) && activeTriggerIdSelector(state) == null && state.triggerCount === 1;
}
var popupStoreSelectors = {
open: openSelector,
mounted: createSelector3((state) => state.mounted),
transitionStatus: createSelector3((state) => state.transitionStatus),
floatingRootContext: createSelector3((state) => state.floatingRootContext),
triggerCount: createSelector3((state) => state.triggerCount),
preventUnmountingOnClose: createSelector3((state) => state.preventUnmountingOnClose),
payload: createSelector3((state) => state.payload),
activeTriggerId: activeTriggerIdSelector,
activeTriggerElement: createSelector3((state) => state.mounted ? state.activeTriggerElement : null),
popupId: popupIdSelector,
/**
* Whether the trigger with the given ID was used to open the popup.
*/
isTriggerActive: createSelector3((state, triggerId) => triggerId !== void 0 && activeTriggerIdSelector(state) === triggerId),
/**
* Whether the popup is open and was activated by a trigger with the given ID.
*/
isOpenedByTrigger: createSelector3((state, triggerId) => triggerOwnsOpenPopup(state, triggerId)),
/**
* Whether the popup is mounted and was activated by a trigger with the given ID.
*/
isMountedByTrigger: createSelector3((state, triggerId) => triggerId !== void 0 && activeTriggerIdSelector(state) === triggerId && state.mounted),
triggerProps: createSelector3((state, isActive) => isActive ? state.activeTriggerProps : state.inactiveTriggerProps),
/**
* Popup id for the trigger that currently owns the open popup.
*/
triggerPopupId: createSelector3((state, triggerId) => triggerOwnsOpenPopupOrIsOnlyTrigger(state, triggerId) ? popupIdSelector(state) : void 0),
popupProps: createSelector3((state) => state.popupProps),
popupElement: createSelector3((state) => state.popupElement),
positionerElement: createSelector3((state) => state.positionerElement)
};
// node_modules/@base-ui/react/floating-ui-react/hooks/useFloatingRootContext.mjs
function useFloatingRootContext(options) {
const {
open = false,
onOpenChange,
elements = {}
} = options;
const floatingId = useId();
const nested = useFloatingParentNodeId() != null;
if (true) {
const optionDomReference = elements.reference;
if (optionDomReference && !isElement(optionDomReference)) {
console.error("Cannot pass a virtual element to the `elements.reference` option,", "as it must be a real DOM element. Use `context.setPositionReference()`", "instead.");
}
}
const store2 = useRefWithInit(() => new FloatingRootStore({
open,
transitionStatus: void 0,
onOpenChange,
referenceElement: elements.reference ?? null,
floatingElement: elements.floating ?? null,
triggerElements: new PopupTriggerMap(),
floatingId,
syncOnly: false,
nested
})).current;
useIsoLayoutEffect(() => {
const valuesToSync = {
open,
floatingId
};
if (elements.reference !== void 0) {
valuesToSync.referenceElement = elements.reference;
valuesToSync.domReferenceElement = isElement(elements.reference) ? elements.reference : null;
}
if (elements.floating !== void 0) {
valuesToSync.floatingElement = elements.floating;
}
store2.update(valuesToSync);
}, [open, floatingId, elements.reference, elements.floating, store2]);
store2.context.onOpenChange = onOpenChange;
store2.context.nested = nested;
return store2;
}
// node_modules/@base-ui/react/floating-ui-react/hooks/useFloating.mjs
function useFloating2(options = {}) {
const {
nodeId,
externalTree
} = options;
const internalStore = useFloatingRootContext(options);
const store2 = options.rootContext || internalStore;
const referenceElement = store2.useState("referenceElement");
const floatingElement = store2.useState("floatingElement");
const domReferenceElement = store2.useState("domReferenceElement");
const open = store2.useState("open");
const floatingId = store2.useState("floatingId");
const [positionReference, setPositionReferenceRaw] = React39.useState(null);
const [localDomReference, setLocalDomReference] = React39.useState(void 0);
const [localFloatingElement, setLocalFloatingElement] = React39.useState(void 0);
const domReferenceRef = React39.useRef(null);
const tree = useFloatingTree(externalTree);
const storeElements = React39.useMemo(() => ({
reference: referenceElement,
floating: floatingElement,
domReference: domReferenceElement
}), [referenceElement, floatingElement, domReferenceElement]);
const position = useFloating({
...options,
elements: {
...storeElements,
...positionReference && {
reference: positionReference
}
}
});
const localDomReferenceElement = isElement(localDomReference) ? localDomReference : null;
const syncedFloatingElement = localFloatingElement === void 0 ? store2.state.floatingElement : localFloatingElement;
store2.useSyncedValue("referenceElement", localDomReference ?? null);
store2.useSyncedValue("domReferenceElement", localDomReference === void 0 ? domReferenceElement : localDomReferenceElement);
store2.useSyncedValue("floatingElement", syncedFloatingElement);
const setPositionReference = React39.useCallback((node) => {
const computedPositionReference = isElement(node) ? {
getBoundingClientRect: () => node.getBoundingClientRect(),
getClientRects: () => node.getClientRects(),
contextElement: node
} : node;
setPositionReferenceRaw(computedPositionReference);
position.refs.setReference(computedPositionReference);
}, [position.refs]);
const setReference = React39.useCallback((node) => {
if (isElement(node) || node === null) {
domReferenceRef.current = node;
setLocalDomReference(node);
}
if (isElement(position.refs.reference.current) || position.refs.reference.current === null || // Don't allow setting virtual elements using the old technique back to
// `null` to support `positionReference` + an unstable `reference`
// callback ref.
node !== null && !isElement(node)) {
position.refs.setReference(node);
}
}, [position.refs, setLocalDomReference]);
const setFloating = React39.useCallback((node) => {
setLocalFloatingElement(node);
position.refs.setFloating(node);
}, [position.refs]);
const refs = React39.useMemo(() => ({
...position.refs,
setReference,
setFloating,
setPositionReference,
domReference: domReferenceRef
}), [position.refs, setReference, setFloating, setPositionReference]);
const elements = React39.useMemo(() => ({
...position.elements,
domReference: domReferenceElement
}), [position.elements, domReferenceElement]);
const context = React39.useMemo(() => ({
...position,
dataRef: store2.context.dataRef,
open,
onOpenChange: store2.setOpen,
events: store2.context.events,
floatingId,
refs,
elements,
nodeId,
rootStore: store2
}), [position, refs, elements, nodeId, store2, open, floatingId]);
useIsoLayoutEffect(() => {
if (domReferenceElement) {
domReferenceRef.current = domReferenceElement;
}
}, [domReferenceElement]);
useIsoLayoutEffect(() => {
store2.context.dataRef.current.floatingContext = context;
const node = tree?.nodesRef.current.find((n2) => n2.id === nodeId);
if (node) {
node.context = context;
}
});
return React39.useMemo(() => ({
...position,
context,
refs,
elements,
rootStore: store2
}), [position, refs, elements, context, store2]);
}
// node_modules/@base-ui/react/floating-ui-react/hooks/useFocus.mjs
var React40 = __toESM(require_react(), 1);
var isMacSafari = parts_exports.os.mac && parts_exports.engine.webkit;
function useFocus(context, props = {}) {
const {
enabled = true,
delay
} = props;
const store2 = "rootStore" in context ? context.rootStore : context;
const {
events,
dataRef
} = store2.context;
const blockFocusRef = React40.useRef(false);
const blockedReferenceRef = React40.useRef(null);
const keyboardModalityRef = React40.useRef(true);
const timeout = useTimeout();
React40.useEffect(() => {
const domReference = store2.select("domReferenceElement");
if (!enabled) {
return void 0;
}
const win = getWindow(domReference);
function onBlur() {
const currentDomReference = store2.select("domReferenceElement");
if (!store2.select("open") && isHTMLElement(currentDomReference) && currentDomReference === activeElement(ownerDocument(currentDomReference))) {
blockFocusRef.current = true;
}
}
function onKeyDown() {
keyboardModalityRef.current = true;
}
function onPointerDown() {
keyboardModalityRef.current = false;
}
return mergeCleanups(addEventListener(win, "blur", onBlur), isMacSafari && addEventListener(win, "keydown", onKeyDown, true), isMacSafari && addEventListener(win, "pointerdown", onPointerDown, true));
}, [store2, enabled]);
React40.useEffect(() => {
if (!enabled) {
return void 0;
}
function onOpenChangeLocal(details) {
if (details.reason === reason_parts_exports.triggerPress || details.reason === reason_parts_exports.escapeKey) {
const referenceElement = store2.select("domReferenceElement");
if (isElement(referenceElement)) {
blockedReferenceRef.current = referenceElement;
blockFocusRef.current = true;
}
}
}
events.on("openchange", onOpenChangeLocal);
return () => {
events.off("openchange", onOpenChangeLocal);
};
}, [events, enabled, store2]);
const reference = React40.useMemo(() => {
function resetBlockedFocus() {
blockFocusRef.current = false;
blockedReferenceRef.current = null;
}
return {
onMouseLeave() {
resetBlockedFocus();
},
onFocus(event) {
const focusTarget = event.currentTarget;
if (blockFocusRef.current) {
if (blockedReferenceRef.current === focusTarget) {
return;
}
resetBlockedFocus();
}
const target = getTarget(event.nativeEvent);
if (isElement(target)) {
if (isMacSafari && !event.relatedTarget) {
if (!keyboardModalityRef.current && !isTypeableElement(target)) {
return;
}
} else if (!matchesFocusVisible(target)) {
return;
}
}
const movedFromOtherEnabledTrigger = isTargetInsideEnabledTrigger(event.relatedTarget, store2.context.triggerElements);
const {
nativeEvent,
currentTarget
} = event;
const delayValue = typeof delay === "function" ? delay() : delay;
if (store2.select("open") && movedFromOtherEnabledTrigger || delayValue === 0 || delayValue === void 0) {
store2.setOpen(true, createChangeEventDetails(reason_parts_exports.triggerFocus, nativeEvent, currentTarget));
return;
}
timeout.start(delayValue, () => {
if (blockFocusRef.current) {
return;
}
store2.setOpen(true, createChangeEventDetails(reason_parts_exports.triggerFocus, nativeEvent, currentTarget));
});
},
onBlur(event) {
resetBlockedFocus();
const relatedTarget = event.relatedTarget;
const nativeEvent = event.nativeEvent;
const movedToFocusGuard = isElement(relatedTarget) && relatedTarget.hasAttribute(createAttribute("focus-guard")) && relatedTarget.getAttribute("data-type") === "outside";
timeout.start(0, () => {
const domReference = store2.select("domReferenceElement");
const activeEl = activeElement(ownerDocument(domReference));
if (!relatedTarget && activeEl === domReference) {
return;
}
if (contains(dataRef.current.floatingContext?.refs.floating.current, activeEl) || contains(domReference, activeEl) || movedToFocusGuard) {
return;
}
const nextFocusedElement = relatedTarget ?? activeEl;
if (isTargetInsideEnabledTrigger(nextFocusedElement, store2.context.triggerElements)) {
return;
}
store2.setOpen(false, createChangeEventDetails(reason_parts_exports.triggerFocus, nativeEvent));
});
}
};
}, [dataRef, delay, store2, timeout]);
return React40.useMemo(() => enabled ? {
reference,
trigger: reference
} : {}, [enabled, reference]);
}
// node_modules/@base-ui/react/floating-ui-react/hooks/useHoverFloatingInteraction.mjs
var React41 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/floating-ui-react/hooks/useHoverInteractionSharedState.mjs
var HoverInteraction = class _HoverInteraction {
constructor() {
this.pointerType = void 0;
this.interactedInside = false;
this.handler = void 0;
this.blockMouseMove = true;
this.performedPointerEventsMutation = false;
this.pointerEventsScopeElement = null;
this.pointerEventsReferenceElement = null;
this.pointerEventsFloatingElement = null;
this.restTimeoutPending = false;
this.openChangeTimeout = new Timeout();
this.restTimeout = new Timeout();
this.handleCloseOptions = void 0;
}
static create() {
return new _HoverInteraction();
}
dispose = () => {
this.openChangeTimeout.clear();
this.restTimeout.clear();
};
disposeEffect = () => {
return this.dispose;
};
};
var pointerEventsMutationOwnerByScopeElement = /* @__PURE__ */ new WeakMap();
function clearSafePolygonPointerEventsMutation(instance) {
if (!instance.performedPointerEventsMutation) {
return;
}
const scopeElement = instance.pointerEventsScopeElement;
if (scopeElement && pointerEventsMutationOwnerByScopeElement.get(scopeElement) === instance) {
instance.pointerEventsScopeElement?.style.removeProperty("pointer-events");
instance.pointerEventsReferenceElement?.style.removeProperty("pointer-events");
instance.pointerEventsFloatingElement?.style.removeProperty("pointer-events");
pointerEventsMutationOwnerByScopeElement.delete(scopeElement);
}
instance.performedPointerEventsMutation = false;
instance.pointerEventsScopeElement = null;
instance.pointerEventsReferenceElement = null;
instance.pointerEventsFloatingElement = null;
}
function applySafePolygonPointerEventsMutation(instance, options) {
const {
scopeElement,
referenceElement,
floatingElement
} = options;
const existingOwner = pointerEventsMutationOwnerByScopeElement.get(scopeElement);
if (existingOwner && existingOwner !== instance) {
clearSafePolygonPointerEventsMutation(existingOwner);
}
clearSafePolygonPointerEventsMutation(instance);
instance.performedPointerEventsMutation = true;
instance.pointerEventsScopeElement = scopeElement;
instance.pointerEventsReferenceElement = referenceElement;
instance.pointerEventsFloatingElement = floatingElement;
pointerEventsMutationOwnerByScopeElement.set(scopeElement, instance);
scopeElement.style.pointerEvents = "none";
referenceElement.style.pointerEvents = "auto";
floatingElement.style.pointerEvents = "auto";
}
function useHoverInteractionSharedState(store2) {
const data = store2.context.dataRef.current;
const instance = useRefWithInit(() => data.hoverInteractionState ?? HoverInteraction.create()).current;
if (!data.hoverInteractionState) {
data.hoverInteractionState = instance;
}
useOnMount(data.hoverInteractionState.disposeEffect);
return data.hoverInteractionState;
}
// node_modules/@base-ui/react/floating-ui-react/hooks/useHoverFloatingInteraction.mjs
function useHoverFloatingInteraction(context, parameters = {}) {
const {
enabled = true,
closeDelay: closeDelayProp = 0,
nodeId: nodeIdProp
} = parameters;
const store2 = "rootStore" in context ? context.rootStore : context;
const open = store2.useState("open");
const floatingElement = store2.useState("floatingElement");
const domReferenceElement = store2.useState("domReferenceElement");
const {
dataRef
} = store2.context;
const tree = useFloatingTree();
const parentId = useFloatingParentNodeId();
const instance = useHoverInteractionSharedState(store2);
const childClosedTimeout = useTimeout();
const isClickLikeOpenEvent2 = useStableCallback(() => {
return isClickLikeOpenEvent(dataRef.current.openEvent?.type, instance.interactedInside);
});
const isHoverOpen = useStableCallback(() => {
return isHoverOpenEvent(dataRef.current.openEvent?.type);
});
const clearPointerEvents = useStableCallback(() => {
clearSafePolygonPointerEventsMutation(instance);
});
useIsoLayoutEffect(() => {
if (!open) {
instance.pointerType = void 0;
instance.restTimeoutPending = false;
instance.interactedInside = false;
clearPointerEvents();
}
}, [open, instance, clearPointerEvents]);
React41.useEffect(() => {
return clearPointerEvents;
}, [clearPointerEvents]);
useIsoLayoutEffect(() => {
if (!enabled) {
return void 0;
}
if (open && instance.handleCloseOptions?.blockPointerEvents && isHoverOpen() && isElement(domReferenceElement) && floatingElement) {
const ref = domReferenceElement;
const floatingEl = floatingElement;
const doc = ownerDocument(floatingElement);
const parentFloating = tree?.nodesRef.current.find((node) => node.id === parentId)?.context?.elements.floating;
if (parentFloating) {
parentFloating.style.pointerEvents = "";
}
const cachedScopeElement = instance.pointerEventsScopeElement !== floatingEl ? instance.pointerEventsScopeElement : null;
const parentScopeElement = parentFloating !== floatingEl ? parentFloating : null;
const scopeElement = instance.handleCloseOptions?.getScope?.() ?? cachedScopeElement ?? parentScopeElement ?? ref.closest("[data-rootownerid]") ?? doc.body;
applySafePolygonPointerEventsMutation(instance, {
scopeElement,
referenceElement: ref,
floatingElement: floatingEl
});
return () => {
clearPointerEvents();
};
}
return void 0;
}, [enabled, open, domReferenceElement, floatingElement, instance, isHoverOpen, tree, parentId, clearPointerEvents]);
React41.useEffect(() => {
if (!enabled) {
return void 0;
}
function hasParentChildren() {
return !!(tree && parentId && getNodeChildren(tree.nodesRef.current, parentId).length > 0);
}
function closeWithDelay(event) {
const closeDelay = getDelay(closeDelayProp, "close", instance.pointerType);
const close = () => {
store2.setOpen(false, createChangeEventDetails(reason_parts_exports.triggerHover, event));
tree?.events.emit("floating.closed", event);
};
if (closeDelay) {
instance.openChangeTimeout.start(closeDelay, close);
} else {
instance.openChangeTimeout.clear();
close();
}
}
function handleInteractInside(event) {
const target = getTarget(event);
if (!isInteractiveElement(target)) {
instance.interactedInside = false;
return;
}
instance.interactedInside = target?.closest("[aria-haspopup]") != null;
}
function onFloatingMouseEnter() {
instance.openChangeTimeout.clear();
childClosedTimeout.clear();
tree?.events.off("floating.closed", onNodeClosed);
clearPointerEvents();
}
function onFloatingMouseLeave(event) {
if (hasParentChildren() && tree) {
tree.events.on("floating.closed", onNodeClosed);
return;
}
if (isTargetInsideEnabledTrigger(event.relatedTarget, store2.context.triggerElements)) {
return;
}
const currentNodeId = dataRef.current.floatingContext?.nodeId ?? nodeIdProp;
const relatedTarget = event.relatedTarget;
const isMovingIntoDescendantFloating = tree && currentNodeId && isElement(relatedTarget) && getNodeChildren(tree.nodesRef.current, currentNodeId, false).some((node) => contains(node.context?.elements.floating, relatedTarget));
if (isMovingIntoDescendantFloating) {
return;
}
if (instance.handler) {
instance.handler(event);
return;
}
clearPointerEvents();
if (isHoverOpen() && !isClickLikeOpenEvent2()) {
closeWithDelay(event);
}
}
function onNodeClosed(event) {
if (!tree || !parentId || hasParentChildren()) {
return;
}
childClosedTimeout.start(0, () => {
tree.events.off("floating.closed", onNodeClosed);
store2.setOpen(false, createChangeEventDetails(reason_parts_exports.triggerHover, event));
tree.events.emit("floating.closed", event);
});
}
const floating = floatingElement;
return mergeCleanups(floating && addEventListener(floating, "mouseenter", onFloatingMouseEnter), floating && addEventListener(floating, "mouseleave", onFloatingMouseLeave), floating && addEventListener(floating, "pointerdown", handleInteractInside, true), () => {
tree?.events.off("floating.closed", onNodeClosed);
});
}, [enabled, floatingElement, store2, dataRef, closeDelayProp, nodeIdProp, isHoverOpen, isClickLikeOpenEvent2, clearPointerEvents, instance, tree, parentId, childClosedTimeout]);
}
// node_modules/@base-ui/react/floating-ui-react/hooks/useHoverReferenceInteraction.mjs
var React42 = __toESM(require_react(), 1);
var ReactDOM5 = __toESM(require_react_dom(), 1);
var EMPTY_REF = {
current: null
};
function useHoverReferenceInteraction(context, props = {}) {
const {
enabled = true,
delay = 0,
handleClose = null,
mouseOnly = false,
restMs = 0,
move = true,
triggerElementRef = EMPTY_REF,
externalTree,
isActiveTrigger = true,
getHandleCloseContext,
isClosing,
shouldOpen: shouldOpenProp
} = props;
const store2 = "rootStore" in context ? context.rootStore : context;
const {
dataRef,
events
} = store2.context;
const tree = useFloatingTree(externalTree);
const instance = useHoverInteractionSharedState(store2);
const isHoverCloseActiveRef = React42.useRef(false);
const handleCloseRef = useValueAsRef(handleClose);
const delayRef = useValueAsRef(delay);
const restMsRef = useValueAsRef(restMs);
const enabledRef = useValueAsRef(enabled);
const shouldOpenRef = useValueAsRef(shouldOpenProp);
const isClosingRef = useValueAsRef(isClosing);
const isClickLikeOpenEvent2 = useStableCallback(() => {
return isClickLikeOpenEvent(dataRef.current.openEvent?.type, instance.interactedInside);
});
const checkShouldOpen = useStableCallback(() => {
return shouldOpenRef.current?.() !== false;
});
const isOverInactiveTrigger = useStableCallback((currentDomReference, currentTarget, target) => {
const allTriggers = store2.context.triggerElements;
if (allTriggers.hasElement(currentTarget)) {
return !currentDomReference || !contains(currentDomReference, currentTarget);
}
if (!isElement(target)) {
return false;
}
const targetElement = target;
return allTriggers.hasMatchingElement((trigger) => contains(trigger, targetElement)) && (!currentDomReference || !contains(currentDomReference, targetElement));
});
const cleanupMouseMoveHandler = useStableCallback(() => {
if (!instance.handler) {
return;
}
const doc = ownerDocument(store2.select("domReferenceElement"));
doc.removeEventListener("mousemove", instance.handler);
instance.handler = void 0;
});
const clearPointerEvents = useStableCallback(() => {
clearSafePolygonPointerEventsMutation(instance);
});
if (isActiveTrigger) {
instance.handleCloseOptions = handleCloseRef.current?.__options;
}
React42.useEffect(() => cleanupMouseMoveHandler, [cleanupMouseMoveHandler]);
React42.useEffect(() => {
if (!enabled) {
return void 0;
}
function onOpenChangeLocal(details) {
if (!details.open) {
isHoverCloseActiveRef.current = details.reason === reason_parts_exports.triggerHover;
cleanupMouseMoveHandler();
instance.openChangeTimeout.clear();
instance.restTimeout.clear();
instance.blockMouseMove = true;
instance.restTimeoutPending = false;
} else {
isHoverCloseActiveRef.current = false;
}
}
events.on("openchange", onOpenChangeLocal);
return () => {
events.off("openchange", onOpenChangeLocal);
};
}, [enabled, events, instance, cleanupMouseMoveHandler]);
React42.useEffect(() => {
if (!enabled) {
return void 0;
}
function closeWithDelay(event, runElseBranch = true) {
const closeDelay = getDelay(delayRef.current, "close", instance.pointerType);
if (closeDelay) {
instance.openChangeTimeout.start(closeDelay, () => {
store2.setOpen(false, createChangeEventDetails(reason_parts_exports.triggerHover, event));
tree?.events.emit("floating.closed", event);
});
} else if (runElseBranch) {
instance.openChangeTimeout.clear();
store2.setOpen(false, createChangeEventDetails(reason_parts_exports.triggerHover, event));
tree?.events.emit("floating.closed", event);
}
}
const trigger = triggerElementRef.current ?? (isActiveTrigger ? store2.select("domReferenceElement") : null);
if (!isElement(trigger)) {
return void 0;
}
function onMouseEnter(event) {
instance.openChangeTimeout.clear();
instance.blockMouseMove = false;
if (mouseOnly && !isMouseLikePointerType(instance.pointerType)) {
return;
}
const restMsValue = getRestMs(restMsRef.current);
const openDelay = getDelay(delayRef.current, "open", instance.pointerType);
const eventTarget = getTarget(event);
const currentTarget = event.currentTarget ?? null;
const currentDomReference = store2.select("domReferenceElement");
let triggerNode = currentTarget;
if (isElement(eventTarget) && !store2.context.triggerElements.hasElement(eventTarget)) {
for (const triggerElement of store2.context.triggerElements.elements()) {
if (contains(triggerElement, eventTarget)) {
triggerNode = triggerElement;
break;
}
}
}
if (isElement(currentTarget) && isElement(currentDomReference) && !store2.context.triggerElements.hasElement(currentTarget) && contains(currentTarget, currentDomReference)) {
triggerNode = currentDomReference;
}
const isOverInactive = triggerNode == null ? false : isOverInactiveTrigger(currentDomReference, triggerNode, eventTarget);
const isOpen = store2.select("open");
const isInClosingTransition = isClosingRef.current?.() ?? store2.select("transitionStatus") === "ending";
const isHoverCloseTransition = !isOpen && isInClosingTransition && isHoverCloseActiveRef.current;
const isReenteringSameTriggerDuringCloseTransition = !isOverInactive && isElement(triggerNode) && isElement(currentDomReference) && contains(currentDomReference, triggerNode) && isHoverCloseTransition;
const isRestOnlyDelay = restMsValue > 0 && !openDelay;
const shouldOpenImmediately = isOverInactive && (isOpen || isHoverCloseTransition) || isReenteringSameTriggerDuringCloseTransition;
const shouldOpen = !isOpen || isOverInactive;
if (shouldOpenImmediately) {
if (checkShouldOpen()) {
store2.setOpen(true, createChangeEventDetails(reason_parts_exports.triggerHover, event, triggerNode));
}
return;
}
if (isRestOnlyDelay) {
return;
}
if (openDelay) {
instance.openChangeTimeout.start(openDelay, () => {
if (shouldOpen && checkShouldOpen()) {
store2.setOpen(true, createChangeEventDetails(reason_parts_exports.triggerHover, event, triggerNode));
}
});
} else if (shouldOpen) {
if (checkShouldOpen()) {
store2.setOpen(true, createChangeEventDetails(reason_parts_exports.triggerHover, event, triggerNode));
}
}
}
function onMouseLeave(event) {
if (isClickLikeOpenEvent2()) {
clearPointerEvents();
return;
}
cleanupMouseMoveHandler();
const domReferenceElement = store2.select("domReferenceElement");
const doc = ownerDocument(domReferenceElement);
instance.restTimeout.clear();
instance.restTimeoutPending = false;
const handleCloseContextBase = dataRef.current.floatingContext ?? getHandleCloseContext?.();
if (isTargetInsideEnabledTrigger(event.relatedTarget, store2.context.triggerElements)) {
return;
}
if (handleCloseRef.current && handleCloseContextBase) {
if (!store2.select("open")) {
instance.openChangeTimeout.clear();
}
const currentTrigger = triggerElementRef.current;
instance.handler = handleCloseRef.current({
...handleCloseContextBase,
tree,
x: event.clientX,
y: event.clientY,
onClose() {
clearPointerEvents();
cleanupMouseMoveHandler();
if (enabledRef.current && !isClickLikeOpenEvent2() && currentTrigger === store2.select("domReferenceElement")) {
closeWithDelay(event, true);
}
}
});
doc.addEventListener("mousemove", instance.handler);
instance.handler(event);
return;
}
const shouldClose = instance.pointerType === "touch" ? !contains(store2.select("floatingElement"), event.relatedTarget) : true;
if (shouldClose) {
closeWithDelay(event);
}
}
if (move) {
return mergeCleanups(addEventListener(trigger, "mousemove", onMouseEnter, {
once: true
}), addEventListener(trigger, "mouseenter", onMouseEnter), addEventListener(trigger, "mouseleave", onMouseLeave));
}
return mergeCleanups(addEventListener(trigger, "mouseenter", onMouseEnter), addEventListener(trigger, "mouseleave", onMouseLeave));
}, [cleanupMouseMoveHandler, clearPointerEvents, dataRef, delayRef, store2, enabled, handleCloseRef, instance, isActiveTrigger, isOverInactiveTrigger, isClickLikeOpenEvent2, mouseOnly, move, restMsRef, triggerElementRef, tree, enabledRef, getHandleCloseContext, isClosingRef, checkShouldOpen]);
return React42.useMemo(() => {
if (!enabled) {
return void 0;
}
function setPointerRef(event) {
instance.pointerType = event.pointerType;
}
return {
onPointerDown: setPointerRef,
onPointerEnter: setPointerRef,
onMouseMove(event) {
const {
nativeEvent
} = event;
const trigger = event.currentTarget;
const currentDomReference = store2.select("domReferenceElement");
const currentOpen = store2.select("open");
const isOverInactive = isOverInactiveTrigger(currentDomReference, trigger, event.target);
if (mouseOnly && !isMouseLikePointerType(instance.pointerType)) {
return;
}
if (currentOpen && isOverInactive && instance.handleCloseOptions?.blockPointerEvents) {
const floatingElement = store2.select("floatingElement");
if (floatingElement) {
const scopeElement = instance.handleCloseOptions?.getScope?.() ?? trigger.ownerDocument.body;
applySafePolygonPointerEventsMutation(instance, {
scopeElement,
referenceElement: trigger,
floatingElement
});
}
}
const restMsValue = getRestMs(restMsRef.current);
if (currentOpen && !isOverInactive || restMsValue === 0) {
return;
}
if (!isOverInactive && instance.restTimeoutPending && event.movementX ** 2 + event.movementY ** 2 < 2) {
return;
}
instance.restTimeout.clear();
function handleMouseMove() {
instance.restTimeoutPending = false;
if (isClickLikeOpenEvent2()) {
return;
}
const latestOpen = store2.select("open");
if (!instance.blockMouseMove && (!latestOpen || isOverInactive) && checkShouldOpen()) {
store2.setOpen(true, createChangeEventDetails(reason_parts_exports.triggerHover, nativeEvent, trigger));
}
}
if (instance.pointerType === "touch") {
ReactDOM5.flushSync(() => {
handleMouseMove();
});
} else if (isOverInactive && currentOpen) {
handleMouseMove();
} else {
instance.restTimeoutPending = true;
instance.restTimeout.start(restMsValue, handleMouseMove);
}
}
};
}, [enabled, instance, isClickLikeOpenEvent2, isOverInactiveTrigger, mouseOnly, store2, restMsRef, checkShouldOpen]);
}
// node_modules/@base-ui/react/floating-ui-react/hooks/useListNavigation.mjs
var React43 = __toESM(require_react(), 1);
var ESCAPE = "Escape";
function doSwitch(orientation, vertical, horizontal) {
switch (orientation) {
case "vertical":
return vertical;
case "horizontal":
return horizontal;
default:
return vertical || horizontal;
}
}
function isMainOrientationKey(key, orientation) {
const vertical = key === ARROW_UP || key === ARROW_DOWN;
const horizontal = key === ARROW_LEFT || key === ARROW_RIGHT;
return doSwitch(orientation, vertical, horizontal);
}
function isMainOrientationToEndKey(key, orientation, rtl) {
const vertical = key === ARROW_DOWN;
const horizontal = rtl ? key === ARROW_LEFT : key === ARROW_RIGHT;
return doSwitch(orientation, vertical, horizontal) || key === "Enter" || key === " " || key === "";
}
function isCrossOrientationOpenKey(key, orientation, rtl) {
const vertical = rtl ? key === ARROW_LEFT : key === ARROW_RIGHT;
const horizontal = key === ARROW_DOWN;
return doSwitch(orientation, vertical, horizontal);
}
function isCrossOrientationCloseKey(key, orientation, rtl, grid) {
const vertical = rtl ? key === ARROW_RIGHT : key === ARROW_LEFT;
const horizontal = key === ARROW_UP;
if (orientation === "both" || orientation === "horizontal" && grid) {
return key === ESCAPE;
}
return doSwitch(orientation, vertical, horizontal);
}
function useListNavigation(context, props) {
const {
listRef,
activeIndex,
onNavigate: onNavigateProp = () => {
},
enabled = true,
selectedIndex = null,
allowEscape = false,
loopFocus = false,
nested = false,
rtl = false,
virtual = false,
focusItemOnOpen = "auto",
focusItemOnHover = true,
openOnArrowKeyDown = true,
disabledIndices = void 0,
orientation = "vertical",
parentOrientation,
id,
resetOnPointerLeave = true,
externalTree,
grid: navigateGrid
} = props;
const isGrid = navigateGrid != null;
if (true) {
if (allowEscape) {
if (!loopFocus) {
console.warn("`useListNavigation` looping must be enabled to allow escaping.");
}
if (!virtual) {
console.warn("`useListNavigation` must be virtual to allow escaping.");
}
}
if (orientation === "vertical" && isGrid) {
console.warn("In grid list navigation mode, the `orientation` should", 'be either "horizontal" or "both".');
}
}
const store2 = "rootStore" in context ? context.rootStore : context;
const open = store2.useState("open");
const floatingElement = store2.useState("floatingElement");
const domReferenceElement = store2.useState("domReferenceElement");
const dataRef = store2.context.dataRef;
const floatingFocusElement = getFloatingFocusElement(floatingElement);
const typeableComboboxReference = isTypeableCombobox(domReferenceElement);
const floatingFocusElementRef = useValueAsRef(floatingFocusElement);
const parentId = useFloatingParentNodeId();
const tree = useFloatingTree(externalTree);
const focusItemOnOpenRef = React43.useRef(focusItemOnOpen);
const indexRef = React43.useRef(selectedIndex ?? -1);
const keyRef = React43.useRef(null);
const isPointerModalityRef = React43.useRef(true);
const onNavigate = useStableCallback((event) => {
onNavigateProp(indexRef.current === -1 ? null : indexRef.current, event);
});
const previousMountedRef = React43.useRef(!!floatingElement);
const previousOpenRef = React43.useRef(open);
const forceSyncFocusRef = React43.useRef(false);
const forceScrollIntoViewRef = React43.useRef(false);
const cancelQueuedFocusRef = React43.useRef(null);
const disabledIndicesRef = useValueAsRef(disabledIndices);
const latestOpenRef = useValueAsRef(open);
const selectedIndexRef = useValueAsRef(selectedIndex);
const resetOnPointerLeaveRef = useValueAsRef(resetOnPointerLeave);
const focusFrame = useAnimationFrame();
const waitForListPopulatedFrame = useAnimationFrame();
const focusItem = useStableCallback(() => {
function runFocus(item2) {
if (virtual) {
tree?.events.emit("virtualfocus", item2);
} else {
cancelQueuedFocusRef.current = enqueueFocus(item2, {
sync: forceSyncFocusRef.current,
preventScroll: true
});
}
}
const initialItem = listRef.current[indexRef.current];
const forceScrollIntoView = forceScrollIntoViewRef.current;
if (initialItem) {
runFocus(initialItem);
}
const scheduler2 = forceSyncFocusRef.current ? (callback) => callback() : (callback) => focusFrame.request(callback);
scheduler2(() => {
const waitedItem = listRef.current[indexRef.current] || initialItem;
if (!waitedItem) {
return;
}
if (!initialItem) {
runFocus(waitedItem);
}
const shouldScrollIntoView = (
// eslint-disable-next-line @typescript-eslint/no-use-before-define
item && (forceScrollIntoView || !isPointerModalityRef.current)
);
if (shouldScrollIntoView) {
waitedItem.scrollIntoView?.({
block: "nearest",
inline: "nearest"
});
}
});
});
useIsoLayoutEffect(() => {
dataRef.current.orientation = orientation;
}, [dataRef, orientation]);
useIsoLayoutEffect(() => {
if (!enabled) {
return;
}
if (open && floatingElement) {
indexRef.current = selectedIndex ?? -1;
if (focusItemOnOpenRef.current && selectedIndex != null) {
forceScrollIntoViewRef.current = true;
onNavigate();
}
} else if (previousMountedRef.current) {
indexRef.current = -1;
onNavigate();
}
}, [enabled, open, floatingElement, selectedIndex, onNavigate]);
useIsoLayoutEffect(() => {
if (!enabled) {
return;
}
if (!open) {
forceSyncFocusRef.current = false;
return;
}
if (!floatingElement) {
return;
}
if (activeIndex == null) {
forceSyncFocusRef.current = false;
if (selectedIndexRef.current != null) {
return;
}
if (previousMountedRef.current) {
indexRef.current = -1;
focusItem();
}
if ((!previousOpenRef.current || !previousMountedRef.current) && focusItemOnOpenRef.current && (keyRef.current != null || focusItemOnOpenRef.current === true && keyRef.current == null)) {
let runs = 0;
const waitForListPopulated = () => {
if (listRef.current[0] == null) {
if (runs < 2) {
const scheduler2 = runs ? (callback) => waitForListPopulatedFrame.request(callback) : queueMicrotask;
scheduler2(waitForListPopulated);
}
runs += 1;
} else {
indexRef.current = keyRef.current == null || isMainOrientationToEndKey(keyRef.current, orientation, rtl) || nested ? getMinListIndex(listRef) : getMaxListIndex(listRef);
keyRef.current = null;
onNavigate();
}
};
waitForListPopulated();
}
} else if (!isIndexOutOfListBounds(listRef.current, activeIndex)) {
indexRef.current = activeIndex;
focusItem();
forceScrollIntoViewRef.current = false;
}
}, [enabled, open, floatingElement, activeIndex, selectedIndexRef, nested, listRef, orientation, rtl, onNavigate, focusItem, waitForListPopulatedFrame]);
useIsoLayoutEffect(() => {
if (!enabled || floatingElement || !tree || virtual || !previousMountedRef.current) {
return;
}
const nodes = tree.nodesRef.current;
const parent = nodes.find((node) => node.id === parentId)?.context?.elements.floating;
const activeEl = activeElement(ownerDocument(domReferenceElement ?? parent ?? null));
const treeContainsActiveEl = nodes.some((node) => node.context && contains(node.context.elements.floating, activeEl));
if (parent && !treeContainsActiveEl && isPointerModalityRef.current) {
parent.focus({
preventScroll: true
});
}
}, [enabled, floatingElement, domReferenceElement, tree, parentId, virtual]);
useIsoLayoutEffect(() => {
previousOpenRef.current = open;
previousMountedRef.current = !!floatingElement;
});
useIsoLayoutEffect(() => {
if (!open) {
keyRef.current = null;
focusItemOnOpenRef.current = focusItemOnOpen;
}
}, [open, focusItemOnOpen]);
const hasActiveIndex = activeIndex != null;
const syncCurrentTarget = useStableCallback((event) => {
if (!latestOpenRef.current) {
return;
}
const index2 = listRef.current.indexOf(event.currentTarget);
if (index2 !== -1 && (indexRef.current !== index2 || activeIndex !== index2)) {
indexRef.current = index2;
onNavigate(event);
}
});
const getParentOrientation = useStableCallback(() => {
return parentOrientation ?? tree?.nodesRef.current.find((node) => node.id === parentId)?.context?.dataRef?.current.orientation;
});
const getMinEnabledIndex = useStableCallback(() => {
return getMinListIndex(listRef, disabledIndicesRef.current);
});
const commonOnKeyDown = useStableCallback((event) => {
isPointerModalityRef.current = false;
forceSyncFocusRef.current = true;
if (event.which === 229) {
return;
}
if (!latestOpenRef.current && event.currentTarget === floatingFocusElementRef.current) {
return;
}
if (nested && isCrossOrientationCloseKey(event.key, orientation, rtl, isGrid)) {
if (!isMainOrientationKey(event.key, getParentOrientation())) {
stopEvent(event);
}
store2.setOpen(false, createChangeEventDetails(reason_parts_exports.listNavigation, event.nativeEvent));
if (isHTMLElement(domReferenceElement)) {
if (virtual) {
tree?.events.emit("virtualfocus", domReferenceElement);
} else {
domReferenceElement.focus();
}
}
return;
}
const currentIndex = indexRef.current;
const minIndex = getMinListIndex(listRef, disabledIndices);
const maxIndex = getMaxListIndex(listRef, disabledIndices);
if (!typeableComboboxReference) {
if (event.key === "Home") {
stopEvent(event);
indexRef.current = minIndex;
onNavigate(event);
}
if (event.key === "End") {
stopEvent(event);
indexRef.current = maxIndex;
onNavigate(event);
}
}
if (navigateGrid != null) {
const index2 = navigateGrid(event, indexRef.current, listRef, orientation, loopFocus, rtl, disabledIndices, minIndex, maxIndex);
if (index2 != null) {
indexRef.current = index2;
onNavigate(event);
}
if (orientation === "both") {
return;
}
}
if (isMainOrientationKey(event.key, orientation)) {
stopEvent(event);
if (open && !virtual && activeElement(event.currentTarget.ownerDocument) === event.currentTarget) {
indexRef.current = isMainOrientationToEndKey(event.key, orientation, rtl) ? minIndex : maxIndex;
onNavigate(event);
return;
}
if (isMainOrientationToEndKey(event.key, orientation, rtl)) {
if (loopFocus) {
if (currentIndex >= maxIndex) {
if (allowEscape && currentIndex !== listRef.current.length) {
indexRef.current = -1;
} else {
forceSyncFocusRef.current = false;
indexRef.current = minIndex;
}
} else {
indexRef.current = findNonDisabledListIndex(listRef.current, {
startingIndex: currentIndex,
disabledIndices
});
}
} else {
indexRef.current = Math.min(maxIndex, findNonDisabledListIndex(listRef.current, {
startingIndex: currentIndex,
disabledIndices
}));
}
} else if (loopFocus) {
if (currentIndex <= minIndex) {
if (allowEscape && currentIndex !== -1) {
indexRef.current = listRef.current.length;
} else {
forceSyncFocusRef.current = false;
indexRef.current = maxIndex;
}
} else {
indexRef.current = findNonDisabledListIndex(listRef.current, {
startingIndex: currentIndex,
decrement: true,
disabledIndices
});
}
} else {
indexRef.current = Math.max(minIndex, findNonDisabledListIndex(listRef.current, {
startingIndex: currentIndex,
decrement: true,
disabledIndices
}));
}
if (isIndexOutOfListBounds(listRef.current, indexRef.current)) {
indexRef.current = -1;
}
onNavigate(event);
}
});
const item = React43.useMemo(() => {
const itemProps = {
onFocus(event) {
forceSyncFocusRef.current = true;
syncCurrentTarget(event);
},
onClick: ({
currentTarget
}) => currentTarget.focus({
preventScroll: true
}),
// Safari
onMouseMove(event) {
forceSyncFocusRef.current = true;
forceScrollIntoViewRef.current = false;
if (focusItemOnHover) {
syncCurrentTarget(event);
}
},
onPointerLeave(event) {
if (!latestOpenRef.current || !isPointerModalityRef.current || event.pointerType === "touch") {
return;
}
forceSyncFocusRef.current = true;
const relatedTarget = event.relatedTarget;
if (!focusItemOnHover || listRef.current.includes(relatedTarget)) {
return;
}
if (!resetOnPointerLeaveRef.current) {
return;
}
cancelQueuedFocusRef.current?.();
cancelQueuedFocusRef.current = null;
indexRef.current = -1;
onNavigate(event);
if (!virtual) {
const floatingFocusEl = floatingFocusElementRef.current;
const activeEl = activeElement(ownerDocument(floatingFocusEl));
if (floatingFocusEl && contains(floatingFocusEl, activeEl)) {
floatingFocusEl.focus({
preventScroll: true
});
}
}
}
};
return itemProps;
}, [syncCurrentTarget, latestOpenRef, floatingFocusElementRef, focusItemOnHover, listRef, onNavigate, resetOnPointerLeaveRef, virtual]);
const ariaActiveDescendantProp = React43.useMemo(() => {
return virtual && open && hasActiveIndex && {
"aria-activedescendant": `${id}-${activeIndex}`
};
}, [virtual, open, hasActiveIndex, id, activeIndex]);
const floating = React43.useMemo(() => {
return {
"aria-orientation": orientation === "both" ? void 0 : orientation,
...!typeableComboboxReference ? ariaActiveDescendantProp : {},
onKeyDown(event) {
if (event.key === "Tab" && event.shiftKey && open && !virtual) {
const target = getTarget(event.nativeEvent);
if (target && !contains(floatingFocusElementRef.current, target)) {
return;
}
stopEvent(event);
store2.setOpen(false, createChangeEventDetails(reason_parts_exports.focusOut, event.nativeEvent));
if (isHTMLElement(domReferenceElement)) {
domReferenceElement.focus();
}
return;
}
commonOnKeyDown(event);
},
onPointerMove() {
isPointerModalityRef.current = true;
}
};
}, [ariaActiveDescendantProp, commonOnKeyDown, floatingFocusElementRef, orientation, typeableComboboxReference, store2, open, virtual, domReferenceElement]);
const trigger = React43.useMemo(() => {
function openOnNavigationKeyDown(event) {
store2.setOpen(true, createChangeEventDetails(reason_parts_exports.listNavigation, event.nativeEvent, event.currentTarget));
}
function checkVirtualMouse(event) {
if (focusItemOnOpen === "auto" && isVirtualClick(event.nativeEvent)) {
focusItemOnOpenRef.current = !virtual;
}
}
function checkVirtualPointer(event) {
focusItemOnOpenRef.current = focusItemOnOpen;
if (focusItemOnOpen === "auto" && isVirtualPointerEvent(event.nativeEvent)) {
focusItemOnOpenRef.current = true;
}
}
return {
onKeyDown(event) {
const currentOpen = store2.select("open");
isPointerModalityRef.current = false;
const isArrowKey = event.key.startsWith("Arrow");
const isParentCrossOpenKey = isCrossOrientationOpenKey(event.key, getParentOrientation(), rtl);
const isMainKey = isMainOrientationKey(event.key, orientation);
const isNavigationKey = (nested ? isParentCrossOpenKey : isMainKey) || event.key === "Enter" || event.key.trim() === "";
if (virtual && currentOpen) {
return commonOnKeyDown(event);
}
if (!currentOpen && !openOnArrowKeyDown && isArrowKey) {
return void 0;
}
if (isNavigationKey) {
const isParentMainKey = isMainOrientationKey(event.key, getParentOrientation());
keyRef.current = nested && isParentMainKey ? null : event.key;
}
if (nested) {
if (isParentCrossOpenKey) {
stopEvent(event);
if (currentOpen) {
indexRef.current = getMinEnabledIndex();
onNavigate(event);
} else {
openOnNavigationKeyDown(event);
}
}
return void 0;
}
if (isMainKey) {
if (selectedIndexRef.current != null) {
indexRef.current = selectedIndexRef.current;
}
stopEvent(event);
if (!currentOpen && openOnArrowKeyDown) {
openOnNavigationKeyDown(event);
} else {
commonOnKeyDown(event);
}
if (currentOpen) {
onNavigate(event);
}
}
return void 0;
},
onFocus(event) {
if (store2.select("open") && !virtual) {
indexRef.current = -1;
onNavigate(event);
}
},
onPointerDown: checkVirtualPointer,
onPointerEnter: checkVirtualPointer,
onMouseDown: checkVirtualMouse,
onClick: checkVirtualMouse
};
}, [commonOnKeyDown, focusItemOnOpen, getMinEnabledIndex, nested, onNavigate, store2, openOnArrowKeyDown, orientation, getParentOrientation, rtl, selectedIndexRef, virtual]);
const reference = React43.useMemo(() => {
return {
...ariaActiveDescendantProp,
...trigger
};
}, [ariaActiveDescendantProp, trigger]);
return React43.useMemo(() => enabled ? {
reference,
floating,
item,
trigger
} : {}, [enabled, reference, floating, trigger, item]);
}
// node_modules/@base-ui/react/floating-ui-react/hooks/useTypeahead.mjs
var React44 = __toESM(require_react(), 1);
function useTypeahead(context, props) {
const {
listRef,
elementsRef,
activeIndex,
onMatch: onMatchProp,
disabledIndices,
onTyping,
enabled = true,
resetMs = 750,
selectedIndex = null
} = props;
const store2 = "rootStore" in context ? context.rootStore : context;
const open = store2.useState("open");
const timeout = useTimeout();
const stringRef = React44.useRef("");
const prevIndexRef = React44.useRef(selectedIndex ?? activeIndex ?? -1);
const matchIndexRef = React44.useRef(null);
const onKeyDown = useStableCallback((event) => {
function isVisible(index3) {
const element = elementsRef?.current[index3];
return !element || isElementVisible2(element);
}
function isItemAvailable(index3) {
if (!isVisible(index3)) {
return false;
}
return disabledIndices == null || !isListIndexDisabled(EMPTY_ARRAY5, index3, disabledIndices);
}
function getMatchingIndex(list, string, startIndex2 = 0) {
if (list.length === 0) {
return -1;
}
const normalizedStartIndex = (startIndex2 % list.length + list.length) % list.length;
const lowerString = string.toLowerCase();
for (let offset4 = 0; offset4 < list.length; offset4 += 1) {
const index3 = (normalizedStartIndex + offset4) % list.length;
const text = list[index3];
if (!text?.toLowerCase().startsWith(lowerString) || !isItemAvailable(index3)) {
continue;
}
return index3;
}
return -1;
}
const listContent = listRef.current;
if (stringRef.current.length > 0 && event.key === " ") {
stopEvent(event);
onTyping?.(true);
}
if (stringRef.current.length > 0 && stringRef.current[0] !== " ") {
if (getMatchingIndex(listContent, stringRef.current) === -1 && event.key !== " ") {
onTyping?.(false);
}
}
if (listContent == null || // Character key.
event.key.length !== 1 || // Modifier key.
event.ctrlKey || event.metaKey || event.altKey) {
return;
}
if (open && event.key !== " ") {
stopEvent(event);
onTyping?.(true);
}
const isNewSession = stringRef.current === "";
if (isNewSession) {
prevIndexRef.current = selectedIndex ?? activeIndex ?? -1;
}
const allowRapidSuccessionOfFirstLetter = listContent.every((text, index3) => text && isItemAvailable(index3) ? text[0]?.toLowerCase() !== text[1]?.toLowerCase() : true);
if (allowRapidSuccessionOfFirstLetter && stringRef.current === event.key) {
stringRef.current = "";
prevIndexRef.current = matchIndexRef.current;
}
stringRef.current += event.key;
timeout.start(resetMs, () => {
stringRef.current = "";
prevIndexRef.current = matchIndexRef.current;
onTyping?.(false);
});
const prevIndex = isNewSession ? selectedIndex ?? activeIndex ?? -1 : prevIndexRef.current;
const startIndex = (prevIndex ?? 0) + 1;
const index2 = getMatchingIndex(listContent, stringRef.current, startIndex);
if (index2 !== -1) {
onMatchProp?.(index2);
matchIndexRef.current = index2;
} else if (event.key !== " ") {
stringRef.current = "";
onTyping?.(false);
}
});
const onBlur = useStableCallback((event) => {
const next = event.relatedTarget;
const currentDomReferenceElement = store2.select("domReferenceElement");
const currentFloatingElement = store2.select("floatingElement");
const withinComposite = contains(currentDomReferenceElement, next) || contains(currentFloatingElement, next);
if (withinComposite) {
return;
}
timeout.clear();
stringRef.current = "";
prevIndexRef.current = matchIndexRef.current;
onTyping?.(false);
});
useIsoLayoutEffect(() => {
if (!open && selectedIndex !== null) {
return;
}
timeout.clear();
matchIndexRef.current = null;
if (stringRef.current !== "") {
stringRef.current = "";
}
}, [open, selectedIndex, timeout]);
useIsoLayoutEffect(() => {
if (open && stringRef.current === "") {
prevIndexRef.current = selectedIndex ?? activeIndex ?? -1;
}
}, [open, selectedIndex, activeIndex]);
const sharedProps = React44.useMemo(() => ({
onKeyDown,
onBlur
}), [onKeyDown, onBlur]);
return React44.useMemo(() => enabled ? {
reference: sharedProps,
floating: sharedProps
} : {}, [enabled, sharedProps]);
}
// node_modules/@base-ui/react/floating-ui-react/safePolygon.mjs
var CURSOR_SPEED_THRESHOLD = 0.1;
var CURSOR_SPEED_THRESHOLD_SQUARED = CURSOR_SPEED_THRESHOLD * CURSOR_SPEED_THRESHOLD;
var POLYGON_BUFFER = 0.5;
function hasIntersectingEdge(pointX, pointY, xi, yi, xj, yj) {
return yi >= pointY !== yj >= pointY && pointX <= (xj - xi) * (pointY - yi) / (yj - yi) + xi;
}
function isPointInQuadrilateral(pointX, pointY, x1, y1, x2, y2, x3, y3, x4, y4) {
let isInsideValue = false;
if (hasIntersectingEdge(pointX, pointY, x1, y1, x2, y2)) {
isInsideValue = !isInsideValue;
}
if (hasIntersectingEdge(pointX, pointY, x2, y2, x3, y3)) {
isInsideValue = !isInsideValue;
}
if (hasIntersectingEdge(pointX, pointY, x3, y3, x4, y4)) {
isInsideValue = !isInsideValue;
}
if (hasIntersectingEdge(pointX, pointY, x4, y4, x1, y1)) {
isInsideValue = !isInsideValue;
}
return isInsideValue;
}
function isInsideRect(pointX, pointY, rect) {
return pointX >= rect.x && pointX <= rect.x + rect.width && pointY >= rect.y && pointY <= rect.y + rect.height;
}
function isInsideAxisAlignedRect(pointX, pointY, x1, y1, x2, y2) {
const minX = Math.min(x1, x2);
const maxX = Math.max(x1, x2);
const minY = Math.min(y1, y2);
const maxY = Math.max(y1, y2);
return pointX >= minX && pointX <= maxX && pointY >= minY && pointY <= maxY;
}
function safePolygon(options = {}) {
const {
blockPointerEvents = false
} = options;
const timeout = new Timeout();
const fn = ({
x: x2,
y: y2,
placement,
elements,
onClose,
nodeId,
tree
}) => {
const side = placement?.split("-")[0];
let hasLanded = false;
let lastX = null;
let lastY = null;
let lastCursorTime = typeof performance !== "undefined" ? performance.now() : 0;
function isCursorMovingSlowly(nextX, nextY) {
const currentTime = performance.now();
const elapsedTime = currentTime - lastCursorTime;
if (lastX === null || lastY === null || elapsedTime === 0) {
lastX = nextX;
lastY = nextY;
lastCursorTime = currentTime;
return false;
}
const deltaX = nextX - lastX;
const deltaY = nextY - lastY;
const distanceSquared = deltaX * deltaX + deltaY * deltaY;
const thresholdSquared = elapsedTime * elapsedTime * CURSOR_SPEED_THRESHOLD_SQUARED;
lastX = nextX;
lastY = nextY;
lastCursorTime = currentTime;
return distanceSquared < thresholdSquared;
}
function close() {
timeout.clear();
onClose();
}
return function onMouseMove(event) {
timeout.clear();
const domReference = elements.domReference;
const floating = elements.floating;
if (!domReference || !floating || side == null || x2 == null || y2 == null) {
return void 0;
}
const {
clientX,
clientY
} = event;
const target = getTarget(event);
const isLeave = event.type === "mouseleave";
const isOverFloatingEl = contains(floating, target);
const isOverReferenceEl = contains(domReference, target);
if (isOverFloatingEl) {
hasLanded = true;
if (!isLeave) {
return void 0;
}
}
if (isOverReferenceEl) {
hasLanded = false;
if (!isLeave) {
hasLanded = true;
return void 0;
}
}
if (isLeave && isElement(event.relatedTarget) && contains(floating, event.relatedTarget)) {
return void 0;
}
function hasOpenChildNode() {
return Boolean(tree && getNodeChildren(tree.nodesRef.current, nodeId).length > 0);
}
function closeIfNoOpenChild() {
if (!hasOpenChildNode()) {
close();
}
}
if (hasOpenChildNode()) {
return void 0;
}
const refRect = domReference.getBoundingClientRect();
const rect = floating.getBoundingClientRect();
const cursorLeaveFromRight = x2 > rect.right - rect.width / 2;
const cursorLeaveFromBottom = y2 > rect.bottom - rect.height / 2;
const isFloatingWider = rect.width > refRect.width;
const isFloatingTaller = rect.height > refRect.height;
const left = (isFloatingWider ? refRect : rect).left;
const right = (isFloatingWider ? refRect : rect).right;
const top = (isFloatingTaller ? refRect : rect).top;
const bottom = (isFloatingTaller ? refRect : rect).bottom;
if (side === "top" && y2 >= refRect.bottom - 1 || side === "bottom" && y2 <= refRect.top + 1 || side === "left" && x2 >= refRect.right - 1 || side === "right" && x2 <= refRect.left + 1) {
closeIfNoOpenChild();
return void 0;
}
let isInsideTroughRect = false;
switch (side) {
case "top":
isInsideTroughRect = isInsideAxisAlignedRect(clientX, clientY, left, refRect.top + 1, right, rect.bottom - 1);
break;
case "bottom":
isInsideTroughRect = isInsideAxisAlignedRect(clientX, clientY, left, rect.top + 1, right, refRect.bottom - 1);
break;
case "left":
isInsideTroughRect = isInsideAxisAlignedRect(clientX, clientY, rect.right - 1, bottom, refRect.left + 1, top);
break;
case "right":
isInsideTroughRect = isInsideAxisAlignedRect(clientX, clientY, refRect.right - 1, bottom, rect.left + 1, top);
break;
default:
}
if (isInsideTroughRect) {
return void 0;
}
if (hasLanded && !isInsideRect(clientX, clientY, refRect)) {
closeIfNoOpenChild();
return void 0;
}
if (!isLeave && isCursorMovingSlowly(clientX, clientY)) {
closeIfNoOpenChild();
return void 0;
}
let isInsidePolygon = false;
switch (side) {
case "top": {
const cursorXOffset = isFloatingWider ? POLYGON_BUFFER / 2 : POLYGON_BUFFER * 4;
const cursorPointOneX = isFloatingWider ? x2 + cursorXOffset : cursorLeaveFromRight ? x2 + cursorXOffset : x2 - cursorXOffset;
const cursorPointTwoX = isFloatingWider ? x2 - cursorXOffset : cursorLeaveFromRight ? x2 + cursorXOffset : x2 - cursorXOffset;
const cursorPointY = y2 + POLYGON_BUFFER + 1;
const commonYLeft = cursorLeaveFromRight ? rect.bottom - POLYGON_BUFFER : isFloatingWider ? rect.bottom - POLYGON_BUFFER : rect.top;
const commonYRight = cursorLeaveFromRight ? isFloatingWider ? rect.bottom - POLYGON_BUFFER : rect.top : rect.bottom - POLYGON_BUFFER;
isInsidePolygon = isPointInQuadrilateral(clientX, clientY, cursorPointOneX, cursorPointY, cursorPointTwoX, cursorPointY, rect.left, commonYLeft, rect.right, commonYRight);
break;
}
case "bottom": {
const cursorXOffset = isFloatingWider ? POLYGON_BUFFER / 2 : POLYGON_BUFFER * 4;
const cursorPointOneX = isFloatingWider ? x2 + cursorXOffset : cursorLeaveFromRight ? x2 + cursorXOffset : x2 - cursorXOffset;
const cursorPointTwoX = isFloatingWider ? x2 - cursorXOffset : cursorLeaveFromRight ? x2 + cursorXOffset : x2 - cursorXOffset;
const cursorPointY = y2 - POLYGON_BUFFER;
const commonYLeft = cursorLeaveFromRight ? rect.top + POLYGON_BUFFER : isFloatingWider ? rect.top + POLYGON_BUFFER : rect.bottom;
const commonYRight = cursorLeaveFromRight ? isFloatingWider ? rect.top + POLYGON_BUFFER : rect.bottom : rect.top + POLYGON_BUFFER;
isInsidePolygon = isPointInQuadrilateral(clientX, clientY, cursorPointOneX, cursorPointY, cursorPointTwoX, cursorPointY, rect.left, commonYLeft, rect.right, commonYRight);
break;
}
case "left": {
const cursorYOffset = isFloatingTaller ? POLYGON_BUFFER / 2 : POLYGON_BUFFER * 4;
const cursorPointOneY = isFloatingTaller ? y2 + cursorYOffset : cursorLeaveFromBottom ? y2 + cursorYOffset : y2 - cursorYOffset;
const cursorPointTwoY = isFloatingTaller ? y2 - cursorYOffset : cursorLeaveFromBottom ? y2 + cursorYOffset : y2 - cursorYOffset;
const cursorPointX = x2 + POLYGON_BUFFER + 1;
const commonXTop = cursorLeaveFromBottom ? rect.right - POLYGON_BUFFER : isFloatingTaller ? rect.right - POLYGON_BUFFER : rect.left;
const commonXBottom = cursorLeaveFromBottom ? isFloatingTaller ? rect.right - POLYGON_BUFFER : rect.left : rect.right - POLYGON_BUFFER;
isInsidePolygon = isPointInQuadrilateral(clientX, clientY, commonXTop, rect.top, commonXBottom, rect.bottom, cursorPointX, cursorPointOneY, cursorPointX, cursorPointTwoY);
break;
}
case "right": {
const cursorYOffset = isFloatingTaller ? POLYGON_BUFFER / 2 : POLYGON_BUFFER * 4;
const cursorPointOneY = isFloatingTaller ? y2 + cursorYOffset : cursorLeaveFromBottom ? y2 + cursorYOffset : y2 - cursorYOffset;
const cursorPointTwoY = isFloatingTaller ? y2 - cursorYOffset : cursorLeaveFromBottom ? y2 + cursorYOffset : y2 - cursorYOffset;
const cursorPointX = x2 - POLYGON_BUFFER;
const commonXTop = cursorLeaveFromBottom ? rect.left + POLYGON_BUFFER : isFloatingTaller ? rect.left + POLYGON_BUFFER : rect.right;
const commonXBottom = cursorLeaveFromBottom ? isFloatingTaller ? rect.left + POLYGON_BUFFER : rect.right : rect.left + POLYGON_BUFFER;
isInsidePolygon = isPointInQuadrilateral(clientX, clientY, cursorPointX, cursorPointOneY, cursorPointX, cursorPointTwoY, commonXTop, rect.top, commonXBottom, rect.bottom);
break;
}
default:
}
if (!isInsidePolygon) {
closeIfNoOpenChild();
} else if (!hasLanded) {
timeout.start(40, closeIfNoOpenChild);
}
return void 0;
};
};
fn.__options = {
...options,
blockPointerEvents
};
return fn;
}
// node_modules/@base-ui/react/utils/popupStateMapping.mjs
var CommonPopupDataAttributes = (function(CommonPopupDataAttributes2) {
CommonPopupDataAttributes2["open"] = "data-open";
CommonPopupDataAttributes2["closed"] = "data-closed";
CommonPopupDataAttributes2[CommonPopupDataAttributes2["startingStyle"] = TransitionStatusDataAttributes.startingStyle] = "startingStyle";
CommonPopupDataAttributes2[CommonPopupDataAttributes2["endingStyle"] = TransitionStatusDataAttributes.endingStyle] = "endingStyle";
CommonPopupDataAttributes2["anchorHidden"] = "data-anchor-hidden";
CommonPopupDataAttributes2["side"] = "data-side";
CommonPopupDataAttributes2["align"] = "data-align";
return CommonPopupDataAttributes2;
})({});
var CommonTriggerDataAttributes = /* @__PURE__ */ (function(CommonTriggerDataAttributes2) {
CommonTriggerDataAttributes2["popupOpen"] = "data-popup-open";
CommonTriggerDataAttributes2["pressed"] = "data-pressed";
return CommonTriggerDataAttributes2;
})({});
var TRIGGER_HOOK = {
[CommonTriggerDataAttributes.popupOpen]: ""
};
var PRESSABLE_TRIGGER_HOOK = {
[CommonTriggerDataAttributes.popupOpen]: "",
[CommonTriggerDataAttributes.pressed]: ""
};
var POPUP_OPEN_HOOK = {
[CommonPopupDataAttributes.open]: ""
};
var POPUP_CLOSED_HOOK = {
[CommonPopupDataAttributes.closed]: ""
};
var ANCHOR_HIDDEN_HOOK = {
[CommonPopupDataAttributes.anchorHidden]: ""
};
var triggerOpenStateMapping2 = {
open(value) {
if (value) {
return TRIGGER_HOOK;
}
return null;
}
};
var pressableTriggerOpenStateMapping = {
open(value) {
if (value) {
return PRESSABLE_TRIGGER_HOOK;
}
return null;
}
};
var popupStateMapping = {
open(value) {
if (value) {
return POPUP_OPEN_HOOK;
}
return POPUP_CLOSED_HOOK;
},
anchorHidden(value) {
if (value) {
return ANCHOR_HIDDEN_HOOK;
}
return null;
}
};
// node_modules/@base-ui/react/internals/composite/composite.mjs
var ARROW_UP2 = "ArrowUp";
var ARROW_DOWN2 = "ArrowDown";
var ARROW_LEFT2 = "ArrowLeft";
var ARROW_RIGHT2 = "ArrowRight";
var HOME = "Home";
var END = "End";
var HORIZONTAL_KEYS = /* @__PURE__ */ new Set([ARROW_LEFT2, ARROW_RIGHT2]);
var VERTICAL_KEYS = /* @__PURE__ */ new Set([ARROW_UP2, ARROW_DOWN2]);
var ARROW_KEYS = /* @__PURE__ */ new Set([...HORIZONTAL_KEYS, ...VERTICAL_KEYS]);
var COMPOSITE_KEYS = /* @__PURE__ */ new Set([...ARROW_KEYS, HOME, END]);
// node_modules/@base-ui/utils/inertValue.mjs
function inertValue(value) {
if (isReactVersionAtLeast(19)) {
return value;
}
return value ? "true" : void 0;
}
// node_modules/@base-ui/react/utils/InternalBackdrop.mjs
var React45 = __toESM(require_react(), 1);
var import_jsx_runtime158 = __toESM(require_jsx_runtime(), 1);
var InternalBackdrop = /* @__PURE__ */ React45.forwardRef(function InternalBackdrop2(props, ref) {
const {
cutout,
...otherProps
} = props;
let clipPath;
if (cutout) {
const rect = cutout.getBoundingClientRect();
clipPath = `polygon(0% 0%,100% 0%,100% 100%,0% 100%,0% 0%,${rect.left}px ${rect.top}px,${rect.left}px ${rect.bottom}px,${rect.right}px ${rect.bottom}px,${rect.right}px ${rect.top}px,${rect.left}px ${rect.top}px)`;
}
return /* @__PURE__ */ (0, import_jsx_runtime158.jsx)("div", {
ref,
role: "presentation",
"data-base-ui-inert": "",
...otherProps,
style: {
position: "fixed",
inset: 0,
userSelect: "none",
WebkitUserSelect: "none",
clipPath
}
});
});
if (true) InternalBackdrop.displayName = "InternalBackdrop";
// node_modules/@base-ui/react/utils/useOpenInteractionType.mjs
var React48 = __toESM(require_react(), 1);
// node_modules/@base-ui/utils/useEnhancedClickHandler.mjs
var React46 = __toESM(require_react(), 1);
function useEnhancedClickHandler(handler) {
const lastClickInteractionTypeRef = React46.useRef("");
const handlePointerDown = React46.useCallback((event) => {
if (event.defaultPrevented) {
return;
}
lastClickInteractionTypeRef.current = event.pointerType;
handler(event, event.pointerType);
}, [handler]);
const handleClick = React46.useCallback((event) => {
if (event.detail === 0) {
handler(event, "keyboard");
return;
}
if ("pointerType" in event) {
handler(event, event.pointerType);
} else {
handler(event, lastClickInteractionTypeRef.current);
}
lastClickInteractionTypeRef.current = "";
}, [handler]);
return {
onClick: handleClick,
onPointerDown: handlePointerDown
};
}
// node_modules/@base-ui/react/internals/useValueChanged.mjs
var React47 = __toESM(require_react(), 1);
function useValueChanged(value, onChange) {
const valueRef = React47.useRef(value);
const onChangeCallback = useStableCallback(onChange);
useIsoLayoutEffect(() => {
if (valueRef.current === value) {
return;
}
onChangeCallback(valueRef.current);
}, [value, onChangeCallback]);
useIsoLayoutEffect(() => {
valueRef.current = value;
}, [value]);
}
// node_modules/@base-ui/react/utils/useOpenInteractionType.mjs
function useOpenMethodTriggerProps(open, setOpenMethod) {
const handleTriggerClick = useStableCallback((_, interactionType) => {
const isOpen = typeof open === "function" ? open() : open;
if (!isOpen) {
setOpenMethod(interactionType || // On iOS Safari, the hitslop around touch targets means tapping outside an element's
// bounds does not fire `pointerdown` but does fire `mousedown`. The `interactionType`
// will be "" in that case.
(parts_exports.os.ios ? "touch" : ""));
}
});
const {
onClick,
onPointerDown
} = useEnhancedClickHandler(handleTriggerClick);
return React48.useMemo(() => ({
onClick,
onPointerDown
}), [onClick, onPointerDown]);
}
function useOpenInteractionType(open) {
const [openMethod, setOpenMethod] = React48.useState(null);
const triggerProps = useOpenMethodTriggerProps(open, setOpenMethod);
useValueChanged(open, (previousOpen) => {
if (previousOpen && !open) {
setOpenMethod(null);
}
});
return React48.useMemo(() => ({
openMethod,
triggerProps
}), [openMethod, triggerProps]);
}
// node_modules/@base-ui/react/internals/itemEquality.mjs
var defaultItemEquality = (itemValue, selectedValue) => Object.is(itemValue, selectedValue);
function compareItemEquality(itemValue, selectedValue, comparer) {
if (itemValue == null || selectedValue == null) {
return Object.is(itemValue, selectedValue);
}
return comparer(itemValue, selectedValue);
}
function selectedValueIncludes(selectedValues, itemValue, comparer) {
if (!selectedValues || selectedValues.length === 0) {
return false;
}
return selectedValues.some((selectedValue) => {
if (selectedValue === void 0) {
return false;
}
return compareItemEquality(itemValue, selectedValue, comparer);
});
}
function findItemIndex(itemValues, selectedValue, comparer) {
if (!itemValues || itemValues.length === 0) {
return -1;
}
return itemValues.findIndex((itemValue) => {
if (itemValue === void 0) {
return false;
}
return compareItemEquality(itemValue, selectedValue, comparer);
});
}
function removeItem(selectedValues, itemValue, comparer) {
return selectedValues.filter((selectedValue) => !compareItemEquality(itemValue, selectedValue, comparer));
}
// node_modules/@base-ui/react/internals/resolveValueLabel.mjs
var React49 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/internals/serializeValue.mjs
function serializeValue(value) {
if (value == null) {
return "";
}
if (typeof value === "string") {
return value;
}
try {
return JSON.stringify(value);
} catch {
return String(value);
}
}
// node_modules/@base-ui/react/internals/resolveValueLabel.mjs
var import_jsx_runtime159 = __toESM(require_jsx_runtime(), 1);
function isGroupedItems(items) {
return items != null && items.length > 0 && typeof items[0] === "object" && items[0] != null && "items" in items[0];
}
function hasNullItemLabel(items) {
if (!Array.isArray(items)) {
return items != null && "null" in items;
}
const arrayItems = items;
if (isGroupedItems(arrayItems)) {
for (const group of arrayItems) {
for (const item of group.items) {
if (item && item.value == null && item.label != null) {
return true;
}
}
}
return false;
}
for (const item of arrayItems) {
if (item && item.value == null && item.label != null) {
return true;
}
}
return false;
}
function stringifyAsLabel(item, itemToStringLabel) {
if (itemToStringLabel && item != null) {
return itemToStringLabel(item) ?? "";
}
if (item && typeof item === "object") {
if ("label" in item && item.label != null) {
return String(item.label);
}
if ("value" in item) {
return String(item.value);
}
}
return serializeValue(item);
}
function stringifyAsValue(item, itemToStringValue) {
if (itemToStringValue && item != null) {
return itemToStringValue(item) ?? "";
}
if (item && typeof item === "object" && "value" in item && "label" in item) {
return serializeValue(item.value);
}
return serializeValue(item);
}
function resolveSelectedLabel(value, items, itemToStringLabel) {
function fallback() {
return stringifyAsLabel(value, itemToStringLabel);
}
if (itemToStringLabel && value != null) {
return itemToStringLabel(value);
}
if (value && typeof value === "object" && "label" in value && value.label != null) {
return value.label;
}
if (items && !Array.isArray(items)) {
return items[value] ?? fallback();
}
if (Array.isArray(items)) {
const arrayItems = items;
const flatItems = isGroupedItems(arrayItems) ? arrayItems.flatMap((group) => group.items) : arrayItems;
if (value == null || typeof value !== "object") {
const match2 = flatItems.find((item) => item.value === value);
if (match2 && match2.label != null) {
return match2.label;
}
return fallback();
}
if ("value" in value) {
const match2 = flatItems.find((item) => item && item.value === value.value);
if (match2 && match2.label != null) {
return match2.label;
}
}
}
return fallback();
}
function resolveMultipleLabels(values, items, itemToStringLabel) {
return values.reduce((acc, value, index2) => {
if (index2 > 0) {
acc.push(", ");
}
acc.push(/* @__PURE__ */ (0, import_jsx_runtime159.jsx)(React49.Fragment, {
children: resolveSelectedLabel(value, items, itemToStringLabel)
}, index2));
return acc;
}, []);
}
// node_modules/@base-ui/react/internals/field-root-context/FieldRootContext.mjs
var React50 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/field/control/FieldControlDataAttributes.mjs
var FieldControlDataAttributes = /* @__PURE__ */ (function(FieldControlDataAttributes2) {
FieldControlDataAttributes2["disabled"] = "data-disabled";
FieldControlDataAttributes2["valid"] = "data-valid";
FieldControlDataAttributes2["invalid"] = "data-invalid";
FieldControlDataAttributes2["touched"] = "data-touched";
FieldControlDataAttributes2["dirty"] = "data-dirty";
FieldControlDataAttributes2["filled"] = "data-filled";
FieldControlDataAttributes2["focused"] = "data-focused";
return FieldControlDataAttributes2;
})({});
// node_modules/@base-ui/react/internals/field-constants/constants.mjs
var DEFAULT_VALIDITY_STATE = {
badInput: false,
customError: false,
patternMismatch: false,
rangeOverflow: false,
rangeUnderflow: false,
stepMismatch: false,
tooLong: false,
tooShort: false,
typeMismatch: false,
valid: null,
valueMissing: false
};
var DEFAULT_FIELD_STATE_ATTRIBUTES = {
valid: null,
touched: false,
dirty: false,
filled: false,
focused: false
};
var DEFAULT_FIELD_ROOT_STATE = {
disabled: false,
...DEFAULT_FIELD_STATE_ATTRIBUTES
};
var fieldValidityMapping = {
valid(value) {
if (value === null) {
return null;
}
if (value) {
return {
[FieldControlDataAttributes.valid]: ""
};
}
return {
[FieldControlDataAttributes.invalid]: ""
};
}
};
// node_modules/@base-ui/react/internals/field-root-context/FieldRootContext.mjs
var DEFAULT_FIELD_ROOT_CONTEXT = {
invalid: void 0,
name: void 0,
validityData: {
state: DEFAULT_VALIDITY_STATE,
errors: [],
error: "",
value: "",
initialValue: null
},
setValidityData: NOOP,
disabled: void 0,
touched: DEFAULT_FIELD_STATE_ATTRIBUTES.touched,
setTouched: NOOP,
dirty: DEFAULT_FIELD_STATE_ATTRIBUTES.dirty,
setDirty: NOOP,
filled: DEFAULT_FIELD_STATE_ATTRIBUTES.filled,
setFilled: NOOP,
focused: DEFAULT_FIELD_STATE_ATTRIBUTES.focused,
setFocused: NOOP,
validate: () => null,
validationMode: "onSubmit",
validationDebounceTime: 0,
shouldValidateOnChange: () => false,
state: DEFAULT_FIELD_ROOT_STATE,
markedDirtyRef: {
current: false
},
registerFieldControl: NOOP,
validation: {
getValidationProps: (_disabled, props = EMPTY_OBJECT) => props,
inputRef: {
current: null
},
registerInput: NOOP,
commit: async () => {
},
change: NOOP
}
};
var FieldRootContext = /* @__PURE__ */ React50.createContext(DEFAULT_FIELD_ROOT_CONTEXT);
if (true) FieldRootContext.displayName = "FieldRootContext";
function useFieldRootContext(optional = true) {
const context = React50.useContext(FieldRootContext);
if (context.setValidityData === NOOP && !optional) {
throw new Error(true ? "Base UI: FieldRootContext is missing. Field parts must be placed within <Field.Root>." : formatErrorMessage_default(28));
}
return context;
}
// node_modules/@base-ui/react/internals/field-register-control/useRegisterFieldControl.mjs
var React51 = __toESM(require_react(), 1);
function useRegisterFieldControl(controlRef, id, value, getFormValueOverride, enabled = true, name) {
const {
registerFieldControl
} = useFieldRootContext();
const sourceRef = React51.useRef(null);
if (!sourceRef.current) {
sourceRef.current = /* @__PURE__ */ Symbol();
}
useIsoLayoutEffect(() => {
const source = sourceRef.current;
if (!source || !enabled) {
return void 0;
}
const registration = {
controlRef,
getValue: getFormValueOverride,
id,
name,
value
};
registerFieldControl(source, registration);
return () => {
registerFieldControl(source, void 0);
};
}, [controlRef, enabled, getFormValueOverride, id, name, registerFieldControl, value]);
}
// node_modules/@base-ui/react/internals/form-context/FormContext.mjs
var React52 = __toESM(require_react(), 1);
var FormContext = /* @__PURE__ */ React52.createContext({
formRef: {
current: {
fields: /* @__PURE__ */ new Map()
}
},
errors: {},
clearErrors: NOOP,
validationMode: "onSubmit",
submitAttemptedRef: {
current: false
}
});
if (true) FormContext.displayName = "FormContext";
function useFormContext() {
return React52.useContext(FormContext);
}
// node_modules/@base-ui/react/internals/labelable-provider/useLabelableId.mjs
var React54 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/internals/labelable-provider/LabelableContext.mjs
var React53 = __toESM(require_react(), 1);
var LabelableContext = /* @__PURE__ */ React53.createContext({
controlId: void 0,
registerControlId: NOOP,
labelId: void 0,
setLabelId: NOOP,
messageIds: [],
setMessageIds: NOOP,
getDescriptionProps: (externalProps) => externalProps
});
if (true) LabelableContext.displayName = "LabelableContext";
function useLabelableContext() {
return React53.useContext(LabelableContext);
}
// node_modules/@base-ui/react/internals/labelable-provider/useLabelableId.mjs
function useLabelableId(params = {}) {
const {
id,
implicit = false,
controlRef
} = params;
const {
controlId,
registerControlId
} = useLabelableContext();
const defaultId = useBaseUiId(id);
const controlIdForEffect = implicit ? controlId : void 0;
const controlSourceRef = useRefWithInit(() => /* @__PURE__ */ Symbol("labelable-control"));
const hasRegisteredRef = React54.useRef(false);
const hadExplicitIdRef = React54.useRef(id != null);
const unregisterControlId = useStableCallback(() => {
if (!hasRegisteredRef.current || registerControlId === NOOP) {
return;
}
hasRegisteredRef.current = false;
registerControlId(controlSourceRef.current, void 0);
});
useIsoLayoutEffect(() => {
if (registerControlId === NOOP) {
return void 0;
}
let nextId2;
if (implicit) {
const elem = controlRef?.current;
if (isElement(elem) && elem.closest("label") != null) {
nextId2 = id ?? null;
} else {
nextId2 = controlIdForEffect ?? defaultId;
}
} else if (id != null) {
hadExplicitIdRef.current = true;
nextId2 = id;
} else if (hadExplicitIdRef.current) {
nextId2 = defaultId;
} else {
unregisterControlId();
return void 0;
}
if (nextId2 === void 0) {
unregisterControlId();
return void 0;
}
hasRegisteredRef.current = true;
registerControlId(controlSourceRef.current, nextId2);
return void 0;
}, [id, controlRef, controlIdForEffect, registerControlId, implicit, defaultId, controlSourceRef, unregisterControlId]);
React54.useEffect(() => {
return unregisterControlId;
}, [unregisterControlId]);
return controlId ?? defaultId;
}
// node_modules/@base-ui/react/internals/areArraysEqual.mjs
function areArraysEqual(array1, array2, itemComparer = (a2, b2) => a2 === b2) {
return array1.length === array2.length && array1.every((value, index2) => itemComparer(value, array2[index2]));
}
// node_modules/@base-ui/react/utils/getPseudoElementBounds.mjs
function getPseudoElementBounds(element) {
const elementRect = element.getBoundingClientRect();
const win = getWindow(element);
if (parts_exports.env.jsdom) {
return elementRect;
}
const beforeStyles = win.getComputedStyle(element, "::before");
const afterStyles = win.getComputedStyle(element, "::after");
const hasPseudoElements = beforeStyles.content !== "none" || afterStyles.content !== "none";
if (!hasPseudoElements) {
return elementRect;
}
const beforeWidth = parseFloat(beforeStyles.width) || 0;
const beforeHeight = parseFloat(beforeStyles.height) || 0;
const afterWidth = parseFloat(afterStyles.width) || 0;
const afterHeight = parseFloat(afterStyles.height) || 0;
const totalWidth = Math.max(elementRect.width, beforeWidth, afterWidth);
const totalHeight = Math.max(elementRect.height, beforeHeight, afterHeight);
const widthDiff = totalWidth - elementRect.width;
const heightDiff = totalHeight - elementRect.height;
return {
left: elementRect.left - widthDiff / 2,
right: elementRect.right + widthDiff / 2,
top: elementRect.top - heightDiff / 2,
bottom: elementRect.bottom + heightDiff / 2
};
}
// node_modules/@base-ui/react/utils/resolveAriaLabelledBy.mjs
function getDefaultLabelId(id) {
return id == null ? void 0 : `${id}-label`;
}
function resolveAriaLabelledBy(fieldLabelId, localLabelId) {
return fieldLabelId ?? localLabelId;
}
// node_modules/@base-ui/react/utils/useAnchorPositioning.mjs
var React55 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/floating-ui-react/middleware/arrow.mjs
var baseArrow = (options) => ({
name: "arrow",
options,
async fn(state) {
const {
x: x2,
y: y2,
placement,
rects,
platform: platform3,
elements,
middlewareData
} = state;
const {
element,
padding = 0,
offsetParent = "real"
} = evaluate(options, state) || {};
if (element == null) {
return {};
}
const paddingObject = getPaddingObject(padding);
const coords = {
x: x2,
y: y2
};
const axis = getAlignmentAxis(placement);
const length = getAxisLength(axis);
const arrowDimensions = await platform3.getDimensions(element);
const isYAxis = axis === "y";
const minProp = isYAxis ? "top" : "left";
const maxProp = isYAxis ? "bottom" : "right";
const clientProp = isYAxis ? "clientHeight" : "clientWidth";
const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length];
const startDiff = coords[axis] - rects.reference[axis];
const arrowOffsetParent = offsetParent === "real" ? await platform3.getOffsetParent?.(element) : elements.floating;
let clientSize = elements.floating[clientProp] || rects.floating[length];
if (!clientSize || !await platform3.isElement?.(arrowOffsetParent)) {
clientSize = elements.floating[clientProp] || rects.floating[length];
}
const centerToReference = endDiff / 2 - startDiff / 2;
const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1;
const minPadding = Math.min(paddingObject[minProp], largestPossiblePadding);
const maxPadding = Math.min(paddingObject[maxProp], largestPossiblePadding);
const min2 = minPadding;
const max2 = clientSize - arrowDimensions[length] - maxPadding;
const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference;
const offset4 = clamp(min2, center, max2);
const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center !== offset4 && rects.reference[length] / 2 - (center < min2 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0;
const alignmentOffset = shouldAddOffset ? center < min2 ? center - min2 : center - max2 : 0;
return {
[axis]: coords[axis] + alignmentOffset,
data: {
[axis]: offset4,
centerOffset: center - offset4 - alignmentOffset,
...shouldAddOffset && {
alignmentOffset
}
},
reset: shouldAddOffset
};
}
});
var arrow4 = (options, deps) => ({
...baseArrow(options),
options: [options, deps]
});
// node_modules/@base-ui/react/utils/hideMiddleware.mjs
var nativeHideFn = hide3().fn;
var hide4 = {
name: "hide",
async fn(state) {
const {
width,
height,
x: x2,
y: y2
} = state.rects.reference;
const anchorHidden = width === 0 && height === 0 && x2 === 0 && y2 === 0;
const nativeHideResult = await nativeHideFn(state);
return {
data: {
referenceHidden: nativeHideResult.data?.referenceHidden || anchorHidden
}
};
}
};
// node_modules/@base-ui/react/utils/adaptiveOriginMiddleware.mjs
var DEFAULT_SIDES = {
sideX: "left",
sideY: "top"
};
var adaptiveOrigin = {
name: "adaptiveOrigin",
async fn(state) {
const {
x: rawX,
y: rawY,
rects: {
floating: floatRect
},
elements: {
floating
},
platform: platform3,
strategy,
placement
} = state;
const win = getWindow(floating);
const styles = win.getComputedStyle(floating);
const hasTransition = styles.transitionDuration !== "0s" && styles.transitionDuration !== "";
if (!hasTransition) {
return {
x: rawX,
y: rawY,
data: DEFAULT_SIDES
};
}
const offsetParent = await platform3.getOffsetParent?.(floating);
let offsetDimensions = {
width: 0,
height: 0
};
if (strategy === "fixed" && win?.visualViewport) {
offsetDimensions = {
width: win.visualViewport.width,
height: win.visualViewport.height
};
} else if (offsetParent === win) {
const doc = ownerDocument(floating);
offsetDimensions = {
width: doc.documentElement.clientWidth,
height: doc.documentElement.clientHeight
};
} else if (await platform3.isElement?.(offsetParent)) {
offsetDimensions = await platform3.getDimensions(offsetParent);
}
const currentSide = getSide(placement);
let x2 = rawX;
let y2 = rawY;
if (currentSide === "left") {
x2 = offsetDimensions.width - (rawX + floatRect.width);
}
if (currentSide === "top") {
y2 = offsetDimensions.height - (rawY + floatRect.height);
}
const sideX = currentSide === "left" ? "right" : DEFAULT_SIDES.sideX;
const sideY = currentSide === "top" ? "bottom" : DEFAULT_SIDES.sideY;
return {
x: x2,
y: y2,
data: {
sideX,
sideY
}
};
}
};
// node_modules/@base-ui/react/utils/useAnchorPositioning.mjs
function getLogicalSide(sideParam, renderedSide, isRtl) {
const isLogicalSideParam = sideParam === "inline-start" || sideParam === "inline-end";
const logicalRight = isRtl ? "inline-start" : "inline-end";
const logicalLeft = isRtl ? "inline-end" : "inline-start";
return {
top: "top",
right: isLogicalSideParam ? logicalRight : "right",
bottom: "bottom",
left: isLogicalSideParam ? logicalLeft : "left"
}[renderedSide];
}
function getOffsetData(state, sideParam, isRtl) {
const {
rects,
placement
} = state;
const data = {
side: getLogicalSide(sideParam, getSide(placement), isRtl),
align: getAlignment(placement) || "center",
anchor: {
width: rects.reference.width,
height: rects.reference.height
},
positioner: {
width: rects.floating.width,
height: rects.floating.height
}
};
return data;
}
function useAnchorPositioning(params) {
const {
// Public parameters
anchor,
positionMethod = "absolute",
side: sideParam = "bottom",
sideOffset = 0,
align = "center",
alignOffset = 0,
collisionBoundary,
collisionPadding: collisionPaddingParam = 5,
sticky = false,
arrowPadding = 5,
disableAnchorTracking = false,
inline: inlineMiddleware,
// Private parameters
keepMounted = false,
floatingRootContext,
mounted,
collisionAvoidance,
shiftCrossAxis = false,
nodeId,
adaptiveOrigin: adaptiveOrigin2,
lazyFlip = false,
externalTree
} = params;
const [mountSide, setMountSide] = React55.useState(null);
if (!mounted && mountSide !== null) {
setMountSide(null);
}
const collisionAvoidanceSide = collisionAvoidance.side || "flip";
const collisionAvoidanceAlign = collisionAvoidance.align || "flip";
const collisionAvoidanceFallbackAxisSide = collisionAvoidance.fallbackAxisSide || "end";
const anchorFn = typeof anchor === "function" ? anchor : void 0;
const anchorFnCallback = useStableCallback(anchorFn);
const anchorDep = anchorFn ? anchorFnCallback : anchor;
const anchorValueRef = useValueAsRef(anchor);
const mountedRef = useValueAsRef(mounted);
const direction = useDirection();
const isRtl = direction === "rtl";
const side = mountSide || {
top: "top",
right: "right",
bottom: "bottom",
left: "left",
"inline-end": isRtl ? "left" : "right",
"inline-start": isRtl ? "right" : "left"
}[sideParam];
const placement = align === "center" ? side : `${side}-${align}`;
let collisionPadding = collisionPaddingParam;
const bias = 1;
const biasTop = sideParam === "bottom" ? bias : 0;
const biasBottom = sideParam === "top" ? bias : 0;
const biasLeft = sideParam === "right" ? bias : 0;
const biasRight = sideParam === "left" ? bias : 0;
if (typeof collisionPadding === "number") {
collisionPadding = {
top: collisionPadding + biasTop,
right: collisionPadding + biasRight,
bottom: collisionPadding + biasBottom,
left: collisionPadding + biasLeft
};
} else if (collisionPadding) {
collisionPadding = {
top: (collisionPadding.top || 0) + biasTop,
right: (collisionPadding.right || 0) + biasRight,
bottom: (collisionPadding.bottom || 0) + biasBottom,
left: (collisionPadding.left || 0) + biasLeft
};
}
const commonCollisionProps = {
boundary: collisionBoundary === "clipping-ancestors" ? "clippingAncestors" : collisionBoundary,
padding: collisionPadding
};
const arrowRef = React55.useRef(null);
const sideOffsetRef = useValueAsRef(sideOffset);
const alignOffsetRef = useValueAsRef(alignOffset);
const sideOffsetDep = typeof sideOffset !== "function" ? sideOffset : 0;
const alignOffsetDep = typeof alignOffset !== "function" ? alignOffset : 0;
const middleware = [];
if (inlineMiddleware) {
middleware.push(inlineMiddleware);
}
middleware.push(offset3((state) => {
const data = getOffsetData(state, sideParam, isRtl);
const sideAxis = typeof sideOffsetRef.current === "function" ? sideOffsetRef.current(data) : sideOffsetRef.current;
const alignAxis = typeof alignOffsetRef.current === "function" ? alignOffsetRef.current(data) : alignOffsetRef.current;
return {
mainAxis: sideAxis,
crossAxis: alignAxis,
alignmentAxis: alignAxis
};
}, [sideOffsetDep, alignOffsetDep, isRtl, sideParam]));
const shiftDisabled = collisionAvoidanceAlign === "none" && collisionAvoidanceSide !== "shift";
const crossAxisShiftEnabled = !shiftDisabled && (sticky || shiftCrossAxis || collisionAvoidanceSide === "shift");
const flipMiddleware = collisionAvoidanceSide === "none" ? null : flip3({
...commonCollisionProps,
// Ensure the popup flips if it's been limited by its --available-height and it resizes.
// Since the size() padding is smaller than the flip() padding, flip() will take precedence.
padding: {
top: collisionPadding.top + bias,
right: collisionPadding.right + bias,
bottom: collisionPadding.bottom + bias,
left: collisionPadding.left + bias
},
mainAxis: !shiftCrossAxis && collisionAvoidanceSide === "flip",
crossAxis: collisionAvoidanceAlign === "flip" ? "alignment" : false,
fallbackAxisSideDirection: collisionAvoidanceFallbackAxisSide
});
const shiftMiddleware = shiftDisabled ? null : shift3((data) => {
const html = ownerDocument(data.elements.floating).documentElement;
return {
...commonCollisionProps,
// Use the Layout Viewport to avoid shifting around when pinch-zooming
// for context menus.
rootBoundary: shiftCrossAxis ? {
x: 0,
y: 0,
width: html.clientWidth,
height: html.clientHeight
} : void 0,
mainAxis: collisionAvoidanceAlign !== "none",
crossAxis: crossAxisShiftEnabled,
limiter: sticky || shiftCrossAxis ? void 0 : limitShift3((limitData) => {
if (!arrowRef.current) {
return {};
}
const {
width,
height
} = arrowRef.current.getBoundingClientRect();
const sideAxis = getSideAxis(getSide(limitData.placement));
const arrowSize = sideAxis === "y" ? width : height;
const offsetAmount = sideAxis === "y" ? collisionPadding.left + collisionPadding.right : collisionPadding.top + collisionPadding.bottom;
return {
offset: arrowSize / 2 + offsetAmount / 2
};
})
};
}, [commonCollisionProps, sticky, shiftCrossAxis, collisionPadding, collisionAvoidanceAlign]);
if (collisionAvoidanceSide === "shift" || collisionAvoidanceAlign === "shift" || align === "center") {
middleware.push(shiftMiddleware, flipMiddleware);
} else {
middleware.push(flipMiddleware, shiftMiddleware);
}
middleware.push(size3({
...commonCollisionProps,
apply({
elements: {
floating
},
availableWidth,
availableHeight,
rects
}) {
if (!mountedRef.current) {
return;
}
const floatingStyle = floating.style;
floatingStyle.setProperty("--available-width", `${availableWidth}px`);
floatingStyle.setProperty("--available-height", `${availableHeight}px`);
const dpr = getWindow(floating).devicePixelRatio || 1;
const {
x: x3,
y: y3,
width,
height
} = rects.reference;
const anchorWidth = (Math.round((x3 + width) * dpr) - Math.round(x3 * dpr)) / dpr;
const anchorHeight = (Math.round((y3 + height) * dpr) - Math.round(y3 * dpr)) / dpr;
floatingStyle.setProperty("--anchor-width", `${anchorWidth}px`);
floatingStyle.setProperty("--anchor-height", `${anchorHeight}px`);
}
}), arrow4((state) => ({
// `transform-origin` calculations rely on an element existing. If the arrow hasn't been set,
// we'll create a fake element.
element: arrowRef.current || ownerDocument(state.elements.floating).createElement("div"),
padding: arrowPadding,
offsetParent: "floating"
}), [arrowPadding]), {
name: "transformOrigin",
fn(state) {
const {
elements: elements2,
middlewareData: middlewareData2,
placement: renderedPlacement2,
rects,
y: y3
} = state;
const currentRenderedSide = getSide(renderedPlacement2);
const currentRenderedAxis = getSideAxis(currentRenderedSide);
const arrowEl = arrowRef.current;
const arrowX = middlewareData2.arrow?.x || 0;
const arrowY = middlewareData2.arrow?.y || 0;
const arrowWidth = arrowEl?.clientWidth || 0;
const arrowHeight = arrowEl?.clientHeight || 0;
const transformX = arrowX + arrowWidth / 2;
const transformY = arrowY + arrowHeight / 2;
const shiftY = Math.abs(middlewareData2.shift?.y || 0);
const halfAnchorHeight = rects.reference.height / 2;
const sideOffsetValue = typeof sideOffset === "function" ? sideOffset(getOffsetData(state, sideParam, isRtl)) : sideOffset;
const isOverlappingAnchor = shiftY > sideOffsetValue;
const adjacentTransformOrigin = {
top: `${transformX}px calc(100% + ${sideOffsetValue}px)`,
bottom: `${transformX}px ${-sideOffsetValue}px`,
left: `calc(100% + ${sideOffsetValue}px) ${transformY}px`,
right: `${-sideOffsetValue}px ${transformY}px`
}[currentRenderedSide];
const overlapTransformOrigin = `${transformX}px ${rects.reference.y + halfAnchorHeight - y3}px`;
elements2.floating.style.setProperty("--transform-origin", crossAxisShiftEnabled && currentRenderedAxis === "y" && isOverlappingAnchor ? overlapTransformOrigin : adjacentTransformOrigin);
return {};
}
}, hide4, adaptiveOrigin2);
useIsoLayoutEffect(() => {
if (!mounted && floatingRootContext) {
floatingRootContext.update({
referenceElement: null,
floatingElement: null,
domReferenceElement: null,
positionReference: null
});
}
}, [mounted, floatingRootContext]);
const autoUpdateOptions = React55.useMemo(() => ({
elementResize: !disableAnchorTracking && typeof ResizeObserver !== "undefined",
layoutShift: !disableAnchorTracking && typeof IntersectionObserver !== "undefined"
}), [disableAnchorTracking]);
const {
refs,
elements,
x: x2,
y: y2,
middlewareData,
update: update4,
placement: renderedPlacement,
context,
isPositioned,
floatingStyles: originalFloatingStyles
} = useFloating2({
rootContext: floatingRootContext,
open: keepMounted ? mounted : void 0,
placement,
middleware,
strategy: positionMethod,
whileElementsMounted: keepMounted ? void 0 : (...args) => autoUpdate(...args, autoUpdateOptions),
nodeId,
externalTree
});
const {
sideX,
sideY
} = middlewareData.adaptiveOrigin || DEFAULT_SIDES;
const resolvedPosition = isPositioned ? positionMethod : "fixed";
const floatingStyles = React55.useMemo(() => {
const base = adaptiveOrigin2 ? {
position: resolvedPosition,
[sideX]: x2,
[sideY]: y2
} : {
position: resolvedPosition,
...originalFloatingStyles
};
if (!isPositioned) {
base.opacity = 0;
}
return base;
}, [adaptiveOrigin2, resolvedPosition, sideX, x2, sideY, y2, originalFloatingStyles, isPositioned]);
const registeredPositionReferenceRef = React55.useRef(null);
useIsoLayoutEffect(() => {
if (!mounted) {
return;
}
const anchorValue = anchorValueRef.current;
const resolvedAnchor = typeof anchorValue === "function" ? anchorValue() : anchorValue;
const unwrappedElement = (isRef(resolvedAnchor) ? resolvedAnchor.current : resolvedAnchor) || null;
const finalAnchor = unwrappedElement || null;
if (finalAnchor !== registeredPositionReferenceRef.current) {
refs.setPositionReference(finalAnchor);
registeredPositionReferenceRef.current = finalAnchor;
}
}, [mounted, refs, anchorDep, anchorValueRef]);
React55.useEffect(() => {
if (!mounted) {
return;
}
const anchorValue = anchorValueRef.current;
if (typeof anchorValue === "function") {
return;
}
if (isRef(anchorValue) && anchorValue.current !== registeredPositionReferenceRef.current) {
refs.setPositionReference(anchorValue.current);
registeredPositionReferenceRef.current = anchorValue.current;
}
}, [mounted, refs, anchorDep, anchorValueRef]);
React55.useEffect(() => {
if (keepMounted && mounted && elements.reference && elements.floating) {
return autoUpdate(elements.reference, elements.floating, update4, autoUpdateOptions);
}
return void 0;
}, [keepMounted, mounted, elements, update4, autoUpdateOptions]);
const renderedSide = getSide(renderedPlacement);
const logicalRenderedSide = getLogicalSide(sideParam, renderedSide, isRtl);
const renderedAlign = getAlignment(renderedPlacement) || "center";
const anchorHidden = Boolean(middlewareData.hide?.referenceHidden);
useIsoLayoutEffect(() => {
if (lazyFlip && mounted && isPositioned) {
setMountSide(renderedSide);
}
}, [lazyFlip, mounted, isPositioned, renderedSide]);
const arrowStyles = React55.useMemo(() => ({
position: "absolute",
top: middlewareData.arrow?.y,
left: middlewareData.arrow?.x
}), [middlewareData.arrow]);
const arrowUncentered = middlewareData.arrow?.centerOffset !== 0;
return React55.useMemo(() => ({
positionerStyles: floatingStyles,
arrowStyles,
arrowRef,
arrowUncentered,
side: logicalRenderedSide,
align: renderedAlign,
physicalSide: renderedSide,
anchorHidden,
refs,
context,
isPositioned,
update: update4
}), [floatingStyles, arrowStyles, arrowRef, arrowUncentered, logicalRenderedSide, renderedAlign, renderedSide, anchorHidden, refs, context, isPositioned, update4]);
}
function isRef(param) {
return param != null && "current" in param;
}
// node_modules/@base-ui/react/utils/getDisabledMountTransitionStyles.mjs
function getDisabledMountTransitionStyles(transitionStatus) {
return transitionStatus === "starting" ? DISABLED_TRANSITIONS_STYLE : EMPTY_OBJECT;
}
// node_modules/@base-ui/react/utils/usePositioner.mjs
function usePositioner(componentProps, state, {
styles,
transitionStatus,
props,
refs,
hidden,
inert = false
}) {
const style = {
...styles
};
if (inert) {
style.pointerEvents = "none";
}
return useRenderElement("div", componentProps, {
state,
ref: refs,
props: [{
role: "presentation",
hidden,
style
}, getDisabledMountTransitionStyles(transitionStatus), props],
stateAttributesMapping: popupStateMapping
});
}
// node_modules/@base-ui/react/utils/useAnchoredPopupScrollLock.mjs
var React56 = __toESM(require_react(), 1);
var VIEWPORT_WIDTH_TOLERANCE_PX = 20;
function useAnchoredPopupScrollLock(enabled, touchOpen, positionerElement, referenceElement) {
const [touchOpenShouldLockScroll, setTouchOpenShouldLockScroll] = React56.useState(false);
useIsoLayoutEffect(() => {
if (!enabled || !touchOpen || positionerElement == null) {
setTouchOpenShouldLockScroll(false);
return;
}
const viewportWidth = ownerDocument(positionerElement).documentElement.clientWidth;
const popupWidth = positionerElement.offsetWidth;
setTouchOpenShouldLockScroll(viewportWidth > 0 && popupWidth > 0 && popupWidth >= viewportWidth - VIEWPORT_WIDTH_TOLERANCE_PX);
}, [enabled, touchOpen, positionerElement]);
useScrollLock(enabled && (!touchOpen || touchOpenShouldLockScroll), referenceElement);
}
// node_modules/@base-ui/react/separator/Separator.mjs
var React57 = __toESM(require_react(), 1);
var Separator = /* @__PURE__ */ React57.forwardRef(function SeparatorComponent(componentProps, forwardedRef) {
const {
className,
render: render4,
orientation = "horizontal",
style,
...elementProps
} = componentProps;
const state = {
orientation
};
const element = useRenderElement("div", componentProps, {
state,
ref: forwardedRef,
props: [{
role: "separator",
"aria-orientation": orientation
}, elementProps]
});
return element;
});
if (true) Separator.displayName = "Separator";
// node_modules/@base-ui/react/field/item/FieldItemContext.mjs
var React58 = __toESM(require_react(), 1);
var FieldItemContext = /* @__PURE__ */ React58.createContext({
disabled: false
});
if (true) FieldItemContext.displayName = "FieldItemContext";
function useFieldItemContext() {
const context = React58.useContext(FieldItemContext);
return context;
}
// node_modules/@base-ui/react/checkbox-group/CheckboxGroupContext.mjs
var React59 = __toESM(require_react(), 1);
var CheckboxGroupContext = /* @__PURE__ */ React59.createContext(void 0);
if (true) CheckboxGroupContext.displayName = "CheckboxGroupContext";
function useCheckboxGroupContext(optional = true) {
const context = React59.useContext(CheckboxGroupContext);
if (context === void 0 && !optional) {
throw new Error(true ? "Base UI: CheckboxGroupContext is missing. CheckboxGroup parts must be placed within <CheckboxGroup>." : formatErrorMessage_default(3));
}
return context;
}
// node_modules/@base-ui/react/collapsible/index.parts.mjs
var index_parts_exports = {};
__export(index_parts_exports, {
Panel: () => CollapsiblePanel,
Root: () => CollapsibleRoot,
Trigger: () => CollapsibleTrigger
});
// node_modules/@base-ui/react/collapsible/root/CollapsibleRoot.mjs
var React60 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/collapsible/root/stateAttributesMapping.mjs
var collapsibleStateAttributesMapping = {
...collapsibleOpenStateMapping,
...transitionStatusMapping
};
// node_modules/@base-ui/react/collapsible/root/CollapsibleRoot.mjs
var import_jsx_runtime160 = __toESM(require_jsx_runtime(), 1);
var CollapsibleRoot = /* @__PURE__ */ React60.forwardRef(function CollapsibleRoot2(componentProps, forwardedRef) {
const {
render: render4,
className,
defaultOpen = false,
disabled: disabled2 = false,
onOpenChange: onOpenChangeProp,
open,
style,
...elementProps
} = componentProps;
const onOpenChange = useStableCallback(onOpenChangeProp);
const collapsible = useCollapsibleRoot({
open,
defaultOpen,
onOpenChange,
disabled: disabled2
});
const state = React60.useMemo(() => ({
open: collapsible.open,
disabled: collapsible.disabled,
transitionStatus: collapsible.transitionStatus
}), [collapsible.open, collapsible.disabled, collapsible.transitionStatus]);
const contextValue = React60.useMemo(() => ({
...collapsible,
onOpenChange,
state
}), [collapsible, onOpenChange, state]);
const element = useRenderElement("div", componentProps, {
state,
ref: forwardedRef,
props: elementProps,
stateAttributesMapping: collapsibleStateAttributesMapping
});
return /* @__PURE__ */ (0, import_jsx_runtime160.jsx)(CollapsibleRootContext.Provider, {
value: contextValue,
children: element
});
});
if (true) CollapsibleRoot.displayName = "CollapsibleRoot";
// node_modules/@base-ui/react/collapsible/trigger/CollapsibleTrigger.mjs
var React61 = __toESM(require_react(), 1);
var stateAttributesMapping = {
...triggerOpenStateMapping,
...transitionStatusMapping
};
var CollapsibleTrigger = /* @__PURE__ */ React61.forwardRef(function CollapsibleTrigger2(componentProps, forwardedRef) {
const {
panelId,
open,
handleTrigger,
state,
disabled: contextDisabled
} = useCollapsibleRootContext();
const {
className,
disabled: disabled2 = contextDisabled,
render: render4,
nativeButton = true,
style,
...elementProps
} = componentProps;
const {
getButtonProps,
buttonRef
} = useButton({
disabled: disabled2,
focusableWhenDisabled: true,
native: nativeButton
});
const element = useRenderElement("button", componentProps, {
state,
ref: [forwardedRef, buttonRef],
props: [{
"aria-controls": open ? panelId : void 0,
"aria-expanded": open,
onClick: handleTrigger
}, elementProps, getButtonProps],
stateAttributesMapping
});
return element;
});
if (true) CollapsibleTrigger.displayName = "CollapsibleTrigger";
// node_modules/@base-ui/react/collapsible/panel/CollapsiblePanel.mjs
var React62 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/collapsible/panel/CollapsiblePanelCssVars.mjs
var CollapsiblePanelCssVars = /* @__PURE__ */ (function(CollapsiblePanelCssVars2) {
CollapsiblePanelCssVars2["collapsiblePanelHeight"] = "--collapsible-panel-height";
CollapsiblePanelCssVars2["collapsiblePanelWidth"] = "--collapsible-panel-width";
return CollapsiblePanelCssVars2;
})({});
// node_modules/@base-ui/react/collapsible/panel/CollapsiblePanel.mjs
var CollapsiblePanel = /* @__PURE__ */ React62.forwardRef(function CollapsiblePanel2(componentProps, forwardedRef) {
const {
className,
hiddenUntilFound: hiddenUntilFoundProp,
keepMounted: keepMountedProp,
render: render4,
id: idProp,
style,
...elementProps
} = componentProps;
if (true) {
useIsoLayoutEffect(() => {
if (hiddenUntilFoundProp && keepMountedProp === false) {
warn("The `keepMounted={false}` prop on `Collapsible.Panel` is ignored when `hiddenUntilFound` is enabled, since the panel must remain mounted while closed.");
}
}, [hiddenUntilFoundProp, keepMountedProp]);
}
const {
mounted,
onOpenChange,
open,
panelId,
setMounted,
setPanelIdState,
setOpen,
state,
transitionStatus
} = useCollapsibleRootContext();
const hiddenUntilFound = hiddenUntilFoundProp ?? false;
const keepMounted = keepMountedProp ?? false;
useIsoLayoutEffect(() => {
if (idProp) {
setPanelIdState(idProp);
return () => {
setPanelIdState(void 0);
};
}
return void 0;
}, [idProp, setPanelIdState]);
const {
height,
props,
ref,
shouldPreventOpenAnimation,
shouldRender,
transitionStatus: panelTransitionStatus,
width
} = useCollapsiblePanel({
externalRef: forwardedRef,
hiddenUntilFound,
id: panelId,
keepMounted,
mounted,
onOpenChange,
open,
setMounted,
setOpen,
transitionStatus
});
const panelState = {
...state,
transitionStatus: panelTransitionStatus
};
const resolvedStyle = resolveStyle(style, panelState);
const element = useRenderElement("div", {
...componentProps,
style: void 0
}, {
state: panelState,
ref,
props: [
props,
{
style: {
[CollapsiblePanelCssVars.collapsiblePanelHeight]: height === void 0 ? "auto" : `${height}px`,
[CollapsiblePanelCssVars.collapsiblePanelWidth]: width === void 0 ? "auto" : `${width}px`
}
},
elementProps,
resolvedStyle ? {
style: resolvedStyle
} : void 0,
// Resolve the public `style` prop so temporary `animationName: 'none'`
// can still win after user's inline styles have been merged.
shouldPreventOpenAnimation ? {
style: {
animationName: "none"
}
} : void 0
],
stateAttributesMapping: collapsibleStateAttributesMapping
});
if (!shouldRender) {
return null;
}
return element;
});
if (true) CollapsiblePanel.displayName = "CollapsiblePanel";
// node_modules/@base-ui/react/utils/useRegisteredLabelId.mjs
function useRegisteredLabelId(idProp, setLabelId) {
const id = useBaseUiId(idProp);
useIsoLayoutEffect(() => {
setLabelId(id);
return () => {
setLabelId(void 0);
};
}, [id, setLabelId]);
return id;
}
// node_modules/@base-ui/react/internals/labelable-provider/useLabel.mjs
function useLabel(params = {}) {
const {
id: idProp,
fallbackControlId,
native = false,
setLabelId: setLabelIdProp,
focusControl: focusControlProp
} = params;
const {
controlId: contextControlId,
setLabelId: setContextLabelId
} = useLabelableContext();
const syncLabelId = useStableCallback((nextLabelId) => {
setContextLabelId(nextLabelId);
setLabelIdProp?.(nextLabelId);
});
const id = useRegisteredLabelId(idProp, syncLabelId);
const resolvedControlId = contextControlId ?? fallbackControlId;
function focusControl(event) {
if (focusControlProp) {
focusControlProp(event, resolvedControlId);
return;
}
if (!resolvedControlId) {
return;
}
const controlElement = ownerDocument(event.currentTarget).getElementById(resolvedControlId);
if (isHTMLElement(controlElement)) {
focusElementWithVisible(controlElement);
}
}
function handleInteraction(event) {
const target = getTarget(event.nativeEvent);
if (target?.closest("button,input,select,textarea")) {
return;
}
if (!event.defaultPrevented && event.detail > 1) {
event.preventDefault();
}
if (native) {
return;
}
focusControl(event);
}
return native ? {
id,
htmlFor: resolvedControlId ?? void 0,
onMouseDown: handleInteraction
} : {
id,
onClick: handleInteraction,
onPointerDown(event) {
event.preventDefault();
}
};
}
function focusElementWithVisible(element) {
element.focus({
// Available from Chrome 144+ (January 2026).
// Safari and Firefox already support it.
focusVisible: true
});
}
// node_modules/@base-ui/react/toolbar/root/ToolbarRootContext.mjs
var React63 = __toESM(require_react(), 1);
var ToolbarRootContext = /* @__PURE__ */ React63.createContext(void 0);
if (true) ToolbarRootContext.displayName = "ToolbarRootContext";
function useToolbarRootContext(optional) {
const context = React63.useContext(ToolbarRootContext);
if (context === void 0 && !optional) {
throw new Error(true ? "Base UI: ToolbarRootContext is missing. Toolbar parts must be placed within <Toolbar.Root>." : formatErrorMessage_default(69));
}
return context;
}
// node_modules/@base-ui/react/utils/usePopupViewport.mjs
var React66 = __toESM(require_react(), 1);
var ReactDOM6 = __toESM(require_react_dom(), 1);
// node_modules/@base-ui/utils/usePreviousValue.mjs
var React64 = __toESM(require_react(), 1);
function usePreviousValue(value) {
const [state, setState] = React64.useState({
current: value,
previous: null
});
if (value !== state.current) {
setState({
current: value,
previous: state.current
});
}
return state.previous;
}
// node_modules/@base-ui/react/utils/usePopupAutoResize.mjs
var React65 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/utils/getCssDimensions.mjs
function getCssDimensions2(element) {
const css = getComputedStyle2(element);
let width = parseFloat(css.width) || 0;
let height = parseFloat(css.height) || 0;
const hasOffset = isHTMLElement(element);
const offsetWidth = hasOffset ? element.offsetWidth : width;
const offsetHeight = hasOffset ? element.offsetHeight : height;
const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight;
if (shouldFallback) {
width = offsetWidth;
height = offsetHeight;
}
return {
width,
height
};
}
// node_modules/@base-ui/react/utils/usePopupAutoResize.mjs
function usePopupAutoResize(parameters) {
const {
popupElement,
positionerElement,
content,
mounted,
onMeasureLayout: onMeasureLayoutParam,
onMeasureLayoutComplete: onMeasureLayoutCompleteParam,
side,
direction
} = parameters;
const runOnceAnimationsFinish = useAnimationsFinished(popupElement, true, false);
const animationFrame = useAnimationFrame();
const committedDimensionsRef = React65.useRef(null);
const isInitialRenderRef = React65.useRef(true);
const restoreAnchoringStylesRef = React65.useRef(NOOP);
const onMeasureLayout = useStableCallback(onMeasureLayoutParam);
const onMeasureLayoutComplete = useStableCallback(onMeasureLayoutCompleteParam);
const anchoringStyles = React65.useMemo(() => {
let isOriginSide = side === "top";
let isPhysicalLeft = side === "left";
if (direction === "rtl") {
isOriginSide = isOriginSide || side === "inline-end";
isPhysicalLeft = isPhysicalLeft || side === "inline-end";
} else {
isOriginSide = isOriginSide || side === "inline-start";
isPhysicalLeft = isPhysicalLeft || side === "inline-start";
}
return isOriginSide ? {
position: "absolute",
[side === "top" ? "bottom" : "top"]: "0",
[isPhysicalLeft ? "right" : "left"]: "0"
} : EMPTY_OBJECT;
}, [side, direction]);
useIsoLayoutEffect(() => {
if (!mounted) {
restoreAnchoringStylesRef.current = NOOP;
isInitialRenderRef.current = true;
committedDimensionsRef.current = null;
return void 0;
}
if (!popupElement || !positionerElement) {
return void 0;
}
restoreAnchoringStylesRef.current = applyElementStyles(popupElement, anchoringStyles);
setPopupCssSize(popupElement, "auto");
const restorePopupPosition = overrideElementStyle(popupElement, "position", "static");
const restorePopupTransform = overrideElementStyle(popupElement, "transform", "none");
const restorePopupScale = overrideElementStyle(popupElement, "scale", "1");
const restorePositionerAvailableSize = applyElementStyles(positionerElement, {
"--available-width": "max-content",
"--available-height": "max-content"
});
function restoreMeasurementOverrides() {
restorePopupPosition();
restorePopupTransform();
restorePositionerAvailableSize();
}
function restoreMeasurementOverridesIncludingScale() {
restoreMeasurementOverrides();
restorePopupScale();
}
onMeasureLayout?.();
if (isInitialRenderRef.current || committedDimensionsRef.current === null) {
setPositionerCssSize(positionerElement, "max-content");
const dimensions = getCssDimensions2(popupElement);
committedDimensionsRef.current = dimensions;
setPositionerCssSize(positionerElement, dimensions);
restoreMeasurementOverridesIncludingScale();
onMeasureLayoutComplete?.(null, dimensions);
isInitialRenderRef.current = false;
return () => {
restoreAnchoringStylesRef.current();
restoreAnchoringStylesRef.current = NOOP;
};
}
setPositionerCssSize(positionerElement, "max-content");
const previousDimensions = committedDimensionsRef.current;
const newDimensions = getCssDimensions2(popupElement);
committedDimensionsRef.current = newDimensions;
setPopupCssSize(popupElement, previousDimensions);
restoreMeasurementOverridesIncludingScale();
onMeasureLayoutComplete?.(previousDimensions, newDimensions);
setPositionerCssSize(positionerElement, newDimensions);
const abortController = new AbortController();
animationFrame.request(() => {
setPopupCssSize(popupElement, newDimensions);
runOnceAnimationsFinish(() => {
popupElement.style.setProperty("--popup-width", "auto");
popupElement.style.setProperty("--popup-height", "auto");
}, abortController.signal);
});
return () => {
abortController.abort();
animationFrame.cancel();
restoreAnchoringStylesRef.current();
restoreAnchoringStylesRef.current = NOOP;
};
}, [content, popupElement, positionerElement, runOnceAnimationsFinish, animationFrame, mounted, onMeasureLayout, onMeasureLayoutComplete, anchoringStyles]);
}
function overrideElementStyle(element, property, value) {
const originalValue = element.style.getPropertyValue(property);
element.style.setProperty(property, value);
return () => {
element.style.setProperty(property, originalValue);
};
}
function applyElementStyles(element, styles) {
const restorers = [];
for (const [key, value] of Object.entries(styles)) {
restorers.push(overrideElementStyle(element, key, value));
}
return restorers.length ? () => {
restorers.forEach((restore2) => restore2());
} : NOOP;
}
function setPopupCssSize(popupElement, size4) {
const width = size4 === "auto" ? "auto" : `${size4.width}px`;
const height = size4 === "auto" ? "auto" : `${size4.height}px`;
popupElement.style.setProperty("--popup-width", width);
popupElement.style.setProperty("--popup-height", height);
}
function setPositionerCssSize(positionerElement, size4) {
const width = size4 === "max-content" ? "max-content" : `${size4.width}px`;
const height = size4 === "max-content" ? "max-content" : `${size4.height}px`;
positionerElement.style.setProperty("--positioner-width", width);
positionerElement.style.setProperty("--positioner-height", height);
}
// node_modules/@base-ui/react/utils/usePopupViewport.mjs
var import_jsx_runtime161 = __toESM(require_jsx_runtime(), 1);
function usePopupViewport(parameters) {
const {
store: store2,
side,
cssVars,
children
} = parameters;
const direction = useDirection();
const activeTrigger = store2.useState("activeTriggerElement");
const activeTriggerId = store2.useState("activeTriggerId");
const open = store2.useState("open");
const payload = store2.useState("payload");
const mounted = store2.useState("mounted");
const popupElement = store2.useState("popupElement");
const positionerElement = store2.useState("positionerElement");
const previousActiveTrigger = usePreviousValue(open ? activeTrigger : null);
const currentContentKey = usePopupContentKey(activeTriggerId, payload);
const capturedNodeRef = React66.useRef(null);
const [previousContentNode, setPreviousContentNode] = React66.useState(null);
const [newTriggerOffset, setNewTriggerOffset] = React66.useState(null);
const currentContainerRef = React66.useRef(null);
const previousContainerRef = React66.useRef(null);
const onAnimationsFinished = useAnimationsFinished(currentContainerRef, true, false);
const cleanupFrame = useAnimationFrame();
const [previousContentDimensions, setPreviousContentDimensions] = React66.useState(null);
const [showStartingStyleAttribute, setShowStartingStyleAttribute] = React66.useState(false);
useIsoLayoutEffect(() => {
store2.set("hasViewport", true);
return () => {
store2.set("hasViewport", false);
};
}, [store2]);
const handleMeasureLayout = useStableCallback(() => {
currentContainerRef.current?.style.setProperty("animation", "none");
currentContainerRef.current?.style.setProperty("transition", "none");
previousContainerRef.current?.style.setProperty("display", "none");
});
const handleMeasureLayoutComplete = useStableCallback((previousDimensions) => {
currentContainerRef.current?.style.removeProperty("animation");
currentContainerRef.current?.style.removeProperty("transition");
previousContainerRef.current?.style.removeProperty("display");
if (previousDimensions) {
setPreviousContentDimensions(previousDimensions);
}
});
const lastHandledTriggerRef = React66.useRef(null);
useIsoLayoutEffect(() => {
if (!open || !mounted) {
lastHandledTriggerRef.current = null;
}
}, [open, mounted]);
useIsoLayoutEffect(() => {
if (activeTrigger && previousActiveTrigger && activeTrigger !== previousActiveTrigger && lastHandledTriggerRef.current !== activeTrigger && capturedNodeRef.current) {
setPreviousContentNode(capturedNodeRef.current);
setShowStartingStyleAttribute(true);
const offset4 = calculateRelativePosition(previousActiveTrigger, activeTrigger);
setNewTriggerOffset(offset4);
cleanupFrame.request(() => {
ReactDOM6.flushSync(() => {
setShowStartingStyleAttribute(false);
});
onAnimationsFinished(() => {
setPreviousContentNode(null);
setPreviousContentDimensions(null);
capturedNodeRef.current = null;
});
});
lastHandledTriggerRef.current = activeTrigger;
}
}, [activeTrigger, previousActiveTrigger, previousContentNode, onAnimationsFinished, cleanupFrame]);
useIsoLayoutEffect(() => {
const source = currentContainerRef.current;
if (!source) {
return;
}
const wrapper = ownerDocument(source).createElement("div");
for (const child of Array.from(source.childNodes)) {
wrapper.appendChild(child.cloneNode(true));
}
capturedNodeRef.current = wrapper;
});
const isTransitioning = previousContentNode != null;
let childrenToRender;
if (!isTransitioning) {
childrenToRender = /* @__PURE__ */ (0, import_jsx_runtime161.jsx)("div", {
"data-current": true,
ref: currentContainerRef,
children
}, currentContentKey);
} else {
childrenToRender = /* @__PURE__ */ (0, import_jsx_runtime161.jsxs)(React66.Fragment, {
children: [/* @__PURE__ */ (0, import_jsx_runtime161.jsx)("div", {
"data-previous": true,
inert: inertValue(true),
ref: previousContainerRef,
style: {
...previousContentDimensions ? {
[cssVars.popupWidth]: `${previousContentDimensions.width}px`,
[cssVars.popupHeight]: `${previousContentDimensions.height}px`
} : null,
position: "absolute"
},
"data-ending-style": showStartingStyleAttribute ? void 0 : ""
}, "previous"), /* @__PURE__ */ (0, import_jsx_runtime161.jsx)("div", {
"data-current": true,
ref: currentContainerRef,
"data-starting-style": showStartingStyleAttribute ? "" : void 0,
children
}, currentContentKey)]
});
}
useIsoLayoutEffect(() => {
const container = previousContainerRef.current;
if (!container || !previousContentNode) {
return;
}
container.replaceChildren(...Array.from(previousContentNode.childNodes));
}, [previousContentNode]);
usePopupAutoResize({
popupElement,
positionerElement,
mounted,
content: payload,
onMeasureLayout: handleMeasureLayout,
onMeasureLayoutComplete: handleMeasureLayoutComplete,
side,
direction
});
const state = {
activationDirection: getActivationDirection(newTriggerOffset),
transitioning: isTransitioning
};
return {
children: childrenToRender,
state
};
}
function getActivationDirection(offset4) {
if (!offset4) {
return void 0;
}
return `${getValueWithTolerance(offset4.horizontal, 5, "right", "left")} ${getValueWithTolerance(offset4.vertical, 5, "down", "up")}`;
}
function getValueWithTolerance(value, tolerance, positiveLabel, negativeLabel) {
if (value > tolerance) {
return positiveLabel;
}
if (value < -tolerance) {
return negativeLabel;
}
return "";
}
function calculateRelativePosition(from, to2) {
const fromRect = from.getBoundingClientRect();
const toRect = to2.getBoundingClientRect();
const fromCenter = {
x: fromRect.left + fromRect.width / 2,
y: fromRect.top + fromRect.height / 2
};
const toCenter = {
x: toRect.left + toRect.width / 2,
y: toRect.top + toRect.height / 2
};
return {
horizontal: toCenter.x - fromCenter.x,
vertical: toCenter.y - fromCenter.y
};
}
function usePopupContentKey(activeTriggerId, payload) {
const [contentKey, setContentKey] = React66.useState(0);
const previousActiveTriggerIdRef = React66.useRef(activeTriggerId);
const previousPayloadRef = React66.useRef(payload);
const pendingPayloadUpdateRef = React66.useRef(false);
useIsoLayoutEffect(() => {
const previousActiveTriggerId = previousActiveTriggerIdRef.current;
const previousPayload = previousPayloadRef.current;
const triggerIdChanged = activeTriggerId !== previousActiveTriggerId;
const payloadChanged = payload !== previousPayload;
if (triggerIdChanged) {
setContentKey((value) => value + 1);
pendingPayloadUpdateRef.current = !payloadChanged;
} else if (pendingPayloadUpdateRef.current && payloadChanged) {
setContentKey((value) => value + 1);
pendingPayloadUpdateRef.current = false;
}
previousActiveTriggerIdRef.current = activeTriggerId;
previousPayloadRef.current = payload;
}, [activeTriggerId, payload]);
return `${activeTriggerId ?? "current"}-${contentKey}`;
}
// node_modules/@base-ui/utils/isElementDisabled.mjs
function isElementDisabled(element) {
return element == null || element.hasAttribute("disabled") || element.getAttribute("aria-disabled") === "true";
}
// node_modules/@base-ui/react/internals/csp-context/CSPContext.mjs
var React67 = __toESM(require_react(), 1);
var CSPContext = /* @__PURE__ */ React67.createContext(void 0);
if (true) CSPContext.displayName = "CSPContext";
var DEFAULT_CSP_CONTEXT_VALUE = {
disableStyleElements: false
};
function useCSPContext() {
return React67.useContext(CSPContext) ?? DEFAULT_CSP_CONTEXT_VALUE;
}
// node_modules/@base-ui/react/internals/clamp.mjs
function clamp2(val, min2 = Number.MIN_SAFE_INTEGER, max2 = Number.MAX_SAFE_INTEGER) {
return Math.max(min2, Math.min(val, max2));
}
// node_modules/@base-ui/react/field/index.parts.mjs
var index_parts_exports2 = {};
__export(index_parts_exports2, {
Control: () => FieldControl,
Description: () => FieldDescription,
Error: () => FieldError,
Item: () => FieldItem,
Label: () => FieldLabel,
Root: () => FieldRoot,
Validity: () => FieldValidity
});
// node_modules/@base-ui/react/field/root/FieldRoot.mjs
var React72 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/fieldset/root/FieldsetRootContext.mjs
var React68 = __toESM(require_react(), 1);
var FieldsetRootContext = /* @__PURE__ */ React68.createContext(void 0);
if (true) FieldsetRootContext.displayName = "FieldsetRootContext";
function useFieldsetRootContext(optional = false) {
const context = React68.useContext(FieldsetRootContext);
if (!context && !optional) {
throw new Error(true ? "Base UI: FieldsetRootContext is missing. Fieldset parts must be placed within <Fieldset.Root>." : formatErrorMessage_default(86));
}
return context;
}
// node_modules/@base-ui/react/internals/labelable-provider/LabelableProvider.mjs
var React69 = __toESM(require_react(), 1);
var import_jsx_runtime162 = __toESM(require_jsx_runtime(), 1);
var LabelableProvider = function LabelableProvider2(props) {
const defaultId = useBaseUiId();
const initialControlId = props.controlId === void 0 ? defaultId : props.controlId;
const [controlId, setControlIdState] = React69.useState(initialControlId);
const [labelId, setLabelId] = React69.useState(props.labelId);
const [messageIds, setMessageIds] = React69.useState([]);
const registrationsRef = useRefWithInit(() => /* @__PURE__ */ new Map());
const {
messageIds: parentMessageIds
} = useLabelableContext();
const registerControlId = useStableCallback((source, nextId2) => {
const registrations = registrationsRef.current;
if (nextId2 === void 0) {
registrations.delete(source);
return;
}
registrations.set(source, nextId2);
setControlIdState((prev) => {
if (registrations.size === 0) {
return void 0;
}
let nextControlId;
for (const id of registrations.values()) {
if (prev !== void 0 && id === prev) {
return prev;
}
if (nextControlId === void 0) {
nextControlId = id;
}
}
return nextControlId;
});
});
const getDescriptionProps = React69.useCallback((externalProps) => {
const ids = externalProps["aria-describedby"] ? externalProps["aria-describedby"].split(" ") : [];
ids.push(...parentMessageIds, ...messageIds);
return {
...externalProps,
"aria-describedby": Array.from(new Set(ids)).join(" ") || void 0
};
}, [parentMessageIds, messageIds]);
const contextValue = React69.useMemo(() => ({
controlId,
registerControlId,
labelId,
setLabelId,
messageIds,
setMessageIds,
getDescriptionProps
}), [controlId, registerControlId, labelId, setLabelId, messageIds, setMessageIds, getDescriptionProps]);
return /* @__PURE__ */ (0, import_jsx_runtime162.jsx)(LabelableContext.Provider, {
value: contextValue,
children: props.children
});
};
if (true) LabelableProvider.displayName = "LabelableProvider";
// node_modules/@base-ui/react/field/root/useFieldValidation.mjs
var React70 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/field/utils/getCombinedFieldValidityData.mjs
function getCombinedFieldValidityData(validityData, invalid) {
return {
...validityData,
state: {
...validityData.state,
valid: !invalid && validityData.state.valid
}
};
}
// node_modules/@base-ui/react/field/root/useFieldValidation.mjs
var validityKeys = Object.keys(DEFAULT_VALIDITY_STATE);
function isOnlyValueMissing(state) {
if (!state || state.valid || !state.valueMissing) {
return false;
}
let onlyValueMissing = false;
for (const key of validityKeys) {
if (key === "valid") {
continue;
}
if (key === "valueMissing") {
onlyValueMissing = state[key];
} else if (state[key]) {
onlyValueMissing = false;
}
}
return onlyValueMissing;
}
function findRepresentativeInput(inputs) {
let fallback = null;
for (const input of inputs) {
if (input.disabled) {
continue;
}
if (!input.validity.valid) {
return input;
}
fallback ??= input;
}
return fallback;
}
function clearCustomValidity(element, inputs) {
let didClearElement = false;
for (const input of inputs) {
input.setCustomValidity("");
didClearElement ||= input === element;
}
if (!didClearElement) {
element.setCustomValidity("");
}
}
function useFieldValidation(params) {
const {
formRef
} = useFormContext();
const {
setValidityData,
validate,
validityData,
validationDebounceTime,
invalid,
markedDirtyRef,
state,
shouldValidateOnChange,
getRegisteredFieldId
} = params;
const {
controlId,
getDescriptionProps
} = useLabelableContext();
const timeout = useTimeout();
const inputRef = React70.useRef(null);
const registeredInputs = useRefWithInit(() => /* @__PURE__ */ new Set()).current;
const validationCommitIdRef = React70.useRef(0);
const registerInput = React70.useCallback((element) => {
if (!element) {
return void 0;
}
registeredInputs.add(element);
return () => {
registeredInputs.delete(element);
};
}, [registeredInputs]);
const commit = useStableCallback(async (value, revalidate = false) => {
const element = findRepresentativeInput(registeredInputs) ?? inputRef.current;
if (!element) {
return;
}
validationCommitIdRef.current += 1;
const validationCommitId = validationCommitIdRef.current;
function updateRegisteredFieldValidity(nextValidityData2, externalInvalid = invalid) {
const fieldId = getRegisteredFieldId() ?? controlId;
if (fieldId == null) {
return;
}
const currentFieldData = formRef.current.fields.get(fieldId);
if (!currentFieldData) {
return;
}
const validityDataWithFormErrors = getCombinedFieldValidityData(nextValidityData2, externalInvalid);
formRef.current.fields.set(fieldId, {
...currentFieldData,
validityData: validityDataWithFormErrors
});
}
if (revalidate) {
if (state.valid !== false) {
return;
}
const currentNativeValidity = element.validity;
if (!currentNativeValidity.valueMissing) {
const nextValidityData2 = {
value,
state: {
...DEFAULT_VALIDITY_STATE,
valid: true
},
error: "",
errors: [],
initialValue: validityData.initialValue
};
clearCustomValidity(element, registeredInputs);
updateRegisteredFieldValidity(nextValidityData2, false);
setValidityData(nextValidityData2);
return;
}
const currentNativeValidityObject = validityKeys.reduce((acc, key) => {
acc[key] = currentNativeValidity[key];
return acc;
}, {});
if (!currentNativeValidityObject.valid && !isOnlyValueMissing(currentNativeValidityObject)) {
return;
}
}
function getState(el) {
const computedState = validityKeys.reduce((acc, key) => {
acc[key] = el.validity[key];
return acc;
}, {});
let hasOnlyValueMissingError = false;
for (const key of validityKeys) {
if (key === "valid") {
continue;
}
if (key === "valueMissing" && computedState[key]) {
hasOnlyValueMissingError = true;
} else if (computedState[key]) {
return computedState;
}
}
if (hasOnlyValueMissingError && !markedDirtyRef.current) {
computedState.valid = true;
computedState.valueMissing = false;
}
return computedState;
}
timeout.clear();
let result = null;
let validationErrors = [];
const nextState = getState(element);
let defaultValidationMessage;
const isValidatingOnChange = shouldValidateOnChange();
if (element.validationMessage && !isValidatingOnChange) {
defaultValidationMessage = element.validationMessage;
validationErrors = [element.validationMessage];
} else {
const formValues = Array.from(formRef.current.fields.values()).reduce((acc, field) => {
if (field.name) {
acc[field.name] = field.getValue();
}
return acc;
}, {});
const resultOrPromise = validate(value, formValues);
if (typeof resultOrPromise === "object" && resultOrPromise !== null && "then" in resultOrPromise) {
result = await resultOrPromise;
if (validationCommitId !== validationCommitIdRef.current) {
return;
}
} else {
result = resultOrPromise;
}
if (result !== null) {
nextState.valid = false;
nextState.customError = true;
if (Array.isArray(result)) {
validationErrors = result;
element.setCustomValidity(result.join("\n"));
} else if (result) {
validationErrors = [result];
element.setCustomValidity(result);
}
} else if (isValidatingOnChange) {
clearCustomValidity(element, registeredInputs);
nextState.customError = false;
if (element.validationMessage) {
defaultValidationMessage = element.validationMessage;
validationErrors = [element.validationMessage];
} else if (element.validity.valid && !nextState.valid) {
nextState.valid = true;
}
}
}
const nextValidityData = {
value,
state: nextState,
error: defaultValidationMessage ?? (Array.isArray(result) ? result[0] : result ?? ""),
errors: validationErrors,
initialValue: validityData.initialValue
};
updateRegisteredFieldValidity(nextValidityData);
setValidityData(nextValidityData);
});
const change = useStableCallback((value) => {
timeout.clear();
const validateOnChange = shouldValidateOnChange();
if (validateOnChange && value !== "" && validationDebounceTime) {
validationCommitIdRef.current += 1;
timeout.start(validationDebounceTime, () => {
commit(value);
});
} else {
commit(value, !validateOnChange);
}
});
const getValidationProps = React70.useCallback((disabled2, externalProps = {}) => mergeProps(getDescriptionProps(externalProps), state.valid === false && !state.disabled && !disabled2 ? {
"aria-invalid": true
} : EMPTY_OBJECT), [getDescriptionProps, state.disabled, state.valid]);
return React70.useMemo(() => ({
getValidationProps,
inputRef,
registerInput,
commit,
change
}), [getValidationProps, registerInput, commit, change]);
}
// node_modules/@base-ui/react/internals/field-register-control/useFieldControlRegistration.mjs
var React71 = __toESM(require_react(), 1);
function useFieldControlRegistration(params) {
const {
commit,
invalid,
markedDirtyRef,
name,
setRegisteredFieldName,
setRegisteredFieldId,
setValidityData,
validityData
} = params;
const {
formRef
} = useFormContext();
const activeFieldControlSourceRef = React71.useRef(null);
const registrationRef = React71.useRef(null);
const fallbackControlRef = React71.useRef(null);
const getValueForForm = useStableCallback(() => {
const registration = registrationRef.current;
if (!registration) {
return void 0;
}
if (registration.getValue) {
return registration.getValue();
}
return registration.value;
});
function getRegistrationValue(registration) {
return registration.value === void 0 ? getValueForForm() : registration.value;
}
const validate = useStableCallback(() => {
const registration = registrationRef.current;
markedDirtyRef.current = true;
if (!registration) {
commit(validityData.value);
return;
}
commit(getRegistrationValue(registration));
});
function refreshRegistration() {
const registration = registrationRef.current;
if (!registration || !registration.id) {
return;
}
formRef.current.fields.set(registration.id, {
getValue: getValueForForm,
name: name ?? registration.name,
controlRef: registration.controlRef ?? fallbackControlRef,
validityData: getCombinedFieldValidityData(validityData, invalid),
validate
});
}
function deleteRegistration(id = registrationRef.current?.id) {
if (id) {
formRef.current.fields.delete(id);
}
}
function syncInitialValue() {
const registration = registrationRef.current;
if (!registration) {
return;
}
const initialValue = getRegistrationValue(registration);
if (validityData.initialValue === null && initialValue !== null) {
setValidityData((prev) => ({
...prev,
initialValue
}));
}
}
useIsoLayoutEffect(() => {
const registration = registrationRef.current;
if (!registration || !registration.id) {
return;
}
setRegisteredFieldName(name ? void 0 : registration.name);
formRef.current.fields.set(registration.id, {
getValue: getValueForForm,
name: name ?? registration.name,
controlRef: registration.controlRef ?? fallbackControlRef,
validityData: getCombinedFieldValidityData(validityData, invalid),
validate
});
}, [formRef, getValueForForm, invalid, name, setRegisteredFieldName, validate, validityData]);
useIsoLayoutEffect(() => {
const fields = formRef.current.fields;
return () => {
const id = registrationRef.current?.id;
if (id) {
fields.delete(id);
}
};
}, [formRef]);
const register2 = useStableCallback((source, registration) => {
if (!registration) {
if (activeFieldControlSourceRef.current === source) {
activeFieldControlSourceRef.current = null;
deleteRegistration();
registrationRef.current = null;
setRegisteredFieldName(void 0);
setRegisteredFieldId(void 0);
}
return;
}
const previousId = registrationRef.current?.id;
activeFieldControlSourceRef.current = source;
registrationRef.current = registration;
if (!name) {
setRegisteredFieldName(registration.name);
}
setRegisteredFieldId(registration.id);
if (previousId && previousId !== registration.id) {
deleteRegistration(previousId);
}
syncInitialValue();
refreshRegistration();
});
return [validate, register2];
}
// node_modules/@base-ui/react/field/root/FieldRoot.mjs
var import_jsx_runtime163 = __toESM(require_jsx_runtime(), 1);
var FieldRootInner = /* @__PURE__ */ React72.forwardRef(function FieldRootInner2(componentProps, forwardedRef) {
const {
errors,
validationMode: formValidationMode,
submitAttemptedRef
} = useFormContext();
const {
render: render4,
className,
validate: validateProp,
validationDebounceTime = 0,
validationMode = formValidationMode,
name,
disabled: disabledProp = false,
invalid: invalidProp,
dirty: dirtyProp,
touched: touchedProp,
actionsRef,
style,
...elementProps
} = componentProps;
const disabledFieldset = useFieldsetRootContext(true)?.disabled;
const validate = useStableCallback(validateProp || (() => null));
const disabled2 = disabledFieldset || disabledProp;
const [touchedState, setTouchedUnwrapped] = React72.useState(false);
const [dirtyState, setDirtyUnwrapped] = React72.useState(false);
const [filled, setFilled] = React72.useState(false);
const [focused, setFocused] = React72.useState(false);
const dirty = dirtyProp ?? dirtyState;
const touched = touchedProp ?? touchedState;
const markedDirtyRef = React72.useRef(dirty);
const registeredFieldIdRef = React72.useRef(void 0);
const [registeredFieldName, setRegisteredFieldName] = React72.useState();
const effectiveName = name ?? registeredFieldName;
useIsoLayoutEffect(() => {
if (dirtyProp !== void 0) {
markedDirtyRef.current = dirtyProp;
}
}, [dirtyProp]);
const getRegisteredFieldId = React72.useCallback(() => registeredFieldIdRef.current, []);
const setRegisteredFieldId = React72.useCallback((id) => {
registeredFieldIdRef.current = id;
}, []);
const setDirty = useStableCallback((value) => {
if (dirtyProp !== void 0) {
return;
}
if (value) {
markedDirtyRef.current = true;
}
setDirtyUnwrapped(value);
});
const setTouched = useStableCallback((value) => {
if (touchedProp !== void 0) {
return;
}
setTouchedUnwrapped(value);
});
const shouldValidateOnChange = useStableCallback(() => validationMode === "onChange" || validationMode === "onSubmit" && submitAttemptedRef.current);
const formError = effectiveName && Object.hasOwn(errors, effectiveName) ? errors[effectiveName] : null;
const hasFormError = !!(Array.isArray(formError) ? formError.length : formError);
const invalid = invalidProp === true || hasFormError;
const [validityData, setValidityData] = React72.useState({
state: DEFAULT_VALIDITY_STATE,
error: "",
errors: [],
value: null,
initialValue: null
});
const valid = disabled2 ? null : !invalid && validityData.state.valid;
const state = React72.useMemo(() => ({
disabled: disabled2,
touched,
dirty,
valid,
filled,
focused
}), [disabled2, touched, dirty, valid, filled, focused]);
const validation = useFieldValidation({
setValidityData,
validate,
validityData,
validationDebounceTime,
invalid,
markedDirtyRef,
state,
shouldValidateOnChange,
getRegisteredFieldId
});
const [validateFieldControl, registerFieldControl] = useFieldControlRegistration({
commit: validation.commit,
invalid,
markedDirtyRef,
name,
setRegisteredFieldName,
setRegisteredFieldId,
setValidityData,
validityData
});
React72.useImperativeHandle(actionsRef, () => ({
validate: validateFieldControl
}), [validateFieldControl]);
const contextValue = React72.useMemo(() => ({
invalid,
name: effectiveName,
validityData,
setValidityData,
disabled: disabled2,
touched,
setTouched,
dirty,
setDirty,
filled,
setFilled,
focused,
setFocused,
validate,
validationMode,
validationDebounceTime,
shouldValidateOnChange,
state,
markedDirtyRef,
registerFieldControl,
validation
}), [invalid, effectiveName, validityData, disabled2, touched, setTouched, dirty, setDirty, filled, setFilled, focused, setFocused, validate, validationMode, validationDebounceTime, shouldValidateOnChange, state, registerFieldControl, validation]);
const element = useRenderElement("div", componentProps, {
ref: forwardedRef,
state,
props: elementProps,
stateAttributesMapping: fieldValidityMapping
});
return /* @__PURE__ */ (0, import_jsx_runtime163.jsx)(FieldRootContext.Provider, {
value: contextValue,
children: element
});
});
if (true) FieldRootInner.displayName = "FieldRootInner";
var FieldRoot = /* @__PURE__ */ React72.forwardRef(function FieldRoot2(componentProps, forwardedRef) {
return /* @__PURE__ */ (0, import_jsx_runtime163.jsx)(LabelableProvider, {
children: /* @__PURE__ */ (0, import_jsx_runtime163.jsx)(FieldRootInner, {
...componentProps,
ref: forwardedRef
})
});
});
if (true) FieldRoot.displayName = "FieldRoot";
// node_modules/@base-ui/react/field/label/FieldLabel.mjs
var React73 = __toESM(require_react(), 1);
var FieldLabel = /* @__PURE__ */ React73.forwardRef(function FieldLabel2(componentProps, forwardedRef) {
const {
render: render4,
className,
style,
id: idProp,
nativeLabel = true,
...elementProps
} = componentProps;
const fieldRootContext = useFieldRootContext(false);
const fieldItemContext = useFieldItemContext();
const {
labelId
} = useLabelableContext();
const state = {
...fieldRootContext.state,
disabled: fieldRootContext.disabled || fieldItemContext.disabled
};
const labelRef = React73.useRef(null);
const labelProps = useLabel({
id: labelId ?? idProp,
native: nativeLabel
});
if (true) {
React73.useEffect(() => {
if (!labelRef.current) {
return;
}
const isLabelTag = labelRef.current.tagName === "LABEL";
if (nativeLabel) {
if (!isLabelTag) {
const ownerStackMessage = SafeReact.captureOwnerStack?.() || "";
const message2 = "<Field.Label> expected a <label> element because the `nativeLabel` prop is true. Rendering a non-<label> disables native label association, so `htmlFor` will not work. Use a real <label> in the `render` prop, or set `nativeLabel` to `false`.";
error(`${message2}${ownerStackMessage}`);
}
} else if (isLabelTag) {
const ownerStackMessage = SafeReact.captureOwnerStack?.() || "";
const message2 = "<Field.Label> expected a non-<label> element because the `nativeLabel` prop is false. Rendering a <label> assumes native label behavior while Base UI treats it as non-native, which can cause unexpected pointer behavior. Use a non-<label> in the `render` prop, or set `nativeLabel` to `true`.";
error(`${message2}${ownerStackMessage}`);
}
}, [nativeLabel]);
}
const element = useRenderElement("label", componentProps, {
ref: [forwardedRef, labelRef],
state,
props: [labelProps, elementProps],
stateAttributesMapping: fieldValidityMapping
});
return element;
});
if (true) FieldLabel.displayName = "FieldLabel";
// node_modules/@base-ui/react/field/error/FieldError.mjs
var React74 = __toESM(require_react(), 1);
var import_jsx_runtime164 = __toESM(require_jsx_runtime(), 1);
var stateAttributesMapping2 = {
...fieldValidityMapping,
...transitionStatusMapping
};
var FieldError = /* @__PURE__ */ React74.forwardRef(function FieldError2(componentProps, forwardedRef) {
const {
render: render4,
id: idProp,
className,
match: match2,
style,
...elementProps
} = componentProps;
const id = useBaseUiId(idProp);
const {
validityData,
state: fieldState,
name
} = useFieldRootContext(false);
const {
setMessageIds
} = useLabelableContext();
const {
errors
} = useFormContext();
const formError = name && Object.hasOwn(errors, name) ? errors[name] : null;
const hasFormError = !!(Array.isArray(formError) ? formError.length : formError);
const hasSpecificMatch = typeof match2 === "string";
let rendered = false;
if (match2 === true) {
rendered = true;
} else if (fieldState.disabled) {
rendered = false;
} else if (hasSpecificMatch) {
rendered = Boolean(validityData.state[match2]);
} else {
rendered = hasFormError || validityData.state.valid === false;
}
const {
mounted,
transitionStatus,
setMounted
} = useTransitionStatus(rendered);
useIsoLayoutEffect(() => {
if (!rendered || !id) {
return void 0;
}
setMessageIds((v2) => v2.concat(id));
return () => {
setMessageIds((v2) => v2.filter((item) => item !== id));
};
}, [rendered, id, setMessageIds]);
const errorRef = React74.useRef(null);
const [lastRenderedMessage, setLastRenderedMessage] = React74.useState(null);
const [lastRenderedMessageKey, setLastRenderedMessageKey] = React74.useState(null);
let error2 = validityData.error;
if (!hasSpecificMatch && hasFormError) {
error2 = formError;
} else if (validityData.errors.length > 1) {
error2 = validityData.errors;
}
let errorMessage = error2 ?? "";
if (Array.isArray(error2)) {
errorMessage = error2.length > 1 ? /* @__PURE__ */ (0, import_jsx_runtime164.jsx)("ul", {
children: error2.map((message2) => /* @__PURE__ */ (0, import_jsx_runtime164.jsx)("li", {
children: message2
}, message2))
}) : error2[0] ?? "";
}
const errorKey = Array.isArray(error2) ? JSON.stringify(error2) : error2;
if (rendered && errorKey !== lastRenderedMessageKey) {
setLastRenderedMessageKey(errorKey);
setLastRenderedMessage(errorMessage);
}
useOpenChangeComplete({
open: rendered,
ref: errorRef,
onComplete() {
if (!rendered) {
setMounted(false);
}
}
});
const state = {
...fieldState,
transitionStatus
};
const element = useRenderElement("div", componentProps, {
ref: [forwardedRef, errorRef],
state,
props: [{
id,
children: rendered ? errorMessage : lastRenderedMessage
}, elementProps],
stateAttributesMapping: stateAttributesMapping2,
enabled: mounted
});
if (!mounted) {
return null;
}
return element;
});
if (true) FieldError.displayName = "FieldError";
// node_modules/@base-ui/react/field/description/FieldDescription.mjs
var React75 = __toESM(require_react(), 1);
var FieldDescription = /* @__PURE__ */ React75.forwardRef(function FieldDescription2(componentProps, forwardedRef) {
const {
render: render4,
id: idProp,
className,
style,
...elementProps
} = componentProps;
const id = useBaseUiId(idProp);
const fieldRootContext = useFieldRootContext(false);
const fieldItemContext = useFieldItemContext();
const {
setMessageIds
} = useLabelableContext();
const state = {
...fieldRootContext.state,
disabled: fieldRootContext.disabled || fieldItemContext.disabled
};
useIsoLayoutEffect(() => {
if (!id) {
return void 0;
}
setMessageIds((v2) => v2.concat(id));
return () => {
setMessageIds((v2) => v2.filter((item) => item !== id));
};
}, [id, setMessageIds]);
const element = useRenderElement("p", componentProps, {
ref: forwardedRef,
state,
props: [{
id
}, elementProps],
stateAttributesMapping: fieldValidityMapping
});
return element;
});
if (true) FieldDescription.displayName = "FieldDescription";
// node_modules/@base-ui/react/field/control/FieldControl.mjs
var React76 = __toESM(require_react(), 1);
var FieldControl = /* @__PURE__ */ React76.forwardRef(function FieldControl2(componentProps, forwardedRef) {
const {
render: render4,
className,
id: idProp,
name: nameProp,
value: valueProp,
disabled: disabledProp = false,
onValueChange,
defaultValue,
autoFocus = false,
style,
...elementProps
} = componentProps;
const {
state: fieldState,
name: fieldName,
disabled: fieldDisabled,
setTouched,
setDirty,
validityData,
setFocused,
setFilled,
validationMode,
validation
} = useFieldRootContext();
const {
clearErrors
} = useFormContext();
const disabled2 = fieldDisabled || disabledProp;
const name = fieldName ?? nameProp;
const state = {
...fieldState,
disabled: disabled2
};
const {
labelId
} = useLabelableContext();
const id = useLabelableId({
id: idProp
});
useIsoLayoutEffect(() => {
const hasExternalValue = valueProp != null;
if (validation.inputRef.current?.value || hasExternalValue && valueProp !== "") {
setFilled(true);
} else if (hasExternalValue && valueProp === "") {
setFilled(false);
}
}, [validation.inputRef, setFilled, valueProp]);
const inputRef = React76.useRef(null);
useIsoLayoutEffect(() => {
if (autoFocus && inputRef.current === activeElement(ownerDocument(inputRef.current))) {
setFocused(true);
}
}, [autoFocus, setFocused]);
const [valueUnwrapped] = useControlled({
controlled: valueProp,
default: defaultValue,
name: "FieldControl",
state: "value"
});
const isControlled = valueProp !== void 0;
const value = isControlled ? valueUnwrapped : void 0;
const getValueFromInput = useStableCallback(() => validation.inputRef.current?.value);
useRegisterFieldControl(validation.inputRef, id, value, getValueFromInput, !disabled2, nameProp);
const element = useRenderElement("input", componentProps, {
ref: [forwardedRef, inputRef],
state,
props: [{
id,
disabled: disabled2,
name,
ref: validation.inputRef,
"aria-labelledby": labelId,
autoFocus,
...isControlled ? {
value
} : {
defaultValue
},
onChange(event) {
const inputValue = event.currentTarget.value;
onValueChange?.(inputValue, createChangeEventDetails(reason_parts_exports.none, event.nativeEvent));
setDirty(inputValue !== validityData.initialValue);
setFilled(inputValue !== "");
if (!event.nativeEvent.defaultPrevented) {
clearErrors(name);
validation.change(inputValue);
}
},
onFocus() {
setFocused(true);
},
onBlur(event) {
setTouched(true);
setFocused(false);
if (validationMode === "onBlur") {
validation.commit(event.currentTarget.value);
}
},
onKeyDown(event) {
if (event.currentTarget.tagName === "INPUT" && event.key === "Enter") {
setTouched(true);
validation.commit(event.currentTarget.value);
}
}
}, elementProps, (props) => validation.getValidationProps(disabled2, props)],
stateAttributesMapping: fieldValidityMapping
});
return element;
});
if (true) FieldControl.displayName = "FieldControl";
// node_modules/@base-ui/react/field/validity/FieldValidity.mjs
var React77 = __toESM(require_react(), 1);
var import_jsx_runtime165 = __toESM(require_jsx_runtime(), 1);
var FieldValidity = function FieldValidity2(props) {
const {
children
} = props;
const {
validityData,
invalid
} = useFieldRootContext(false);
const combinedFieldValidityData = React77.useMemo(() => getCombinedFieldValidityData(validityData, invalid), [validityData, invalid]);
const isInvalid = combinedFieldValidityData.state.valid === false;
const {
transitionStatus
} = useTransitionStatus(isInvalid);
const fieldValidityState = React77.useMemo(() => {
return {
...combinedFieldValidityData,
validity: combinedFieldValidityData.state,
transitionStatus
};
}, [combinedFieldValidityData, transitionStatus]);
return /* @__PURE__ */ (0, import_jsx_runtime165.jsx)(React77.Fragment, {
children: children(fieldValidityState)
});
};
if (true) FieldValidity.displayName = "FieldValidity";
// node_modules/@base-ui/react/field/item/FieldItem.mjs
var React78 = __toESM(require_react(), 1);
var import_jsx_runtime166 = __toESM(require_jsx_runtime(), 1);
var FieldItem = /* @__PURE__ */ React78.forwardRef(function FieldItem2(componentProps, forwardedRef) {
const {
render: render4,
className,
style,
disabled: disabledProp = false,
...elementProps
} = componentProps;
const {
state: fieldState,
disabled: rootDisabled
} = useFieldRootContext(false);
const disabled2 = rootDisabled || disabledProp;
const state = {
...fieldState,
disabled: disabled2
};
const checkboxGroupContext = useCheckboxGroupContext();
const hasParentCheckbox = checkboxGroupContext?.allValues !== void 0;
const controlId = hasParentCheckbox ? checkboxGroupContext?.parent.id : void 0;
const fieldItemContext = React78.useMemo(() => ({
disabled: disabled2
}), [disabled2]);
const element = useRenderElement("div", componentProps, {
ref: forwardedRef,
state,
props: elementProps,
stateAttributesMapping: fieldValidityMapping
});
return /* @__PURE__ */ (0, import_jsx_runtime166.jsx)(LabelableProvider, {
controlId,
children: /* @__PURE__ */ (0, import_jsx_runtime166.jsx)(FieldItemContext.Provider, {
value: fieldItemContext,
children: element
})
});
});
if (true) FieldItem.displayName = "FieldItem";
// node_modules/@base-ui/react/utils/FloatingPortalLite.mjs
var React79 = __toESM(require_react(), 1);
var ReactDOM7 = __toESM(require_react_dom(), 1);
var import_jsx_runtime167 = __toESM(require_jsx_runtime(), 1);
var FloatingPortalLite = /* @__PURE__ */ React79.forwardRef(function FloatingPortalLite2(componentProps, forwardedRef) {
const {
children,
container,
className,
render: render4,
style,
...elementProps
} = componentProps;
const {
portalNode,
portalSubtree
} = useFloatingPortalNode({
container,
ref: forwardedRef,
componentProps,
elementProps
});
if (!portalSubtree && !portalNode) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime167.jsxs)(React79.Fragment, {
children: [portalSubtree, portalNode && /* @__PURE__ */ ReactDOM7.createPortal(children, portalNode)]
});
});
if (true) FloatingPortalLite.displayName = "FloatingPortalLite";
// node_modules/@base-ui/react/utils/styles.mjs
var import_jsx_runtime168 = __toESM(require_jsx_runtime(), 1);
var DISABLE_SCROLLBAR_CLASS_NAME = "base-ui-disable-scrollbar";
var styleDisableScrollbar = {
className: DISABLE_SCROLLBAR_CLASS_NAME,
getElement(nonce) {
return /* @__PURE__ */ (0, import_jsx_runtime168.jsx)("style", {
nonce,
href: DISABLE_SCROLLBAR_CLASS_NAME,
precedence: "base-ui:low",
children: `.${DISABLE_SCROLLBAR_CLASS_NAME}{scrollbar-width:none}.${DISABLE_SCROLLBAR_CLASS_NAME}::-webkit-scrollbar{display:none}`
});
}
};
if (true) styleDisableScrollbar.getElement.displayName = "styleDisableScrollbar.getElement";
// node_modules/@base-ui/react/utils/scrollEdges.mjs
var SCROLL_EDGE_TOLERANCE_PX = 1;
function getMaxScrollOffset(scrollSize, clientSize) {
return Math.max(0, scrollSize - clientSize);
}
function normalizeScrollOffset(value, max2) {
if (max2 <= 0) {
return 0;
}
const clamped = clamp2(value, 0, max2);
const startDistance = clamped;
const endDistance = max2 - clamped;
const withinStartTolerance = startDistance <= SCROLL_EDGE_TOLERANCE_PX;
const withinEndTolerance = endDistance <= SCROLL_EDGE_TOLERANCE_PX;
if (withinStartTolerance && withinEndTolerance) {
return startDistance <= endDistance ? 0 : max2;
}
if (withinStartTolerance) {
return 0;
}
if (withinEndTolerance) {
return max2;
}
return clamped;
}
// node_modules/@base-ui/react/select/index.parts.mjs
var index_parts_exports3 = {};
__export(index_parts_exports3, {
Arrow: () => SelectArrow,
Backdrop: () => SelectBackdrop,
Group: () => SelectGroup,
GroupLabel: () => SelectGroupLabel,
Icon: () => SelectIcon,
Item: () => SelectItem,
ItemIndicator: () => SelectItemIndicator,
ItemText: () => SelectItemText,
Label: () => SelectLabel,
List: () => SelectList,
Popup: () => SelectPopup,
Portal: () => SelectPortal,
Positioner: () => SelectPositioner,
Root: () => SelectRoot,
ScrollDownArrow: () => SelectScrollDownArrow,
ScrollUpArrow: () => SelectScrollUpArrow,
Separator: () => Separator,
Trigger: () => SelectTrigger,
Value: () => SelectValue
});
// node_modules/@base-ui/react/select/root/SelectRoot.mjs
var React81 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/select/root/SelectRootContext.mjs
var React80 = __toESM(require_react(), 1);
var SelectRootContext = /* @__PURE__ */ React80.createContext(null);
if (true) SelectRootContext.displayName = "SelectRootContext";
var SelectFloatingContext = /* @__PURE__ */ React80.createContext(null);
if (true) SelectFloatingContext.displayName = "SelectFloatingContext";
function useSelectRootContext() {
const context = React80.useContext(SelectRootContext);
if (context === null) {
throw new Error(true ? "Base UI: SelectRootContext is missing. Select parts must be placed within <Select.Root>." : formatErrorMessage_default(60));
}
return context;
}
function useSelectFloatingContext() {
const context = React80.useContext(SelectFloatingContext);
if (context === null) {
throw new Error(true ? "Base UI: SelectFloatingContext is missing. Select parts must be placed within <Select.Root>." : formatErrorMessage_default(61));
}
return context;
}
// node_modules/@base-ui/react/select/store.mjs
var selectors2 = {
id: createSelector3((state) => state.id),
labelId: createSelector3((state) => state.labelId),
modal: createSelector3((state) => state.modal),
multiple: createSelector3((state) => state.multiple),
items: createSelector3((state) => state.items),
itemToStringLabel: createSelector3((state) => state.itemToStringLabel),
itemToStringValue: createSelector3((state) => state.itemToStringValue),
isItemEqualToValue: createSelector3((state) => state.isItemEqualToValue),
value: createSelector3((state) => state.value),
hasSelectedValue: createSelector3((state) => {
const {
value,
multiple,
itemToStringValue
} = state;
if (value == null) {
return false;
}
if (multiple && Array.isArray(value)) {
return value.length > 0;
}
return stringifyAsValue(value, itemToStringValue) !== "";
}),
hasNullItemLabel: createSelector3((state, enabled) => {
return enabled ? hasNullItemLabel(state.items) : false;
}),
open: createSelector3((state) => state.open),
mounted: createSelector3((state) => state.mounted),
forceMount: createSelector3((state) => state.forceMount),
transitionStatus: createSelector3((state) => state.transitionStatus),
openMethod: createSelector3((state) => state.openMethod),
activeIndex: createSelector3((state) => state.activeIndex),
selectedIndex: createSelector3((state) => state.selectedIndex),
isActive: createSelector3((state, index2) => state.activeIndex === index2),
isSelected: createSelector3((state, itemValue) => {
const comparer = state.isItemEqualToValue;
const storeValue = state.value;
if (state.multiple) {
return Array.isArray(storeValue) && storeValue.some((selectedItem) => compareItemEquality(itemValue, selectedItem, comparer));
}
return compareItemEquality(itemValue, storeValue, comparer);
}),
isSelectedByFocus: createSelector3((state, index2) => {
return state.selectedIndex === index2;
}),
popupProps: createSelector3((state) => state.popupProps),
triggerProps: createSelector3((state) => state.triggerProps),
triggerElement: createSelector3((state) => state.triggerElement),
positionerElement: createSelector3((state) => state.positionerElement),
listElement: createSelector3((state) => state.listElement),
popupSide: createSelector3((state) => state.popupSide),
scrollUpArrowVisible: createSelector3((state) => state.scrollUpArrowVisible),
scrollDownArrowVisible: createSelector3((state) => state.scrollDownArrowVisible),
hasScrollArrows: createSelector3((state) => state.hasScrollArrows)
};
// node_modules/@base-ui/react/select/root/SelectRoot.mjs
var import_jsx_runtime169 = __toESM(require_jsx_runtime(), 1);
function SelectRoot(props) {
const {
id,
value: valueProp,
defaultValue = null,
onValueChange,
open: openProp,
defaultOpen = false,
onOpenChange,
name: nameProp,
form,
autoComplete,
disabled: disabledProp = false,
readOnly = false,
required = false,
modal = true,
actionsRef,
inputRef,
onOpenChangeComplete,
items,
multiple = false,
itemToStringLabel,
itemToStringValue,
isItemEqualToValue = defaultItemEquality,
highlightItemOnHover = true,
children
} = props;
const {
clearErrors
} = useFormContext();
const {
setDirty,
setTouched,
setFocused,
validityData,
setFilled,
name: fieldName,
disabled: fieldDisabled,
validation,
validationMode
} = useFieldRootContext();
const generatedId = useLabelableId({
id
});
const disabled2 = fieldDisabled || disabledProp;
const name = fieldName ?? nameProp;
const [value, setValueUnwrapped] = useControlled({
controlled: valueProp,
default: multiple ? defaultValue ?? EMPTY_ARRAY5 : defaultValue,
name: "Select",
state: "value"
});
const [open, setOpenUnwrapped] = useControlled({
controlled: openProp,
default: defaultOpen,
name: "Select",
state: "open"
});
const listRef = React81.useRef([]);
const labelsRef = React81.useRef([]);
const popupRef = React81.useRef(null);
const scrollHandlerRef = React81.useRef(null);
const scrollArrowsMountedCountRef = React81.useRef(0);
const valueRef = React81.useRef(null);
const valuesRef = React81.useRef([]);
const typingRef = React81.useRef(false);
const firstItemTextRef = React81.useRef(null);
const selectedItemTextRef = React81.useRef(null);
const selectionRef = React81.useRef({
allowSelectedMouseUp: false,
allowUnselectedMouseUp: false,
dragY: 0
});
const alignItemWithTriggerActiveRef = React81.useRef(false);
const {
mounted,
setMounted,
transitionStatus
} = useTransitionStatus(open);
const {
openMethod,
triggerProps: interactionTypeProps
} = useOpenInteractionType(open);
const store2 = useRefWithInit(() => new Store({
id: generatedId,
labelId: void 0,
modal,
multiple,
itemToStringLabel,
itemToStringValue,
isItemEqualToValue,
value,
open,
mounted,
transitionStatus,
items,
forceMount: false,
openMethod: null,
activeIndex: null,
selectedIndex: null,
popupProps: {},
triggerProps: {},
triggerElement: null,
positionerElement: null,
listElement: null,
popupSide: null,
scrollUpArrowVisible: false,
scrollDownArrowVisible: false,
hasScrollArrows: false
})).current;
const activeIndex = useStore(store2, selectors2.activeIndex);
const selectedIndex = useStore(store2, selectors2.selectedIndex);
const triggerElement = useStore(store2, selectors2.triggerElement);
const positionerElement = useStore(store2, selectors2.positionerElement);
const previousOpenMethod = usePreviousValue(openMethod);
const renderedOpenMethod = openMethod ?? previousOpenMethod ?? null;
const serializedValue = React81.useMemo(() => {
if (multiple) {
return "";
}
return stringifyAsValue(value, itemToStringValue);
}, [multiple, value, itemToStringValue]);
const fieldStringValue = React81.useMemo(() => {
if (multiple && Array.isArray(value)) {
return value.map((currentValue) => stringifyAsValue(currentValue, itemToStringValue));
}
return stringifyAsValue(value, itemToStringValue);
}, [multiple, value, itemToStringValue]);
const controlRef = useValueAsRef(store2.state.triggerElement);
const getStringifiedValueForForm = useStableCallback(() => fieldStringValue);
useRegisterFieldControl(controlRef, generatedId, value, getStringifiedValueForForm, !disabled2, nameProp);
const initialValueRef = React81.useRef(value);
const hasSelectedValue = multiple ? Array.isArray(value) && value.length > 0 : value != null && stringifyAsValue(value, itemToStringValue) !== "";
useIsoLayoutEffect(() => {
if (value !== initialValueRef.current) {
store2.set("forceMount", true);
}
}, [store2, value]);
useIsoLayoutEffect(() => {
setFilled(hasSelectedValue);
}, [hasSelectedValue, setFilled]);
useIsoLayoutEffect(function syncSelectedIndex() {
const registry = valuesRef.current;
let nextIndex;
if (multiple) {
const currentValue = Array.isArray(value) ? value : [];
if (currentValue.length === 0) {
nextIndex = null;
} else {
const lastValue = currentValue[currentValue.length - 1];
const lastIndex = findItemIndex(registry, lastValue, isItemEqualToValue);
nextIndex = lastIndex === -1 ? null : lastIndex;
}
} else {
const index2 = findItemIndex(registry, value, isItemEqualToValue);
nextIndex = index2 === -1 ? null : index2;
}
if (nextIndex === null) {
selectedItemTextRef.current = null;
}
if (open) {
return;
}
store2.set("selectedIndex", nextIndex);
}, [hasSelectedValue, multiple, open, value, valuesRef, isItemEqualToValue, store2, selectedItemTextRef]);
function isSelectedValueDirty(currentValue) {
const initialValue = validityData.initialValue;
if (Array.isArray(currentValue) && Array.isArray(initialValue)) {
return !areArraysEqual(currentValue, initialValue, (itemValue, initialItemValue) => compareItemEquality(itemValue, initialItemValue, isItemEqualToValue));
}
return currentValue !== initialValue;
}
useValueChanged(value, () => {
clearErrors(name);
setDirty(isSelectedValueDirty(value));
validation.change(value);
});
const setOpen = useStableCallback((nextOpen, eventDetails) => {
onOpenChange?.(nextOpen, eventDetails);
if (eventDetails.isCanceled) {
return;
}
setOpenUnwrapped(nextOpen);
if (!nextOpen && (eventDetails.reason === reason_parts_exports.focusOut || eventDetails.reason === reason_parts_exports.outsidePress)) {
setTouched(true);
setFocused(false);
if (validationMode === "onBlur") {
validation.commit(value);
}
}
});
const handleUnmount = useStableCallback(() => {
setMounted(false);
store2.update({
activeIndex: null,
openMethod: null
});
onOpenChangeComplete?.(false);
});
useOpenChangeComplete({
enabled: !actionsRef,
open,
ref: popupRef,
onComplete() {
if (!open) {
handleUnmount();
}
}
});
React81.useImperativeHandle(actionsRef, () => ({
unmount: handleUnmount
}), [handleUnmount]);
const setValue = useStableCallback((nextValue, eventDetails) => {
onValueChange?.(nextValue, eventDetails);
if (eventDetails.isCanceled) {
return;
}
setValueUnwrapped(nextValue);
});
const handleScrollArrowVisibility = useStableCallback(() => {
const scroller = store2.state.listElement || popupRef.current;
if (!scroller) {
return;
}
const maxScrollTop = getMaxScrollOffset(scroller.scrollHeight, scroller.clientHeight);
const scrollTop = normalizeScrollOffset(scroller.scrollTop, maxScrollTop);
const shouldShowUp = scrollTop > 0;
const shouldShowDown = scrollTop < maxScrollTop;
if (store2.state.scrollUpArrowVisible !== shouldShowUp) {
store2.set("scrollUpArrowVisible", shouldShowUp);
}
if (store2.state.scrollDownArrowVisible !== shouldShowDown) {
store2.set("scrollDownArrowVisible", shouldShowDown);
}
});
const floatingContext = useFloatingRootContext({
open,
onOpenChange: setOpen,
elements: {
reference: triggerElement,
floating: positionerElement
}
});
const click = useClick(floatingContext, {
enabled: !readOnly && !disabled2,
event: "mousedown"
});
const dismiss = useDismiss(floatingContext);
const listNavigation2 = useListNavigation(floatingContext, {
enabled: !readOnly && !disabled2,
listRef,
activeIndex,
selectedIndex,
disabledIndices: EMPTY_ARRAY5,
onNavigate(nextActiveIndex) {
if (nextActiveIndex === null && !open) {
return;
}
store2.set("activeIndex", nextActiveIndex);
},
focusItemOnHover: highlightItemOnHover
});
const typeahead = useTypeahead(floatingContext, {
enabled: !readOnly && !disabled2 && (open || !multiple),
listRef: labelsRef,
activeIndex,
selectedIndex,
// Skip disabled items while matching so typeahead advances to the next selectable item
// (a click can never select a disabled item and native `<select>` skips them too). Resolve
// the disabled state from the element via the attribute-only `isElementDisabled` so the
// hidden, force-mounted items used for closed-trigger typeahead aren't dropped by the
// `elementsRef`/visibility filter that `disabledIndices` deliberately sidesteps.
disabledIndices: (index2) => isElementDisabled(listRef.current[index2]),
onMatch(index2) {
if (open) {
store2.set("activeIndex", index2);
} else {
setValue(valuesRef.current[index2], createChangeEventDetails("none"));
}
},
onTyping(typing) {
typingRef.current = typing;
}
});
const mergedTriggerProps = React81.useMemo(() => {
const triggerInteractionProps = mergeProps(typeahead.reference, listNavigation2.reference, dismiss.reference, click.reference, interactionTypeProps);
if (generatedId) {
triggerInteractionProps.id = generatedId;
}
return triggerInteractionProps;
}, [click.reference, typeahead.reference, listNavigation2.reference, dismiss.reference, interactionTypeProps, generatedId]);
const popupProps = React81.useMemo(() => mergeProps(FOCUSABLE_POPUP_PROPS, typeahead.floating, listNavigation2.floating, dismiss.floating), [typeahead.floating, listNavigation2.floating, dismiss.floating]);
const itemProps = listNavigation2.item ?? EMPTY_OBJECT;
useOnFirstRender(() => {
store2.update({
popupProps,
triggerProps: mergedTriggerProps
});
});
useIsoLayoutEffect(() => {
store2.update({
id: generatedId,
modal,
multiple,
value,
open,
mounted,
transitionStatus,
popupProps,
triggerProps: mergedTriggerProps,
items,
itemToStringLabel,
itemToStringValue,
isItemEqualToValue,
openMethod: renderedOpenMethod
});
}, [store2, generatedId, modal, multiple, value, open, mounted, transitionStatus, popupProps, mergedTriggerProps, items, itemToStringLabel, itemToStringValue, isItemEqualToValue, renderedOpenMethod]);
const contextValue = React81.useMemo(() => ({
store: store2,
name,
required,
disabled: disabled2,
readOnly,
multiple,
highlightItemOnHover,
setValue,
setOpen,
listRef,
popupRef,
scrollHandlerRef,
handleScrollArrowVisibility,
scrollArrowsMountedCountRef,
itemProps,
valueRef,
valuesRef,
labelsRef,
typingRef,
selectionRef,
firstItemTextRef,
selectedItemTextRef,
validation,
onOpenChangeComplete,
alignItemWithTriggerActiveRef,
initialValueRef
}), [store2, name, required, disabled2, readOnly, multiple, highlightItemOnHover, setValue, setOpen, itemProps, validation, onOpenChangeComplete, handleScrollArrowVisibility]);
const ref = useMergedRefs(inputRef, validation.inputRef);
const hasMultipleSelection = multiple && Array.isArray(value) && value.length > 0;
const hiddenInputName = multiple ? void 0 : name;
const hiddenInputs = React81.useMemo(() => {
if (!multiple || !Array.isArray(value) || !name) {
return null;
}
return value.map((v2) => {
const currentSerializedValue = stringifyAsValue(v2, itemToStringValue);
return /* @__PURE__ */ (0, import_jsx_runtime169.jsx)("input", {
type: "hidden",
form,
name,
value: currentSerializedValue,
disabled: disabled2
}, currentSerializedValue);
});
}, [multiple, value, form, name, itemToStringValue, disabled2]);
return /* @__PURE__ */ (0, import_jsx_runtime169.jsx)(SelectRootContext.Provider, {
value: contextValue,
children: /* @__PURE__ */ (0, import_jsx_runtime169.jsxs)(SelectFloatingContext.Provider, {
value: floatingContext,
children: [children, /* @__PURE__ */ (0, import_jsx_runtime169.jsx)("input", {
...validation.getValidationProps(disabled2, {
onFocus() {
store2.state.triggerElement?.focus({
// Supported in Chrome from 144 (January 2026)
focusVisible: true
});
},
// Handle browser autofill.
onChange(event) {
if (event.nativeEvent.defaultPrevented || disabled2 || readOnly) {
return;
}
const nextValue = event.currentTarget.value;
const details = createChangeEventDetails(reason_parts_exports.none, event.nativeEvent);
function handleChange() {
if (multiple) {
return;
}
const nextValueLower = nextValue.toLowerCase();
let matchingIndex = valuesRef.current.findIndex((candidate) => stringifyAsValue(candidate, itemToStringValue).toLowerCase() === nextValueLower || stringifyAsLabel(candidate, itemToStringLabel).toLowerCase() === nextValueLower);
if (matchingIndex === -1) {
matchingIndex = valuesRef.current.findIndex((_, index2) => {
const renderedLabel = labelsRef.current[index2];
return renderedLabel != null && renderedLabel.toLowerCase() === nextValueLower;
});
}
const matchingValue = matchingIndex === -1 ? void 0 : valuesRef.current[matchingIndex];
if (matchingValue != null) {
setValue(matchingValue, details);
}
}
store2.set("forceMount", true);
queueMicrotask(handleChange);
}
}),
id: generatedId && hiddenInputName == null ? `${generatedId}-hidden-input` : void 0,
form,
name: hiddenInputName,
autoComplete,
value: serializedValue,
disabled: disabled2,
required: required && !hasMultipleSelection,
readOnly,
ref,
style: name ? visuallyHiddenInput : visuallyHidden,
tabIndex: -1,
"aria-hidden": true,
suppressHydrationWarning: true
}), hiddenInputs]
})
});
}
// node_modules/@base-ui/react/select/label/SelectLabel.mjs
var React82 = __toESM(require_react(), 1);
var SelectLabel = /* @__PURE__ */ React82.forwardRef(function SelectLabel2(componentProps, forwardedRef) {
const {
render: render4,
className,
style,
...elementProps
} = componentProps;
const elementPropsWithoutId = elementProps;
delete elementPropsWithoutId.id;
const fieldRootContext = useFieldRootContext();
const {
store: store2
} = useSelectRootContext();
const triggerElement = useStore(store2, selectors2.triggerElement);
const rootId = useStore(store2, selectors2.id);
const defaultLabelId = getDefaultLabelId(rootId);
const labelProps = useLabel({
id: defaultLabelId,
fallbackControlId: triggerElement?.id ?? rootId,
setLabelId(nextLabelId) {
store2.set("labelId", nextLabelId);
}
});
return useRenderElement("div", componentProps, {
ref: forwardedRef,
state: fieldRootContext.state,
props: [labelProps, elementProps],
stateAttributesMapping: fieldValidityMapping
});
});
if (true) SelectLabel.displayName = "SelectLabel";
// node_modules/@base-ui/react/select/trigger/SelectTrigger.mjs
var React83 = __toESM(require_react(), 1);
var BOUNDARY_OFFSET = 2;
var SELECTED_DELAY = 400;
var stateAttributesMapping3 = {
...pressableTriggerOpenStateMapping,
...fieldValidityMapping,
popupSide: (side) => side ? {
"data-popup-side": side
} : null,
value: () => null
};
var SelectTrigger = /* @__PURE__ */ React83.forwardRef(function SelectTrigger2(componentProps, forwardedRef) {
const {
render: render4,
className,
id: idProp,
disabled: disabledProp = false,
nativeButton = true,
style,
...elementProps
} = componentProps;
const {
setTouched,
setFocused,
validationMode,
state: fieldState,
disabled: fieldDisabled
} = useFieldRootContext();
const {
labelId: fieldLabelId
} = useLabelableContext();
const {
store: store2,
setOpen,
selectionRef,
validation,
readOnly,
required,
alignItemWithTriggerActiveRef,
disabled: selectDisabled
} = useSelectRootContext();
const disabled2 = fieldDisabled || selectDisabled || disabledProp;
const open = useStore(store2, selectors2.open);
const mounted = useStore(store2, selectors2.mounted);
const value = useStore(store2, selectors2.value);
const triggerProps = useStore(store2, selectors2.triggerProps);
const positionerElement = useStore(store2, selectors2.positionerElement);
const listElement = useStore(store2, selectors2.listElement);
const popupSideValue = useStore(store2, selectors2.popupSide);
const rootId = useStore(store2, selectors2.id);
const selectLabelId = useStore(store2, selectors2.labelId);
const hasSelectedValue = useStore(store2, selectors2.hasSelectedValue);
const popupSide = mounted && positionerElement ? popupSideValue : null;
const id = idProp ?? rootId;
const ariaLabelledBy = resolveAriaLabelledBy(fieldLabelId, selectLabelId);
useLabelableId({
id
});
const positionerRef = useValueAsRef(positionerElement);
const triggerRef = React83.useRef(null);
const {
getButtonProps,
buttonRef
} = useButton({
disabled: disabled2,
native: nativeButton
});
const setTriggerElement = useStableCallback((element) => {
store2.set("triggerElement", element);
});
const timeoutFocus = useTimeout();
const timeoutMouseDown = useTimeout();
const selectedDelayTimeout = useTimeout();
React83.useEffect(() => {
if (open) {
selectedDelayTimeout.start(SELECTED_DELAY, () => {
selectionRef.current.allowUnselectedMouseUp = true;
selectionRef.current.allowSelectedMouseUp = true;
});
return () => {
selectedDelayTimeout.clear();
};
}
selectionRef.current = {
allowSelectedMouseUp: false,
allowUnselectedMouseUp: false,
dragY: 0
};
timeoutMouseDown.clear();
return void 0;
}, [open, selectionRef, timeoutMouseDown, selectedDelayTimeout]);
const mergedProps = mergeProps(triggerProps, {
id,
role: "combobox",
"aria-expanded": open ? "true" : "false",
"aria-haspopup": "listbox",
"aria-controls": open ? listElement?.id ?? getFloatingFocusElement(positionerElement)?.id : void 0,
"aria-labelledby": ariaLabelledBy,
"aria-readonly": readOnly || void 0,
"aria-required": required || void 0,
tabIndex: disabled2 ? -1 : 0,
onFocus(event) {
setFocused(true);
if (open && alignItemWithTriggerActiveRef.current) {
setOpen(false, createChangeEventDetails(reason_parts_exports.none, event.nativeEvent));
}
timeoutFocus.start(0, () => {
store2.set("forceMount", true);
});
},
onBlur(event) {
if (contains(positionerElement, event.relatedTarget)) {
return;
}
setTouched(true);
setFocused(false);
if (validationMode === "onBlur") {
validation.commit(value);
}
},
onMouseDown(event) {
if (open) {
return;
}
const doc = ownerDocument(event.currentTarget);
function handleMouseUp(mouseEvent) {
if (!triggerRef.current) {
return;
}
const mouseUpTarget = mouseEvent.target;
if (contains(triggerRef.current, mouseUpTarget) || contains(positionerRef.current, mouseUpTarget)) {
return;
}
const bounds = getPseudoElementBounds(triggerRef.current);
if (mouseEvent.clientX >= bounds.left - BOUNDARY_OFFSET && mouseEvent.clientX <= bounds.right + BOUNDARY_OFFSET && mouseEvent.clientY >= bounds.top - BOUNDARY_OFFSET && mouseEvent.clientY <= bounds.bottom + BOUNDARY_OFFSET) {
return;
}
setOpen(false, createChangeEventDetails(reason_parts_exports.cancelOpen, mouseEvent));
}
timeoutMouseDown.start(0, () => {
doc.addEventListener("mouseup", handleMouseUp, {
once: true
});
});
}
}, elementProps, getButtonProps);
const props = validation.getValidationProps(disabled2, mergedProps);
props.role = "combobox";
const state = {
...fieldState,
open,
disabled: disabled2,
value,
readOnly,
popupSide,
placeholder: !hasSelectedValue
};
return useRenderElement("button", componentProps, {
ref: [forwardedRef, triggerRef, buttonRef, setTriggerElement],
state,
stateAttributesMapping: stateAttributesMapping3,
props
});
});
if (true) SelectTrigger.displayName = "SelectTrigger";
// node_modules/@base-ui/react/select/value/SelectValue.mjs
var React84 = __toESM(require_react(), 1);
var stateAttributesMapping4 = {
value: () => null
};
var SelectValue = /* @__PURE__ */ React84.forwardRef(function SelectValue2(componentProps, forwardedRef) {
const {
className,
render: render4,
children: childrenProp,
placeholder,
style,
...elementProps
} = componentProps;
const {
store: store2,
valueRef
} = useSelectRootContext();
const value = useStore(store2, selectors2.value);
const items = useStore(store2, selectors2.items);
const itemToStringLabel = useStore(store2, selectors2.itemToStringLabel);
const hasSelectedValue = useStore(store2, selectors2.hasSelectedValue);
const shouldCheckNullItemLabel = !hasSelectedValue && placeholder != null && childrenProp == null;
const hasNullLabel = useStore(store2, selectors2.hasNullItemLabel, shouldCheckNullItemLabel);
const state = {
value,
placeholder: !hasSelectedValue
};
let children = null;
if (typeof childrenProp === "function") {
children = childrenProp(value);
} else if (childrenProp != null) {
children = childrenProp;
} else if (!hasSelectedValue && placeholder != null && !hasNullLabel) {
children = placeholder;
} else if (Array.isArray(value)) {
children = resolveMultipleLabels(value, items, itemToStringLabel);
} else {
children = resolveSelectedLabel(value, items, itemToStringLabel);
}
const element = useRenderElement("span", componentProps, {
state,
ref: [forwardedRef, valueRef],
props: [{
children
}, elementProps],
stateAttributesMapping: stateAttributesMapping4
});
return element;
});
if (true) SelectValue.displayName = "SelectValue";
// node_modules/@base-ui/react/select/icon/SelectIcon.mjs
var React85 = __toESM(require_react(), 1);
var SelectIcon = /* @__PURE__ */ React85.forwardRef(function SelectIcon2(componentProps, forwardedRef) {
const {
render: render4,
className,
style,
...elementProps
} = componentProps;
const {
store: store2
} = useSelectRootContext();
const open = useStore(store2, selectors2.open);
const state = {
open
};
const element = useRenderElement("span", componentProps, {
state,
ref: forwardedRef,
props: [{
"aria-hidden": true,
children: "\u25BC"
}, elementProps],
stateAttributesMapping: triggerOpenStateMapping2
});
return element;
});
if (true) SelectIcon.displayName = "SelectIcon";
// node_modules/@base-ui/react/select/portal/SelectPortal.mjs
var React87 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/select/portal/SelectPortalContext.mjs
var React86 = __toESM(require_react(), 1);
var SelectPortalContext = /* @__PURE__ */ React86.createContext(void 0);
if (true) SelectPortalContext.displayName = "SelectPortalContext";
// node_modules/@base-ui/react/select/portal/SelectPortal.mjs
var import_jsx_runtime170 = __toESM(require_jsx_runtime(), 1);
var SelectPortal = /* @__PURE__ */ React87.forwardRef(function SelectPortal2(portalProps, forwardedRef) {
const {
store: store2
} = useSelectRootContext();
const mounted = useStore(store2, selectors2.mounted);
const forceMount = useStore(store2, selectors2.forceMount);
const shouldRender = mounted || forceMount;
if (!shouldRender) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime170.jsx)(SelectPortalContext.Provider, {
value: true,
children: /* @__PURE__ */ (0, import_jsx_runtime170.jsx)(FloatingPortal, {
ref: forwardedRef,
...portalProps
})
});
});
if (true) SelectPortal.displayName = "SelectPortal";
// node_modules/@base-ui/react/select/backdrop/SelectBackdrop.mjs
var React88 = __toESM(require_react(), 1);
var stateAttributesMapping5 = {
...popupStateMapping,
...transitionStatusMapping
};
var SelectBackdrop = /* @__PURE__ */ React88.forwardRef(function SelectBackdrop2(componentProps, forwardedRef) {
const {
render: render4,
className,
style,
...elementProps
} = componentProps;
const {
store: store2
} = useSelectRootContext();
const open = useStore(store2, selectors2.open);
const mounted = useStore(store2, selectors2.mounted);
const transitionStatus = useStore(store2, selectors2.transitionStatus);
const state = {
open,
transitionStatus
};
const element = useRenderElement("div", componentProps, {
state,
ref: forwardedRef,
props: [{
role: "presentation",
hidden: !mounted,
style: {
userSelect: "none",
WebkitUserSelect: "none"
}
}, elementProps],
stateAttributesMapping: stateAttributesMapping5
});
return element;
});
if (true) SelectBackdrop.displayName = "SelectBackdrop";
// node_modules/@base-ui/react/select/positioner/SelectPositioner.mjs
var React90 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/select/positioner/SelectPositionerContext.mjs
var React89 = __toESM(require_react(), 1);
var SelectPositionerContext = /* @__PURE__ */ React89.createContext(void 0);
if (true) SelectPositionerContext.displayName = "SelectPositionerContext";
function useSelectPositionerContext() {
const context = React89.useContext(SelectPositionerContext);
if (!context) {
throw new Error(true ? "Base UI: SelectPositionerContext is missing. SelectPositioner parts must be placed within <Select.Positioner>." : formatErrorMessage_default(59));
}
return context;
}
// node_modules/@base-ui/react/select/popup/utils.mjs
function clearStyles(element, originalStyles) {
if (element) {
Object.assign(element.style, originalStyles);
}
}
var LIST_FUNCTIONAL_STYLES = {
position: "relative",
maxHeight: "100%",
overflowX: "hidden",
overflowY: "auto"
};
// node_modules/@base-ui/react/select/positioner/SelectPositioner.mjs
var import_jsx_runtime171 = __toESM(require_jsx_runtime(), 1);
var FIXED = {
position: "fixed"
};
var SelectPositioner = /* @__PURE__ */ React90.forwardRef(function SelectPositioner2(componentProps, forwardedRef) {
const {
anchor,
positionMethod = "absolute",
className,
render: render4,
side = "bottom",
align = "center",
sideOffset = 0,
alignOffset = 0,
collisionBoundary = "clipping-ancestors",
collisionPadding,
arrowPadding = 5,
sticky = false,
disableAnchorTracking,
alignItemWithTrigger = true,
collisionAvoidance = DROPDOWN_COLLISION_AVOIDANCE,
style,
...elementProps
} = componentProps;
const {
store: store2,
listRef,
labelsRef,
alignItemWithTriggerActiveRef,
selectedItemTextRef,
valuesRef,
initialValueRef,
popupRef,
setValue
} = useSelectRootContext();
const floatingRootContext = useSelectFloatingContext();
const open = useStore(store2, selectors2.open);
const mounted = useStore(store2, selectors2.mounted);
const modal = useStore(store2, selectors2.modal);
const value = useStore(store2, selectors2.value);
const openMethod = useStore(store2, selectors2.openMethod);
const positionerElement = useStore(store2, selectors2.positionerElement);
const triggerElement = useStore(store2, selectors2.triggerElement);
const isItemEqualToValue = useStore(store2, selectors2.isItemEqualToValue);
const transitionStatus = useStore(store2, selectors2.transitionStatus);
const scrollUpArrowRef = React90.useRef(null);
const scrollDownArrowRef = React90.useRef(null);
const [controlledAlignItemWithTrigger, setControlledAlignItemWithTrigger] = React90.useState(alignItemWithTrigger);
const alignItemWithTriggerActive = mounted && controlledAlignItemWithTrigger && openMethod !== "touch";
if (!mounted && controlledAlignItemWithTrigger !== alignItemWithTrigger) {
setControlledAlignItemWithTrigger(alignItemWithTrigger);
}
useIsoLayoutEffect(() => {
if (!mounted) {
if (selectors2.scrollUpArrowVisible(store2.state)) {
store2.set("scrollUpArrowVisible", false);
}
if (selectors2.scrollDownArrowVisible(store2.state)) {
store2.set("scrollDownArrowVisible", false);
}
}
}, [store2, mounted]);
React90.useImperativeHandle(alignItemWithTriggerActiveRef, () => alignItemWithTriggerActive);
useAnchoredPopupScrollLock((alignItemWithTriggerActive || modal) && open, openMethod === "touch", positionerElement, triggerElement);
const positioning = useAnchorPositioning({
anchor,
floatingRootContext,
positionMethod,
mounted,
side,
sideOffset,
align,
alignOffset,
arrowPadding,
collisionBoundary,
collisionPadding,
sticky,
disableAnchorTracking: disableAnchorTracking ?? alignItemWithTriggerActive,
collisionAvoidance,
keepMounted: true
});
const renderedSide = alignItemWithTriggerActive ? "none" : positioning.side;
const positionerStyles = alignItemWithTriggerActive ? FIXED : positioning.positionerStyles;
const state = {
open,
side: renderedSide,
align: positioning.align,
anchorHidden: positioning.anchorHidden
};
useIsoLayoutEffect(() => {
store2.set("popupSide", positioning.side);
}, [store2, positioning.side]);
const setPositionerElement = useStableCallback((element2) => {
store2.set("positionerElement", element2);
});
const element = usePositioner(componentProps, state, {
styles: positionerStyles,
transitionStatus,
props: elementProps,
refs: [forwardedRef, setPositionerElement],
hidden: !mounted,
inert: !open
});
const prevMapSizeRef = React90.useRef(0);
const onMapChange = useStableCallback((map) => {
if (map.size === 0 && prevMapSizeRef.current === 0) {
return;
}
if (valuesRef.current.length === 0) {
return;
}
const prevSize = prevMapSizeRef.current;
prevMapSizeRef.current = map.size;
if (map.size === prevSize) {
return;
}
const eventDetails = createChangeEventDetails(reason_parts_exports.none);
if (prevSize !== 0 && !store2.state.multiple && value !== null) {
const selectedValueIndex = findItemIndex(valuesRef.current, value, isItemEqualToValue);
if (selectedValueIndex === -1) {
const initialSelectedValue = initialValueRef.current;
const hasInitial = initialSelectedValue != null && findItemIndex(valuesRef.current, initialSelectedValue, isItemEqualToValue) !== -1;
const nextValue = hasInitial ? initialSelectedValue : null;
setValue(nextValue, eventDetails);
if (nextValue === null) {
store2.set("selectedIndex", null);
selectedItemTextRef.current = null;
}
}
}
if (prevSize !== 0 && store2.state.multiple && Array.isArray(value)) {
const hasVisibleItem = (selectedItemValue) => findItemIndex(valuesRef.current, selectedItemValue, isItemEqualToValue) !== -1;
const nextValue = value.filter((selectedItemValue) => hasVisibleItem(selectedItemValue));
if (nextValue.length !== value.length || nextValue.some((selectedItemValue) => !selectedValueIncludes(value, selectedItemValue, isItemEqualToValue))) {
setValue(nextValue, eventDetails);
if (nextValue.length === 0) {
store2.set("selectedIndex", null);
selectedItemTextRef.current = null;
}
}
}
if (open && alignItemWithTriggerActive) {
store2.update({
scrollUpArrowVisible: false,
scrollDownArrowVisible: false
});
const stylesToClear = {
height: ""
};
clearStyles(positionerElement, stylesToClear);
clearStyles(popupRef.current, stylesToClear);
}
});
const contextValue = React90.useMemo(() => ({
...positioning,
side: renderedSide,
alignItemWithTriggerActive,
setControlledAlignItemWithTrigger,
scrollUpArrowRef,
scrollDownArrowRef
}), [positioning, renderedSide, alignItemWithTriggerActive, setControlledAlignItemWithTrigger]);
return /* @__PURE__ */ (0, import_jsx_runtime171.jsx)(CompositeList, {
elementsRef: listRef,
labelsRef,
onMapChange,
children: /* @__PURE__ */ (0, import_jsx_runtime171.jsxs)(SelectPositionerContext.Provider, {
value: contextValue,
children: [mounted && modal && /* @__PURE__ */ (0, import_jsx_runtime171.jsx)(InternalBackdrop, {
inert: inertValue(!open),
cutout: triggerElement
}), element]
})
});
});
if (true) SelectPositioner.displayName = "SelectPositioner";
// node_modules/@base-ui/react/select/popup/SelectPopup.mjs
var React91 = __toESM(require_react(), 1);
var import_jsx_runtime172 = __toESM(require_jsx_runtime(), 1);
var stateAttributesMapping6 = {
...popupStateMapping,
...transitionStatusMapping
};
var SelectPopup = /* @__PURE__ */ React91.forwardRef(function SelectPopup2(componentProps, forwardedRef) {
const {
render: render4,
className,
style,
finalFocus,
...elementProps
} = componentProps;
const {
store: store2,
popupRef,
onOpenChangeComplete,
setOpen,
valueRef,
firstItemTextRef,
selectedItemTextRef,
multiple,
handleScrollArrowVisibility,
scrollHandlerRef,
listRef,
highlightItemOnHover
} = useSelectRootContext();
const {
side,
align,
alignItemWithTriggerActive,
isPositioned,
setControlledAlignItemWithTrigger
} = useSelectPositionerContext();
const insideToolbar = useToolbarRootContext(true) != null;
const floatingRootContext = useSelectFloatingContext();
const direction = useDirection();
const {
nonce,
disableStyleElements
} = useCSPContext();
const id = useStore(store2, selectors2.id);
const open = useStore(store2, selectors2.open);
const openMethod = useStore(store2, selectors2.openMethod);
const mounted = useStore(store2, selectors2.mounted);
const popupProps = useStore(store2, selectors2.popupProps);
const transitionStatus = useStore(store2, selectors2.transitionStatus);
const triggerElement = useStore(store2, selectors2.triggerElement);
const positionerElement = useStore(store2, selectors2.positionerElement);
const listElement = useStore(store2, selectors2.listElement);
const reachedMaxHeightRef = React91.useRef(false);
const initialPlacedRef = React91.useRef(false);
const originalPositionerStylesRef = React91.useRef({});
const scrollArrowFrame = useAnimationFrame();
const handleScroll = useStableCallback((scroller) => {
if (!positionerElement || !popupRef.current || !initialPlacedRef.current) {
return;
}
if (reachedMaxHeightRef.current || !alignItemWithTriggerActive) {
handleScrollArrowVisibility();
return;
}
const isTopPositioned = positionerElement.style.top === "0px";
const isBottomPositioned = positionerElement.style.bottom === "0px";
if (!isTopPositioned && !isBottomPositioned) {
handleScrollArrowVisibility();
return;
}
const scale = getScale2(positionerElement);
const currentHeight = normalizeSize(positionerElement.getBoundingClientRect().height, "y", scale);
const doc = ownerDocument(positionerElement);
const win = getWindow(positionerElement);
const positionerStyles = win.getComputedStyle(positionerElement);
const marginTop = parseFloat(positionerStyles.marginTop);
const marginBottom = parseFloat(positionerStyles.marginBottom);
const maxPopupHeight = getMaxPopupHeight(win.getComputedStyle(popupRef.current));
const maxAvailableHeight = Math.min(doc.documentElement.clientHeight - marginTop - marginBottom, maxPopupHeight);
const scrollTop = scroller.scrollTop;
const maxScrollTop = getMaxScrollTop(scroller);
let nextPositionerHeight = 0;
let nextScrollTop = null;
let setReachedMax = false;
let scrollToMax = false;
const setHeight = (height) => {
positionerElement.style.height = `${height}px`;
};
const handleSmallDiff = (diff2, targetScrollTop) => {
const heightDelta = clamp2(diff2, 0, maxAvailableHeight - currentHeight);
if (heightDelta > 0) {
setHeight(currentHeight + heightDelta);
}
scroller.scrollTop = targetScrollTop;
if (maxAvailableHeight - (currentHeight + heightDelta) <= SCROLL_EDGE_TOLERANCE_PX) {
reachedMaxHeightRef.current = true;
}
handleScrollArrowVisibility();
};
const diff = isTopPositioned ? maxScrollTop - scrollTop : scrollTop;
const nextHeight = Math.min(currentHeight + diff, maxAvailableHeight);
nextPositionerHeight = nextHeight;
if (diff <= SCROLL_EDGE_TOLERANCE_PX) {
handleSmallDiff(diff, isTopPositioned ? maxScrollTop : 0);
return;
}
if (maxAvailableHeight - nextHeight > SCROLL_EDGE_TOLERANCE_PX) {
if (isTopPositioned) {
scrollToMax = true;
} else {
nextScrollTop = 0;
}
} else {
setReachedMax = true;
if (isBottomPositioned && scrollTop < maxScrollTop) {
const overshoot = currentHeight + diff - maxAvailableHeight;
nextScrollTop = scrollTop - (diff - overshoot);
}
}
nextPositionerHeight = Math.ceil(nextPositionerHeight);
if (nextPositionerHeight !== 0) {
setHeight(nextPositionerHeight);
}
if (scrollToMax || nextScrollTop != null) {
const nextMaxScrollTop = getMaxScrollTop(scroller);
const target = scrollToMax ? nextMaxScrollTop : clamp2(nextScrollTop, 0, nextMaxScrollTop);
if (Math.abs(scroller.scrollTop - target) > SCROLL_EDGE_TOLERANCE_PX) {
scroller.scrollTop = target;
}
}
if (setReachedMax || nextPositionerHeight >= maxAvailableHeight - SCROLL_EDGE_TOLERANCE_PX) {
reachedMaxHeightRef.current = true;
}
handleScrollArrowVisibility();
});
React91.useImperativeHandle(scrollHandlerRef, () => handleScroll, [handleScroll]);
useOpenChangeComplete({
open,
ref: popupRef,
onComplete() {
if (open) {
onOpenChangeComplete?.(true);
}
}
});
const state = {
open,
transitionStatus,
side,
align
};
useIsoLayoutEffect(() => {
if (!positionerElement || !popupRef.current || Object.keys(originalPositionerStylesRef.current).length) {
return;
}
originalPositionerStylesRef.current = {
top: positionerElement.style.top || "0",
left: positionerElement.style.left || "0",
right: positionerElement.style.right,
height: positionerElement.style.height,
bottom: positionerElement.style.bottom,
minHeight: positionerElement.style.minHeight,
maxHeight: positionerElement.style.maxHeight,
marginTop: positionerElement.style.marginTop,
marginBottom: positionerElement.style.marginBottom
};
}, [popupRef, positionerElement]);
useIsoLayoutEffect(() => {
if (open || alignItemWithTriggerActive) {
return;
}
initialPlacedRef.current = false;
reachedMaxHeightRef.current = false;
clearStyles(positionerElement, originalPositionerStylesRef.current);
}, [open, alignItemWithTriggerActive, positionerElement, popupRef]);
useIsoLayoutEffect(() => {
const popupElement = popupRef.current;
if (!open || !triggerElement || !positionerElement || !popupElement || alignItemWithTriggerActive && !isPositioned || store2.state.transitionStatus === "ending") {
return;
}
if (!alignItemWithTriggerActive) {
initialPlacedRef.current = true;
scrollArrowFrame.request(handleScrollArrowVisibility);
popupElement.style.removeProperty("--transform-origin");
return;
}
const restoreTransformStyles = unsetTransformStyles(popupElement);
popupElement.style.removeProperty("--transform-origin");
try {
let textElement = selectedItemTextRef.current;
if (!textElement?.isConnected) {
const hasSelectedValue = selectors2.hasSelectedValue(store2.state);
textElement = !hasSelectedValue && firstItemTextRef.current?.isConnected ? firstItemTextRef.current : null;
}
const valueElement = valueRef.current;
const win = getWindow(positionerElement);
const positionerStyles = win.getComputedStyle(positionerElement);
const popupStyles = win.getComputedStyle(popupElement);
const doc = ownerDocument(triggerElement);
const scale = getScale2(triggerElement);
const triggerRect = normalizeRect(triggerElement.getBoundingClientRect(), scale);
const positionerRect = normalizeRect(positionerElement.getBoundingClientRect(), scale);
const triggerHeight = triggerRect.height;
const scroller = listElement || popupElement;
const scrollHeight = scroller.scrollHeight;
const borderBottom = parseFloat(popupStyles.borderBottomWidth);
const marginTop = parseFloat(positionerStyles.marginTop) || 10;
const marginBottom = parseFloat(positionerStyles.marginBottom) || 10;
const minHeight = parseFloat(positionerStyles.minHeight) || 100;
const maxPopupHeight = getMaxPopupHeight(popupStyles);
const paddingLeft = 5;
const paddingRight = 5;
const triggerCollisionThreshold = 20;
const viewportHeight = doc.documentElement.clientHeight - marginTop - marginBottom;
const viewportWidth = doc.documentElement.clientWidth;
const availableSpaceBeneathTrigger = viewportHeight - triggerRect.bottom + triggerHeight;
let textRect;
let alignedLeft = direction === "rtl" ? triggerRect.right - positionerRect.width : triggerRect.left;
let offsetY = 0;
if (textElement && valueElement) {
const valueRect = normalizeRect(valueElement.getBoundingClientRect(), scale);
textRect = normalizeRect(textElement.getBoundingClientRect(), scale);
alignedLeft = positionerRect.left + (direction === "rtl" ? valueRect.right - textRect.right : valueRect.left - textRect.left);
const valueCenterFromTriggerTop = valueRect.top - triggerRect.top + valueRect.height / 2;
const textCenterFromPositionerTop = textRect.top - positionerRect.top + textRect.height / 2;
offsetY = textCenterFromPositionerTop - valueCenterFromTriggerTop;
}
const idealHeight = availableSpaceBeneathTrigger + offsetY + marginBottom + borderBottom;
let height = Math.min(viewportHeight, idealHeight);
const maxHeight = viewportHeight - marginTop - marginBottom;
const scrollTop = idealHeight - height;
const maxRight = viewportWidth - paddingRight;
positionerElement.style.left = `${clamp2(alignedLeft, paddingLeft, maxRight - positionerRect.width)}px`;
positionerElement.style.height = `${height}px`;
positionerElement.style.maxHeight = "none";
positionerElement.style.marginTop = `${marginTop}px`;
positionerElement.style.marginBottom = `${marginBottom}px`;
popupElement.style.height = "100%";
const maxScrollTop = getMaxScrollTop(scroller);
const isTopPositioned = scrollTop >= maxScrollTop - SCROLL_EDGE_TOLERANCE_PX;
if (isTopPositioned) {
height = Math.min(viewportHeight, positionerRect.height) - (scrollTop - maxScrollTop);
}
const fallbackToAlignPopupToTrigger = triggerRect.top < triggerCollisionThreshold || triggerRect.bottom > viewportHeight - triggerCollisionThreshold || Math.ceil(height) + SCROLL_EDGE_TOLERANCE_PX < Math.min(scrollHeight, minHeight);
const isPinchZoomed = (win.visualViewport?.scale ?? 1) !== 1 && parts_exports.engine.webkit;
if (fallbackToAlignPopupToTrigger || isPinchZoomed) {
initialPlacedRef.current = true;
clearStyles(positionerElement, originalPositionerStylesRef.current);
setControlledAlignItemWithTrigger(false);
return;
}
const initialHeight = Math.max(minHeight, height);
if (isTopPositioned) {
const topOffset = Math.max(0, viewportHeight - idealHeight);
positionerElement.style.top = positionerRect.height >= maxHeight ? "0" : `${topOffset}px`;
positionerElement.style.height = `${height}px`;
scroller.scrollTop = getMaxScrollTop(scroller);
} else {
positionerElement.style.bottom = "0";
scroller.scrollTop = scrollTop;
}
if (textRect) {
const popupTop = positionerRect.top;
const popupHeight = positionerRect.height;
const textCenterY = textRect.top + textRect.height / 2;
const transformOriginY = popupHeight > 0 ? (textCenterY - popupTop) / popupHeight * 100 : 50;
const clampedY = clamp2(transformOriginY, 0, 100);
popupElement.style.setProperty("--transform-origin", `50% ${clampedY}%`);
}
if (initialHeight === viewportHeight || height >= maxPopupHeight) {
reachedMaxHeightRef.current = true;
}
handleScrollArrowVisibility();
if (highlightItemOnHover && store2.state.selectedIndex === null && store2.state.activeIndex === null && listRef.current[0] != null) {
store2.set("activeIndex", 0);
}
initialPlacedRef.current = true;
} finally {
restoreTransformStyles();
}
}, [store2, open, positionerElement, triggerElement, valueRef, firstItemTextRef, selectedItemTextRef, popupRef, handleScrollArrowVisibility, alignItemWithTriggerActive, setControlledAlignItemWithTrigger, scrollArrowFrame, listElement, listRef, highlightItemOnHover, direction, isPositioned]);
React91.useEffect(() => {
if (!alignItemWithTriggerActive || !positionerElement || !open) {
return void 0;
}
const win = getWindow(positionerElement);
function handleResize(event) {
setOpen(false, createChangeEventDetails(reason_parts_exports.windowResize, event));
}
return addEventListener(win, "resize", handleResize);
}, [setOpen, alignItemWithTriggerActive, positionerElement, open]);
const defaultProps = {
...listElement ? {
role: "presentation",
"aria-orientation": void 0
} : {
role: "listbox",
"aria-multiselectable": multiple || void 0,
id: `${id}-list`
},
onKeyDown(event) {
if (insideToolbar && COMPOSITE_KEYS.has(event.key)) {
event.stopPropagation();
}
},
onScroll(event) {
if (listElement) {
return;
}
handleScroll(event.currentTarget);
},
...alignItemWithTriggerActive && {
style: listElement ? {
height: "100%"
} : LIST_FUNCTIONAL_STYLES
}
};
const element = useRenderElement("div", componentProps, {
ref: [forwardedRef, popupRef],
state,
stateAttributesMapping: stateAttributesMapping6,
props: [popupProps, defaultProps, getDisabledMountTransitionStyles(transitionStatus), {
className: !listElement && alignItemWithTriggerActive ? styleDisableScrollbar.className : void 0
}, elementProps]
});
return /* @__PURE__ */ (0, import_jsx_runtime172.jsxs)(React91.Fragment, {
children: [!disableStyleElements && styleDisableScrollbar.getElement(nonce), /* @__PURE__ */ (0, import_jsx_runtime172.jsx)(FloatingFocusManager, {
context: floatingRootContext,
modal: false,
disabled: !mounted,
openInteractionType: openMethod,
returnFocus: finalFocus,
restoreFocus: true,
children: element
})]
});
});
if (true) SelectPopup.displayName = "SelectPopup";
function getMaxPopupHeight(popupStyles) {
const maxHeightStyle = popupStyles.maxHeight || "";
return maxHeightStyle.endsWith("px") ? parseFloat(maxHeightStyle) || Infinity : Infinity;
}
function getMaxScrollTop(scroller) {
return getMaxScrollOffset(scroller.scrollHeight, scroller.clientHeight);
}
function getScale2(element) {
return platform2.getScale(element);
}
function normalizeSize(size4, axis, scale) {
return size4 / scale[axis];
}
function normalizeRect(rect, scale) {
return rectToClientRect({
x: normalizeSize(rect.x, "x", scale),
y: normalizeSize(rect.y, "y", scale),
width: normalizeSize(rect.width, "x", scale),
height: normalizeSize(rect.height, "y", scale)
});
}
var TRANSFORM_STYLE_RESETS = [["transform", "none"], ["scale", "1"], ["translate", "0 0"]];
function unsetTransformStyles(popupElement) {
const {
style
} = popupElement;
const originalStyles = {};
for (const [property, value] of TRANSFORM_STYLE_RESETS) {
originalStyles[property] = style.getPropertyValue(property);
style.setProperty(property, value, "important");
}
return () => {
for (const [property] of TRANSFORM_STYLE_RESETS) {
const originalValue = originalStyles[property];
if (originalValue) {
style.setProperty(property, originalValue);
} else {
style.removeProperty(property);
}
}
};
}
// node_modules/@base-ui/react/select/list/SelectList.mjs
var React92 = __toESM(require_react(), 1);
var SelectList = /* @__PURE__ */ React92.forwardRef(function SelectList2(componentProps, forwardedRef) {
const {
render: render4,
className,
style,
...elementProps
} = componentProps;
const {
store: store2,
scrollHandlerRef
} = useSelectRootContext();
const {
alignItemWithTriggerActive
} = useSelectPositionerContext();
const hasScrollArrows = useStore(store2, selectors2.hasScrollArrows);
const openMethod = useStore(store2, selectors2.openMethod);
const multiple = useStore(store2, selectors2.multiple);
const id = useStore(store2, selectors2.id);
const defaultProps = {
id: `${id}-list`,
role: "listbox",
"aria-multiselectable": multiple || void 0,
onScroll(event) {
scrollHandlerRef.current?.(event.currentTarget);
},
...alignItemWithTriggerActive && {
style: LIST_FUNCTIONAL_STYLES
},
className: hasScrollArrows && openMethod !== "touch" ? styleDisableScrollbar.className : void 0
};
const setListElement = useStableCallback((element) => {
store2.set("listElement", element);
});
return useRenderElement("div", componentProps, {
ref: [forwardedRef, setListElement],
props: [defaultProps, elementProps]
});
});
if (true) SelectList.displayName = "SelectList";
// node_modules/@base-ui/react/select/item/SelectItem.mjs
var React94 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/select/item/SelectItemContext.mjs
var React93 = __toESM(require_react(), 1);
var SelectItemContext = /* @__PURE__ */ React93.createContext(void 0);
if (true) SelectItemContext.displayName = "SelectItemContext";
function useSelectItemContext() {
const context = React93.useContext(SelectItemContext);
if (!context) {
throw new Error(true ? "Base UI: SelectItemContext is missing. SelectItem parts must be placed within <Select.Item>." : formatErrorMessage_default(57));
}
return context;
}
// node_modules/@base-ui/react/select/item/SelectItem.mjs
var import_jsx_runtime173 = __toESM(require_jsx_runtime(), 1);
var SelectItem = /* @__PURE__ */ React94.memo(/* @__PURE__ */ React94.forwardRef(function SelectItem2(componentProps, forwardedRef) {
const {
render: render4,
className,
style,
value: itemValue = null,
label,
disabled: disabled2 = false,
nativeButton = false,
...elementProps
} = componentProps;
const textRef = React94.useRef(null);
const listItem = useCompositeListItem({
label,
textRef,
indexGuessBehavior: IndexGuessBehavior.GuessFromOrder
});
const {
store: store2,
itemProps,
setOpen,
setValue,
selectionRef,
typingRef,
valuesRef,
multiple,
selectedItemTextRef,
disabled: selectDisabled,
readOnly
} = useSelectRootContext();
const highlighted = useStore(store2, selectors2.isActive, listItem.index);
const open = useStore(store2, selectors2.open);
const selected = useStore(store2, selectors2.isSelected, itemValue);
const selectedByFocus = useStore(store2, selectors2.isSelectedByFocus, listItem.index);
const isItemEqualToValue = useStore(store2, selectors2.isItemEqualToValue);
const index2 = listItem.index;
const hasRegistered = index2 !== -1;
const itemRef = React94.useRef(null);
useIsoLayoutEffect(() => {
if (!hasRegistered) {
return void 0;
}
const values = valuesRef.current;
values[index2] = itemValue;
return () => {
delete values[index2];
};
}, [hasRegistered, index2, itemValue, valuesRef]);
useIsoLayoutEffect(() => {
if (!hasRegistered) {
return;
}
const selectedValue = store2.state.value;
let selectedCandidate = selectedValue;
if (multiple && Array.isArray(selectedValue)) {
selectedCandidate = selectedValue.length > 0 ? selectedValue[selectedValue.length - 1] : void 0;
}
if (selectedCandidate !== void 0 && compareItemEquality(itemValue, selectedCandidate, isItemEqualToValue)) {
store2.set("selectedIndex", index2);
if (textRef.current) {
selectedItemTextRef.current = textRef.current;
}
}
}, [hasRegistered, index2, multiple, isItemEqualToValue, store2, itemValue, selectedItemTextRef]);
const lastKeyRef = React94.useRef(null);
const pointerTypeRef = React94.useRef("mouse");
const allowMouseSelectionRef = React94.useRef(false);
const {
getButtonProps,
buttonRef
} = useButton({
disabled: disabled2,
focusableWhenDisabled: true,
native: nativeButton,
composite: true
});
const state = {
disabled: disabled2,
selected,
highlighted
};
function commitSelection(event) {
if (selectDisabled || readOnly) {
return;
}
const selectedValue = store2.state.value;
if (multiple) {
const currentValue = Array.isArray(selectedValue) ? selectedValue : [];
const nextValue = selected ? removeItem(currentValue, itemValue, isItemEqualToValue) : [...currentValue, itemValue];
setValue(nextValue, createChangeEventDetails(reason_parts_exports.itemPress, event));
} else {
setValue(itemValue, createChangeEventDetails(reason_parts_exports.itemPress, event));
setOpen(false, createChangeEventDetails(reason_parts_exports.itemPress, event));
}
}
function resetDragMovement() {
selectionRef.current.dragY = 0;
}
const defaultProps = {
role: "option",
"aria-selected": selected,
tabIndex: open && highlighted ? 0 : -1,
onKeyDown(event) {
lastKeyRef.current = event.key;
store2.set("activeIndex", index2);
if (event.key === " " && typingRef.current) {
event.preventDefault();
}
},
onClick(event) {
const isMouseClick = event.type === "click" && pointerTypeRef.current !== "touch";
const clickPointerType = event.nativeEvent.pointerType;
const isVirtualMouseClick = isMouseClick && isVirtualClick(event.nativeEvent) && // Generic no-pointer `detail === 0` clicks stay tied to highlight state. Virtual
// clicks that carry browser pointer data, including an empty string from assistive
// technology, can activate unhighlighted items.
(clickPointerType !== void 0 || highlighted);
const isInvalidMouseClick = isMouseClick && !isVirtualMouseClick && !allowMouseSelectionRef.current;
allowMouseSelectionRef.current = false;
if (event.type === "keydown" && lastKeyRef.current === null) {
return;
}
if (disabled2 || event.type === "keydown" && lastKeyRef.current === " " && typingRef.current || isInvalidMouseClick) {
return;
}
lastKeyRef.current = null;
commitSelection(event.nativeEvent);
},
onPointerEnter(event) {
pointerTypeRef.current = event.pointerType;
},
onPointerMove(event) {
if (event.pointerType === "mouse" && event.buttons === 1) {
const selection2 = selectionRef.current;
selection2.dragY += event.movementY;
if (selection2.dragY ** 2 >= 64) {
selection2.allowUnselectedMouseUp = true;
}
}
},
onPointerDown(event) {
pointerTypeRef.current = event.pointerType;
allowMouseSelectionRef.current = true;
resetDragMovement();
},
onMouseUp() {
resetDragMovement();
if (disabled2 || pointerTypeRef.current === "touch") {
return;
}
if (allowMouseSelectionRef.current) {
return;
}
const disallowSelectedMouseUp = !selectionRef.current.allowSelectedMouseUp && selected;
const disallowUnselectedMouseUp = !selectionRef.current.allowUnselectedMouseUp && !selected;
if (disallowSelectedMouseUp || disallowUnselectedMouseUp) {
return;
}
allowMouseSelectionRef.current = true;
itemRef.current?.click();
allowMouseSelectionRef.current = false;
}
};
const element = useRenderElement("div", componentProps, {
ref: [buttonRef, forwardedRef, listItem.ref, itemRef],
state,
props: [itemProps, defaultProps, elementProps, getButtonProps]
});
const contextValue = React94.useMemo(() => ({
selected,
index: index2,
textRef,
selectedByFocus,
hasRegistered
}), [selected, index2, textRef, selectedByFocus, hasRegistered]);
return /* @__PURE__ */ (0, import_jsx_runtime173.jsx)(SelectItemContext.Provider, {
value: contextValue,
children: element
});
}));
if (true) SelectItem.displayName = "SelectItem";
// node_modules/@base-ui/react/select/item-indicator/SelectItemIndicator.mjs
var React95 = __toESM(require_react(), 1);
var import_jsx_runtime174 = __toESM(require_jsx_runtime(), 1);
var SelectItemIndicator = /* @__PURE__ */ React95.forwardRef(function SelectItemIndicator2(componentProps, forwardedRef) {
const keepMounted = componentProps.keepMounted ?? false;
const {
selected
} = useSelectItemContext();
const shouldRender = keepMounted || selected;
if (!shouldRender) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime174.jsx)(Inner, {
...componentProps,
ref: forwardedRef
});
});
if (true) SelectItemIndicator.displayName = "SelectItemIndicator";
var Inner = /* @__PURE__ */ React95.memo(/* @__PURE__ */ React95.forwardRef((componentProps, forwardedRef) => {
const {
render: render4,
className,
style,
keepMounted,
...elementProps
} = componentProps;
const {
selected
} = useSelectItemContext();
const indicatorRef = React95.useRef(null);
const {
transitionStatus,
setMounted
} = useTransitionStatus(selected);
const state = {
selected,
transitionStatus
};
const element = useRenderElement("span", componentProps, {
ref: [forwardedRef, indicatorRef],
state,
props: [{
"aria-hidden": true,
children: "\u2714\uFE0F"
}, elementProps],
stateAttributesMapping: transitionStatusMapping
});
useOpenChangeComplete({
open: selected,
ref: indicatorRef,
onComplete() {
if (!selected) {
setMounted(false);
}
}
});
return element;
}));
if (true) Inner.displayName = "Inner";
// node_modules/@base-ui/react/select/item-text/SelectItemText.mjs
var React96 = __toESM(require_react(), 1);
var SelectItemText = /* @__PURE__ */ React96.memo(/* @__PURE__ */ React96.forwardRef(function SelectItemText2(componentProps, forwardedRef) {
const {
index: index2,
textRef,
selectedByFocus,
hasRegistered
} = useSelectItemContext();
const {
firstItemTextRef,
selectedItemTextRef
} = useSelectRootContext();
const {
render: render4,
className,
style,
...elementProps
} = componentProps;
const localRef = React96.useCallback((node) => {
if (!node) {
return;
}
if (hasRegistered && index2 === 0) {
firstItemTextRef.current = node;
}
if (hasRegistered && selectedByFocus) {
selectedItemTextRef.current = node;
}
}, [firstItemTextRef, selectedItemTextRef, index2, selectedByFocus, hasRegistered]);
const element = useRenderElement("div", componentProps, {
ref: [localRef, forwardedRef, textRef],
props: elementProps
});
return element;
}));
if (true) SelectItemText.displayName = "SelectItemText";
// node_modules/@base-ui/react/select/arrow/SelectArrow.mjs
var React97 = __toESM(require_react(), 1);
var stateAttributesMapping7 = {
...popupStateMapping,
...transitionStatusMapping
};
var SelectArrow = /* @__PURE__ */ React97.forwardRef(function SelectArrow2(componentProps, forwardedRef) {
const {
render: render4,
className,
style,
...elementProps
} = componentProps;
const {
store: store2
} = useSelectRootContext();
const {
side,
align,
arrowRef,
arrowStyles,
arrowUncentered,
alignItemWithTriggerActive
} = useSelectPositionerContext();
const open = useStore(store2, selectors2.open);
const state = {
open,
side,
align,
uncentered: arrowUncentered
};
const element = useRenderElement("div", componentProps, {
state,
ref: [arrowRef, forwardedRef],
props: [{
style: arrowStyles,
"aria-hidden": true
}, elementProps],
stateAttributesMapping: stateAttributesMapping7
});
if (alignItemWithTriggerActive) {
return null;
}
return element;
});
if (true) SelectArrow.displayName = "SelectArrow";
// node_modules/@base-ui/react/select/scroll-down-arrow/SelectScrollDownArrow.mjs
var React99 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/select/scroll-arrow/SelectScrollArrow.mjs
var React98 = __toESM(require_react(), 1);
var SelectScrollArrow = /* @__PURE__ */ React98.forwardRef(function SelectScrollArrow2(componentProps, forwardedRef) {
const {
render: render4,
className,
style,
direction,
keepMounted = false,
...elementProps
} = componentProps;
const isUp = direction === "up";
const {
store: store2,
popupRef,
listRef,
handleScrollArrowVisibility,
scrollArrowsMountedCountRef
} = useSelectRootContext();
const {
side,
scrollDownArrowRef,
scrollUpArrowRef
} = useSelectPositionerContext();
const visibleSelector = isUp ? selectors2.scrollUpArrowVisible : selectors2.scrollDownArrowVisible;
const stateVisible = useStore(store2, visibleSelector);
const openMethod = useStore(store2, selectors2.openMethod);
const visible = stateVisible && openMethod !== "touch";
const timeout = useTimeout();
const scrollArrowRef = isUp ? scrollUpArrowRef : scrollDownArrowRef;
const {
mounted,
transitionStatus,
setMounted
} = useTransitionStatus(visible);
useIsoLayoutEffect(() => {
scrollArrowsMountedCountRef.current += 1;
if (!store2.state.hasScrollArrows) {
store2.set("hasScrollArrows", true);
}
return () => {
scrollArrowsMountedCountRef.current = Math.max(0, scrollArrowsMountedCountRef.current - 1);
if (scrollArrowsMountedCountRef.current === 0 && store2.state.hasScrollArrows) {
store2.set("hasScrollArrows", false);
}
};
}, [store2, scrollArrowsMountedCountRef]);
useOpenChangeComplete({
open: visible,
ref: scrollArrowRef,
onComplete() {
if (!visible) {
setMounted(false);
}
}
});
const state = {
direction,
visible,
side,
transitionStatus
};
const defaultProps = {
"aria-hidden": true,
children: isUp ? "\u25B2" : "\u25BC",
style: {
position: "absolute"
},
onMouseMove(event) {
if (event.movementX === 0 && event.movementY === 0 || timeout.isStarted()) {
return;
}
store2.set("activeIndex", null);
function scrollNextItem() {
const scroller = store2.state.listElement ?? popupRef.current;
if (!scroller) {
return;
}
store2.set("activeIndex", null);
handleScrollArrowVisibility();
const maxScrollTop = getMaxScrollOffset(scroller.scrollHeight, scroller.clientHeight);
const scrollTop = normalizeScrollOffset(scroller.scrollTop, maxScrollTop);
const isScrolledToEdge = scrollTop === (isUp ? 0 : maxScrollTop);
const items = listRef.current;
if (scrollTop !== scroller.scrollTop) {
scroller.scrollTop = scrollTop;
}
if (items.length === 0) {
store2.set(isUp ? "scrollUpArrowVisible" : "scrollDownArrowVisible", !isScrolledToEdge);
}
if (isScrolledToEdge) {
timeout.clear();
return;
}
if (items.length > 0) {
const scrollArrowHeight = scrollArrowRef.current?.offsetHeight || 0;
scroller.scrollTop = getTargetScrollTop(items, isUp, scrollTop, scroller.clientHeight, scrollArrowHeight, maxScrollTop);
}
timeout.start(40, scrollNextItem);
}
timeout.start(40, scrollNextItem);
},
onMouseLeave() {
timeout.clear();
}
};
const element = useRenderElement("div", componentProps, {
ref: [forwardedRef, scrollArrowRef],
state,
props: [defaultProps, elementProps],
stateAttributesMapping: transitionStatusMapping
});
const shouldRender = mounted || keepMounted;
if (!shouldRender) {
return null;
}
return element;
});
if (true) SelectScrollArrow.displayName = "SelectScrollArrow";
function getTargetScrollTop(items, isUp, scrollTop, clientHeight, scrollArrowHeight, maxScrollTop) {
if (isUp) {
let firstVisibleIndex = 0;
const visibleTop = scrollTop + scrollArrowHeight - SCROLL_EDGE_TOLERANCE_PX;
for (let i2 = 0; i2 < items.length; i2 += 1) {
const item = items[i2];
if (item && item.offsetTop >= visibleTop) {
firstVisibleIndex = i2;
break;
}
}
const targetIndex2 = Math.max(0, firstVisibleIndex - 1);
const targetItem2 = items[targetIndex2];
return targetIndex2 < firstVisibleIndex && targetItem2 ? normalizeScrollOffset(targetItem2.offsetTop - scrollArrowHeight, maxScrollTop) : 0;
}
let lastVisibleIndex = items.length - 1;
const visibleBottom = scrollTop + clientHeight - scrollArrowHeight + SCROLL_EDGE_TOLERANCE_PX;
for (let i2 = 0; i2 < items.length; i2 += 1) {
const item = items[i2];
if (item && item.offsetTop + item.offsetHeight > visibleBottom) {
lastVisibleIndex = Math.max(0, i2 - 1);
break;
}
}
const targetIndex = Math.min(items.length - 1, lastVisibleIndex + 1);
const targetItem = items[targetIndex];
return targetIndex > lastVisibleIndex && targetItem ? normalizeScrollOffset(targetItem.offsetTop + targetItem.offsetHeight - clientHeight + scrollArrowHeight, maxScrollTop) : maxScrollTop;
}
// node_modules/@base-ui/react/select/scroll-down-arrow/SelectScrollDownArrow.mjs
var import_jsx_runtime175 = __toESM(require_jsx_runtime(), 1);
var SelectScrollDownArrow = /* @__PURE__ */ React99.forwardRef(function SelectScrollDownArrow2(props, forwardedRef) {
return /* @__PURE__ */ (0, import_jsx_runtime175.jsx)(SelectScrollArrow, {
...props,
ref: forwardedRef,
direction: "down"
});
});
if (true) SelectScrollDownArrow.displayName = "SelectScrollDownArrow";
// node_modules/@base-ui/react/select/scroll-up-arrow/SelectScrollUpArrow.mjs
var React100 = __toESM(require_react(), 1);
var import_jsx_runtime176 = __toESM(require_jsx_runtime(), 1);
var SelectScrollUpArrow = /* @__PURE__ */ React100.forwardRef(function SelectScrollUpArrow2(props, forwardedRef) {
return /* @__PURE__ */ (0, import_jsx_runtime176.jsx)(SelectScrollArrow, {
...props,
ref: forwardedRef,
direction: "up"
});
});
if (true) SelectScrollUpArrow.displayName = "SelectScrollUpArrow";
// node_modules/@base-ui/react/select/group/SelectGroup.mjs
var React102 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/select/group/SelectGroupContext.mjs
var React101 = __toESM(require_react(), 1);
var SelectGroupContext = /* @__PURE__ */ React101.createContext(void 0);
if (true) SelectGroupContext.displayName = "SelectGroupContext";
function useSelectGroupContext() {
const context = React101.useContext(SelectGroupContext);
if (context === void 0) {
throw new Error(true ? "Base UI: SelectGroupContext is missing. SelectGroup parts must be placed within <Select.Group>." : formatErrorMessage_default(56));
}
return context;
}
// node_modules/@base-ui/react/select/group/SelectGroup.mjs
var import_jsx_runtime177 = __toESM(require_jsx_runtime(), 1);
var SelectGroup = /* @__PURE__ */ React102.forwardRef(function SelectGroup2(componentProps, forwardedRef) {
const {
render: render4,
className,
style,
...elementProps
} = componentProps;
const [labelId, setLabelId] = React102.useState();
const contextValue = React102.useMemo(() => ({
labelId,
setLabelId
}), [labelId, setLabelId]);
const element = useRenderElement("div", componentProps, {
ref: forwardedRef,
props: [{
role: "group",
"aria-labelledby": labelId
}, elementProps]
});
return /* @__PURE__ */ (0, import_jsx_runtime177.jsx)(SelectGroupContext.Provider, {
value: contextValue,
children: element
});
});
if (true) SelectGroup.displayName = "SelectGroup";
// node_modules/@base-ui/react/select/group-label/SelectGroupLabel.mjs
var React103 = __toESM(require_react(), 1);
var SelectGroupLabel = /* @__PURE__ */ React103.forwardRef(function SelectGroupLabel2(componentProps, forwardedRef) {
const {
render: render4,
className,
style,
id: idProp,
...elementProps
} = componentProps;
const {
setLabelId
} = useSelectGroupContext();
const id = useBaseUiId(idProp);
useIsoLayoutEffect(() => {
setLabelId(id);
}, [id, setLabelId]);
const element = useRenderElement("div", componentProps, {
ref: forwardedRef,
props: [{
id
}, elementProps]
});
return element;
});
if (true) SelectGroupLabel.displayName = "SelectGroupLabel";
// node_modules/@base-ui/react/tooltip/index.parts.mjs
var index_parts_exports4 = {};
__export(index_parts_exports4, {
Arrow: () => TooltipArrow,
Handle: () => TooltipHandle,
Popup: () => TooltipPopup,
Portal: () => TooltipPortal,
Positioner: () => TooltipPositioner,
Provider: () => TooltipProvider,
Root: () => TooltipRoot,
Trigger: () => TooltipTrigger,
Viewport: () => TooltipViewport,
createHandle: () => createTooltipHandle
});
// node_modules/@base-ui/react/tooltip/root/TooltipRoot.mjs
var React106 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/tooltip/root/TooltipRootContext.mjs
var React104 = __toESM(require_react(), 1);
var TooltipRootContext = /* @__PURE__ */ React104.createContext(void 0);
if (true) TooltipRootContext.displayName = "TooltipRootContext";
function useTooltipRootContext(optional) {
const context = React104.useContext(TooltipRootContext);
if (context === void 0 && !optional) {
throw new Error(true ? "Base UI: TooltipRootContext is missing. Tooltip parts must be placed within <Tooltip.Root>." : formatErrorMessage_default(72));
}
return context;
}
// node_modules/@base-ui/react/tooltip/store/TooltipStore.mjs
var React105 = __toESM(require_react(), 1);
var selectors3 = {
...popupStoreSelectors,
disabled: createSelector3((state) => state.disabled),
instantType: createSelector3((state) => state.instantType),
isInstantPhase: createSelector3((state) => state.isInstantPhase),
trackCursorAxis: createSelector3((state) => state.trackCursorAxis),
disableHoverablePopup: createSelector3((state) => state.disableHoverablePopup),
lastOpenChangeReason: createSelector3((state) => state.openChangeReason),
closeOnClick: createSelector3((state) => state.closeOnClick),
closeDelay: createSelector3((state) => state.closeDelay),
hasViewport: createSelector3((state) => state.hasViewport)
};
var TooltipStore = class _TooltipStore extends ReactStore {
constructor(initialState, floatingId, nested = false) {
const triggerElements = new PopupTriggerMap();
const state = {
...createInitialState(),
...initialState
};
state.floatingRootContext = createPopupFloatingRootContext(triggerElements, floatingId, nested);
super(state, {
popupRef: /* @__PURE__ */ React105.createRef(),
onOpenChange: void 0,
onOpenChangeComplete: void 0,
triggerElements
}, selectors3);
}
setOpen = (nextOpen, eventDetails) => {
applyPopupOpenChange(this, nextOpen, eventDetails, {
extraState: {
openChangeReason: eventDetails.reason
}
});
};
// Used by trigger clicks to clear a delayed hover open without reporting a public open-state change.
cancelPendingOpen(event) {
this.state.floatingRootContext.dispatchOpenChange(false, createChangeEventDetails(reason_parts_exports.triggerPress, event));
}
static useStore(externalStore, initialState) {
const store2 = usePopupStore(externalStore, (floatingId, nested) => new _TooltipStore(initialState, floatingId, nested)).store;
return store2;
}
};
function createInitialState() {
return {
...createInitialPopupStoreState(),
disabled: false,
instantType: void 0,
isInstantPhase: false,
trackCursorAxis: "none",
disableHoverablePopup: false,
openChangeReason: null,
closeOnClick: true,
closeDelay: 0,
hasViewport: false
};
}
// node_modules/@base-ui/react/tooltip/root/TooltipRoot.mjs
var import_jsx_runtime178 = __toESM(require_jsx_runtime(), 1);
var TooltipRoot = fastComponent(function TooltipRoot2(props) {
const {
disabled: disabled2 = false,
defaultOpen = false,
open: openProp,
disableHoverablePopup = false,
trackCursorAxis = "none",
actionsRef,
onOpenChange,
onOpenChangeComplete,
handle,
triggerId: triggerIdProp,
defaultTriggerId: defaultTriggerIdProp = null,
children
} = props;
const store2 = TooltipStore.useStore(handle?.store, {
open: defaultOpen,
openProp,
activeTriggerId: defaultTriggerIdProp,
triggerIdProp
});
useInitialOpenSync(store2, openProp, defaultOpen, defaultTriggerIdProp);
store2.useControlledProp("openProp", openProp);
store2.useControlledProp("triggerIdProp", triggerIdProp);
store2.useContextCallback("onOpenChange", onOpenChange);
store2.useContextCallback("onOpenChangeComplete", onOpenChangeComplete);
const openState = store2.useState("open");
const open = !disabled2 && openState;
const activeTriggerId = store2.useState("activeTriggerId");
const mounted = store2.useState("mounted");
const payload = store2.useState("payload");
store2.useSyncedValues({
trackCursorAxis,
disableHoverablePopup
});
store2.useSyncedValue("disabled", disabled2);
useImplicitActiveTrigger(store2, {
closeOnActiveTriggerUnmount: true
});
const {
forceUnmount,
transitionStatus
} = useOpenStateTransitions(open, store2);
const isInstantPhase = store2.useState("isInstantPhase");
const instantType = store2.useState("instantType");
const lastOpenChangeReason = store2.useState("lastOpenChangeReason");
const previousInstantTypeRef = React106.useRef(null);
useIsoLayoutEffect(() => {
if (openState && disabled2) {
store2.setOpen(false, createChangeEventDetails(reason_parts_exports.disabled));
}
}, [openState, disabled2, store2]);
useIsoLayoutEffect(() => {
if (transitionStatus === "ending" && lastOpenChangeReason === reason_parts_exports.none || transitionStatus !== "ending" && isInstantPhase) {
if (instantType !== "delay") {
previousInstantTypeRef.current = instantType;
}
store2.set("instantType", "delay");
} else if (previousInstantTypeRef.current !== null) {
store2.set("instantType", previousInstantTypeRef.current);
previousInstantTypeRef.current = null;
}
}, [transitionStatus, isInstantPhase, lastOpenChangeReason, instantType, store2]);
useIsoLayoutEffect(() => {
if (open) {
if (activeTriggerId == null) {
store2.set("payload", void 0);
}
}
}, [store2, activeTriggerId, open]);
const handleImperativeClose = React106.useCallback(() => {
store2.setOpen(false, createChangeEventDetails(reason_parts_exports.imperativeAction));
}, [store2]);
React106.useImperativeHandle(actionsRef, () => ({
unmount: forceUnmount,
close: handleImperativeClose
}), [forceUnmount, handleImperativeClose]);
const shouldRenderInteractions = open || mounted || !disabled2 && trackCursorAxis !== "none";
return /* @__PURE__ */ (0, import_jsx_runtime178.jsxs)(TooltipRootContext.Provider, {
value: store2,
children: [shouldRenderInteractions && /* @__PURE__ */ (0, import_jsx_runtime178.jsx)(TooltipInteractions, {
store: store2,
disabled: disabled2,
trackCursorAxis
}), typeof children === "function" ? children({
payload
}) : children]
});
});
if (true) TooltipRoot.displayName = "TooltipRoot";
function TooltipInteractions({
store: store2,
disabled: disabled2,
trackCursorAxis
}) {
const floatingRootContext = store2.useState("floatingRootContext");
const dismiss = useDismiss(floatingRootContext, {
enabled: !disabled2,
referencePress: () => store2.select("closeOnClick")
});
const clientPoint = useClientPoint(floatingRootContext, {
enabled: !disabled2 && trackCursorAxis !== "none",
axis: trackCursorAxis === "none" ? void 0 : trackCursorAxis
});
const activeTriggerProps = React106.useMemo(() => mergeProps(clientPoint.reference, dismiss.reference), [clientPoint.reference, dismiss.reference]);
const inactiveTriggerProps = React106.useMemo(() => mergeProps(clientPoint.trigger, dismiss.trigger), [clientPoint.trigger, dismiss.trigger]);
const popupProps = React106.useMemo(() => mergeProps(FOCUSABLE_POPUP_PROPS, clientPoint.floating, dismiss.floating), [clientPoint.floating, dismiss.floating]);
usePopupInteractionProps(store2, {
activeTriggerProps,
inactiveTriggerProps,
popupProps
});
return null;
}
// node_modules/@base-ui/react/tooltip/trigger/TooltipTrigger.mjs
var React108 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/tooltip/provider/TooltipProviderContext.mjs
var React107 = __toESM(require_react(), 1);
var TooltipProviderContext = /* @__PURE__ */ React107.createContext(void 0);
if (true) TooltipProviderContext.displayName = "TooltipProviderContext";
function useTooltipProviderContext() {
return React107.useContext(TooltipProviderContext);
}
// node_modules/@base-ui/react/tooltip/trigger/TooltipTriggerDataAttributes.mjs
var TooltipTriggerDataAttributes = (function(TooltipTriggerDataAttributes2) {
TooltipTriggerDataAttributes2[TooltipTriggerDataAttributes2["popupOpen"] = CommonTriggerDataAttributes.popupOpen] = "popupOpen";
TooltipTriggerDataAttributes2["triggerDisabled"] = "data-trigger-disabled";
return TooltipTriggerDataAttributes2;
})({});
// node_modules/@base-ui/react/tooltip/utils/constants.mjs
var OPEN_DELAY = 600;
// node_modules/@base-ui/react/tooltip/trigger/TooltipTrigger.mjs
var TOOLTIP_TRIGGER_IDENTIFIER = "data-base-ui-tooltip-trigger";
function getTargetElement(event) {
if ("composedPath" in event) {
const path = event.composedPath();
for (let i2 = 0; i2 < path.length; i2 += 1) {
const element = path[i2];
if (isElement(element)) {
return element;
}
}
}
const target = event.target;
if (isElement(target)) {
return target;
}
return null;
}
function closestEnabledTooltipTrigger(element) {
let current = element;
while (current) {
if (current.hasAttribute(TOOLTIP_TRIGGER_IDENTIFIER)) {
return current;
}
const parentElement = current.parentElement;
if (parentElement) {
current = parentElement;
continue;
}
const root = current.getRootNode();
current = "host" in root && isElement(root.host) ? root.host : null;
}
return null;
}
var TooltipTrigger = fastComponentRef(function TooltipTrigger2(componentProps, forwardedRef) {
const {
render: render4,
className,
style,
handle,
payload,
disabled: disabledProp,
delay,
closeOnClick = true,
closeDelay,
id: idProp,
...elementProps
} = componentProps;
const rootContext = useTooltipRootContext(true);
const store2 = handle?.store ?? rootContext;
if (!store2) {
throw new Error(true ? "Base UI: <Tooltip.Trigger> must be either used within a <Tooltip.Root> component or provided with a handle." : formatErrorMessage_default(82));
}
const thisTriggerId = useBaseUiId(idProp);
const isTriggerActive = store2.useState("isTriggerActive", thisTriggerId);
const isOpenedByThisTrigger = store2.useState("isOpenedByTrigger", thisTriggerId);
const floatingRootContext = store2.useState("floatingRootContext");
const triggerElementRef = React108.useRef(null);
const delayWithDefault = delay ?? OPEN_DELAY;
const closeDelayWithDefault = closeDelay ?? 0;
const {
registerTrigger,
isMountedByThisTrigger
} = useTriggerDataForwarding(thisTriggerId, triggerElementRef, store2, {
payload,
closeOnClick,
closeDelay: closeDelayWithDefault
});
const providerContext = useTooltipProviderContext();
const {
delayRef,
isInstantPhase,
hasProvider
} = useDelayGroup(floatingRootContext, {
open: isOpenedByThisTrigger
});
const hoverInteraction = useHoverInteractionSharedState(floatingRootContext);
store2.useSyncedValue("isInstantPhase", isInstantPhase);
const rootDisabled = store2.useState("disabled");
const disabled2 = disabledProp ?? rootDisabled;
const disabledRef = useValueAsRef(disabled2);
const trackCursorAxis = store2.useState("trackCursorAxis");
const disableHoverablePopup = store2.useState("disableHoverablePopup");
const isNestedTriggerHoveredRef = React108.useRef(false);
const nestedTriggerOpenTimeout = useTimeout();
const pointerTypeRef = React108.useRef(void 0);
function getOpenDelay() {
const providerDelay = providerContext?.delay;
const groupOpenValue = typeof delayRef.current === "object" ? delayRef.current.open : void 0;
let computedOpenDelay = delayWithDefault;
if (hasProvider) {
if (groupOpenValue !== 0) {
computedOpenDelay = delay ?? providerDelay ?? delayWithDefault;
} else {
computedOpenDelay = 0;
}
}
return computedOpenDelay;
}
function isEnabledNestedTriggerTarget(target) {
const triggerEl = triggerElementRef.current;
if (!triggerEl || !target) {
return false;
}
const nearestTrigger = closestEnabledTooltipTrigger(target);
return nearestTrigger !== null && nearestTrigger !== triggerEl && contains(triggerEl, nearestTrigger);
}
function detectNestedTriggerHover(target) {
const nestedTriggerHovered = isEnabledNestedTriggerTarget(target);
isNestedTriggerHoveredRef.current = nestedTriggerHovered;
if (nestedTriggerHovered) {
hoverInteraction.openChangeTimeout.clear();
hoverInteraction.restTimeout.clear();
hoverInteraction.restTimeoutPending = false;
nestedTriggerOpenTimeout.clear();
}
return nestedTriggerHovered;
}
const hoverProps = useHoverReferenceInteraction(floatingRootContext, {
enabled: !disabled2,
mouseOnly: true,
move: false,
handleClose: !disableHoverablePopup && trackCursorAxis !== "both" ? safePolygon() : null,
restMs: getOpenDelay,
delay() {
const closeValue = typeof delayRef.current === "object" ? delayRef.current.close : void 0;
let computedCloseDelay = closeDelayWithDefault;
if (closeDelay == null && hasProvider) {
computedCloseDelay = closeValue;
}
return {
close: computedCloseDelay
};
},
triggerElementRef,
isActiveTrigger: isTriggerActive,
isClosing: () => store2.select("transitionStatus") === "ending",
shouldOpen() {
return !isNestedTriggerHoveredRef.current;
}
});
const focusProps = useFocus(floatingRootContext, {
enabled: !disabled2
}).reference;
const handleNestedTriggerHover = (event) => {
const wasNestedTriggerHovered = isNestedTriggerHoveredRef.current;
const target = getTargetElement(event);
const nestedTriggerHovered = detectNestedTriggerHover(target);
const triggerEl = triggerElementRef.current;
const targetInsideTrigger = triggerEl && target && contains(triggerEl, target);
if (nestedTriggerHovered && store2.select("open") && store2.select("lastOpenChangeReason") === reason_parts_exports.triggerHover) {
store2.setOpen(false, createChangeEventDetails(reason_parts_exports.triggerHover, event));
return;
}
if (wasNestedTriggerHovered && !nestedTriggerHovered && targetInsideTrigger && !disabledRef.current && !store2.select("open") && triggerEl && // Match the hover hook's non-strict mouse fallback for mouse-only event sequences.
isMouseLikePointerType(pointerTypeRef.current)) {
const open = () => {
if (!isNestedTriggerHoveredRef.current && !disabledRef.current && !store2.select("open")) {
store2.setOpen(true, createChangeEventDetails(reason_parts_exports.triggerHover, event, triggerEl));
}
};
const openDelay = getOpenDelay();
if (openDelay === 0) {
nestedTriggerOpenTimeout.clear();
open();
} else {
nestedTriggerOpenTimeout.start(openDelay, open);
}
}
};
const rootTriggerProps = store2.useState("triggerProps", isMountedByThisTrigger);
const shouldApplyRootTriggerProps = isMountedByThisTrigger || trackCursorAxis !== "none";
const state = {
open: isOpenedByThisTrigger
};
const element = useRenderElement("button", componentProps, {
state,
ref: [forwardedRef, registerTrigger, triggerElementRef],
props: [hoverProps, focusProps, shouldApplyRootTriggerProps ? rootTriggerProps : void 0, {
onMouseOver(event) {
handleNestedTriggerHover(event.nativeEvent);
},
onFocus(event) {
if (isEnabledNestedTriggerTarget(getTargetElement(event.nativeEvent))) {
event.preventBaseUIHandler();
}
},
onMouseLeave() {
isNestedTriggerHoveredRef.current = false;
nestedTriggerOpenTimeout.clear();
pointerTypeRef.current = void 0;
},
onPointerEnter(event) {
pointerTypeRef.current = event.pointerType;
},
onPointerDown(event) {
pointerTypeRef.current = event.pointerType;
store2.set("closeOnClick", closeOnClick);
if (closeOnClick && !store2.select("open")) {
store2.cancelPendingOpen(event.nativeEvent);
}
},
onClick(event) {
if (closeOnClick && !store2.select("open")) {
store2.cancelPendingOpen(event.nativeEvent);
}
},
id: thisTriggerId,
[TooltipTriggerDataAttributes.triggerDisabled]: disabled2 ? "" : void 0,
[TOOLTIP_TRIGGER_IDENTIFIER]: disabled2 ? void 0 : ""
}, elementProps],
stateAttributesMapping: triggerOpenStateMapping2
});
return element;
});
if (true) TooltipTrigger.displayName = "TooltipTrigger";
// node_modules/@base-ui/react/tooltip/portal/TooltipPortal.mjs
var React110 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/tooltip/portal/TooltipPortalContext.mjs
var React109 = __toESM(require_react(), 1);
var TooltipPortalContext = /* @__PURE__ */ React109.createContext(void 0);
if (true) TooltipPortalContext.displayName = "TooltipPortalContext";
function useTooltipPortalContext() {
const value = React109.useContext(TooltipPortalContext);
if (value === void 0) {
throw new Error(true ? "Base UI: <Tooltip.Portal> is missing." : formatErrorMessage_default(70));
}
return value;
}
// node_modules/@base-ui/react/tooltip/portal/TooltipPortal.mjs
var import_jsx_runtime179 = __toESM(require_jsx_runtime(), 1);
var TooltipPortal = /* @__PURE__ */ React110.forwardRef(function TooltipPortal2(props, forwardedRef) {
const {
keepMounted = false,
...portalProps
} = props;
const store2 = useTooltipRootContext();
const mounted = store2.useState("mounted");
const shouldRender = mounted || keepMounted;
if (!shouldRender) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime179.jsx)(TooltipPortalContext.Provider, {
value: keepMounted,
children: /* @__PURE__ */ (0, import_jsx_runtime179.jsx)(FloatingPortalLite, {
ref: forwardedRef,
...portalProps
})
});
});
if (true) TooltipPortal.displayName = "TooltipPortal";
// node_modules/@base-ui/react/tooltip/positioner/TooltipPositioner.mjs
var React112 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/tooltip/positioner/TooltipPositionerContext.mjs
var React111 = __toESM(require_react(), 1);
var TooltipPositionerContext = /* @__PURE__ */ React111.createContext(void 0);
if (true) TooltipPositionerContext.displayName = "TooltipPositionerContext";
function useTooltipPositionerContext() {
const context = React111.useContext(TooltipPositionerContext);
if (context === void 0) {
throw new Error(true ? "Base UI: TooltipPositionerContext is missing. TooltipPositioner parts must be placed within <Tooltip.Positioner>." : formatErrorMessage_default(71));
}
return context;
}
// node_modules/@base-ui/react/tooltip/positioner/TooltipPositioner.mjs
var import_jsx_runtime180 = __toESM(require_jsx_runtime(), 1);
var TooltipPositioner = /* @__PURE__ */ React112.forwardRef(function TooltipPositioner2(componentProps, forwardedRef) {
const {
render: render4,
className,
anchor,
positionMethod = "absolute",
side = "top",
align = "center",
sideOffset = 0,
alignOffset = 0,
collisionBoundary = "clipping-ancestors",
collisionPadding = 5,
arrowPadding = 5,
sticky = false,
disableAnchorTracking = false,
collisionAvoidance = POPUP_COLLISION_AVOIDANCE,
style,
...elementProps
} = componentProps;
const store2 = useTooltipRootContext();
const keepMounted = useTooltipPortalContext();
const open = store2.useState("open");
const mounted = store2.useState("mounted");
const trackCursorAxis = store2.useState("trackCursorAxis");
const disableHoverablePopup = store2.useState("disableHoverablePopup");
const floatingRootContext = store2.useState("floatingRootContext");
const instantType = store2.useState("instantType");
const transitionStatus = store2.useState("transitionStatus");
const hasViewport = store2.useState("hasViewport");
const positioning = useAnchorPositioning({
anchor,
positionMethod,
floatingRootContext,
mounted,
side,
sideOffset,
align,
alignOffset,
collisionBoundary,
collisionPadding,
sticky,
arrowPadding,
disableAnchorTracking,
keepMounted,
collisionAvoidance,
adaptiveOrigin: hasViewport ? adaptiveOrigin : void 0
});
const state = React112.useMemo(() => ({
open,
side: positioning.side,
align: positioning.align,
anchorHidden: positioning.anchorHidden,
instant: trackCursorAxis !== "none" ? "tracking-cursor" : instantType
}), [open, positioning.side, positioning.align, positioning.anchorHidden, trackCursorAxis, instantType]);
const element = usePositioner(componentProps, state, {
styles: positioning.positionerStyles,
transitionStatus,
props: elementProps,
refs: [forwardedRef, store2.useStateSetter("positionerElement")],
hidden: !mounted,
inert: !open || trackCursorAxis === "both" || disableHoverablePopup
});
return /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(TooltipPositionerContext.Provider, {
value: positioning,
children: element
});
});
if (true) TooltipPositioner.displayName = "TooltipPositioner";
// node_modules/@base-ui/react/tooltip/popup/TooltipPopup.mjs
var React113 = __toESM(require_react(), 1);
var stateAttributesMapping8 = {
...popupStateMapping,
...transitionStatusMapping
};
var TooltipPopup = /* @__PURE__ */ React113.forwardRef(function TooltipPopup2(componentProps, forwardedRef) {
const {
render: render4,
className,
style,
...elementProps
} = componentProps;
const store2 = useTooltipRootContext();
const {
side,
align
} = useTooltipPositionerContext();
const open = store2.useState("open");
const instantType = store2.useState("instantType");
const transitionStatus = store2.useState("transitionStatus");
const popupProps = store2.useState("popupProps");
const floatingContext = store2.useState("floatingRootContext");
const disabled2 = store2.useState("disabled");
const closeDelay = store2.useState("closeDelay");
useOpenChangeComplete({
open,
ref: store2.context.popupRef,
onComplete() {
if (open) {
store2.context.onOpenChangeComplete?.(true);
}
}
});
useHoverFloatingInteraction(floatingContext, {
enabled: !disabled2,
closeDelay
});
const setPopupElement = store2.useStateSetter("popupElement");
const state = {
open,
side,
align,
instant: instantType,
transitionStatus
};
const element = useRenderElement("div", componentProps, {
state,
ref: [forwardedRef, store2.context.popupRef, setPopupElement],
props: [popupProps, getDisabledMountTransitionStyles(transitionStatus), elementProps],
stateAttributesMapping: stateAttributesMapping8
});
return element;
});
if (true) TooltipPopup.displayName = "TooltipPopup";
// node_modules/@base-ui/react/tooltip/arrow/TooltipArrow.mjs
var React114 = __toESM(require_react(), 1);
var TooltipArrow = /* @__PURE__ */ React114.forwardRef(function TooltipArrow2(componentProps, forwardedRef) {
const {
render: render4,
className,
style,
...elementProps
} = componentProps;
const store2 = useTooltipRootContext();
const {
arrowRef,
side,
align,
arrowUncentered,
arrowStyles
} = useTooltipPositionerContext();
const open = store2.useState("open");
const instantType = store2.useState("instantType");
const state = {
open,
side,
align,
uncentered: arrowUncentered,
instant: instantType
};
const element = useRenderElement("div", componentProps, {
state,
ref: [forwardedRef, arrowRef],
props: [{
style: arrowStyles,
"aria-hidden": true
}, elementProps],
stateAttributesMapping: popupStateMapping
});
return element;
});
if (true) TooltipArrow.displayName = "TooltipArrow";
// node_modules/@base-ui/react/tooltip/provider/TooltipProvider.mjs
var React115 = __toESM(require_react(), 1);
var import_jsx_runtime181 = __toESM(require_jsx_runtime(), 1);
var TooltipProvider = function TooltipProvider2(props) {
const {
delay,
closeDelay,
timeout = 400
} = props;
const contextValue = React115.useMemo(() => ({
delay,
closeDelay
}), [delay, closeDelay]);
const delayValue = React115.useMemo(() => ({
open: delay,
close: closeDelay
}), [delay, closeDelay]);
return /* @__PURE__ */ (0, import_jsx_runtime181.jsx)(TooltipProviderContext.Provider, {
value: contextValue,
children: /* @__PURE__ */ (0, import_jsx_runtime181.jsx)(FloatingDelayGroup, {
delay: delayValue,
timeoutMs: timeout,
children: props.children
})
});
};
if (true) TooltipProvider.displayName = "TooltipProvider";
// node_modules/@base-ui/react/tooltip/viewport/TooltipViewport.mjs
var React116 = __toESM(require_react(), 1);
// node_modules/@base-ui/react/tooltip/viewport/TooltipViewportCssVars.mjs
var TooltipViewportCssVars = /* @__PURE__ */ (function(TooltipViewportCssVars2) {
TooltipViewportCssVars2["popupWidth"] = "--popup-width";
TooltipViewportCssVars2["popupHeight"] = "--popup-height";
return TooltipViewportCssVars2;
})({});
// node_modules/@base-ui/react/tooltip/viewport/TooltipViewport.mjs
var stateAttributesMapping9 = {
activationDirection: (value) => value ? {
"data-activation-direction": value
} : null
};
var TooltipViewport = /* @__PURE__ */ React116.forwardRef(function TooltipViewport2(componentProps, forwardedRef) {
const {
render: render4,
className,
style,
children,
...elementProps
} = componentProps;
const store2 = useTooltipRootContext();
const positioner = useTooltipPositionerContext();
const instantType = store2.useState("instantType");
const {
children: childrenToRender,
state: viewportState
} = usePopupViewport({
store: store2,
side: positioner.side,
cssVars: TooltipViewportCssVars,
children
});
const state = {
activationDirection: viewportState.activationDirection,
transitioning: viewportState.transitioning,
instant: instantType
};
return useRenderElement("div", componentProps, {
state,
ref: forwardedRef,
props: [elementProps, {
children: childrenToRender
}],
stateAttributesMapping: stateAttributesMapping9
});
});
if (true) TooltipViewport.displayName = "TooltipViewport";
// node_modules/@base-ui/react/tooltip/store/TooltipHandle.mjs
var TooltipHandle = class {
/**
* Internal store holding the tooltip state.
* @internal
*/
constructor() {
this.store = new TooltipStore();
}
/**
* Opens the tooltip and associates it with the trigger with the given ID.
* The trigger must be a Tooltip.Trigger component with this handle passed as a prop.
*
* This method should only be called in an event handler or an effect (not during rendering).
*
* @param triggerId ID of the trigger to associate with the tooltip.
*/
open(triggerId) {
const triggerElement = triggerId ? this.store.context.triggerElements.getById(triggerId) : void 0;
if (triggerId && !triggerElement) {
throw new Error(true ? `Base UI: TooltipHandle.open: No trigger found with id "${triggerId}".` : formatErrorMessage_default(81, triggerId));
}
this.store.setOpen(true, createChangeEventDetails(reason_parts_exports.imperativeAction, void 0, triggerElement));
}
/**
* Closes the tooltip.
*/
close() {
this.store.setOpen(false, createChangeEventDetails(reason_parts_exports.imperativeAction, void 0, void 0));
}
/**
* Indicates whether the tooltip is currently open.
*/
get isOpen() {
return this.store.select("open");
}
};
function createTooltipHandle() {
return new TooltipHandle();
}
// node_modules/@base-ui/react/use-render/useRender.mjs
function useRender(params) {
return useRenderElement(params.defaultTagName ?? "div", params, params);
}
// packages/ui/build-module/text/text.mjs
var import_element45 = __toESM(require_element(), 1);
var STYLE_HASH_ATTRIBUTE = "data-wp-hash";
function getRuntime() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) {
return globalScope.__wpStyleRuntime;
}
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") {
registerDocument(document);
}
return globalScope.__wpStyleRuntime;
}
function documentContainsStyleHash(targetDocument, hash) {
if (!targetDocument.head) {
return false;
}
for (const style of targetDocument.head.querySelectorAll(
`style[${STYLE_HASH_ATTRIBUTE}]`
)) {
if (style.getAttribute(STYLE_HASH_ATTRIBUTE) === hash) {
return true;
}
}
return false;
}
function injectStyle(targetDocument, hash, css) {
if (!targetDocument.head) {
return;
}
const runtime = getRuntime();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) {
return;
}
if (documentContainsStyleHash(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
function registerDocument(targetDocument) {
const runtime = getRuntime();
runtime.documents.set(
targetDocument,
(runtime.documents.get(targetDocument) ?? 0) + 1
);
for (const [hash, css] of runtime.styles) {
injectStyle(targetDocument, hash, css);
}
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) {
return;
}
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
function registerStyle(hash, css) {
const runtime = getRuntime();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) {
injectStyle(targetDocument, hash, css);
}
}
if (typeof process === "undefined" || true) {
registerStyle("a495f9d138", '@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._83ed8a8da5dd50ea__text{margin:0}._14437cfb77831647__heading-2xl{--_gcd-heading-font-size:var(--wpds-typography-font-size-2xl,32px);--_gcd-heading-font-weight:var(--wpds-typography-font-weight-emphasis,600);--_gcd-p-font-size:var(--wpds-typography-font-size-2xl,32px);--_gcd-p-line-height:var(--wpds-typography-line-height-2xl,40px);font-size:var(--wpds-typography-font-size-2xl,32px);line-height:var(--wpds-typography-line-height-2xl,40px)}._14437cfb77831647__heading-2xl,._3c78b7fa9b4072dd__heading-xl{font-family:var(--wpds-typography-font-family-heading,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-weight:var(--wpds-typography-font-weight-emphasis,600)}._3c78b7fa9b4072dd__heading-xl{--_gcd-heading-font-size:var(--wpds-typography-font-size-xl,20px);--_gcd-heading-font-weight:var(--wpds-typography-font-weight-emphasis,600);--_gcd-p-font-size:var(--wpds-typography-font-size-xl,20px);--_gcd-p-line-height:var(--wpds-typography-line-height-md,24px);font-size:var(--wpds-typography-font-size-xl,20px);line-height:var(--wpds-typography-line-height-md,24px)}.aa58f227716bcde2__heading-lg{--_gcd-heading-font-size:var(--wpds-typography-font-size-lg,15px);--_gcd-heading-font-weight:var(--wpds-typography-font-weight-emphasis,600);--_gcd-p-font-size:var(--wpds-typography-font-size-lg,15px);--_gcd-p-line-height:var(--wpds-typography-line-height-sm,20px);font-size:var(--wpds-typography-font-size-lg,15px)}.aa58f227716bcde2__heading-lg,.fc4da56d8dfe52c4__heading-md{font-family:var(--wpds-typography-font-family-heading,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-weight:var(--wpds-typography-font-weight-emphasis,600);line-height:var(--wpds-typography-line-height-sm,20px)}.fc4da56d8dfe52c4__heading-md{--_gcd-heading-font-size:var(--wpds-typography-font-size-md,13px);--_gcd-heading-font-weight:var(--wpds-typography-font-weight-emphasis,600);--_gcd-p-font-size:var(--wpds-typography-font-size-md,13px);--_gcd-p-line-height:var(--wpds-typography-line-height-sm,20px);font-size:var(--wpds-typography-font-size-md,13px)}.a9b78c7c82e8dff7__heading-sm{--_gcd-heading-font-size:var(--wpds-typography-font-size-xs,11px);--_gcd-heading-font-weight:var(--wpds-typography-font-weight-emphasis,600);--_gcd-p-font-size:var(--wpds-typography-font-size-xs,11px);--_gcd-p-line-height:var(--wpds-typography-line-height-xs,16px);font-family:var(--wpds-typography-font-family-heading,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-size:var(--wpds-typography-font-size-xs,11px);font-weight:var(--wpds-typography-font-weight-emphasis,600);line-height:var(--wpds-typography-line-height-xs,16px);text-transform:uppercase}._305ff559e52180d5__body-xl{--_gcd-heading-font-size:var(--wpds-typography-font-size-xl,20px);--_gcd-heading-font-weight:var(--wpds-typography-font-weight-default,400);--_gcd-p-font-size:var(--wpds-typography-font-size-xl,20px);--_gcd-p-line-height:var(--wpds-typography-line-height-xl,32px);font-size:var(--wpds-typography-font-size-xl,20px);line-height:var(--wpds-typography-line-height-xl,32px)}._305ff559e52180d5__body-xl,.ca1aa3fc2029e958__body-lg{font-family:var(--wpds-typography-font-family-body,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-weight:var(--wpds-typography-font-weight-default,400)}.ca1aa3fc2029e958__body-lg{--_gcd-heading-font-size:var(--wpds-typography-font-size-lg,15px);--_gcd-heading-font-weight:var(--wpds-typography-font-weight-default,400);--_gcd-p-font-size:var(--wpds-typography-font-size-lg,15px);--_gcd-p-line-height:var(--wpds-typography-line-height-md,24px);font-size:var(--wpds-typography-font-size-lg,15px);line-height:var(--wpds-typography-line-height-md,24px)}._131101940be12424__body-md{--_gcd-heading-font-size:var(--wpds-typography-font-size-md,13px);--_gcd-heading-font-weight:var(--wpds-typography-font-weight-default,400);--_gcd-p-font-size:var(--wpds-typography-font-size-md,13px);--_gcd-p-line-height:var(--wpds-typography-line-height-sm,20px);font-size:var(--wpds-typography-font-size-md,13px);line-height:var(--wpds-typography-line-height-sm,20px)}._0e8d87a42c1f75fa__body-sm,._131101940be12424__body-md{font-family:var(--wpds-typography-font-family-body,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-weight:var(--wpds-typography-font-weight-default,400)}._0e8d87a42c1f75fa__body-sm{--_gcd-heading-font-size:var(--wpds-typography-font-size-sm,12px);--_gcd-heading-font-weight:var(--wpds-typography-font-weight-default,400);--_gcd-p-font-size:var(--wpds-typography-font-size-sm,12px);--_gcd-p-line-height:var(--wpds-typography-line-height-xs,16px);font-size:var(--wpds-typography-font-size-sm,12px);line-height:var(--wpds-typography-line-height-xs,16px)}}}');
}
var style_default = { "text": "_83ed8a8da5dd50ea__text", "heading-2xl": "_14437cfb77831647__heading-2xl", "heading-xl": "_3c78b7fa9b4072dd__heading-xl", "heading-lg": "aa58f227716bcde2__heading-lg", "heading-md": "fc4da56d8dfe52c4__heading-md", "heading-sm": "a9b78c7c82e8dff7__heading-sm", "body-xl": "_305ff559e52180d5__body-xl", "body-lg": "ca1aa3fc2029e958__body-lg", "body-md": "_131101940be12424__body-md", "body-sm": "_0e8d87a42c1f75fa__body-sm" };
if (typeof process === "undefined" || true) {
registerStyle("af6d9984a6", "._6defc79820e382c6__button{box-sizing:var(--_gcd-button-box-sizing,border-box);font-family:var(--_gcd-button-font-family,inherit);font-size:var(--_gcd-button-font-size,inherit);font-weight:var(--_gcd-button-font-weight,inherit)}.d2cff2e5dea83bd1__input{box-sizing:var(--_gcd-input-box-sizing,border-box);font-family:var(--_gcd-input-font-family,inherit);font-size:var(--_gcd-input-font-size,inherit);font-weight:var(--_gcd-input-font-weight,inherit);margin:var(--_gcd-input-margin,0);&:is(textarea,[type=text],[type=password],[type=color],[type=date],[type=datetime],[type=datetime-local],[type=email],[type=month],[type=number],[type=search],[type=tel],[type=time],[type=url],[type=week]){background-color:var(--_gcd-input-background-color,transparent);border:var(--_gcd-input-border,none);border-radius:var(--_gcd-input-border-radius,0);box-shadow:var(--_gcd-input-box-shadow,0 0 0 transparent);color:var(--_gcd-input-color,var(--wpds-color-foreground-interactive-neutral,#1e1e1e));&:focus{border-color:var(--_gcd-input-border-color-focus,var(--wp-admin-theme-color));box-shadow:var(--_gcd-input-box-shadow-focus,none);outline:var(--_gcd-input-outline-focus,none)}&:disabled{background:var(--_gcd-input-background-disabled,transparent);border-color:var(--_gcd-input-border-color-disabled,transparent);box-shadow:var(--_gcd-input-box-shadow-disabled,none);color:var(--_gcd-input-color-disabled,var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d))}&::placeholder{color:var(--_gcd-input-placeholder-color,var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d))}}&:is(textarea,[type=text],[type=password],[type=date],[type=datetime],[type=datetime-local],[type=email],[type=month],[type=number],[type=search],[type=tel],[type=time],[type=url],[type=week]){line-height:var(--_gcd-input-line-height,inherit);min-height:var(--_gcd-input-min-height,auto);padding:var(--_gcd-input-padding,0)}}._547d86373d02e108__textarea{box-sizing:var(--_gcd-textarea-box-sizing,border-box);overflow:var(--_gcd-textarea-overflow,auto);resize:var(--_gcd-textarea-resize,block)}._8c15fd0ed9f28ba4__div{outline:var(--_gcd-div-outline,0 solid transparent)}p._43cec3e1eec1066d__p{font-size:var(--_gcd-p-font-size,13px);line-height:var(--_gcd-p-line-height,1.5);margin:var(--_gcd-p-margin,0)}:is(h1,h2,h3,h4,h5,h6).e97669c6d9a38497__heading{color:var(--_gcd-heading-color,var(--wpds-color-foreground-content-neutral,#1e1e1e));font-size:var(--_gcd-heading-font-size,inherit);font-weight:var(--_gcd-heading-font-weight,var(--wpds-typography-font-weight-emphasis,600));margin:var(--_gcd-heading-margin,0)}._2c0831b0499dbd6e__a,._2c0831b0499dbd6e__a:is(:hover,:focus,:active){border-radius:var(--_gcd-a-border-radius,0);box-shadow:var(--_gcd-a-box-shadow,none);color:var(--_gcd-a-color,inherit);outline:var(--_gcd-a-outline,0 solid transparent);transition:var(--_gcd-a-transition,none)}");
}
var global_css_defense_default = { "button": "_6defc79820e382c6__button", "input": "d2cff2e5dea83bd1__input", "textarea": "_547d86373d02e108__textarea", "div": "_8c15fd0ed9f28ba4__div", "p": "_43cec3e1eec1066d__p", "heading": "e97669c6d9a38497__heading", "a": "_2c0831b0499dbd6e__a" };
var Text = (0, import_element45.forwardRef)(function Text2({ variant = "body-md", render: render4, className, ...props }, ref) {
const element = useRender({
render: render4,
defaultTagName: "span",
ref,
props: mergeProps(props, {
className: clsx_default(
style_default.text,
global_css_defense_default.heading,
global_css_defense_default.p,
style_default[variant],
className
)
})
});
return element;
});
// packages/ui/build-module/badge/badge.mjs
var import_jsx_runtime182 = __toESM(require_jsx_runtime(), 1);
var STYLE_HASH_ATTRIBUTE2 = "data-wp-hash";
function getRuntime2() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) {
return globalScope.__wpStyleRuntime;
}
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") {
registerDocument2(document);
}
return globalScope.__wpStyleRuntime;
}
function documentContainsStyleHash2(targetDocument, hash) {
if (!targetDocument.head) {
return false;
}
for (const style of targetDocument.head.querySelectorAll(
`style[${STYLE_HASH_ATTRIBUTE2}]`
)) {
if (style.getAttribute(STYLE_HASH_ATTRIBUTE2) === hash) {
return true;
}
}
return false;
}
function injectStyle2(targetDocument, hash, css) {
if (!targetDocument.head) {
return;
}
const runtime = getRuntime2();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) {
return;
}
if (documentContainsStyleHash2(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE2, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
function registerDocument2(targetDocument) {
const runtime = getRuntime2();
runtime.documents.set(
targetDocument,
(runtime.documents.get(targetDocument) ?? 0) + 1
);
for (const [hash, css] of runtime.styles) {
injectStyle2(targetDocument, hash, css);
}
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) {
return;
}
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
function registerStyle2(hash, css) {
const runtime = getRuntime2();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) {
injectStyle2(targetDocument, hash, css);
}
}
if (typeof process === "undefined" || true) {
registerStyle2("9db2873e7f", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._96e6251aad1a6136__badge{border-radius:var(--wpds-border-radius-lg,8px);padding-block:var(--wpds-dimension-padding-xs,4px);padding-inline:var(--wpds-dimension-padding-sm,8px)}._99f7158cb520f750__is-high-intent{background-color:var(--wpds-color-background-surface-error,#f6e6e3);color:var(--wpds-color-foreground-content-error,#470000)}.c20ebef2365bc8b7__is-medium-intent{background-color:var(--wpds-color-background-surface-warning,#fde6be);color:var(--wpds-color-foreground-content-warning,#2e1900)}._365e1626c6202e52__is-low-intent{background-color:var(--wpds-color-background-surface-caution,#fee995);color:var(--wpds-color-foreground-content-caution,#281d00)}._33f8198127ddf4ef__is-stable-intent{background-color:var(--wpds-color-background-surface-success,#c6f7cd);color:var(--wpds-color-foreground-content-success,#002900)}._04c1aca8fc449412__is-informational-intent{background-color:var(--wpds-color-background-surface-info,#deebfa);color:var(--wpds-color-foreground-content-info,#001b4f)}._90726e69d495ec19__is-draft-intent{background-color:var(--wpds-color-background-surface-neutral-weak,#f4f4f4);color:var(--wpds-color-foreground-content-neutral,#1e1e1e)}._898f4a544993bd39__is-none-intent{background-color:var(--wpds-color-background-surface-neutral-strong,#fff);border:var(--wpds-border-width-xs,1px) solid var(--wpds-color-stroke-surface-neutral,#dbdbdb);color:var(--wpds-color-foreground-content-neutral,#1e1e1e);padding-block:calc(var(--wpds-dimension-padding-xs, 4px) - var(--wpds-border-width-xs, 1px));padding-inline:calc(var(--wpds-dimension-padding-sm, 8px) - var(--wpds-border-width-xs, 1px))}}}");
}
var style_default2 = { "badge": "_96e6251aad1a6136__badge", "is-high-intent": "_99f7158cb520f750__is-high-intent", "is-medium-intent": "c20ebef2365bc8b7__is-medium-intent", "is-low-intent": "_365e1626c6202e52__is-low-intent", "is-stable-intent": "_33f8198127ddf4ef__is-stable-intent", "is-informational-intent": "_04c1aca8fc449412__is-informational-intent", "is-draft-intent": "_90726e69d495ec19__is-draft-intent", "is-none-intent": "_898f4a544993bd39__is-none-intent" };
var Badge = (0, import_element46.forwardRef)(function Badge2({ intent = "none", className, ...props }, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime182.jsx)(
Text,
{
ref,
className: clsx_default(
style_default2.badge,
style_default2[`is-${intent}-intent`],
className
),
...props,
variant: "body-sm"
}
);
});
// packages/ui/build-module/icon/icon.mjs
var import_element47 = __toESM(require_element(), 1);
var import_primitives117 = __toESM(require_primitives(), 1);
var import_jsx_runtime183 = __toESM(require_jsx_runtime(), 1);
var Icon = (0, import_element47.forwardRef)(function Icon2({ icon, size: size4 = 24, ...restProps }, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime183.jsx)(
import_primitives117.SVG,
{
ref,
...icon.props,
...restProps,
width: size4,
height: size4
}
);
});
// packages/ui/build-module/card/index.mjs
var card_exports = {};
__export(card_exports, {
Content: () => Content,
FullBleed: () => FullBleed,
Header: () => Header,
Root: () => Root,
Title: () => Title
});
// packages/ui/build-module/card/root.mjs
var import_element48 = __toESM(require_element(), 1);
var STYLE_HASH_ATTRIBUTE3 = "data-wp-hash";
function getRuntime3() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) {
return globalScope.__wpStyleRuntime;
}
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") {
registerDocument3(document);
}
return globalScope.__wpStyleRuntime;
}
function documentContainsStyleHash3(targetDocument, hash) {
if (!targetDocument.head) {
return false;
}
for (const style of targetDocument.head.querySelectorAll(
`style[${STYLE_HASH_ATTRIBUTE3}]`
)) {
if (style.getAttribute(STYLE_HASH_ATTRIBUTE3) === hash) {
return true;
}
}
return false;
}
function injectStyle3(targetDocument, hash, css) {
if (!targetDocument.head) {
return;
}
const runtime = getRuntime3();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) {
return;
}
if (documentContainsStyleHash3(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE3, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
function registerDocument3(targetDocument) {
const runtime = getRuntime3();
runtime.documents.set(
targetDocument,
(runtime.documents.get(targetDocument) ?? 0) + 1
);
for (const [hash, css] of runtime.styles) {
injectStyle3(targetDocument, hash, css);
}
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) {
return;
}
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
function registerStyle3(hash, css) {
const runtime = getRuntime3();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) {
injectStyle3(targetDocument, hash, css);
}
}
if (typeof process === "undefined" || true) {
registerStyle3("10f3806643", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._336cd3e4e743482f__box-sizing{box-sizing:border-box;*,:after,:before{box-sizing:inherit}}}}");
}
var resets_default = { "box-sizing": "_336cd3e4e743482f__box-sizing" };
if (typeof process === "undefined" || true) {
registerStyle3("5d38cbdd27", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._02872bf298eadc43__root{--wp-ui-card-padding:var(--wpds-dimension-padding-2xl,24px);--wp-ui-card-header-content-gap:var(--wpds-dimension-gap-xl,24px);--wp-ui-card-header-content-margin:calc(var(--wp-ui-card-header-content-gap) - var(--wp-ui-card-padding));background-color:var(--wpds-color-background-surface-neutral-strong,#fff);border:1px solid var(--wpds-color-stroke-surface-neutral-weak,#f0f0f0);border-radius:var(--wpds-border-radius-lg,8px);color:var(--wpds-color-foreground-content-neutral,#1e1e1e);display:flex;flex-direction:column;overflow:clip}._5dffdaf2a6e669ac__content,.bbccc92e6ba5662d__header{padding:var(--wp-ui-card-padding);&:not(:first-child):not(:last-child){padding-block-end:0}}.bbccc92e6ba5662d__header+._5dffdaf2a6e669ac__content{margin-block-start:var(--wp-ui-card-header-content-margin);padding-block-start:0}.c1fa192587e1b4a6__fullbleed{margin-inline:calc(var(--wp-ui-card-padding)*-1);width:calc(100% + var(--wp-ui-card-padding)*2)}._02872bf298eadc43__root>:is(.bbccc92e6ba5662d__header,._5dffdaf2a6e669ac__content):first-child>.c1fa192587e1b4a6__fullbleed:first-child{margin-block-start:calc(var(--wp-ui-card-padding)*-1)}:is(.bbccc92e6ba5662d__header,._5dffdaf2a6e669ac__content):last-child>.c1fa192587e1b4a6__fullbleed:last-child{margin-block-end:calc(var(--wp-ui-card-padding)*-1)}}}");
}
var style_default3 = { "root": "_02872bf298eadc43__root", "header": "bbccc92e6ba5662d__header", "content": "_5dffdaf2a6e669ac__content", "fullbleed": "c1fa192587e1b4a6__fullbleed" };
var Root = (0, import_element48.forwardRef)(function Card({ render: render4, ...restProps }, ref) {
const mergedClassName = clsx_default(style_default3.root, resets_default["box-sizing"]);
const element = useRender({
defaultTagName: "div",
render: render4,
ref,
props: mergeProps({ className: mergedClassName }, restProps)
});
return element;
});
// packages/ui/build-module/card/header.mjs
var import_element49 = __toESM(require_element(), 1);
var STYLE_HASH_ATTRIBUTE4 = "data-wp-hash";
function getRuntime4() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) {
return globalScope.__wpStyleRuntime;
}
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") {
registerDocument4(document);
}
return globalScope.__wpStyleRuntime;
}
function documentContainsStyleHash4(targetDocument, hash) {
if (!targetDocument.head) {
return false;
}
for (const style of targetDocument.head.querySelectorAll(
`style[${STYLE_HASH_ATTRIBUTE4}]`
)) {
if (style.getAttribute(STYLE_HASH_ATTRIBUTE4) === hash) {
return true;
}
}
return false;
}
function injectStyle4(targetDocument, hash, css) {
if (!targetDocument.head) {
return;
}
const runtime = getRuntime4();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) {
return;
}
if (documentContainsStyleHash4(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE4, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
function registerDocument4(targetDocument) {
const runtime = getRuntime4();
runtime.documents.set(
targetDocument,
(runtime.documents.get(targetDocument) ?? 0) + 1
);
for (const [hash, css] of runtime.styles) {
injectStyle4(targetDocument, hash, css);
}
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) {
return;
}
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
function registerStyle4(hash, css) {
const runtime = getRuntime4();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) {
injectStyle4(targetDocument, hash, css);
}
}
if (typeof process === "undefined" || true) {
registerStyle4("5d38cbdd27", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._02872bf298eadc43__root{--wp-ui-card-padding:var(--wpds-dimension-padding-2xl,24px);--wp-ui-card-header-content-gap:var(--wpds-dimension-gap-xl,24px);--wp-ui-card-header-content-margin:calc(var(--wp-ui-card-header-content-gap) - var(--wp-ui-card-padding));background-color:var(--wpds-color-background-surface-neutral-strong,#fff);border:1px solid var(--wpds-color-stroke-surface-neutral-weak,#f0f0f0);border-radius:var(--wpds-border-radius-lg,8px);color:var(--wpds-color-foreground-content-neutral,#1e1e1e);display:flex;flex-direction:column;overflow:clip}._5dffdaf2a6e669ac__content,.bbccc92e6ba5662d__header{padding:var(--wp-ui-card-padding);&:not(:first-child):not(:last-child){padding-block-end:0}}.bbccc92e6ba5662d__header+._5dffdaf2a6e669ac__content{margin-block-start:var(--wp-ui-card-header-content-margin);padding-block-start:0}.c1fa192587e1b4a6__fullbleed{margin-inline:calc(var(--wp-ui-card-padding)*-1);width:calc(100% + var(--wp-ui-card-padding)*2)}._02872bf298eadc43__root>:is(.bbccc92e6ba5662d__header,._5dffdaf2a6e669ac__content):first-child>.c1fa192587e1b4a6__fullbleed:first-child{margin-block-start:calc(var(--wp-ui-card-padding)*-1)}:is(.bbccc92e6ba5662d__header,._5dffdaf2a6e669ac__content):last-child>.c1fa192587e1b4a6__fullbleed:last-child{margin-block-end:calc(var(--wp-ui-card-padding)*-1)}}}");
}
var style_default4 = { "root": "_02872bf298eadc43__root", "header": "bbccc92e6ba5662d__header", "content": "_5dffdaf2a6e669ac__content", "fullbleed": "c1fa192587e1b4a6__fullbleed" };
var Header = (0, import_element49.forwardRef)(
function CardHeader({ render: render4, ...props }, ref) {
const element = useRender({
defaultTagName: "div",
render: render4,
ref,
props: mergeProps({ className: style_default4.header }, props)
});
return element;
}
);
// packages/ui/build-module/card/content.mjs
var import_element50 = __toESM(require_element(), 1);
var STYLE_HASH_ATTRIBUTE5 = "data-wp-hash";
function getRuntime5() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) {
return globalScope.__wpStyleRuntime;
}
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") {
registerDocument5(document);
}
return globalScope.__wpStyleRuntime;
}
function documentContainsStyleHash5(targetDocument, hash) {
if (!targetDocument.head) {
return false;
}
for (const style of targetDocument.head.querySelectorAll(
`style[${STYLE_HASH_ATTRIBUTE5}]`
)) {
if (style.getAttribute(STYLE_HASH_ATTRIBUTE5) === hash) {
return true;
}
}
return false;
}
function injectStyle5(targetDocument, hash, css) {
if (!targetDocument.head) {
return;
}
const runtime = getRuntime5();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) {
return;
}
if (documentContainsStyleHash5(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE5, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
function registerDocument5(targetDocument) {
const runtime = getRuntime5();
runtime.documents.set(
targetDocument,
(runtime.documents.get(targetDocument) ?? 0) + 1
);
for (const [hash, css] of runtime.styles) {
injectStyle5(targetDocument, hash, css);
}
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) {
return;
}
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
function registerStyle5(hash, css) {
const runtime = getRuntime5();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) {
injectStyle5(targetDocument, hash, css);
}
}
if (typeof process === "undefined" || true) {
registerStyle5("5d38cbdd27", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._02872bf298eadc43__root{--wp-ui-card-padding:var(--wpds-dimension-padding-2xl,24px);--wp-ui-card-header-content-gap:var(--wpds-dimension-gap-xl,24px);--wp-ui-card-header-content-margin:calc(var(--wp-ui-card-header-content-gap) - var(--wp-ui-card-padding));background-color:var(--wpds-color-background-surface-neutral-strong,#fff);border:1px solid var(--wpds-color-stroke-surface-neutral-weak,#f0f0f0);border-radius:var(--wpds-border-radius-lg,8px);color:var(--wpds-color-foreground-content-neutral,#1e1e1e);display:flex;flex-direction:column;overflow:clip}._5dffdaf2a6e669ac__content,.bbccc92e6ba5662d__header{padding:var(--wp-ui-card-padding);&:not(:first-child):not(:last-child){padding-block-end:0}}.bbccc92e6ba5662d__header+._5dffdaf2a6e669ac__content{margin-block-start:var(--wp-ui-card-header-content-margin);padding-block-start:0}.c1fa192587e1b4a6__fullbleed{margin-inline:calc(var(--wp-ui-card-padding)*-1);width:calc(100% + var(--wp-ui-card-padding)*2)}._02872bf298eadc43__root>:is(.bbccc92e6ba5662d__header,._5dffdaf2a6e669ac__content):first-child>.c1fa192587e1b4a6__fullbleed:first-child{margin-block-start:calc(var(--wp-ui-card-padding)*-1)}:is(.bbccc92e6ba5662d__header,._5dffdaf2a6e669ac__content):last-child>.c1fa192587e1b4a6__fullbleed:last-child{margin-block-end:calc(var(--wp-ui-card-padding)*-1)}}}");
}
var style_default5 = { "root": "_02872bf298eadc43__root", "header": "bbccc92e6ba5662d__header", "content": "_5dffdaf2a6e669ac__content", "fullbleed": "c1fa192587e1b4a6__fullbleed" };
var Content = (0, import_element50.forwardRef)(
function CardContent({ render: render4, ...props }, ref) {
const element = useRender({
defaultTagName: "div",
render: render4,
ref,
props: mergeProps({ className: style_default5.content }, props)
});
return element;
}
);
// packages/ui/build-module/card/full-bleed.mjs
var import_element51 = __toESM(require_element(), 1);
var STYLE_HASH_ATTRIBUTE6 = "data-wp-hash";
function getRuntime6() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) {
return globalScope.__wpStyleRuntime;
}
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") {
registerDocument6(document);
}
return globalScope.__wpStyleRuntime;
}
function documentContainsStyleHash6(targetDocument, hash) {
if (!targetDocument.head) {
return false;
}
for (const style of targetDocument.head.querySelectorAll(
`style[${STYLE_HASH_ATTRIBUTE6}]`
)) {
if (style.getAttribute(STYLE_HASH_ATTRIBUTE6) === hash) {
return true;
}
}
return false;
}
function injectStyle6(targetDocument, hash, css) {
if (!targetDocument.head) {
return;
}
const runtime = getRuntime6();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) {
return;
}
if (documentContainsStyleHash6(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE6, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
function registerDocument6(targetDocument) {
const runtime = getRuntime6();
runtime.documents.set(
targetDocument,
(runtime.documents.get(targetDocument) ?? 0) + 1
);
for (const [hash, css] of runtime.styles) {
injectStyle6(targetDocument, hash, css);
}
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) {
return;
}
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
function registerStyle6(hash, css) {
const runtime = getRuntime6();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) {
injectStyle6(targetDocument, hash, css);
}
}
if (typeof process === "undefined" || true) {
registerStyle6("5d38cbdd27", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._02872bf298eadc43__root{--wp-ui-card-padding:var(--wpds-dimension-padding-2xl,24px);--wp-ui-card-header-content-gap:var(--wpds-dimension-gap-xl,24px);--wp-ui-card-header-content-margin:calc(var(--wp-ui-card-header-content-gap) - var(--wp-ui-card-padding));background-color:var(--wpds-color-background-surface-neutral-strong,#fff);border:1px solid var(--wpds-color-stroke-surface-neutral-weak,#f0f0f0);border-radius:var(--wpds-border-radius-lg,8px);color:var(--wpds-color-foreground-content-neutral,#1e1e1e);display:flex;flex-direction:column;overflow:clip}._5dffdaf2a6e669ac__content,.bbccc92e6ba5662d__header{padding:var(--wp-ui-card-padding);&:not(:first-child):not(:last-child){padding-block-end:0}}.bbccc92e6ba5662d__header+._5dffdaf2a6e669ac__content{margin-block-start:var(--wp-ui-card-header-content-margin);padding-block-start:0}.c1fa192587e1b4a6__fullbleed{margin-inline:calc(var(--wp-ui-card-padding)*-1);width:calc(100% + var(--wp-ui-card-padding)*2)}._02872bf298eadc43__root>:is(.bbccc92e6ba5662d__header,._5dffdaf2a6e669ac__content):first-child>.c1fa192587e1b4a6__fullbleed:first-child{margin-block-start:calc(var(--wp-ui-card-padding)*-1)}:is(.bbccc92e6ba5662d__header,._5dffdaf2a6e669ac__content):last-child>.c1fa192587e1b4a6__fullbleed:last-child{margin-block-end:calc(var(--wp-ui-card-padding)*-1)}}}");
}
var style_default6 = { "root": "_02872bf298eadc43__root", "header": "bbccc92e6ba5662d__header", "content": "_5dffdaf2a6e669ac__content", "fullbleed": "c1fa192587e1b4a6__fullbleed" };
var FullBleed = (0, import_element51.forwardRef)(
function CardFullBleed({ render: render4, ...props }, ref) {
const element = useRender({
defaultTagName: "div",
render: render4,
ref,
props: mergeProps(
{ className: style_default6.fullbleed },
props
)
});
return element;
}
);
// packages/ui/build-module/card/title.mjs
var import_element52 = __toESM(require_element(), 1);
var import_jsx_runtime184 = __toESM(require_jsx_runtime(), 1);
var DEFAULT_TAG = /* @__PURE__ */ (0, import_jsx_runtime184.jsx)("div", {});
var Title = (0, import_element52.forwardRef)(
function CardTitle({ render: render4 = DEFAULT_TAG, children, ...props }, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime184.jsx)(
Text,
{
ref,
variant: "heading-lg",
render: render4,
...props,
children
}
);
}
);
// packages/ui/build-module/collapsible/panel.mjs
var import_element53 = __toESM(require_element(), 1);
var import_jsx_runtime185 = __toESM(require_jsx_runtime(), 1);
var Panel = (0, import_element53.forwardRef)(
function CollapsiblePanel3(props, forwardedRef) {
return /* @__PURE__ */ (0, import_jsx_runtime185.jsx)(index_parts_exports.Panel, { ref: forwardedRef, ...props });
}
);
// packages/ui/build-module/collapsible/root.mjs
var import_element54 = __toESM(require_element(), 1);
var import_jsx_runtime186 = __toESM(require_jsx_runtime(), 1);
var Root2 = (0, import_element54.forwardRef)(
function CollapsibleRoot3(props, forwardedRef) {
return /* @__PURE__ */ (0, import_jsx_runtime186.jsx)(index_parts_exports.Root, { ref: forwardedRef, ...props });
}
);
// packages/ui/build-module/collapsible/trigger.mjs
var import_element55 = __toESM(require_element(), 1);
var import_jsx_runtime187 = __toESM(require_jsx_runtime(), 1);
var Trigger = (0, import_element55.forwardRef)(
function CollapsibleTrigger3(props, forwardedRef) {
return /* @__PURE__ */ (0, import_jsx_runtime187.jsx)(index_parts_exports.Trigger, { ref: forwardedRef, ...props });
}
);
// packages/ui/build-module/collapsible-card/index.mjs
var collapsible_card_exports = {};
__export(collapsible_card_exports, {
Content: () => Content2,
Header: () => Header2,
HeaderDescription: () => HeaderDescription,
Root: () => Root3
});
// packages/ui/build-module/collapsible-card/root.mjs
var import_element56 = __toESM(require_element(), 1);
var import_jsx_runtime188 = __toESM(require_jsx_runtime(), 1);
var Root3 = (0, import_element56.forwardRef)(
function CollapsibleCardRoot({ render: render4, ...restProps }, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime188.jsx)(
Root2,
{
ref,
render: /* @__PURE__ */ (0, import_jsx_runtime188.jsx)(Root, { render: render4 }),
...restProps
}
);
}
);
// packages/ui/build-module/collapsible-card/header.mjs
var import_element58 = __toESM(require_element(), 1);
// packages/ui/build-module/collapsible-card/context.mjs
var import_element57 = __toESM(require_element(), 1);
var HeaderDescriptionIdContext = (0, import_element57.createContext)({
setDescriptionId: () => {
}
});
// packages/ui/build-module/collapsible-card/header.mjs
var import_jsx_runtime189 = __toESM(require_jsx_runtime(), 1);
var STYLE_HASH_ATTRIBUTE7 = "data-wp-hash";
function getRuntime7() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) {
return globalScope.__wpStyleRuntime;
}
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") {
registerDocument7(document);
}
return globalScope.__wpStyleRuntime;
}
function documentContainsStyleHash7(targetDocument, hash) {
if (!targetDocument.head) {
return false;
}
for (const style of targetDocument.head.querySelectorAll(
`style[${STYLE_HASH_ATTRIBUTE7}]`
)) {
if (style.getAttribute(STYLE_HASH_ATTRIBUTE7) === hash) {
return true;
}
}
return false;
}
function injectStyle7(targetDocument, hash, css) {
if (!targetDocument.head) {
return;
}
const runtime = getRuntime7();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) {
return;
}
if (documentContainsStyleHash7(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE7, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
function registerDocument7(targetDocument) {
const runtime = getRuntime7();
runtime.documents.set(
targetDocument,
(runtime.documents.get(targetDocument) ?? 0) + 1
);
for (const [hash, css] of runtime.styles) {
injectStyle7(targetDocument, hash, css);
}
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) {
return;
}
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
function registerStyle7(hash, css) {
const runtime = getRuntime7();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) {
injectStyle7(targetDocument, hash, css);
}
}
if (typeof process === "undefined" || true) {
registerStyle7("78199613cf", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._626190151275d6d3__heading-wrapper{--_gcd-heading-color:inherit;--_gcd-heading-font-size:inherit;--_gcd-heading-font-weight:inherit;--_gcd-heading-margin:0;font-family:inherit;line-height:inherit}.cab17c7a373cb60d__header-content{flex:1;min-width:0}.dd89d27c4f15912d__header-trigger-positioner{align-self:center;flex-shrink:0;max-height:0;overflow:visible}.bcfab5f2448bafef__header-trigger-wrapper{border-radius:var(--wpds-border-radius-sm,2px);display:flex;translate:0 -50%}._3106f8d2b0330faa__header-trigger{@media not (prefers-reduced-motion){transition:rotate .15s ease-out}}._5d2dfcb4085c6d0f__header[data-panel-open] ._3106f8d2b0330faa__header-trigger{rotate:180deg}._5d2dfcb4085c6d0f__header[data-disabled] ._3106f8d2b0330faa__header-trigger{color:var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d)}.e34cf37ccd0d81e0__content{height:var(--collapsible-panel-height);margin-block-start:var(--wp-ui-card-header-content-margin);overflow:hidden;&._03cfdbcd710393c9__overflow-visible{overflow:visible}&[hidden]:not([hidden=until-found]){display:none}&[data-ending-style],&[data-starting-style]{height:0}@media not (prefers-reduced-motion){transition:all .15s ease-out}}}@layer compositions{._41bfdbf7b6c087c2__content-inner{padding-block-start:0}._5d2dfcb4085c6d0f__header{align-items:stretch;display:flex;flex-direction:row;gap:var(--wpds-dimension-gap-sm,8px);outline:none;&:not([data-disabled]){cursor:var(--wpds-cursor-control,pointer)}}}}");
}
var style_default7 = { "heading-wrapper": "_626190151275d6d3__heading-wrapper", "header-content": "cab17c7a373cb60d__header-content", "header-trigger-positioner": "dd89d27c4f15912d__header-trigger-positioner", "header-trigger-wrapper": "bcfab5f2448bafef__header-trigger-wrapper", "header-trigger": "_3106f8d2b0330faa__header-trigger", "header": "_5d2dfcb4085c6d0f__header", "content": "e34cf37ccd0d81e0__content", "overflow-visible": "_03cfdbcd710393c9__overflow-visible", "content-inner": "_41bfdbf7b6c087c2__content-inner" };
if (typeof process === "undefined" || true) {
registerStyle7("af6d9984a6", "._6defc79820e382c6__button{box-sizing:var(--_gcd-button-box-sizing,border-box);font-family:var(--_gcd-button-font-family,inherit);font-size:var(--_gcd-button-font-size,inherit);font-weight:var(--_gcd-button-font-weight,inherit)}.d2cff2e5dea83bd1__input{box-sizing:var(--_gcd-input-box-sizing,border-box);font-family:var(--_gcd-input-font-family,inherit);font-size:var(--_gcd-input-font-size,inherit);font-weight:var(--_gcd-input-font-weight,inherit);margin:var(--_gcd-input-margin,0);&:is(textarea,[type=text],[type=password],[type=color],[type=date],[type=datetime],[type=datetime-local],[type=email],[type=month],[type=number],[type=search],[type=tel],[type=time],[type=url],[type=week]){background-color:var(--_gcd-input-background-color,transparent);border:var(--_gcd-input-border,none);border-radius:var(--_gcd-input-border-radius,0);box-shadow:var(--_gcd-input-box-shadow,0 0 0 transparent);color:var(--_gcd-input-color,var(--wpds-color-foreground-interactive-neutral,#1e1e1e));&:focus{border-color:var(--_gcd-input-border-color-focus,var(--wp-admin-theme-color));box-shadow:var(--_gcd-input-box-shadow-focus,none);outline:var(--_gcd-input-outline-focus,none)}&:disabled{background:var(--_gcd-input-background-disabled,transparent);border-color:var(--_gcd-input-border-color-disabled,transparent);box-shadow:var(--_gcd-input-box-shadow-disabled,none);color:var(--_gcd-input-color-disabled,var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d))}&::placeholder{color:var(--_gcd-input-placeholder-color,var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d))}}&:is(textarea,[type=text],[type=password],[type=date],[type=datetime],[type=datetime-local],[type=email],[type=month],[type=number],[type=search],[type=tel],[type=time],[type=url],[type=week]){line-height:var(--_gcd-input-line-height,inherit);min-height:var(--_gcd-input-min-height,auto);padding:var(--_gcd-input-padding,0)}}._547d86373d02e108__textarea{box-sizing:var(--_gcd-textarea-box-sizing,border-box);overflow:var(--_gcd-textarea-overflow,auto);resize:var(--_gcd-textarea-resize,block)}._8c15fd0ed9f28ba4__div{outline:var(--_gcd-div-outline,0 solid transparent)}p._43cec3e1eec1066d__p{font-size:var(--_gcd-p-font-size,13px);line-height:var(--_gcd-p-line-height,1.5);margin:var(--_gcd-p-margin,0)}:is(h1,h2,h3,h4,h5,h6).e97669c6d9a38497__heading{color:var(--_gcd-heading-color,var(--wpds-color-foreground-content-neutral,#1e1e1e));font-size:var(--_gcd-heading-font-size,inherit);font-weight:var(--_gcd-heading-font-weight,var(--wpds-typography-font-weight-emphasis,600));margin:var(--_gcd-heading-margin,0)}._2c0831b0499dbd6e__a,._2c0831b0499dbd6e__a:is(:hover,:focus,:active){border-radius:var(--_gcd-a-border-radius,0);box-shadow:var(--_gcd-a-box-shadow,none);color:var(--_gcd-a-color,inherit);outline:var(--_gcd-a-outline,0 solid transparent);transition:var(--_gcd-a-transition,none)}");
}
var global_css_defense_default2 = { "button": "_6defc79820e382c6__button", "input": "d2cff2e5dea83bd1__input", "textarea": "_547d86373d02e108__textarea", "div": "_8c15fd0ed9f28ba4__div", "p": "_43cec3e1eec1066d__p", "heading": "e97669c6d9a38497__heading", "a": "_2c0831b0499dbd6e__a" };
if (typeof process === "undefined" || true) {
registerStyle7("5f8e7aa0bc", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._08e8a2e44959f892__outset-ring--focus:focus,._970d04df7376df67__outset-ring--focus-within-except-active:focus-within:not(:has(:active)),.c5cb3ee4bddaa8e4__outset-ring--focus-within-visible:focus-within:has(:focus-visible),.cd83dfc2126a0846__outset-ring--focus-within:focus-within,.d0541bc9dd9dc7b6__outset-ring--focus-visible:focus-visible,.e25b2bdd7aa21721__outset-ring--focus-except-active:focus:not(:active),:focus-visible .ecadb9e080e2dfa5__outset-ring--focus-parent-visible{--_gcd-a-outline:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px)) solid var(--wpds-color-stroke-focus,var(--wp-admin-theme-color,#3858e9));--_gcd-div-outline:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px)) solid var(--wpds-color-stroke-focus,var(--wp-admin-theme-color,#3858e9));outline:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px)) solid var(--wpds-color-stroke-focus,var(--wp-admin-theme-color,#3858e9));outline-offset:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px))}}}");
}
var focus_default = { "outset-ring--focus": "_08e8a2e44959f892__outset-ring--focus", "outset-ring--focus-except-active": "e25b2bdd7aa21721__outset-ring--focus-except-active", "outset-ring--focus-visible": "d0541bc9dd9dc7b6__outset-ring--focus-visible", "outset-ring--focus-within": "cd83dfc2126a0846__outset-ring--focus-within", "outset-ring--focus-within-except-active": "_970d04df7376df67__outset-ring--focus-within-except-active", "outset-ring--focus-within-visible": "c5cb3ee4bddaa8e4__outset-ring--focus-within-visible", "outset-ring--focus-parent-visible": "ecadb9e080e2dfa5__outset-ring--focus-parent-visible" };
var Header2 = (0, import_element58.forwardRef)(
function CollapsibleCardHeader({ children, className, render: render4, ...restProps }, ref) {
const [descriptionId, setDescriptionId] = (0, import_element58.useState)();
const contextValue = (0, import_element58.useMemo)(
() => ({ setDescriptionId }),
[setDescriptionId]
);
return useRender({
defaultTagName: "div",
render: render4,
ref,
props: mergeProps(restProps, {
className: clsx_default(
global_css_defense_default2.heading,
style_default7["heading-wrapper"],
className
),
children: /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(HeaderDescriptionIdContext.Provider, { value: contextValue, children: /* @__PURE__ */ (0, import_jsx_runtime189.jsxs)(
Trigger,
{
className: style_default7.header,
render: /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(Header, {}),
nativeButton: false,
"aria-describedby": descriptionId,
children: [
/* @__PURE__ */ (0, import_jsx_runtime189.jsx)("div", { className: style_default7["header-content"], children }),
/* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
"div",
{
className: clsx_default(
style_default7["header-trigger-positioner"]
),
children: /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
"div",
{
className: clsx_default(
style_default7["header-trigger-wrapper"],
global_css_defense_default2.div,
// While the interactive trigger element is the whole header,
// the focus ring will be displayed only on the icon to visually
// emulate it being the button.
focus_default["outset-ring--focus-parent-visible"]
),
children: /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
Icon,
{
icon: chevron_down_default,
className: style_default7["header-trigger"]
}
)
}
)
}
)
]
}
) })
})
});
}
);
// packages/ui/build-module/collapsible-card/header-description.mjs
var import_element59 = __toESM(require_element(), 1);
var import_jsx_runtime190 = __toESM(require_jsx_runtime(), 1);
var HeaderDescription = (0, import_element59.forwardRef)(function CollapsibleCardHeaderDescription({ children, className, ...restProps }, ref) {
const descriptionId = (0, import_element59.useId)();
const { setDescriptionId } = (0, import_element59.useContext)(HeaderDescriptionIdContext);
(0, import_element59.useEffect)(() => {
setDescriptionId(descriptionId);
return () => setDescriptionId(void 0);
}, [descriptionId, setDescriptionId]);
return /* @__PURE__ */ (0, import_jsx_runtime190.jsx)(
"div",
{
ref,
id: descriptionId,
"aria-hidden": "true",
className,
...restProps,
children
}
);
});
// packages/ui/build-module/collapsible-card/content.mjs
var import_element60 = __toESM(require_element(), 1);
var import_jsx_runtime191 = __toESM(require_jsx_runtime(), 1);
var STYLE_HASH_ATTRIBUTE8 = "data-wp-hash";
function getRuntime8() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) {
return globalScope.__wpStyleRuntime;
}
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") {
registerDocument8(document);
}
return globalScope.__wpStyleRuntime;
}
function documentContainsStyleHash8(targetDocument, hash) {
if (!targetDocument.head) {
return false;
}
for (const style of targetDocument.head.querySelectorAll(
`style[${STYLE_HASH_ATTRIBUTE8}]`
)) {
if (style.getAttribute(STYLE_HASH_ATTRIBUTE8) === hash) {
return true;
}
}
return false;
}
function injectStyle8(targetDocument, hash, css) {
if (!targetDocument.head) {
return;
}
const runtime = getRuntime8();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) {
return;
}
if (documentContainsStyleHash8(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE8, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
function registerDocument8(targetDocument) {
const runtime = getRuntime8();
runtime.documents.set(
targetDocument,
(runtime.documents.get(targetDocument) ?? 0) + 1
);
for (const [hash, css] of runtime.styles) {
injectStyle8(targetDocument, hash, css);
}
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) {
return;
}
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
function registerStyle8(hash, css) {
const runtime = getRuntime8();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) {
injectStyle8(targetDocument, hash, css);
}
}
if (typeof process === "undefined" || true) {
registerStyle8("78199613cf", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._626190151275d6d3__heading-wrapper{--_gcd-heading-color:inherit;--_gcd-heading-font-size:inherit;--_gcd-heading-font-weight:inherit;--_gcd-heading-margin:0;font-family:inherit;line-height:inherit}.cab17c7a373cb60d__header-content{flex:1;min-width:0}.dd89d27c4f15912d__header-trigger-positioner{align-self:center;flex-shrink:0;max-height:0;overflow:visible}.bcfab5f2448bafef__header-trigger-wrapper{border-radius:var(--wpds-border-radius-sm,2px);display:flex;translate:0 -50%}._3106f8d2b0330faa__header-trigger{@media not (prefers-reduced-motion){transition:rotate .15s ease-out}}._5d2dfcb4085c6d0f__header[data-panel-open] ._3106f8d2b0330faa__header-trigger{rotate:180deg}._5d2dfcb4085c6d0f__header[data-disabled] ._3106f8d2b0330faa__header-trigger{color:var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d)}.e34cf37ccd0d81e0__content{height:var(--collapsible-panel-height);margin-block-start:var(--wp-ui-card-header-content-margin);overflow:hidden;&._03cfdbcd710393c9__overflow-visible{overflow:visible}&[hidden]:not([hidden=until-found]){display:none}&[data-ending-style],&[data-starting-style]{height:0}@media not (prefers-reduced-motion){transition:all .15s ease-out}}}@layer compositions{._41bfdbf7b6c087c2__content-inner{padding-block-start:0}._5d2dfcb4085c6d0f__header{align-items:stretch;display:flex;flex-direction:row;gap:var(--wpds-dimension-gap-sm,8px);outline:none;&:not([data-disabled]){cursor:var(--wpds-cursor-control,pointer)}}}}");
}
var style_default8 = { "heading-wrapper": "_626190151275d6d3__heading-wrapper", "header-content": "cab17c7a373cb60d__header-content", "header-trigger-positioner": "dd89d27c4f15912d__header-trigger-positioner", "header-trigger-wrapper": "bcfab5f2448bafef__header-trigger-wrapper", "header-trigger": "_3106f8d2b0330faa__header-trigger", "header": "_5d2dfcb4085c6d0f__header", "content": "e34cf37ccd0d81e0__content", "overflow-visible": "_03cfdbcd710393c9__overflow-visible", "content-inner": "_41bfdbf7b6c087c2__content-inner" };
var Content2 = (0, import_element60.forwardRef)(
function CollapsibleCardContent({ className, render: render4, children, hiddenUntilFound = true, ...restProps }, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime191.jsx)(
Panel,
{
ref,
className: (state) => clsx_default(
style_default8.content,
state.open && state.transitionStatus === "idle" && style_default8["overflow-visible"],
className
),
hiddenUntilFound,
...restProps,
children: /* @__PURE__ */ (0, import_jsx_runtime191.jsx)(
Content,
{
className: style_default8["content-inner"],
render: render4,
children
}
)
}
);
}
);
// packages/ui/build-module/utils/render-slot-with-children.mjs
var import_element61 = __toESM(require_element(), 1);
function renderSlotWithChildren(slot, defaultSlot, children) {
return (0, import_element61.cloneElement)(slot ?? defaultSlot, { children });
}
// packages/ui/build-module/utils/theme-provider.mjs
var theme = __toESM(require_theme(), 1);
// packages/ui/build-module/lock-unlock.mjs
var import_private_apis4 = __toESM(require_private_apis(), 1);
var { lock: lock3, unlock: unlock3 } = (0, import_private_apis4.__dangerousOptInToUnstableAPIsOnlyForCoreModules)(
"I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.",
"@wordpress/ui"
);
// packages/ui/build-module/utils/theme-provider.mjs
function getThemeProvider() {
const themePackage = theme;
if (themePackage.ThemeProvider) {
return themePackage.ThemeProvider;
}
if (!themePackage.privateApis) {
throw new Error(
"@wordpress/ui: @wordpress/theme must expose `ThemeProvider` or `privateApis.ThemeProvider`."
);
}
return unlock3(
themePackage.privateApis
).ThemeProvider;
}
var ThemeProvider = getThemeProvider();
// packages/ui/build-module/stack/stack.mjs
var import_element62 = __toESM(require_element(), 1);
var STYLE_HASH_ATTRIBUTE9 = "data-wp-hash";
function getRuntime9() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) {
return globalScope.__wpStyleRuntime;
}
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") {
registerDocument9(document);
}
return globalScope.__wpStyleRuntime;
}
function documentContainsStyleHash9(targetDocument, hash) {
if (!targetDocument.head) {
return false;
}
for (const style of targetDocument.head.querySelectorAll(
`style[${STYLE_HASH_ATTRIBUTE9}]`
)) {
if (style.getAttribute(STYLE_HASH_ATTRIBUTE9) === hash) {
return true;
}
}
return false;
}
function injectStyle9(targetDocument, hash, css) {
if (!targetDocument.head) {
return;
}
const runtime = getRuntime9();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) {
return;
}
if (documentContainsStyleHash9(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE9, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
function registerDocument9(targetDocument) {
const runtime = getRuntime9();
runtime.documents.set(
targetDocument,
(runtime.documents.get(targetDocument) ?? 0) + 1
);
for (const [hash, css] of runtime.styles) {
injectStyle9(targetDocument, hash, css);
}
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) {
return;
}
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
function registerStyle9(hash, css) {
const runtime = getRuntime9();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) {
injectStyle9(targetDocument, hash, css);
}
}
if (typeof process === "undefined" || true) {
registerStyle9("32aba35fe1", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._19ce0419607e1896__stack{display:flex}}}");
}
var style_default9 = { "stack": "_19ce0419607e1896__stack" };
var gapTokens = {
xs: "var(--wpds-dimension-gap-xs, 4px)",
sm: "var(--wpds-dimension-gap-sm, 8px)",
md: "var(--wpds-dimension-gap-md, 12px)",
lg: "var(--wpds-dimension-gap-lg, 16px)",
xl: "var(--wpds-dimension-gap-xl, 24px)",
"2xl": "var(--wpds-dimension-gap-2xl, 32px)",
"3xl": "var(--wpds-dimension-gap-3xl, 40px)"
};
var Stack = (0, import_element62.forwardRef)(function Stack2({ direction, gap, align, justify, wrap, render: render4, ...props }, ref) {
const style = {
gap: gap && gapTokens[gap],
alignItems: align,
justifyContent: justify,
flexDirection: direction,
flexWrap: wrap
};
const element = useRender({
render: render4,
ref,
props: mergeProps(props, { style, className: style_default9.stack })
});
return element;
});
// packages/ui/build-module/tooltip/index.mjs
var tooltip_exports = {};
__export(tooltip_exports, {
Popup: () => Popup,
Portal: () => Portal,
Positioner: () => Positioner,
Provider: () => Provider2,
Root: () => Root4,
Trigger: () => Trigger2
});
// packages/ui/build-module/tooltip/popup.mjs
var import_element65 = __toESM(require_element(), 1);
// packages/ui/build-module/tooltip/portal.mjs
var import_element63 = __toESM(require_element(), 1);
// packages/ui/build-module/utils/wp-compat-overlay-slot.mjs
var STYLE_HASH_ATTRIBUTE10 = "data-wp-hash";
function getRuntime10() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) {
return globalScope.__wpStyleRuntime;
}
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") {
registerDocument10(document);
}
return globalScope.__wpStyleRuntime;
}
function documentContainsStyleHash10(targetDocument, hash) {
if (!targetDocument.head) {
return false;
}
for (const style of targetDocument.head.querySelectorAll(
`style[${STYLE_HASH_ATTRIBUTE10}]`
)) {
if (style.getAttribute(STYLE_HASH_ATTRIBUTE10) === hash) {
return true;
}
}
return false;
}
function injectStyle10(targetDocument, hash, css) {
if (!targetDocument.head) {
return;
}
const runtime = getRuntime10();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) {
return;
}
if (documentContainsStyleHash10(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE10, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
function registerDocument10(targetDocument) {
const runtime = getRuntime10();
runtime.documents.set(
targetDocument,
(runtime.documents.get(targetDocument) ?? 0) + 1
);
for (const [hash, css] of runtime.styles) {
injectStyle10(targetDocument, hash, css);
}
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) {
return;
}
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
function registerStyle10(hash, css) {
const runtime = getRuntime10();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) {
injectStyle10(targetDocument, hash, css);
}
}
if (typeof process === "undefined" || true) {
registerStyle10("be37f31c1e", "._11fc52b637ff8a7e__slot{inset:0;isolation:isolate;pointer-events:none;position:fixed;z-index:1000000003}@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._11fc52b637ff8a7e__slot>*{pointer-events:auto}}}");
}
var wp_compat_overlay_slot_default = { "slot": "_11fc52b637ff8a7e__slot" };
var WP_COMPAT_OVERLAY_SLOT_ATTRIBUTE = "data-wp-compat-overlay-slot";
function resolveOwnerDocument() {
return typeof document === "undefined" ? null : document;
}
function isInWordPressEnvironment() {
let topWp;
try {
topWp = window.top?.wp;
} catch {
}
const wp = topWp ?? window.wp;
return typeof wp?.components === "object" && wp.components !== null;
}
var cachedSlot = null;
function createSlot(ownerDocument2) {
const element = ownerDocument2.createElement("div");
element.setAttribute(WP_COMPAT_OVERLAY_SLOT_ATTRIBUTE, "");
if (wp_compat_overlay_slot_default.slot) {
element.classList.add(wp_compat_overlay_slot_default.slot);
}
ownerDocument2.body.appendChild(element);
return element;
}
function getWpCompatOverlaySlot() {
if (typeof window === "undefined") {
return void 0;
}
if (!isInWordPressEnvironment() && window.__wpUiCompatOverlaySlotEnabled !== true) {
return void 0;
}
const ownerDocument2 = resolveOwnerDocument();
if (!ownerDocument2 || !ownerDocument2.body) {
return void 0;
}
if (cachedSlot && cachedSlot.ownerDocument === ownerDocument2 && cachedSlot.isConnected) {
return cachedSlot;
}
const existing = ownerDocument2.querySelector(
`[${WP_COMPAT_OVERLAY_SLOT_ATTRIBUTE}]`
);
if (existing instanceof HTMLDivElement) {
cachedSlot = existing;
return existing;
}
if (cachedSlot?.isConnected) {
cachedSlot.remove();
}
cachedSlot = createSlot(ownerDocument2);
return cachedSlot;
}
// packages/ui/build-module/tooltip/portal.mjs
var import_jsx_runtime192 = __toESM(require_jsx_runtime(), 1);
var Portal = (0, import_element63.forwardRef)(
function TooltipPortal3({ container, ...restProps }, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime192.jsx)(
index_parts_exports4.Portal,
{
container: container ?? getWpCompatOverlaySlot(),
...restProps,
ref
}
);
}
);
// packages/ui/build-module/tooltip/positioner.mjs
var import_element64 = __toESM(require_element(), 1);
var import_jsx_runtime193 = __toESM(require_jsx_runtime(), 1);
var STYLE_HASH_ATTRIBUTE11 = "data-wp-hash";
function getRuntime11() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) {
return globalScope.__wpStyleRuntime;
}
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") {
registerDocument11(document);
}
return globalScope.__wpStyleRuntime;
}
function documentContainsStyleHash11(targetDocument, hash) {
if (!targetDocument.head) {
return false;
}
for (const style of targetDocument.head.querySelectorAll(
`style[${STYLE_HASH_ATTRIBUTE11}]`
)) {
if (style.getAttribute(STYLE_HASH_ATTRIBUTE11) === hash) {
return true;
}
}
return false;
}
function injectStyle11(targetDocument, hash, css) {
if (!targetDocument.head) {
return;
}
const runtime = getRuntime11();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) {
return;
}
if (documentContainsStyleHash11(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE11, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
function registerDocument11(targetDocument) {
const runtime = getRuntime11();
runtime.documents.set(
targetDocument,
(runtime.documents.get(targetDocument) ?? 0) + 1
);
for (const [hash, css] of runtime.styles) {
injectStyle11(targetDocument, hash, css);
}
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) {
return;
}
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
function registerStyle11(hash, css) {
const runtime = getRuntime11();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) {
injectStyle11(targetDocument, hash, css);
}
}
if (typeof process === "undefined" || true) {
registerStyle11("10f3806643", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._336cd3e4e743482f__box-sizing{box-sizing:border-box;*,:after,:before{box-sizing:inherit}}}}");
}
var resets_default2 = { "box-sizing": "_336cd3e4e743482f__box-sizing" };
if (typeof process === "undefined" || true) {
registerStyle11("19fcc06039", '@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._480b748dd3510e64__positioner{z-index:var(--wp-ui-tooltip-z-index,initial)}._50096b232db7709d__popup{--_wp-ui-elevation-sm:0 1px 2px rgba(0,0,0,.05),0 2px 3px rgba(0,0,0,.04),0 6px 6px rgba(0,0,0,.03),0 8px 8px rgba(0,0,0,.02);background-color:var(--wpds-color-background-surface-neutral-strong,#fff);border-radius:var(--wpds-border-radius-md,4px);box-shadow:var(--_wp-ui-elevation-sm);color:var(--wpds-color-foreground-content-neutral,#1e1e1e);font-family:var(--wpds-typography-font-family-body,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-size:var(--wpds-typography-font-size-sm,12px);line-height:1.4;padding:var(--wpds-dimension-padding-xs,4px) var(--wpds-dimension-padding-sm,8px);@media (forced-colors:active){border-bottom-color:CanvasText;border-bottom-style:solid;border-bottom-width:1px;border-left-color:CanvasText;border-left-style:solid;border-left-width:1px;border-right-color:CanvasText;border-right-style:solid;border-right-width:1px;border-top-color:CanvasText;border-top-style:solid;border-top-width:1px}}}}');
}
var style_default10 = { "positioner": "_480b748dd3510e64__positioner", "popup": "_50096b232db7709d__popup" };
var Positioner = (0, import_element64.forwardRef)(
function TooltipPositioner3({ align = "center", className, side = "top", sideOffset = 4, ...props }, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime193.jsx)(
index_parts_exports4.Positioner,
{
ref,
align,
side,
sideOffset,
...props,
className: clsx_default(
resets_default2["box-sizing"],
style_default10.positioner,
className
)
}
);
}
);
// packages/ui/build-module/tooltip/popup.mjs
var import_jsx_runtime194 = __toESM(require_jsx_runtime(), 1);
var STYLE_HASH_ATTRIBUTE12 = "data-wp-hash";
function getRuntime12() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) {
return globalScope.__wpStyleRuntime;
}
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") {
registerDocument12(document);
}
return globalScope.__wpStyleRuntime;
}
function documentContainsStyleHash12(targetDocument, hash) {
if (!targetDocument.head) {
return false;
}
for (const style of targetDocument.head.querySelectorAll(
`style[${STYLE_HASH_ATTRIBUTE12}]`
)) {
if (style.getAttribute(STYLE_HASH_ATTRIBUTE12) === hash) {
return true;
}
}
return false;
}
function injectStyle12(targetDocument, hash, css) {
if (!targetDocument.head) {
return;
}
const runtime = getRuntime12();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) {
return;
}
if (documentContainsStyleHash12(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE12, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
function registerDocument12(targetDocument) {
const runtime = getRuntime12();
runtime.documents.set(
targetDocument,
(runtime.documents.get(targetDocument) ?? 0) + 1
);
for (const [hash, css] of runtime.styles) {
injectStyle12(targetDocument, hash, css);
}
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) {
return;
}
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
function registerStyle12(hash, css) {
const runtime = getRuntime12();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) {
injectStyle12(targetDocument, hash, css);
}
}
if (typeof process === "undefined" || true) {
registerStyle12("19fcc06039", '@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._480b748dd3510e64__positioner{z-index:var(--wp-ui-tooltip-z-index,initial)}._50096b232db7709d__popup{--_wp-ui-elevation-sm:0 1px 2px rgba(0,0,0,.05),0 2px 3px rgba(0,0,0,.04),0 6px 6px rgba(0,0,0,.03),0 8px 8px rgba(0,0,0,.02);background-color:var(--wpds-color-background-surface-neutral-strong,#fff);border-radius:var(--wpds-border-radius-md,4px);box-shadow:var(--_wp-ui-elevation-sm);color:var(--wpds-color-foreground-content-neutral,#1e1e1e);font-family:var(--wpds-typography-font-family-body,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-size:var(--wpds-typography-font-size-sm,12px);line-height:1.4;padding:var(--wpds-dimension-padding-xs,4px) var(--wpds-dimension-padding-sm,8px);@media (forced-colors:active){border-bottom-color:CanvasText;border-bottom-style:solid;border-bottom-width:1px;border-left-color:CanvasText;border-left-style:solid;border-left-width:1px;border-right-color:CanvasText;border-right-style:solid;border-right-width:1px;border-top-color:CanvasText;border-top-style:solid;border-top-width:1px}}}}');
}
var style_default11 = { "positioner": "_480b748dd3510e64__positioner", "popup": "_50096b232db7709d__popup" };
var POPUP_COLOR = { background: "#1e1e1e" };
var Popup = (0, import_element65.forwardRef)(function TooltipPopup3({ portal, positioner, children, className, ...props }, ref) {
const popupContent = /* @__PURE__ */ (0, import_jsx_runtime194.jsx)(ThemeProvider, { color: POPUP_COLOR, children: /* @__PURE__ */ (0, import_jsx_runtime194.jsx)(
index_parts_exports4.Popup,
{
ref,
className: clsx_default(style_default11.popup, className),
...props,
children
}
) });
const positionedPopup = renderSlotWithChildren(
positioner,
/* @__PURE__ */ (0, import_jsx_runtime194.jsx)(Positioner, {}),
popupContent
);
return renderSlotWithChildren(portal, /* @__PURE__ */ (0, import_jsx_runtime194.jsx)(Portal, {}), positionedPopup);
});
// packages/ui/build-module/tooltip/trigger.mjs
var import_element66 = __toESM(require_element(), 1);
var import_jsx_runtime195 = __toESM(require_jsx_runtime(), 1);
var Trigger2 = (0, import_element66.forwardRef)(
function TooltipTrigger3(props, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime195.jsx)(index_parts_exports4.Trigger, { ref, ...props });
}
);
// packages/ui/build-module/tooltip/root.mjs
var import_jsx_runtime196 = __toESM(require_jsx_runtime(), 1);
function Root4(props) {
return /* @__PURE__ */ (0, import_jsx_runtime196.jsx)(index_parts_exports4.Root, { ...props });
}
// packages/ui/build-module/tooltip/provider.mjs
var import_jsx_runtime197 = __toESM(require_jsx_runtime(), 1);
function Provider2({ ...props }) {
return /* @__PURE__ */ (0, import_jsx_runtime197.jsx)(index_parts_exports4.Provider, { ...props });
}
// packages/ui/build-module/form/primitives/input-layout/input-layout.mjs
var import_element67 = __toESM(require_element(), 1);
var import_jsx_runtime198 = __toESM(require_jsx_runtime(), 1);
var STYLE_HASH_ATTRIBUTE13 = "data-wp-hash";
function getRuntime13() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) {
return globalScope.__wpStyleRuntime;
}
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") {
registerDocument13(document);
}
return globalScope.__wpStyleRuntime;
}
function documentContainsStyleHash13(targetDocument, hash) {
if (!targetDocument.head) {
return false;
}
for (const style of targetDocument.head.querySelectorAll(
`style[${STYLE_HASH_ATTRIBUTE13}]`
)) {
if (style.getAttribute(STYLE_HASH_ATTRIBUTE13) === hash) {
return true;
}
}
return false;
}
function injectStyle13(targetDocument, hash, css) {
if (!targetDocument.head) {
return;
}
const runtime = getRuntime13();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) {
return;
}
if (documentContainsStyleHash13(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE13, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
function registerDocument13(targetDocument) {
const runtime = getRuntime13();
runtime.documents.set(
targetDocument,
(runtime.documents.get(targetDocument) ?? 0) + 1
);
for (const [hash, css] of runtime.styles) {
injectStyle13(targetDocument, hash, css);
}
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) {
return;
}
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
function registerStyle13(hash, css) {
const runtime = getRuntime13();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) {
injectStyle13(targetDocument, hash, css);
}
}
if (typeof process === "undefined" || true) {
registerStyle13("af6d9984a6", "._6defc79820e382c6__button{box-sizing:var(--_gcd-button-box-sizing,border-box);font-family:var(--_gcd-button-font-family,inherit);font-size:var(--_gcd-button-font-size,inherit);font-weight:var(--_gcd-button-font-weight,inherit)}.d2cff2e5dea83bd1__input{box-sizing:var(--_gcd-input-box-sizing,border-box);font-family:var(--_gcd-input-font-family,inherit);font-size:var(--_gcd-input-font-size,inherit);font-weight:var(--_gcd-input-font-weight,inherit);margin:var(--_gcd-input-margin,0);&:is(textarea,[type=text],[type=password],[type=color],[type=date],[type=datetime],[type=datetime-local],[type=email],[type=month],[type=number],[type=search],[type=tel],[type=time],[type=url],[type=week]){background-color:var(--_gcd-input-background-color,transparent);border:var(--_gcd-input-border,none);border-radius:var(--_gcd-input-border-radius,0);box-shadow:var(--_gcd-input-box-shadow,0 0 0 transparent);color:var(--_gcd-input-color,var(--wpds-color-foreground-interactive-neutral,#1e1e1e));&:focus{border-color:var(--_gcd-input-border-color-focus,var(--wp-admin-theme-color));box-shadow:var(--_gcd-input-box-shadow-focus,none);outline:var(--_gcd-input-outline-focus,none)}&:disabled{background:var(--_gcd-input-background-disabled,transparent);border-color:var(--_gcd-input-border-color-disabled,transparent);box-shadow:var(--_gcd-input-box-shadow-disabled,none);color:var(--_gcd-input-color-disabled,var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d))}&::placeholder{color:var(--_gcd-input-placeholder-color,var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d))}}&:is(textarea,[type=text],[type=password],[type=date],[type=datetime],[type=datetime-local],[type=email],[type=month],[type=number],[type=search],[type=tel],[type=time],[type=url],[type=week]){line-height:var(--_gcd-input-line-height,inherit);min-height:var(--_gcd-input-min-height,auto);padding:var(--_gcd-input-padding,0)}}._547d86373d02e108__textarea{box-sizing:var(--_gcd-textarea-box-sizing,border-box);overflow:var(--_gcd-textarea-overflow,auto);resize:var(--_gcd-textarea-resize,block)}._8c15fd0ed9f28ba4__div{outline:var(--_gcd-div-outline,0 solid transparent)}p._43cec3e1eec1066d__p{font-size:var(--_gcd-p-font-size,13px);line-height:var(--_gcd-p-line-height,1.5);margin:var(--_gcd-p-margin,0)}:is(h1,h2,h3,h4,h5,h6).e97669c6d9a38497__heading{color:var(--_gcd-heading-color,var(--wpds-color-foreground-content-neutral,#1e1e1e));font-size:var(--_gcd-heading-font-size,inherit);font-weight:var(--_gcd-heading-font-weight,var(--wpds-typography-font-weight-emphasis,600));margin:var(--_gcd-heading-margin,0)}._2c0831b0499dbd6e__a,._2c0831b0499dbd6e__a:is(:hover,:focus,:active){border-radius:var(--_gcd-a-border-radius,0);box-shadow:var(--_gcd-a-box-shadow,none);color:var(--_gcd-a-color,inherit);outline:var(--_gcd-a-outline,0 solid transparent);transition:var(--_gcd-a-transition,none)}");
}
var global_css_defense_default3 = { "button": "_6defc79820e382c6__button", "input": "d2cff2e5dea83bd1__input", "textarea": "_547d86373d02e108__textarea", "div": "_8c15fd0ed9f28ba4__div", "p": "_43cec3e1eec1066d__p", "heading": "e97669c6d9a38497__heading", "a": "_2c0831b0499dbd6e__a" };
if (typeof process === "undefined" || true) {
registerStyle13("10f3806643", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._336cd3e4e743482f__box-sizing{box-sizing:border-box;*,:after,:before{box-sizing:inherit}}}}");
}
var resets_default3 = { "box-sizing": "_336cd3e4e743482f__box-sizing" };
if (typeof process === "undefined" || true) {
registerStyle13("bc14d8e61b", '@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{.cb2baafdc08746bb__input-layout{--wp-ui-input-layout-padding-inline:var(--wpds-dimension-padding-md,12px);background-color:var(--wpds-color-background-interactive-neutral-weak,#0000);border-color:var(--wpds-color-stroke-interactive-neutral,#8d8d8d);border-radius:var(--wpds-border-radius-sm,2px);border-style:solid;border-width:var(--wpds-border-width-xs,1px);color:var(--wpds-color-foreground-interactive-neutral,#1e1e1e);display:flex;font-family:var(--wpds-typography-font-family-body,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-size:max(var(--wpds-typography-font-size-md,13px),16px);height:var(--wpds-dimension-size-lg,40px);line-height:1;@media (min-width:600px){font-size:var(--wpds-typography-font-size-md,13px)}&._0c807a84cbb94e0c__is-size-compact{height:var(--wpds-dimension-size-md,32px)}&._0c807a84cbb94e0c__is-size-compact,&.ed67cda122dc1e7b__is-size-small{--wp-ui-input-layout-padding-inline:var(--wpds-dimension-padding-sm,8px)}&.ed67cda122dc1e7b__is-size-small{height:var(--wpds-dimension-size-sm,24px)}&._6fb7104732387680__is-disabled,&:has([data-can-disable-input-layout][data-disabled]){background-color:var(--wpds-color-background-interactive-neutral-weak-disabled,#0000);border-color:var(--wpds-color-stroke-interactive-neutral-disabled,#dbdbdb);color:var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d);@media (forced-colors:active){border-bottom-color:GrayText;border-left-color:GrayText;border-right-color:GrayText;border-top-color:GrayText;color:GrayText}}&._8097270636ca6100__is-borderless{border-color:transparent}&:has(._0d7afad74a057888__input-layout-slot:focus-within){outline:none}&:hover:not(._6fb7104732387680__is-disabled,:has([data-can-disable-input-layout][data-disabled]),._8097270636ca6100__is-borderless){border-color:var(--wpds-color-stroke-interactive-neutral-active,#6e6e6e)}}.c192b41a12b4387b__slot-wrapper{display:contents}._0d7afad74a057888__input-layout-slot{align-items:center;display:flex;&._0c952682762ca288__is-padding-minimal{--wp-ui-input-layout-prefix-padding-start:calc(var(--wp-ui-input-layout-padding-inline) - var(--wpds-dimension-padding-xs, 4px));--wp-ui-input-layout-suffix-padding-end:calc(var(--wp-ui-input-layout-padding-inline) - var(--wpds-dimension-padding-xs, 4px))}[data-slot-type=prefix] &{padding-inline-start:var(--wp-ui-input-layout-prefix-padding-start,var(--wp-ui-input-layout-padding-inline))}[data-slot-type=suffix] &{padding-inline-end:var(--wp-ui-input-layout-suffix-padding-end,var(--wp-ui-input-layout-padding-inline))}}}}');
}
var style_default12 = { "input-layout": "cb2baafdc08746bb__input-layout", "is-size-compact": "_0c807a84cbb94e0c__is-size-compact", "is-size-small": "ed67cda122dc1e7b__is-size-small", "is-disabled": "_6fb7104732387680__is-disabled", "is-borderless": "_8097270636ca6100__is-borderless", "input-layout-slot": "_0d7afad74a057888__input-layout-slot", "slot-wrapper": "c192b41a12b4387b__slot-wrapper", "is-padding-minimal": "_0c952682762ca288__is-padding-minimal" };
var InputLayout = (0, import_element67.forwardRef)(
function InputLayout2({
className,
children,
visuallyDisabled,
size: size4 = "default",
isBorderless,
prefix: prefix2,
suffix,
...restProps
}, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime198.jsxs)(
"div",
{
ref,
className: clsx_default(
global_css_defense_default3.div,
resets_default3["box-sizing"],
style_default12["input-layout"],
style_default12[`is-size-${size4}`],
visuallyDisabled && style_default12["is-disabled"],
isBorderless && style_default12["is-borderless"],
className
),
...restProps,
children: [
import_element67.Children.count(prefix2) > 0 && /* @__PURE__ */ (0, import_jsx_runtime198.jsx)(
"div",
{
className: style_default12["slot-wrapper"],
"data-slot-type": "prefix",
children: prefix2
}
),
children,
import_element67.Children.count(suffix) > 0 && /* @__PURE__ */ (0, import_jsx_runtime198.jsx)(
"div",
{
className: style_default12["slot-wrapper"],
"data-slot-type": "suffix",
children: suffix
}
)
]
}
);
}
);
// packages/ui/build-module/form/primitives/input-layout/slot.mjs
var import_element68 = __toESM(require_element(), 1);
var import_jsx_runtime199 = __toESM(require_jsx_runtime(), 1);
var STYLE_HASH_ATTRIBUTE14 = "data-wp-hash";
function getRuntime14() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) {
return globalScope.__wpStyleRuntime;
}
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") {
registerDocument14(document);
}
return globalScope.__wpStyleRuntime;
}
function documentContainsStyleHash14(targetDocument, hash) {
if (!targetDocument.head) {
return false;
}
for (const style of targetDocument.head.querySelectorAll(
`style[${STYLE_HASH_ATTRIBUTE14}]`
)) {
if (style.getAttribute(STYLE_HASH_ATTRIBUTE14) === hash) {
return true;
}
}
return false;
}
function injectStyle14(targetDocument, hash, css) {
if (!targetDocument.head) {
return;
}
const runtime = getRuntime14();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) {
return;
}
if (documentContainsStyleHash14(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE14, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
function registerDocument14(targetDocument) {
const runtime = getRuntime14();
runtime.documents.set(
targetDocument,
(runtime.documents.get(targetDocument) ?? 0) + 1
);
for (const [hash, css] of runtime.styles) {
injectStyle14(targetDocument, hash, css);
}
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) {
return;
}
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
function registerStyle14(hash, css) {
const runtime = getRuntime14();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) {
injectStyle14(targetDocument, hash, css);
}
}
if (typeof process === "undefined" || true) {
registerStyle14("bc14d8e61b", '@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{.cb2baafdc08746bb__input-layout{--wp-ui-input-layout-padding-inline:var(--wpds-dimension-padding-md,12px);background-color:var(--wpds-color-background-interactive-neutral-weak,#0000);border-color:var(--wpds-color-stroke-interactive-neutral,#8d8d8d);border-radius:var(--wpds-border-radius-sm,2px);border-style:solid;border-width:var(--wpds-border-width-xs,1px);color:var(--wpds-color-foreground-interactive-neutral,#1e1e1e);display:flex;font-family:var(--wpds-typography-font-family-body,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-size:max(var(--wpds-typography-font-size-md,13px),16px);height:var(--wpds-dimension-size-lg,40px);line-height:1;@media (min-width:600px){font-size:var(--wpds-typography-font-size-md,13px)}&._0c807a84cbb94e0c__is-size-compact{height:var(--wpds-dimension-size-md,32px)}&._0c807a84cbb94e0c__is-size-compact,&.ed67cda122dc1e7b__is-size-small{--wp-ui-input-layout-padding-inline:var(--wpds-dimension-padding-sm,8px)}&.ed67cda122dc1e7b__is-size-small{height:var(--wpds-dimension-size-sm,24px)}&._6fb7104732387680__is-disabled,&:has([data-can-disable-input-layout][data-disabled]){background-color:var(--wpds-color-background-interactive-neutral-weak-disabled,#0000);border-color:var(--wpds-color-stroke-interactive-neutral-disabled,#dbdbdb);color:var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d);@media (forced-colors:active){border-bottom-color:GrayText;border-left-color:GrayText;border-right-color:GrayText;border-top-color:GrayText;color:GrayText}}&._8097270636ca6100__is-borderless{border-color:transparent}&:has(._0d7afad74a057888__input-layout-slot:focus-within){outline:none}&:hover:not(._6fb7104732387680__is-disabled,:has([data-can-disable-input-layout][data-disabled]),._8097270636ca6100__is-borderless){border-color:var(--wpds-color-stroke-interactive-neutral-active,#6e6e6e)}}.c192b41a12b4387b__slot-wrapper{display:contents}._0d7afad74a057888__input-layout-slot{align-items:center;display:flex;&._0c952682762ca288__is-padding-minimal{--wp-ui-input-layout-prefix-padding-start:calc(var(--wp-ui-input-layout-padding-inline) - var(--wpds-dimension-padding-xs, 4px));--wp-ui-input-layout-suffix-padding-end:calc(var(--wp-ui-input-layout-padding-inline) - var(--wpds-dimension-padding-xs, 4px))}[data-slot-type=prefix] &{padding-inline-start:var(--wp-ui-input-layout-prefix-padding-start,var(--wp-ui-input-layout-padding-inline))}[data-slot-type=suffix] &{padding-inline-end:var(--wp-ui-input-layout-suffix-padding-end,var(--wp-ui-input-layout-padding-inline))}}}}');
}
var style_default13 = { "input-layout": "cb2baafdc08746bb__input-layout", "is-size-compact": "_0c807a84cbb94e0c__is-size-compact", "is-size-small": "ed67cda122dc1e7b__is-size-small", "is-disabled": "_6fb7104732387680__is-disabled", "is-borderless": "_8097270636ca6100__is-borderless", "input-layout-slot": "_0d7afad74a057888__input-layout-slot", "slot-wrapper": "c192b41a12b4387b__slot-wrapper", "is-padding-minimal": "_0c952682762ca288__is-padding-minimal" };
var InputLayoutSlot = (0, import_element68.forwardRef)(function InputLayoutSlot2({ padding = "default", className, ...restProps }, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime199.jsx)(
"div",
{
ref,
className: clsx_default(
style_default13["input-layout-slot"],
style_default13[`is-padding-${padding}`],
className
),
...restProps
}
);
});
InputLayoutSlot.displayName = "InputLayout.Slot";
// packages/ui/build-module/form/primitives/input-layout/index.mjs
var InputLayout3 = Object.assign(InputLayout, {
Slot: InputLayoutSlot
});
// packages/ui/build-module/form/primitives/constants.mjs
var ITEM_POPUP_POSITIONER_PROPS = {
align: "start",
sideOffset: 8,
collisionPadding: 12
};
// packages/ui/build-module/form/primitives/field/index.mjs
var field_exports = {};
__export(field_exports, {
Control: () => Control,
Description: () => Description,
Details: () => Details,
Item: () => Item2,
Label: () => Label,
Root: () => Root5
});
// packages/ui/build-module/form/primitives/field/root.mjs
var import_element69 = __toESM(require_element(), 1);
var import_jsx_runtime200 = __toESM(require_jsx_runtime(), 1);
var STYLE_HASH_ATTRIBUTE15 = "data-wp-hash";
function getRuntime15() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) {
return globalScope.__wpStyleRuntime;
}
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") {
registerDocument15(document);
}
return globalScope.__wpStyleRuntime;
}
function documentContainsStyleHash15(targetDocument, hash) {
if (!targetDocument.head) {
return false;
}
for (const style of targetDocument.head.querySelectorAll(
`style[${STYLE_HASH_ATTRIBUTE15}]`
)) {
if (style.getAttribute(STYLE_HASH_ATTRIBUTE15) === hash) {
return true;
}
}
return false;
}
function injectStyle15(targetDocument, hash, css) {
if (!targetDocument.head) {
return;
}
const runtime = getRuntime15();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) {
return;
}
if (documentContainsStyleHash15(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE15, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
function registerDocument15(targetDocument) {
const runtime = getRuntime15();
runtime.documents.set(
targetDocument,
(runtime.documents.get(targetDocument) ?? 0) + 1
);
for (const [hash, css] of runtime.styles) {
injectStyle15(targetDocument, hash, css);
}
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) {
return;
}
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
function registerStyle15(hash, css) {
const runtime = getRuntime15();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) {
injectStyle15(targetDocument, hash, css);
}
}
if (typeof process === "undefined" || true) {
registerStyle15("10f3806643", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._336cd3e4e743482f__box-sizing{box-sizing:border-box;*,:after,:before{box-sizing:inherit}}}}");
}
var resets_default4 = { "box-sizing": "_336cd3e4e743482f__box-sizing" };
var DEFAULT_RENDER = (props) => /* @__PURE__ */ (0, import_jsx_runtime200.jsx)(Stack, { ...props, direction: "column", gap: "sm" });
var Root5 = (0, import_element69.forwardRef)(function Root22({ className, render: render4 = DEFAULT_RENDER, ...restProps }, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime200.jsx)(
index_parts_exports2.Root,
{
ref,
className: clsx_default(resets_default4["box-sizing"], className),
render: render4,
...restProps
}
);
});
// packages/ui/build-module/form/primitives/field/item.mjs
var import_element70 = __toESM(require_element(), 1);
var import_jsx_runtime201 = __toESM(require_jsx_runtime(), 1);
var Item2 = (0, import_element70.forwardRef)(function Item22(props, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime201.jsx)(index_parts_exports2.Item, { ref, ...props });
});
// packages/ui/build-module/form/primitives/field/label.mjs
var import_element72 = __toESM(require_element(), 1);
// packages/ui/build-module/visually-hidden/visually-hidden.mjs
var import_element71 = __toESM(require_element(), 1);
var STYLE_HASH_ATTRIBUTE16 = "data-wp-hash";
function getRuntime16() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) {
return globalScope.__wpStyleRuntime;
}
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") {
registerDocument16(document);
}
return globalScope.__wpStyleRuntime;
}
function documentContainsStyleHash16(targetDocument, hash) {
if (!targetDocument.head) {
return false;
}
for (const style of targetDocument.head.querySelectorAll(
`style[${STYLE_HASH_ATTRIBUTE16}]`
)) {
if (style.getAttribute(STYLE_HASH_ATTRIBUTE16) === hash) {
return true;
}
}
return false;
}
function injectStyle16(targetDocument, hash, css) {
if (!targetDocument.head) {
return;
}
const runtime = getRuntime16();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) {
return;
}
if (documentContainsStyleHash16(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE16, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
function registerDocument16(targetDocument) {
const runtime = getRuntime16();
runtime.documents.set(
targetDocument,
(runtime.documents.get(targetDocument) ?? 0) + 1
);
for (const [hash, css] of runtime.styles) {
injectStyle16(targetDocument, hash, css);
}
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) {
return;
}
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
function registerStyle16(hash, css) {
const runtime = getRuntime16();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) {
injectStyle16(targetDocument, hash, css);
}
}
if (typeof process === "undefined" || true) {
registerStyle16("fa606a57ae", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{.f37b9e2e191ebd66__visually-hidden{word-wrap:normal;border:0;clip-path:inset(50%);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;word-break:normal}}}");
}
var style_default14 = { "visually-hidden": "f37b9e2e191ebd66__visually-hidden" };
var VisuallyHidden = (0, import_element71.forwardRef)(
function VisuallyHidden2({ render: render4, ...restProps }, ref) {
const element = useRender({
render: render4,
ref,
props: mergeProps(
{ className: style_default14["visually-hidden"] },
restProps,
{
// @ts-expect-error Arbitrary data-* attributes aren't indexable on the typed div props. Kept hardcoded so consumers can't change or remove it.
"data-visually-hidden": ""
}
)
});
return element;
}
);
// packages/ui/build-module/form/primitives/field/label.mjs
var import_jsx_runtime202 = __toESM(require_jsx_runtime(), 1);
var STYLE_HASH_ATTRIBUTE17 = "data-wp-hash";
function getRuntime17() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) {
return globalScope.__wpStyleRuntime;
}
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") {
registerDocument17(document);
}
return globalScope.__wpStyleRuntime;
}
function documentContainsStyleHash17(targetDocument, hash) {
if (!targetDocument.head) {
return false;
}
for (const style of targetDocument.head.querySelectorAll(
`style[${STYLE_HASH_ATTRIBUTE17}]`
)) {
if (style.getAttribute(STYLE_HASH_ATTRIBUTE17) === hash) {
return true;
}
}
return false;
}
function injectStyle17(targetDocument, hash, css) {
if (!targetDocument.head) {
return;
}
const runtime = getRuntime17();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) {
return;
}
if (documentContainsStyleHash17(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE17, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
function registerDocument17(targetDocument) {
const runtime = getRuntime17();
runtime.documents.set(
targetDocument,
(runtime.documents.get(targetDocument) ?? 0) + 1
);
for (const [hash, css] of runtime.styles) {
injectStyle17(targetDocument, hash, css);
}
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) {
return;
}
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
function registerStyle17(hash, css) {
const runtime = getRuntime17();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) {
injectStyle17(targetDocument, hash, css);
}
}
if (typeof process === "undefined" || true) {
registerStyle17("e08ffbfdae", '@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._2d5ad850b2f90964__label{--wp-ui-field-label-line-height:var(--wpds-typography-line-height-xs,16px);color:var(--wpds-color-foreground-content-neutral,#1e1e1e);font-family:var(--wpds-typography-font-family-body,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-size:var(--wpds-typography-font-size-xs,11px);font-weight:var(--wpds-typography-font-weight-emphasis,600);line-height:var(--wp-ui-field-label-line-height);text-transform:uppercase;&._17c4214649230bea__is-plain{font-size:var(--wpds-typography-font-size-md,13px);text-transform:none}}._08a3750500e0233f__description{--_gcd-p-font-size:var(--wpds-typography-font-size-sm,12px);--_gcd-p-line-height:var(--wpds-typography-line-height-xs,16px);--_gcd-p-margin:0;text-wrap:pretty;color:var(--wpds-color-foreground-content-neutral-weak,#707070);font-family:var(--wpds-typography-font-family-body,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-size:var(--wpds-typography-font-size-sm,12px);line-height:var(--wpds-typography-line-height-xs,16px)}}}');
}
var field_default = { "label": "_2d5ad850b2f90964__label", "is-plain": "_17c4214649230bea__is-plain", "description": "_08a3750500e0233f__description" };
var Label = (0, import_element72.forwardRef)(
function Label2({ className, hideFromVision, variant, ...restProps }, ref) {
const label = /* @__PURE__ */ (0, import_jsx_runtime202.jsx)(
index_parts_exports2.Label,
{
ref,
className: clsx_default(
field_default.label,
variant && field_default[`is-${variant}`],
className
),
...restProps
}
);
if (hideFromVision) {
return /* @__PURE__ */ (0, import_jsx_runtime202.jsx)(VisuallyHidden, { render: label });
}
return label;
}
);
// packages/ui/build-module/form/primitives/field/description.mjs
var import_element73 = __toESM(require_element(), 1);
var import_jsx_runtime203 = __toESM(require_jsx_runtime(), 1);
var STYLE_HASH_ATTRIBUTE18 = "data-wp-hash";
function getRuntime18() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) {
return globalScope.__wpStyleRuntime;
}
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") {
registerDocument18(document);
}
return globalScope.__wpStyleRuntime;
}
function documentContainsStyleHash18(targetDocument, hash) {
if (!targetDocument.head) {
return false;
}
for (const style of targetDocument.head.querySelectorAll(
`style[${STYLE_HASH_ATTRIBUTE18}]`
)) {
if (style.getAttribute(STYLE_HASH_ATTRIBUTE18) === hash) {
return true;
}
}
return false;
}
function injectStyle18(targetDocument, hash, css) {
if (!targetDocument.head) {
return;
}
const runtime = getRuntime18();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) {
return;
}
if (documentContainsStyleHash18(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE18, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
function registerDocument18(targetDocument) {
const runtime = getRuntime18();
runtime.documents.set(
targetDocument,
(runtime.documents.get(targetDocument) ?? 0) + 1
);
for (const [hash, css] of runtime.styles) {
injectStyle18(targetDocument, hash, css);
}
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) {
return;
}
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
function registerStyle18(hash, css) {
const runtime = getRuntime18();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) {
injectStyle18(targetDocument, hash, css);
}
}
if (typeof process === "undefined" || true) {
registerStyle18("af6d9984a6", "._6defc79820e382c6__button{box-sizing:var(--_gcd-button-box-sizing,border-box);font-family:var(--_gcd-button-font-family,inherit);font-size:var(--_gcd-button-font-size,inherit);font-weight:var(--_gcd-button-font-weight,inherit)}.d2cff2e5dea83bd1__input{box-sizing:var(--_gcd-input-box-sizing,border-box);font-family:var(--_gcd-input-font-family,inherit);font-size:var(--_gcd-input-font-size,inherit);font-weight:var(--_gcd-input-font-weight,inherit);margin:var(--_gcd-input-margin,0);&:is(textarea,[type=text],[type=password],[type=color],[type=date],[type=datetime],[type=datetime-local],[type=email],[type=month],[type=number],[type=search],[type=tel],[type=time],[type=url],[type=week]){background-color:var(--_gcd-input-background-color,transparent);border:var(--_gcd-input-border,none);border-radius:var(--_gcd-input-border-radius,0);box-shadow:var(--_gcd-input-box-shadow,0 0 0 transparent);color:var(--_gcd-input-color,var(--wpds-color-foreground-interactive-neutral,#1e1e1e));&:focus{border-color:var(--_gcd-input-border-color-focus,var(--wp-admin-theme-color));box-shadow:var(--_gcd-input-box-shadow-focus,none);outline:var(--_gcd-input-outline-focus,none)}&:disabled{background:var(--_gcd-input-background-disabled,transparent);border-color:var(--_gcd-input-border-color-disabled,transparent);box-shadow:var(--_gcd-input-box-shadow-disabled,none);color:var(--_gcd-input-color-disabled,var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d))}&::placeholder{color:var(--_gcd-input-placeholder-color,var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d))}}&:is(textarea,[type=text],[type=password],[type=date],[type=datetime],[type=datetime-local],[type=email],[type=month],[type=number],[type=search],[type=tel],[type=time],[type=url],[type=week]){line-height:var(--_gcd-input-line-height,inherit);min-height:var(--_gcd-input-min-height,auto);padding:var(--_gcd-input-padding,0)}}._547d86373d02e108__textarea{box-sizing:var(--_gcd-textarea-box-sizing,border-box);overflow:var(--_gcd-textarea-overflow,auto);resize:var(--_gcd-textarea-resize,block)}._8c15fd0ed9f28ba4__div{outline:var(--_gcd-div-outline,0 solid transparent)}p._43cec3e1eec1066d__p{font-size:var(--_gcd-p-font-size,13px);line-height:var(--_gcd-p-line-height,1.5);margin:var(--_gcd-p-margin,0)}:is(h1,h2,h3,h4,h5,h6).e97669c6d9a38497__heading{color:var(--_gcd-heading-color,var(--wpds-color-foreground-content-neutral,#1e1e1e));font-size:var(--_gcd-heading-font-size,inherit);font-weight:var(--_gcd-heading-font-weight,var(--wpds-typography-font-weight-emphasis,600));margin:var(--_gcd-heading-margin,0)}._2c0831b0499dbd6e__a,._2c0831b0499dbd6e__a:is(:hover,:focus,:active){border-radius:var(--_gcd-a-border-radius,0);box-shadow:var(--_gcd-a-box-shadow,none);color:var(--_gcd-a-color,inherit);outline:var(--_gcd-a-outline,0 solid transparent);transition:var(--_gcd-a-transition,none)}");
}
var global_css_defense_default4 = { "button": "_6defc79820e382c6__button", "input": "d2cff2e5dea83bd1__input", "textarea": "_547d86373d02e108__textarea", "div": "_8c15fd0ed9f28ba4__div", "p": "_43cec3e1eec1066d__p", "heading": "e97669c6d9a38497__heading", "a": "_2c0831b0499dbd6e__a" };
if (typeof process === "undefined" || true) {
registerStyle18("e08ffbfdae", '@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._2d5ad850b2f90964__label{--wp-ui-field-label-line-height:var(--wpds-typography-line-height-xs,16px);color:var(--wpds-color-foreground-content-neutral,#1e1e1e);font-family:var(--wpds-typography-font-family-body,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-size:var(--wpds-typography-font-size-xs,11px);font-weight:var(--wpds-typography-font-weight-emphasis,600);line-height:var(--wp-ui-field-label-line-height);text-transform:uppercase;&._17c4214649230bea__is-plain{font-size:var(--wpds-typography-font-size-md,13px);text-transform:none}}._08a3750500e0233f__description{--_gcd-p-font-size:var(--wpds-typography-font-size-sm,12px);--_gcd-p-line-height:var(--wpds-typography-line-height-xs,16px);--_gcd-p-margin:0;text-wrap:pretty;color:var(--wpds-color-foreground-content-neutral-weak,#707070);font-family:var(--wpds-typography-font-family-body,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-size:var(--wpds-typography-font-size-sm,12px);line-height:var(--wpds-typography-line-height-xs,16px)}}}');
}
var field_default2 = { "label": "_2d5ad850b2f90964__label", "is-plain": "_17c4214649230bea__is-plain", "description": "_08a3750500e0233f__description" };
var Description = (0, import_element73.forwardRef)(function Description2({ className, ...restProps }, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime203.jsx)(
index_parts_exports2.Description,
{
ref,
className: clsx_default(
global_css_defense_default4.p,
field_default2.description,
className
),
...restProps
}
);
});
// packages/ui/build-module/form/primitives/field/details.mjs
var import_element74 = __toESM(require_element(), 1);
var import_i18n32 = __toESM(require_i18n(), 1);
var import_jsx_runtime204 = __toESM(require_jsx_runtime(), 1);
var STYLE_HASH_ATTRIBUTE19 = "data-wp-hash";
function getRuntime19() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) {
return globalScope.__wpStyleRuntime;
}
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") {
registerDocument19(document);
}
return globalScope.__wpStyleRuntime;
}
function documentContainsStyleHash19(targetDocument, hash) {
if (!targetDocument.head) {
return false;
}
for (const style of targetDocument.head.querySelectorAll(
`style[${STYLE_HASH_ATTRIBUTE19}]`
)) {
if (style.getAttribute(STYLE_HASH_ATTRIBUTE19) === hash) {
return true;
}
}
return false;
}
function injectStyle19(targetDocument, hash, css) {
if (!targetDocument.head) {
return;
}
const runtime = getRuntime19();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) {
return;
}
if (documentContainsStyleHash19(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE19, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
function registerDocument19(targetDocument) {
const runtime = getRuntime19();
runtime.documents.set(
targetDocument,
(runtime.documents.get(targetDocument) ?? 0) + 1
);
for (const [hash, css] of runtime.styles) {
injectStyle19(targetDocument, hash, css);
}
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) {
return;
}
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
function registerStyle19(hash, css) {
const runtime = getRuntime19();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) {
injectStyle19(targetDocument, hash, css);
}
}
if (typeof process === "undefined" || true) {
registerStyle19("e08ffbfdae", '@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._2d5ad850b2f90964__label{--wp-ui-field-label-line-height:var(--wpds-typography-line-height-xs,16px);color:var(--wpds-color-foreground-content-neutral,#1e1e1e);font-family:var(--wpds-typography-font-family-body,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-size:var(--wpds-typography-font-size-xs,11px);font-weight:var(--wpds-typography-font-weight-emphasis,600);line-height:var(--wp-ui-field-label-line-height);text-transform:uppercase;&._17c4214649230bea__is-plain{font-size:var(--wpds-typography-font-size-md,13px);text-transform:none}}._08a3750500e0233f__description{--_gcd-p-font-size:var(--wpds-typography-font-size-sm,12px);--_gcd-p-line-height:var(--wpds-typography-line-height-xs,16px);--_gcd-p-margin:0;text-wrap:pretty;color:var(--wpds-color-foreground-content-neutral-weak,#707070);font-family:var(--wpds-typography-font-family-body,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-size:var(--wpds-typography-font-size-sm,12px);line-height:var(--wpds-typography-line-height-xs,16px)}}}');
}
var field_default3 = { "label": "_2d5ad850b2f90964__label", "is-plain": "_17c4214649230bea__is-plain", "description": "_08a3750500e0233f__description" };
var Details = (0, import_element74.forwardRef)(
function Details2({ className, ...restProps }, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime204.jsxs)(import_jsx_runtime204.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime204.jsx)(VisuallyHidden, { render: /* @__PURE__ */ (0, import_jsx_runtime204.jsx)(index_parts_exports2.Description, {}), children: (0, import_i18n32.__)("More details follow the field.") }),
/* @__PURE__ */ (0, import_jsx_runtime204.jsx)(
"div",
{
ref,
className: clsx_default(field_default3.description, className),
...restProps
}
)
] });
}
);
// packages/ui/build-module/form/primitives/field/control.mjs
var import_element75 = __toESM(require_element(), 1);
var import_jsx_runtime205 = __toESM(require_jsx_runtime(), 1);
var Control = (0, import_element75.forwardRef)(
function Control2(props, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime205.jsx)(index_parts_exports2.Control, { ref, ...props });
}
);
// packages/ui/build-module/form/primitives/select/index.mjs
var select_exports = {};
__export(select_exports, {
Item: () => Item3,
Popup: () => Popup2,
Portal: () => Portal2,
Positioner: () => Positioner2,
Root: () => Root6,
Trigger: () => Trigger3
});
// packages/ui/build-module/form/primitives/select/item.mjs
var import_element76 = __toESM(require_element(), 1);
var import_jsx_runtime206 = __toESM(require_jsx_runtime(), 1);
var STYLE_HASH_ATTRIBUTE20 = "data-wp-hash";
function getRuntime20() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) {
return globalScope.__wpStyleRuntime;
}
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") {
registerDocument20(document);
}
return globalScope.__wpStyleRuntime;
}
function documentContainsStyleHash20(targetDocument, hash) {
if (!targetDocument.head) {
return false;
}
for (const style of targetDocument.head.querySelectorAll(
`style[${STYLE_HASH_ATTRIBUTE20}]`
)) {
if (style.getAttribute(STYLE_HASH_ATTRIBUTE20) === hash) {
return true;
}
}
return false;
}
function injectStyle20(targetDocument, hash, css) {
if (!targetDocument.head) {
return;
}
const runtime = getRuntime20();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) {
return;
}
if (documentContainsStyleHash20(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE20, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
function registerDocument20(targetDocument) {
const runtime = getRuntime20();
runtime.documents.set(
targetDocument,
(runtime.documents.get(targetDocument) ?? 0) + 1
);
for (const [hash, css] of runtime.styles) {
injectStyle20(targetDocument, hash, css);
}
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) {
return;
}
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
function registerStyle20(hash, css) {
const runtime = getRuntime20();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) {
injectStyle20(targetDocument, hash, css);
}
}
if (typeof process === "undefined" || true) {
registerStyle20("5705fc490f", '@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._380b81b8f79fb10f__dropdown-motion{--wp-ui-dropdown-slide-distance:4px;--wp-ui-dropdown-slide-duration:var(--wpds-motion-duration-md,200ms);--wp-ui-dropdown-slide-easing:var(--wpds-motion-easing-expressive,cubic-bezier(0.25,0,0,1));--wp-ui-dropdown-fade-duration:var(--wpds-motion-duration-sm,100ms);--wp-ui-dropdown-fade-easing:linear;@media not (prefers-reduced-motion){transition-duration:var(--wp-ui-dropdown-slide-duration),var(--wp-ui-dropdown-fade-duration);transition-property:transform,opacity;transition-timing-function:var(--wp-ui-dropdown-slide-easing),var(--wp-ui-dropdown-fade-easing);will-change:transform,opacity}opacity:1;transform:translate(0);&[data-instant]{transition:none}&[data-ending-style],&[data-starting-style]{opacity:0}&[data-side=bottom][data-ending-style],&[data-side=bottom][data-starting-style]{transform:translateY(calc(var(--wp-ui-dropdown-slide-distance)*-1))}&[data-side=top][data-ending-style],&[data-side=top][data-starting-style]{transform:translateY(var(--wp-ui-dropdown-slide-distance))}&[data-side=left][data-ending-style],&[data-side=left][data-starting-style]{transform:translateX(var(--wp-ui-dropdown-slide-distance))}&[data-side=right][data-ending-style],&[data-side=right][data-starting-style]{transform:translateX(calc(var(--wp-ui-dropdown-slide-distance)*-1))}}}}@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._234b520016b4e56f__popup{--wp-ui-popup-padding:var(--wpds-dimension-padding-xs,4px);--_wp-ui-elevation-md:0 2px 3px rgba(0,0,0,.05),0 4px 5px rgba(0,0,0,.04),0 12px 12px rgba(0,0,0,.03),0 16px 16px rgba(0,0,0,.02);background-color:var(--wpds-color-background-surface-neutral-strong,#fff);border:var(--wpds-border-width-xs,1px) solid var(--wpds-color-stroke-surface-neutral,#dbdbdb);border-radius:var(--wpds-border-radius-md,4px);box-shadow:var(--_wp-ui-elevation-md);display:grid;grid-template-areas:"header" "main";grid-template-rows:auto minmax(0,1fr);max-height:min(var(--available-height),480px,60dvh);max-width:var(--available-width);min-width:var(--anchor-width)}.f43dc7c768d7b622__list{color:var(--wpds-color-foreground-interactive-neutral,#1e1e1e);display:grid;font-family:var(--wpds-typography-font-family-body,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-size:var(--wpds-typography-font-size-md,13px);grid-area:main;grid-template-areas:"scrollable" "footer";grid-template-rows:minmax(0,1fr) auto;line-height:var(--wpds-typography-line-height-sm,20px)}._233cd60cdb84a2ef__list-scrollable-container{grid-area:scrollable;overflow-block:auto;overscroll-behavior:contain;scroll-padding-block:var(--wp-ui-popup-padding);&:not(:empty){padding-block:var(--wp-ui-popup-padding)}}.ec4db6f0122263e7__list-footer{grid-area:footer;padding-block:var(--wp-ui-popup-padding);._233cd60cdb84a2ef__list-scrollable-container:not(:empty)+&{border-block-start:var(--wpds-border-width-xs,1px) solid var(--wpds-color-stroke-surface-neutral,#dbdbdb)}}.b3c0d7f103fb10a2__group:not(:first-child){margin-block-start:var(--wpds-dimension-gap-sm,8px)}._21b59380477c306c__group-label{align-items:center;color:var(--wpds-color-foreground-content-neutral-weak,#707070);display:flex;min-height:var(--wpds-dimension-size-md,32px);padding-inline:var(--wpds-dimension-padding-md,12px)}._684ccb7988365b4f__item{--wp-ui-popup-item-height:var(--wpds-dimension-size-lg,40px);--wp-ui-popup-item-padding-inline:var(--wpds-dimension-padding-md,12px);--wp-ui-popup-item-padding-block:var(--wpds-dimension-padding-xs,4px);align-items:center;border-radius:var(--wpds-border-radius-sm,2px);display:flex;gap:var(--wpds-dimension-gap-xs,4px);justify-content:flex-start;margin-inline:var(--wp-ui-popup-padding);min-height:var(--wp-ui-popup-item-height);padding-block:var(--wp-ui-popup-item-padding-block);padding-inline-end:var(--wp-ui-popup-item-padding-inline);padding-inline-start:calc(var(--wp-ui-popup-item-padding-inline) - var(--wpds-dimension-padding-xs, 4px));user-select:none;&:not([data-disabled]){cursor:var(--wpds-cursor-control,pointer)}&.f181b98b0d33282a__is-size-compact{--wp-ui-popup-item-height:var(--wpds-dimension-size-md,32px);--wp-ui-popup-item-padding-inline:var(--wpds-dimension-padding-sm,8px)}&._38f7faff93c61958__is-size-small{--wp-ui-popup-item-height:var(--wpds-dimension-size-sm,24px);--wp-ui-popup-item-padding-inline:var(--wpds-dimension-padding-sm,8px);--wp-ui-popup-item-padding-block:2px}&:not([data-selected]){._92fbe4765dfad5ee__item-indicator-icon{opacity:0}}&[data-highlighted]:not([aria-disabled=true]){background-color:var(--wpds-color-background-interactive-brand-weak-active,color-mix(in oklch,var(--wp-admin-theme-color,#3858e9) 12%,#fff));color:var(--wpds-color-foreground-interactive-neutral,#1e1e1e);outline:none;@media (forced-colors:active){outline:1px solid Highlight}}&[aria-disabled=true]{background-color:var(--wpds-color-background-interactive-brand-weak-disabled,#0000);color:var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d);@media (forced-colors:active){color:GrayText}}}.a3adcfd0b73ffd40__item-icon{flex-shrink:0}._06c7ff39d2f685b9__empty:not(:empty){--wp-ui-popup-empty-min-height:var(--wpds-dimension-size-lg,40px);--wp-ui-popup-empty-padding-inline:var(--wpds-dimension-padding-md,12px);align-items:center;color:var(--wpds-color-foreground-content-neutral-weak,#707070);display:flex;font-family:var(--wpds-typography-font-family-body,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-size:var(--wpds-typography-font-size-md,13px);grid-area:main;line-height:var(--wpds-typography-line-height-sm,20px);min-height:var(--wp-ui-popup-empty-min-height);padding-inline:var(--wp-ui-popup-empty-padding-inline)}}}');
}
var item_popup_default = { "popup": "_234b520016b4e56f__popup _380b81b8f79fb10f__dropdown-motion", "list": "f43dc7c768d7b622__list", "list-scrollable-container": "_233cd60cdb84a2ef__list-scrollable-container", "list-footer": "ec4db6f0122263e7__list-footer", "group": "b3c0d7f103fb10a2__group", "group-label": "_21b59380477c306c__group-label", "item": "_684ccb7988365b4f__item", "is-size-compact": "f181b98b0d33282a__is-size-compact", "is-size-small": "_38f7faff93c61958__is-size-small", "item-indicator-icon": "_92fbe4765dfad5ee__item-indicator-icon", "item-icon": "a3adcfd0b73ffd40__item-icon", "empty": "_06c7ff39d2f685b9__empty" };
if (typeof process === "undefined" || true) {
registerStyle20("10f3806643", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._336cd3e4e743482f__box-sizing{box-sizing:border-box;*,:after,:before{box-sizing:inherit}}}}");
}
var resets_default5 = { "box-sizing": "_336cd3e4e743482f__box-sizing" };
var Item3 = (0, import_element76.forwardRef)(
function Item23({ className, value, size: size4 = "default", children, ...restProps }, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime206.jsxs)(
index_parts_exports3.Item,
{
className: clsx_default(
resets_default5["box-sizing"],
item_popup_default.item,
item_popup_default[`is-size-${size4}`],
className
),
value,
ref,
...restProps,
children: [
/* @__PURE__ */ (0, import_jsx_runtime206.jsx)(
Icon,
{
icon: check_default,
className: clsx_default(
item_popup_default["item-icon"],
item_popup_default["item-indicator-icon"]
),
size: size4 === "small" ? 20 : 24
}
),
/* @__PURE__ */ (0, import_jsx_runtime206.jsx)(index_parts_exports3.ItemText, { children })
]
}
);
}
);
// packages/ui/build-module/form/primitives/select/popup.mjs
var import_element79 = __toESM(require_element(), 1);
// packages/ui/build-module/form/primitives/select/portal.mjs
var import_element77 = __toESM(require_element(), 1);
var import_jsx_runtime207 = __toESM(require_jsx_runtime(), 1);
var Portal2 = (0, import_element77.forwardRef)(function SelectPortal3({ container, ...restProps }, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime207.jsx)(
index_parts_exports3.Portal,
{
container: container ?? getWpCompatOverlaySlot(),
...restProps,
ref
}
);
});
// packages/ui/build-module/form/primitives/select/positioner.mjs
var import_element78 = __toESM(require_element(), 1);
var import_jsx_runtime208 = __toESM(require_jsx_runtime(), 1);
var STYLE_HASH_ATTRIBUTE21 = "data-wp-hash";
function getRuntime21() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) {
return globalScope.__wpStyleRuntime;
}
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") {
registerDocument21(document);
}
return globalScope.__wpStyleRuntime;
}
function documentContainsStyleHash21(targetDocument, hash) {
if (!targetDocument.head) {
return false;
}
for (const style of targetDocument.head.querySelectorAll(
`style[${STYLE_HASH_ATTRIBUTE21}]`
)) {
if (style.getAttribute(STYLE_HASH_ATTRIBUTE21) === hash) {
return true;
}
}
return false;
}
function injectStyle21(targetDocument, hash, css) {
if (!targetDocument.head) {
return;
}
const runtime = getRuntime21();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) {
return;
}
if (documentContainsStyleHash21(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE21, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
function registerDocument21(targetDocument) {
const runtime = getRuntime21();
runtime.documents.set(
targetDocument,
(runtime.documents.get(targetDocument) ?? 0) + 1
);
for (const [hash, css] of runtime.styles) {
injectStyle21(targetDocument, hash, css);
}
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) {
return;
}
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
function registerStyle21(hash, css) {
const runtime = getRuntime21();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) {
injectStyle21(targetDocument, hash, css);
}
}
if (typeof process === "undefined" || true) {
registerStyle21("10f3806643", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._336cd3e4e743482f__box-sizing{box-sizing:border-box;*,:after,:before{box-sizing:inherit}}}}");
}
var resets_default6 = { "box-sizing": "_336cd3e4e743482f__box-sizing" };
if (typeof process === "undefined" || true) {
registerStyle21("8c70612dd7", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._0ab863136fb95530__positioner{z-index:var(--wp-ui-select-z-index,initial)}}}");
}
var style_default15 = { "positioner": "_0ab863136fb95530__positioner" };
var Positioner2 = (0, import_element78.forwardRef)(
function SelectPositioner3({ className, ...props }, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime208.jsx)(
index_parts_exports3.Positioner,
{
...ITEM_POPUP_POSITIONER_PROPS,
alignItemWithTrigger: false,
...props,
ref,
className: clsx_default(
resets_default6["box-sizing"],
style_default15.positioner,
className
)
}
);
}
);
// packages/ui/build-module/form/primitives/select/popup.mjs
var import_jsx_runtime209 = __toESM(require_jsx_runtime(), 1);
var STYLE_HASH_ATTRIBUTE22 = "data-wp-hash";
function getRuntime22() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) {
return globalScope.__wpStyleRuntime;
}
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") {
registerDocument22(document);
}
return globalScope.__wpStyleRuntime;
}
function documentContainsStyleHash22(targetDocument, hash) {
if (!targetDocument.head) {
return false;
}
for (const style of targetDocument.head.querySelectorAll(
`style[${STYLE_HASH_ATTRIBUTE22}]`
)) {
if (style.getAttribute(STYLE_HASH_ATTRIBUTE22) === hash) {
return true;
}
}
return false;
}
function injectStyle22(targetDocument, hash, css) {
if (!targetDocument.head) {
return;
}
const runtime = getRuntime22();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) {
return;
}
if (documentContainsStyleHash22(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE22, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
function registerDocument22(targetDocument) {
const runtime = getRuntime22();
runtime.documents.set(
targetDocument,
(runtime.documents.get(targetDocument) ?? 0) + 1
);
for (const [hash, css] of runtime.styles) {
injectStyle22(targetDocument, hash, css);
}
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) {
return;
}
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
function registerStyle22(hash, css) {
const runtime = getRuntime22();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) {
injectStyle22(targetDocument, hash, css);
}
}
if (typeof process === "undefined" || true) {
registerStyle22("5705fc490f", '@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._380b81b8f79fb10f__dropdown-motion{--wp-ui-dropdown-slide-distance:4px;--wp-ui-dropdown-slide-duration:var(--wpds-motion-duration-md,200ms);--wp-ui-dropdown-slide-easing:var(--wpds-motion-easing-expressive,cubic-bezier(0.25,0,0,1));--wp-ui-dropdown-fade-duration:var(--wpds-motion-duration-sm,100ms);--wp-ui-dropdown-fade-easing:linear;@media not (prefers-reduced-motion){transition-duration:var(--wp-ui-dropdown-slide-duration),var(--wp-ui-dropdown-fade-duration);transition-property:transform,opacity;transition-timing-function:var(--wp-ui-dropdown-slide-easing),var(--wp-ui-dropdown-fade-easing);will-change:transform,opacity}opacity:1;transform:translate(0);&[data-instant]{transition:none}&[data-ending-style],&[data-starting-style]{opacity:0}&[data-side=bottom][data-ending-style],&[data-side=bottom][data-starting-style]{transform:translateY(calc(var(--wp-ui-dropdown-slide-distance)*-1))}&[data-side=top][data-ending-style],&[data-side=top][data-starting-style]{transform:translateY(var(--wp-ui-dropdown-slide-distance))}&[data-side=left][data-ending-style],&[data-side=left][data-starting-style]{transform:translateX(var(--wp-ui-dropdown-slide-distance))}&[data-side=right][data-ending-style],&[data-side=right][data-starting-style]{transform:translateX(calc(var(--wp-ui-dropdown-slide-distance)*-1))}}}}@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._234b520016b4e56f__popup{--wp-ui-popup-padding:var(--wpds-dimension-padding-xs,4px);--_wp-ui-elevation-md:0 2px 3px rgba(0,0,0,.05),0 4px 5px rgba(0,0,0,.04),0 12px 12px rgba(0,0,0,.03),0 16px 16px rgba(0,0,0,.02);background-color:var(--wpds-color-background-surface-neutral-strong,#fff);border:var(--wpds-border-width-xs,1px) solid var(--wpds-color-stroke-surface-neutral,#dbdbdb);border-radius:var(--wpds-border-radius-md,4px);box-shadow:var(--_wp-ui-elevation-md);display:grid;grid-template-areas:"header" "main";grid-template-rows:auto minmax(0,1fr);max-height:min(var(--available-height),480px,60dvh);max-width:var(--available-width);min-width:var(--anchor-width)}.f43dc7c768d7b622__list{color:var(--wpds-color-foreground-interactive-neutral,#1e1e1e);display:grid;font-family:var(--wpds-typography-font-family-body,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-size:var(--wpds-typography-font-size-md,13px);grid-area:main;grid-template-areas:"scrollable" "footer";grid-template-rows:minmax(0,1fr) auto;line-height:var(--wpds-typography-line-height-sm,20px)}._233cd60cdb84a2ef__list-scrollable-container{grid-area:scrollable;overflow-block:auto;overscroll-behavior:contain;scroll-padding-block:var(--wp-ui-popup-padding);&:not(:empty){padding-block:var(--wp-ui-popup-padding)}}.ec4db6f0122263e7__list-footer{grid-area:footer;padding-block:var(--wp-ui-popup-padding);._233cd60cdb84a2ef__list-scrollable-container:not(:empty)+&{border-block-start:var(--wpds-border-width-xs,1px) solid var(--wpds-color-stroke-surface-neutral,#dbdbdb)}}.b3c0d7f103fb10a2__group:not(:first-child){margin-block-start:var(--wpds-dimension-gap-sm,8px)}._21b59380477c306c__group-label{align-items:center;color:var(--wpds-color-foreground-content-neutral-weak,#707070);display:flex;min-height:var(--wpds-dimension-size-md,32px);padding-inline:var(--wpds-dimension-padding-md,12px)}._684ccb7988365b4f__item{--wp-ui-popup-item-height:var(--wpds-dimension-size-lg,40px);--wp-ui-popup-item-padding-inline:var(--wpds-dimension-padding-md,12px);--wp-ui-popup-item-padding-block:var(--wpds-dimension-padding-xs,4px);align-items:center;border-radius:var(--wpds-border-radius-sm,2px);display:flex;gap:var(--wpds-dimension-gap-xs,4px);justify-content:flex-start;margin-inline:var(--wp-ui-popup-padding);min-height:var(--wp-ui-popup-item-height);padding-block:var(--wp-ui-popup-item-padding-block);padding-inline-end:var(--wp-ui-popup-item-padding-inline);padding-inline-start:calc(var(--wp-ui-popup-item-padding-inline) - var(--wpds-dimension-padding-xs, 4px));user-select:none;&:not([data-disabled]){cursor:var(--wpds-cursor-control,pointer)}&.f181b98b0d33282a__is-size-compact{--wp-ui-popup-item-height:var(--wpds-dimension-size-md,32px);--wp-ui-popup-item-padding-inline:var(--wpds-dimension-padding-sm,8px)}&._38f7faff93c61958__is-size-small{--wp-ui-popup-item-height:var(--wpds-dimension-size-sm,24px);--wp-ui-popup-item-padding-inline:var(--wpds-dimension-padding-sm,8px);--wp-ui-popup-item-padding-block:2px}&:not([data-selected]){._92fbe4765dfad5ee__item-indicator-icon{opacity:0}}&[data-highlighted]:not([aria-disabled=true]){background-color:var(--wpds-color-background-interactive-brand-weak-active,color-mix(in oklch,var(--wp-admin-theme-color,#3858e9) 12%,#fff));color:var(--wpds-color-foreground-interactive-neutral,#1e1e1e);outline:none;@media (forced-colors:active){outline:1px solid Highlight}}&[aria-disabled=true]{background-color:var(--wpds-color-background-interactive-brand-weak-disabled,#0000);color:var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d);@media (forced-colors:active){color:GrayText}}}.a3adcfd0b73ffd40__item-icon{flex-shrink:0}._06c7ff39d2f685b9__empty:not(:empty){--wp-ui-popup-empty-min-height:var(--wpds-dimension-size-lg,40px);--wp-ui-popup-empty-padding-inline:var(--wpds-dimension-padding-md,12px);align-items:center;color:var(--wpds-color-foreground-content-neutral-weak,#707070);display:flex;font-family:var(--wpds-typography-font-family-body,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-size:var(--wpds-typography-font-size-md,13px);grid-area:main;line-height:var(--wpds-typography-line-height-sm,20px);min-height:var(--wp-ui-popup-empty-min-height);padding-inline:var(--wp-ui-popup-empty-padding-inline)}}}');
}
var item_popup_default2 = { "popup": "_234b520016b4e56f__popup _380b81b8f79fb10f__dropdown-motion", "list": "f43dc7c768d7b622__list", "list-scrollable-container": "_233cd60cdb84a2ef__list-scrollable-container", "list-footer": "ec4db6f0122263e7__list-footer", "group": "b3c0d7f103fb10a2__group", "group-label": "_21b59380477c306c__group-label", "item": "_684ccb7988365b4f__item", "is-size-compact": "f181b98b0d33282a__is-size-compact", "is-size-small": "_38f7faff93c61958__is-size-small", "item-indicator-icon": "_92fbe4765dfad5ee__item-indicator-icon", "item-icon": "a3adcfd0b73ffd40__item-icon", "empty": "_06c7ff39d2f685b9__empty" };
var Popup2 = (0, import_element79.forwardRef)(
function Popup22({ className, portal, positioner, children, ...restProps }, ref) {
const popupContent = /* @__PURE__ */ (0, import_jsx_runtime209.jsx)(ThemeProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime209.jsx)(
index_parts_exports3.Popup,
{
ref,
className: clsx_default(item_popup_default2.popup, className),
...restProps,
children: /* @__PURE__ */ (0, import_jsx_runtime209.jsx)(index_parts_exports3.List, { className: item_popup_default2.list, children: /* @__PURE__ */ (0, import_jsx_runtime209.jsx)(
"div",
{
className: item_popup_default2["list-scrollable-container"],
children
}
) })
}
) });
const positionedPopup = renderSlotWithChildren(
positioner,
/* @__PURE__ */ (0, import_jsx_runtime209.jsx)(Positioner2, {}),
popupContent
);
return renderSlotWithChildren(portal, /* @__PURE__ */ (0, import_jsx_runtime209.jsx)(Portal2, {}), positionedPopup);
}
);
// packages/ui/build-module/form/primitives/select/root.mjs
var import_jsx_runtime210 = __toESM(require_jsx_runtime(), 1);
function Root6(props) {
return /* @__PURE__ */ (0, import_jsx_runtime210.jsx)(index_parts_exports3.Root, { ...props });
}
// packages/ui/build-module/form/primitives/select/trigger.mjs
var import_element80 = __toESM(require_element(), 1);
var import_i18n33 = __toESM(require_i18n(), 1);
var import_jsx_runtime211 = __toESM(require_jsx_runtime(), 1);
var STYLE_HASH_ATTRIBUTE23 = "data-wp-hash";
function getRuntime23() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) {
return globalScope.__wpStyleRuntime;
}
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") {
registerDocument23(document);
}
return globalScope.__wpStyleRuntime;
}
function documentContainsStyleHash23(targetDocument, hash) {
if (!targetDocument.head) {
return false;
}
for (const style of targetDocument.head.querySelectorAll(
`style[${STYLE_HASH_ATTRIBUTE23}]`
)) {
if (style.getAttribute(STYLE_HASH_ATTRIBUTE23) === hash) {
return true;
}
}
return false;
}
function injectStyle23(targetDocument, hash, css) {
if (!targetDocument.head) {
return;
}
const runtime = getRuntime23();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) {
return;
}
if (documentContainsStyleHash23(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE23, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
function registerDocument23(targetDocument) {
const runtime = getRuntime23();
runtime.documents.set(
targetDocument,
(runtime.documents.get(targetDocument) ?? 0) + 1
);
for (const [hash, css] of runtime.styles) {
injectStyle23(targetDocument, hash, css);
}
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) {
return;
}
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
function registerStyle23(hash, css) {
const runtime = getRuntime23();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) {
injectStyle23(targetDocument, hash, css);
}
}
if (typeof process === "undefined" || true) {
registerStyle23("5f8e7aa0bc", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._08e8a2e44959f892__outset-ring--focus:focus,._970d04df7376df67__outset-ring--focus-within-except-active:focus-within:not(:has(:active)),.c5cb3ee4bddaa8e4__outset-ring--focus-within-visible:focus-within:has(:focus-visible),.cd83dfc2126a0846__outset-ring--focus-within:focus-within,.d0541bc9dd9dc7b6__outset-ring--focus-visible:focus-visible,.e25b2bdd7aa21721__outset-ring--focus-except-active:focus:not(:active),:focus-visible .ecadb9e080e2dfa5__outset-ring--focus-parent-visible{--_gcd-a-outline:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px)) solid var(--wpds-color-stroke-focus,var(--wp-admin-theme-color,#3858e9));--_gcd-div-outline:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px)) solid var(--wpds-color-stroke-focus,var(--wp-admin-theme-color,#3858e9));outline:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px)) solid var(--wpds-color-stroke-focus,var(--wp-admin-theme-color,#3858e9));outline-offset:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px))}}}");
}
var focus_default2 = { "outset-ring--focus": "_08e8a2e44959f892__outset-ring--focus", "outset-ring--focus-except-active": "e25b2bdd7aa21721__outset-ring--focus-except-active", "outset-ring--focus-visible": "d0541bc9dd9dc7b6__outset-ring--focus-visible", "outset-ring--focus-within": "cd83dfc2126a0846__outset-ring--focus-within", "outset-ring--focus-within-except-active": "_970d04df7376df67__outset-ring--focus-within-except-active", "outset-ring--focus-within-visible": "c5cb3ee4bddaa8e4__outset-ring--focus-within-visible", "outset-ring--focus-parent-visible": "ecadb9e080e2dfa5__outset-ring--focus-parent-visible" };
if (typeof process === "undefined" || true) {
registerStyle23("7b4a0ac519", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._6e4e0445ef20426b__trigger-wrapper{&.fa98c865fb77e675__is-minimal{width:fit-content}}._7893295e3f6d1af7__trigger{align-items:center;background-color:transparent;border:none;color:var(--wpds-color-foreground-interactive-neutral,#1e1e1e);display:flex;font-family:inherit;font-size:inherit;gap:var(--wpds-dimension-gap-xs,4px);justify-content:space-between;line-height:1.4;padding-block:4px;padding-inline-end:calc(var(--wp-ui-input-layout-padding-inline) - 4px);padding-inline-start:var(--wp-ui-input-layout-padding-inline);text-align:start;user-select:none;width:100%;&:not([data-disabled]){cursor:var(--wpds-cursor-control,pointer)}&.fa98c865fb77e675__is-minimal{width:auto}&:focus{outline:none}&[data-disabled]{background-color:var(--wpds-color-background-interactive-neutral-weak-disabled,#0000);color:var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d)}}.e760c9339965ce84__trigger-value{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;._7893295e3f6d1af7__trigger[data-placeholder] &{color:var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d)}}._308bc63e43681f99__trigger-caret{flex:0 0 auto}}}");
}
var select_trigger_default = { "trigger-wrapper": "_6e4e0445ef20426b__trigger-wrapper", "is-minimal": "fa98c865fb77e675__is-minimal", "trigger": "_7893295e3f6d1af7__trigger", "trigger-value": "e760c9339965ce84__trigger-value", "trigger-caret": "_308bc63e43681f99__trigger-caret" };
var Trigger3 = (0, import_element80.forwardRef)(
function Trigger22({
className,
size: size4,
variant,
children,
placeholder = (0, import_i18n33.__)("Select"),
...restProps
}, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime211.jsx)(
InputLayout3,
{
className: clsx_default(
focus_default2["outset-ring--focus-within-except-active"],
select_trigger_default["trigger-wrapper"],
variant === "minimal" && select_trigger_default["is-minimal"],
className
),
size: size4,
isBorderless: variant === "minimal",
children: /* @__PURE__ */ (0, import_jsx_runtime211.jsxs)(
index_parts_exports3.Trigger,
{
...restProps,
className: clsx_default(
select_trigger_default.trigger,
variant === "minimal" && select_trigger_default["is-minimal"]
),
"data-can-disable-input-layout": true,
ref,
children: [
/* @__PURE__ */ (0, import_jsx_runtime211.jsx)(
index_parts_exports3.Value,
{
placeholder,
className: select_trigger_default["trigger-value"],
children
}
),
/* @__PURE__ */ (0, import_jsx_runtime211.jsx)(
Icon,
{
className: select_trigger_default["trigger-caret"],
icon: chevron_down_default,
size: 18
}
)
]
}
)
}
);
}
);
// packages/ui/build-module/form/select-control/select-control.mjs
var import_element83 = __toESM(require_element(), 1);
// packages/ui/build-module/form/select-control/context.mjs
var import_element81 = __toESM(require_element(), 1);
var SelectControlSizeContext = (0, import_element81.createContext)(void 0);
var useSelectControlSizeContext = () => {
return (0, import_element81.useContext)(SelectControlSizeContext);
};
// packages/ui/build-module/form/select-control/item.mjs
var import_element82 = __toESM(require_element(), 1);
var import_jsx_runtime212 = __toESM(require_jsx_runtime(), 1);
var Item4 = (0, import_element82.forwardRef)(
function Item24({ size: sizeProp, ...restProps }, ref) {
const contextSize = useSelectControlSizeContext();
const size4 = sizeProp ?? contextSize;
return /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(select_exports.Item, { size: size4, ref, ...restProps });
}
);
// packages/ui/build-module/form/select-control/select-control.mjs
var import_jsx_runtime213 = __toESM(require_jsx_runtime(), 1);
var SelectControl = (0, import_element83.forwardRef)(function SelectControl2({
className,
children,
items,
label,
description,
details,
hideLabelFromVision,
placeholder,
size: size4 = "default",
triggerContent,
...restProps
}, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime213.jsxs)(field_exports.Root, { className, children: [
/* @__PURE__ */ (0, import_jsx_runtime213.jsx)(field_exports.Label, { hideFromVision: hideLabelFromVision, children: label }),
/* @__PURE__ */ (0, import_jsx_runtime213.jsxs)(select_exports.Root, { items, ...restProps, children: [
/* @__PURE__ */ (0, import_jsx_runtime213.jsx)(
select_exports.Trigger,
{
ref,
placeholder,
size: size4,
children: triggerContent
}
),
/* @__PURE__ */ (0, import_jsx_runtime213.jsx)(select_exports.Popup, { children: /* @__PURE__ */ (0, import_jsx_runtime213.jsx)(SelectControlSizeContext.Provider, { value: size4, children: children !== void 0 ? children : items?.map((item) => /* @__PURE__ */ (0, import_jsx_runtime213.jsx)(
Item4,
{
value: item,
label: item.label,
disabled: item.disabled,
children: item.label
},
item.value ?? "null"
)) }) })
] }),
description && /* @__PURE__ */ (0, import_jsx_runtime213.jsx)(field_exports.Description, { children: description }),
details && /* @__PURE__ */ (0, import_jsx_runtime213.jsx)(field_exports.Details, { children: details })
] });
});
// packages/ui/build-module/form/select-control/index.mjs
Item4.displayName = "SelectControl.Item";
var SelectControl3 = Object.assign(SelectControl, {
/**
* An item rendered inside a `SelectControl` popup.
*/
Item: Item4
});
// packages/block-editor/build-module/components/inserter/menu.mjs
var import_i18n62 = __toESM(require_i18n(), 1);
var import_compose46 = __toESM(require_compose(), 1);
var import_data63 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/inserter/tips.mjs
var import_i18n34 = __toESM(require_i18n(), 1);
var import_element84 = __toESM(require_element(), 1);
var import_components29 = __toESM(require_components(), 1);
var import_jsx_runtime214 = __toESM(require_jsx_runtime(), 1);
var globalTips = [
(0, import_element84.createInterpolateElement)(
(0, import_i18n34.__)(
"While writing, you can press <kbd>/</kbd> to quickly insert new blocks."
),
{ kbd: /* @__PURE__ */ (0, import_jsx_runtime214.jsx)("kbd", {}) }
),
(0, import_element84.createInterpolateElement)(
(0, import_i18n34.__)(
"Indent a list by pressing <kbd>space</kbd> at the beginning of a line."
),
{ kbd: /* @__PURE__ */ (0, import_jsx_runtime214.jsx)("kbd", {}) }
),
(0, import_element84.createInterpolateElement)(
(0, import_i18n34.__)(
"Outdent a list by pressing <kbd>backspace</kbd> at the beginning of a line."
),
{ kbd: /* @__PURE__ */ (0, import_jsx_runtime214.jsx)("kbd", {}) }
),
(0, import_i18n34.__)("Drag files into the editor to automatically insert media blocks."),
(0, import_i18n34.__)("Change a block's type by pressing the block icon on the toolbar.")
];
function Tips() {
const [randomIndex] = (0, import_element84.useState)(
() => Math.floor(Math.random() * globalTips.length)
);
return /* @__PURE__ */ (0, import_jsx_runtime214.jsx)(import_components29.Tip, { children: globalTips[randomIndex] });
}
var tips_default = Tips;
// packages/block-editor/build-module/components/inserter/preview-panel.mjs
var import_blocks31 = __toESM(require_blocks(), 1);
var import_element100 = __toESM(require_element(), 1);
var import_i18n40 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/block-card/index.mjs
var import_components30 = __toESM(require_components(), 1);
var import_data31 = __toESM(require_data(), 1);
var import_deprecated6 = __toESM(require_deprecated(), 1);
var import_i18n35 = __toESM(require_i18n(), 1);
var import_blocks25 = __toESM(require_blocks(), 1);
var import_jsx_runtime215 = __toESM(require_jsx_runtime(), 1);
var { Badge: WCBadge2 } = unlock(import_components30.privateApis);
function OptionalParentSelectButton({ children, onClick }) {
if (!onClick) {
return children;
}
return /* @__PURE__ */ (0, import_jsx_runtime215.jsx)(
import_components30.Button,
{
__next40pxDefaultSize: true,
className: "block-editor-block-card__parent-select-button",
onClick,
children
}
);
}
function BlockCard({
title,
icon,
description,
blockType,
className,
name,
allowParentNavigation,
parentClientId,
isChild,
children,
clientId,
controls
}) {
if (blockType) {
(0, import_deprecated6.default)("`blockType` property in `BlockCard component`", {
since: "5.7",
alternative: "`title, icon and description` properties"
});
({ title, icon, description } = blockType);
}
const { parentBlockClientId, parentBlockName } = (0, import_data31.useSelect)(
(select3) => {
if (parentClientId || isChild || !allowParentNavigation) {
return {};
}
const { getBlockParents: getBlockParents2, getBlockName: getBlockName2, shouldRenderBlockListView: shouldRenderBlockListView2 } = unlock(select3(store));
const parents = getBlockParents2(clientId, false);
const foundParentId = parents.find(
(parentId) => shouldRenderBlockListView2(parentId)
);
return {
parentBlockClientId: foundParentId,
parentBlockName: foundParentId ? getBlockName2(foundParentId) : null
};
},
[clientId, allowParentNavigation, isChild, parentClientId]
);
const { selectBlock: selectBlock2 } = (0, import_data31.useDispatch)(store);
const TitleElement = parentClientId ? "div" : "h2";
return /* @__PURE__ */ (0, import_jsx_runtime215.jsx)(
"div",
{
className: clsx_default(
"block-editor-block-card",
{
"is-parent": parentClientId,
"is-child": isChild
},
className
),
children: /* @__PURE__ */ (0, import_jsx_runtime215.jsxs)(Stack, { direction: "column", gap: "sm", children: [
/* @__PURE__ */ (0, import_jsx_runtime215.jsxs)(Stack, { direction: "row", align: "center", justify: "space-between", children: [
/* @__PURE__ */ (0, import_jsx_runtime215.jsxs)(Stack, { direction: "row", align: "center", justify: "flex-start", children: [
parentBlockClientId && /* @__PURE__ */ (0, import_jsx_runtime215.jsx)(
import_components30.Button,
{
onClick: () => selectBlock2(parentBlockClientId),
label: parentBlockName ? (0, import_i18n35.sprintf)(
/* translators: %s: The name of the parent block. */
(0, import_i18n35.__)('Go to "%s" block'),
(0, import_blocks25.getBlockType)(parentBlockName)?.title
) : (0, import_i18n35.__)("Go to parent block"),
style: (
// TODO: This style override is also used in ToolsPanelHeader.
// It should be supported out-of-the-box by Button.
{ minWidth: 24, padding: 0 }
),
icon: (0, import_i18n35.isRTL)() ? chevron_right_default : chevron_left_default,
size: "small"
}
),
isChild && /* @__PURE__ */ (0, import_jsx_runtime215.jsx)("span", { className: "block-editor-block-card__child-indicator-icon", children: /* @__PURE__ */ (0, import_jsx_runtime215.jsx)(
import_components30.Icon,
{
icon: (0, import_i18n35.isRTL)() ? arrow_left_default : arrow_right_default
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime215.jsxs)(
OptionalParentSelectButton,
{
onClick: parentClientId ? () => {
selectBlock2(parentClientId);
} : void 0,
children: [
/* @__PURE__ */ (0, import_jsx_runtime215.jsx)(block_icon_default, { icon, showColors: true }),
/* @__PURE__ */ (0, import_jsx_runtime215.jsxs)(Stack, { direction: "column", gap: "xs", children: [
/* @__PURE__ */ (0, import_jsx_runtime215.jsxs)(TitleElement, { className: "block-editor-block-card__title", children: [
/* @__PURE__ */ (0, import_jsx_runtime215.jsx)("span", { className: "block-editor-block-card__name", children: !!name?.length ? name : title }),
!parentClientId && !isChild && !!name?.length && /* @__PURE__ */ (0, import_jsx_runtime215.jsx)(WCBadge2, { children: title })
] }),
children
] })
]
}
)
] }),
controls
] }),
!parentClientId && !isChild && description && /* @__PURE__ */ (0, import_jsx_runtime215.jsx)(Text, { className: "block-editor-block-card__description", children: description })
] })
}
);
}
var block_card_default = BlockCard;
// packages/block-editor/build-module/components/block-preview/index.mjs
var import_compose35 = __toESM(require_compose(), 1);
var import_data53 = __toESM(require_data(), 1);
var import_element99 = __toESM(require_element(), 1);
var import_deprecated7 = __toESM(require_deprecated(), 1);
// packages/block-editor/build-module/components/provider/index.mjs
var import_data35 = __toESM(require_data(), 1);
var import_element90 = __toESM(require_element(), 1);
var import_components31 = __toESM(require_components(), 1);
var import_upload_media = __toESM(require_upload_media(), 1);
// packages/block-editor/build-module/components/provider/with-registry-provider.mjs
var import_element85 = __toESM(require_element(), 1);
var import_data32 = __toESM(require_data(), 1);
var import_compose18 = __toESM(require_compose(), 1);
var import_jsx_runtime216 = __toESM(require_jsx_runtime(), 1);
function getSubRegistry(subRegistries, registry, useSubRegistry) {
if (!useSubRegistry) {
return registry;
}
let subRegistry = subRegistries.get(registry);
if (!subRegistry) {
subRegistry = (0, import_data32.createRegistry)({}, registry);
subRegistry.registerStore(STORE_NAME, storeConfig);
subRegistries.set(registry, subRegistry);
}
return subRegistry;
}
var withRegistryProvider = (0, import_compose18.createHigherOrderComponent)(
(WrappedComponent) => function WithRegistryProvider({ useSubRegistry = true, ...props }) {
const registry = (0, import_data32.useRegistry)();
const [subRegistries] = (0, import_element85.useState)(() => /* @__PURE__ */ new WeakMap());
const subRegistry = getSubRegistry(
subRegistries,
registry,
useSubRegistry
);
if (subRegistry === registry) {
return /* @__PURE__ */ (0, import_jsx_runtime216.jsx)(WrappedComponent, { registry, ...props });
}
return /* @__PURE__ */ (0, import_jsx_runtime216.jsx)(import_data32.RegistryProvider, { value: subRegistry, children: /* @__PURE__ */ (0, import_jsx_runtime216.jsx)(WrappedComponent, { registry: subRegistry, ...props }) });
},
"withRegistryProvider"
);
var with_registry_provider_default = withRegistryProvider;
// packages/block-editor/build-module/components/provider/use-block-sync.mjs
var import_element87 = __toESM(require_element(), 1);
var import_data33 = __toESM(require_data(), 1);
var import_blocks26 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/components/provider/selection-context.mjs
var import_element86 = __toESM(require_element(), 1);
var noop7 = () => {
};
var SelectionContext = (0, import_element86.createContext)({
getSelection: () => void 0,
onChangeSelection: noop7
});
// packages/block-editor/build-module/components/provider/use-block-sync.mjs
var noop8 = () => {
};
function cloneBlockWithMapping(block, mapping) {
const clonedBlock = (0, import_blocks26.cloneBlock)(block);
mapping.externalToInternal.set(block.clientId, clonedBlock.clientId);
mapping.internalToExternal.set(clonedBlock.clientId, block.clientId);
if (block.innerBlocks?.length) {
clonedBlock.innerBlocks = block.innerBlocks.map((innerBlock) => {
const clonedInner = cloneBlockWithMapping(innerBlock, mapping);
return clonedInner;
});
}
return clonedBlock;
}
function restoreExternalIds(blocks2, mapping) {
return blocks2.map((block) => {
const externalId = mapping.internalToExternal.get(block.clientId);
return {
...block,
// Use external ID if available, otherwise keep internal ID (for new blocks)
clientId: externalId ?? block.clientId,
innerBlocks: restoreExternalIds(block.innerBlocks, mapping)
};
});
}
function restoreSelectionIds(selectionState, mapping) {
const { selectionStart, selectionEnd, initialPosition: initialPosition2 } = selectionState;
const restoreClientId = (sel) => {
if (!sel?.clientId) {
return sel;
}
const externalId = mapping.internalToExternal.get(sel.clientId);
return {
...sel,
clientId: externalId ?? sel.clientId
};
};
return {
selectionStart: restoreClientId(selectionStart),
selectionEnd: restoreClientId(selectionEnd),
initialPosition: initialPosition2
};
}
function useBlockSync({
clientId = null,
value: controlledBlocks,
onChange = noop8,
onInput = noop8
}) {
const registry = (0, import_data33.useRegistry)();
const { getSelection, onChangeSelection } = (0, import_element87.useContext)(SelectionContext);
const {
resetBlocks: resetBlocks2,
resetSelection: resetSelection2,
replaceInnerBlocks: replaceInnerBlocks2,
setHasControlledInnerBlocks: setHasControlledInnerBlocks2,
__unstableMarkNextChangeAsNotPersistent: __unstableMarkNextChangeAsNotPersistent2
} = registry.dispatch(store);
const { getBlockName: getBlockName2, getBlocks: getBlocks2, getSelectionStart: getSelectionStart2, getSelectionEnd: getSelectionEnd2 } = registry.select(store);
const pendingChangesRef = (0, import_element87.useRef)({ incoming: null, outgoing: [] });
const subscribedRef = (0, import_element87.useRef)(false);
const idMappingRef = (0, import_element87.useRef)({
externalToInternal: /* @__PURE__ */ new Map(),
internalToExternal: /* @__PURE__ */ new Map()
});
const appliedSelectionRef = (0, import_element87.useRef)(null);
const isRestoringSelectionRef = (0, import_element87.useRef)(false);
const restoreSelection = () => {
const selection2 = getSelection();
if (!selection2?.selectionStart?.clientId || selection2 === appliedSelectionRef.current) {
return;
}
const startClientId = selection2.selectionStart.clientId;
const isOurs = clientId ? idMappingRef.current.externalToInternal.has(startClientId) : !!getBlockName2(startClientId);
if (isOurs) {
appliedSelectionRef.current = selection2;
const convert = (sel) => {
if (!sel?.clientId || !clientId) {
return sel;
}
return {
...sel,
clientId: idMappingRef.current.externalToInternal.get(
sel.clientId
) ?? sel.clientId
};
};
isRestoringSelectionRef.current = true;
resetSelection2(
convert(selection2.selectionStart),
convert(selection2.selectionEnd),
selection2.initialPosition
);
isRestoringSelectionRef.current = false;
}
};
const setControlledBlocks = () => {
if (!controlledBlocks) {
return;
}
if (clientId) {
registry.batch(() => {
idMappingRef.current.externalToInternal.clear();
idMappingRef.current.internalToExternal.clear();
const storeBlocks = controlledBlocks.map(
(block) => cloneBlockWithMapping(block, idMappingRef.current)
);
__unstableMarkNextChangeAsNotPersistent2();
setHasControlledInnerBlocks2(clientId, true);
if (subscribedRef.current) {
pendingChangesRef.current.incoming = storeBlocks;
}
__unstableMarkNextChangeAsNotPersistent2();
replaceInnerBlocks2(clientId, storeBlocks);
appliedSelectionRef.current = null;
});
} else {
if (subscribedRef.current) {
pendingChangesRef.current.incoming = controlledBlocks;
}
__unstableMarkNextChangeAsNotPersistent2();
resetBlocks2(controlledBlocks);
}
};
const unsetControlledBlocks = () => {
if (clientId) {
__unstableMarkNextChangeAsNotPersistent2();
setHasControlledInnerBlocks2(clientId, false);
__unstableMarkNextChangeAsNotPersistent2();
replaceInnerBlocks2(clientId, []);
} else {
__unstableMarkNextChangeAsNotPersistent2();
resetBlocks2([]);
}
};
const onInputRef = (0, import_element87.useRef)(onInput);
const onChangeRef = (0, import_element87.useRef)(onChange);
(0, import_element87.useEffect)(() => {
onInputRef.current = onInput;
onChangeRef.current = onChange;
}, [onInput, onChange]);
(0, import_element87.useEffect)(() => {
const isOutgoing = pendingChangesRef.current.outgoing.includes(controlledBlocks);
const storeMatch = getBlocks2(clientId) === controlledBlocks;
if (isOutgoing) {
if (pendingChangesRef.current.outgoing[pendingChangesRef.current.outgoing.length - 1] === controlledBlocks) {
pendingChangesRef.current.outgoing = [];
}
} else if (!storeMatch) {
pendingChangesRef.current.outgoing = [];
setControlledBlocks();
restoreSelection();
}
}, [controlledBlocks, clientId]);
(0, import_element87.useEffect)(() => {
const {
getSelectedBlocksInitialCaretPosition: getSelectedBlocksInitialCaretPosition2,
isLastBlockChangePersistent: isLastBlockChangePersistent2,
__unstableGetLastBlockChangeHistoryMode: __unstableGetLastBlockChangeHistoryMode2,
__unstableIsLastBlockChangeIgnored: __unstableIsLastBlockChangeIgnored2,
areInnerBlocksControlled: areInnerBlocksControlled2,
getBlockParents: getBlockParents2
} = registry.select(store);
let blocks2 = getBlocks2(clientId);
let isPersistent = isLastBlockChangePersistent2();
let blockHistoryMode = __unstableGetLastBlockChangeHistoryMode2();
let previousAreBlocksDifferent = false;
let prevSelectionStart = getSelectionStart2();
let prevSelectionEnd = getSelectionEnd2();
subscribedRef.current = true;
const unsubscribe = registry.subscribe(() => {
if (clientId !== null && getBlockName2(clientId) === null) {
return;
}
const newIsPersistent = isLastBlockChangePersistent2();
const newBlockHistoryMode = __unstableGetLastBlockChangeHistoryMode2();
const newBlocks = getBlocks2(clientId);
const areBlocksDifferent = newBlocks !== blocks2;
blocks2 = newBlocks;
if (areBlocksDifferent && (pendingChangesRef.current.incoming || __unstableIsLastBlockChangeIgnored2())) {
pendingChangesRef.current.incoming = null;
isPersistent = newIsPersistent;
blockHistoryMode = newBlockHistoryMode;
return;
}
const didPersistenceChange = previousAreBlocksDifferent && !areBlocksDifferent && newIsPersistent && !isPersistent;
const blocksChanged = areBlocksDifferent || didPersistenceChange;
const newSelectionStart = getSelectionStart2();
const newSelectionEnd = getSelectionEnd2();
const selectionChanged = newSelectionStart !== prevSelectionStart || newSelectionEnd !== prevSelectionEnd;
if (selectionChanged) {
prevSelectionStart = newSelectionStart;
prevSelectionEnd = newSelectionEnd;
}
if (blocksChanged || selectionChanged) {
registry.batch(() => {
if (blocksChanged) {
isPersistent = newIsPersistent;
blockHistoryMode = newBlockHistoryMode;
const blocksForParent = clientId ? restoreExternalIds(blocks2, idMappingRef.current) : blocks2;
const selectionInfo = {
selectionStart: newSelectionStart,
selectionEnd: newSelectionEnd,
initialPosition: getSelectedBlocksInitialCaretPosition2()
};
const selectionForParent = clientId ? restoreSelectionIds(
selectionInfo,
idMappingRef.current
) : selectionInfo;
pendingChangesRef.current.outgoing.push(
blocksForParent
);
const updateParent = isPersistent ? onChangeRef.current : onInputRef.current;
const updateOptions = {
selection: selectionForParent
};
if (blockHistoryMode === "ignore") {
updateOptions.undoIgnore = true;
}
updateParent(blocksForParent, updateOptions);
}
if (selectionChanged && !blocksChanged && newSelectionStart?.clientId && !isRestoringSelectionRef.current) {
const isOurs = clientId ? idMappingRef.current.internalToExternal.has(
newSelectionStart.clientId
) : !getBlockParents2(
newSelectionStart.clientId
).some(
(parentId) => areInnerBlocksControlled2(parentId)
);
if (isOurs) {
const selectionInfo = {
selectionStart: newSelectionStart,
selectionEnd: newSelectionEnd,
initialPosition: getSelectedBlocksInitialCaretPosition2()
};
onChangeSelection(
clientId ? restoreSelectionIds(
selectionInfo,
idMappingRef.current
) : selectionInfo
);
}
}
});
}
previousAreBlocksDifferent = areBlocksDifferent;
}, store);
return () => {
subscribedRef.current = false;
unsubscribe();
};
}, [registry, clientId]);
(0, import_element87.useEffect)(() => {
return () => {
unsetControlledBlocks();
};
}, []);
}
// packages/block-editor/build-module/components/keyboard-shortcuts/index.mjs
var import_element88 = __toESM(require_element(), 1);
var import_data34 = __toESM(require_data(), 1);
var import_keyboard_shortcuts3 = __toESM(require_keyboard_shortcuts(), 1);
var import_i18n36 = __toESM(require_i18n(), 1);
function KeyboardShortcuts() {
return null;
}
function KeyboardShortcutsRegister() {
const { registerShortcut, unregisterShortcut } = (0, import_data34.useDispatch)(
import_keyboard_shortcuts3.store
);
const [blockVisibility2] = useSettings("blockVisibility.allowEditing");
(0, import_element88.useEffect)(() => {
registerShortcut({
name: "core/block-editor/copy",
category: "block",
description: (0, import_i18n36.__)("Copy the selected block(s)."),
keyCombination: {
modifier: "primary",
character: "c"
}
});
registerShortcut({
name: "core/block-editor/cut",
category: "block",
description: (0, import_i18n36.__)("Cut the selected block(s)."),
keyCombination: {
modifier: "primary",
character: "x"
}
});
registerShortcut({
name: "core/block-editor/paste",
category: "block",
description: (0, import_i18n36.__)("Paste the selected block(s)."),
keyCombination: {
modifier: "primary",
character: "v"
}
});
registerShortcut({
name: "core/block-editor/duplicate",
category: "block",
description: (0, import_i18n36.__)("Duplicate the selected block(s)."),
keyCombination: {
modifier: "primaryShift",
character: "d"
}
});
registerShortcut({
name: "core/block-editor/remove",
category: "block",
description: (0, import_i18n36.__)("Remove the selected block(s)."),
keyCombination: {
modifier: "access",
character: "z"
}
});
registerShortcut({
name: "core/block-editor/paste-styles",
category: "block",
description: (0, import_i18n36.__)(
"Paste the copied style to the selected block(s)."
),
keyCombination: {
modifier: "primaryAlt",
character: "v"
}
});
registerShortcut({
name: "core/block-editor/insert-before",
category: "block",
description: (0, import_i18n36.__)(
"Insert a new block before the selected block(s)."
),
keyCombination: {
modifier: "primaryAlt",
character: "t"
}
});
registerShortcut({
name: "core/block-editor/insert-after",
category: "block",
description: (0, import_i18n36.__)(
"Insert a new block after the selected block(s)."
),
keyCombination: {
modifier: "primaryAlt",
character: "y"
}
});
registerShortcut({
name: "core/block-editor/delete-multi-selection",
category: "block",
description: (0, import_i18n36.__)("Delete selection."),
keyCombination: {
character: "del"
},
aliases: [
{
character: "backspace"
}
]
});
registerShortcut({
name: "core/block-editor/stop-editing-as-blocks",
category: "block",
description: (0, import_i18n36.__)("Finish editing a design."),
keyCombination: {
character: "escape"
}
});
registerShortcut({
name: "core/block-editor/select-all",
category: "selection",
description: (0, import_i18n36.__)(
"Select all text when typing. Press again to select all blocks."
),
keyCombination: {
modifier: "primary",
character: "a"
}
});
registerShortcut({
name: "core/block-editor/unselect",
category: "selection",
description: (0, import_i18n36.__)("Clear selection."),
keyCombination: {
character: "escape"
}
});
registerShortcut({
name: "core/block-editor/multi-text-selection",
category: "selection",
description: (0, import_i18n36.__)("Select text across multiple blocks."),
keyCombination: {
modifier: "shift",
// Spotted during my own research — invalid character?
character: "arrow"
}
});
registerShortcut({
name: "core/block-editor/focus-toolbar",
category: "global",
description: (0, import_i18n36.__)("Navigate to the nearest toolbar."),
keyCombination: {
modifier: "alt",
character: "F10"
}
});
registerShortcut({
name: "core/block-editor/move-up",
category: "block",
description: (0, import_i18n36.__)("Move the selected block(s) up."),
keyCombination: {
modifier: "secondary",
character: "t"
}
});
registerShortcut({
name: "core/block-editor/move-down",
category: "block",
description: (0, import_i18n36.__)("Move the selected block(s) down."),
keyCombination: {
modifier: "secondary",
character: "y"
}
});
registerShortcut({
name: "core/block-editor/collapse-list-view",
category: "list-view",
description: (0, import_i18n36.__)("Collapse all other items."),
keyCombination: {
modifier: "alt",
character: "l"
}
});
registerShortcut({
name: "core/block-editor/group",
category: "block",
description: (0, import_i18n36.__)(
"Create a group block from the selected multiple blocks."
),
keyCombination: {
modifier: "primary",
character: "g"
}
});
if (blockVisibility2 === false) {
unregisterShortcut("core/block-editor/toggle-block-visibility");
} else {
registerShortcut({
name: "core/block-editor/toggle-block-visibility",
category: "block",
description: (0, import_i18n36.__)("Show or hide the selected block(s)."),
keyCombination: {
modifier: "primaryShift",
character: "h"
}
});
}
registerShortcut({
name: "core/block-editor/rename",
category: "block",
description: (0, import_i18n36.__)("Rename the selected block."),
keyCombination: {
modifier: "primaryAlt",
character: "r"
}
});
}, [registerShortcut, unregisterShortcut, blockVisibility2]);
return null;
}
KeyboardShortcuts.Register = KeyboardShortcutsRegister;
var keyboard_shortcuts_default = KeyboardShortcuts;
// packages/block-editor/build-module/components/provider/use-media-upload-settings.mjs
var import_element89 = __toESM(require_element(), 1);
function useMediaUploadSettings(settings2 = {}) {
return (0, import_element89.useMemo)(
() => ({
mediaUpload: settings2.mediaUpload,
mediaSideload: settings2.mediaSideload,
mediaFinalize: settings2.mediaFinalize,
mediaDelete: settings2.mediaDelete,
maxUploadFileSize: settings2.maxUploadFileSize,
allowedMimeTypes: settings2.allowedMimeTypes,
allImageSizes: settings2.allImageSizes,
bigImageSizeThreshold: settings2.bigImageSizeThreshold
}),
[settings2]
);
}
var use_media_upload_settings_default = useMediaUploadSettings;
// packages/block-editor/build-module/components/provider/index.mjs
var import_jsx_runtime217 = __toESM(require_jsx_runtime(), 1);
var noop9 = () => {
};
var hasLoggedFallback = false;
var isClientSideMediaEnabledCache = null;
var isHeicCanvasEnabledCache = null;
var HEIC_MIME_TYPES = ["image/heic", "image/heif"];
function shouldEnableClientSideMediaProcessing() {
if (isClientSideMediaEnabledCache !== null) {
return isClientSideMediaEnabledCache;
}
if (!window.__clientSideMediaProcessing) {
isClientSideMediaEnabledCache = false;
return false;
}
if (typeof import_upload_media.detectClientSideMediaSupport !== "function") {
isClientSideMediaEnabledCache = false;
return false;
}
const detection = (0, import_upload_media.detectClientSideMediaSupport)();
if (!detection || !detection.supported) {
if (!hasLoggedFallback) {
console.info(
`Client-side media processing unavailable: ${detection.reason}. Using server-side processing.`
);
hasLoggedFallback = true;
}
isClientSideMediaEnabledCache = false;
return false;
}
isClientSideMediaEnabledCache = true;
return true;
}
function shouldEnableHeicCanvasProcessing() {
if (isHeicCanvasEnabledCache !== null) {
return isHeicCanvasEnabledCache;
}
if (shouldEnableClientSideMediaProcessing()) {
isHeicCanvasEnabledCache = false;
return false;
}
if (!window.__heicUploadSupport) {
isHeicCanvasEnabledCache = false;
return false;
}
if (typeof import_upload_media.isHeicCanvasSupported !== "function" || !(0, import_upload_media.isHeicCanvasSupported)()) {
isHeicCanvasEnabledCache = false;
return false;
}
isHeicCanvasEnabledCache = true;
return true;
}
function mediaUpload(registry, settings2, {
allowedTypes,
additionalData = {},
filesList,
onError = noop9,
onFileChange,
onSuccess,
onBatchSuccess
}) {
void registry.dispatch(import_upload_media.store).addItems({
files: Array.from(filesList),
onChange: onFileChange,
onSuccess: (attachments) => {
settings2?.[mediaUploadOnSuccessKey]?.(attachments);
onSuccess?.(attachments);
},
onBatchSuccess,
onError: (error2) => onError(typeof error2 === "string" ? error2 : error2?.message ?? ""),
additionalData,
allowedTypes
});
}
function heicMediaUpload(registry, settings2, {
allowedTypes,
additionalData = {},
filesList,
onError = noop9,
onFileChange,
onSuccess,
onBatchSuccess
}) {
const files = Array.from(filesList);
const heicFiles = files.filter(
(file) => HEIC_MIME_TYPES.includes(file.type)
);
const otherFiles = files.filter(
(file) => !HEIC_MIME_TYPES.includes(file.type)
);
const hasBothPaths = heicFiles.length > 0 && otherFiles.length > 0 && settings2?.mediaUpload;
let pathsRemaining = hasBothPaths ? 2 : 1;
const coordinatedBatchSuccess = hasBothPaths ? () => {
pathsRemaining--;
if (pathsRemaining <= 0) {
onBatchSuccess?.();
}
} : onBatchSuccess;
if (heicFiles.length > 0) {
void registry.dispatch(import_upload_media.store).addItems({
files: heicFiles,
onChange: onFileChange,
onSuccess: (attachments) => {
settings2?.[mediaUploadOnSuccessKey]?.(attachments);
onSuccess?.(attachments);
},
onBatchSuccess: coordinatedBatchSuccess,
onError: (error2) => onError(
typeof error2 === "string" ? error2 : error2?.message ?? ""
),
additionalData,
allowedTypes
});
}
if (otherFiles.length > 0 && settings2?.mediaUpload) {
settings2.mediaUpload({
allowedTypes,
additionalData,
filesList: otherFiles,
onError,
onFileChange,
onSuccess,
onBatchSuccess: coordinatedBatchSuccess
});
}
}
function BlockSyncEffect(props) {
useBlockSync(props);
return null;
}
var ExperimentalBlockEditorProvider = with_registry_provider_default(
(props) => {
const {
settings: _settings,
registry,
stripExperimentalSettings = false
} = props;
const mediaUploadSettings = use_media_upload_settings_default(_settings);
const isClientSideMediaEnabled = shouldEnableClientSideMediaProcessing();
const isHeicCanvasEnabled = shouldEnableHeicCanvasProcessing();
const useUploadMediaPipeline = isClientSideMediaEnabled || isHeicCanvasEnabled;
const isMediaUploadIntercepted = !!_settings?.mediaUpload?.__isMediaUploadInterceptor;
const settings2 = (0, import_element90.useMemo)(() => {
if (useUploadMediaPipeline && _settings?.mediaUpload && !isMediaUploadIntercepted) {
const uploadFn = isClientSideMediaEnabled ? mediaUpload : heicMediaUpload;
const interceptor = uploadFn.bind(null, registry, _settings);
interceptor.__isMediaUploadInterceptor = true;
return {
..._settings,
mediaUpload: interceptor
};
}
return _settings;
}, [
_settings,
registry,
useUploadMediaPipeline,
isClientSideMediaEnabled,
isMediaUploadIntercepted
]);
const { __experimentalUpdateSettings: __experimentalUpdateSettings2 } = unlock(
(0, import_data35.useDispatch)(store)
);
(0, import_element90.useEffect)(() => {
__experimentalUpdateSettings2(
{
...settings2,
__internalIsInitialized: true
},
{
stripExperimentalSettings,
reset: true
}
);
}, [
settings2,
stripExperimentalSettings,
__experimentalUpdateSettings2
]);
const selectionRef = (0, import_element90.useRef)(props.selection);
selectionRef.current = props.selection;
const onChangeSelectionRef = (0, import_element90.useRef)(props.onChangeSelection ?? noop9);
onChangeSelectionRef.current = props.onChangeSelection ?? noop9;
const selectionContextValue = (0, import_element90.useMemo)(
() => ({
getSelection: () => selectionRef.current,
onChangeSelection: (...args) => onChangeSelectionRef.current(...args)
}),
[]
);
const children = /* @__PURE__ */ (0, import_jsx_runtime217.jsxs)(import_components31.SlotFillProvider, { passthrough: true, children: [
!settings2?.isPreviewMode && /* @__PURE__ */ (0, import_jsx_runtime217.jsx)(keyboard_shortcuts_default.Register, {}),
/* @__PURE__ */ (0, import_jsx_runtime217.jsx)(BlockRefsProvider, { children: props.children })
] });
const content = /* @__PURE__ */ (0, import_jsx_runtime217.jsxs)(SelectionContext.Provider, { value: selectionContextValue, children: [
/* @__PURE__ */ (0, import_jsx_runtime217.jsx)(
BlockSyncEffect,
{
clientId: props.clientId,
value: props.value,
onChange: props.onChange,
onInput: props.onInput
}
),
children
] });
if (useUploadMediaPipeline && !isMediaUploadIntercepted) {
return /* @__PURE__ */ (0, import_jsx_runtime217.jsx)(
import_upload_media.MediaUploadProvider,
{
settings: mediaUploadSettings,
useSubRegistry: false,
children: content
}
);
}
return content;
}
);
var BlockEditorProvider = (props) => {
return /* @__PURE__ */ (0, import_jsx_runtime217.jsx)(ExperimentalBlockEditorProvider, { ...props, stripExperimentalSettings: true, children: props.children });
};
var provider_default = BlockEditorProvider;
// packages/block-editor/build-module/components/block-preview/auto.mjs
var import_compose34 = __toESM(require_compose(), 1);
var import_data52 = __toESM(require_data(), 1);
var import_element97 = __toESM(require_element(), 1);
var import_components34 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/iframe/index.mjs
var import_react14 = __toESM(require_react(), 1);
var import_element95 = __toESM(require_element(), 1);
var import_i18n39 = __toESM(require_i18n(), 1);
var import_compose33 = __toESM(require_compose(), 1);
var import_components32 = __toESM(require_components(), 1);
var import_data50 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/writing-flow/index.mjs
var import_data49 = __toESM(require_data(), 1);
var import_i18n38 = __toESM(require_i18n(), 1);
var import_compose31 = __toESM(require_compose(), 1);
var import_element93 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/writing-flow/use-editable-root.mjs
var import_data36 = __toESM(require_data(), 1);
var import_compose19 = __toESM(require_compose(), 1);
var import_blocks27 = __toESM(require_blocks(), 1);
function canHostEditableRoot(select3, clientId) {
const {
getBlockName: getBlockName2,
getBlockEditingMode: getBlockEditingMode2,
getBlockMode: getBlockMode2,
getBlockRootClientId: getBlockRootClientId2,
getBlockOrder: getBlockOrder2
} = select3;
if (!clientId || getBlockEditingMode2(clientId) !== "default" || // Not when the block is edited as HTML: there is no rich text to
// host then, only a textarea, which the editing host would
// interfere with.
getBlockMode2(clientId) !== "visual" || !(0, import_blocks27.hasBlockSupport)(getBlockName2(clientId), "editableRoot", false)) {
return false;
}
const siblings = getBlockOrder2(getBlockRootClientId2(clientId));
return siblings.length > 1 && siblings.every(
(siblingClientId) => getBlockEditingMode2(siblingClientId) === "default"
);
}
function useHasEditableRoot() {
return (0, import_data36.useSelect)((select3) => {
const selectors4 = select3(store);
return canHostEditableRoot(
selectors4,
selectors4.getSelectedBlockClientId()
);
}, []);
}
function useEditableRoot() {
const registry = (0, import_data36.useRegistry)();
const isZoomOut2 = (0, import_data36.useSelect)(
(select3) => unlock(select3(store)).isZoomOut(),
[]
);
const enabled = useHasEditableRoot() && !isZoomOut2;
return (0, import_compose19.useRefEffect)(
(node) => {
if (!enabled) {
return;
}
const {
getSelectedBlockClientId: getSelectedBlockClientId2,
hasMultiSelection: hasMultiSelection2,
isMultiSelecting: isMultiSelecting3
} = registry.select(store);
if (!setContentEditableWrapper(node, true, { focus: false })) {
return;
}
const { activeElement: activeElement2 } = node.ownerDocument;
const selection2 = node.ownerDocument.defaultView.getSelection();
if (activeElement2 !== node && activeElement2?.isContentEditable && node.contains(activeElement2) && getBlockClientId(activeElement2) === getSelectedBlockClientId2() && selection2.anchorNode && activeElement2.contains(selection2.anchorNode)) {
node.focus();
}
return () => {
if (hasMultiSelection2() || isMultiSelecting3()) {
return;
}
setContentEditableWrapper(node, false);
if (node.ownerDocument.activeElement === node) {
const editable = getSelectionEditableElement(
node.ownerDocument.defaultView.getSelection(),
node
);
if (editable && getBlockClientId(editable) === getSelectedBlockClientId2()) {
editable.focus();
}
}
};
},
[enabled, registry]
);
}
// packages/block-editor/build-module/components/writing-flow/use-home-end.mjs
var import_keycodes3 = __toESM(require_keycodes(), 1);
var import_data37 = __toESM(require_data(), 1);
var import_compose20 = __toESM(require_compose(), 1);
function useHomeEnd() {
const { hasMultiSelection: hasMultiSelection2 } = (0, import_data37.useSelect)(store);
return (0, import_compose20.useRefEffect)((node) => {
function onKeyDown(event) {
if (event.defaultPrevented) {
return;
}
if (event.keyCode !== import_keycodes3.HOME && event.keyCode !== import_keycodes3.END) {
return;
}
if (event.metaKey || event.ctrlKey || event.altKey) {
return;
}
if (node.contentEditable !== "true" || node.ownerDocument.activeElement !== node || hasMultiSelection2()) {
return;
}
const selection2 = node.ownerDocument.defaultView.getSelection();
if (!getSelectionEditableElement(selection2, node)) {
return;
}
event.preventDefault();
selection2.modify(
event.shiftKey ? "extend" : "move",
event.keyCode === import_keycodes3.HOME ? "backward" : "forward",
"lineboundary"
);
}
node.addEventListener("keydown", onKeyDown);
return () => {
node.removeEventListener("keydown", onKeyDown);
};
}, []);
}
// packages/block-editor/build-module/components/writing-flow/use-multi-selection.mjs
var import_compose21 = __toESM(require_compose(), 1);
var import_data38 = __toESM(require_data(), 1);
function selector(select3) {
const {
isMultiSelecting: isMultiSelecting3,
getMultiSelectedBlockClientIds: getMultiSelectedBlockClientIds2,
hasMultiSelection: hasMultiSelection2,
getSelectedBlockClientId: getSelectedBlockClientId2,
getSelectedBlocksInitialCaretPosition: getSelectedBlocksInitialCaretPosition2,
__unstableIsFullySelected: __unstableIsFullySelected2
} = select3(store);
return {
isMultiSelecting: isMultiSelecting3(),
multiSelectedBlockClientIds: getMultiSelectedBlockClientIds2(),
hasMultiSelection: hasMultiSelection2(),
selectedBlockClientId: getSelectedBlockClientId2(),
initialPosition: getSelectedBlocksInitialCaretPosition2(),
isFullSelection: __unstableIsFullySelected2()
};
}
function useMultiSelection() {
const {
initialPosition: initialPosition2,
isMultiSelecting: isMultiSelecting3,
multiSelectedBlockClientIds,
hasMultiSelection: hasMultiSelection2,
selectedBlockClientId,
isFullSelection
} = (0, import_data38.useSelect)(selector, []);
return (0, import_compose21.useRefEffect)(
(node) => {
const { ownerDocument: ownerDocument2 } = node;
const { defaultView } = ownerDocument2;
if (initialPosition2 === void 0 || initialPosition2 === null) {
return;
}
if (!hasMultiSelection2 || isMultiSelecting3) {
return;
}
const { length } = multiSelectedBlockClientIds;
if (length < 2) {
return;
}
if (!isFullSelection) {
return;
}
setContentEditableWrapper(node, true);
defaultView.getSelection().removeAllRanges();
},
[
hasMultiSelection2,
isMultiSelecting3,
multiSelectedBlockClientIds,
selectedBlockClientId,
initialPosition2,
isFullSelection
]
);
}
// packages/block-editor/build-module/components/writing-flow/use-tab-nav.mjs
var import_dom39 = __toESM(require_dom(), 1);
var import_keycodes4 = __toESM(require_keycodes(), 1);
var import_data39 = __toESM(require_data(), 1);
var import_compose22 = __toESM(require_compose(), 1);
var import_element91 = __toESM(require_element(), 1);
var import_jsx_runtime218 = __toESM(require_jsx_runtime(), 1);
function useTabNav() {
const containerRef = (
/** @type {typeof useRef<HTMLElement>} */
(0, import_element91.useRef)()
);
const focusCaptureBeforeRef = (0, import_element91.useRef)();
const focusCaptureAfterRef = (0, import_element91.useRef)();
const {
hasMultiSelection: hasMultiSelection2,
getSelectedBlockClientId: getSelectedBlockClientId2,
getBlockCount: getBlockCount2,
getBlockOrder: getBlockOrder2,
getLastFocus: getLastFocus2,
getSectionRootClientId: getSectionRootClientId2,
isZoomOut: isZoomOut2
} = unlock((0, import_data39.useSelect)(store));
const { setLastFocus: setLastFocus2 } = unlock((0, import_data39.useDispatch)(store));
const noCaptureRef = (0, import_element91.useRef)();
function onFocusCapture(event) {
const canvasElement = containerRef.current.ownerDocument === event.target.ownerDocument ? containerRef.current : containerRef.current.ownerDocument.defaultView.frameElement;
if (noCaptureRef.current) {
noCaptureRef.current = null;
} else if (hasMultiSelection2()) {
containerRef.current.focus();
} else if (getSelectedBlockClientId2()) {
if (getLastFocus2()?.current) {
getLastFocus2().current.focus();
} else {
containerRef.current.querySelector(
`[data-block="${getSelectedBlockClientId2()}"]`
).focus();
}
} else if (isZoomOut2()) {
const sectionRootClientId = getSectionRootClientId2();
const sectionBlocks = getBlockOrder2(sectionRootClientId);
if (sectionBlocks.length) {
containerRef.current.querySelector(`[data-block="${sectionBlocks[0]}"]`).focus();
} else if (sectionRootClientId) {
containerRef.current.querySelector(`[data-block="${sectionRootClientId}"]`).focus();
} else {
canvasElement.focus();
}
} else {
const isBefore = (
// eslint-disable-next-line no-bitwise
event.target.compareDocumentPosition(canvasElement) & event.target.DOCUMENT_POSITION_FOLLOWING
);
const tabbables = import_dom39.focus.tabbable.find(containerRef.current);
if (tabbables.length) {
const next = isBefore ? tabbables[0] : tabbables[tabbables.length - 1];
next.focus();
}
}
}
const before = /* @__PURE__ */ (0, import_jsx_runtime218.jsx)(
"div",
{
ref: focusCaptureBeforeRef,
tabIndex: "0",
onFocus: onFocusCapture
}
);
const after = /* @__PURE__ */ (0, import_jsx_runtime218.jsx)(
"div",
{
ref: focusCaptureAfterRef,
tabIndex: "0",
onFocus: onFocusCapture
}
);
const ref = (0, import_compose22.useRefEffect)((node) => {
function onKeyDown(event) {
if (event.defaultPrevented) {
return;
}
if (event.keyCode !== import_keycodes4.TAB) {
return;
}
if (
// Bails in case the focus capture elements aren’t present. They
// may be omitted to avoid silent tab stops in preview mode.
// See: https://github.com/WordPress/gutenberg/pull/59317
!focusCaptureAfterRef.current || !focusCaptureBeforeRef.current
) {
return;
}
const { target, shiftKey: isShift } = event;
const direction = isShift ? "findPrevious" : "findNext";
const nextTabbable = import_dom39.focus.tabbable[direction](target);
const currentBlock = target.closest("[data-block]");
const isElementPartOfSelectedBlock = currentBlock && nextTabbable && (isInSameBlock(currentBlock, nextTabbable) || isInsideRootBlock(currentBlock, nextTabbable));
if ((0, import_dom39.isFormElement)(nextTabbable) && isElementPartOfSelectedBlock) {
return;
}
const next = isShift ? focusCaptureBeforeRef : focusCaptureAfterRef;
noCaptureRef.current = true;
next.current.focus({ preventScroll: true });
}
function onFocusOut(event) {
setLastFocus2({ ...getLastFocus2(), current: event.target });
const { ownerDocument: ownerDocument22 } = node;
if (!event.relatedTarget && event.target.hasAttribute("data-block") && ownerDocument22.activeElement === ownerDocument22.body && getBlockCount2() === 0) {
node.focus();
}
}
function preventScrollOnTab(event) {
if (event.keyCode !== import_keycodes4.TAB) {
return;
}
if (event.target?.getAttribute("role") === "region") {
return;
}
if (containerRef.current === event.target) {
return;
}
const isShift = event.shiftKey;
const direction = isShift ? "findPrevious" : "findNext";
const target = import_dom39.focus.tabbable[direction](event.target);
if (target === focusCaptureBeforeRef.current || target === focusCaptureAfterRef.current) {
event.preventDefault();
target.focus({ preventScroll: true });
}
}
const { ownerDocument: ownerDocument2 } = node;
const { defaultView } = ownerDocument2;
defaultView.addEventListener("keydown", preventScrollOnTab);
node.addEventListener("keydown", onKeyDown);
node.addEventListener("focusout", onFocusOut);
return () => {
defaultView.removeEventListener("keydown", preventScrollOnTab);
node.removeEventListener("keydown", onKeyDown);
node.removeEventListener("focusout", onFocusOut);
};
}, []);
const mergedRefs = (0, import_compose22.useMergeRefs)([containerRef, ref]);
return [before, mergedRefs, after];
}
// packages/block-editor/build-module/components/writing-flow/use-arrow-nav.mjs
var import_dom41 = __toESM(require_dom(), 1);
var import_keycodes5 = __toESM(require_keycodes(), 1);
var import_data40 = __toESM(require_data(), 1);
var import_compose23 = __toESM(require_compose(), 1);
function isNavigationCandidate(element, keyCode, hasModifier) {
const isVertical = keyCode === import_keycodes5.UP || keyCode === import_keycodes5.DOWN;
const { tagName } = element;
const elementType = element.getAttribute("type");
if (isVertical && !hasModifier) {
if (tagName === "INPUT") {
const verticalInputTypes = [
"date",
"datetime-local",
"month",
"number",
"range",
"time",
"week"
];
return !verticalInputTypes.includes(elementType);
}
return true;
}
if (tagName === "INPUT") {
const simpleInputTypes = [
"button",
"checkbox",
"number",
"color",
"file",
"image",
"radio",
"reset",
"submit"
];
return simpleInputTypes.includes(elementType);
}
return tagName !== "TEXTAREA";
}
function getClosestTabbable(target, isReverse, containerElement, onlyVertical) {
let focusableNodes = import_dom41.focus.focusable.find(containerElement);
if (isReverse) {
focusableNodes.reverse();
}
focusableNodes = focusableNodes.slice(
focusableNodes.indexOf(target) + 1
);
let targetRect;
if (onlyVertical) {
targetRect = target.getBoundingClientRect();
}
function isTabCandidate(node) {
if (node.contentEditable !== "true" && getBlockClientId(node) && import_dom41.focus.focusable.find(node).filter((element) => !(0, import_dom41.isFormElement)(element)).length !== 0) {
return false;
}
if (!import_dom41.focus.tabbable.isTabbableIndex(node)) {
return false;
}
if (node.isContentEditable && node.contentEditable !== "true" && getBlockClientId(node.closest('[contenteditable="true"]'))) {
return false;
}
if (onlyVertical) {
const nodeRect = node.getBoundingClientRect();
if (nodeRect.left >= targetRect.right || nodeRect.right <= targetRect.left) {
return false;
}
}
return true;
}
return focusableNodes.find(isTabCandidate);
}
function useArrowNav() {
const {
getMultiSelectedBlocksStartClientId: getMultiSelectedBlocksStartClientId2,
getMultiSelectedBlocksEndClientId: getMultiSelectedBlocksEndClientId2,
getSettings: getSettings7,
hasMultiSelection: hasMultiSelection2,
__unstableIsFullySelected: __unstableIsFullySelected2
} = (0, import_data40.useSelect)(store);
const { selectBlock: selectBlock2 } = (0, import_data40.useDispatch)(store);
return (0, import_compose23.useRefEffect)((node) => {
let verticalRect;
function onMouseDown() {
verticalRect = null;
}
function isClosestTabbableABlock(target, isReverse) {
const closestTabbable = getClosestTabbable(
target,
isReverse,
node
);
return closestTabbable && getBlockClientId(closestTabbable);
}
function onKeyDown(event) {
if (event.defaultPrevented) {
return;
}
const { keyCode, shiftKey, ctrlKey, altKey, metaKey } = event;
const target = event.target === node && getSelectionEditableElement(
node.ownerDocument.defaultView.getSelection(),
node
) || event.target;
const isUp = keyCode === import_keycodes5.UP;
const isDown = keyCode === import_keycodes5.DOWN;
const isLeft = keyCode === import_keycodes5.LEFT;
const isRight = keyCode === import_keycodes5.RIGHT;
const isReverse = isUp || isLeft;
const isHorizontal = isLeft || isRight;
const isVertical = isUp || isDown;
const isNav = isHorizontal || isVertical;
const hasModifier = shiftKey || ctrlKey || altKey || metaKey;
const isNavEdge = isVertical ? import_dom41.isVerticalEdge : import_dom41.isHorizontalEdge;
const { ownerDocument: ownerDocument2 } = node;
const { defaultView } = ownerDocument2;
if (!isNav) {
return;
}
if (getSettings7().isPreviewMode) {
return;
}
if (hasMultiSelection2()) {
if (shiftKey) {
return;
}
if (!__unstableIsFullySelected2()) {
return;
}
event.preventDefault();
if (isReverse) {
selectBlock2(getMultiSelectedBlocksStartClientId2());
} else {
selectBlock2(getMultiSelectedBlocksEndClientId2(), -1);
}
return;
}
if (!isNavigationCandidate(target, keyCode, hasModifier)) {
return;
}
if (!isVertical) {
verticalRect = null;
} else if (!verticalRect) {
verticalRect = (0, import_dom41.computeCaretRect)(defaultView);
}
const isReverseDir = (0, import_dom41.isRTL)(target) ? !isReverse : isReverse;
const { keepCaretInsideBlock } = getSettings7();
if (shiftKey) {
if (isNavEdge(target, isReverse)) {
if (isClosestTabbableABlock(target, isReverse)) {
setContentEditableWrapper(node, true);
} else if (node.contentEditable === "true") {
const selection2 = defaultView.getSelection();
selection2.extend(
target,
isReverse ? 0 : target.childNodes.length
);
event.preventDefault();
}
}
} else if (isVertical && (0, import_dom41.isVerticalEdge)(target, isReverse) && // When Alt is pressed, only intercept if the caret is also at
// the horizontal edge.
(altKey ? (0, import_dom41.isHorizontalEdge)(target, isReverseDir) : true) && !keepCaretInsideBlock) {
const closestTabbable = getClosestTabbable(
target,
isReverse,
node,
true
);
if (closestTabbable) {
(0, import_dom41.placeCaretAtVerticalEdge)(
closestTabbable,
// When Alt is pressed, place the caret at the furthest
// horizontal edge and the furthest vertical edge.
altKey ? !isReverse : isReverse,
altKey ? void 0 : verticalRect
);
event.preventDefault();
}
} else if (isHorizontal && defaultView.getSelection().isCollapsed && (0, import_dom41.isHorizontalEdge)(target, isReverseDir) && !keepCaretInsideBlock) {
const closestTabbable = getClosestTabbable(
target,
isReverseDir,
node
);
(0, import_dom41.placeCaretAtHorizontalEdge)(closestTabbable, isReverse);
event.preventDefault();
}
}
node.addEventListener("mousedown", onMouseDown);
node.addEventListener("keydown", onKeyDown);
return () => {
node.removeEventListener("mousedown", onMouseDown);
node.removeEventListener("keydown", onKeyDown);
};
}, []);
}
// packages/block-editor/build-module/components/writing-flow/use-preview-mode-nav.mjs
var import_compose24 = __toESM(require_compose(), 1);
var import_data41 = __toESM(require_data(), 1);
var import_keycodes6 = __toESM(require_keycodes(), 1);
function usePreviewModeNav() {
const isPreviewMode = (0, import_data41.useSelect)(
(select3) => select3(store).getSettings().isPreviewMode,
[]
);
return (0, import_compose24.useRefEffect)(
(node) => {
if (!isPreviewMode) {
return;
}
function onKeyDown(event) {
const { keyCode, shiftKey, target } = event;
const isTab = keyCode === import_keycodes6.TAB;
const isUp = keyCode === import_keycodes6.UP;
const isDown = keyCode === import_keycodes6.DOWN;
const isLeft = keyCode === import_keycodes6.LEFT;
const isRight = keyCode === import_keycodes6.RIGHT;
const isArrow = isUp || isDown || isLeft || isRight;
if (!isTab && !isArrow) {
return;
}
const isReverse = isTab ? shiftKey : isUp || isLeft;
const blocks2 = Array.from(
node.querySelectorAll("[data-block]")
);
if (!blocks2.length) {
return;
}
const currentBlock = target.closest("[data-block]");
const currentIndex = currentBlock ? blocks2.indexOf(currentBlock) : -1;
if (currentIndex === -1) {
return;
}
if (isTab) {
if (isReverse && currentIndex === 0) {
return;
}
if (!isReverse && currentIndex === blocks2.length - 1) {
return;
}
}
let nextIndex;
if (isReverse) {
nextIndex = currentIndex <= 0 ? blocks2.length - 1 : currentIndex - 1;
} else {
nextIndex = currentIndex === -1 || currentIndex >= blocks2.length - 1 ? 0 : currentIndex + 1;
}
event.preventDefault();
blocks2[nextIndex].focus();
}
node.addEventListener("keydown", onKeyDown);
return () => {
node.removeEventListener("keydown", onKeyDown);
};
},
[isPreviewMode]
);
}
// packages/block-editor/build-module/components/writing-flow/use-select-all.mjs
var import_dom43 = __toESM(require_dom(), 1);
var import_data42 = __toESM(require_data(), 1);
var import_keyboard_shortcuts5 = __toESM(require_keyboard_shortcuts(), 1);
var import_compose25 = __toESM(require_compose(), 1);
function useSelectAll() {
const { getBlockOrder: getBlockOrder2, getSelectedBlockClientIds: getSelectedBlockClientIds2, getBlockRootClientId: getBlockRootClientId2 } = (0, import_data42.useSelect)(store);
const { multiSelect: multiSelect2, selectBlock: selectBlock2 } = (0, import_data42.useDispatch)(store);
const isMatch = (0, import_keyboard_shortcuts5.__unstableUseShortcutEventMatch)();
return (0, import_compose25.useRefEffect)((node) => {
function onKeyDown(event) {
if (!isMatch("core/block-editor/select-all", event)) {
return;
}
const selectedClientIds = getSelectedBlockClientIds2();
const { ownerDocument: ownerDocument2 } = node;
const selection2 = ownerDocument2.defaultView.getSelection();
const editable = event.target === node && getSelectionEditableElement(selection2, node) || event.target;
if (selectedClientIds.length < 2 && !(0, import_dom43.isEntirelySelected)(editable)) {
if (event.target === node && editable !== node) {
event.preventDefault();
const range2 = ownerDocument2.createRange();
range2.selectNodeContents(editable);
selection2.removeAllRanges();
selection2.addRange(range2);
ownerDocument2.dispatchEvent(
new Event("selectionchange")
);
}
return;
}
event.preventDefault();
const [firstSelectedClientId] = selectedClientIds;
const activeClientId = getBlockClientId(
ownerDocument2.activeElement
);
if (activeClientId && activeClientId !== firstSelectedClientId && !isInsideRootBlock(
ownerDocument2.getElementById(
"block-" + firstSelectedClientId
),
ownerDocument2.activeElement
)) {
selectBlock2(activeClientId);
return;
}
const rootClientId = getBlockRootClientId2(firstSelectedClientId);
const blockClientIds = getBlockOrder2(rootClientId);
if (selectedClientIds.length === blockClientIds.length) {
if (rootClientId) {
node.ownerDocument.defaultView.getSelection().removeAllRanges();
selectBlock2(rootClientId);
}
return;
}
multiSelect2(
blockClientIds[0],
blockClientIds[blockClientIds.length - 1]
);
}
node.addEventListener("keydown", onKeyDown);
return () => {
node.removeEventListener("keydown", onKeyDown);
};
}, []);
}
// packages/block-editor/build-module/components/writing-flow/use-drag-selection.mjs
var import_data43 = __toESM(require_data(), 1);
var import_compose26 = __toESM(require_compose(), 1);
function useDragSelection() {
const { startMultiSelect: startMultiSelect2, stopMultiSelect: stopMultiSelect2 } = (0, import_data43.useDispatch)(store);
const {
getSettings: getSettings7,
isSelectionEnabled: isSelectionEnabled3,
hasSelectedBlock: hasSelectedBlock2,
isDraggingBlocks: isDraggingBlocks2,
isMultiSelecting: isMultiSelecting3
} = (0, import_data43.useSelect)(store);
return (0, import_compose26.useRefEffect)(
(node) => {
const { ownerDocument: ownerDocument2 } = node;
const { defaultView } = ownerDocument2;
let anchorElement;
let rafId2;
function onMouseUp() {
stopMultiSelect2();
defaultView.removeEventListener("mouseup", onMouseUp);
rafId2 = defaultView.requestAnimationFrame(() => {
if (!hasSelectedBlock2()) {
return;
}
setContentEditableWrapper(node, false);
const selection2 = defaultView.getSelection();
if (selection2.rangeCount) {
const range2 = selection2.getRangeAt(0);
const { commonAncestorContainer } = range2;
const clonedRange = range2.cloneRange();
if (anchorElement.contains(commonAncestorContainer)) {
anchorElement.focus();
selection2.removeAllRanges();
selection2.addRange(clonedRange);
}
}
});
}
let lastMouseDownTarget;
function onMouseDown({ target }) {
lastMouseDownTarget = target;
}
function onMouseLeave({ buttons, target, relatedTarget }) {
if (!target.contains(lastMouseDownTarget)) {
return;
}
if (target.contains(relatedTarget)) {
return;
}
if (isDraggingBlocks2()) {
return;
}
if (buttons !== 1) {
return;
}
if (isMultiSelecting3()) {
return;
}
if (node === target) {
return;
}
if (target.getAttribute("contenteditable") !== "true" && !getSettings7().isPreviewMode) {
return;
}
if (!isSelectionEnabled3()) {
return;
}
anchorElement = target;
startMultiSelect2();
defaultView.addEventListener("mouseup", onMouseUp);
setContentEditableWrapper(node, true);
}
node.addEventListener("mouseout", onMouseLeave);
node.addEventListener("mousedown", onMouseDown);
return () => {
node.removeEventListener("mouseout", onMouseLeave);
defaultView.removeEventListener("mouseup", onMouseUp);
defaultView.cancelAnimationFrame(rafId2);
};
},
[
startMultiSelect2,
stopMultiSelect2,
isSelectionEnabled3,
hasSelectedBlock2
]
);
}
// packages/block-editor/build-module/components/writing-flow/use-selection-observer.mjs
var import_data44 = __toESM(require_data(), 1);
var import_compose27 = __toESM(require_compose(), 1);
var import_rich_text4 = __toESM(require_rich_text(), 1);
var import_dom45 = __toESM(require_dom(), 1);
var { ownsSelection } = unlock(import_rich_text4.privateApis);
function extractSelectionStartNode(selection2) {
const { anchorNode, anchorOffset } = selection2;
if (anchorNode.nodeType === anchorNode.TEXT_NODE) {
return anchorNode;
}
if (anchorOffset === 0) {
return anchorNode;
}
return anchorNode.childNodes[anchorOffset - 1];
}
function extractSelectionEndNode(selection2, isTripleClick) {
const { focusNode, focusOffset } = selection2;
if (focusNode.nodeType === focusNode.TEXT_NODE) {
return focusNode;
}
if (focusOffset === focusNode.childNodes.length) {
return focusNode;
}
if (focusOffset === 0 && (0, import_dom45.isSelectionForward)(selection2) && isTripleClick) {
return focusNode.previousSibling ?? focusNode.parentElement;
}
return focusNode.childNodes[focusOffset];
}
function findDepth(a2, b2) {
let depth = 0;
while (a2[depth] === b2[depth]) {
depth++;
}
return depth;
}
function getRichTextElement(node) {
const element = node.nodeType === node.ELEMENT_NODE ? node : node.parentElement;
return element?.closest("[data-wp-block-attribute-key]");
}
function useSelectionObserver() {
const { multiSelect: multiSelect2, selectBlock: selectBlock2, selectionChange: selectionChange2 } = (0, import_data44.useDispatch)(store);
const blockEditorSelectors = (0, import_data44.useSelect)(store);
const {
getBlockParents: getBlockParents2,
getBlockSelectionStart: getBlockSelectionStart2,
isMultiSelecting: isMultiSelecting3,
getSelectionStart: getSelectionStart2,
getSelectionEnd: getSelectionEnd2,
getSelectedBlockClientId: getSelectedBlockClientId2
} = blockEditorSelectors;
return (0, import_compose27.useRefEffect)(
(node) => {
const { ownerDocument: ownerDocument2 } = node;
const { defaultView } = ownerDocument2;
let isTripleClick = false;
function onMouseDown(event) {
isTripleClick = event.detail === 3;
setShiftClickInProgress(event.shiftKey);
}
function onKeyDown() {
isTripleClick = false;
setShiftClickInProgress(false);
}
function onSelectionChange(event) {
const selection2 = defaultView.getSelection();
if (!selection2.rangeCount) {
return;
}
const startNode = extractSelectionStartNode(selection2);
const endNode = extractSelectionEndNode(
selection2,
isTripleClick
);
if (!node.contains(startNode) || !node.contains(endNode)) {
return;
}
const isClickShift = event.shiftKey && event.type === "mouseup";
if (selection2.isCollapsed && !isClickShift) {
const collapsedClientId = getBlockClientId(startNode);
if (!isMultiSelecting3() && collapsedClientId && // Only keep the wrapper editable when the collapsed
// selection is in the block that is actually selected.
// A stale native selection may linger in a previously
// selected editable root block (e.g. Firefox does not
// always move it), which must not re-enable the wrapper
// after another block has been selected.
collapsedClientId === getSelectedBlockClientId2() && canHostEditableRoot(
blockEditorSelectors,
collapsedClientId
)) {
setContentEditableWrapper(node, true);
const { activeElement: activeElement2 } = ownerDocument2;
if (activeElement2 !== node && activeElement2?.isContentEditable && node.contains(activeElement2) && getBlockClientId(activeElement2) === collapsedClientId) {
node.focus();
}
return;
}
if (node.contentEditable === "true" && !isMultiSelecting3()) {
setContentEditableWrapper(node, false);
let element = startNode.nodeType === startNode.ELEMENT_NODE ? startNode : startNode.parentElement;
element = element?.closest("[contenteditable]");
element?.focus();
}
return;
}
let startClientId = getBlockClientId(startNode);
let endClientId = getBlockClientId(endNode);
if (isClickShift) {
const selectedClientId = getBlockSelectionStart2();
const clickedClientId = getBlockClientId(event.target);
const focusNodeIsNonSelectable = clickedClientId !== endClientId;
if (startClientId === endClientId && selection2.isCollapsed || !endClientId || focusNodeIsNonSelectable) {
endClientId = clickedClientId;
}
if (startClientId !== selectedClientId) {
startClientId = selectedClientId;
}
}
if (startClientId === void 0 && endClientId === void 0) {
setContentEditableWrapper(node, false);
return;
}
if (event.type === "mouseup" && !event.shiftKey && !isMultiSelecting3() && startClientId === endClientId) {
const clickedClientId = getBlockClientId(event.target);
if (clickedClientId && clickedClientId !== startClientId) {
selection2.removeAllRanges();
return;
}
}
const isSingularSelection = startClientId === endClientId;
if (isSingularSelection) {
if (!isMultiSelecting3()) {
const richTextElement = !selection2.isCollapsed && (getRichTextElement(startNode) || getRichTextElement(endNode));
if (richTextElement && // The rich text instance syncs the selection
// itself when its element is editable and owns the
// selection (also through a focused editing host).
// It may be temporarily non-editable while a drag
// that started outside it is in progress (see
// rich-text's preventFocusCapture).
(richTextElement.contentEditable !== "true" || ownerDocument2.activeElement !== richTextElement && !ownsSelection(richTextElement))) {
const range2 = selection2.getRangeAt(0);
const richTextData = (0, import_rich_text4.create)({
element: richTextElement,
range: range2,
__unstableIsEditableTree: true
});
const selectionUpdate = {
start: {
clientId: startClientId,
attributeKey: richTextElement.dataset.wpBlockAttributeKey,
offset: richTextData.start ?? 0
},
end: {
clientId: startClientId,
attributeKey: richTextElement.dataset.wpBlockAttributeKey,
// Clamp the end offset to the element. A
// forward selection can overshoot past the
// rich text (e.g. a triple click extends
// into the next block at offset 0), leaving
// `end` undefined; that means the selection
// reaches through the end of this element's
// content.
offset: richTextData.end ?? richTextData.text.length
}
};
const { start: start2, end } = selectionUpdate;
const selectionStart = getSelectionStart2();
const selectionEnd = getSelectionEnd2();
if (selectionStart.clientId !== start2.clientId || selectionEnd.clientId !== end.clientId || selectionStart.attributeKey !== start2.attributeKey || selectionStart.offset !== start2.offset || selectionEnd.offset !== end.offset) {
selectionChange2(selectionUpdate);
}
} else {
selectBlock2(startClientId);
}
} else {
multiSelect2(startClientId, startClientId);
}
} else {
const startPath = [
...getBlockParents2(startClientId),
startClientId
];
const endPath = [
...getBlockParents2(endClientId),
endClientId
];
const depth = findDepth(startPath, endPath);
if (startPath[depth] !== startClientId || endPath[depth] !== endClientId) {
multiSelect2(startPath[depth], endPath[depth]);
return;
}
const richTextElementStart = getRichTextElement(startNode);
const richTextElementEnd = getRichTextElement(endNode);
if (richTextElementStart && richTextElementEnd) {
const range2 = selection2.getRangeAt(0);
const richTextDataStart = (0, import_rich_text4.create)({
element: richTextElementStart,
range: range2,
__unstableIsEditableTree: true
});
const richTextDataEnd = (0, import_rich_text4.create)({
element: richTextElementEnd,
range: range2,
__unstableIsEditableTree: true
});
const startOffset = richTextDataStart.start ?? richTextDataStart.end;
const endOffset = richTextDataEnd.start ?? richTextDataEnd.end;
selectionChange2({
start: {
clientId: startClientId,
attributeKey: richTextElementStart.dataset.wpBlockAttributeKey,
offset: startOffset
},
end: {
clientId: endClientId,
attributeKey: richTextElementEnd.dataset.wpBlockAttributeKey,
offset: endOffset
}
});
} else {
multiSelect2(startClientId, endClientId);
}
}
}
function ensureMultiBlockSelectionSync(event) {
const selection2 = defaultView.getSelection();
if (!selection2.rangeCount || selection2.isCollapsed) {
return;
}
const startClientId = getBlockClientId(
extractSelectionStartNode(selection2)
);
const endClientId = getBlockClientId(
extractSelectionEndNode(selection2, isTripleClick)
);
if (startClientId !== endClientId) {
onSelectionChange(event);
}
}
ownerDocument2.addEventListener(
"selectionchange",
onSelectionChange
);
function onMouseUp(event) {
onSelectionChange(event);
setShiftClickInProgress(false);
}
defaultView.addEventListener("mouseup", onMouseUp);
node.addEventListener("mousedown", onMouseDown);
node.addEventListener("keydown", onKeyDown);
ownerDocument2.addEventListener(
"copy",
ensureMultiBlockSelectionSync,
true
);
ownerDocument2.addEventListener(
"cut",
ensureMultiBlockSelectionSync,
true
);
ownerDocument2.addEventListener(
"paste",
ensureMultiBlockSelectionSync,
true
);
return () => {
ownerDocument2.removeEventListener(
"selectionchange",
onSelectionChange
);
defaultView.removeEventListener("mouseup", onMouseUp);
node.removeEventListener("mousedown", onMouseDown);
node.removeEventListener("keydown", onKeyDown);
ownerDocument2.removeEventListener(
"copy",
ensureMultiBlockSelectionSync,
true
);
ownerDocument2.removeEventListener(
"cut",
ensureMultiBlockSelectionSync,
true
);
ownerDocument2.removeEventListener(
"paste",
ensureMultiBlockSelectionSync,
true
);
};
},
[multiSelect2, selectBlock2, selectionChange2, getBlockParents2]
);
}
// packages/block-editor/build-module/components/writing-flow/use-click-selection.mjs
var import_data45 = __toESM(require_data(), 1);
var import_compose28 = __toESM(require_compose(), 1);
function useClickSelection() {
const { selectBlock: selectBlock2 } = (0, import_data45.useDispatch)(store);
const { isSelectionEnabled: isSelectionEnabled3, getBlockSelectionStart: getBlockSelectionStart2, hasMultiSelection: hasMultiSelection2 } = (0, import_data45.useSelect)(store);
return (0, import_compose28.useRefEffect)(
(node) => {
function onMouseDown(event) {
if (!isSelectionEnabled3() || event.button !== 0) {
return;
}
const startClientId = getBlockSelectionStart2();
const clickedClientId = getBlockClientId(event.target);
if (event.shiftKey) {
if (startClientId && startClientId !== clickedClientId) {
setContentEditableWrapper(node, true);
}
} else if (hasMultiSelection2()) {
selectBlock2(clickedClientId);
}
}
node.addEventListener("mousedown", onMouseDown);
return () => {
node.removeEventListener("mousedown", onMouseDown);
};
},
[
selectBlock2,
isSelectionEnabled3,
getBlockSelectionStart2,
hasMultiSelection2
]
);
}
// packages/block-editor/build-module/components/writing-flow/use-input.mjs
var import_data46 = __toESM(require_data(), 1);
var import_compose29 = __toESM(require_compose(), 1);
var import_keycodes7 = __toESM(require_keycodes(), 1);
var import_blocks28 = __toESM(require_blocks(), 1);
function useInput() {
const {
__unstableIsFullySelected: __unstableIsFullySelected2,
getSelectedBlockClientIds: getSelectedBlockClientIds2,
getSelectedBlockClientId: getSelectedBlockClientId2,
__unstableIsSelectionMergeable: __unstableIsSelectionMergeable2,
hasMultiSelection: hasMultiSelection2,
getBlockName: getBlockName2,
canInsertBlockType: canInsertBlockType2,
getBlockRootClientId: getBlockRootClientId2,
getSelectionStart: getSelectionStart2,
getSelectionEnd: getSelectionEnd2,
getBlockAttributes: getBlockAttributes3
} = (0, import_data46.useSelect)(store);
const {
replaceBlocks: replaceBlocks2,
__unstableSplitSelection: __unstableSplitSelection2,
removeBlocks: removeBlocks2,
__unstableDeleteSelection: __unstableDeleteSelection2,
__unstableExpandSelection: __unstableExpandSelection2,
__unstableMarkAutomaticChange: __unstableMarkAutomaticChange2
} = (0, import_data46.useDispatch)(store);
return (0, import_compose29.useRefEffect)((node) => {
function onBeforeInput(event) {
if (node.contentEditable !== "true") {
return;
}
if (hasMultiSelection2()) {
event.preventDefault();
return;
}
const selection2 = node.ownerDocument.defaultView.getSelection();
if (!getSelectionEditableElement(selection2, node)) {
event.preventDefault();
}
}
function onKeyDown(event) {
if (event.defaultPrevented) {
return;
}
if (!hasMultiSelection2()) {
if (event.keyCode === import_keycodes7.ENTER) {
if (event.shiftKey || __unstableIsFullySelected2()) {
return;
}
const clientId = getSelectedBlockClientId2();
const blockName = getBlockName2(clientId);
const selectionStart = getSelectionStart2();
const selectionEnd = getSelectionEnd2();
if (selectionStart.attributeKey === selectionEnd.attributeKey) {
const selectedAttributeValue = getBlockAttributes3(clientId)[selectionStart.attributeKey];
const transforms = (0, import_blocks28.getBlockTransforms)("from").filter(
({ type }) => type === "enter"
);
const transformation = (0, import_blocks28.findTransform)(
transforms,
(item) => {
return item.regExp.test(
selectedAttributeValue
);
}
);
if (transformation) {
replaceBlocks2(
clientId,
transformation.transform({
content: selectedAttributeValue
})
);
__unstableMarkAutomaticChange2();
return;
}
}
if (!(0, import_blocks28.hasBlockSupport)(blockName, "splitting", false) && !event.__deprecatedOnSplit) {
return;
}
if (canInsertBlockType2(
(0, import_blocks28.getDefaultBlockName)(),
getBlockRootClientId2(clientId)
) || canInsertBlockType2(
blockName,
getBlockRootClientId2(clientId)
)) {
__unstableSplitSelection2();
event.preventDefault();
}
}
return;
}
if (event.keyCode === import_keycodes7.ENTER) {
setContentEditableWrapper(node, false);
event.preventDefault();
if (__unstableIsFullySelected2()) {
replaceBlocks2(
getSelectedBlockClientIds2(),
(0, import_blocks28.createBlock)((0, import_blocks28.getDefaultBlockName)())
);
} else {
__unstableSplitSelection2();
}
} else if (event.keyCode === import_keycodes7.BACKSPACE || event.keyCode === import_keycodes7.DELETE) {
setContentEditableWrapper(node, false);
event.preventDefault();
if (__unstableIsFullySelected2()) {
removeBlocks2(getSelectedBlockClientIds2());
} else if (__unstableIsSelectionMergeable2()) {
__unstableDeleteSelection2(event.keyCode === import_keycodes7.DELETE);
} else {
__unstableExpandSelection2();
}
} else if (
// If key.length is longer than 1, it's a control key that doesn't
// input anything.
event.key.length === 1 && !(event.metaKey || event.ctrlKey)
) {
setContentEditableWrapper(node, false);
if (__unstableIsSelectionMergeable2()) {
__unstableDeleteSelection2(event.keyCode === import_keycodes7.DELETE);
} else {
event.preventDefault();
node.ownerDocument.defaultView.getSelection().removeAllRanges();
}
}
}
function onCompositionStart(event) {
if (!hasMultiSelection2()) {
return;
}
setContentEditableWrapper(node, false);
if (__unstableIsSelectionMergeable2()) {
__unstableDeleteSelection2();
} else {
event.preventDefault();
node.ownerDocument.defaultView.getSelection().removeAllRanges();
}
}
node.addEventListener("beforeinput", onBeforeInput);
node.addEventListener("keydown", onKeyDown);
node.addEventListener("compositionstart", onCompositionStart);
return () => {
node.removeEventListener("beforeinput", onBeforeInput);
node.removeEventListener("keydown", onKeyDown);
node.removeEventListener("compositionstart", onCompositionStart);
};
}, []);
}
// packages/block-editor/build-module/components/writing-flow/use-clipboard-handler.mjs
var import_blocks30 = __toESM(require_blocks(), 1);
var import_dom49 = __toESM(require_dom(), 1);
var import_data48 = __toESM(require_data(), 1);
var import_compose30 = __toESM(require_compose(), 1);
// packages/block-editor/build-module/utils/use-notify-copy.mjs
var import_element92 = __toESM(require_element(), 1);
var import_blocks29 = __toESM(require_blocks(), 1);
var import_data47 = __toESM(require_data(), 1);
var import_i18n37 = __toESM(require_i18n(), 1);
var import_notices4 = __toESM(require_notices(), 1);
function useNotifyCopy() {
const { getBlockName: getBlockName2 } = (0, import_data47.useSelect)(store);
const { getBlockType: getBlockType29 } = (0, import_data47.useSelect)(import_blocks29.store);
const { createSuccessNotice } = (0, import_data47.useDispatch)(import_notices4.store);
return (0, import_element92.useCallback)(
(eventType, selectedBlockClientIds) => {
let notice = "";
if (eventType === "copyStyles") {
notice = (0, import_i18n37.__)("Styles copied to clipboard.");
} else if (selectedBlockClientIds.length === 1) {
const clientId = selectedBlockClientIds[0];
const title = getBlockType29(getBlockName2(clientId))?.title;
if (eventType === "copy") {
notice = (0, import_i18n37.sprintf)(
// Translators: %s: Name of the block being copied, e.g. "Paragraph".
(0, import_i18n37.__)('Copied "%s" to clipboard.'),
title
);
} else {
notice = (0, import_i18n37.sprintf)(
// Translators: %s: Name of the block being cut, e.g. "Paragraph".
(0, import_i18n37.__)('Moved "%s" to clipboard.'),
title
);
}
} else if (eventType === "copy") {
notice = (0, import_i18n37.sprintf)(
// Translators: %d: Number of blocks being copied.
(0, import_i18n37._n)(
"Copied %d block to clipboard.",
"Copied %d blocks to clipboard.",
selectedBlockClientIds.length
),
selectedBlockClientIds.length
);
} else {
notice = (0, import_i18n37.sprintf)(
// Translators: %d: Number of blocks being moved.
(0, import_i18n37._n)(
"Moved %d block to clipboard.",
"Moved %d blocks to clipboard.",
selectedBlockClientIds.length
),
selectedBlockClientIds.length
);
}
createSuccessNotice(notice, {
type: "snackbar"
});
},
[createSuccessNotice, getBlockName2, getBlockType29]
);
}
// packages/block-editor/build-module/components/writing-flow/use-clipboard-handler.mjs
function useClipboardHandler() {
const registry = (0, import_data48.useRegistry)();
const {
getBlocksByClientId: getBlocksByClientId2,
getSelectedBlockClientIds: getSelectedBlockClientIds2,
hasMultiSelection: hasMultiSelection2,
getSettings: getSettings7,
getBlockName: getBlockName2,
__unstableIsFullySelected: __unstableIsFullySelected2,
__unstableIsSelectionCollapsed: __unstableIsSelectionCollapsed2,
__unstableIsSelectionMergeable: __unstableIsSelectionMergeable2,
__unstableGetSelectedBlocksWithPartialSelection: __unstableGetSelectedBlocksWithPartialSelection2,
canInsertBlockType: canInsertBlockType2,
getBlockRootClientId: getBlockRootClientId2
} = (0, import_data48.useSelect)(store);
const {
flashBlock: flashBlock2,
removeBlocks: removeBlocks2,
replaceBlocks: replaceBlocks2,
__unstableDeleteSelection: __unstableDeleteSelection2,
__unstableExpandSelection: __unstableExpandSelection2,
__unstableSplitSelection: __unstableSplitSelection2
} = (0, import_data48.useDispatch)(store);
const notifyCopy = useNotifyCopy();
return (0, import_compose30.useRefEffect)((node) => {
function handler(event) {
if (event.defaultPrevented) {
return;
}
const selectedBlockClientIds = getSelectedBlockClientIds2();
if (selectedBlockClientIds.length === 0) {
return;
}
if (!hasMultiSelection2()) {
const { target } = event;
const { ownerDocument: ownerDocument2 } = target;
const hasSelection = event.type === "copy" || event.type === "cut" ? (0, import_dom49.documentHasUncollapsedSelection)(ownerDocument2) : (0, import_dom49.documentHasSelection)(ownerDocument2) && !ownerDocument2.activeElement.isContentEditable;
if (hasSelection) {
return;
}
}
const { activeElement: activeElement2 } = event.target.ownerDocument;
if (!node.contains(activeElement2)) {
return;
}
const isSelectionMergeable = __unstableIsSelectionMergeable2();
const shouldHandleWholeBlocks = __unstableIsSelectionCollapsed2() || __unstableIsFullySelected2();
const expandSelectionIsNeeded = !shouldHandleWholeBlocks && !isSelectionMergeable;
if (event.type === "copy" || event.type === "cut") {
event.preventDefault();
if (selectedBlockClientIds.length === 1) {
flashBlock2(selectedBlockClientIds[0]);
}
if (expandSelectionIsNeeded) {
__unstableExpandSelection2();
} else {
notifyCopy(event.type, selectedBlockClientIds);
let blocks2;
if (shouldHandleWholeBlocks) {
blocks2 = getBlocksByClientId2(selectedBlockClientIds);
} else {
const [head, tail] = __unstableGetSelectedBlocksWithPartialSelection2();
const inBetweenBlocks = getBlocksByClientId2(
selectedBlockClientIds.slice(
1,
selectedBlockClientIds.length - 1
)
);
blocks2 = [head, ...inBetweenBlocks, tail];
}
setClipboardBlocks(event, blocks2, registry);
}
}
if (event.type === "cut") {
if (shouldHandleWholeBlocks && !expandSelectionIsNeeded) {
removeBlocks2(selectedBlockClientIds);
} else {
setContentEditableWrapper(
event.target.ownerDocument.activeElement,
false
);
__unstableDeleteSelection2();
}
} else if (event.type === "paste") {
const {
__experimentalCanUserUseUnfilteredHTML: canUserUseUnfilteredHTML,
mediaUpload: mediaUpload2
} = getSettings7();
const isInternal = event.clipboardData.getData("rich-text") === "true";
if (isInternal) {
return;
}
const { plainText, html, files } = getPasteEventData(event);
const isFullySelected = __unstableIsFullySelected2();
let blocks2 = [];
if (files.length) {
if (!mediaUpload2) {
event.preventDefault();
return;
}
const fromTransforms = (0, import_blocks30.getBlockTransforms)("from");
blocks2 = files.reduce((accumulator, file) => {
const transformation = (0, import_blocks30.findTransform)(
fromTransforms,
(transform) => transform.type === "files" && transform.isMatch([file])
);
if (transformation) {
accumulator.push(
transformation.transform([file])
);
}
return accumulator;
}, []).flat();
} else {
blocks2 = (0, import_blocks30.pasteHandler)({
HTML: html,
plainText,
mode: isFullySelected ? "BLOCKS" : "AUTO",
canUserUseUnfilteredHTML
});
}
if (typeof blocks2 === "string") {
return;
}
if (isFullySelected) {
replaceBlocks2(
selectedBlockClientIds,
blocks2,
blocks2.length - 1,
-1
);
event.preventDefault();
return;
}
if (!hasMultiSelection2() && !(0, import_blocks30.hasBlockSupport)(
getBlockName2(selectedBlockClientIds[0]),
"splitting",
false
) && !event.__deprecatedOnSplit) {
return;
}
const [firstSelectedClientId] = selectedBlockClientIds;
const rootClientId = getBlockRootClientId2(
firstSelectedClientId
);
const newBlocks = [];
for (const block of blocks2) {
if (canInsertBlockType2(block.name, rootClientId)) {
newBlocks.push(block);
} else {
const rootBlockName = getBlockName2(rootClientId);
const switchedBlocks = block.name !== rootBlockName ? (0, import_blocks30.switchToBlockType)(block, rootBlockName) : [block];
if (!switchedBlocks) {
return;
}
for (const switchedBlock of switchedBlocks) {
for (const innerBlock of switchedBlock.innerBlocks) {
newBlocks.push(innerBlock);
}
}
}
}
__unstableSplitSelection2(newBlocks);
event.preventDefault();
}
}
node.ownerDocument.addEventListener("copy", handler);
node.ownerDocument.addEventListener("cut", handler);
node.ownerDocument.addEventListener("paste", handler);
return () => {
node.ownerDocument.removeEventListener("copy", handler);
node.ownerDocument.removeEventListener("cut", handler);
node.ownerDocument.removeEventListener("paste", handler);
};
}, []);
}
// packages/block-editor/build-module/components/writing-flow/index.mjs
var import_jsx_runtime219 = __toESM(require_jsx_runtime(), 1);
function useWritingFlow() {
const [before, ref, after] = useTabNav();
const hasMultiSelection2 = (0, import_data49.useSelect)(
(select3) => select3(store).hasMultiSelection(),
[]
);
return [
before,
(0, import_compose31.useMergeRefs)([
ref,
useClipboardHandler(),
useInput(),
useEditableRoot(),
useHomeEnd(),
useDragSelection(),
useSelectionObserver(),
useClickSelection(),
useMultiSelection(),
useSelectAll(),
useArrowNav(),
usePreviewModeNav(),
(0, import_compose31.useRefEffect)(
(node) => {
node.tabIndex = 0;
node.dataset.hasMultiSelection = hasMultiSelection2;
if (!hasMultiSelection2) {
return () => {
delete node.dataset.hasMultiSelection;
};
}
node.setAttribute(
"aria-label",
(0, import_i18n38.__)("Multiple selected blocks")
);
return () => {
delete node.dataset.hasMultiSelection;
if (node.contentEditable === "true") {
node.setAttribute(
"aria-label",
(0, import_i18n38.__)("Editor canvas")
);
} else {
node.removeAttribute("aria-label");
}
};
},
[hasMultiSelection2]
)
]),
after
];
}
function WritingFlow({ children, ...props }, forwardedRef) {
const [before, ref, after] = useWritingFlow();
return /* @__PURE__ */ (0, import_jsx_runtime219.jsxs)(import_jsx_runtime219.Fragment, { children: [
before,
/* @__PURE__ */ (0, import_jsx_runtime219.jsx)(
"div",
{
...props,
ref: (0, import_compose31.useMergeRefs)([ref, forwardedRef]),
className: clsx_default(
props.className,
"block-editor-writing-flow"
),
children
}
),
after
] });
}
var writing_flow_default = (0, import_element93.forwardRef)(WritingFlow);
// packages/block-editor/build-module/components/iframe/get-compatibility-styles.mjs
var compatibilityStyles = null;
function getCompatibilityStyles() {
if (compatibilityStyles) {
return compatibilityStyles;
}
compatibilityStyles = Array.from(document.styleSheets).reduce(
(accumulator, styleSheet) => {
try {
styleSheet.cssRules;
} catch {
return accumulator;
}
const { ownerNode, cssRules } = styleSheet;
if (ownerNode === null) {
return accumulator;
}
if (!cssRules) {
return accumulator;
}
if (ownerNode.id.startsWith("wp-")) {
return accumulator;
}
if (!ownerNode.id) {
return accumulator;
}
function matchFromRules(_cssRules) {
return Array.from(_cssRules).find(
({
selectorText,
conditionText,
cssRules: __cssRules
}) => {
if (conditionText) {
return matchFromRules(__cssRules);
}
return selectorText && (selectorText.includes(
".editor-styles-wrapper"
) || selectorText.includes(".wp-block"));
}
);
}
if (matchFromRules(cssRules)) {
const isInline = ownerNode.tagName === "STYLE";
if (isInline) {
const mainStylesCssId = ownerNode.id.replace(
"-inline-css",
"-css"
);
const mainStylesElement = document.getElementById(mainStylesCssId);
if (mainStylesElement) {
accumulator.push(mainStylesElement.cloneNode(true));
}
}
accumulator.push(ownerNode.cloneNode(true));
if (!isInline) {
const inlineStylesCssId = ownerNode.id.replace(
"-css",
"-inline-css"
);
const inlineStylesElement = document.getElementById(inlineStylesCssId);
if (inlineStylesElement) {
accumulator.push(
inlineStylesElement.cloneNode(true)
);
}
}
}
return accumulator;
},
[]
);
return compatibilityStyles;
}
// packages/block-editor/build-module/components/iframe/use-scale-canvas.mjs
var import_element94 = __toESM(require_element(), 1);
var import_compose32 = __toESM(require_compose(), 1);
function calculateScale({
frameSize,
containerWidth,
maxContainerWidth,
scaleContainerWidth
}) {
return (Math.min(containerWidth, maxContainerWidth) - frameSize * 2) / scaleContainerWidth;
}
function computeScrollHeightNext(transitionFrom, transitionTo) {
const { scaleValue: prevScale, scrollHeight: prevScrollHeight } = transitionFrom;
const { frameSize, scaleValue } = transitionTo;
return prevScrollHeight * (scaleValue / prevScale) + frameSize * 2;
}
function computeScrollTopNext(transitionFrom, transitionTo) {
const {
containerHeight: prevContainerHeight,
frameSize: prevFrameSize,
scaleValue: prevScale,
scrollTop: prevScrollTop
} = transitionFrom;
const { containerHeight, frameSize, scaleValue, scrollHeight } = transitionTo;
let scrollTopNext = prevScrollTop;
scrollTopNext = (scrollTopNext + prevContainerHeight / 2 - prevFrameSize) / prevScale - prevContainerHeight / 2;
scrollTopNext = (scrollTopNext + containerHeight / 2) * scaleValue + frameSize - containerHeight / 2;
scrollTopNext = prevScrollTop <= prevFrameSize ? 0 : scrollTopNext;
const maxScrollTop = scrollHeight - containerHeight;
return Math.round(
Math.min(Math.max(0, scrollTopNext), Math.max(0, maxScrollTop))
);
}
function getAnimationKeyframes(transitionFrom, transitionTo) {
const {
scaleValue: prevScale,
frameSize: prevFrameSize,
scrollTop
} = transitionFrom;
const { scaleValue, frameSize, scrollTop: scrollTopNext } = transitionTo;
return [
{
translate: `0 0`,
scale: prevScale,
paddingTop: `${prevFrameSize / prevScale}px`,
paddingBottom: `${prevFrameSize / prevScale}px`
},
{
translate: `0 ${scrollTop - scrollTopNext}px`,
scale: scaleValue,
paddingTop: `${frameSize / scaleValue}px`,
paddingBottom: `${frameSize / scaleValue}px`
}
];
}
function useScaleCanvas({
frameSize,
iframeDocument,
maxContainerWidth = 750,
scale
}) {
const [contentResizeListener, { height: contentHeight }] = (0, import_compose32.useResizeObserver)();
const [
containerResizeListener,
{ width: containerWidth, height: containerHeight }
] = (0, import_compose32.useResizeObserver)();
const initialContainerWidthRef = (0, import_element94.useRef)(0);
const isZoomedOut = scale !== 1;
const prefersReducedMotion = (0, import_compose32.useReducedMotion)();
const isAutoScaled = scale === "auto-scaled";
const startAnimationRef = (0, import_element94.useRef)(false);
const animationRef = (0, import_element94.useRef)(null);
(0, import_element94.useEffect)(() => {
if (!isZoomedOut) {
initialContainerWidthRef.current = containerWidth;
}
}, [containerWidth, isZoomedOut]);
const scaleContainerWidth = Math.max(
initialContainerWidthRef.current,
containerWidth
);
const scaleValue = isAutoScaled ? calculateScale({
frameSize,
containerWidth,
maxContainerWidth,
scaleContainerWidth
}) : scale;
const transitionFromRef = (0, import_element94.useRef)({
scaleValue,
frameSize,
containerHeight: 0,
scrollTop: 0,
scrollHeight: 0
});
const transitionToRef = (0, import_element94.useRef)({
scaleValue,
frameSize,
containerHeight: 0,
scrollTop: 0,
scrollHeight: 0
});
const startZoomOutAnimation = (0, import_element94.useCallback)(() => {
const { scrollTop } = transitionFromRef.current;
const { scrollTop: scrollTopNext } = transitionToRef.current;
iframeDocument.documentElement.style.setProperty(
"--wp-block-editor-iframe-zoom-out-scroll-top",
`${scrollTop}px`
);
iframeDocument.documentElement.style.setProperty(
"--wp-block-editor-iframe-zoom-out-scroll-top-next",
`${scrollTopNext}px`
);
iframeDocument.documentElement.style.setProperty(
"--wp-block-editor-iframe-zoom-out-overflow-behavior",
transitionFromRef.current.scrollHeight === transitionFromRef.current.containerHeight ? "auto" : "scroll"
);
iframeDocument.documentElement.classList.add("zoom-out-animation");
return iframeDocument.documentElement.animate(
getAnimationKeyframes(
transitionFromRef.current,
transitionToRef.current
),
{
easing: "cubic-bezier(0.46, 0.03, 0.52, 0.96)",
duration: 400
}
);
}, [iframeDocument]);
const finishZoomOutAnimation = (0, import_element94.useCallback)(() => {
startAnimationRef.current = false;
animationRef.current = null;
iframeDocument.documentElement.style.setProperty(
"--wp-block-editor-iframe-zoom-out-scale",
transitionToRef.current.scaleValue
);
iframeDocument.documentElement.style.setProperty(
"--wp-block-editor-iframe-zoom-out-frame-size",
`${transitionToRef.current.frameSize}px`
);
iframeDocument.documentElement.classList.remove("zoom-out-animation");
iframeDocument.documentElement.scrollTop = transitionToRef.current.scrollTop;
iframeDocument.documentElement.style.removeProperty(
"--wp-block-editor-iframe-zoom-out-scroll-top"
);
iframeDocument.documentElement.style.removeProperty(
"--wp-block-editor-iframe-zoom-out-scroll-top-next"
);
iframeDocument.documentElement.style.removeProperty(
"--wp-block-editor-iframe-zoom-out-overflow-behavior"
);
transitionFromRef.current = transitionToRef.current;
}, [iframeDocument]);
const previousIsZoomedOut = (0, import_element94.useRef)(false);
(0, import_element94.useEffect)(() => {
if (!iframeDocument) {
return;
}
const trigger = previousIsZoomedOut.current !== isZoomedOut;
previousIsZoomedOut.current = isZoomedOut;
if (!trigger) {
return;
}
startAnimationRef.current = true;
if (!isZoomedOut) {
return;
}
iframeDocument.documentElement.classList.add("is-zoomed-out");
return () => {
iframeDocument.documentElement.classList.remove("is-zoomed-out");
};
}, [iframeDocument, isZoomedOut]);
(0, import_element94.useEffect)(() => {
if (!iframeDocument) {
return;
}
if (isAutoScaled && transitionFromRef.current.scaleValue !== 1) {
transitionFromRef.current.scaleValue = calculateScale({
frameSize: transitionFromRef.current.frameSize,
containerWidth,
maxContainerWidth,
scaleContainerWidth: containerWidth
});
}
if (scaleValue < 1) {
if (!startAnimationRef.current) {
iframeDocument.documentElement.style.setProperty(
"--wp-block-editor-iframe-zoom-out-scale",
scaleValue
);
iframeDocument.documentElement.style.setProperty(
"--wp-block-editor-iframe-zoom-out-frame-size",
`${frameSize}px`
);
}
iframeDocument.documentElement.style.setProperty(
"--wp-block-editor-iframe-zoom-out-content-height",
`${contentHeight}px`
);
iframeDocument.documentElement.style.setProperty(
"--wp-block-editor-iframe-zoom-out-inner-height",
`${containerHeight}px`
);
iframeDocument.documentElement.style.setProperty(
"--wp-block-editor-iframe-zoom-out-container-width",
`${containerWidth}px`
);
iframeDocument.documentElement.style.setProperty(
"--wp-block-editor-iframe-zoom-out-scale-container-width",
`${scaleContainerWidth}px`
);
}
if (startAnimationRef.current) {
startAnimationRef.current = false;
if (animationRef.current) {
animationRef.current.reverse();
const tempTransitionFrom = transitionFromRef.current;
const tempTransitionTo = transitionToRef.current;
transitionFromRef.current = tempTransitionTo;
transitionToRef.current = tempTransitionFrom;
} else {
transitionFromRef.current.scrollTop = iframeDocument.documentElement.scrollTop;
transitionFromRef.current.scrollHeight = iframeDocument.documentElement.scrollHeight;
transitionFromRef.current.containerHeight = containerHeight;
transitionToRef.current = {
scaleValue,
frameSize,
containerHeight: iframeDocument.documentElement.clientHeight
// use clientHeight to get the actual height of the new container after zoom state changes have rendered, as it will be the most up-to-date.
};
transitionToRef.current.scrollHeight = computeScrollHeightNext(
transitionFromRef.current,
transitionToRef.current
);
transitionToRef.current.scrollTop = computeScrollTopNext(
transitionFromRef.current,
transitionToRef.current
);
animationRef.current = startZoomOutAnimation();
if (prefersReducedMotion) {
finishZoomOutAnimation();
} else {
animationRef.current.onfinish = finishZoomOutAnimation;
}
}
}
}, [
startZoomOutAnimation,
finishZoomOutAnimation,
prefersReducedMotion,
isAutoScaled,
scaleValue,
frameSize,
iframeDocument,
contentHeight,
containerWidth,
containerHeight,
maxContainerWidth,
scaleContainerWidth
]);
return {
isZoomedOut,
scaleContainerWidth,
contentResizeListener,
containerResizeListener
};
}
// packages/block-editor/build-module/components/iframe/index.mjs
var import_jsx_runtime220 = __toESM(require_jsx_runtime(), 1);
function bubbleEvent(event, Constructor, frame) {
const init = {};
for (const key in event) {
init[key] = event[key];
}
if (event instanceof frame.contentDocument.defaultView.MouseEvent) {
const rect = frame.getBoundingClientRect();
init.clientX += rect.left;
init.clientY += rect.top;
}
const newEvent = new Constructor(event.type, init);
if (init.defaultPrevented) {
newEvent.preventDefault();
}
const cancelled = !frame.dispatchEvent(newEvent);
if (cancelled) {
event.preventDefault();
}
}
function useBubbleEvents(iframeDocument) {
return (0, import_compose33.useRefEffect)(() => {
const { defaultView } = iframeDocument;
if (!defaultView) {
return;
}
const { frameElement } = defaultView;
const html = iframeDocument.documentElement;
const eventTypes = ["dragover", "mousemove"];
const handlers = {};
for (const name of eventTypes) {
handlers[name] = (event) => {
const prototype = Object.getPrototypeOf(event);
const constructorName = prototype.constructor.name;
const Constructor = window[constructorName];
bubbleEvent(event, Constructor, frameElement);
};
html.addEventListener(name, handlers[name]);
}
return () => {
for (const name of eventTypes) {
html.removeEventListener(name, handlers[name]);
}
};
});
}
var iframeSrcCache = /* @__PURE__ */ new WeakMap();
var iframeSrcCleanup = globalThis.FinalizationRegistry ? new globalThis.FinalizationRegistry(
(url) => URL.revokeObjectURL(url)
) : void 0;
function getIframeSrc(resolvedAssets) {
let src = iframeSrcCache.get(resolvedAssets);
if (src) {
return src;
}
let body = "";
if (import_react14.version.split(".")[0] === "18") {
body = "<body><script>document.currentScript.parentElement.remove()<\/script></body>";
}
const html = `<!doctype html>
<html>
<head>
<meta charset="utf-8">
<base href="${window.location.href}">
<style>
html{
height: auto !important;
min-height: 100%;
}
/* Lowest specificity to not override global styles */
:where(body) {
margin: 0;
/* Default background color in case zoom out mode background
colors the html element */
background-color: white;
}
</style>
${resolvedAssets.styles ?? ""}
${resolvedAssets.scripts ?? ""}
</head>
${body}
</html>`;
src = URL.createObjectURL(new Blob([html], { type: "text/html" }));
iframeSrcCache.set(resolvedAssets, src);
iframeSrcCleanup?.register(resolvedAssets, src);
return src;
}
function Iframe({
contentRef,
children,
tabIndex = 0,
scale = 1,
frameSize = 0,
readonly,
forwardedRef: ref,
title = (0, import_i18n39.__)("Editor canvas"),
...props
}) {
const { resolvedAssets, isPreviewMode } = (0, import_data50.useSelect)((select3) => {
const settings2 = select3(store).getSettings();
return {
resolvedAssets: settings2.__unstableResolvedAssets,
isPreviewMode: settings2.isPreviewMode
};
}, []);
const [iframeDocument, setIframeDocument] = (0, import_element95.useState)();
const [bodyClasses, setBodyClasses] = (0, import_element95.useState)([]);
const [before, writingFlowRef, after] = useWritingFlow();
const setRef = (0, import_compose33.useRefEffect)((node) => {
let iFrameDocument;
function preventFileDropDefault(event) {
event.preventDefault();
}
function interceptLinkClicks(event) {
if (event.target.tagName === "A" && event.target.getAttribute("href")?.startsWith("#")) {
event.preventDefault();
iFrameDocument.defaultView.location.hash = event.target.getAttribute("href").slice(1);
}
}
const { ownerDocument: ownerDocument2 } = node;
setBodyClasses(
Array.from(ownerDocument2.body.classList).filter(
(name) => name.startsWith("admin-color-") || name.startsWith("post-type-") || name === "wp-embed-responsive"
)
);
function onLoad() {
const { contentDocument } = node;
const { documentElement } = contentDocument;
iFrameDocument = contentDocument;
setIframeDocument(contentDocument);
documentElement.classList.add("block-editor-iframe__html");
contentDocument.dir = ownerDocument2.dir;
for (const compatStyle of getCompatibilityStyles()) {
if (contentDocument.getElementById(compatStyle.id)) {
continue;
}
contentDocument.head.appendChild(
compatStyle.cloneNode(true)
);
if (!isPreviewMode) {
console.warn(
`${compatStyle.id} was added to the iframe incorrectly. Please use block.json or enqueue_block_assets to add styles to the iframe.`,
compatStyle
);
}
}
iFrameDocument.addEventListener(
"dragover",
preventFileDropDefault,
false
);
iFrameDocument.addEventListener(
"drop",
preventFileDropDefault,
false
);
iFrameDocument.addEventListener("click", interceptLinkClicks);
}
node.addEventListener("load", onLoad);
return () => {
setIframeDocument(void 0);
node.removeEventListener("load", onLoad);
iFrameDocument?.removeEventListener(
"dragover",
preventFileDropDefault
);
iFrameDocument?.removeEventListener(
"drop",
preventFileDropDefault
);
iFrameDocument?.removeEventListener("click", interceptLinkClicks);
};
}, []);
const {
contentResizeListener,
containerResizeListener,
isZoomedOut,
scaleContainerWidth
} = useScaleCanvas({
scale,
frameSize: parseInt(frameSize),
iframeDocument
});
const disabledRef = (0, import_compose33.useDisabled)({ isDisabled: !readonly });
const unguardedBodyRef = (0, import_compose33.useMergeRefs)([
useBubbleEvents(iframeDocument),
contentRef,
writingFlowRef,
disabledRef
]);
const bodyRef = (0, import_compose33.useRefEffect)(
(node) => {
if (node.ownerDocument.defaultView) {
unguardedBodyRef(node);
return () => unguardedBodyRef(null);
}
return () => {
};
},
[unguardedBodyRef]
);
const src = getIframeSrc(resolvedAssets);
const shouldRenderFocusCaptureElements = tabIndex >= 0 && !isPreviewMode;
const iframe = /* @__PURE__ */ (0, import_jsx_runtime220.jsxs)(import_jsx_runtime220.Fragment, { children: [
shouldRenderFocusCaptureElements && before,
/* @__PURE__ */ (0, import_jsx_runtime220.jsx)(
"iframe",
{
...props,
style: {
...props.style,
height: props.style?.height,
border: 0
},
ref: (0, import_compose33.useMergeRefs)([ref, setRef]),
tabIndex,
src,
title,
onKeyDown: (event) => {
if (props.onKeyDown) {
props.onKeyDown(event);
}
if (event.currentTarget.ownerDocument !== event.target.ownerDocument) {
const { stopPropagation } = event.nativeEvent;
event.nativeEvent.stopPropagation = () => {
};
event.stopPropagation();
event.nativeEvent.stopPropagation = stopPropagation;
bubbleEvent(
event,
window.KeyboardEvent,
event.currentTarget
);
}
},
children: iframeDocument && (0, import_element95.createPortal)(
/* @__PURE__ */ (0, import_jsx_runtime220.jsxs)(
"body",
{
ref: bodyRef,
className: clsx_default(
"block-editor-iframe__body",
"editor-styles-wrapper",
...bodyClasses
),
children: [
contentResizeListener,
/* @__PURE__ */ (0, import_jsx_runtime220.jsx)(import_components32.__experimentalStyleProvider, { document: iframeDocument, children })
]
}
),
iframeDocument.documentElement
)
}
),
shouldRenderFocusCaptureElements && after
] });
return /* @__PURE__ */ (0, import_jsx_runtime220.jsxs)("div", { className: "block-editor-iframe__container", children: [
containerResizeListener,
/* @__PURE__ */ (0, import_jsx_runtime220.jsx)(
"div",
{
className: clsx_default(
"block-editor-iframe__scale-container",
isZoomedOut && "is-zoomed-out"
),
style: {
"--wp-block-editor-iframe-zoom-out-scale-container-width": isZoomedOut && `${scaleContainerWidth}px`
},
children: iframe
}
)
] });
}
function IframeIfReady(props, ref) {
const isInitialised = (0, import_data50.useSelect)(
(select3) => select3(store).getSettings().__internalIsInitialized,
[]
);
if (!isInitialised) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime220.jsx)(Iframe, { ...props, forwardedRef: ref });
}
var iframe_default = (0, import_element95.forwardRef)(IframeIfReady);
// packages/block-editor/build-module/components/editor-styles/index.mjs
var import_components33 = __toESM(require_components(), 1);
var import_element96 = __toESM(require_element(), 1);
var import_data51 = __toESM(require_data(), 1);
// node_modules/parsel-js/dist/parsel.js
var TOKENS = {
attribute: /\[\s*(?:(?<namespace>\*|[-\w\P{ASCII}]*)\|)?(?<name>[-\w\P{ASCII}]+)\s*(?:(?<operator>\W?=)\s*(?<value>.+?)\s*(\s(?<caseSensitive>[iIsS]))?\s*)?\]/gu,
id: /#(?<name>[-\w\P{ASCII}]+)/gu,
class: /\.(?<name>[-\w\P{ASCII}]+)/gu,
comma: /\s*,\s*/g,
combinator: /\s*[\s>+~]\s*/g,
"pseudo-element": /::(?<name>[-\w\P{ASCII}]+)(?:\((?<argument>¶*)\))?/gu,
"pseudo-class": /:(?<name>[-\w\P{ASCII}]+)(?:\((?<argument>¶*)\))?/gu,
universal: /(?:(?<namespace>\*|[-\w\P{ASCII}]*)\|)?\*/gu,
type: /(?:(?<namespace>\*|[-\w\P{ASCII}]*)\|)?(?<name>[-\w\P{ASCII}]+)/gu
// this must be last
};
var TRIM_TOKENS = /* @__PURE__ */ new Set(["combinator", "comma"]);
var getArgumentPatternByType = (type) => {
switch (type) {
case "pseudo-element":
case "pseudo-class":
return new RegExp(TOKENS[type].source.replace("(?<argument>\xB6*)", "(?<argument>.*)"), "gu");
default:
return TOKENS[type];
}
};
function gobbleParens(text, offset4) {
let nesting = 0;
let result = "";
for (; offset4 < text.length; offset4++) {
const char = text[offset4];
switch (char) {
case "(":
++nesting;
break;
case ")":
--nesting;
break;
}
result += char;
if (nesting === 0) {
return result;
}
}
return result;
}
function tokenizeBy(text, grammar = TOKENS) {
if (!text) {
return [];
}
const tokens = [text];
for (const [type, pattern] of Object.entries(grammar)) {
for (let i2 = 0; i2 < tokens.length; i2++) {
const token = tokens[i2];
if (typeof token !== "string") {
continue;
}
pattern.lastIndex = 0;
const match2 = pattern.exec(token);
if (!match2) {
continue;
}
const from = match2.index - 1;
const args = [];
const content = match2[0];
const before = token.slice(0, from + 1);
if (before) {
args.push(before);
}
args.push({
...match2.groups,
type,
content
});
const after = token.slice(from + content.length + 1);
if (after) {
args.push(after);
}
tokens.splice(i2, 1, ...args);
}
}
let offset4 = 0;
for (const token of tokens) {
switch (typeof token) {
case "string":
throw new Error(`Unexpected sequence ${token} found at index ${offset4}`);
case "object":
offset4 += token.content.length;
token.pos = [offset4 - token.content.length, offset4];
if (TRIM_TOKENS.has(token.type)) {
token.content = token.content.trim() || " ";
}
break;
}
}
return tokens;
}
var STRING_PATTERN = /(['"])([^\\\n]+?)\1/g;
var ESCAPE_PATTERN = /\\./g;
function tokenize(selector3, grammar = TOKENS) {
selector3 = selector3.trim();
if (selector3 === "") {
return [];
}
const replacements = [];
selector3 = selector3.replace(ESCAPE_PATTERN, (value, offset4) => {
replacements.push({ value, offset: offset4 });
return "\uE000".repeat(value.length);
});
selector3 = selector3.replace(STRING_PATTERN, (value, quote, content, offset4) => {
replacements.push({ value, offset: offset4 });
return `${quote}${"\uE001".repeat(content.length)}${quote}`;
});
{
let pos = 0;
let offset4;
while ((offset4 = selector3.indexOf("(", pos)) > -1) {
const value = gobbleParens(selector3, offset4);
replacements.push({ value, offset: offset4 });
selector3 = `${selector3.substring(0, offset4)}(${"\xB6".repeat(value.length - 2)})${selector3.substring(offset4 + value.length)}`;
pos = offset4 + value.length;
}
}
const tokens = tokenizeBy(selector3, grammar);
const changedTokens = /* @__PURE__ */ new Set();
for (const replacement of replacements.reverse()) {
for (const token of tokens) {
const { offset: offset4, value } = replacement;
if (!(token.pos[0] <= offset4 && offset4 + value.length <= token.pos[1])) {
continue;
}
const { content } = token;
const tokenOffset = offset4 - token.pos[0];
token.content = content.slice(0, tokenOffset) + value + content.slice(tokenOffset + value.length);
if (token.content !== content) {
changedTokens.add(token);
}
}
}
for (const token of changedTokens) {
const pattern = getArgumentPatternByType(token.type);
if (!pattern) {
throw new Error(`Unknown token type: ${token.type}`);
}
pattern.lastIndex = 0;
const match2 = pattern.exec(token.content);
if (!match2) {
throw new Error(`Unable to parse content for ${token.type}: ${token.content}`);
}
Object.assign(token, match2.groups);
}
return tokens;
}
function* flatten(node, parent) {
switch (node.type) {
case "list":
for (let child of node.list) {
yield* flatten(child, node);
}
break;
case "complex":
yield* flatten(node.left, node);
yield* flatten(node.right, node);
break;
case "compound":
yield* node.list.map((token) => [token, node]);
break;
default:
yield [node, parent];
}
}
function stringify(listOrNode) {
let tokens;
if (Array.isArray(listOrNode)) {
tokens = listOrNode;
} else {
tokens = [...flatten(listOrNode)].map(([token]) => token);
}
return tokens.map((token) => token.content).join("");
}
// packages/block-editor/build-module/utils/transform-styles/index.mjs
var import_processor = __toESM(require_processor(), 1);
var import_css_syntax_error = __toESM(require_css_syntax_error(), 1);
var import_postcss_prefix_selector = __toESM(require_postcss_prefix_selector(), 1);
var import_postcss_urlrebase = __toESM(require_postcss_urlrebase(), 1);
var cacheByWrapperSelector = /* @__PURE__ */ new Map();
var ROOT_SELECTOR_TOKENS = [
{ type: "type", content: "body" },
{ type: "type", content: "html" },
{ type: "pseudo-class", content: ":root" },
{ type: "pseudo-class", content: ":where(body)" },
{ type: "pseudo-class", content: ":where(:root)" },
{ type: "pseudo-class", content: ":where(html)" }
];
function prefixRootSelector(prefix2, selector3) {
const tokenized = tokenize(selector3);
const lastRootIndex = tokenized.findLastIndex(({ content, type }) => {
return ROOT_SELECTOR_TOKENS.some(
(rootSelector) => content === rootSelector.content && type === rootSelector.type
);
});
let insertionPoint2 = -1;
for (let i2 = lastRootIndex + 1; i2 < tokenized.length; i2++) {
if (tokenized[i2].type === "combinator") {
insertionPoint2 = i2;
break;
}
}
const tokenizedPrefix = tokenize(prefix2);
tokenized.splice(
// Insert at the insertion point, or the end.
insertionPoint2 === -1 ? tokenized.length : insertionPoint2,
0,
{
type: "combinator",
content: " ",
pos: [0, 0]
},
...tokenizedPrefix
);
return stringify(tokenized);
}
function transformStyle({ css, ignoredSelectors = [], baseURL }, wrapperSelector = "", transformOptions) {
if (!wrapperSelector && !baseURL) {
return css;
}
try {
const excludedSelectors = [
...ignoredSelectors,
...transformOptions?.ignoredSelectors ?? [],
wrapperSelector
];
return new import_processor.default(
[
wrapperSelector && (0, import_postcss_prefix_selector.default)({
prefix: wrapperSelector,
transform(prefix2, selector3, prefixedSelector) {
if (excludedSelectors.some(
(excludedSelector) => excludedSelector instanceof RegExp ? selector3.match(excludedSelector) : selector3.includes(excludedSelector)
)) {
return selector3;
}
const hasRootSelector = ROOT_SELECTOR_TOKENS.some(
(rootSelector) => selector3.startsWith(rootSelector.content)
);
if (hasRootSelector) {
return prefixRootSelector(prefix2, selector3);
}
return prefixedSelector;
}
}),
baseURL && (0, import_postcss_urlrebase.default)({ rootUrl: baseURL })
].filter(Boolean)
).process(css, {}).css;
} catch (error2) {
if (error2 instanceof import_css_syntax_error.default) {
console.warn(
"wp.blockEditor.transformStyles Failed to transform CSS.",
error2.message + "\n" + error2.showSourceCode(false)
);
} else {
console.warn(
"wp.blockEditor.transformStyles Failed to transform CSS.",
error2
);
}
return null;
}
}
var transformStyles = (styles, wrapperSelector = "", transformOptions) => {
let cache = cacheByWrapperSelector.get(wrapperSelector);
if (!cache) {
cache = /* @__PURE__ */ new WeakMap();
cacheByWrapperSelector.set(wrapperSelector, cache);
}
return styles.map((style) => {
let css = cache.get(style);
if (!css) {
css = transformStyle(style, wrapperSelector, transformOptions);
cache.set(style, css);
}
return css;
});
};
var transform_styles_default = transformStyles;
// packages/block-editor/build-module/components/editor-styles/index.mjs
var import_jsx_runtime221 = __toESM(require_jsx_runtime(), 1);
k([names_default, a11y_default]);
function useDarkThemeBodyClassName(styles, scope) {
return (0, import_element96.useCallback)(
(node) => {
if (!node) {
return;
}
const { ownerDocument: ownerDocument2 } = node;
const { defaultView, body } = ownerDocument2;
const canvas = scope ? ownerDocument2.querySelector(scope) : body;
let backgroundColor;
if (!canvas) {
const tempCanvas = ownerDocument2.createElement("div");
tempCanvas.classList.add("editor-styles-wrapper");
body.appendChild(tempCanvas);
backgroundColor = defaultView?.getComputedStyle(tempCanvas, null).getPropertyValue("background-color");
body.removeChild(tempCanvas);
} else {
backgroundColor = defaultView?.getComputedStyle(canvas, null).getPropertyValue("background-color");
}
const colordBackgroundColor = w(backgroundColor);
if (colordBackgroundColor.luminance() > 0.5 || colordBackgroundColor.alpha() === 0) {
body.classList.remove("is-dark-theme");
} else {
body.classList.add("is-dark-theme");
}
},
[styles, scope]
);
}
function EditorStyles({ styles, scope, transformOptions }) {
const overrides = (0, import_data51.useSelect)(
(select3) => unlock(select3(store)).getStyleOverrides(),
[]
);
const [transformedStyles, transformedSvgs] = (0, import_element96.useMemo)(() => {
const _styles = Object.values(styles ?? []);
for (const [id, override] of overrides) {
const index2 = _styles.findIndex(({ id: _id }) => id === _id);
const overrideWithId = { ...override, id };
if (index2 === -1) {
_styles.push(overrideWithId);
} else {
_styles[index2] = overrideWithId;
}
}
return [
transform_styles_default(
_styles.filter((style) => style?.css),
scope,
transformOptions
),
_styles.filter((style) => style.__unstableType === "svgs").map((style) => style.assets).join("")
];
}, [styles, overrides, scope, transformOptions]);
return /* @__PURE__ */ (0, import_jsx_runtime221.jsxs)(import_jsx_runtime221.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime221.jsx)(
"style",
{
ref: useDarkThemeBodyClassName(transformedStyles, scope)
}
),
transformedStyles.map((css, index2) => /* @__PURE__ */ (0, import_jsx_runtime221.jsx)("style", { children: css }, index2)),
/* @__PURE__ */ (0, import_jsx_runtime221.jsx)(
import_components33.SVG,
{
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 0 0",
width: "0",
height: "0",
role: "none",
style: {
visibility: "hidden",
position: "absolute",
left: "-9999px",
overflow: "hidden"
},
dangerouslySetInnerHTML: { __html: transformedSvgs }
}
)
] });
}
var editor_styles_default = (0, import_element96.memo)(EditorStyles);
// packages/block-editor/build-module/components/block-preview/auto.mjs
var import_jsx_runtime222 = __toESM(require_jsx_runtime(), 1);
var MemoizedBlockList = (0, import_element97.memo)(BlockList);
var MAX_HEIGHT = 2e3;
var EMPTY_ADDITIONAL_STYLES = [];
function ScaledBlockPreview({
viewportWidth,
containerWidth,
minHeight,
additionalStyles = EMPTY_ADDITIONAL_STYLES
}) {
if (!viewportWidth) {
viewportWidth = containerWidth;
}
const [contentResizeListener, { height: contentHeight }] = (0, import_compose34.useResizeObserver)();
const { styles } = (0, import_data52.useSelect)((select3) => {
const settings2 = select3(store).getSettings();
return {
styles: settings2.styles
};
}, []);
const editorStyles = (0, import_element97.useMemo)(() => {
if (styles) {
return [
...styles,
{
css: "body{height:auto;overflow:hidden;border:none;padding:0;}",
__unstableType: "presets"
},
...additionalStyles
];
}
return styles;
}, [styles, additionalStyles]);
const scale = containerWidth / viewportWidth;
const aspectRatio = contentHeight ? containerWidth / (contentHeight * scale) : 0;
return /* @__PURE__ */ (0, import_jsx_runtime222.jsx)(
import_components34.Disabled,
{
className: "block-editor-block-preview__content",
style: {
transform: `scale(${scale})`,
// Using width + aspect-ratio instead of height here triggers browsers' native
// handling of scrollbar's visibility. It prevents the flickering issue seen
// in https://github.com/WordPress/gutenberg/issues/52027.
// See https://github.com/WordPress/gutenberg/pull/52921 for more info.
aspectRatio,
maxHeight: contentHeight > MAX_HEIGHT ? MAX_HEIGHT * scale : void 0,
minHeight
},
children: /* @__PURE__ */ (0, import_jsx_runtime222.jsxs)(
iframe_default,
{
contentRef: (0, import_compose34.useRefEffect)((bodyElement) => {
const {
ownerDocument: { documentElement }
} = bodyElement;
documentElement.classList.add(
"block-editor-block-preview__content-iframe"
);
documentElement.style.position = "absolute";
documentElement.style.width = "100%";
bodyElement.style.boxSizing = "border-box";
bodyElement.style.position = "absolute";
bodyElement.style.width = "100%";
}, []),
"aria-hidden": true,
tabIndex: -1,
style: {
position: "absolute",
width: viewportWidth,
height: contentHeight,
pointerEvents: "none",
// This is a catch-all max-height for patterns.
// See: https://github.com/WordPress/gutenberg/pull/38175.
maxHeight: MAX_HEIGHT,
minHeight: scale !== 0 && scale < 1 && minHeight ? minHeight / scale : minHeight
},
children: [
/* @__PURE__ */ (0, import_jsx_runtime222.jsx)(editor_styles_default, { styles: editorStyles }),
contentResizeListener,
/* @__PURE__ */ (0, import_jsx_runtime222.jsx)(MemoizedBlockList, { renderAppender: false })
]
}
)
}
);
}
function AutoBlockPreview(props) {
const [containerResizeListener, { width: containerWidth }] = (0, import_compose34.useResizeObserver)();
return /* @__PURE__ */ (0, import_jsx_runtime222.jsxs)(import_jsx_runtime222.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime222.jsx)("div", { style: { position: "relative", width: "100%", height: 0 }, children: containerResizeListener }),
/* @__PURE__ */ (0, import_jsx_runtime222.jsx)("div", { className: "block-editor-block-preview__container", children: !!containerWidth && /* @__PURE__ */ (0, import_jsx_runtime222.jsx)(
ScaledBlockPreview,
{
...props,
containerWidth
}
) })
] });
}
// packages/block-editor/build-module/components/block-preview/async.mjs
var import_element98 = __toESM(require_element(), 1);
var import_priority_queue = __toESM(require_priority_queue(), 1);
var blockPreviewQueue = (0, import_priority_queue.createQueue)();
function Async({ children, placeholder }) {
const [shouldRender, setShouldRender] = (0, import_element98.useState)(false);
(0, import_element98.useEffect)(() => {
const context = {};
blockPreviewQueue.add(context, () => {
(0, import_element98.flushSync)(() => {
setShouldRender(true);
});
});
return () => {
blockPreviewQueue.cancel(context);
};
}, []);
if (!shouldRender) {
return placeholder;
}
return children;
}
// packages/block-editor/build-module/components/block-preview/index.mjs
var import_jsx_runtime223 = __toESM(require_jsx_runtime(), 1);
var EMPTY_ADDITIONAL_STYLES2 = [];
function BlockPreview({
blocks: blocks2,
viewportWidth = 1200,
minHeight,
additionalStyles = EMPTY_ADDITIONAL_STYLES2,
// Deprecated props:
__experimentalMinHeight,
__experimentalPadding
}) {
if (__experimentalMinHeight) {
minHeight = __experimentalMinHeight;
(0, import_deprecated7.default)("The __experimentalMinHeight prop", {
since: "6.2",
version: "6.4",
alternative: "minHeight"
});
}
if (__experimentalPadding) {
additionalStyles = [
...additionalStyles,
{ css: `body { padding: ${__experimentalPadding}px; }` }
];
(0, import_deprecated7.default)("The __experimentalPadding prop of BlockPreview", {
since: "6.2",
version: "6.4",
alternative: "additionalStyles"
});
}
const originalSettings = (0, import_data53.useSelect)(
(select3) => select3(store).getSettings(),
[]
);
const settings2 = (0, import_element99.useMemo)(
() => ({
...originalSettings,
focusMode: false,
// Disable "Spotlight mode".
isPreviewMode: true
}),
[originalSettings]
);
const renderedBlocks = (0, import_element99.useMemo)(
() => Array.isArray(blocks2) ? blocks2 : [blocks2],
[blocks2]
);
if (!blocks2 || blocks2.length === 0) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime223.jsx)(
ExperimentalBlockEditorProvider,
{
value: renderedBlocks,
settings: settings2,
children: /* @__PURE__ */ (0, import_jsx_runtime223.jsx)(
AutoBlockPreview,
{
viewportWidth,
minHeight,
additionalStyles
}
)
}
);
}
var MemoizedBlockPreview = (0, import_element99.memo)(BlockPreview);
MemoizedBlockPreview.Async = Async;
var block_preview_default = MemoizedBlockPreview;
function useBlockPreview({ blocks: blocks2, props = {}, layout }) {
const originalSettings = (0, import_data53.useSelect)(
(select3) => select3(store).getSettings(),
[]
);
const settings2 = (0, import_element99.useMemo)(
() => ({
...originalSettings,
styles: void 0,
// Clear styles included by the parent settings, as they are already output by the parent's EditorStyles.
focusMode: false,
// Disable "Spotlight mode".
isPreviewMode: true
}),
[originalSettings]
);
const disabledRef = (0, import_compose35.useDisabled)();
const ref = (0, import_compose35.useMergeRefs)([props.ref, disabledRef]);
const renderedBlocks = (0, import_element99.useMemo)(
() => Array.isArray(blocks2) ? blocks2 : [blocks2],
[blocks2]
);
const children = /* @__PURE__ */ (0, import_jsx_runtime223.jsxs)(
ExperimentalBlockEditorProvider,
{
value: renderedBlocks,
settings: settings2,
children: [
/* @__PURE__ */ (0, import_jsx_runtime223.jsx)(editor_styles_default, {}),
/* @__PURE__ */ (0, import_jsx_runtime223.jsx)(BlockListItems, { renderAppender: false, layout })
]
}
);
return {
...props,
ref,
className: clsx_default(
props.className,
"block-editor-block-preview__live-content",
"components-disabled"
),
children: blocks2?.length ? children : null
};
}
// packages/block-editor/build-module/components/inserter/preview-panel.mjs
var import_jsx_runtime224 = __toESM(require_jsx_runtime(), 1);
function InserterPreviewPanel({ item }) {
const { name, title, icon, description, initialAttributes, example } = item;
const isReusable = (0, import_blocks31.isReusableBlock)(item);
const blocks2 = (0, import_element100.useMemo)(() => {
if (!example) {
return (0, import_blocks31.createBlock)(name, initialAttributes);
}
return (0, import_blocks31.getBlockFromExample)(name, {
attributes: {
...example.attributes,
...initialAttributes
},
innerBlocks: example.innerBlocks,
innerContent: example.innerContent
});
}, [name, example, initialAttributes]);
const previewHeight = 144;
const sidebarWidth = 280;
const viewportWidth = example?.viewportWidth ?? 500;
const scale = sidebarWidth / viewportWidth;
const minHeight = scale !== 0 && scale < 1 && previewHeight ? previewHeight / scale : previewHeight;
return /* @__PURE__ */ (0, import_jsx_runtime224.jsxs)("div", { className: "block-editor-inserter__preview-container", children: [
/* @__PURE__ */ (0, import_jsx_runtime224.jsx)("div", { className: "block-editor-inserter__preview", children: isReusable || example ? /* @__PURE__ */ (0, import_jsx_runtime224.jsx)("div", { className: "block-editor-inserter__preview-content", children: /* @__PURE__ */ (0, import_jsx_runtime224.jsx)(
block_preview_default,
{
blocks: blocks2,
viewportWidth,
minHeight: previewHeight,
additionalStyles: (
//We want this CSS to be in sync with the one in BlockPreviewPanel.
[
{
css: `
body {
padding: 24px;
min-height:${Math.round(minHeight)}px;
display:flex;
align-items:center;
}
.is-root-container { width: 100%; }
`
}
]
)
}
) }) : /* @__PURE__ */ (0, import_jsx_runtime224.jsx)("div", { className: "block-editor-inserter__preview-content-missing", children: (0, import_i18n40.__)("No preview available.") }) }),
!isReusable && /* @__PURE__ */ (0, import_jsx_runtime224.jsx)(
block_card_default,
{
title,
icon,
description
}
)
] });
}
var preview_panel_default = InserterPreviewPanel;
// packages/block-editor/build-module/components/inserter/block-types-tab.mjs
var import_i18n44 = __toESM(require_i18n(), 1);
var import_element107 = __toESM(require_element(), 1);
var import_compose37 = __toESM(require_compose(), 1);
// packages/block-editor/build-module/components/block-types-list/index.mjs
var import_blocks34 = __toESM(require_blocks(), 1);
var import_compose36 = __toESM(require_compose(), 1);
// packages/block-editor/build-module/components/inserter-list-item/index.mjs
var import_element106 = __toESM(require_element(), 1);
var import_blocks33 = __toESM(require_blocks(), 1);
var import_components40 = __toESM(require_components(), 1);
var import_keycodes8 = __toESM(require_keycodes(), 1);
// packages/block-editor/build-module/components/inserter-listbox/index.mjs
var import_components37 = __toESM(require_components(), 1);
var import_element104 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/inserter-listbox/group.mjs
var import_element101 = __toESM(require_element(), 1);
var import_i18n41 = __toESM(require_i18n(), 1);
var import_a11y5 = __toESM(require_a11y(), 1);
var import_jsx_runtime225 = __toESM(require_jsx_runtime(), 1);
function InserterListboxGroup(props, ref) {
const [shouldSpeak, setShouldSpeak] = (0, import_element101.useState)(false);
(0, import_element101.useEffect)(() => {
if (shouldSpeak) {
(0, import_a11y5.speak)(
(0, import_i18n41.__)("Use left and right arrow keys to move through blocks")
);
}
}, [shouldSpeak]);
return /* @__PURE__ */ (0, import_jsx_runtime225.jsx)(
"div",
{
ref,
role: "listbox",
"aria-orientation": "horizontal",
onFocus: () => {
setShouldSpeak(true);
},
onBlur: (event) => {
const focusingOutsideGroup = !event.currentTarget.contains(
event.relatedTarget
);
if (focusingOutsideGroup) {
setShouldSpeak(false);
}
},
...props
}
);
}
var group_default2 = (0, import_element101.forwardRef)(InserterListboxGroup);
// packages/block-editor/build-module/components/inserter-listbox/row.mjs
var import_element102 = __toESM(require_element(), 1);
var import_components35 = __toESM(require_components(), 1);
var import_jsx_runtime226 = __toESM(require_jsx_runtime(), 1);
function InserterListboxRow(props, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime226.jsx)(import_components35.Composite.Group, { role: "presentation", ref, ...props });
}
var row_default2 = (0, import_element102.forwardRef)(InserterListboxRow);
// packages/block-editor/build-module/components/inserter-listbox/item.mjs
var import_components36 = __toESM(require_components(), 1);
var import_element103 = __toESM(require_element(), 1);
var import_jsx_runtime227 = __toESM(require_jsx_runtime(), 1);
function InserterListboxItem({ isFirst, as: Component6, children, ...props }, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime227.jsx)(
import_components36.Composite.Item,
{
ref,
role: "option",
accessibleWhenDisabled: true,
...props,
render: (htmlProps) => {
const propsWithTabIndex = {
...htmlProps,
tabIndex: isFirst ? 0 : htmlProps.tabIndex
};
if (Component6) {
return /* @__PURE__ */ (0, import_jsx_runtime227.jsx)(Component6, { ...propsWithTabIndex, children });
}
if (typeof children === "function") {
return children(propsWithTabIndex);
}
return /* @__PURE__ */ (0, import_jsx_runtime227.jsx)(import_components36.Button, { __next40pxDefaultSize: true, ...propsWithTabIndex, children });
}
}
);
}
var item_default = (0, import_element103.forwardRef)(InserterListboxItem);
// packages/block-editor/build-module/components/inserter-listbox/index.mjs
var import_jsx_runtime228 = __toESM(require_jsx_runtime(), 1);
function InserterListBoxWrapper({ key, children }) {
return /* @__PURE__ */ (0, import_jsx_runtime228.jsx)(import_element104.Fragment, { children }, key);
}
function InserterListbox({ children }) {
return /* @__PURE__ */ (0, import_jsx_runtime228.jsx)(
import_components37.Composite,
{
focusShift: true,
focusWrap: "horizontal",
render: InserterListBoxWrapper,
children
}
);
}
var inserter_listbox_default = InserterListbox;
// packages/block-editor/build-module/components/inserter-draggable-blocks/index.mjs
var import_components39 = __toESM(require_components(), 1);
var import_blocks32 = __toESM(require_blocks(), 1);
var import_data54 = __toESM(require_data(), 1);
var import_element105 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/block-draggable/draggable-chip.mjs
var import_i18n42 = __toESM(require_i18n(), 1);
var import_components38 = __toESM(require_components(), 1);
var import_jsx_runtime229 = __toESM(require_jsx_runtime(), 1);
function BlockDraggableChip({
count,
icon,
isPattern,
fadeWhenDisabled
}) {
const patternLabel = isPattern && (0, import_i18n42.__)("Pattern");
return /* @__PURE__ */ (0, import_jsx_runtime229.jsx)("div", { className: "block-editor-block-draggable-chip-wrapper", children: /* @__PURE__ */ (0, import_jsx_runtime229.jsx)(
"div",
{
className: "block-editor-block-draggable-chip",
"data-testid": "block-draggable-chip",
children: /* @__PURE__ */ (0, import_jsx_runtime229.jsxs)(
import_components38.Flex,
{
justify: "center",
className: "block-editor-block-draggable-chip__content",
children: [
/* @__PURE__ */ (0, import_jsx_runtime229.jsx)(import_components38.FlexItem, { children: icon ? /* @__PURE__ */ (0, import_jsx_runtime229.jsx)(block_icon_default, { icon }) : patternLabel || (0, import_i18n42.sprintf)(
/* translators: %d: Number of blocks. */
(0, import_i18n42._n)("%d block", "%d blocks", count),
count
) }),
/* @__PURE__ */ (0, import_jsx_runtime229.jsx)(import_components38.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime229.jsx)(block_icon_default, { icon: drag_handle_default }) }),
fadeWhenDisabled && /* @__PURE__ */ (0, import_jsx_runtime229.jsx)(import_components38.FlexItem, { className: "block-editor-block-draggable-chip__disabled", children: /* @__PURE__ */ (0, import_jsx_runtime229.jsx)("span", { className: "block-editor-block-draggable-chip__disabled-icon" }) })
]
}
)
}
) });
}
// packages/block-editor/build-module/components/inserter-draggable-blocks/index.mjs
var import_jsx_runtime230 = __toESM(require_jsx_runtime(), 1);
var InserterDraggableBlocks = ({
isEnabled,
blocks: blocks2,
icon,
children,
pattern
}) => {
const blockName = blocks2.length === 1 ? blocks2[0].name : void 0;
const blockTypeIcon = (0, import_data54.useSelect)(
(select3) => {
return blockName && select3(import_blocks32.store).getBlockType(blockName)?.icon;
},
[blockName]
);
const { startDragging: startDragging2, stopDragging: stopDragging2 } = unlock(
(0, import_data54.useDispatch)(store)
);
const patternBlock = (0, import_element105.useMemo)(() => {
return pattern?.type === INSERTER_PATTERN_TYPES.user && pattern?.syncStatus !== "unsynced" ? [(0, import_blocks32.createBlock)("core/block", { ref: pattern.id })] : void 0;
}, [pattern?.type, pattern?.syncStatus, pattern?.id]);
if (!isEnabled) {
return children({
draggable: false,
onDragStart: void 0,
onDragEnd: void 0
});
}
const draggableBlocks = patternBlock ?? blocks2;
return /* @__PURE__ */ (0, import_jsx_runtime230.jsx)(
import_components39.Draggable,
{
__experimentalTransferDataType: "wp-blocks",
transferData: { type: "inserter", blocks: draggableBlocks },
onDragStart: (event) => {
startDragging2();
const addedTypes = /* @__PURE__ */ new Set();
for (const block of draggableBlocks) {
const type = `wp-block:${block.name}`;
if (!addedTypes.has(type)) {
event.dataTransfer.items.add("", type);
addedTypes.add(type);
}
}
},
onDragEnd: () => {
stopDragging2();
},
__experimentalDragComponent: /* @__PURE__ */ (0, import_jsx_runtime230.jsx)(
BlockDraggableChip,
{
count: blocks2.length,
icon: icon || !pattern && blockTypeIcon,
isPattern: !!pattern
}
),
children: ({ onDraggableStart, onDraggableEnd }) => {
return children({
draggable: true,
onDragStart: onDraggableStart,
onDragEnd: onDraggableEnd
});
}
}
);
};
var inserter_draggable_blocks_default = InserterDraggableBlocks;
// packages/block-editor/build-module/components/inserter-list-item/index.mjs
var import_jsx_runtime231 = __toESM(require_jsx_runtime(), 1);
function InserterListItem({
className,
isFirst,
item,
onSelect,
onHover,
isDraggable,
...props
}) {
const isDraggingRef = (0, import_element106.useRef)(false);
const itemIconStyle = item.icon ? {
backgroundColor: item.icon.background,
color: item.icon.foreground
} : {};
const blocks2 = (0, import_element106.useMemo)(
() => [
(0, import_blocks33.createBlock)(
item.name,
item.initialAttributes,
(0, import_blocks33.createBlocksFromInnerBlocksTemplate)(item.innerBlocks),
item.innerContent
)
],
[
item.name,
item.initialAttributes,
item.innerBlocks,
item.innerContent
]
);
const isSynced = (0, import_blocks33.isReusableBlock)(item) && item.syncStatus !== "unsynced" || (0, import_blocks33.isTemplatePart)(item);
return /* @__PURE__ */ (0, import_jsx_runtime231.jsx)(
inserter_draggable_blocks_default,
{
isEnabled: isDraggable && !item.isDisabled,
blocks: blocks2,
icon: item.icon,
children: ({ draggable, onDragStart, onDragEnd }) => /* @__PURE__ */ (0, import_jsx_runtime231.jsx)(
"div",
{
className: clsx_default(
"block-editor-block-types-list__list-item",
{
"is-synced": isSynced
}
),
draggable,
onDragStart: (event) => {
isDraggingRef.current = true;
if (onDragStart) {
onHover(null);
onDragStart(event);
}
},
onDragEnd: (event) => {
isDraggingRef.current = false;
if (onDragEnd) {
onDragEnd(event);
}
},
children: /* @__PURE__ */ (0, import_jsx_runtime231.jsxs)(
item_default,
{
isFirst,
className: clsx_default(
"block-editor-block-types-list__item",
className
),
disabled: item.isDisabled,
onClick: (event) => {
event.preventDefault();
onSelect(
item,
(0, import_keycodes8.isAppleOS)() ? event.metaKey : event.ctrlKey
);
onHover(null);
},
onKeyDown: (event) => {
const { keyCode } = event;
if (keyCode === import_keycodes8.ENTER) {
event.preventDefault();
onSelect(
item,
(0, import_keycodes8.isAppleOS)() ? event.metaKey : event.ctrlKey
);
onHover(null);
}
},
onMouseEnter: () => {
if (isDraggingRef.current) {
return;
}
onHover(item);
},
onMouseLeave: () => onHover(null),
...props,
children: [
/* @__PURE__ */ (0, import_jsx_runtime231.jsx)(
"span",
{
className: "block-editor-block-types-list__item-icon",
style: itemIconStyle,
children: /* @__PURE__ */ (0, import_jsx_runtime231.jsx)(block_icon_default, { icon: item.icon, showColors: true })
}
),
/* @__PURE__ */ (0, import_jsx_runtime231.jsx)("span", { className: "block-editor-block-types-list__item-title", children: /* @__PURE__ */ (0, import_jsx_runtime231.jsx)(import_components40.__experimentalTruncate, { numberOfLines: 3, children: item.title }) })
]
}
)
}
)
}
);
}
var inserter_list_item_default = (0, import_element106.memo)(InserterListItem);
// packages/block-editor/build-module/components/block-types-list/index.mjs
var import_jsx_runtime232 = __toESM(require_jsx_runtime(), 1);
function chunk(array, size4) {
const chunks = [];
for (let i2 = 0, j2 = array.length; i2 < j2; i2 += size4) {
chunks.push(array.slice(i2, i2 + size4));
}
return chunks;
}
function BlockTypesList({
items = [],
onSelect,
onHover = () => {
},
children,
label,
isDraggable = true
}) {
const className = "block-editor-block-types-list";
const listId = (0, import_compose36.useInstanceId)(BlockTypesList, className);
return /* @__PURE__ */ (0, import_jsx_runtime232.jsxs)(group_default2, { className, "aria-label": label, children: [
chunk(items, 3).map((row, i2) => /* @__PURE__ */ (0, import_jsx_runtime232.jsx)(row_default2, { children: row.map((item, j2) => /* @__PURE__ */ (0, import_jsx_runtime232.jsx)(
inserter_list_item_default,
{
item,
className: (0, import_blocks34.getBlockMenuDefaultClassName)(
item.id
),
onSelect,
onHover,
isDraggable: isDraggable && !item.isDisabled,
isFirst: i2 === 0 && j2 === 0,
rowId: `${listId}-${i2}`
},
item.id
)) }, i2)),
children
] });
}
var block_types_list_default = BlockTypesList;
// packages/block-editor/build-module/components/inserter/panel.mjs
var import_components41 = __toESM(require_components(), 1);
var import_jsx_runtime233 = __toESM(require_jsx_runtime(), 1);
function InserterPanel({ title, icon, children }) {
return /* @__PURE__ */ (0, import_jsx_runtime233.jsxs)(import_jsx_runtime233.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime233.jsxs)("div", { className: "block-editor-inserter__panel-header", children: [
/* @__PURE__ */ (0, import_jsx_runtime233.jsx)("h2", { className: "block-editor-inserter__panel-title", children: title }),
/* @__PURE__ */ (0, import_jsx_runtime233.jsx)(import_components41.Icon, { icon })
] }),
/* @__PURE__ */ (0, import_jsx_runtime233.jsx)("div", { className: "block-editor-inserter__panel-content", children })
] });
}
var panel_default = InserterPanel;
// packages/block-editor/build-module/components/inserter/no-results.mjs
var import_i18n43 = __toESM(require_i18n(), 1);
var import_jsx_runtime234 = __toESM(require_jsx_runtime(), 1);
function InserterNoResults({ children = (0, import_i18n43.__)("No results found.") }) {
return /* @__PURE__ */ (0, import_jsx_runtime234.jsx)("div", { className: "block-editor-inserter__no-results", children: /* @__PURE__ */ (0, import_jsx_runtime234.jsx)("p", { children }) });
}
var no_results_default = InserterNoResults;
// packages/block-editor/build-module/components/inserter/block-types-tab.mjs
var import_jsx_runtime235 = __toESM(require_jsx_runtime(), 1);
var getBlockNamespace = (item) => item.name.split("/")[0];
var MAX_SUGGESTED_ITEMS = 6;
var EMPTY_ARRAY6 = [];
function BlockTypesTabPanel({
items,
collections,
categories,
onSelectItem,
onHover,
showMostUsedBlocks,
className
}) {
const suggestedItems = (0, import_element107.useMemo)(() => {
return orderBy(items, "frecency", "desc").slice(
0,
MAX_SUGGESTED_ITEMS
);
}, [items]);
const uncategorizedItems = (0, import_element107.useMemo)(() => {
return items.filter((item) => !item.category);
}, [items]);
const itemsPerCollection = (0, import_element107.useMemo)(() => {
const result = { ...collections };
Object.keys(collections).forEach((namespace) => {
result[namespace] = items.filter(
(item) => getBlockNamespace(item) === namespace
);
if (result[namespace].length === 0) {
delete result[namespace];
}
});
return result;
}, [items, collections]);
(0, import_element107.useEffect)(() => () => onHover(null), []);
const currentlyRenderedCategories = (0, import_compose37.useAsyncList)(categories);
const didRenderAllCategories = categories.length === currentlyRenderedCategories.length;
const collectionEntries = (0, import_element107.useMemo)(() => {
return Object.entries(collections);
}, [collections]);
const currentlyRenderedCollections = (0, import_compose37.useAsyncList)(
didRenderAllCategories ? collectionEntries : EMPTY_ARRAY6
);
return /* @__PURE__ */ (0, import_jsx_runtime235.jsxs)("div", { className, children: [
showMostUsedBlocks && // Only show the most used blocks if the total amount of block
// is larger than 1 row, otherwise it is not so useful.
items.length > 3 && !!suggestedItems.length && /* @__PURE__ */ (0, import_jsx_runtime235.jsx)(panel_default, { title: (0, import_i18n44._x)("Most used", "blocks"), children: /* @__PURE__ */ (0, import_jsx_runtime235.jsx)(
block_types_list_default,
{
items: suggestedItems,
onSelect: onSelectItem,
onHover,
label: (0, import_i18n44._x)("Most used", "blocks")
}
) }),
currentlyRenderedCategories.map((category) => {
const categoryItems = items.filter(
(item) => item.category === category.slug
);
if (!categoryItems || !categoryItems.length) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime235.jsx)(
panel_default,
{
title: category.title,
icon: category.icon,
children: /* @__PURE__ */ (0, import_jsx_runtime235.jsx)(
block_types_list_default,
{
items: categoryItems,
onSelect: onSelectItem,
onHover,
label: category.title
}
)
},
category.slug
);
}),
didRenderAllCategories && uncategorizedItems.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime235.jsx)(
panel_default,
{
className: "block-editor-inserter__uncategorized-blocks-panel",
title: (0, import_i18n44.__)("Uncategorized"),
children: /* @__PURE__ */ (0, import_jsx_runtime235.jsx)(
block_types_list_default,
{
items: uncategorizedItems,
onSelect: onSelectItem,
onHover,
label: (0, import_i18n44.__)("Uncategorized")
}
)
}
),
currentlyRenderedCollections.map(
([namespace, collection]) => {
const collectionItems = itemsPerCollection[namespace];
if (!collectionItems || !collectionItems.length) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime235.jsx)(
panel_default,
{
title: collection.title,
icon: collection.icon,
children: /* @__PURE__ */ (0, import_jsx_runtime235.jsx)(
block_types_list_default,
{
items: collectionItems,
onSelect: onSelectItem,
onHover,
label: collection.title
}
)
},
namespace
);
}
)
] });
}
function BlockTypesTab({ rootClientId, onInsert, onHover, showMostUsedBlocks }, ref) {
const [items, categories, collections, onSelectItem] = use_block_types_state_default(
rootClientId,
onInsert
);
if (!items.length) {
return /* @__PURE__ */ (0, import_jsx_runtime235.jsx)(no_results_default, {});
}
const itemsForCurrentRoot = [];
const itemsRemaining = [];
for (const item of items) {
if (item.category === "reusable") {
continue;
}
if (item.isSearchOnly) {
continue;
}
if (item.isAllowedInCurrentRoot) {
itemsForCurrentRoot.push(item);
} else {
itemsRemaining.push(item);
}
}
return /* @__PURE__ */ (0, import_jsx_runtime235.jsx)(inserter_listbox_default, { children: /* @__PURE__ */ (0, import_jsx_runtime235.jsxs)("div", { ref, children: [
!!itemsForCurrentRoot.length && /* @__PURE__ */ (0, import_jsx_runtime235.jsx)(import_jsx_runtime235.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime235.jsx)(
BlockTypesTabPanel,
{
items: itemsForCurrentRoot,
categories,
collections,
onSelectItem,
onHover,
showMostUsedBlocks,
className: "block-editor-inserter__insertable-blocks-at-selection"
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime235.jsx)(
BlockTypesTabPanel,
{
items: itemsRemaining,
categories,
collections,
onSelectItem,
onHover,
showMostUsedBlocks,
className: "block-editor-inserter__all-blocks"
}
)
] }) });
}
var block_types_tab_default = (0, import_element107.forwardRef)(BlockTypesTab);
// packages/block-editor/build-module/components/inserter/block-patterns-tab/index.mjs
var import_element118 = __toESM(require_element(), 1);
var import_compose42 = __toESM(require_compose(), 1);
var import_components51 = __toESM(require_components(), 1);
var import_i18n56 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/inserter/block-patterns-explorer/index.mjs
var import_components46 = __toESM(require_components(), 1);
var import_element114 = __toESM(require_element(), 1);
var import_i18n52 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/inserter/block-patterns-explorer/pattern-explorer-sidebar.mjs
var import_components42 = __toESM(require_components(), 1);
var import_i18n45 = __toESM(require_i18n(), 1);
var import_jsx_runtime236 = __toESM(require_jsx_runtime(), 1);
function PatternCategoriesList({
selectedCategory,
patternCategories,
onClickCategory
}) {
const baseClassName = "block-editor-block-patterns-explorer__sidebar";
return /* @__PURE__ */ (0, import_jsx_runtime236.jsx)("div", { className: `${baseClassName}__categories-list`, children: patternCategories.map(({ name, label }) => {
return /* @__PURE__ */ (0, import_jsx_runtime236.jsx)(
import_components42.Button,
{
__next40pxDefaultSize: true,
label,
className: `${baseClassName}__categories-list__item`,
isPressed: selectedCategory === name,
onClick: () => {
onClickCategory(name);
},
children: label
},
name
);
}) });
}
function PatternsExplorerSearch({ searchValue, setSearchValue }) {
const baseClassName = "block-editor-block-patterns-explorer__search";
return /* @__PURE__ */ (0, import_jsx_runtime236.jsx)("div", { className: baseClassName, children: /* @__PURE__ */ (0, import_jsx_runtime236.jsx)(
import_components42.SearchControl,
{
onChange: setSearchValue,
value: searchValue,
label: (0, import_i18n45.__)("Search"),
placeholder: (0, import_i18n45.__)("Search")
}
) });
}
function PatternExplorerSidebar({
selectedCategory,
patternCategories,
onClickCategory,
searchValue,
setSearchValue
}) {
const baseClassName = "block-editor-block-patterns-explorer__sidebar";
return /* @__PURE__ */ (0, import_jsx_runtime236.jsxs)("div", { className: baseClassName, children: [
/* @__PURE__ */ (0, import_jsx_runtime236.jsx)(
PatternsExplorerSearch,
{
searchValue,
setSearchValue
}
),
!searchValue && /* @__PURE__ */ (0, import_jsx_runtime236.jsx)(
PatternCategoriesList,
{
selectedCategory,
patternCategories,
onClickCategory
}
)
] });
}
var pattern_explorer_sidebar_default = PatternExplorerSidebar;
// packages/block-editor/build-module/components/inserter/block-patterns-explorer/pattern-list.mjs
var import_element112 = __toESM(require_element(), 1);
var import_i18n50 = __toESM(require_i18n(), 1);
var import_compose40 = __toESM(require_compose(), 1);
var import_components45 = __toESM(require_components(), 1);
var import_a11y7 = __toESM(require_a11y(), 1);
// packages/block-editor/build-module/components/block-patterns-list/index.mjs
var import_blocks35 = __toESM(require_blocks(), 1);
var import_element108 = __toESM(require_element(), 1);
var import_components44 = __toESM(require_components(), 1);
var import_compose38 = __toESM(require_compose(), 1);
var import_i18n47 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/block-patterns-paging/index.mjs
var import_components43 = __toESM(require_components(), 1);
var import_i18n46 = __toESM(require_i18n(), 1);
var import_jsx_runtime237 = __toESM(require_jsx_runtime(), 1);
function Pagination({
currentPage,
numPages,
changePage,
totalItems
}) {
return /* @__PURE__ */ (0, import_jsx_runtime237.jsxs)(import_components43.__experimentalVStack, { className: "block-editor-patterns__grid-pagination-wrapper", children: [
/* @__PURE__ */ (0, import_jsx_runtime237.jsx)(import_components43.__experimentalText, { variant: "muted", children: (0, import_i18n46.sprintf)(
// translators: %s: Total number of patterns.
(0, import_i18n46._n)("%s item", "%s items", totalItems),
totalItems
) }),
numPages > 1 && /* @__PURE__ */ (0, import_jsx_runtime237.jsxs)(
import_components43.__experimentalHStack,
{
expanded: false,
spacing: 3,
justify: "flex-start",
className: "block-editor-patterns__grid-pagination",
children: [
/* @__PURE__ */ (0, import_jsx_runtime237.jsxs)(
import_components43.__experimentalHStack,
{
expanded: false,
spacing: 1,
className: "block-editor-patterns__grid-pagination-previous",
children: [
/* @__PURE__ */ (0, import_jsx_runtime237.jsx)(
import_components43.Button,
{
variant: "tertiary",
onClick: () => changePage(1),
disabled: currentPage === 1,
"aria-label": (0, import_i18n46.__)("First page"),
size: "compact",
accessibleWhenDisabled: true,
className: "block-editor-patterns__grid-pagination-button",
children: /* @__PURE__ */ (0, import_jsx_runtime237.jsx)("span", { children: "\xAB" })
}
),
/* @__PURE__ */ (0, import_jsx_runtime237.jsx)(
import_components43.Button,
{
variant: "tertiary",
onClick: () => changePage(currentPage - 1),
disabled: currentPage === 1,
"aria-label": (0, import_i18n46.__)("Previous page"),
size: "compact",
accessibleWhenDisabled: true,
className: "block-editor-patterns__grid-pagination-button",
children: /* @__PURE__ */ (0, import_jsx_runtime237.jsx)("span", { children: "\u2039" })
}
)
]
}
),
/* @__PURE__ */ (0, import_jsx_runtime237.jsx)(import_components43.__experimentalText, { variant: "muted", children: (0, import_i18n46.sprintf)(
// translators: 1: Current page number. 2: Total number of pages.
(0, import_i18n46._x)("%1$s of %2$s", "paging"),
currentPage,
numPages
) }),
/* @__PURE__ */ (0, import_jsx_runtime237.jsxs)(
import_components43.__experimentalHStack,
{
expanded: false,
spacing: 1,
className: "block-editor-patterns__grid-pagination-next",
children: [
/* @__PURE__ */ (0, import_jsx_runtime237.jsx)(
import_components43.Button,
{
variant: "tertiary",
onClick: () => changePage(currentPage + 1),
disabled: currentPage === numPages,
"aria-label": (0, import_i18n46.__)("Next page"),
size: "compact",
accessibleWhenDisabled: true,
className: "block-editor-patterns__grid-pagination-button",
children: /* @__PURE__ */ (0, import_jsx_runtime237.jsx)("span", { children: "\u203A" })
}
),
/* @__PURE__ */ (0, import_jsx_runtime237.jsx)(
import_components43.Button,
{
variant: "tertiary",
onClick: () => changePage(numPages),
disabled: currentPage === numPages,
"aria-label": (0, import_i18n46.__)("Last page"),
size: "compact",
accessibleWhenDisabled: true,
className: "block-editor-patterns__grid-pagination-button",
children: /* @__PURE__ */ (0, import_jsx_runtime237.jsx)("span", { children: "\xBB" })
}
)
]
}
)
]
}
)
] });
}
// packages/block-editor/build-module/components/block-patterns-list/index.mjs
var import_jsx_runtime238 = __toESM(require_jsx_runtime(), 1);
var WithToolTip = ({ showTooltip, title, children }) => {
if (showTooltip) {
return /* @__PURE__ */ (0, import_jsx_runtime238.jsxs)(tooltip_exports.Root, { children: [
/* @__PURE__ */ (0, import_jsx_runtime238.jsx)(tooltip_exports.Trigger, { render: children }),
/* @__PURE__ */ (0, import_jsx_runtime238.jsx)(tooltip_exports.Popup, { children: title })
] });
}
return /* @__PURE__ */ (0, import_jsx_runtime238.jsx)(import_jsx_runtime238.Fragment, { children });
};
function BlockPattern({
id,
isDraggable,
pattern,
onClick,
onHover,
showTitlesAsTooltip,
category,
isSelected
}) {
const [isDragging3, setIsDragging] = (0, import_element108.useState)(false);
const { blocks: blocks2, viewportWidth } = pattern;
const instanceId = (0, import_compose38.useInstanceId)(BlockPattern);
const descriptionId = `block-editor-block-patterns-list__item-description-${instanceId}`;
const isUserPattern = pattern.type === INSERTER_PATTERN_TYPES.user;
const patternBlocks = (0, import_element108.useMemo)(() => {
if (!category || !isDraggable) {
return blocks2;
}
return (blocks2 ?? []).map((block) => {
const clonedBlock = (0, import_blocks35.cloneBlock)(block);
if (clonedBlock.attributes.metadata?.categories?.includes(
category
)) {
clonedBlock.attributes.metadata.categories = [category];
}
return clonedBlock;
});
}, [blocks2, isDraggable, category]);
return /* @__PURE__ */ (0, import_jsx_runtime238.jsx)(
inserter_draggable_blocks_default,
{
isEnabled: isDraggable,
blocks: patternBlocks,
pattern,
children: ({ draggable, onDragStart, onDragEnd }) => /* @__PURE__ */ (0, import_jsx_runtime238.jsx)(
"div",
{
className: "block-editor-block-patterns-list__list-item",
draggable,
onDragStart: (event) => {
setIsDragging(true);
if (onDragStart) {
onHover?.(null);
onDragStart(event);
}
},
onDragEnd: (event) => {
setIsDragging(false);
if (onDragEnd) {
onDragEnd(event);
}
},
children: /* @__PURE__ */ (0, import_jsx_runtime238.jsx)(
WithToolTip,
{
showTooltip: showTitlesAsTooltip && !isUserPattern,
title: pattern.title,
children: /* @__PURE__ */ (0, import_jsx_runtime238.jsxs)(
import_components44.Composite.Item,
{
render: /* @__PURE__ */ (0, import_jsx_runtime238.jsx)(
"div",
{
role: "option",
"aria-label": pattern.title,
"aria-describedby": pattern.description ? descriptionId : void 0,
className: clsx_default(
"block-editor-block-patterns-list__item",
{
"block-editor-block-patterns-list__list-item-synced": pattern.type === INSERTER_PATTERN_TYPES.user && !pattern.syncStatus,
"is-selected": isSelected
}
)
}
),
id,
onClick: () => {
onClick(pattern, blocks2);
onHover?.(null);
},
onMouseEnter: () => {
if (isDragging3) {
return;
}
onHover?.(pattern);
},
onMouseLeave: () => onHover?.(null),
children: [
/* @__PURE__ */ (0, import_jsx_runtime238.jsx)(
block_preview_default.Async,
{
placeholder: /* @__PURE__ */ (0, import_jsx_runtime238.jsx)(BlockPatternPlaceholder, {}),
children: /* @__PURE__ */ (0, import_jsx_runtime238.jsx)(
block_preview_default,
{
blocks: blocks2,
viewportWidth
}
)
}
),
(!showTitlesAsTooltip || isUserPattern) && /* @__PURE__ */ (0, import_jsx_runtime238.jsxs)(
import_components44.__experimentalHStack,
{
className: "block-editor-patterns__pattern-details",
spacing: 2,
children: [
isUserPattern && !pattern.syncStatus && /* @__PURE__ */ (0, import_jsx_runtime238.jsx)("div", { className: "block-editor-patterns__pattern-icon-wrapper", children: /* @__PURE__ */ (0, import_jsx_runtime238.jsx)(
icon_default,
{
className: "block-editor-patterns__pattern-icon",
icon: symbol_default
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime238.jsx)(
Text,
{
render: /* @__PURE__ */ (0, import_jsx_runtime238.jsx)("div", {}),
className: "block-editor-block-patterns-list__item-title",
variant: "body-sm",
children: pattern.title
}
)
]
}
),
!!pattern.description && /* @__PURE__ */ (0, import_jsx_runtime238.jsx)(VisuallyHidden, { id: descriptionId, children: pattern.description })
]
}
)
}
)
}
)
}
);
}
function BlockPatternPlaceholder() {
return /* @__PURE__ */ (0, import_jsx_runtime238.jsx)("div", { className: "block-editor-block-patterns-list__item is-placeholder" });
}
function BlockPatternsList({
isDraggable,
blockPatterns,
onHover,
onClickPattern,
orientation,
category,
label = (0, import_i18n47.__)("Patterns"),
showTitlesAsTooltip,
pagingProps
}, ref) {
const [activeCompositeId, setActiveCompositeId] = (0, import_element108.useState)(void 0);
const [activePattern, setActivePattern] = (0, import_element108.useState)(null);
(0, import_element108.useEffect)(() => {
const firstCompositeItemId = blockPatterns[0]?.name;
setActiveCompositeId(firstCompositeItemId);
}, [blockPatterns]);
const handleClickPattern = (pattern, blocks2) => {
setActivePattern(pattern.name);
onClickPattern(pattern, blocks2);
};
return /* @__PURE__ */ (0, import_jsx_runtime238.jsxs)(
import_components44.Composite,
{
orientation,
activeId: activeCompositeId,
setActiveId: setActiveCompositeId,
role: "listbox",
className: "block-editor-block-patterns-list",
"aria-label": label,
ref,
children: [
blockPatterns.map((pattern) => /* @__PURE__ */ (0, import_jsx_runtime238.jsx)(
BlockPattern,
{
id: pattern.name,
pattern,
onClick: handleClickPattern,
onHover,
isDraggable,
showTitlesAsTooltip,
category,
isSelected: !!activePattern && activePattern === pattern.name
},
pattern.name
)),
pagingProps && /* @__PURE__ */ (0, import_jsx_runtime238.jsx)(Pagination, { ...pagingProps })
]
}
);
}
var block_patterns_list_default = (0, import_element108.forwardRef)(BlockPatternsList);
// packages/block-editor/build-module/components/inserter/hooks/use-insertion-point.mjs
var import_data55 = __toESM(require_data(), 1);
var import_blocks36 = __toESM(require_blocks(), 1);
var import_i18n48 = __toESM(require_i18n(), 1);
var import_a11y6 = __toESM(require_a11y(), 1);
var import_element109 = __toESM(require_element(), 1);
function getIndex({
destinationRootClientId,
destinationIndex,
rootClientId,
registry
}) {
if (rootClientId === destinationRootClientId) {
return destinationIndex;
}
const parents = [
"",
...registry.select(store).getBlockParents(destinationRootClientId),
destinationRootClientId
];
const parentIndex = parents.indexOf(rootClientId);
if (parentIndex !== -1) {
return registry.select(store).getBlockIndex(parents[parentIndex + 1]) + 1;
}
return registry.select(store).getBlockOrder(rootClientId).length;
}
function useInsertionPoint({
rootClientId = "",
insertionIndex,
clientId,
isAppender,
onSelect,
shouldFocusBlock = true,
selectBlockOnInsert = true
}) {
const registry = (0, import_data55.useRegistry)();
const {
getSelectedBlock: getSelectedBlock2,
getClosestAllowedInsertionPoint: getClosestAllowedInsertionPoint2,
isBlockInsertionPointVisible: isBlockInsertionPointVisible2
} = unlock((0, import_data55.useSelect)(store));
const { destinationRootClientId, destinationIndex } = (0, import_data55.useSelect)(
(select3) => {
const {
getSelectedBlockClientId: getSelectedBlockClientId2,
getBlockRootClientId: getBlockRootClientId2,
getBlockIndex: getBlockIndex2,
getBlockOrder: getBlockOrder2,
getInsertionPoint: getInsertionPoint2
} = unlock(select3(store));
const selectedBlockClientId = getSelectedBlockClientId2();
let _destinationRootClientId = rootClientId;
let _destinationIndex;
const insertionPoint2 = getInsertionPoint2();
if (insertionIndex !== void 0) {
_destinationIndex = insertionIndex;
} else if (insertionPoint2 && insertionPoint2.hasOwnProperty("index")) {
_destinationRootClientId = insertionPoint2?.rootClientId ? insertionPoint2.rootClientId : rootClientId;
_destinationIndex = insertionPoint2.index;
} else if (clientId) {
_destinationIndex = getBlockIndex2(clientId);
} else if (!isAppender && selectedBlockClientId) {
_destinationRootClientId = getBlockRootClientId2(
selectedBlockClientId
);
_destinationIndex = getBlockIndex2(selectedBlockClientId) + 1;
} else {
_destinationIndex = getBlockOrder2(
_destinationRootClientId
).length;
}
return {
destinationRootClientId: _destinationRootClientId,
destinationIndex: _destinationIndex
};
},
[rootClientId, insertionIndex, clientId, isAppender]
);
const {
replaceBlocks: replaceBlocks2,
insertBlocks: insertBlocks2,
showInsertionPoint: showInsertionPoint2,
hideInsertionPoint: hideInsertionPoint2,
setLastFocus: setLastFocus2
} = unlock((0, import_data55.useDispatch)(store));
const onInsertBlocks = (0, import_element109.useCallback)(
(blocks2, meta, shouldForceFocusBlock = false, _rootClientId) => {
if (shouldForceFocusBlock || shouldFocusBlock || selectBlockOnInsert) {
setLastFocus2(null);
}
const selectedBlock = getSelectedBlock2();
if (!isAppender && selectedBlock && (0, import_blocks36.isUnmodifiedDefaultBlock)(selectedBlock, "content")) {
replaceBlocks2(
selectedBlock.clientId,
blocks2,
null,
shouldFocusBlock || shouldForceFocusBlock ? 0 : null,
meta
);
} else {
insertBlocks2(
blocks2,
isAppender || _rootClientId === void 0 ? destinationIndex : getIndex({
destinationRootClientId,
destinationIndex,
rootClientId: _rootClientId,
registry
}),
isAppender || _rootClientId === void 0 ? destinationRootClientId : _rootClientId,
selectBlockOnInsert,
shouldFocusBlock || shouldForceFocusBlock ? 0 : null,
meta
);
}
const blockLength = Array.isArray(blocks2) ? blocks2.length : 1;
const message2 = (0, import_i18n48.sprintf)(
// translators: %d: the name of the block that has been added
(0, import_i18n48._n)("%d block added.", "%d blocks added.", blockLength),
blockLength
);
(0, import_a11y6.speak)(message2);
if (onSelect) {
onSelect(blocks2);
}
},
[
isAppender,
getSelectedBlock2,
replaceBlocks2,
insertBlocks2,
destinationRootClientId,
destinationIndex,
onSelect,
shouldFocusBlock,
selectBlockOnInsert,
setLastFocus2,
registry
]
);
const onToggleInsertionPoint = (0, import_element109.useCallback)(
(item) => {
if (item && !isBlockInsertionPointVisible2()) {
const allowedDestinationRootClientId = getClosestAllowedInsertionPoint2(
item.name,
destinationRootClientId
);
if (allowedDestinationRootClientId !== null) {
showInsertionPoint2(
allowedDestinationRootClientId,
getIndex({
destinationRootClientId,
destinationIndex,
rootClientId: allowedDestinationRootClientId,
registry
})
);
}
} else {
hideInsertionPoint2();
}
},
[
getClosestAllowedInsertionPoint2,
isBlockInsertionPointVisible2,
showInsertionPoint2,
hideInsertionPoint2,
destinationRootClientId,
destinationIndex,
registry
]
);
return [destinationRootClientId, onInsertBlocks, onToggleInsertionPoint];
}
var use_insertion_point_default = useInsertionPoint;
// packages/block-editor/build-module/components/inserter/hooks/use-patterns-state.mjs
var import_element110 = __toESM(require_element(), 1);
var import_blocks37 = __toESM(require_blocks(), 1);
var import_data56 = __toESM(require_data(), 1);
var import_i18n49 = __toESM(require_i18n(), 1);
var import_notices5 = __toESM(require_notices(), 1);
var usePatternsState = (onInsert, rootClientId, selectedCategory, isQuick) => {
const options = (0, import_element110.useMemo)(
() => ({ [isFiltered]: !!isQuick }),
[isQuick]
);
const isWithinNavigationOverlayContext = (0, import_data56.useSelect)((select3) => {
const { getSettings: getSettings7 } = unlock(select3(store));
const settings2 = getSettings7();
return settings2[isNavigationOverlayContextKey] ?? false;
}, []);
const { patternCategories, patterns, userPatternCategories } = (0, import_data56.useSelect)(
(select3) => {
const { getSettings: getSettings7, __experimentalGetAllowedPatterns: __experimentalGetAllowedPatterns2 } = unlock(
select3(store)
);
const settings2 = getSettings7();
const userPatternCategoriesSelect = settings2[userPatternCategoriesSelectKey];
return {
patterns: __experimentalGetAllowedPatterns2(
rootClientId,
options
),
userPatternCategories: userPatternCategoriesSelect ? userPatternCategoriesSelect(select3) : settings2.__experimentalUserPatternCategories,
patternCategories: settings2.__experimentalBlockPatternCategories
};
},
[rootClientId, options]
);
const filteredPatterns = (0, import_element110.useMemo)(() => {
return patterns.filter((pattern) => {
const hasNavigationCategory = pattern.categories?.includes("navigation");
if (hasNavigationCategory && !isWithinNavigationOverlayContext) {
return false;
}
return true;
});
}, [patterns, isWithinNavigationOverlayContext]);
const { getClosestAllowedInsertionPointForPattern: getClosestAllowedInsertionPointForPattern2 } = unlock(
(0, import_data56.useSelect)(store)
);
const allCategories = (0, import_element110.useMemo)(() => {
const categories = [...patternCategories];
userPatternCategories?.forEach((userCategory) => {
if (!categories.find(
(existingCategory) => existingCategory.name === userCategory.name
)) {
categories.push(userCategory);
}
});
return categories;
}, [patternCategories, userPatternCategories]);
const { createSuccessNotice } = (0, import_data56.useDispatch)(import_notices5.store);
const onClickPattern = (0, import_element110.useCallback)(
(pattern, blocks2) => {
const destinationRootClientId = isQuick ? rootClientId : getClosestAllowedInsertionPointForPattern2(
pattern,
rootClientId
);
if (destinationRootClientId === null) {
return;
}
const patternBlocks = pattern.type === INSERTER_PATTERN_TYPES.user && pattern.syncStatus !== "unsynced" ? [(0, import_blocks37.createBlock)("core/block", { ref: pattern.id })] : blocks2;
onInsert(
(patternBlocks ?? []).map((block) => {
const clonedBlock = (0, import_blocks37.cloneBlock)(block);
if (clonedBlock.attributes.metadata?.categories?.includes(
selectedCategory
)) {
clonedBlock.attributes.metadata.categories = [
selectedCategory
];
}
return clonedBlock;
}),
pattern.name,
false,
destinationRootClientId
);
createSuccessNotice(
(0, import_i18n49.sprintf)(
/* translators: %s: block pattern title. */
(0, import_i18n49.__)('Pattern "%s" inserted.'),
pattern.title
),
{
type: "snackbar",
id: "inserter-notice"
}
);
},
[
createSuccessNotice,
onInsert,
selectedCategory,
rootClientId,
getClosestAllowedInsertionPointForPattern2,
isQuick
]
);
return [filteredPatterns, allCategories, onClickPattern];
};
var use_patterns_state_default = usePatternsState;
// packages/block-editor/build-module/components/inserter/hooks/use-patterns-paging.mjs
var import_element111 = __toESM(require_element(), 1);
var import_compose39 = __toESM(require_compose(), 1);
var import_dom50 = __toESM(require_dom(), 1);
var PAGE_SIZE = 20;
function usePatternsPaging(currentCategoryPatterns, currentCategory, scrollContainerRef, currentFilter = "") {
const [currentPage, setCurrentPage] = (0, import_element111.useState)(1);
const previousCategory = (0, import_compose39.usePrevious)(currentCategory);
const previousFilter = (0, import_compose39.usePrevious)(currentFilter);
if ((previousCategory !== currentCategory || previousFilter !== currentFilter) && currentPage !== 1) {
setCurrentPage(1);
}
const totalItems = currentCategoryPatterns.length;
const pageIndex = currentPage - 1;
const categoryPatterns = (0, import_element111.useMemo)(() => {
return currentCategoryPatterns.slice(
pageIndex * PAGE_SIZE,
pageIndex * PAGE_SIZE + PAGE_SIZE
);
}, [pageIndex, currentCategoryPatterns]);
const numPages = Math.ceil(currentCategoryPatterns.length / PAGE_SIZE);
const changePage = (page) => {
const scrollContainer = (0, import_dom50.getScrollContainer)(
scrollContainerRef?.current
);
scrollContainer?.scrollTo(0, 0);
setCurrentPage(page);
};
(0, import_element111.useEffect)(
function scrollToTopOnCategoryChange() {
const scrollContainer = (0, import_dom50.getScrollContainer)(
scrollContainerRef?.current
);
scrollContainer?.scrollTo(0, 0);
},
[currentCategory, scrollContainerRef]
);
return {
totalItems,
categoryPatterns,
numPages,
changePage,
currentPage
};
}
// packages/block-editor/build-module/components/inserter/block-patterns-explorer/pattern-list.mjs
var import_jsx_runtime239 = __toESM(require_jsx_runtime(), 1);
function PatternsListHeader({ filterValue, filteredBlockPatternsLength }) {
if (!filterValue) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime239.jsx)(
import_components45.__experimentalHeading,
{
level: 2,
lineHeight: "48px",
className: "block-editor-block-patterns-explorer__search-results-count",
children: (0, import_i18n50.sprintf)(
/* translators: %d: number of patterns. */
(0, import_i18n50._n)(
"%d pattern found",
"%d patterns found",
filteredBlockPatternsLength
),
filteredBlockPatternsLength
)
}
);
}
function PatternList({
searchValue,
selectedCategory,
patternCategories,
rootClientId,
onModalClose
}) {
const container = (0, import_element112.useRef)();
const debouncedSpeak = (0, import_compose40.useDebounce)(import_a11y7.speak, 500);
const [destinationRootClientId, onInsertBlocks] = use_insertion_point_default({
rootClientId,
shouldFocusBlock: true
});
const [patterns, , onClickPattern] = use_patterns_state_default(
onInsertBlocks,
destinationRootClientId,
selectedCategory
);
const registeredPatternCategories = (0, import_element112.useMemo)(
() => patternCategories.map(
(patternCategory) => patternCategory.name
),
[patternCategories]
);
const filteredBlockPatterns = (0, import_element112.useMemo)(() => {
const filteredPatterns = patterns.filter((pattern) => {
if (selectedCategory === allPatternsCategory.name) {
return true;
}
if (selectedCategory === myPatternsCategory.name && pattern.type === INSERTER_PATTERN_TYPES.user) {
return true;
}
if (selectedCategory === starterPatternsCategory.name && pattern.blockTypes?.includes("core/post-content")) {
return true;
}
if (selectedCategory === "uncategorized") {
const hasKnownCategory = pattern.categories?.some(
(category) => registeredPatternCategories.includes(category)
) ?? false;
return !pattern.categories?.length || !hasKnownCategory;
}
return pattern.categories?.includes(selectedCategory);
});
if (!searchValue) {
return filteredPatterns;
}
return searchItems(filteredPatterns, searchValue);
}, [
searchValue,
patterns,
selectedCategory,
registeredPatternCategories
]);
(0, import_element112.useEffect)(() => {
if (!searchValue) {
return;
}
const count = filteredBlockPatterns.length;
const resultsFoundMessage = (0, import_i18n50.sprintf)(
/* translators: %d: number of results. */
(0, import_i18n50._n)("%d result found.", "%d results found.", count),
count
);
debouncedSpeak(resultsFoundMessage);
}, [searchValue, debouncedSpeak, filteredBlockPatterns.length]);
const pagingProps = usePatternsPaging(
filteredBlockPatterns,
selectedCategory,
container
);
const [previousSearchValue, setPreviousSearchValue] = (0, import_element112.useState)(searchValue);
if (searchValue !== previousSearchValue) {
setPreviousSearchValue(searchValue);
pagingProps.changePage(1);
}
const hasItems = !!filteredBlockPatterns?.length;
return /* @__PURE__ */ (0, import_jsx_runtime239.jsxs)(
"div",
{
className: "block-editor-block-patterns-explorer__list",
ref: container,
children: [
/* @__PURE__ */ (0, import_jsx_runtime239.jsx)(
PatternsListHeader,
{
filterValue: searchValue,
filteredBlockPatternsLength: filteredBlockPatterns.length
}
),
/* @__PURE__ */ (0, import_jsx_runtime239.jsx)(inserter_listbox_default, { children: hasItems && /* @__PURE__ */ (0, import_jsx_runtime239.jsxs)(import_jsx_runtime239.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime239.jsx)(
block_patterns_list_default,
{
blockPatterns: pagingProps.categoryPatterns,
onClickPattern: (pattern, blocks2) => {
onClickPattern(pattern, blocks2);
onModalClose();
},
isDraggable: false
}
),
/* @__PURE__ */ (0, import_jsx_runtime239.jsx)(Pagination, { ...pagingProps })
] }) })
]
}
);
}
var pattern_list_default = PatternList;
// packages/block-editor/build-module/components/inserter/block-patterns-tab/use-pattern-categories.mjs
var import_element113 = __toESM(require_element(), 1);
var import_i18n51 = __toESM(require_i18n(), 1);
var import_a11y8 = __toESM(require_a11y(), 1);
function hasRegisteredCategory(pattern, allCategories) {
if (!pattern.categories || !pattern.categories.length) {
return false;
}
return pattern.categories.some(
(cat) => allCategories.some((category) => category.name === cat)
);
}
function usePatternCategories(rootClientId, sourceFilter = "all") {
const [patterns, allCategories] = use_patterns_state_default(
void 0,
rootClientId
);
const filteredPatterns = (0, import_element113.useMemo)(
() => sourceFilter === "all" ? patterns : patterns.filter(
(pattern) => !isPatternFiltered(pattern, sourceFilter)
),
[sourceFilter, patterns]
);
const populatedCategories = (0, import_element113.useMemo)(() => {
const categories = allCategories.filter(
(category) => filteredPatterns.some(
(pattern) => pattern.categories?.includes(category.name)
)
).sort((a2, b2) => a2.label.localeCompare(b2.label));
if (filteredPatterns.some(
(pattern) => !hasRegisteredCategory(pattern, allCategories)
) && !categories.find(
(category) => category.name === "uncategorized"
)) {
categories.push({
name: "uncategorized",
label: (0, import_i18n51._x)("Uncategorized")
});
}
if (filteredPatterns.some(
(pattern) => pattern.blockTypes?.includes("core/post-content")
)) {
categories.unshift(starterPatternsCategory);
}
if (filteredPatterns.some(
(pattern) => pattern.type === INSERTER_PATTERN_TYPES.user
)) {
categories.unshift(myPatternsCategory);
}
if (filteredPatterns.length > 0) {
categories.unshift({
name: allPatternsCategory.name,
label: allPatternsCategory.label
});
}
(0, import_a11y8.speak)(
(0, import_i18n51.sprintf)(
/* translators: %d: number of categories . */
(0, import_i18n51._n)(
"%d category button displayed.",
"%d category buttons displayed.",
categories.length
),
categories.length
)
);
return categories;
}, [allCategories, filteredPatterns]);
return populatedCategories;
}
// packages/block-editor/build-module/components/inserter/block-patterns-explorer/index.mjs
var import_jsx_runtime240 = __toESM(require_jsx_runtime(), 1);
function PatternsExplorer({ initialCategory, rootClientId, onModalClose }) {
const [searchValue, setSearchValue] = (0, import_element114.useState)("");
const [selectedCategory, setSelectedCategory] = (0, import_element114.useState)(
initialCategory?.name
);
const patternCategories = usePatternCategories(rootClientId);
return /* @__PURE__ */ (0, import_jsx_runtime240.jsxs)("div", { className: "block-editor-block-patterns-explorer", children: [
/* @__PURE__ */ (0, import_jsx_runtime240.jsx)(
pattern_explorer_sidebar_default,
{
selectedCategory,
patternCategories,
onClickCategory: setSelectedCategory,
searchValue,
setSearchValue
}
),
/* @__PURE__ */ (0, import_jsx_runtime240.jsx)(
pattern_list_default,
{
searchValue,
selectedCategory,
patternCategories,
rootClientId,
onModalClose
}
)
] });
}
function PatternsExplorerModal({ onModalClose, ...restProps }) {
return /* @__PURE__ */ (0, import_jsx_runtime240.jsx)(
import_components46.Modal,
{
title: (0, import_i18n52.__)("Patterns"),
onRequestClose: onModalClose,
isFullScreen: true,
children: /* @__PURE__ */ (0, import_jsx_runtime240.jsx)(PatternsExplorer, { onModalClose, ...restProps })
}
);
}
var block_patterns_explorer_default = PatternsExplorerModal;
// packages/block-editor/build-module/components/inserter/mobile-tab-navigation.mjs
var import_i18n53 = __toESM(require_i18n(), 1);
var import_components47 = __toESM(require_components(), 1);
var import_jsx_runtime241 = __toESM(require_jsx_runtime(), 1);
function ScreenHeader({ title }) {
return /* @__PURE__ */ (0, import_jsx_runtime241.jsx)(import_components47.__experimentalVStack, { spacing: 0, children: /* @__PURE__ */ (0, import_jsx_runtime241.jsx)(import_components47.__experimentalView, { children: /* @__PURE__ */ (0, import_jsx_runtime241.jsx)(import_components47.__experimentalSpacer, { marginBottom: 0, paddingX: 4, paddingY: 3, children: /* @__PURE__ */ (0, import_jsx_runtime241.jsxs)(import_components47.__experimentalHStack, { spacing: 2, children: [
/* @__PURE__ */ (0, import_jsx_runtime241.jsx)(
import_components47.Navigator.BackButton,
{
style: (
// TODO: This style override is also used in ToolsPanelHeader.
// It should be supported out-of-the-box by Button.
{ minWidth: 24, padding: 0 }
),
icon: (0, import_i18n53.isRTL)() ? chevron_right_default : chevron_left_default,
size: "small",
label: (0, import_i18n53.__)("Back")
}
),
/* @__PURE__ */ (0, import_jsx_runtime241.jsx)(import_components47.__experimentalSpacer, { children: /* @__PURE__ */ (0, import_jsx_runtime241.jsx)(import_components47.__experimentalHeading, { level: 5, children: title }) })
] }) }) }) });
}
function MobileTabNavigation({
categories,
children,
screenClassName
}) {
return /* @__PURE__ */ (0, import_jsx_runtime241.jsxs)(
import_components47.Navigator,
{
initialPath: "/",
className: "block-editor-inserter__mobile-tab-navigation",
children: [
/* @__PURE__ */ (0, import_jsx_runtime241.jsx)(import_components47.Navigator.Screen, { path: "/", children: /* @__PURE__ */ (0, import_jsx_runtime241.jsx)(import_components47.__experimentalItemGroup, { children: categories.map((category) => /* @__PURE__ */ (0, import_jsx_runtime241.jsx)(
import_components47.Navigator.Button,
{
path: `/category/${category.name}`,
as: import_components47.__experimentalItem,
isAction: true,
children: /* @__PURE__ */ (0, import_jsx_runtime241.jsxs)(import_components47.__experimentalHStack, { children: [
/* @__PURE__ */ (0, import_jsx_runtime241.jsx)(import_components47.FlexBlock, { children: category.label }),
/* @__PURE__ */ (0, import_jsx_runtime241.jsx)(
icon_default,
{
icon: (0, import_i18n53.isRTL)() ? chevron_left_default : chevron_right_default
}
)
] })
},
category.name
)) }) }),
categories.map((category) => /* @__PURE__ */ (0, import_jsx_runtime241.jsxs)(
import_components47.Navigator.Screen,
{
className: screenClassName,
path: `/category/${category.name}`,
children: [
/* @__PURE__ */ (0, import_jsx_runtime241.jsx)(ScreenHeader, { title: (0, import_i18n53.__)("Back") }),
children(category)
]
},
category.name
))
]
}
);
}
// packages/block-editor/build-module/components/inserter/block-patterns-tab/pattern-category-previews.mjs
var import_element116 = __toESM(require_element(), 1);
var import_i18n55 = __toESM(require_i18n(), 1);
var import_components49 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/inserter/block-patterns-tab/patterns-filter.mjs
var import_components48 = __toESM(require_components(), 1);
var import_i18n54 = __toESM(require_i18n(), 1);
var import_element115 = __toESM(require_element(), 1);
var import_jsx_runtime242 = __toESM(require_jsx_runtime(), 1);
var getShouldDisableSyncFilter = (sourceFilter) => sourceFilter !== "all" && sourceFilter !== "user";
var getShouldHideSourcesFilter = (category) => {
return category.name === myPatternsCategory.name;
};
var PATTERN_SOURCE_MENU_OPTIONS = [
{
value: "all",
label: (0, import_i18n54._x)("All", "patterns")
},
{
value: INSERTER_PATTERN_TYPES.directory,
label: (0, import_i18n54.__)("Pattern Directory")
},
{
value: INSERTER_PATTERN_TYPES.theme,
label: (0, import_i18n54.__)("Theme & Plugins")
},
{
value: INSERTER_PATTERN_TYPES.user,
label: (0, import_i18n54.__)("User")
}
];
function PatternsFilter({
setPatternSyncFilter,
setPatternSourceFilter,
patternSyncFilter,
patternSourceFilter,
scrollContainerRef,
category
}) {
const currentPatternSourceFilter = category.name === myPatternsCategory.name ? INSERTER_PATTERN_TYPES.user : patternSourceFilter;
const shouldDisableSyncFilter = getShouldDisableSyncFilter(
currentPatternSourceFilter
);
const shouldHideSourcesFilter = getShouldHideSourcesFilter(category);
const patternSyncMenuOptions = (0, import_element115.useMemo)(
() => [
{
value: "all",
label: (0, import_i18n54._x)("All", "patterns")
},
{
value: INSERTER_SYNC_TYPES.full,
label: (0, import_i18n54._x)("Synced", "patterns"),
disabled: shouldDisableSyncFilter
},
{
value: INSERTER_SYNC_TYPES.unsynced,
label: (0, import_i18n54._x)("Not synced", "patterns"),
disabled: shouldDisableSyncFilter
}
],
[shouldDisableSyncFilter]
);
function handleSetSourceFilterChange(newSourceFilter) {
setPatternSourceFilter(newSourceFilter);
if (getShouldDisableSyncFilter(newSourceFilter)) {
setPatternSyncFilter("all");
}
}
return /* @__PURE__ */ (0, import_jsx_runtime242.jsx)(import_jsx_runtime242.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime242.jsx)(
import_components48.DropdownMenu,
{
popoverProps: {
placement: "right-end"
},
label: (0, import_i18n54.__)("Filter patterns"),
toggleProps: { size: "compact" },
icon: /* @__PURE__ */ (0, import_jsx_runtime242.jsx)(
icon_default,
{
icon: /* @__PURE__ */ (0, import_jsx_runtime242.jsx)(
import_components48.SVG,
{
width: "24",
height: "24",
viewBox: "0 0 24 24",
fill: "none",
xmlns: "http://www.w3.org/2000/svg",
children: /* @__PURE__ */ (0, import_jsx_runtime242.jsx)(
import_components48.Path,
{
d: "M10 17.5H14V16H10V17.5ZM6 6V7.5H18V6H6ZM8 12.5H16V11H8V12.5Z",
fill: "currentColor"
}
)
}
)
}
),
children: () => /* @__PURE__ */ (0, import_jsx_runtime242.jsxs)(import_jsx_runtime242.Fragment, { children: [
!shouldHideSourcesFilter && /* @__PURE__ */ (0, import_jsx_runtime242.jsx)(import_components48.MenuGroup, { label: (0, import_i18n54.__)("Source"), children: /* @__PURE__ */ (0, import_jsx_runtime242.jsx)(
import_components48.MenuItemsChoice,
{
choices: PATTERN_SOURCE_MENU_OPTIONS,
onSelect: (value) => {
handleSetSourceFilterChange(value);
scrollContainerRef.current?.scrollTo(
0,
0
);
},
value: currentPatternSourceFilter
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime242.jsx)(import_components48.MenuGroup, { label: (0, import_i18n54.__)("Type"), children: /* @__PURE__ */ (0, import_jsx_runtime242.jsx)(
import_components48.MenuItemsChoice,
{
choices: patternSyncMenuOptions,
onSelect: (value) => {
setPatternSyncFilter(value);
scrollContainerRef.current?.scrollTo(
0,
0
);
},
value: patternSyncFilter
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime242.jsx)("div", { className: "block-editor-inserter__patterns-filter-help", children: (0, import_element115.createInterpolateElement)(
(0, import_i18n54.__)(
"Patterns are available from the <Link>WordPress.org Pattern Directory</Link>, bundled in the active theme, or created by users on this site. Only patterns created on this site can be synced."
),
{
Link: /* @__PURE__ */ (0, import_jsx_runtime242.jsx)(
import_components48.ExternalLink,
{
href: (0, import_i18n54.__)(
"https://wordpress.org/patterns/"
)
}
)
}
) })
] })
}
) });
}
// packages/block-editor/build-module/components/inserter/block-patterns-tab/pattern-category-previews.mjs
var import_jsx_runtime243 = __toESM(require_jsx_runtime(), 1);
var noop10 = () => {
};
function PatternCategoryPreviews({
rootClientId,
onInsert,
onHover = noop10,
category,
showTitlesAsTooltip
}) {
const [allPatterns, , onClickPattern] = use_patterns_state_default(
onInsert,
rootClientId,
category?.name
);
const [patternSyncFilter, setPatternSyncFilter] = (0, import_element116.useState)("all");
const [patternSourceFilter, setPatternSourceFilter] = (0, import_element116.useState)("all");
const availableCategories = usePatternCategories(
rootClientId,
patternSourceFilter
);
const scrollContainerRef = (0, import_element116.useRef)();
const currentCategoryPatterns = (0, import_element116.useMemo)(
() => allPatterns.filter((pattern) => {
if (isPatternFiltered(
pattern,
patternSourceFilter,
patternSyncFilter
)) {
return false;
}
if (category.name === allPatternsCategory.name) {
return true;
}
if (category.name === myPatternsCategory.name && pattern.type === INSERTER_PATTERN_TYPES.user) {
return true;
}
if (category.name === starterPatternsCategory.name && pattern.blockTypes?.includes("core/post-content")) {
return true;
}
if (category.name === "uncategorized") {
if (!pattern.categories) {
return true;
}
return !pattern.categories.some(
(catName) => availableCategories.some((c6) => c6.name === catName)
);
}
return pattern.categories?.includes(category.name);
}),
[
allPatterns,
availableCategories,
category.name,
patternSourceFilter,
patternSyncFilter
]
);
const pagingProps = usePatternsPaging(
currentCategoryPatterns,
category,
scrollContainerRef
);
const { changePage } = pagingProps;
(0, import_element116.useEffect)(() => () => onHover(null), []);
const onSetPatternSyncFilter = (0, import_element116.useCallback)(
(value) => {
setPatternSyncFilter(value);
changePage(1);
},
[setPatternSyncFilter, changePage]
);
const onSetPatternSourceFilter = (0, import_element116.useCallback)(
(value) => {
setPatternSourceFilter(value);
changePage(1);
},
[setPatternSourceFilter, changePage]
);
return /* @__PURE__ */ (0, import_jsx_runtime243.jsxs)(import_jsx_runtime243.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime243.jsxs)(
import_components49.__experimentalVStack,
{
spacing: 2,
className: "block-editor-inserter__patterns-category-panel-header",
children: [
/* @__PURE__ */ (0, import_jsx_runtime243.jsxs)(import_components49.__experimentalHStack, { children: [
/* @__PURE__ */ (0, import_jsx_runtime243.jsx)(import_components49.FlexBlock, { children: /* @__PURE__ */ (0, import_jsx_runtime243.jsx)(
import_components49.__experimentalHeading,
{
className: "block-editor-inserter__patterns-category-panel-title",
size: 13,
level: 4,
as: "div",
children: category.label
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime243.jsx)(
PatternsFilter,
{
patternSyncFilter,
patternSourceFilter,
setPatternSyncFilter: onSetPatternSyncFilter,
setPatternSourceFilter: onSetPatternSourceFilter,
scrollContainerRef,
category
}
)
] }),
!currentCategoryPatterns.length && /* @__PURE__ */ (0, import_jsx_runtime243.jsx)(
import_components49.__experimentalText,
{
variant: "muted",
className: "block-editor-inserter__patterns-category-no-results",
children: (0, import_i18n55.__)("No results found")
}
)
]
}
),
currentCategoryPatterns.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime243.jsxs)(import_jsx_runtime243.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime243.jsx)(
import_components49.__experimentalText,
{
size: "12",
as: "p",
className: "block-editor-inserter__help-text",
children: (0, import_i18n55.__)("Drag and drop patterns into the canvas.")
}
),
/* @__PURE__ */ (0, import_jsx_runtime243.jsx)(
block_patterns_list_default,
{
ref: scrollContainerRef,
blockPatterns: pagingProps.categoryPatterns,
onClickPattern,
onHover,
label: category.label,
orientation: "vertical",
category: category.name,
isDraggable: true,
showTitlesAsTooltip,
patternFilter: patternSourceFilter,
pagingProps
}
)
] })
] });
}
// packages/block-editor/build-module/components/inserter/category-tabs/index.mjs
var import_compose41 = __toESM(require_compose(), 1);
var import_components50 = __toESM(require_components(), 1);
var import_element117 = __toESM(require_element(), 1);
var import_jsx_runtime244 = __toESM(require_jsx_runtime(), 1);
var { Tabs } = unlock(import_components50.privateApis);
function CategoryTabs({
categories,
selectedCategory,
onSelectCategory,
children
}) {
const ANIMATION_DURATION = 0.25;
const disableMotion = (0, import_compose41.useReducedMotion)();
const defaultTransition = {
type: "tween",
duration: disableMotion ? 0 : ANIMATION_DURATION,
ease: [0.6, 0, 0.4, 1]
};
const previousSelectedCategory = (0, import_compose41.usePrevious)(selectedCategory);
const selectedTabId = selectedCategory ? selectedCategory.name : null;
const [activeTabId, setActiveId] = (0, import_element117.useState)();
const firstTabId = categories?.[0]?.name;
if (selectedTabId === null && !activeTabId && firstTabId) {
setActiveId(firstTabId);
}
return /* @__PURE__ */ (0, import_jsx_runtime244.jsxs)(
Tabs,
{
selectOnMove: false,
selectedTabId,
orientation: "vertical",
onSelect: (categoryId) => {
onSelectCategory(
categories.find(
(category) => category.name === categoryId
)
);
},
activeTabId,
onActiveTabIdChange: setActiveId,
children: [
/* @__PURE__ */ (0, import_jsx_runtime244.jsx)(Tabs.TabList, { className: "block-editor-inserter__category-tablist", children: categories.map((category) => /* @__PURE__ */ (0, import_jsx_runtime244.jsx)(
Tabs.Tab,
{
tabId: category.name,
"aria-current": category === selectedCategory ? "true" : void 0,
children: category.label
},
category.name
)) }),
categories.map((category) => /* @__PURE__ */ (0, import_jsx_runtime244.jsx)(
Tabs.TabPanel,
{
tabId: category.name,
focusable: false,
children: /* @__PURE__ */ (0, import_jsx_runtime244.jsx)(
import_components50.__unstableMotion.div,
{
className: "block-editor-inserter__category-panel",
initial: !previousSelectedCategory ? "closed" : "open",
animate: "open",
variants: {
open: {
transform: "translateX( 0 )",
transitionEnd: {
zIndex: "1"
}
},
closed: {
transform: "translateX( -100% )",
zIndex: "-1"
}
},
transition: defaultTransition,
children
}
)
},
category.name
))
]
}
);
}
var category_tabs_default = CategoryTabs;
// packages/block-editor/build-module/components/inserter/block-patterns-tab/index.mjs
var import_jsx_runtime245 = __toESM(require_jsx_runtime(), 1);
function BlockPatternsTab({
onSelectCategory,
selectedCategory,
onInsert,
rootClientId,
children
}) {
const [showPatternsExplorer, setShowPatternsExplorer] = (0, import_element118.useState)(false);
const categories = usePatternCategories(rootClientId);
const isMobile = (0, import_compose42.useViewportMatch)("medium", "<");
if (!categories.length) {
return /* @__PURE__ */ (0, import_jsx_runtime245.jsx)(no_results_default, {});
}
return /* @__PURE__ */ (0, import_jsx_runtime245.jsxs)(import_jsx_runtime245.Fragment, { children: [
!isMobile && /* @__PURE__ */ (0, import_jsx_runtime245.jsxs)("div", { className: "block-editor-inserter__block-patterns-tabs-container", children: [
/* @__PURE__ */ (0, import_jsx_runtime245.jsx)(
category_tabs_default,
{
categories,
selectedCategory,
onSelectCategory,
children
}
),
/* @__PURE__ */ (0, import_jsx_runtime245.jsx)(
import_components51.Button,
{
__next40pxDefaultSize: true,
className: "block-editor-inserter__patterns-explore-button",
onClick: () => setShowPatternsExplorer(true),
variant: "secondary",
children: (0, import_i18n56.__)("Explore all patterns")
}
)
] }),
isMobile && /* @__PURE__ */ (0, import_jsx_runtime245.jsx)(MobileTabNavigation, { categories, children: (category) => /* @__PURE__ */ (0, import_jsx_runtime245.jsx)("div", { className: "block-editor-inserter__category-panel", children: /* @__PURE__ */ (0, import_jsx_runtime245.jsx)(
PatternCategoryPreviews,
{
onInsert,
rootClientId,
category
},
category.name
) }) }),
showPatternsExplorer && /* @__PURE__ */ (0, import_jsx_runtime245.jsx)(
block_patterns_explorer_default,
{
initialCategory: selectedCategory || categories[0],
patternCategories: categories,
onModalClose: () => setShowPatternsExplorer(false),
rootClientId
}
)
] });
}
var block_patterns_tab_default = BlockPatternsTab;
// packages/block-editor/build-module/components/inserter/media-tab/media-tab.mjs
var import_i18n60 = __toESM(require_i18n(), 1);
var import_compose44 = __toESM(require_compose(), 1);
var import_components56 = __toESM(require_components(), 1);
var import_element122 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/inserter/media-tab/media-panel.mjs
var import_components55 = __toESM(require_components(), 1);
var import_i18n59 = __toESM(require_i18n(), 1);
var import_element121 = __toESM(require_element(), 1);
var import_compose43 = __toESM(require_compose(), 1);
var import_data60 = __toESM(require_data(), 1);
var import_dom51 = __toESM(require_dom(), 1);
var import_notices7 = __toESM(require_notices(), 1);
// packages/block-editor/build-module/components/inserter/media-tab/media-list.mjs
var import_components53 = __toESM(require_components(), 1);
var import_i18n58 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/inserter/media-tab/media-preview.mjs
var import_components52 = __toESM(require_components(), 1);
var import_i18n57 = __toESM(require_i18n(), 1);
var import_element119 = __toESM(require_element(), 1);
var import_blocks39 = __toESM(require_blocks(), 1);
var import_data57 = __toESM(require_data(), 1);
var import_notices6 = __toESM(require_notices(), 1);
var import_blob = __toESM(require_blob(), 1);
var import_url2 = __toESM(require_url(), 1);
// packages/block-editor/build-module/components/inserter/media-tab/utils.mjs
var import_blocks38 = __toESM(require_blocks(), 1);
var import_jsx_runtime246 = __toESM(require_jsx_runtime(), 1);
var mediaTypeTag = { image: "img", video: "video", audio: "audio" };
function getBlockAndPreviewFromMedia(media, mediaType) {
const attributes = {
id: media.id || void 0,
caption: media.caption || void 0
};
const mediaSrc = media.url;
const alt = media.alt || void 0;
if (mediaType === "image") {
attributes.url = mediaSrc;
attributes.alt = alt;
} else if (["video", "audio"].includes(mediaType)) {
attributes.src = mediaSrc;
}
const PreviewTag = mediaTypeTag[mediaType];
const preview = /* @__PURE__ */ (0, import_jsx_runtime246.jsx)(
PreviewTag,
{
src: media.previewUrl || mediaSrc,
alt,
controls: mediaType === "audio" ? true : void 0,
inert: "true",
onError: ({ currentTarget }) => {
if (currentTarget.src === media.previewUrl) {
currentTarget.src = mediaSrc;
}
}
}
);
return [(0, import_blocks38.createBlock)(`core/${mediaType}`, attributes), preview];
}
// packages/block-editor/build-module/components/inserter/media-tab/media-preview.mjs
var import_jsx_runtime247 = __toESM(require_jsx_runtime(), 1);
var ALLOWED_MEDIA_TYPES = ["image"];
var MEDIA_OPTIONS_POPOVER_PROPS = {
placement: "bottom-end",
className: "block-editor-inserter__media-list__item-preview-options__popover"
};
function MediaPreviewOptions({ category, media, onDetach }) {
if (!category.getReportUrl && !onDetach) {
return null;
}
const reportUrl = category.getReportUrl?.(media);
return /* @__PURE__ */ (0, import_jsx_runtime247.jsx)(
import_components52.DropdownMenu,
{
className: "block-editor-inserter__media-list__item-preview-options",
label: (0, import_i18n57.__)("Options"),
popoverProps: MEDIA_OPTIONS_POPOVER_PROPS,
icon: more_vertical_default,
children: () => /* @__PURE__ */ (0, import_jsx_runtime247.jsxs)(import_components52.MenuGroup, { children: [
reportUrl && /* @__PURE__ */ (0, import_jsx_runtime247.jsx)(
import_components52.MenuItem,
{
onClick: () => window.open(reportUrl, "_blank").focus(),
icon: external_default,
children: (0, import_i18n57.sprintf)(
/* translators: %s: The media type to report e.g: "image", "video", "audio" */
(0, import_i18n57.__)("Report %s"),
category.mediaType
)
}
),
onDetach && /* @__PURE__ */ (0, import_jsx_runtime247.jsx)(
import_components52.MenuItem,
{
onClick: () => onDetach(media),
icon: link_off_default,
children: category.postTypeLabel ? (0, import_i18n57.sprintf)(
/* translators: %s: Name of the post type e.g: "Page". */
(0, import_i18n57.__)("Detach from %s"),
category.postTypeLabel
) : (0, import_i18n57.__)("Detach from post")
}
)
] })
}
);
}
function InsertExternalImageModal({ onClose, onSubmit }) {
return /* @__PURE__ */ (0, import_jsx_runtime247.jsxs)(
import_components52.Modal,
{
title: (0, import_i18n57.__)("Insert external image"),
onRequestClose: onClose,
className: "block-editor-inserter-media-tab-media-preview-inserter-external-image-modal",
children: [
/* @__PURE__ */ (0, import_jsx_runtime247.jsxs)(import_components52.__experimentalVStack, { spacing: 3, children: [
/* @__PURE__ */ (0, import_jsx_runtime247.jsx)("p", { children: (0, import_i18n57.__)(
"This image cannot be uploaded to your Media Library, but it can still be inserted as an external image."
) }),
/* @__PURE__ */ (0, import_jsx_runtime247.jsx)("p", { children: (0, import_i18n57.__)(
"External images can be removed by the external provider without warning and could even have legal compliance issues related to privacy legislation."
) })
] }),
/* @__PURE__ */ (0, import_jsx_runtime247.jsxs)(
import_components52.Flex,
{
className: "block-editor-block-lock-modal__actions",
justify: "flex-end",
expanded: false,
children: [
/* @__PURE__ */ (0, import_jsx_runtime247.jsx)(import_components52.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime247.jsx)(
import_components52.Button,
{
__next40pxDefaultSize: true,
variant: "tertiary",
onClick: onClose,
children: (0, import_i18n57.__)("Cancel")
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime247.jsx)(import_components52.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime247.jsx)(
import_components52.Button,
{
__next40pxDefaultSize: true,
variant: "primary",
onClick: onSubmit,
children: (0, import_i18n57.__)("Insert")
}
) })
]
}
)
]
}
);
}
function MediaPreview({ media, onClick, onDetach, category }) {
const [showExternalUploadModal, setShowExternalUploadModal] = (0, import_element119.useState)(false);
const [isHovered, setIsHovered] = (0, import_element119.useState)(false);
const [isInserting, setIsInserting] = (0, import_element119.useState)(false);
const [block, preview] = (0, import_element119.useMemo)(
() => getBlockAndPreviewFromMedia(media, category.mediaType),
[media, category.mediaType]
);
const { createErrorNotice, createSuccessNotice } = (0, import_data57.useDispatch)(import_notices6.store);
const { getSettings: getSettings7, getBlock: getBlock2 } = (0, import_data57.useSelect)(store);
const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data57.useDispatch)(store);
const onMediaInsert = (0, import_element119.useCallback)(
(previewBlock) => {
if (isInserting) {
return;
}
const settings2 = getSettings7();
const clonedBlock = (0, import_blocks39.cloneBlock)(previewBlock);
const { id, url, caption } = clonedBlock.attributes;
if (!id && !settings2.mediaUpload) {
setShowExternalUploadModal(true);
return;
}
if (!!id) {
onClick(clonedBlock);
return;
}
setIsInserting(true);
window.fetch(url).then((response) => response.blob()).then((blob) => {
const fileName = (0, import_url2.getFilename)(url) || "image.jpg";
const file = new File([blob], fileName, {
type: blob.type
});
settings2.mediaUpload({
filesList: [file],
additionalData: { caption },
onFileChange([img]) {
if ((0, import_blob.isBlobURL)(img.url)) {
return;
}
if (!getBlock2(clonedBlock.clientId)) {
onClick({
...clonedBlock,
attributes: {
...clonedBlock.attributes,
id: img.id,
url: img.url
}
});
createSuccessNotice(
(0, import_i18n57.__)("Image uploaded and inserted."),
{ type: "snackbar", id: "inserter-notice" }
);
} else {
updateBlockAttributes2(clonedBlock.clientId, {
...clonedBlock.attributes,
id: img.id,
url: img.url
});
}
setIsInserting(false);
},
allowedTypes: ALLOWED_MEDIA_TYPES,
onError(message2) {
createErrorNotice(message2, {
type: "snackbar",
id: "inserter-notice"
});
setIsInserting(false);
}
});
}).catch(() => {
setShowExternalUploadModal(true);
setIsInserting(false);
});
},
[
isInserting,
getSettings7,
onClick,
createSuccessNotice,
updateBlockAttributes2,
createErrorNotice,
getBlock2
]
);
const title = typeof media.title === "string" ? media.title : media.title?.rendered || (0, import_i18n57.__)("no title");
const onMouseEnter = (0, import_element119.useCallback)(() => setIsHovered(true), []);
const onMouseLeave = (0, import_element119.useCallback)(() => setIsHovered(false), []);
return /* @__PURE__ */ (0, import_jsx_runtime247.jsxs)(import_jsx_runtime247.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime247.jsx)(inserter_draggable_blocks_default, { isEnabled: true, blocks: [block], children: ({ draggable, onDragStart, onDragEnd }) => /* @__PURE__ */ (0, import_jsx_runtime247.jsx)(
"div",
{
className: clsx_default(
"block-editor-inserter__media-list__list-item",
{
"is-hovered": isHovered
}
),
draggable,
onDragStart,
onDragEnd,
children: /* @__PURE__ */ (0, import_jsx_runtime247.jsxs)(
"div",
{
onMouseEnter,
onMouseLeave,
children: [
/* @__PURE__ */ (0, import_jsx_runtime247.jsxs)(tooltip_exports.Root, { children: [
/* @__PURE__ */ (0, import_jsx_runtime247.jsx)(
tooltip_exports.Trigger,
{
render: /* @__PURE__ */ (0, import_jsx_runtime247.jsx)(
import_components52.Composite.Item,
{
render: /* @__PURE__ */ (0, import_jsx_runtime247.jsx)(
"div",
{
"aria-label": title,
role: "option",
className: "block-editor-inserter__media-list__item"
}
),
onClick: () => onMediaInsert(block),
children: /* @__PURE__ */ (0, import_jsx_runtime247.jsxs)("div", { className: "block-editor-inserter__media-list__item-preview", children: [
preview,
isInserting && /* @__PURE__ */ (0, import_jsx_runtime247.jsx)("div", { className: "block-editor-inserter__media-list__item-preview-spinner", children: /* @__PURE__ */ (0, import_jsx_runtime247.jsx)(import_components52.Spinner, {}) })
] })
}
)
}
),
/* @__PURE__ */ (0, import_jsx_runtime247.jsx)(tooltip_exports.Popup, { children: title })
] }),
!isInserting && /* @__PURE__ */ (0, import_jsx_runtime247.jsx)(
MediaPreviewOptions,
{
category,
media,
onDetach
}
)
]
}
)
}
) }),
showExternalUploadModal && /* @__PURE__ */ (0, import_jsx_runtime247.jsx)(
InsertExternalImageModal,
{
onClose: () => setShowExternalUploadModal(false),
onSubmit: () => {
onClick((0, import_blocks39.cloneBlock)(block));
createSuccessNotice((0, import_i18n57.__)("Image inserted."), {
type: "snackbar",
id: "inserter-notice"
});
setShowExternalUploadModal(false);
}
}
)
] });
}
// packages/block-editor/build-module/components/inserter/media-tab/media-list.mjs
var import_jsx_runtime248 = __toESM(require_jsx_runtime(), 1);
function MediaList({
mediaList,
category,
onClick,
onDetach,
label = (0, import_i18n58.__)("Media List")
}) {
return /* @__PURE__ */ (0, import_jsx_runtime248.jsx)(
import_components53.Composite,
{
role: "listbox",
className: "block-editor-inserter__media-list",
"aria-label": label,
children: mediaList.map((media, index2) => /* @__PURE__ */ (0, import_jsx_runtime248.jsx)(
MediaPreview,
{
media,
category,
onClick,
onDetach
},
media.id || media.sourceId || index2
))
}
);
}
var media_list_default = MediaList;
// packages/block-editor/build-module/components/media-upload/index.mjs
var import_components54 = __toESM(require_components(), 1);
var MediaUpload = () => null;
var media_upload_default = (0, import_components54.withFilters)("editor.MediaUpload")(MediaUpload);
// packages/block-editor/build-module/components/media-upload/check.mjs
var import_data58 = __toESM(require_data(), 1);
function MediaUploadCheck({ fallback = null, children }) {
const hasUploadPermissions = (0, import_data58.useSelect)((select3) => {
const { getSettings: getSettings7 } = select3(store);
return !!getSettings7().mediaUpload;
}, []);
return hasUploadPermissions ? children : fallback;
}
var check_default2 = MediaUploadCheck;
// packages/block-editor/build-module/components/inserter/media-tab/hooks.mjs
var import_element120 = __toESM(require_element(), 1);
var import_data59 = __toESM(require_data(), 1);
function normalizeFetchResult(result) {
if (Array.isArray(result)) {
return { mediaItems: result };
}
return {
mediaItems: result?.mediaItems ?? [],
totalItems: result?.totalItems,
totalPages: result?.totalPages
};
}
function useMediaResults(category, query = {}, refreshKey) {
const [mediaList, setMediaList] = (0, import_element120.useState)();
const [totals, setTotals] = (0, import_element120.useState)({});
const [isLoading, setIsLoading] = (0, import_element120.useState)(false);
const lastRequestRef = (0, import_element120.useRef)();
const lastQueryKeyRef = (0, import_element120.useRef)();
const lastFetchRef = (0, import_element120.useRef)();
const lastSourceRef = (0, import_element120.useRef)();
(0, import_element120.useEffect)(() => {
(async () => {
const key = JSON.stringify({
category: category.name,
...query
});
const request = {};
lastRequestRef.current = request;
setIsLoading(true);
if (lastQueryKeyRef.current !== key || lastFetchRef.current !== category.fetch) {
setMediaList([]);
}
if (lastSourceRef.current !== category.name || lastFetchRef.current !== category.fetch) {
setTotals({});
}
lastQueryKeyRef.current = key;
lastFetchRef.current = category.fetch;
lastSourceRef.current = category.name;
const { page, ...queryWithoutPage } = query;
const fetchQuery = page > 1 ? query : queryWithoutPage;
const { mediaItems, totalItems, totalPages } = normalizeFetchResult(
await category.fetch?.(fetchQuery)
);
if (request === lastRequestRef.current) {
setMediaList(mediaItems);
setTotals({ totalItems, totalPages });
setIsLoading(false);
}
})();
}, [
category.name,
category.fetch,
...Object.values(query),
refreshKey
]);
return {
mediaList,
isLoading,
totalItems: totals.totalItems,
totalPages: totals.totalPages
};
}
function useDelayedLoading(isLoading, delay = 400) {
const [showLoading, setShowLoading] = (0, import_element120.useState)(false);
(0, import_element120.useEffect)(() => {
if (!isLoading) {
return void 0;
}
const timeout = setTimeout(() => setShowLoading(true), delay);
return () => {
clearTimeout(timeout);
setShowLoading(false);
};
}, [isLoading, delay]);
return showLoading;
}
function useMediaCategories(rootClientId) {
const [categories, setCategories] = (0, import_element120.useState)([]);
const inserterMediaCategories = (0, import_data59.useSelect)(
(select3) => unlock(select3(store)).getInserterMediaCategories(),
[]
);
const { canInsertImage, canInsertVideo, canInsertAudio } = (0, import_data59.useSelect)(
(select3) => {
const { canInsertBlockType: canInsertBlockType2 } = select3(store);
return {
canInsertImage: canInsertBlockType2(
"core/image",
rootClientId
),
canInsertVideo: canInsertBlockType2(
"core/video",
rootClientId
),
canInsertAudio: canInsertBlockType2(
"core/audio",
rootClientId
)
};
},
[rootClientId]
);
(0, import_element120.useEffect)(() => {
(async () => {
const _categories = [];
if (!inserterMediaCategories) {
return;
}
const categoriesHaveMedia = new Map(
await Promise.all(
inserterMediaCategories.map(async (category) => {
if (category.isExternalResource) {
return [category.name, true];
}
let results = [];
try {
const { mediaItems } = normalizeFetchResult(
await category.fetch({ per_page: 1 })
);
results = mediaItems;
} catch {
}
return [category.name, !!results.length];
})
)
);
const canInsertMediaType = {
image: canInsertImage,
video: canInsertVideo,
audio: canInsertAudio
};
inserterMediaCategories.forEach((category) => {
if (canInsertMediaType[category.mediaType] && (categoriesHaveMedia.get(category.name) || category.emptyMessage)) {
_categories.push(category);
}
});
if (!!_categories.length) {
setCategories(_categories);
}
})();
}, [
canInsertImage,
canInsertVideo,
canInsertAudio,
inserterMediaCategories
]);
return categories;
}
// packages/block-editor/build-module/components/inserter/media-tab/media-panel.mjs
var import_jsx_runtime249 = __toESM(require_jsx_runtime(), 1);
var MEDIA_ITEMS_PER_PAGE = 20;
var ATTACH_ALLOWED_TYPES = ["image"];
function AttachImagesButton({ onSelect }) {
return /* @__PURE__ */ (0, import_jsx_runtime249.jsx)(check_default2, { children: /* @__PURE__ */ (0, import_jsx_runtime249.jsx)(
media_upload_default,
{
multiple: "add",
onSelect,
allowedTypes: ATTACH_ALLOWED_TYPES,
title: (0, import_i18n59.__)("Attach images"),
render: ({ open }) => /* @__PURE__ */ (0, import_jsx_runtime249.jsx)(
import_components55.Button,
{
__next40pxDefaultSize: true,
className: "block-editor-inserter__media-panel-attach",
"data-unstable-ignore-focus-outside-for-relatedtarget": ".media-modal",
onClick: (event) => {
event.target.focus();
open();
},
variant: "secondary",
children: (0, import_i18n59.__)("Attach images")
}
)
}
) });
}
function MediaCategoryPanel({ rootClientId, onInsert, category }) {
const [search, setSearch, debouncedSearch] = (0, import_compose43.useDebouncedInput)();
const [page, setPage] = (0, import_element121.useState)(1);
const previousCategory = (0, import_compose43.usePrevious)(category.name);
const previousSearch = (0, import_compose43.usePrevious)(debouncedSearch);
if ((previousCategory !== category.name || previousSearch !== debouncedSearch) && page !== 1) {
setPage(1);
}
const query = (0, import_element121.useMemo)(
() => ({
per_page: MEDIA_ITEMS_PER_PAGE,
page,
search: debouncedSearch
}),
[page, debouncedSearch]
);
const [refreshKey, setRefreshKey] = (0, import_element121.useState)(0);
const { mediaList, isLoading, totalItems, totalPages } = useMediaResults(
category,
query,
refreshKey
);
const numPages = totalPages || 1;
if (typeof totalPages === "number" && page > numPages) {
setPage(numPages);
}
const supportsAttachments = !category.isExternalResource;
const attach = supportsAttachments ? category.attach : void 0;
const detach = supportsAttachments ? category.detach : void 0;
const subscribe = supportsAttachments ? category.subscribe : void 0;
const showPagination = numPages > 1;
const hasFooter = showPagination || !!attach;
const scrollContainerRef = (0, import_element121.useRef)();
const changePage = (0, import_element121.useCallback)((nextPage) => {
const scrollContainer = (0, import_dom51.getScrollContainer)(
scrollContainerRef.current
);
scrollContainer?.scrollTo(0, 0);
setPage(nextPage);
}, []);
const { createErrorNotice, createSuccessNotice, createWarningNotice } = (0, import_data60.useDispatch)(import_notices7.store);
const showRefreshing = useDelayedLoading(isLoading);
const refresh = (0, import_element121.useCallback)(() => {
if (supportsAttachments) {
category.invalidate?.(query);
}
setRefreshKey((key) => key + 1);
}, [category, query, supportsAttachments]);
(0, import_element121.useEffect)(() => {
if (!subscribe) {
return;
}
return subscribe(() => setRefreshKey((key) => key + 1), query);
}, [subscribe, query]);
const handleAttach = (0, import_element121.useCallback)(
async (selectedMedia) => {
try {
const attachedCount = await attach(selectedMedia);
if (!attachedCount) {
createWarningNotice((0, import_i18n59.__)("No images were attached."), {
type: "snackbar",
id: "inserter-notice"
});
return;
}
refresh();
createSuccessNotice(
category.postTypeLabel ? (0, import_i18n59.sprintf)(
/* translators: %1$d: Number of images attached. %2$s: Name of the post type e.g: "Page". */
(0, import_i18n59._n)(
"%1$d image attached to %2$s.",
"%1$d images attached to %2$s.",
attachedCount
),
attachedCount,
category.postTypeLabel
) : (0, import_i18n59.sprintf)(
/* translators: %d: Number of images attached to the post. */
(0, import_i18n59._n)(
"%d image attached to post.",
"%d images attached to post.",
attachedCount
),
attachedCount
),
{ type: "snackbar", id: "inserter-notice" }
);
} catch {
createErrorNotice((0, import_i18n59.__)("Could not attach images."), {
type: "snackbar",
id: "inserter-notice"
});
}
},
[
attach,
category,
refresh,
createErrorNotice,
createSuccessNotice,
createWarningNotice
]
);
const handleDetach = (0, import_element121.useCallback)(
async (media) => {
try {
await detach(media);
refresh();
createSuccessNotice(
category.postTypeLabel ? (0, import_i18n59.sprintf)(
/* translators: %s: Name of the post type e.g: "Page". */
(0, import_i18n59.__)("Image detached from %s."),
category.postTypeLabel
) : (0, import_i18n59.__)("Image detached from post."),
{ type: "snackbar", id: "inserter-notice" }
);
} catch {
createErrorNotice((0, import_i18n59.__)("Could not detach image."), {
type: "snackbar",
id: "inserter-notice"
});
}
},
[detach, category, refresh, createErrorNotice, createSuccessNotice]
);
const [mediaPendingDetach, setMediaPendingDetach] = (0, import_element121.useState)();
const confirmDetach = (0, import_element121.useCallback)(() => {
const media = mediaPendingDetach;
setMediaPendingDetach(void 0);
handleDetach(media);
}, [handleDetach, mediaPendingDetach]);
const baseCssClass = "block-editor-inserter__media-panel";
const searchLabel = category.labels.search_items || (0, import_i18n59.__)("Search");
return /* @__PURE__ */ (0, import_jsx_runtime249.jsxs)(
"div",
{
ref: scrollContainerRef,
className: clsx_default(baseCssClass, {
// The footer supplies the breathing room beneath the grid, so the
// list drops its own bottom padding (see styles).
"has-footer": hasFooter
}),
children: [
/* @__PURE__ */ (0, import_jsx_runtime249.jsx)(
import_components55.SearchControl,
{
className: `${baseCssClass}-search`,
onChange: setSearch,
value: search,
label: searchLabel,
placeholder: searchLabel
}
),
isLoading && !mediaList?.length && /* @__PURE__ */ (0, import_jsx_runtime249.jsx)("div", { className: `${baseCssClass}-spinner`, children: /* @__PURE__ */ (0, import_jsx_runtime249.jsx)(import_components55.Spinner, {}) }),
!isLoading && !mediaList?.length && /* @__PURE__ */ (0, import_jsx_runtime249.jsx)(no_results_default, { children: category.emptyMessage && !debouncedSearch ? (
// For a source with a custom empty message (e.g.
// Attachments) and no active search, an empty result
// means nothing is attached yet — clearer than the
// generic "no results found".
category.emptyMessage
) : (0, import_i18n59.__)("No results found.") }),
!!mediaList?.length && // Keep the existing items visible while a refetch is in flight,
// dimming (and gently pulsing) them rather than clearing the grid,
// so it doesn't flicker or pop.
/* @__PURE__ */ (0, import_jsx_runtime249.jsx)(
"div",
{
className: clsx_default(`${baseCssClass}-results`, {
"is-loading": showRefreshing
}),
"aria-busy": showRefreshing,
children: /* @__PURE__ */ (0, import_jsx_runtime249.jsx)(
media_list_default,
{
rootClientId,
onClick: onInsert,
onDetach: detach ? setMediaPendingDetach : void 0,
mediaList,
category
}
)
}
),
hasFooter && // A single footer wrapper owns the top and horizontal breathing
// room, so the pager and attach button don't span the full width
// and sit clear of the grid above (see styles).
/* @__PURE__ */ (0, import_jsx_runtime249.jsxs)(
Stack,
{
direction: "column",
gap: "sm",
className: `${baseCssClass}-footer`,
children: [
showPagination && // Reuse the Patterns tab pager (presentational only); only
// rendered for multi-page sources (see `showPagination`).
/* @__PURE__ */ (0, import_jsx_runtime249.jsx)(
Pagination,
{
currentPage: page,
numPages,
changePage,
totalItems
}
),
attach && // Lines up with the "Open Media Library" button in the
// adjacent column.
/* @__PURE__ */ (0, import_jsx_runtime249.jsx)(AttachImagesButton, { onSelect: handleAttach })
]
}
),
mediaPendingDetach && // A plain `Modal` (not `ConfirmDialog`) so we can pass
// `overlayClassName` and stack it above the options dropdown that
// opened it (see the z-index entry in `_z-index.scss`).
/* @__PURE__ */ (0, import_jsx_runtime249.jsxs)(
import_components55.Modal,
{
title: (0, import_i18n59.__)("Detach image"),
onRequestClose: () => setMediaPendingDetach(void 0),
overlayClassName: `${baseCssClass}-detach-modal`,
children: [
/* @__PURE__ */ (0, import_jsx_runtime249.jsx)("p", { children: category.postTypeLabel ? (0, import_i18n59.sprintf)(
/* translators: %s: Name of the post type e.g: "Page". */
(0, import_i18n59.__)(
"Detach this image from the current %s? The image will remain in the Media Library."
),
category.postTypeLabel
) : (0, import_i18n59.__)(
"Detach this image from the current post? The image will remain in the Media Library."
) }),
/* @__PURE__ */ (0, import_jsx_runtime249.jsxs)("div", { className: `${baseCssClass}-detach-actions`, children: [
/* @__PURE__ */ (0, import_jsx_runtime249.jsx)(
import_components55.Button,
{
__next40pxDefaultSize: true,
variant: "tertiary",
onClick: () => setMediaPendingDetach(void 0),
children: (0, import_i18n59.__)("Cancel")
}
),
/* @__PURE__ */ (0, import_jsx_runtime249.jsx)(
import_components55.Button,
{
__next40pxDefaultSize: true,
variant: "primary",
onClick: confirmDetach,
children: (0, import_i18n59.__)("Detach")
}
)
] })
]
}
)
]
}
);
}
// packages/block-editor/build-module/components/inserter/media-tab/media-tab.mjs
var import_jsx_runtime250 = __toESM(require_jsx_runtime(), 1);
var ALLOWED_MEDIA_TYPES2 = ["image", "video", "audio"];
function MediaTab({
rootClientId,
selectedCategory,
onSelectCategory,
onInsert,
children
}) {
const mediaCategories = useMediaCategories(rootClientId);
const isMobile = (0, import_compose44.useViewportMatch)("medium", "<");
const baseCssClass = "block-editor-inserter__media-tabs";
const onSelectMedia = (0, import_element122.useCallback)(
(media) => {
if (!media?.url) {
return;
}
const mediaType = window.__experimentalDataViewsMediaModal && media.mime_type ? media.mime_type.split("/")[0] : media.type;
const [block] = getBlockAndPreviewFromMedia(media, mediaType);
onInsert(block);
},
[onInsert]
);
const categories = (0, import_element122.useMemo)(
() => mediaCategories.map((mediaCategory) => ({
...mediaCategory,
label: mediaCategory.labels.name
})),
[mediaCategories]
);
(0, import_element122.useEffect)(() => {
if (!selectedCategory) {
return;
}
const latestCategory = categories.find(
(category) => category.name === selectedCategory.name
);
if (latestCategory && latestCategory !== selectedCategory) {
onSelectCategory(latestCategory);
} else if (!latestCategory) {
onSelectCategory(null);
}
}, [categories, onSelectCategory, selectedCategory]);
if (!categories.length) {
return /* @__PURE__ */ (0, import_jsx_runtime250.jsx)(no_results_default, {});
}
return /* @__PURE__ */ (0, import_jsx_runtime250.jsxs)(import_jsx_runtime250.Fragment, { children: [
!isMobile && /* @__PURE__ */ (0, import_jsx_runtime250.jsxs)("div", { className: `${baseCssClass}-container`, children: [
/* @__PURE__ */ (0, import_jsx_runtime250.jsx)(
category_tabs_default,
{
categories,
selectedCategory,
onSelectCategory,
children
}
),
/* @__PURE__ */ (0, import_jsx_runtime250.jsx)(check_default2, { children: /* @__PURE__ */ (0, import_jsx_runtime250.jsx)(
media_upload_default,
{
multiple: false,
onSelect: onSelectMedia,
allowedTypes: ALLOWED_MEDIA_TYPES2,
render: ({ open }) => /* @__PURE__ */ (0, import_jsx_runtime250.jsx)(
import_components56.Button,
{
__next40pxDefaultSize: true,
onClick: (event) => {
event.target.focus();
open();
},
className: "block-editor-inserter__media-library-button",
variant: "secondary",
"data-unstable-ignore-focus-outside-for-relatedtarget": ".media-modal",
children: (0, import_i18n60.__)("Open Media Library")
}
)
}
) })
] }),
isMobile && /* @__PURE__ */ (0, import_jsx_runtime250.jsx)(
MobileTabNavigation,
{
categories,
screenClassName: "block-editor-inserter__media-mobile-screen",
children: (category) => /* @__PURE__ */ (0, import_jsx_runtime250.jsx)(
MediaCategoryPanel,
{
onInsert,
rootClientId,
category
}
)
}
)
] });
}
var media_tab_default = MediaTab;
// packages/block-editor/build-module/components/inserter/search-results.mjs
var import_element123 = __toESM(require_element(), 1);
var import_i18n61 = __toESM(require_i18n(), 1);
var import_compose45 = __toESM(require_compose(), 1);
var import_a11y9 = __toESM(require_a11y(), 1);
var import_data61 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/inserter-menu-extension/index.mjs
var import_components57 = __toESM(require_components(), 1);
var { Fill: __unstableInserterMenuExtension, Slot } = (0, import_components57.createSlotFill)(
"__unstableInserterMenuExtension"
);
__unstableInserterMenuExtension.Slot = Slot;
var inserter_menu_extension_default = __unstableInserterMenuExtension;
// packages/block-editor/build-module/components/inserter/search-results.mjs
var import_jsx_runtime251 = __toESM(require_jsx_runtime(), 1);
var INITIAL_INSERTER_RESULTS = 9;
var EMPTY_ARRAY7 = [];
function InserterSearchResults({
filterValue,
onSelect,
onHover,
onHoverPattern,
rootClientId,
clientId,
isAppender,
__experimentalInsertionIndex,
maxBlockPatterns,
maxBlockTypes,
showBlockDirectory = false,
isDraggable = true,
shouldFocusBlock = true,
prioritizePatterns,
selectBlockOnInsert,
isQuick
}) {
const debouncedSpeak = (0, import_compose45.useDebounce)(import_a11y9.speak, 500);
const { prioritizedBlocks } = (0, import_data61.useSelect)(
(select3) => {
const blockListSettings2 = select3(store).getBlockListSettings(rootClientId);
return {
prioritizedBlocks: blockListSettings2?.prioritizedInserterBlocks || EMPTY_ARRAY7
};
},
[rootClientId]
);
const [destinationRootClientId, onInsertBlocks] = use_insertion_point_default({
onSelect,
rootClientId,
clientId,
isAppender,
insertionIndex: __experimentalInsertionIndex,
shouldFocusBlock,
selectBlockOnInsert
});
const [
blockTypes,
blockTypeCategories,
blockTypeCollections,
onSelectBlockType
] = use_block_types_state_default(destinationRootClientId, onInsertBlocks, isQuick);
const [patterns, , onClickPattern] = use_patterns_state_default(
onInsertBlocks,
destinationRootClientId,
void 0,
isQuick
);
const filteredBlockPatterns = (0, import_element123.useMemo)(() => {
if (maxBlockPatterns === 0) {
return [];
}
const results = searchItems(patterns, filterValue);
return maxBlockPatterns !== void 0 ? results.slice(0, maxBlockPatterns) : results;
}, [filterValue, patterns, maxBlockPatterns]);
let maxBlockTypesToShow = maxBlockTypes;
if (prioritizePatterns && filteredBlockPatterns.length > 2) {
maxBlockTypesToShow = 0;
}
const filteredBlockTypes = (0, import_element123.useMemo)(() => {
if (maxBlockTypesToShow === 0) {
return [];
}
const nonPatternBlockTypes = blockTypes.filter(
(blockType) => blockType.name !== "core/block"
);
let orderedItems = orderBy(nonPatternBlockTypes, "frecency", "desc");
if (!filterValue && prioritizedBlocks.length) {
orderedItems = orderInserterBlockItems(
orderedItems,
prioritizedBlocks
);
}
const results = searchBlockItems(
orderedItems,
blockTypeCategories,
blockTypeCollections,
filterValue
);
return maxBlockTypesToShow !== void 0 ? results.slice(0, maxBlockTypesToShow) : results;
}, [
filterValue,
blockTypes,
blockTypeCategories,
blockTypeCollections,
maxBlockTypesToShow,
prioritizedBlocks
]);
(0, import_element123.useEffect)(() => {
if (!filterValue) {
return;
}
const count = filteredBlockTypes.length + filteredBlockPatterns.length;
const resultsFoundMessage = (0, import_i18n61.sprintf)(
/* translators: %d: number of results. */
(0, import_i18n61._n)("%d result found.", "%d results found.", count),
count
);
debouncedSpeak(resultsFoundMessage);
}, [
filterValue,
debouncedSpeak,
filteredBlockTypes,
filteredBlockPatterns
]);
const currentShownBlockTypes = (0, import_compose45.useAsyncList)(filteredBlockTypes, {
step: INITIAL_INSERTER_RESULTS
});
const hasItems = filteredBlockTypes.length > 0 || filteredBlockPatterns.length > 0;
const blocksUI = !!filteredBlockTypes.length && /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(
panel_default,
{
title: /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(VisuallyHidden, { children: (0, import_i18n61.__)("Blocks") }),
children: /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(
block_types_list_default,
{
items: currentShownBlockTypes,
onSelect: onSelectBlockType,
onHover,
label: (0, import_i18n61.__)("Blocks"),
isDraggable
}
)
}
);
const patternsUI = !!filteredBlockPatterns.length && /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(
panel_default,
{
title: /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(VisuallyHidden, { children: (0, import_i18n61.__)("Patterns") }),
children: /* @__PURE__ */ (0, import_jsx_runtime251.jsx)("div", { className: "block-editor-inserter__quick-inserter-patterns", children: /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(
block_patterns_list_default,
{
blockPatterns: filteredBlockPatterns,
onClickPattern,
onHover: onHoverPattern,
isDraggable
}
) })
}
);
return /* @__PURE__ */ (0, import_jsx_runtime251.jsxs)(inserter_listbox_default, { children: [
!showBlockDirectory && !hasItems && /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(no_results_default, {}),
prioritizePatterns ? patternsUI : blocksUI,
!!filteredBlockTypes.length && !!filteredBlockPatterns.length && /* @__PURE__ */ (0, import_jsx_runtime251.jsx)("div", { className: "block-editor-inserter__quick-inserter-separator" }),
prioritizePatterns ? blocksUI : patternsUI,
showBlockDirectory && /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(
inserter_menu_extension_default.Slot,
{
fillProps: {
onSelect: onSelectBlockType,
onHover,
filterValue,
hasItems,
rootClientId: destinationRootClientId
},
children: (fills) => {
if (fills.length) {
return fills;
}
if (!hasItems) {
return /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(no_results_default, {});
}
return null;
}
}
)
] });
}
var search_results_default = InserterSearchResults;
// packages/block-editor/build-module/components/tabbed-sidebar/index.mjs
var import_components58 = __toESM(require_components(), 1);
var import_element124 = __toESM(require_element(), 1);
var import_jsx_runtime252 = __toESM(require_jsx_runtime(), 1);
var { Tabs: Tabs2 } = unlock(import_components58.privateApis);
function TabbedSidebar({ defaultTabId, onClose, onSelect, selectedTab, tabs, closeButtonLabel }, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime252.jsx)("div", { className: "block-editor-tabbed-sidebar", children: /* @__PURE__ */ (0, import_jsx_runtime252.jsxs)(
Tabs2,
{
selectOnMove: false,
defaultTabId,
onSelect,
selectedTabId: selectedTab,
children: [
/* @__PURE__ */ (0, import_jsx_runtime252.jsxs)("div", { className: "block-editor-tabbed-sidebar__tablist-and-close-button", children: [
/* @__PURE__ */ (0, import_jsx_runtime252.jsx)(
import_components58.Button,
{
className: "block-editor-tabbed-sidebar__close-button",
icon: close_small_default,
label: closeButtonLabel,
onClick: () => onClose(),
size: "compact"
}
),
/* @__PURE__ */ (0, import_jsx_runtime252.jsx)(
Tabs2.TabList,
{
className: "block-editor-tabbed-sidebar__tablist",
ref,
children: tabs.map((tab) => /* @__PURE__ */ (0, import_jsx_runtime252.jsx)(
Tabs2.Tab,
{
tabId: tab.name,
className: "block-editor-tabbed-sidebar__tab",
children: tab.title
},
tab.name
))
}
)
] }),
tabs.map((tab) => /* @__PURE__ */ (0, import_jsx_runtime252.jsx)(
Tabs2.TabPanel,
{
tabId: tab.name,
focusable: false,
className: "block-editor-tabbed-sidebar__tabpanel",
ref: tab.panelRef,
children: tab.panel
},
tab.name
))
]
}
) });
}
var tabbed_sidebar_default = (0, import_element124.forwardRef)(TabbedSidebar);
// packages/block-editor/build-module/hooks/use-zoom-out.mjs
var import_data62 = __toESM(require_data(), 1);
var import_element125 = __toESM(require_element(), 1);
function useZoomOut(enabled = true) {
const { setZoomLevel: setZoomLevel2, resetZoomLevel: resetZoomLevel2 } = unlock(
(0, import_data62.useDispatch)(store)
);
const { isZoomedOut, isZoomOut: isZoomOut2 } = (0, import_data62.useSelect)((select3) => {
const { isZoomOut: _isZoomOut } = unlock(select3(store));
return {
isZoomedOut: _isZoomOut(),
isZoomOut: _isZoomOut
};
}, []);
const controlZoomLevelRef = (0, import_element125.useRef)(false);
const isEnabledRef = (0, import_element125.useRef)(enabled);
(0, import_element125.useEffect)(() => {
if (isZoomedOut !== isEnabledRef.current) {
controlZoomLevelRef.current = false;
}
}, [isZoomedOut]);
(0, import_element125.useEffect)(() => {
isEnabledRef.current = enabled;
if (enabled !== isZoomOut2()) {
controlZoomLevelRef.current = true;
if (enabled) {
setZoomLevel2("auto-scaled");
} else {
resetZoomLevel2();
}
}
return () => {
if (controlZoomLevelRef.current && isZoomOut2()) {
resetZoomLevel2();
}
};
}, [enabled, isZoomOut2, resetZoomLevel2, setZoomLevel2]);
}
// packages/block-editor/build-module/components/inserter/menu.mjs
var import_jsx_runtime253 = __toESM(require_jsx_runtime(), 1);
var NOOP2 = () => {
};
function InserterMenu({
rootClientId,
clientId,
isAppender,
__experimentalInsertionIndex,
onSelect,
showInserterHelpPanel,
showMostUsedBlocks,
__experimentalFilterValue = "",
shouldFocusBlock = true,
onPatternCategorySelection,
onClose,
__experimentalInitialTab,
__experimentalInitialCategory
}, ref) {
const { isZoomOutMode, hasSectionRootClientId } = (0, import_data63.useSelect)((select3) => {
const { isZoomOut: isZoomOut2, getSectionRootClientId: getSectionRootClientId2 } = unlock(
select3(store)
);
return {
isZoomOutMode: isZoomOut2(),
hasSectionRootClientId: !!getSectionRootClientId2()
};
}, []);
const [filterValue, setFilterValue, delayedFilterValue] = (0, import_compose46.useDebouncedInput)(__experimentalFilterValue);
const [hoveredItem, setHoveredItem] = (0, import_element126.useState)(null);
const [selectedPatternCategory, setSelectedPatternCategory] = (0, import_element126.useState)(
__experimentalInitialCategory
);
const [patternFilter, setPatternFilter] = (0, import_element126.useState)("all");
const [selectedMediaCategory, setSelectedMediaCategory] = (0, import_element126.useState)(null);
const isLargeViewport = (0, import_compose46.useViewportMatch)("large");
const isMobileViewport = (0, import_compose46.useViewportMatch)("medium", "<");
const maybeCloseInserter = isMobileViewport ? onClose : NOOP2;
function getInitialTab() {
if (__experimentalInitialTab) {
return __experimentalInitialTab;
}
if (isZoomOutMode) {
return "patterns";
}
return "blocks";
}
const [selectedTab, setSelectedTab] = (0, import_element126.useState)(getInitialTab());
const shouldUseZoomOut = hasSectionRootClientId && (selectedTab === "patterns" || selectedTab === "media");
useZoomOut(shouldUseZoomOut && isLargeViewport);
const [destinationRootClientId, onInsertBlocks, onToggleInsertionPoint] = use_insertion_point_default({
rootClientId,
clientId,
isAppender,
insertionIndex: __experimentalInsertionIndex,
shouldFocusBlock
});
const blockTypesTabRef = (0, import_element126.useRef)();
const onInsert = (0, import_element126.useCallback)(
(blocks2, meta, shouldForceFocusBlock, _rootClientId) => {
onInsertBlocks(
blocks2,
meta,
shouldForceFocusBlock,
_rootClientId
);
onSelect(blocks2);
maybeCloseInserter();
window.requestAnimationFrame(() => {
if (!shouldFocusBlock && !blockTypesTabRef.current?.contains(
ref.current.ownerDocument.activeElement
)) {
blockTypesTabRef.current?.querySelector("button").focus();
}
});
},
[onInsertBlocks, maybeCloseInserter, onSelect, ref, shouldFocusBlock]
);
const onInsertPattern = (0, import_element126.useCallback)(
(blocks2, patternName, ...args) => {
onToggleInsertionPoint(false);
onInsertBlocks(blocks2, { patternName }, ...args);
onSelect();
maybeCloseInserter();
},
[onInsertBlocks, maybeCloseInserter, onSelect, onToggleInsertionPoint]
);
const onHover = (0, import_element126.useCallback)(
(item) => {
onToggleInsertionPoint(item);
setHoveredItem(item);
},
[onToggleInsertionPoint, setHoveredItem]
);
const onClickPatternCategory = (0, import_element126.useCallback)(
(patternCategory, filter) => {
setSelectedPatternCategory(patternCategory);
setPatternFilter(filter);
onPatternCategorySelection?.();
},
[setSelectedPatternCategory, onPatternCategorySelection]
);
const showPatternPanel = selectedTab === "patterns" && !delayedFilterValue && !!selectedPatternCategory;
const showMediaPanel = selectedTab === "media" && !!selectedMediaCategory;
const [isScrolled, setIsScrolled] = (0, import_element126.useState)(false);
const blocksPanelRef = (0, import_element126.useRef)(null);
const patternsPanelRef = (0, import_element126.useRef)(null);
const mediaPanelRef = (0, import_element126.useRef)(null);
(0, import_element126.useEffect)(() => {
const handleScroll = (event) => {
setIsScrolled(event.currentTarget.scrollTop > 0);
};
const panels = [
blocksPanelRef.current,
patternsPanelRef.current,
mediaPanelRef.current
].filter(Boolean);
panels.forEach(
(panel) => panel.addEventListener("scroll", handleScroll)
);
return () => {
panels.forEach(
(panel) => panel.removeEventListener("scroll", handleScroll)
);
};
}, []);
const inserterSearch = (0, import_element126.useMemo)(() => {
if (selectedTab === "media") {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime253.jsxs)(import_jsx_runtime253.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime253.jsx)(
import_components59.SearchControl,
{
className: clsx_default("block-editor-inserter__search", {
"is-scrolled": isScrolled
}),
onChange: (value) => {
if (hoveredItem) {
setHoveredItem(null);
}
setFilterValue(value);
},
value: filterValue,
label: (0, import_i18n62.__)("Search"),
placeholder: (0, import_i18n62.__)("Search")
}
),
!!delayedFilterValue && /* @__PURE__ */ (0, import_jsx_runtime253.jsx)(
search_results_default,
{
filterValue: delayedFilterValue,
onSelect,
onHover,
rootClientId,
clientId,
isAppender,
__experimentalInsertionIndex,
showBlockDirectory: true,
shouldFocusBlock,
prioritizePatterns: selectedTab === "patterns"
}
)
] });
}, [
selectedTab,
hoveredItem,
setHoveredItem,
setFilterValue,
filterValue,
delayedFilterValue,
onSelect,
onHover,
shouldFocusBlock,
clientId,
rootClientId,
__experimentalInsertionIndex,
isAppender,
isScrolled
]);
const blocksTab = (0, import_element126.useMemo)(() => {
return /* @__PURE__ */ (0, import_jsx_runtime253.jsxs)(import_jsx_runtime253.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime253.jsx)("div", { className: "block-editor-inserter__block-list", children: /* @__PURE__ */ (0, import_jsx_runtime253.jsx)(
block_types_tab_default,
{
ref: blockTypesTabRef,
rootClientId: destinationRootClientId,
onInsert,
onHover,
showMostUsedBlocks
}
) }),
showInserterHelpPanel && /* @__PURE__ */ (0, import_jsx_runtime253.jsxs)("div", { className: "block-editor-inserter__tips", children: [
/* @__PURE__ */ (0, import_jsx_runtime253.jsx)(VisuallyHidden, { render: /* @__PURE__ */ (0, import_jsx_runtime253.jsx)("h2", {}), children: (0, import_i18n62.__)("A tip for using the block editor") }),
/* @__PURE__ */ (0, import_jsx_runtime253.jsx)(tips_default, {})
] })
] });
}, [
destinationRootClientId,
onInsert,
onHover,
showMostUsedBlocks,
showInserterHelpPanel
]);
const patternsTab = (0, import_element126.useMemo)(() => {
return /* @__PURE__ */ (0, import_jsx_runtime253.jsx)(
block_patterns_tab_default,
{
rootClientId: destinationRootClientId,
onInsert: onInsertPattern,
onSelectCategory: onClickPatternCategory,
selectedCategory: selectedPatternCategory,
children: showPatternPanel && /* @__PURE__ */ (0, import_jsx_runtime253.jsx)(
PatternCategoryPreviews,
{
rootClientId: destinationRootClientId,
onInsert: onInsertPattern,
category: selectedPatternCategory,
patternFilter,
showTitlesAsTooltip: true
}
)
}
);
}, [
destinationRootClientId,
onInsertPattern,
onClickPatternCategory,
patternFilter,
selectedPatternCategory,
showPatternPanel
]);
const mediaTab = (0, import_element126.useMemo)(() => {
return /* @__PURE__ */ (0, import_jsx_runtime253.jsx)(
media_tab_default,
{
rootClientId: destinationRootClientId,
selectedCategory: selectedMediaCategory,
onSelectCategory: setSelectedMediaCategory,
onInsert,
children: showMediaPanel && /* @__PURE__ */ (0, import_jsx_runtime253.jsx)(
MediaCategoryPanel,
{
rootClientId: destinationRootClientId,
onInsert,
category: selectedMediaCategory
}
)
}
);
}, [
destinationRootClientId,
onInsert,
selectedMediaCategory,
setSelectedMediaCategory,
showMediaPanel
]);
const handleSetSelectedTab = (value) => {
if (value !== "patterns") {
setSelectedPatternCategory(null);
}
setSelectedTab(value);
};
const tabsRef = (0, import_element126.useRef)();
(0, import_element126.useLayoutEffect)(() => {
if (tabsRef.current) {
window.requestAnimationFrame(() => {
tabsRef.current.querySelector('[role="tab"][aria-selected="true"]')?.focus();
});
}
}, []);
return /* @__PURE__ */ (0, import_jsx_runtime253.jsxs)(
"div",
{
className: clsx_default("block-editor-inserter__menu", {
"show-panel": showPatternPanel || showMediaPanel,
"is-zoom-out": isZoomOutMode
}),
ref,
children: [
/* @__PURE__ */ (0, import_jsx_runtime253.jsx)("div", { className: "block-editor-inserter__main-area", children: /* @__PURE__ */ (0, import_jsx_runtime253.jsx)(
tabbed_sidebar_default,
{
ref: tabsRef,
onSelect: handleSetSelectedTab,
onClose,
selectedTab,
closeButtonLabel: (0, import_i18n62.__)("Close Block Inserter"),
tabs: [
{
name: "blocks",
title: (0, import_i18n62.__)("Blocks"),
panelRef: blocksPanelRef,
panel: /* @__PURE__ */ (0, import_jsx_runtime253.jsxs)(import_jsx_runtime253.Fragment, { children: [
inserterSearch,
selectedTab === "blocks" && !delayedFilterValue && blocksTab
] })
},
{
name: "patterns",
title: (0, import_i18n62.__)("Patterns"),
panelRef: patternsPanelRef,
panel: /* @__PURE__ */ (0, import_jsx_runtime253.jsxs)(import_jsx_runtime253.Fragment, { children: [
inserterSearch,
selectedTab === "patterns" && !delayedFilterValue && patternsTab
] })
},
{
name: "media",
title: (0, import_i18n62.__)("Media"),
panelRef: mediaPanelRef,
panel: /* @__PURE__ */ (0, import_jsx_runtime253.jsxs)(import_jsx_runtime253.Fragment, { children: [
inserterSearch,
mediaTab
] })
}
]
}
) }),
showInserterHelpPanel && hoveredItem && /* @__PURE__ */ (0, import_jsx_runtime253.jsx)(
import_components59.Popover,
{
className: "block-editor-inserter__preview-container__popover",
placement: "right-start",
offset: 16,
focusOnMount: false,
animate: false,
children: /* @__PURE__ */ (0, import_jsx_runtime253.jsx)(preview_panel_default, { item: hoveredItem })
}
)
]
}
);
}
var PrivateInserterMenu = (0, import_element126.forwardRef)(InserterMenu);
function PublicInserterMenu(props, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime253.jsx)(
PrivateInserterMenu,
{
...props,
onPatternCategorySelection: NOOP2,
ref
}
);
}
var menu_default = (0, import_element126.forwardRef)(PublicInserterMenu);
// packages/block-editor/build-module/components/inserter/quick-inserter.mjs
var import_element127 = __toESM(require_element(), 1);
var import_i18n63 = __toESM(require_i18n(), 1);
var import_components60 = __toESM(require_components(), 1);
var import_data64 = __toESM(require_data(), 1);
var import_jsx_runtime254 = __toESM(require_jsx_runtime(), 1);
var SEARCH_THRESHOLD = 6;
var SHOWN_BLOCK_TYPES2 = 6;
var SHOWN_BLOCK_PATTERNS = 2;
function QuickInserter({
onSelect,
rootClientId,
clientId,
isAppender,
selectBlockOnInsert,
hasSearch = true
}) {
const [filterValue, setFilterValue] = (0, import_element127.useState)("");
const [destinationRootClientId, onInsertBlocks] = use_insertion_point_default({
onSelect,
rootClientId,
clientId,
isAppender,
selectBlockOnInsert
});
const [blockTypes] = use_block_types_state_default(
destinationRootClientId,
onInsertBlocks,
true
);
const { setInserterIsOpened, insertionIndex } = (0, import_data64.useSelect)(
(select3) => {
const { getSettings: getSettings7, getBlockIndex: getBlockIndex2, getBlockCount: getBlockCount2 } = select3(store);
const settings2 = getSettings7();
const index2 = getBlockIndex2(clientId);
const blockCount = getBlockCount2();
return {
setInserterIsOpened: settings2.__experimentalSetIsInserterOpened,
insertionIndex: index2 === -1 ? blockCount : index2
};
},
[clientId]
);
const showSearch = hasSearch && blockTypes.length > SEARCH_THRESHOLD;
(0, import_element127.useEffect)(() => {
if (setInserterIsOpened) {
setInserterIsOpened(false);
}
}, [setInserterIsOpened]);
const onBrowseAll = () => {
setInserterIsOpened({
filterValue,
onSelect,
rootClientId,
insertionIndex
});
};
return /* @__PURE__ */ (0, import_jsx_runtime254.jsxs)(
"div",
{
className: clsx_default("block-editor-inserter__quick-inserter", {
"has-search": showSearch,
"has-expand": setInserterIsOpened
}),
children: [
showSearch && /* @__PURE__ */ (0, import_jsx_runtime254.jsx)(
import_components60.SearchControl,
{
className: "block-editor-inserter__search",
value: filterValue,
onChange: (value) => {
setFilterValue(value);
},
label: (0, import_i18n63.__)("Search"),
placeholder: (0, import_i18n63.__)("Search")
}
),
/* @__PURE__ */ (0, import_jsx_runtime254.jsx)("div", { className: "block-editor-inserter__quick-inserter-results", children: /* @__PURE__ */ (0, import_jsx_runtime254.jsx)(
search_results_default,
{
filterValue,
onSelect,
rootClientId,
clientId,
isAppender,
maxBlockPatterns: !!filterValue ? SHOWN_BLOCK_PATTERNS : 0,
maxBlockTypes: SHOWN_BLOCK_TYPES2,
isDraggable: false,
selectBlockOnInsert,
isQuick: true
}
) }),
setInserterIsOpened && /* @__PURE__ */ (0, import_jsx_runtime254.jsx)(
import_components60.Button,
{
__next40pxDefaultSize: true,
className: "block-editor-inserter__quick-inserter-expand",
onClick: onBrowseAll,
"aria-label": (0, import_i18n63.__)(
"Browse all. This will open the main inserter panel in the editor toolbar."
),
children: (0, import_i18n63.__)("Browse all")
}
)
]
}
);
}
// packages/block-editor/build-module/components/inserter/get-appender-label.mjs
var MAX_APPENDER_LABEL_LENGTH = 50;
function getAppenderLabel(defaultBlock, defaultBlockType) {
if (!defaultBlock || !defaultBlock.attributes || !defaultBlockType?.__experimentalLabel) {
return null;
}
const result = defaultBlockType.__experimentalLabel(
defaultBlock.attributes,
{ context: "appender" }
);
if (typeof result === "string" && result.length < MAX_APPENDER_LABEL_LENGTH && result.length > 0) {
return result;
}
return null;
}
// packages/block-editor/build-module/components/inserter/index.mjs
var import_jsx_runtime255 = __toESM(require_jsx_runtime(), 1);
var UnforwardedInserterToggle = ({
onToggle,
disabled: disabled2,
isOpen,
blockTitle,
hasSingleBlockType,
appenderLabel,
toggleProps = {}
}, ref) => {
const {
as: Wrapper = import_components61.Button,
label: labelProp,
onClick,
...rest
} = toggleProps;
let label = labelProp;
if (!label && appenderLabel) {
label = appenderLabel;
} else if (!label && hasSingleBlockType) {
label = (0, import_i18n64.sprintf)(
// translators: %s: the name of the block when there is only one
(0, import_i18n64._x)("Add %s", "directly add the only allowed block"),
blockTitle.toLowerCase()
);
} else if (!label) {
label = (0, import_i18n64._x)("Add block", "Generic label for block inserter button");
}
function handleClick(event) {
if (onToggle) {
onToggle(event);
}
if (onClick) {
onClick(event);
}
}
return /* @__PURE__ */ (0, import_jsx_runtime255.jsx)(
Wrapper,
{
ref,
__next40pxDefaultSize: toggleProps.as ? void 0 : true,
icon: plus_default,
label,
tooltipPosition: "bottom",
onClick: handleClick,
className: "block-editor-inserter__toggle",
"aria-haspopup": !hasSingleBlockType ? "true" : false,
"aria-expanded": !hasSingleBlockType ? isOpen : false,
isPressed: !hasSingleBlockType && isOpen,
disabled: disabled2,
...rest
}
);
};
var InserterToggle = (0, import_element128.forwardRef)(UnforwardedInserterToggle);
var UnforwardedInserter = ({
clientId,
rootClientId,
disabled: disabled2,
isAppender,
position,
selectBlockOnInsert,
shouldDirectInsert = true,
showInserterHelpPanel,
// This prop is experimental to give some time for the quick inserter to mature
// Feel free to make them stable after a few releases.
__experimentalIsQuick: isQuick,
onSelectOrClose,
onToggle,
renderToggle: renderToggleProp,
toggleProps
}, ref) => {
const {
hasItems,
hasSingleBlockType,
blockTitle,
allowedBlockType,
blockToInsert,
appenderLabel,
targetRootClientId
} = (0, import_data65.useSelect)(
(select3) => {
const {
getBlockRootClientId: getBlockRootClientId22,
hasInserterItems: hasInserterItems2,
getAllowedBlocks: getAllowedBlocks2,
getDirectInsertBlock: getDirectInsertBlock2,
getBlockListSettings: getBlockListSettings2
} = select3(store);
const { getBlockVariations: getBlockVariations2, getBlockType: getBlockType210 } = select3(import_blocks40.store);
const _targetRootClientId = rootClientId || getBlockRootClientId22(clientId) || void 0;
const allowedBlocks = getAllowedBlocks2(_targetRootClientId);
const directInsertBlock = shouldDirectInsert && getDirectInsertBlock2(_targetRootClientId);
const { defaultBlock } = getBlockListSettings2(_targetRootClientId) ?? {};
const _hasSingleBlockType = allowedBlocks?.length === 1 && getBlockVariations2(allowedBlocks[0].name, "inserter")?.length === 0;
const _allowedBlockType = _hasSingleBlockType ? allowedBlocks[0] : null;
let _blockToInsert = directInsertBlock || null;
if (!_blockToInsert && _hasSingleBlockType && defaultBlock?.name === _allowedBlockType.name) {
_blockToInsert = defaultBlock;
}
const defaultBlockType = directInsertBlock ? getBlockType210(directInsertBlock.name) : null;
return {
hasItems: hasInserterItems2(_targetRootClientId),
hasSingleBlockType: _hasSingleBlockType,
blockTitle: _allowedBlockType ? _allowedBlockType.title : "",
allowedBlockType: _allowedBlockType,
blockToInsert: _blockToInsert,
appenderLabel: getAppenderLabel(
directInsertBlock,
defaultBlockType
),
targetRootClientId: _targetRootClientId
};
},
[rootClientId, clientId, shouldDirectInsert]
);
const { insertBlock: insertBlock2 } = (0, import_data65.useDispatch)(store);
const {
getBlock: getBlock2,
getBlockIndex: getBlockIndex2,
getBlockOrder: getBlockOrder2,
getBlockRootClientId: getBlockRootClientId2,
getBlockSelectionEnd: getBlockSelectionEnd2,
getPreviousBlockClientId: getPreviousBlockClientId2
} = (0, import_data65.useSelect)(store);
const { getActiveBlockVariation, getBlockType: getBlockType29 } = (0, import_data65.useSelect)(import_blocks40.store);
if (!hasItems && (isAppender || targetRootClientId || clientId)) {
return null;
}
function insertOnlyAllowedBlock() {
const blockName = blockToInsert?.name ?? allowedBlockType.name;
function getAdjacentBlockAttributes(attributesToCopy) {
if (!attributesToCopy?.length) {
return {};
}
let adjacentAttributes;
if (clientId) {
const currentBlock = getBlock2(clientId);
const previousBlock = getBlock2(
getPreviousBlockClientId2(clientId)
);
if (currentBlock?.name === previousBlock?.name) {
adjacentAttributes = previousBlock?.attributes;
}
} else if (targetRootClientId) {
const lastInnerBlock = getBlock2(targetRootClientId)?.innerBlocks?.at(-1);
if (lastInnerBlock?.name === blockName) {
adjacentAttributes = lastInnerBlock.attributes;
}
}
if (!adjacentAttributes) {
return {};
}
return Object.fromEntries(
attributesToCopy.filter((attr2) => attr2 in adjacentAttributes).map((attr2) => [attr2, adjacentAttributes[attr2]])
);
}
function getInsertionIndex() {
if (clientId) {
return getBlockIndex2(clientId);
}
const end = getBlockSelectionEnd2();
if (!isAppender && end && getBlockRootClientId2(end) === targetRootClientId) {
return getBlockIndex2(end) + 1;
}
return getBlockOrder2(targetRootClientId).length;
}
const newAttributes = getAdjacentBlockAttributes(
blockToInsert?.attributesToCopy
);
const newBlock = (0, import_blocks40.createBlock)(blockName, {
...blockToInsert?.attributes,
...newAttributes
});
insertBlock2(
newBlock,
getInsertionIndex(),
targetRootClientId,
selectBlockOnInsert
);
onSelectOrClose?.(newBlock);
const blockTypeToInsert = getBlockType29(blockName);
let blockLabelToInsert;
if (blockTypeToInsert) {
blockLabelToInsert = (0, import_blocks40.__experimentalGetBlockLabel)(
blockTypeToInsert,
newBlock.attributes
);
if (blockLabelToInsert === blockTypeToInsert.title) {
blockLabelToInsert = getActiveBlockVariation(blockName, newBlock.attributes)?.title || blockLabelToInsert;
}
}
if (blockLabelToInsert) {
const message2 = (0, import_i18n64.sprintf)(
// translators: %s: the name of the block that has been added
(0, import_i18n64.__)("%s block added"),
blockLabelToInsert
);
(0, import_a11y10.speak)(message2);
}
}
function renderToggle3({ onToggle: dropdownOnToggle, isOpen }) {
const toggleArgs = {
onToggle: dropdownOnToggle,
isOpen,
disabled: disabled2 || !hasItems,
blockTitle,
hasSingleBlockType,
appenderLabel,
toggleProps
};
if (renderToggleProp) {
return renderToggleProp(toggleArgs);
}
return /* @__PURE__ */ (0, import_jsx_runtime255.jsx)(InserterToggle, { ref, ...toggleArgs });
}
function renderContent({ onClose }) {
if (isQuick) {
return /* @__PURE__ */ (0, import_jsx_runtime255.jsx)(
QuickInserter,
{
onSelect: (blocks2) => {
const firstBlock = Array.isArray(blocks2) && blocks2?.length ? blocks2[0] : blocks2;
if (onSelectOrClose && typeof onSelectOrClose === "function") {
onSelectOrClose(firstBlock);
}
onClose();
},
rootClientId: targetRootClientId,
clientId,
isAppender,
selectBlockOnInsert
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime255.jsx)(
menu_default,
{
onSelect: () => {
onClose();
},
onClose,
rootClientId: targetRootClientId,
clientId,
isAppender,
showInserterHelpPanel
}
);
}
if (hasSingleBlockType || blockToInsert) {
return renderToggle3({ onToggle: insertOnlyAllowedBlock });
}
return /* @__PURE__ */ (0, import_jsx_runtime255.jsx)(
import_components61.Dropdown,
{
className: "block-editor-inserter",
contentClassName: clsx_default("block-editor-inserter__popover", {
"is-quick": isQuick
}),
popoverProps: { position, shift: true },
onToggle,
expandOnMobile: true,
headerTitle: (0, import_i18n64.__)("Add a block"),
renderToggle: renderToggle3,
renderContent,
onClose: onSelectOrClose
}
);
};
var Inserter = (0, import_element128.forwardRef)(UnforwardedInserter);
var inserter_default = Inserter;
// packages/block-editor/build-module/components/default-block-appender/index.mjs
var import_jsx_runtime256 = __toESM(require_jsx_runtime(), 1);
var ZWNBSP = "\uFEFF";
function DefaultBlockAppender({ rootClientId }) {
const { showPrompt, isLocked, placeholder, isManualGrid } = (0, import_data66.useSelect)(
(select3) => {
const {
getBlockCount: getBlockCount2,
getSettings: getSettings7,
getTemplateLock: getTemplateLock2,
getBlockAttributes: getBlockAttributes3
} = select3(store);
const isEmpty4 = !getBlockCount2(rootClientId);
const { bodyPlaceholder } = getSettings7();
return {
showPrompt: isEmpty4,
isLocked: !!getTemplateLock2(rootClientId),
placeholder: bodyPlaceholder,
isManualGrid: getBlockAttributes3(rootClientId)?.layout?.isManualPlacement
};
},
[rootClientId]
);
const { insertDefaultBlock: insertDefaultBlock2, startTyping: startTyping2 } = (0, import_data66.useDispatch)(store);
if (isLocked || isManualGrid) {
return null;
}
const value = (0, import_html_entities.decodeEntities)(placeholder) || (0, import_i18n65.__)("Type / to choose a block");
const onAppend = () => {
insertDefaultBlock2(void 0, rootClientId);
startTyping2();
};
return /* @__PURE__ */ (0, import_jsx_runtime256.jsxs)(
"div",
{
"data-root-client-id": rootClientId || "",
className: clsx_default("block-editor-default-block-appender", {
"has-visible-prompt": showPrompt
}),
children: [
/* @__PURE__ */ (0, import_jsx_runtime256.jsx)(
"p",
{
tabIndex: "0",
role: "button",
"aria-label": (0, import_i18n65.__)("Add default block"),
className: "block-editor-default-block-appender__content",
onKeyDown: (event) => {
if (import_keycodes9.ENTER === event.keyCode || import_keycodes9.SPACE === event.keyCode) {
onAppend();
}
},
onClick: () => onAppend(),
onFocus: () => {
if (showPrompt) {
onAppend();
}
},
children: showPrompt ? value : ZWNBSP
}
),
/* @__PURE__ */ (0, import_jsx_runtime256.jsx)(
inserter_default,
{
rootClientId,
position: "bottom right",
isAppender: true,
__experimentalIsQuick: true
}
)
]
}
);
}
// packages/block-editor/build-module/components/button-block-appender/index.mjs
var import_components62 = __toESM(require_components(), 1);
var import_element129 = __toESM(require_element(), 1);
var import_i18n66 = __toESM(require_i18n(), 1);
var import_deprecated8 = __toESM(require_deprecated(), 1);
var import_jsx_runtime257 = __toESM(require_jsx_runtime(), 1);
function ButtonBlockAppender({ rootClientId, className, onFocus, tabIndex, onSelect }, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime257.jsx)(
inserter_default,
{
position: "bottom center",
rootClientId,
__experimentalIsQuick: true,
onSelectOrClose: (...args) => {
if (onSelect && typeof onSelect === "function") {
onSelect(...args);
}
},
renderToggle: ({
onToggle,
disabled: disabled2,
isOpen,
blockTitle,
hasSingleBlockType,
appenderLabel
}) => {
const isToggleButton = !hasSingleBlockType;
let label;
if (appenderLabel) {
label = appenderLabel;
} else if (hasSingleBlockType) {
label = (0, import_i18n66.sprintf)(
// translators: %s: the name of the block when there is only one
(0, import_i18n66._x)("Add %s", "directly add the only allowed block"),
blockTitle.toLowerCase()
);
} else {
label = (0, import_i18n66._x)(
"Add block",
"Generic label for block inserter button"
);
}
return (
// Disable reason: There shouldn't be a case where this button is disabled but not visually hidden.
// eslint-disable-next-line @wordpress/components-no-unsafe-button-disabled
/* @__PURE__ */ (0, import_jsx_runtime257.jsx)(
import_components62.Button,
{
__next40pxDefaultSize: true,
ref,
onFocus,
tabIndex,
className: clsx_default(
className,
"block-editor-button-block-appender"
),
onClick: onToggle,
"aria-haspopup": isToggleButton ? "true" : void 0,
"aria-expanded": isToggleButton ? isOpen : void 0,
disabled: disabled2,
label,
showTooltip: true,
children: /* @__PURE__ */ (0, import_jsx_runtime257.jsx)(icon_default, { icon: plus_default })
}
)
);
},
isAppender: true
}
);
}
var ButtonBlockerAppender = (0, import_element129.forwardRef)((props, ref) => {
(0, import_deprecated8.default)(`wp.blockEditor.ButtonBlockerAppender`, {
alternative: "wp.blockEditor.ButtonBlockAppender",
since: "5.9"
});
return ButtonBlockAppender(props, ref);
});
var button_block_appender_default = (0, import_element129.forwardRef)(ButtonBlockAppender);
// packages/block-editor/build-module/components/block-list-appender/index.mjs
var import_jsx_runtime258 = __toESM(require_jsx_runtime(), 1);
function DefaultAppender({ rootClientId }) {
const canInsertDefaultBlock = (0, import_data67.useSelect)(
(select3) => select3(store).canInsertBlockType(
(0, import_blocks41.getDefaultBlockName)(),
rootClientId
)
);
if (canInsertDefaultBlock) {
return /* @__PURE__ */ (0, import_jsx_runtime258.jsx)(DefaultBlockAppender, { rootClientId });
}
return /* @__PURE__ */ (0, import_jsx_runtime258.jsx)(
button_block_appender_default,
{
rootClientId,
className: "block-list-appender__toggle"
}
);
}
function BlockListAppender({
rootClientId,
CustomAppender,
className,
tagName: TagName = "div"
}) {
const isDragOver = (0, import_data67.useSelect)(
(select3) => {
const {
getBlockInsertionPoint: getBlockInsertionPoint2,
isBlockInsertionPointVisible: isBlockInsertionPointVisible2,
getBlockCount: getBlockCount2
} = select3(store);
const insertionPoint2 = getBlockInsertionPoint2();
return isBlockInsertionPointVisible2() && rootClientId === insertionPoint2?.rootClientId && getBlockCount2(rootClientId) === 0;
},
[rootClientId]
);
return /* @__PURE__ */ (0, import_jsx_runtime258.jsx)(
TagName,
{
tabIndex: -1,
className: clsx_default("block-list-appender wp-block", className, {
"is-drag-over": isDragOver
}),
contentEditable: false,
"data-block": true,
children: CustomAppender ? /* @__PURE__ */ (0, import_jsx_runtime258.jsx)(CustomAppender, {}) : /* @__PURE__ */ (0, import_jsx_runtime258.jsx)(DefaultAppender, { rootClientId })
}
);
}
// packages/block-editor/build-module/components/block-list/use-in-between-inserter.mjs
var import_compose51 = __toESM(require_compose(), 1);
var import_data71 = __toESM(require_data(), 1);
var import_element134 = __toESM(require_element(), 1);
var import_i18n68 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/block-tools/insertion-point.mjs
var import_data70 = __toESM(require_data(), 1);
var import_element133 = __toESM(require_element(), 1);
var import_components66 = __toESM(require_components(), 1);
var import_compose50 = __toESM(require_compose(), 1);
// packages/block-editor/build-module/components/block-popover/inbetween.mjs
var import_data68 = __toESM(require_data(), 1);
var import_element130 = __toESM(require_element(), 1);
var import_components63 = __toESM(require_components(), 1);
var import_i18n67 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/block-popover/use-popover-scroll.mjs
var import_compose47 = __toESM(require_compose(), 1);
var import_dom52 = __toESM(require_dom(), 1);
var scrollContainerCache = /* @__PURE__ */ new WeakMap();
function usePopoverScroll(contentRef) {
const effect = (0, import_compose47.useRefEffect)(
(node) => {
function onWheel(event) {
const { deltaX, deltaY, target } = event;
const contentEl = contentRef.current;
let scrollContainer = scrollContainerCache.get(contentEl);
if (!scrollContainer) {
scrollContainer = (0, import_dom52.getScrollContainer)(contentEl);
scrollContainerCache.set(contentEl, scrollContainer);
}
const eventScrollContainer = (0, import_dom52.getScrollContainer)(target);
if (!node.contains(eventScrollContainer)) {
scrollContainer.scrollBy(deltaX, deltaY);
}
}
const options = { passive: true };
node.addEventListener("wheel", onWheel, options);
return () => {
node.removeEventListener("wheel", onWheel, options);
};
},
[contentRef]
);
return contentRef ? effect : null;
}
var use_popover_scroll_default = usePopoverScroll;
// packages/block-editor/build-module/components/block-popover/inbetween.mjs
var import_jsx_runtime259 = __toESM(require_jsx_runtime(), 1);
var MAX_POPOVER_RECOMPUTE_COUNTER = Number.MAX_SAFE_INTEGER;
function BlockPopoverInbetween({
previousClientId,
nextClientId,
children,
__unstablePopoverSlot,
__unstableContentRef,
operation = "insert",
nearestSide = "right",
...props
}) {
const [popoverRecomputeCounter, forcePopoverRecompute] = (0, import_element130.useReducer)(
// Module is there to make sure that the counter doesn't overflow.
(s2) => (s2 + 1) % MAX_POPOVER_RECOMPUTE_COUNTER,
0
);
const { orientation, rootClientId, isVisible } = (0, import_data68.useSelect)(
(select3) => {
const {
getBlockListSettings: getBlockListSettings2,
getBlockRootClientId: getBlockRootClientId2,
isBlockVisible: isBlockVisible2
} = select3(store);
const _rootClientId = getBlockRootClientId2(
previousClientId ?? nextClientId
);
return {
orientation: getBlockListSettings2(_rootClientId)?.orientation || "vertical",
rootClientId: _rootClientId,
isVisible: isBlockVisible2(previousClientId) && isBlockVisible2(nextClientId)
};
},
[previousClientId, nextClientId]
);
const previousElement = useBlockElement(previousClientId);
const nextElement = useBlockElement(nextClientId);
const isVertical = orientation === "vertical";
const popoverAnchor = (0, import_element130.useMemo)(() => {
if (
// popoverRecomputeCounter is by definition always equal or greater than 0.
// This check is only there to satisfy the correctness of the
// exhaustive-deps rule for the `useMemo` hook.
popoverRecomputeCounter < 0 || !previousElement && !nextElement || !isVisible
) {
return void 0;
}
const contextElement = operation === "group" ? nextElement || previousElement : previousElement || nextElement;
return {
contextElement,
getBoundingClientRect() {
const previousRect = previousElement ? previousElement.getBoundingClientRect() : null;
const nextRect = nextElement ? nextElement.getBoundingClientRect() : null;
let left = 0;
let top = 0;
let width = 0;
let height = 0;
if (operation === "group") {
const targetRect = nextRect || previousRect;
top = targetRect.top;
width = 0;
height = targetRect.bottom - targetRect.top;
left = nearestSide === "left" ? targetRect.left - 2 : targetRect.right - 2;
} else if (isVertical) {
top = previousRect ? previousRect.bottom : nextRect.top;
width = previousRect ? previousRect.width : nextRect.width;
height = nextRect && previousRect ? nextRect.top - previousRect.bottom : 0;
left = previousRect ? previousRect.left : nextRect.left;
} else {
top = previousRect ? previousRect.top : nextRect.top;
height = previousRect ? previousRect.height : nextRect.height;
if ((0, import_i18n67.isRTL)()) {
left = nextRect ? nextRect.right : previousRect.left;
width = previousRect && nextRect ? previousRect.left - nextRect.right : 0;
} else {
left = previousRect ? previousRect.right : nextRect.left;
width = previousRect && nextRect ? nextRect.left - previousRect.right : 0;
}
width = Math.max(width, 0);
}
return new window.DOMRect(left, top, width, height);
}
};
}, [
previousElement,
nextElement,
popoverRecomputeCounter,
isVertical,
isVisible,
operation,
nearestSide
]);
const popoverScrollRef = use_popover_scroll_default(__unstableContentRef);
(0, import_element130.useLayoutEffect)(() => {
if (!previousElement) {
return;
}
const observer = new window.MutationObserver(forcePopoverRecompute);
observer.observe(previousElement, { attributes: true });
return () => {
observer.disconnect();
};
}, [previousElement]);
(0, import_element130.useLayoutEffect)(() => {
if (!nextElement) {
return;
}
const observer = new window.MutationObserver(forcePopoverRecompute);
observer.observe(nextElement, { attributes: true });
return () => {
observer.disconnect();
};
}, [nextElement]);
(0, import_element130.useLayoutEffect)(() => {
if (!previousElement) {
return;
}
previousElement.ownerDocument.defaultView.addEventListener(
"resize",
forcePopoverRecompute
);
return () => {
previousElement.ownerDocument.defaultView?.removeEventListener(
"resize",
forcePopoverRecompute
);
};
}, [previousElement]);
if (!previousElement && !nextElement || !isVisible) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime259.jsx)(
import_components63.Popover,
{
ref: popoverScrollRef,
animate: false,
anchor: popoverAnchor,
focusOnMount: false,
__unstableSlotName: __unstablePopoverSlot,
inline: !__unstablePopoverSlot,
...props,
className: clsx_default(
"block-editor-block-popover",
"block-editor-block-popover__inbetween",
props.className
),
resize: false,
flip: false,
placement: "overlay",
variant: "unstyled",
children: /* @__PURE__ */ (0, import_jsx_runtime259.jsx)("div", { className: "block-editor-block-popover__inbetween-container", children })
},
nextClientId + "--" + rootClientId
);
}
var inbetween_default = BlockPopoverInbetween;
// packages/block-editor/build-module/components/block-popover/drop-zone.mjs
var import_data69 = __toESM(require_data(), 1);
var import_compose49 = __toESM(require_compose(), 1);
var import_components65 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/block-popover/cover.mjs
var import_element132 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/block-popover/index.mjs
var import_compose48 = __toESM(require_compose(), 1);
var import_components64 = __toESM(require_components(), 1);
var import_element131 = __toESM(require_element(), 1);
var import_jsx_runtime260 = __toESM(require_jsx_runtime(), 1);
var MAX_POPOVER_RECOMPUTE_COUNTER2 = Number.MAX_SAFE_INTEGER;
function BlockPopover({
clientId,
bottomClientId,
children,
__unstablePopoverSlot,
__unstableContentRef,
shift: shift4 = true,
...props
}, ref) {
const selectedElement = useBlockElement(clientId);
const lastSelectedElement = useBlockElement(bottomClientId ?? clientId);
const mergedRefs = (0, import_compose48.useMergeRefs)([
ref,
use_popover_scroll_default(__unstableContentRef)
]);
const [
popoverDimensionsRecomputeCounter,
forceRecomputePopoverDimensions
] = (0, import_element131.useReducer)(
// Module is there to make sure that the counter doesn't overflow.
(s2) => (s2 + 1) % MAX_POPOVER_RECOMPUTE_COUNTER2,
0
);
(0, import_element131.useLayoutEffect)(() => {
if (!selectedElement) {
return;
}
let rafId2;
const observer = new window.MutationObserver(() => {
if (rafId2) {
return;
}
rafId2 = window.requestAnimationFrame(() => {
rafId2 = null;
forceRecomputePopoverDimensions();
});
});
observer.observe(selectedElement, { attributes: true });
return () => {
observer.disconnect();
if (rafId2) {
window.cancelAnimationFrame(rafId2);
}
};
}, [selectedElement]);
const popoverAnchor = (0, import_element131.useMemo)(() => {
if (
// popoverDimensionsRecomputeCounter is by definition always equal or greater
// than 0. This check is only there to satisfy the correctness of the
// exhaustive-deps rule for the `useMemo` hook.
popoverDimensionsRecomputeCounter < 0 || !selectedElement || bottomClientId && !lastSelectedElement
) {
return void 0;
}
return {
getBoundingClientRect() {
return lastSelectedElement ? rectUnion(
getElementBounds(selectedElement),
getElementBounds(lastSelectedElement)
) : getElementBounds(selectedElement);
},
contextElement: selectedElement
};
}, [
popoverDimensionsRecomputeCounter,
selectedElement,
bottomClientId,
lastSelectedElement
]);
if (!selectedElement || bottomClientId && !lastSelectedElement) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime260.jsx)(
import_components64.Popover,
{
ref: mergedRefs,
animate: false,
focusOnMount: false,
anchor: popoverAnchor,
__unstableSlotName: __unstablePopoverSlot,
inline: !__unstablePopoverSlot,
placement: "top-start",
resize: false,
flip: false,
shift: shift4,
...props,
className: clsx_default("block-editor-block-popover", props.className),
variant: "unstyled",
children
}
);
}
var PrivateBlockPopover = (0, import_element131.forwardRef)(BlockPopover);
var PublicBlockPopover = ({ clientId, bottomClientId, children, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime260.jsx)(
PrivateBlockPopover,
{
...props,
bottomClientId,
clientId,
__unstableContentRef: void 0,
__unstablePopoverSlot: void 0,
ref,
children
}
);
var block_popover_default = (0, import_element131.forwardRef)(PublicBlockPopover);
// packages/block-editor/build-module/components/block-popover/cover.mjs
var import_jsx_runtime261 = __toESM(require_jsx_runtime(), 1);
function BlockPopoverCover({
clientId,
bottomClientId,
children,
shift: shift4 = false,
additionalStyles,
...props
}, ref) {
bottomClientId ??= clientId;
const selectedElement = useBlockElement(clientId);
return /* @__PURE__ */ (0, import_jsx_runtime261.jsx)(
PrivateBlockPopover,
{
ref,
clientId,
bottomClientId,
shift: shift4,
...props,
children: selectedElement && clientId === bottomClientId ? /* @__PURE__ */ (0, import_jsx_runtime261.jsx)(
CoverContainer,
{
selectedElement,
additionalStyles,
children
}
) : children
}
);
}
function CoverContainer({
selectedElement,
additionalStyles = {},
children
}) {
const [width, setWidth] = (0, import_element132.useState)(selectedElement.offsetWidth);
const [height, setHeight] = (0, import_element132.useState)(selectedElement.offsetHeight);
(0, import_element132.useEffect)(() => {
const observer = new window.ResizeObserver(() => {
setWidth(selectedElement.offsetWidth);
setHeight(selectedElement.offsetHeight);
});
observer.observe(selectedElement, { box: "border-box" });
return () => observer.disconnect();
}, [selectedElement]);
const style = (0, import_element132.useMemo)(() => {
return {
position: "absolute",
width,
height,
...additionalStyles
};
}, [width, height, additionalStyles]);
return /* @__PURE__ */ (0, import_jsx_runtime261.jsx)("div", { style, children });
}
var cover_default = (0, import_element132.forwardRef)(BlockPopoverCover);
// packages/block-editor/build-module/components/block-popover/drop-zone.mjs
var import_jsx_runtime262 = __toESM(require_jsx_runtime(), 1);
var animateVariants = {
hide: { opacity: 0, scaleY: 0.75 },
show: { opacity: 1, scaleY: 1 },
exit: { opacity: 0, scaleY: 0.9 }
};
function BlockDropZonePopover({
__unstablePopoverSlot,
__unstableContentRef
}) {
const { clientId } = (0, import_data69.useSelect)((select3) => {
const { getBlockOrder: getBlockOrder2, getBlockInsertionPoint: getBlockInsertionPoint2 } = select3(store);
const insertionPoint2 = getBlockInsertionPoint2();
const order = getBlockOrder2(insertionPoint2.rootClientId);
if (!order.length) {
return {};
}
return {
clientId: order[insertionPoint2.index]
};
}, []);
const reducedMotion = (0, import_compose49.useReducedMotion)();
return /* @__PURE__ */ (0, import_jsx_runtime262.jsx)(
cover_default,
{
clientId,
__unstablePopoverSlot,
__unstableContentRef,
className: "block-editor-block-popover__drop-zone",
children: /* @__PURE__ */ (0, import_jsx_runtime262.jsx)(
import_components65.__unstableMotion.div,
{
"data-testid": "block-popover-drop-zone",
initial: reducedMotion ? animateVariants.show : animateVariants.hide,
animate: animateVariants.show,
exit: reducedMotion ? animateVariants.show : animateVariants.exit,
className: "block-editor-block-popover__drop-zone-foreground"
}
)
}
);
}
var drop_zone_default = BlockDropZonePopover;
// packages/block-editor/build-module/components/block-tools/insertion-point.mjs
var import_jsx_runtime263 = __toESM(require_jsx_runtime(), 1);
var InsertionPointOpenRef = (0, import_element133.createContext)();
InsertionPointOpenRef.displayName = "InsertionPointOpenRefContext";
function InbetweenInsertionPointPopover({
__unstablePopoverSlot,
__unstableContentRef,
operation = "insert",
nearestSide = "right"
}) {
const { selectBlock: selectBlock2, hideInsertionPoint: hideInsertionPoint2 } = (0, import_data70.useDispatch)(store);
const openRef = (0, import_element133.useContext)(InsertionPointOpenRef);
const ref = (0, import_element133.useRef)();
const {
orientation,
previousClientId,
nextClientId,
rootClientId,
isInserterShown,
isDistractionFree,
isZoomOutMode
} = (0, import_data70.useSelect)((select3) => {
const {
getBlockOrder: getBlockOrder2,
getBlockListSettings: getBlockListSettings2,
getBlockInsertionPoint: getBlockInsertionPoint2,
isBlockBeingDragged: isBlockBeingDragged2,
getPreviousBlockClientId: getPreviousBlockClientId2,
getNextBlockClientId: getNextBlockClientId2,
getSettings: getSettings7,
isZoomOut: isZoomOut2
} = unlock(select3(store));
const insertionPoint2 = getBlockInsertionPoint2();
const order = getBlockOrder2(insertionPoint2.rootClientId);
if (!order.length) {
return {};
}
let _previousClientId = order[insertionPoint2.index - 1];
let _nextClientId = order[insertionPoint2.index];
while (isBlockBeingDragged2(_previousClientId)) {
_previousClientId = getPreviousBlockClientId2(_previousClientId);
}
while (isBlockBeingDragged2(_nextClientId)) {
_nextClientId = getNextBlockClientId2(_nextClientId);
}
const settings2 = getSettings7();
return {
previousClientId: _previousClientId,
nextClientId: _nextClientId,
orientation: getBlockListSettings2(insertionPoint2.rootClientId)?.orientation || "vertical",
rootClientId: insertionPoint2.rootClientId,
isDistractionFree: settings2.isDistractionFree,
isInserterShown: insertionPoint2?.__unstableWithInserter,
isZoomOutMode: isZoomOut2()
};
}, []);
const { getBlockEditingMode: getBlockEditingMode2 } = (0, import_data70.useSelect)(store);
const disableMotion = (0, import_compose50.useReducedMotion)();
function onClick(event) {
if (event.target === ref.current && nextClientId && getBlockEditingMode2(nextClientId) !== "disabled") {
selectBlock2(nextClientId, -1);
}
}
function maybeHideInserterPoint(event) {
if (event.target === ref.current && !openRef.current) {
hideInsertionPoint2();
}
}
function onFocus(event) {
if (event.target !== ref.current) {
openRef.current = true;
}
}
const maybeResetOpenRef = (0, import_element133.useCallback)(
(node) => {
if (!node && openRef.current) {
openRef.current = false;
}
},
[openRef]
);
const lineVariants = {
// Initial position starts from the center and invisible.
start: {
opacity: 0,
scale: 0
},
// The line expands to fill the container. If the inserter is visible it
// is delayed so it appears orchestrated.
rest: {
opacity: 1,
scale: 1,
transition: { delay: isInserterShown ? 0.5 : 0, type: "tween" }
},
hover: {
opacity: 1,
scale: 1,
transition: { delay: 0.5, type: "tween" }
}
};
const inserterVariants = {
start: {
scale: disableMotion ? 1 : 0
},
rest: {
scale: 1,
transition: { delay: 0.4, type: "tween" }
}
};
if (isDistractionFree) {
return null;
}
if (isZoomOutMode && operation !== "insert") {
return null;
}
const orientationClassname = orientation === "horizontal" || operation === "group" ? "is-horizontal" : "is-vertical";
const className = clsx_default(
"block-editor-block-list__insertion-point",
orientationClassname
);
return /* @__PURE__ */ (0, import_jsx_runtime263.jsx)(
inbetween_default,
{
previousClientId,
nextClientId,
__unstablePopoverSlot,
__unstableContentRef,
operation,
nearestSide,
children: /* @__PURE__ */ (0, import_jsx_runtime263.jsxs)(
import_components66.__unstableMotion.div,
{
layout: !disableMotion,
initial: disableMotion ? "rest" : "start",
animate: "rest",
whileHover: "hover",
whileTap: "pressed",
exit: "start",
ref,
tabIndex: -1,
onClick,
onFocus,
className: clsx_default(className, {
"is-with-inserter": isInserterShown
}),
onHoverEnd: maybeHideInserterPoint,
children: [
/* @__PURE__ */ (0, import_jsx_runtime263.jsx)(
import_components66.__unstableMotion.div,
{
variants: lineVariants,
className: "block-editor-block-list__insertion-point-indicator",
"data-testid": "block-list-insertion-point-indicator"
}
),
isInserterShown && /* @__PURE__ */ (0, import_jsx_runtime263.jsx)(
import_components66.__unstableMotion.div,
{
variants: inserterVariants,
className: clsx_default(
"block-editor-block-list__insertion-point-inserter"
),
children: /* @__PURE__ */ (0, import_jsx_runtime263.jsx)(
inserter_default,
{
ref: maybeResetOpenRef,
position: "bottom center",
clientId: nextClientId,
rootClientId,
__experimentalIsQuick: true,
onToggle: (isOpen) => {
openRef.current = isOpen;
},
onSelectOrClose: () => {
openRef.current = false;
}
}
)
}
)
]
}
)
}
);
}
function InsertionPoint(props) {
const { insertionPoint: insertionPoint2, isVisible, isBlockListEmpty } = (0, import_data70.useSelect)(
(select3) => {
const {
getBlockInsertionPoint: getBlockInsertionPoint2,
isBlockInsertionPointVisible: isBlockInsertionPointVisible2,
getBlockCount: getBlockCount2
} = select3(store);
const blockInsertionPoint = getBlockInsertionPoint2();
return {
insertionPoint: blockInsertionPoint,
isVisible: isBlockInsertionPointVisible2(),
isBlockListEmpty: getBlockCount2(blockInsertionPoint?.rootClientId) === 0
};
},
[]
);
if (!isVisible || // Don't render the insertion point if the block list is empty.
// The insertion point will be represented by the appender instead.
isBlockListEmpty) {
return null;
}
return insertionPoint2.operation === "replace" ? /* @__PURE__ */ (0, import_jsx_runtime263.jsx)(
drop_zone_default,
{
...props
},
`${insertionPoint2.rootClientId}-${insertionPoint2.index}`
) : /* @__PURE__ */ (0, import_jsx_runtime263.jsx)(
InbetweenInsertionPointPopover,
{
operation: insertionPoint2.operation,
nearestSide: insertionPoint2.nearestSide,
...props
}
);
}
// packages/block-editor/build-module/components/block-list/use-in-between-inserter.mjs
function useInBetweenInserter() {
const openRef = (0, import_element134.useContext)(InsertionPointOpenRef);
const isInBetweenInserterDisabled = (0, import_data71.useSelect)((select3) => {
const settings2 = select3(store).getSettings();
return settings2.isDistractionFree || settings2.isPreviewMode || unlock(select3(store)).isZoomOut();
}, []);
const {
getBlockListSettings: getBlockListSettings2,
getBlockIndex: getBlockIndex2,
isMultiSelecting: isMultiSelecting3,
getSelectedBlockClientIds: getSelectedBlockClientIds2,
getSettings: getSettings7,
getTemplateLock: getTemplateLock2,
__unstableIsWithinBlockOverlay: __unstableIsWithinBlockOverlay2,
getBlockEditingMode: getBlockEditingMode2,
getBlockName: getBlockName2,
getBlockAttributes: getBlockAttributes3,
getParentSectionBlock: getParentSectionBlock2
} = unlock((0, import_data71.useSelect)(store));
const { showInsertionPoint: showInsertionPoint2, hideInsertionPoint: hideInsertionPoint2 } = (0, import_data71.useDispatch)(store);
return (0, import_compose51.useRefEffect)(
(node) => {
if (isInBetweenInserterDisabled) {
return;
}
function onMouseMove(event) {
if (openRef === void 0 || openRef.current) {
return;
}
if (event.target.nodeType === event.target.TEXT_NODE) {
return;
}
if (isMultiSelecting3()) {
return;
}
if (!event.target.classList.contains(
"block-editor-block-list__layout"
)) {
hideInsertionPoint2();
return;
}
let rootClientId;
if (!event.target.classList.contains("is-root-container")) {
const blockElement = !!event.target.getAttribute(
"data-block"
) ? event.target : event.target.closest("[data-block]");
rootClientId = blockElement.getAttribute("data-block");
}
if (getTemplateLock2(rootClientId) || getBlockEditingMode2(rootClientId) === "disabled" || getBlockName2(rootClientId) === "core/block" || rootClientId && getBlockAttributes3(rootClientId).layout?.isManualPlacement) {
return;
}
const blockListSettings2 = getBlockListSettings2(rootClientId);
const orientation = blockListSettings2?.orientation || "vertical";
const captureToolbars = !!blockListSettings2?.__experimentalCaptureToolbars;
const offsetTop = event.clientY;
const offsetLeft = event.clientX;
const children = Array.from(event.target.children);
let element = children.find((blockEl) => {
const blockElRect = blockEl.getBoundingClientRect();
return blockEl.classList.contains("wp-block") && orientation === "vertical" && blockElRect.top > offsetTop || blockEl.classList.contains("wp-block") && orientation === "horizontal" && ((0, import_i18n68.isRTL)() ? blockElRect.right < offsetLeft : blockElRect.left > offsetLeft);
});
if (!element) {
hideInsertionPoint2();
return;
}
if (!element.id) {
element = element.firstElementChild;
if (!element) {
hideInsertionPoint2();
return;
}
}
const clientId = element.id.slice("block-".length);
if (!clientId || __unstableIsWithinBlockOverlay2(clientId) || !!getParentSectionBlock2(clientId)) {
return;
}
if (getSelectedBlockClientIds2().includes(clientId) && orientation === "vertical" && !captureToolbars && !getSettings7().hasFixedToolbar) {
return;
}
const elementRect = element.getBoundingClientRect();
if (orientation === "horizontal" && (event.clientY > elementRect.bottom || event.clientY < elementRect.top) || orientation === "vertical" && (event.clientX > elementRect.right || event.clientX < elementRect.left)) {
hideInsertionPoint2();
return;
}
const index2 = getBlockIndex2(clientId);
if (index2 === 0) {
hideInsertionPoint2();
return;
}
showInsertionPoint2(rootClientId, index2, {
__unstableWithInserter: true
});
}
node.addEventListener("mousemove", onMouseMove);
return () => {
node.removeEventListener("mousemove", onMouseMove);
};
},
[
openRef,
getBlockListSettings2,
getBlockIndex2,
isMultiSelecting3,
showInsertionPoint2,
hideInsertionPoint2,
getSelectedBlockClientIds2,
isInBetweenInserterDisabled
]
);
}
// packages/block-editor/build-module/components/block-selection-clearer/index.mjs
var import_data72 = __toESM(require_data(), 1);
var import_compose52 = __toESM(require_compose(), 1);
var import_jsx_runtime264 = __toESM(require_jsx_runtime(), 1);
function useBlockSelectionClearer() {
const { getSettings: getSettings7, hasSelectedBlock: hasSelectedBlock2, hasMultiSelection: hasMultiSelection2 } = (0, import_data72.useSelect)(store);
const { clearSelectedBlock: clearSelectedBlock2 } = (0, import_data72.useDispatch)(store);
const { clearBlockSelection: isEnabled } = getSettings7();
return (0, import_compose52.useRefEffect)(
(node) => {
if (!isEnabled) {
return;
}
function onMouseDown(event) {
if (!hasSelectedBlock2() && !hasMultiSelection2()) {
return;
}
if (event.target !== node) {
return;
}
clearSelectedBlock2();
}
node.addEventListener("mousedown", onMouseDown);
return () => {
node.removeEventListener("mousedown", onMouseDown);
};
},
[hasSelectedBlock2, hasMultiSelection2, clearSelectedBlock2, isEnabled]
);
}
function BlockSelectionClearer(props) {
return /* @__PURE__ */ (0, import_jsx_runtime264.jsx)("div", { ref: useBlockSelectionClearer(), ...props });
}
// packages/block-editor/build-module/components/inner-blocks/index.mjs
var import_compose54 = __toESM(require_compose(), 1);
var import_element139 = __toESM(require_element(), 1);
var import_data78 = __toESM(require_data(), 1);
var import_blocks46 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/components/inner-blocks/button-block-appender.mjs
var import_jsx_runtime265 = __toESM(require_jsx_runtime(), 1);
function ButtonBlockAppender2({
showSeparator,
isFloating,
onAddBlock,
isToggle
}) {
const { clientId } = useBlockEditContext();
return /* @__PURE__ */ (0, import_jsx_runtime265.jsx)(
button_block_appender_default,
{
className: clsx_default({
"block-list-appender__toggle": isToggle
}),
rootClientId: clientId,
showSeparator,
isFloating,
onAddBlock
}
);
}
// packages/block-editor/build-module/components/inner-blocks/default-block-appender.mjs
var import_jsx_runtime266 = __toESM(require_jsx_runtime(), 1);
function DefaultBlockAppender2() {
const { clientId } = useBlockEditContext();
return /* @__PURE__ */ (0, import_jsx_runtime266.jsx)(DefaultBlockAppender, { rootClientId: clientId });
}
// packages/block-editor/build-module/components/inner-blocks/use-nested-settings-update.mjs
var import_element135 = __toESM(require_element(), 1);
var import_data73 = __toESM(require_data(), 1);
var import_deprecated9 = __toESM(require_deprecated(), 1);
var import_is_shallow_equal = __toESM(require_is_shallow_equal(), 1);
var pendingSettingsUpdates = /* @__PURE__ */ new WeakMap();
function createShallowMemo() {
let value;
return (newValue) => {
if (value === void 0 || !(0, import_is_shallow_equal.isShallowEqual)(value, newValue)) {
value = newValue;
}
return value;
};
}
function useShallowMemo(value) {
const [memo14] = (0, import_element135.useState)(createShallowMemo);
return memo14(value);
}
function useNestedSettingsUpdate(clientId, parentLock, allowedBlocks, prioritizedInserterBlocks, defaultBlock, directInsert, __experimentalDefaultBlock, __experimentalDirectInsert, templateLock, captureToolbars, orientation, layout) {
const registry = (0, import_data73.useRegistry)();
const _allowedBlocks = useShallowMemo(allowedBlocks);
const _prioritizedInserterBlocks = useShallowMemo(
prioritizedInserterBlocks
);
const _templateLock = templateLock === void 0 || parentLock === "contentOnly" ? parentLock : templateLock;
(0, import_element135.useLayoutEffect)(() => {
const newSettings = {
allowedBlocks: _allowedBlocks,
prioritizedInserterBlocks: _prioritizedInserterBlocks,
templateLock: _templateLock
};
if (captureToolbars !== void 0) {
newSettings.__experimentalCaptureToolbars = captureToolbars;
}
if (orientation !== void 0) {
newSettings.orientation = orientation;
} else {
const layoutType = getLayoutType(layout?.type);
newSettings.orientation = layoutType.getOrientation(layout);
}
if (__experimentalDefaultBlock !== void 0) {
(0, import_deprecated9.default)("__experimentalDefaultBlock", {
alternative: "defaultBlock",
since: "6.3",
version: "6.4"
});
newSettings.defaultBlock = __experimentalDefaultBlock;
}
if (defaultBlock !== void 0) {
newSettings.defaultBlock = defaultBlock;
}
if (__experimentalDirectInsert !== void 0) {
(0, import_deprecated9.default)("__experimentalDirectInsert", {
alternative: "directInsert",
since: "6.3",
version: "6.4"
});
newSettings.directInsert = __experimentalDirectInsert;
}
if (directInsert !== void 0) {
newSettings.directInsert = directInsert;
}
if (newSettings.directInsert !== void 0 && typeof newSettings.directInsert !== "boolean") {
(0, import_deprecated9.default)("Using `Function` as a `directInsert` argument", {
alternative: "`boolean` values",
since: "6.5"
});
}
if (!pendingSettingsUpdates.get(registry)) {
pendingSettingsUpdates.set(registry, {});
}
pendingSettingsUpdates.get(registry)[clientId] = newSettings;
window.queueMicrotask(() => {
const settings2 = pendingSettingsUpdates.get(registry);
if (Object.keys(settings2).length) {
const { updateBlockListSettings: updateBlockListSettings2 } = registry.dispatch(store);
updateBlockListSettings2(settings2);
pendingSettingsUpdates.set(registry, {});
}
});
}, [
clientId,
_allowedBlocks,
_prioritizedInserterBlocks,
_templateLock,
defaultBlock,
directInsert,
__experimentalDefaultBlock,
__experimentalDirectInsert,
captureToolbars,
orientation,
layout,
registry
]);
}
// packages/block-editor/build-module/components/inner-blocks/use-inner-block-template-sync.mjs
var import_es64 = __toESM(require_es6(), 1);
var import_element136 = __toESM(require_element(), 1);
var import_data74 = __toESM(require_data(), 1);
var import_blocks42 = __toESM(require_blocks(), 1);
function useInnerBlockTemplateSync(clientId, template2, templateLock, templateInsertUpdatesSelection) {
const registry = (0, import_data74.useRegistry)();
const existingTemplateRef = (0, import_element136.useRef)(null);
(0, import_element136.useLayoutEffect)(() => {
let isCancelled = false;
const {
getBlocks: getBlocks2,
getSelectedBlocksInitialCaretPosition: getSelectedBlocksInitialCaretPosition2,
isBlockSelected: isBlockSelected2
} = registry.select(store);
const { replaceInnerBlocks: replaceInnerBlocks2, __unstableMarkNextChangeAsNotPersistent: __unstableMarkNextChangeAsNotPersistent2 } = registry.dispatch(store);
window.queueMicrotask(() => {
if (isCancelled) {
return;
}
const currentInnerBlocks = getBlocks2(clientId);
const shouldApplyTemplate = currentInnerBlocks.length === 0 || templateLock === "all" || templateLock === "contentOnly";
const hasTemplateChanged = !(0, import_es64.default)(
template2,
existingTemplateRef.current
);
if (!shouldApplyTemplate || !hasTemplateChanged) {
return;
}
existingTemplateRef.current = template2;
const nextBlocks = (0, import_blocks42.synchronizeBlocksWithTemplate)(
currentInnerBlocks,
template2
);
if (!(0, import_es64.default)(nextBlocks, currentInnerBlocks)) {
__unstableMarkNextChangeAsNotPersistent2({
history: "ignore"
});
replaceInnerBlocks2(
clientId,
nextBlocks,
currentInnerBlocks.length === 0 && templateInsertUpdatesSelection && nextBlocks.length !== 0 && isBlockSelected2(clientId),
// This ensures the "initialPosition" doesn't change when applying the template
// If we're supposed to focus the block, we'll focus the first inner block
// otherwise, we won't apply any auto-focus.
// This ensures for instance that the focus stays in the inserter when inserting the "buttons" block.
getSelectedBlocksInitialCaretPosition2()
);
}
});
return () => {
isCancelled = true;
};
}, [
template2,
templateLock,
clientId,
registry,
templateInsertUpdatesSelection
]);
}
// packages/block-editor/build-module/components/inner-blocks/use-block-context.mjs
var import_blocks43 = __toESM(require_blocks(), 1);
var import_data75 = __toESM(require_data(), 1);
function useBlockContext(clientId) {
return (0, import_data75.useSelect)(
(select3) => {
const block = select3(store).getBlock(clientId);
if (!block) {
return void 0;
}
const blockType = select3(import_blocks43.store).getBlockType(block.name);
if (!blockType) {
return void 0;
}
if (Object.keys(blockType.providesContext).length === 0) {
return void 0;
}
return Object.fromEntries(
Object.entries(blockType.providesContext).map(
([contextName, attributeName]) => [
contextName,
block.attributes[attributeName]
]
)
);
},
[clientId]
);
}
// packages/block-editor/build-module/components/use-block-drop-zone/index.mjs
var import_data77 = __toESM(require_data(), 1);
var import_element138 = __toESM(require_element(), 1);
var import_compose53 = __toESM(require_compose(), 1);
var import_i18n69 = __toESM(require_i18n(), 1);
var import_blocks45 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/components/use-on-block-drop/index.mjs
var import_element137 = __toESM(require_element(), 1);
var import_blocks44 = __toESM(require_blocks(), 1);
var import_data76 = __toESM(require_data(), 1);
var import_dom54 = __toESM(require_dom(), 1);
function parseDropEvent(event) {
let result = {
srcRootClientId: null,
srcClientIds: null,
srcIndex: null,
type: null,
blocks: null
};
if (!event.dataTransfer) {
return result;
}
try {
result = Object.assign(
result,
JSON.parse(event.dataTransfer.getData("wp-blocks"))
);
} catch {
return result;
}
return result;
}
function onBlockDrop(targetRootClientId, targetBlockIndex, getBlockIndex2, getClientIdsOfDescendants2, moveBlocks, insertOrReplaceBlocks, clearSelectedBlock2, operation, getBlock2) {
return (event) => {
const {
srcRootClientId: sourceRootClientId,
srcClientIds: sourceClientIds,
type: dropType,
blocks: blocks2
} = parseDropEvent(event);
if (dropType === "inserter") {
clearSelectedBlock2();
const blocksToInsert = blocks2.map(
(block) => (0, import_blocks44.cloneBlock)(block)
);
insertOrReplaceBlocks(blocksToInsert, true, null);
}
if (dropType === "block") {
const sourceBlockIndex = getBlockIndex2(sourceClientIds[0]);
if (sourceRootClientId === targetRootClientId && sourceBlockIndex === targetBlockIndex) {
return;
}
if (sourceClientIds.includes(targetRootClientId) || getClientIdsOfDescendants2(sourceClientIds).some(
(id) => id === targetRootClientId
)) {
return;
}
if (operation === "group") {
const blocksToInsert = sourceClientIds.map(
(clientId) => getBlock2(clientId)
);
insertOrReplaceBlocks(
blocksToInsert,
true,
null,
sourceClientIds
);
return;
}
const isAtSameLevel = sourceRootClientId === targetRootClientId;
const draggedBlockCount = sourceClientIds.length;
const insertIndex = isAtSameLevel && sourceBlockIndex < targetBlockIndex ? targetBlockIndex - draggedBlockCount : targetBlockIndex;
moveBlocks(sourceClientIds, sourceRootClientId, insertIndex);
}
};
}
function onFilesDrop(targetRootClientId, getSettings7, updateBlockAttributes2, canInsertBlockType2, insertOrReplaceBlocks) {
return (files) => {
if (!getSettings7().mediaUpload) {
return;
}
const transformation = (0, import_blocks44.findTransform)(
(0, import_blocks44.getBlockTransforms)("from"),
(transform) => transform.type === "files" && canInsertBlockType2(transform.blockName, targetRootClientId) && transform.isMatch(files)
);
if (transformation) {
const blocks2 = transformation.transform(
files,
updateBlockAttributes2
);
insertOrReplaceBlocks(blocks2);
}
};
}
function onHTMLDrop(insertOrReplaceBlocks) {
return (HTML) => {
const blocks2 = (0, import_blocks44.pasteHandler)({ HTML, mode: "BLOCKS" });
if (blocks2.length) {
insertOrReplaceBlocks(blocks2);
}
};
}
function useOnBlockDrop(targetRootClientId, targetBlockIndex, options = {}) {
const { operation = "insert", nearestSide = "right" } = options;
const {
canInsertBlockType: canInsertBlockType2,
getBlockIndex: getBlockIndex2,
getClientIdsOfDescendants: getClientIdsOfDescendants2,
getBlockOrder: getBlockOrder2,
getBlocksByClientId: getBlocksByClientId2,
getSettings: getSettings7,
getBlock: getBlock2
} = (0, import_data76.useSelect)(store);
const { getGroupingBlockName } = (0, import_data76.useSelect)(import_blocks44.store);
const {
insertBlocks: insertBlocks2,
moveBlocksToPosition: moveBlocksToPosition2,
updateBlockAttributes: updateBlockAttributes2,
clearSelectedBlock: clearSelectedBlock2,
replaceBlocks: replaceBlocks2,
removeBlocks: removeBlocks2
} = (0, import_data76.useDispatch)(store);
const registry = (0, import_data76.useRegistry)();
const insertOrReplaceBlocks = (0, import_element137.useCallback)(
(blocks2, updateSelection = true, initialPosition2 = 0, clientIdsToReplace = []) => {
if (!Array.isArray(blocks2)) {
blocks2 = [blocks2];
}
const clientIds = getBlockOrder2(targetRootClientId);
const clientId = clientIds[targetBlockIndex];
if (operation === "replace") {
replaceBlocks2(clientId, blocks2, void 0, initialPosition2);
} else if (operation === "group") {
const targetBlock = getBlock2(clientId);
if (nearestSide === "left") {
blocks2.push(targetBlock);
} else {
blocks2.unshift(targetBlock);
}
const groupInnerBlocks = blocks2.map(
(block) => (0, import_blocks44.cloneSanitizedBlock)(block)
);
const areAllImages = blocks2.every((block) => {
return block.name === "core/image";
});
const galleryBlock = canInsertBlockType2(
"core/gallery",
targetRootClientId
);
const wrappedBlocks = (0, import_blocks44.createBlock)(
areAllImages && galleryBlock ? "core/gallery" : getGroupingBlockName(),
{
layout: {
type: "flex",
flexWrap: areAllImages && galleryBlock ? null : "nowrap"
}
},
groupInnerBlocks
);
replaceBlocks2(
[clientId, ...clientIdsToReplace],
wrappedBlocks,
void 0,
initialPosition2
);
} else {
insertBlocks2(
blocks2,
targetBlockIndex,
targetRootClientId,
updateSelection,
initialPosition2
);
}
},
[
getBlockOrder2,
targetRootClientId,
targetBlockIndex,
operation,
replaceBlocks2,
getBlock2,
nearestSide,
canInsertBlockType2,
getGroupingBlockName,
insertBlocks2
]
);
const moveBlocks = (0, import_element137.useCallback)(
(sourceClientIds, sourceRootClientId, insertIndex) => {
if (operation === "replace") {
const sourceBlocks = getBlocksByClientId2(sourceClientIds);
const targetBlockClientIds = getBlockOrder2(targetRootClientId);
const targetBlockClientId = targetBlockClientIds[targetBlockIndex];
registry.batch(() => {
removeBlocks2(sourceClientIds, false);
replaceBlocks2(
targetBlockClientId,
sourceBlocks,
void 0,
0
);
});
} else {
moveBlocksToPosition2(
sourceClientIds,
sourceRootClientId,
targetRootClientId,
insertIndex
);
}
},
[
operation,
getBlockOrder2,
getBlocksByClientId2,
moveBlocksToPosition2,
registry,
removeBlocks2,
replaceBlocks2,
targetBlockIndex,
targetRootClientId
]
);
const _onDrop = onBlockDrop(
targetRootClientId,
targetBlockIndex,
getBlockIndex2,
getClientIdsOfDescendants2,
moveBlocks,
insertOrReplaceBlocks,
clearSelectedBlock2,
operation,
getBlock2
);
const _onFilesDrop = onFilesDrop(
targetRootClientId,
getSettings7,
updateBlockAttributes2,
canInsertBlockType2,
insertOrReplaceBlocks
);
const _onHTMLDrop = onHTMLDrop(insertOrReplaceBlocks);
return (event) => {
const files = (0, import_dom54.getFilesFromDataTransfer)(event.dataTransfer);
const html = event.dataTransfer.getData("text/html");
if (html) {
_onHTMLDrop(html);
} else if (files.length) {
_onFilesDrop(files);
} else {
_onDrop(event);
}
};
}
// packages/block-editor/build-module/utils/math.mjs
function getDistanceFromPointToEdge(point, rect, edge) {
const isHorizontal = edge === "top" || edge === "bottom";
const { x: x2, y: y2 } = point;
const pointLateralPosition = isHorizontal ? x2 : y2;
const pointForwardPosition = isHorizontal ? y2 : x2;
const edgeStart = isHorizontal ? rect.left : rect.top;
const edgeEnd = isHorizontal ? rect.right : rect.bottom;
const edgeForwardPosition = rect[edge];
let edgeLateralPosition;
if (pointLateralPosition >= edgeStart && pointLateralPosition <= edgeEnd) {
edgeLateralPosition = pointLateralPosition;
} else if (pointLateralPosition < edgeEnd) {
edgeLateralPosition = edgeStart;
} else {
edgeLateralPosition = edgeEnd;
}
return Math.sqrt(
(pointLateralPosition - edgeLateralPosition) ** 2 + (pointForwardPosition - edgeForwardPosition) ** 2
);
}
function getDistanceToNearestEdge(point, rect, allowedEdges = ["top", "bottom", "left", "right"]) {
let candidateDistance;
let candidateEdge;
allowedEdges.forEach((edge) => {
const distance = getDistanceFromPointToEdge(point, rect, edge);
if (candidateDistance === void 0 || distance < candidateDistance) {
candidateDistance = distance;
candidateEdge = edge;
}
});
return [candidateDistance, candidateEdge];
}
function isPointContainedByRect(point, rect) {
return rect.left <= point.x && rect.right >= point.x && rect.top <= point.y && rect.bottom >= point.y;
}
function isPointWithinTopAndBottomBoundariesOfRect(point, rect) {
return rect.top <= point.y && rect.bottom >= point.y;
}
// packages/block-editor/build-module/components/use-block-drop-zone/index.mjs
var THRESHOLD_DISTANCE = 30;
var MINIMUM_HEIGHT_FOR_THRESHOLD = 120;
var MINIMUM_WIDTH_FOR_THRESHOLD = 120;
function getDropTargetPosition(blocksData, position, orientation = "vertical", options = {}) {
const allowedEdges = orientation === "horizontal" ? ["left", "right"] : ["top", "bottom"];
let nearestIndex = 0;
let insertPosition = "before";
let minDistance = Infinity;
let targetBlockIndex = null;
let nearestSide = "right";
const {
dropZoneElement,
parentBlockOrientation,
rootBlockIndex = 0
} = options;
if (dropZoneElement && parentBlockOrientation !== "horizontal") {
const rect = dropZoneElement.getBoundingClientRect();
const [distance, edge] = getDistanceToNearestEdge(position, rect, [
"top",
"bottom"
]);
if (rect.height > MINIMUM_HEIGHT_FOR_THRESHOLD && distance < THRESHOLD_DISTANCE) {
if (edge === "top") {
return [rootBlockIndex, "before"];
}
if (edge === "bottom") {
return [rootBlockIndex + 1, "after"];
}
}
}
const isRightToLeft = (0, import_i18n69.isRTL)();
if (dropZoneElement && parentBlockOrientation === "horizontal") {
const rect = dropZoneElement.getBoundingClientRect();
const [distance, edge] = getDistanceToNearestEdge(position, rect, [
"left",
"right"
]);
if (rect.width > MINIMUM_WIDTH_FOR_THRESHOLD && distance < THRESHOLD_DISTANCE) {
if (isRightToLeft && edge === "right" || !isRightToLeft && edge === "left") {
return [rootBlockIndex, "before"];
}
if (isRightToLeft && edge === "left" || !isRightToLeft && edge === "right") {
return [rootBlockIndex + 1, "after"];
}
}
}
blocksData.forEach(
({
isUnmodifiedDefaultBlock: isUnmodifiedDefaultBlock5,
getBoundingClientRect: getBoundingClientRect2,
blockIndex,
blockOrientation
}) => {
const rect = getBoundingClientRect2();
if (!rect) {
return;
}
let [distance, edge] = getDistanceToNearestEdge(
position,
rect,
allowedEdges
);
const [sideDistance, sideEdge] = getDistanceToNearestEdge(
position,
rect,
["left", "right"]
);
const isPointInsideRect = isPointContainedByRect(position, rect);
if (isUnmodifiedDefaultBlock5 && isPointInsideRect) {
distance = 0;
} else if (orientation === "vertical" && blockOrientation !== "horizontal" && (isPointInsideRect && sideDistance < THRESHOLD_DISTANCE || !isPointInsideRect && isPointWithinTopAndBottomBoundariesOfRect(
position,
rect
))) {
targetBlockIndex = blockIndex;
nearestSide = sideEdge;
}
if (distance < minDistance) {
insertPosition = edge === "bottom" || !isRightToLeft && edge === "right" || isRightToLeft && edge === "left" ? "after" : "before";
minDistance = distance;
nearestIndex = blockIndex;
}
}
);
const adjacentIndex = nearestIndex + (insertPosition === "after" ? 1 : -1);
const isNearestBlockUnmodifiedDefaultBlock = !!blocksData[nearestIndex]?.isUnmodifiedDefaultBlock;
const isAdjacentBlockUnmodifiedDefaultBlock = !!blocksData[adjacentIndex]?.isUnmodifiedDefaultBlock;
if (targetBlockIndex !== null) {
return [targetBlockIndex, "group", nearestSide];
}
if (!isNearestBlockUnmodifiedDefaultBlock && !isAdjacentBlockUnmodifiedDefaultBlock) {
const insertionIndex = insertPosition === "after" ? nearestIndex + 1 : nearestIndex;
return [insertionIndex, "insert"];
}
return [
isNearestBlockUnmodifiedDefaultBlock ? nearestIndex : adjacentIndex,
"replace"
];
}
function isDropTargetValid(getBlockType29, allowedBlocks, draggedBlockNames, targetBlockName) {
let areBlocksAllowed = true;
if (allowedBlocks) {
const allowedBlockNames = allowedBlocks?.map(({ name }) => name);
areBlocksAllowed = draggedBlockNames.every(
(name) => allowedBlockNames?.includes(name)
);
}
const draggedBlockTypes = draggedBlockNames.map(
(name) => getBlockType29(name)
);
const targetMatchesDraggedBlockParents = draggedBlockTypes.every(
(block) => {
const [allowedParentName] = block?.parent || [];
if (!allowedParentName) {
return true;
}
return allowedParentName === targetBlockName;
}
);
return areBlocksAllowed && targetMatchesDraggedBlockParents;
}
function isInsertionPoint(targetToCheck, ownerDocument2) {
const { defaultView } = ownerDocument2;
return !!(defaultView && targetToCheck instanceof defaultView.HTMLElement && targetToCheck.closest("[data-is-insertion-point]"));
}
function useBlockDropZone({
dropZoneElement,
// An undefined value represents a top-level block. Default to an empty
// string for this so that `targetRootClientId` can be easily compared to
// values returned by the `getRootBlockClientId` selector, which also uses
// an empty string to represent top-level blocks.
rootClientId: targetRootClientId = "",
parentClientId: parentBlockClientId = "",
isDisabled = false
} = {}) {
const registry = (0, import_data77.useRegistry)();
const [dropTarget, setDropTarget] = (0, import_element138.useState)({
index: null,
operation: "insert"
});
const { getBlockType: getBlockType29, getBlockVariations: getBlockVariations2, getGroupingBlockName } = (0, import_data77.useSelect)(import_blocks45.store);
const {
canInsertBlockType: canInsertBlockType2,
getBlockListSettings: getBlockListSettings2,
getBlocks: getBlocks2,
getBlockIndex: getBlockIndex2,
getDraggedBlockClientIds: getDraggedBlockClientIds2,
getBlockNamesByClientId: getBlockNamesByClientId2,
getAllowedBlocks: getAllowedBlocks2,
isDragging: isDragging3,
isGroupable: isGroupable2,
isZoomOut: isZoomOut2,
getSectionRootClientId: getSectionRootClientId2,
getBlockParents: getBlockParents2
} = unlock((0, import_data77.useSelect)(store));
const {
showInsertionPoint: showInsertionPoint2,
hideInsertionPoint: hideInsertionPoint2,
startDragging: startDragging2,
stopDragging: stopDragging2
} = unlock((0, import_data77.useDispatch)(store));
const onBlockDrop2 = useOnBlockDrop(
dropTarget.operation === "before" || dropTarget.operation === "after" ? parentBlockClientId : targetRootClientId,
dropTarget.index,
{
operation: dropTarget.operation,
nearestSide: dropTarget.nearestSide
}
);
const throttled = (0, import_compose53.useThrottle)(
(0, import_element138.useCallback)(
(event, ownerDocument2) => {
if (!isDragging3()) {
startDragging2();
}
const draggedBlockClientIds = getDraggedBlockClientIds2();
const targetParents = [
targetRootClientId,
...getBlockParents2(targetRootClientId, true)
];
const isTargetWithinDraggedBlocks = draggedBlockClientIds.some(
(clientId) => targetParents.includes(clientId)
);
if (isTargetWithinDraggedBlocks) {
return;
}
const allowedBlocks = getAllowedBlocks2(targetRootClientId);
const targetBlockName = getBlockNamesByClientId2([
targetRootClientId
])[0];
const draggedBlockNames = getBlockNamesByClientId2(
draggedBlockClientIds
);
const isBlockDroppingAllowed = isDropTargetValid(
getBlockType29,
allowedBlocks,
draggedBlockNames,
targetBlockName
);
if (!isBlockDroppingAllowed) {
return;
}
const sectionRootClientId = getSectionRootClientId2();
if (isZoomOut2() && sectionRootClientId !== targetRootClientId) {
return;
}
const blocks2 = getBlocks2(targetRootClientId).filter((block) => {
return !((0, import_blocks45.hasBlockSupport)(block.name, "visibility", true) && block.attributes?.metadata?.blockVisibility === false);
});
if (blocks2.length === 0) {
registry.batch(() => {
setDropTarget({
index: 0,
operation: "insert"
});
showInsertionPoint2(targetRootClientId, 0, {
operation: "insert"
});
});
return;
}
const blocksData = blocks2.map((block) => {
const clientId = block.clientId;
return {
isUnmodifiedDefaultBlock: (0, import_blocks45.isUnmodifiedDefaultBlock)(block),
getBoundingClientRect: () => {
const blockElement = ownerDocument2.getElementById(
`block-${clientId}`
);
return blockElement ? blockElement.getBoundingClientRect() : null;
},
blockIndex: getBlockIndex2(clientId),
blockOrientation: getBlockListSettings2(clientId)?.orientation
};
});
const dropTargetPosition = getDropTargetPosition(
blocksData,
{ x: event.clientX, y: event.clientY },
getBlockListSettings2(targetRootClientId)?.orientation,
{
dropZoneElement,
parentBlockClientId,
parentBlockOrientation: parentBlockClientId ? getBlockListSettings2(parentBlockClientId)?.orientation : void 0,
rootBlockIndex: getBlockIndex2(targetRootClientId)
}
);
const [targetIndex, operation, nearestSide] = dropTargetPosition;
const isTargetIndexEmptyDefaultBlock = blocksData[targetIndex]?.isUnmodifiedDefaultBlock;
if (isZoomOut2() && !isTargetIndexEmptyDefaultBlock && operation !== "insert") {
return;
}
if (operation === "group") {
const targetBlock = blocks2[targetIndex];
const areAllImages = [
targetBlock.name,
...draggedBlockNames
].every((name) => name === "core/image");
const canInsertGalleryBlock = canInsertBlockType2(
"core/gallery",
targetRootClientId
);
const areGroupableBlocks = isGroupable2([
targetBlock.clientId,
getDraggedBlockClientIds2()
]);
const groupBlockVariations = getBlockVariations2(
getGroupingBlockName(),
"block"
);
const canInsertRow = groupBlockVariations && groupBlockVariations.find(
({ name }) => name === "group-row"
);
if (areAllImages && !canInsertGalleryBlock && (!areGroupableBlocks || !canInsertRow)) {
return;
}
if (!areAllImages && (!areGroupableBlocks || !canInsertRow)) {
return;
}
}
registry.batch(() => {
setDropTarget({
index: targetIndex,
operation,
nearestSide
});
const insertionPointClientId = [
"before",
"after"
].includes(operation) ? parentBlockClientId : targetRootClientId;
showInsertionPoint2(insertionPointClientId, targetIndex, {
operation,
nearestSide
});
});
},
[
isDragging3,
getAllowedBlocks2,
targetRootClientId,
getBlockNamesByClientId2,
getDraggedBlockClientIds2,
getBlockType29,
getSectionRootClientId2,
isZoomOut2,
getBlocks2,
getBlockListSettings2,
dropZoneElement,
parentBlockClientId,
getBlockIndex2,
registry,
startDragging2,
showInsertionPoint2,
canInsertBlockType2,
isGroupable2,
getBlockVariations2,
getGroupingBlockName
]
),
200
);
return (0, import_compose53.__experimentalUseDropZone)({
dropZoneElement,
isDisabled,
onDrop: onBlockDrop2,
onDragOver(event) {
throttled(event, event.currentTarget.ownerDocument);
},
onDragLeave(event) {
const { ownerDocument: ownerDocument2 } = event.currentTarget;
if (isInsertionPoint(event.relatedTarget, ownerDocument2) || isInsertionPoint(event.target, ownerDocument2)) {
return;
}
throttled.cancel();
hideInsertionPoint2();
},
onDragEnd() {
throttled.cancel();
stopDragging2();
hideInsertionPoint2();
}
});
}
// packages/block-editor/build-module/components/inner-blocks/index.mjs
var import_jsx_runtime267 = __toESM(require_jsx_runtime(), 1);
var EMPTY_OBJECT2 = {};
function BlockContext({ children, clientId }) {
const context = useBlockContext(clientId);
return /* @__PURE__ */ (0, import_jsx_runtime267.jsx)(BlockContextProvider, { value: context, children });
}
var BlockListItemsMemo = (0, import_element139.memo)(BlockListItems);
function UncontrolledInnerBlocks(props) {
const {
clientId,
allowedBlocks,
prioritizedInserterBlocks,
defaultBlock,
directInsert,
__experimentalDefaultBlock,
__experimentalDirectInsert,
template: template2,
templateLock,
wrapperRef,
templateInsertUpdatesSelection,
__experimentalCaptureToolbars: captureToolbars,
__experimentalAppenderTagName,
renderAppender,
orientation,
placeholder,
layout,
name,
blockType,
parentLock,
defaultLayout: defaultLayout2
} = props;
useNestedSettingsUpdate(
clientId,
parentLock,
allowedBlocks,
prioritizedInserterBlocks,
defaultBlock,
directInsert,
__experimentalDefaultBlock,
__experimentalDirectInsert,
templateLock,
captureToolbars,
orientation,
layout
);
useInnerBlockTemplateSync(
clientId,
template2,
templateLock,
templateInsertUpdatesSelection
);
const defaultLayoutBlockSupport = (0, import_blocks46.getBlockSupport)(name, "layout") || (0, import_blocks46.getBlockSupport)(name, "__experimentalLayout") || EMPTY_OBJECT2;
const { allowSizingOnChildren = false } = defaultLayoutBlockSupport;
const usedLayout = layout || defaultLayoutBlockSupport;
const memoedLayout = (0, import_element139.useMemo)(
() => ({
// Default layout will know about any content/wide size defined by the theme.
...defaultLayout2,
...usedLayout,
...allowSizingOnChildren && {
allowSizingOnChildren: true
}
}),
[defaultLayout2, usedLayout, allowSizingOnChildren]
);
const items = /* @__PURE__ */ (0, import_jsx_runtime267.jsx)(
BlockListItemsMemo,
{
rootClientId: clientId,
renderAppender,
__experimentalAppenderTagName,
layout: memoedLayout,
wrapperRef,
placeholder
}
);
if (!blockType?.providesContext || Object.keys(blockType.providesContext).length === 0) {
return items;
}
return /* @__PURE__ */ (0, import_jsx_runtime267.jsx)(BlockContext, { clientId, children: items });
}
function ControlledInnerBlocks(props) {
useBlockSync(props);
return /* @__PURE__ */ (0, import_jsx_runtime267.jsx)(UncontrolledInnerBlocks, { ...props });
}
var ForwardedInnerBlocks = (0, import_element139.forwardRef)((props, ref) => {
const innerBlocksProps = useInnerBlocksProps({ ref }, props);
return /* @__PURE__ */ (0, import_jsx_runtime267.jsx)("div", { className: "block-editor-inner-blocks", children: /* @__PURE__ */ (0, import_jsx_runtime267.jsx)("div", { ...innerBlocksProps }) });
});
function useInnerBlocksProps(props = {}, options = {}) {
const {
__unstableDisableLayoutClassNames,
__unstableDisableDropZone,
dropZoneElement
} = options;
const {
clientId,
layout = null,
__unstableLayoutClassNames: layoutClassNames = ""
} = useBlockEditContext();
const selected = (0, import_data78.useSelect)(
(select3) => {
const {
getBlockName: getBlockName2,
isZoomOut: isZoomOut2,
getTemplateLock: getTemplateLock2,
getBlockRootClientId: getBlockRootClientId2,
getBlockEditingMode: getBlockEditingMode2,
getBlockSettings: getBlockSettings2,
getSectionRootClientId: getSectionRootClientId2
} = unlock(select3(store));
if (!clientId) {
const sectionRootClientId = getSectionRootClientId2();
return {
isDropZoneDisabled: isZoomOut2() && sectionRootClientId !== ""
};
}
const { hasBlockSupport: hasBlockSupport46, getBlockType: getBlockType29 } = select3(import_blocks46.store);
const blockName = getBlockName2(clientId);
const blockEditingMode = getBlockEditingMode2(clientId);
const parentClientId2 = getBlockRootClientId2(clientId);
const [defaultLayout22] = getBlockSettings2(clientId, "layout");
let _isDropZoneDisabled = blockEditingMode === "disabled";
if (isZoomOut2()) {
const sectionRootClientId = getSectionRootClientId2();
_isDropZoneDisabled = clientId !== sectionRootClientId;
}
return {
__experimentalCaptureToolbars: hasBlockSupport46(
blockName,
"__experimentalExposeControlsToChildren",
false
),
name: blockName,
blockType: getBlockType29(blockName),
parentLock: getTemplateLock2(parentClientId2),
parentClientId: parentClientId2,
isDropZoneDisabled: _isDropZoneDisabled,
defaultLayout: defaultLayout22
};
},
[clientId]
);
const {
__experimentalCaptureToolbars,
name,
blockType,
parentLock,
parentClientId,
isDropZoneDisabled,
defaultLayout: defaultLayout2
} = selected;
const blockDropZoneRef = useBlockDropZone({
dropZoneElement,
rootClientId: clientId,
parentClientId
});
const ref = (0, import_compose54.useMergeRefs)([
props.ref,
__unstableDisableDropZone || isDropZoneDisabled || layout?.isManualPlacement && window.__experimentalEnableGridInteractivity ? null : blockDropZoneRef
]);
const innerBlocksProps = {
__experimentalCaptureToolbars,
layout,
name,
blockType,
parentLock,
defaultLayout: defaultLayout2,
...options
};
const InnerBlocks = innerBlocksProps.value && innerBlocksProps.onChange ? ControlledInnerBlocks : UncontrolledInnerBlocks;
return {
...props,
ref,
className: clsx_default(
props.className,
"block-editor-block-list__layout",
__unstableDisableLayoutClassNames ? "" : layoutClassNames
),
children: clientId ? /* @__PURE__ */ (0, import_jsx_runtime267.jsx)(InnerBlocks, { ...innerBlocksProps, clientId }) : /* @__PURE__ */ (0, import_jsx_runtime267.jsx)(BlockListItems, { ...options })
};
}
useInnerBlocksProps.save = import_blocks46.__unstableGetInnerBlocksProps;
ForwardedInnerBlocks.DefaultBlockAppender = DefaultBlockAppender2;
ForwardedInnerBlocks.ButtonBlockAppender = ButtonBlockAppender2;
ForwardedInnerBlocks.Content = () => useInnerBlocksProps.save().children;
var inner_blocks_default = ForwardedInnerBlocks;
// packages/block-editor/build-module/components/block-list/zoom-out-separator.mjs
var import_components67 = __toESM(require_components(), 1);
var import_compose55 = __toESM(require_compose(), 1);
var import_data79 = __toESM(require_data(), 1);
var import_element140 = __toESM(require_element(), 1);
var import_i18n70 = __toESM(require_i18n(), 1);
var import_jsx_runtime268 = __toESM(require_jsx_runtime(), 1);
function ZoomOutSeparator({
clientId,
rootClientId = "",
position = "top"
}) {
const [isDraggedOver, setIsDraggedOver] = (0, import_element140.useState)(false);
const {
sectionRootClientId,
sectionClientIds,
insertionPoint: insertionPoint2,
blockInsertionPointVisible,
blockInsertionPoint,
blocksBeingDragged
} = (0, import_data79.useSelect)((select3) => {
const {
getInsertionPoint: getInsertionPoint2,
getBlockOrder: getBlockOrder2,
getSectionRootClientId: getSectionRootClientId2,
isBlockInsertionPointVisible: isBlockInsertionPointVisible2,
getBlockInsertionPoint: getBlockInsertionPoint2,
getDraggedBlockClientIds: getDraggedBlockClientIds2
} = unlock(select3(store));
const root = getSectionRootClientId2();
const sectionRootClientIds = getBlockOrder2(root);
return {
sectionRootClientId: root,
sectionClientIds: sectionRootClientIds,
insertionPoint: getInsertionPoint2(),
blockInsertionPoint: getBlockInsertionPoint2(),
blockInsertionPointVisible: isBlockInsertionPointVisible2(),
blocksBeingDragged: getDraggedBlockClientIds2()
};
}, []);
const isReducedMotion = (0, import_compose55.useReducedMotion)();
if (!clientId) {
return;
}
let isVisible = false;
const isSectionBlock2 = rootClientId === sectionRootClientId && sectionClientIds && sectionClientIds.includes(clientId);
if (!isSectionBlock2) {
return null;
}
const hasTopInsertionPoint = insertionPoint2?.index === 0 && clientId === sectionClientIds[insertionPoint2.index];
const hasBottomInsertionPoint = insertionPoint2 && insertionPoint2.hasOwnProperty("index") && clientId === sectionClientIds[insertionPoint2.index - 1];
if (position === "top") {
isVisible = hasTopInsertionPoint || blockInsertionPointVisible && blockInsertionPoint.index === 0 && clientId === sectionClientIds[blockInsertionPoint.index];
}
if (position === "bottom") {
isVisible = hasBottomInsertionPoint || blockInsertionPointVisible && clientId === sectionClientIds[blockInsertionPoint.index - 1];
}
const blockBeingDraggedClientId = blocksBeingDragged[0];
const isCurrentBlockBeingDragged = blocksBeingDragged.includes(clientId);
const blockBeingDraggedIndex = sectionClientIds.indexOf(
blockBeingDraggedClientId
);
const blockBeingDraggedPreviousSiblingClientId = blockBeingDraggedIndex > 0 ? sectionClientIds[blockBeingDraggedIndex - 1] : null;
const isCurrentBlockPreviousSiblingOfBlockBeingDragged = blockBeingDraggedPreviousSiblingClientId === clientId;
if (isCurrentBlockBeingDragged || isCurrentBlockPreviousSiblingOfBlockBeingDragged) {
isVisible = false;
}
return /* @__PURE__ */ (0, import_jsx_runtime268.jsx)(import_components67.__unstableAnimatePresence, { children: isVisible && /* @__PURE__ */ (0, import_jsx_runtime268.jsx)(
import_components67.__unstableMotion.div,
{
initial: { height: 0 },
animate: {
// Use a height equal to that of the zoom out frame size.
height: "calc(1 * var(--wp-block-editor-iframe-zoom-out-frame-size) / var(--wp-block-editor-iframe-zoom-out-scale)"
},
exit: { height: 0 },
transition: {
type: "tween",
duration: isReducedMotion ? 0 : 0.2,
ease: [0.6, 0, 0.4, 1]
},
className: clsx_default(
"block-editor-block-list__zoom-out-separator",
{
"is-dragged-over": isDraggedOver
}
),
"data-is-insertion-point": "true",
onDragOver: () => setIsDraggedOver(true),
onDragLeave: () => setIsDraggedOver(false),
children: /* @__PURE__ */ (0, import_jsx_runtime268.jsx)(
import_components67.__unstableMotion.div,
{
initial: { opacity: 0 },
animate: { opacity: 1 },
exit: { opacity: 0, transition: { delay: -0.125 } },
transition: {
ease: "linear",
duration: 0.1,
delay: 0.125
},
children: (0, import_i18n70.__)("Drop pattern.")
}
)
}
) });
}
// packages/block-editor/build-module/components/block-list/index.mjs
var import_jsx_runtime269 = __toESM(require_jsx_runtime(), 1);
var IntersectionObserver2 = (0, import_element141.createContext)();
IntersectionObserver2.displayName = "IntersectionObserverContext";
var pendingBlockVisibilityUpdatesPerRegistry = /* @__PURE__ */ new WeakMap();
var delayedBlockVisibilityDebounceOptions = {
trailing: true
};
function Root7({ className, ...settings2 }) {
const {
isOutlineMode,
isFocusMode,
isPreviewMode,
editedContentOnlySection: editedContentOnlySection2
} = (0, import_data80.useSelect)((select3) => {
const {
getSettings: getSettings7,
isTyping: isTyping3,
hasBlockSpotlight: hasBlockSpotlight3,
getEditedContentOnlySection: getEditedContentOnlySection2
} = unlock(select3(store));
const {
outlineMode,
focusMode,
isPreviewMode: _isPreviewMode
} = getSettings7();
return {
isOutlineMode: outlineMode && !isTyping3(),
isFocusMode: focusMode || hasBlockSpotlight3(),
isPreviewMode: _isPreviewMode,
editedContentOnlySection: getEditedContentOnlySection2()
};
}, []);
const registry = (0, import_data80.useRegistry)();
const { setBlockVisibility: setBlockVisibility2 } = (0, import_data80.useDispatch)(store);
const delayedBlockVisibilityUpdates = (0, import_compose56.useDebounce)(
(0, import_element141.useCallback)(() => {
const updates = {};
pendingBlockVisibilityUpdatesPerRegistry.get(registry).forEach(([id, isIntersecting]) => {
updates[id] = isIntersecting;
});
setBlockVisibility2(updates);
}, [registry]),
300,
delayedBlockVisibilityDebounceOptions
);
const intersectionObserver = (0, import_element141.useMemo)(() => {
const { IntersectionObserver: Observer } = window;
if (!Observer) {
return;
}
return new Observer((entries) => {
if (!pendingBlockVisibilityUpdatesPerRegistry.get(registry)) {
pendingBlockVisibilityUpdatesPerRegistry.set(registry, []);
}
for (const entry of entries) {
const clientId = entry.target.getAttribute("data-block");
pendingBlockVisibilityUpdatesPerRegistry.get(registry).push([clientId, entry.isIntersecting]);
}
delayedBlockVisibilityUpdates();
});
}, []);
const innerBlocksProps = useInnerBlocksProps(
{
ref: (0, import_compose56.useMergeRefs)([
useBlockSelectionClearer(),
useInBetweenInserter()
]),
className: clsx_default("is-root-container", className, {
"is-outline-mode": isOutlineMode,
"is-focus-mode": isFocusMode,
"is-preview-mode": isPreviewMode
})
},
settings2
);
return /* @__PURE__ */ (0, import_jsx_runtime269.jsxs)(IntersectionObserver2.Provider, { value: intersectionObserver, children: [
/* @__PURE__ */ (0, import_jsx_runtime269.jsx)("div", { ...innerBlocksProps }),
!!editedContentOnlySection2 && /* @__PURE__ */ (0, import_jsx_runtime269.jsx)(
StopEditingContentOnlySectionOnOutsideSelect,
{
clientId: editedContentOnlySection2
}
)
] });
}
function StopEditingContentOnlySectionOnOutsideSelect({ clientId }) {
const { stopEditingContentOnlySection: stopEditingContentOnlySection2 } = unlock(
(0, import_data80.useDispatch)(store)
);
const isBlockOrDescendantSelected = (0, import_data80.useSelect)(
(select3) => {
const {
isBlockSelected: isBlockSelected2,
hasSelectedInnerBlock: hasSelectedInnerBlock2,
getBlockSelectionStart: getBlockSelectionStart2
} = select3(store);
return !getBlockSelectionStart2() || isBlockSelected2(clientId) || hasSelectedInnerBlock2(clientId, true);
},
[clientId]
);
(0, import_element141.useEffect)(() => {
if (!isBlockOrDescendantSelected) {
stopEditingContentOnlySection2();
}
}, [isBlockOrDescendantSelected, stopEditingContentOnlySection2]);
return null;
}
function BlockList(settings2) {
return /* @__PURE__ */ (0, import_jsx_runtime269.jsx)(Provider, { value: DEFAULT_BLOCK_EDIT_CONTEXT, children: /* @__PURE__ */ (0, import_jsx_runtime269.jsx)(Root7, { ...settings2 }) });
}
var EMPTY_ARRAY8 = [];
var EMPTY_SET2 = /* @__PURE__ */ new Set();
function Items({
placeholder,
rootClientId,
renderAppender: CustomAppender,
__experimentalAppenderTagName,
layout = defaultLayout
}) {
const hasAppender = CustomAppender !== false;
const hasCustomAppender = !!CustomAppender;
const {
order,
isZoomOut: isZoomOut2,
selectedBlocks,
visibleBlocks,
shouldRenderAppender
} = (0, import_data80.useSelect)(
(select3) => {
const {
getSettings: getSettings7,
getBlockOrder: getBlockOrder2,
getSelectedBlockClientIds: getSelectedBlockClientIds2,
__unstableGetVisibleBlocks: __unstableGetVisibleBlocks2,
getTemplateLock: getTemplateLock2,
getBlockEditingMode: getBlockEditingMode2,
isSectionBlock: isSectionBlock2,
isContainerInsertableToInContentOnlyMode: isContainerInsertableToInContentOnlyMode2,
getBlockName: getBlockName2,
isZoomOut: _isZoomOut,
canInsertBlockType: canInsertBlockType2
} = unlock(select3(store));
const _order = getBlockOrder2(rootClientId);
if (getSettings7().isPreviewMode) {
return {
order: _order,
selectedBlocks: EMPTY_ARRAY8,
visibleBlocks: EMPTY_SET2
};
}
const selectedBlockClientIds = getSelectedBlockClientIds2();
const selectedBlockClientId = selectedBlockClientIds[0];
const showRootAppender = !rootClientId && !selectedBlockClientId && (!_order.length || !canInsertBlockType2(
(0, import_blocks47.getDefaultBlockName)(),
rootClientId
));
const hasSelectedRoot = !!(rootClientId && selectedBlockClientId && rootClientId === selectedBlockClientId);
const templateLock = getTemplateLock2(rootClientId);
return {
order: _order,
selectedBlocks: selectedBlockClientIds,
visibleBlocks: __unstableGetVisibleBlocks2(),
isZoomOut: _isZoomOut(),
shouldRenderAppender: (!isSectionBlock2(rootClientId) || isContainerInsertableToInContentOnlyMode2(
getBlockName2(selectedBlockClientId),
rootClientId
)) && getBlockEditingMode2(rootClientId) !== "disabled" && (!templateLock || templateLock === "contentOnly") && hasAppender && !_isZoomOut() && (hasCustomAppender || hasSelectedRoot || showRootAppender)
};
},
[rootClientId, hasAppender, hasCustomAppender]
);
return /* @__PURE__ */ (0, import_jsx_runtime269.jsxs)(LayoutProvider, { value: layout, children: [
order.map((clientId) => /* @__PURE__ */ (0, import_jsx_runtime269.jsxs)(
import_data80.AsyncModeProvider,
{
value: (
// Only provide data asynchronously if the block is
// not visible and not selected.
!visibleBlocks.has(clientId) && !selectedBlocks.includes(clientId)
),
children: [
isZoomOut2 && /* @__PURE__ */ (0, import_jsx_runtime269.jsx)(
ZoomOutSeparator,
{
clientId,
rootClientId,
position: "top"
}
),
/* @__PURE__ */ (0, import_jsx_runtime269.jsx)(
block_default2,
{
rootClientId,
clientId
}
),
isZoomOut2 && /* @__PURE__ */ (0, import_jsx_runtime269.jsx)(
ZoomOutSeparator,
{
clientId,
rootClientId,
position: "bottom"
}
)
]
},
clientId
)),
order.length < 1 && placeholder,
shouldRenderAppender && /* @__PURE__ */ (0, import_jsx_runtime269.jsx)(
BlockListAppender,
{
tagName: __experimentalAppenderTagName,
rootClientId,
CustomAppender
}
)
] });
}
function BlockListItems(props) {
return /* @__PURE__ */ (0, import_jsx_runtime269.jsx)(import_data80.AsyncModeProvider, { value: false, children: /* @__PURE__ */ (0, import_jsx_runtime269.jsx)(Items, { ...props }) });
}
// packages/block-editor/build-module/components/block-tools/index.mjs
var import_data123 = __toESM(require_data(), 1);
var import_dom59 = __toESM(require_dom(), 1);
var import_components115 = __toESM(require_components(), 1);
var import_keyboard_shortcuts10 = __toESM(require_keyboard_shortcuts(), 1);
var import_element177 = __toESM(require_element(), 1);
var import_blocks77 = __toESM(require_blocks(), 1);
var import_a11y12 = __toESM(require_a11y(), 1);
var import_i18n103 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/block-tools/use-block-toolbar-popover-props.mjs
var import_compose60 = __toESM(require_compose(), 1);
var import_data85 = __toESM(require_data(), 1);
var import_dom55 = __toESM(require_dom(), 1);
var import_element149 = __toESM(require_element(), 1);
// packages/block-editor/build-module/hooks/position.mjs
var import_i18n72 = __toESM(require_i18n(), 1);
var import_blocks49 = __toESM(require_blocks(), 1);
var import_compose59 = __toESM(require_compose(), 1);
var import_data84 = __toESM(require_data(), 1);
var import_element148 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/inspector-controls/fill.mjs
var import_components70 = __toESM(require_components(), 1);
var import_warning5 = __toESM(require_warning(), 1);
var import_deprecated10 = __toESM(require_deprecated(), 1);
var import_element144 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/inspector-controls/groups.mjs
var import_components68 = __toESM(require_components(), 1);
var InspectorControlsDefault = (0, import_components68.createSlotFill)("InspectorControls");
var InspectorControlsAdvanced = (0, import_components68.createSlotFill)("InspectorAdvancedControls");
var InspectorControlsBindings = (0, import_components68.createSlotFill)("InspectorControlsBindings");
var InspectorControlsBackground = (0, import_components68.createSlotFill)(
"InspectorControlsBackground"
);
var InspectorControlsBorder = (0, import_components68.createSlotFill)("InspectorControlsBorder");
var InspectorControlsColor = (0, import_components68.createSlotFill)("InspectorControlsColor");
var InspectorControlsFilter = (0, import_components68.createSlotFill)("InspectorControlsFilter");
var InspectorControlsDimensions = (0, import_components68.createSlotFill)(
"InspectorControlsDimensions"
);
var InspectorControlsLayout = (0, import_components68.createSlotFill)("InspectorControlsLayout");
var InspectorControlsElements = (0, import_components68.createSlotFill)("InspectorControlsElements");
var InspectorControlsPosition = (0, import_components68.createSlotFill)("InspectorControlsPosition");
var InspectorControlsTypography = (0, import_components68.createSlotFill)(
"InspectorControlsTypography"
);
var InspectorControlsListView = (0, import_components68.createSlotFill)("InspectorControlsListView");
var InspectorControlsStyles = (0, import_components68.createSlotFill)("InspectorControlsStyles");
var InspectorControlsEffects = (0, import_components68.createSlotFill)("InspectorControlsEffects");
var InspectorControlsContent = (0, import_components68.createSlotFill)("InspectorControlsContent");
var groups = {
default: InspectorControlsDefault,
advanced: InspectorControlsAdvanced,
background: InspectorControlsBackground,
bindings: InspectorControlsBindings,
border: InspectorControlsBorder,
color: InspectorControlsColor,
content: InspectorControlsContent,
dimensions: InspectorControlsDimensions,
effects: InspectorControlsEffects,
elements: InspectorControlsElements,
filter: InspectorControlsFilter,
layout: InspectorControlsLayout,
list: InspectorControlsListView,
position: InspectorControlsPosition,
settings: InspectorControlsDefault,
// Alias for default.
styles: InspectorControlsStyles,
typography: InspectorControlsTypography
};
var groups_default = groups;
var PrivateInspectorControlsAllowedBlocks = (0, import_components68.createSlotFill)(
/* @__PURE__ */ Symbol("PrivateInspectorControlsAllowedBlocks")
);
// packages/block-editor/build-module/hooks/block-style-state.mjs
var import_element142 = __toESM(require_element(), 1);
var DEFAULT_STATE_VALUE = "default";
var DEFAULT_BLOCK_STYLE_STATE2 = {
viewport: DEFAULT_STATE_VALUE,
pseudo: DEFAULT_STATE_VALUE
};
var BlockStyleStateContext = (0, import_element142.createContext)(DEFAULT_BLOCK_STYLE_STATE2);
var BlockStyleStateProvider = BlockStyleStateContext.Provider;
function useBlockStyleState() {
return (0, import_element142.useContext)(BlockStyleStateContext);
}
function hasViewportBlockStyleState(selectedState) {
return !!selectedState?.viewport && selectedState.viewport !== DEFAULT_STATE_VALUE;
}
function hasPseudoBlockStyleState(selectedState) {
return !!selectedState?.pseudo && selectedState.pseudo !== DEFAULT_STATE_VALUE;
}
function isDefaultBlockStyleState(selectedState) {
return !hasViewportBlockStyleState(selectedState) && !hasPseudoBlockStyleState(selectedState);
}
function getStyleStatePath(selectedState) {
if (isDefaultBlockStyleState(selectedState)) {
return [];
}
return [selectedState.viewport, selectedState.pseudo].filter(
(state) => state && state !== DEFAULT_STATE_VALUE
);
}
function getStyleForState(style, selectedState) {
const path = getStyleStatePath(selectedState);
if (!path.length) {
return style;
}
return getValueFromObjectPath2(style, path);
}
function setStyleForState(style, selectedState, newStyle) {
const path = getStyleStatePath(selectedState);
if (!path.length) {
return cleanEmptyObject(newStyle);
}
return cleanEmptyObject(setImmutably2(style, path, newStyle));
}
function scopeResetAllFilterToState(selectedState, resetAllFilter) {
if (!resetAllFilter || isDefaultBlockStyleState(selectedState)) {
return resetAllFilter;
}
return (attributes) => {
const existingStateStyle = getStyleForState(attributes?.style, selectedState) || {};
const updatedStateAttributes = resetAllFilter({
style: existingStateStyle
});
const updatedStateStyle = updatedStateAttributes && typeof updatedStateAttributes === "object" && !Array.isArray(updatedStateAttributes) && Object.prototype.hasOwnProperty.call(
updatedStateAttributes,
"style"
) ? updatedStateAttributes.style : updatedStateAttributes;
return {
style: setStyleForState(
attributes?.style,
selectedState,
updatedStateStyle
)
};
};
}
// packages/block-editor/build-module/components/inspector-controls/list-view-content-popover.mjs
var import_components69 = __toESM(require_components(), 1);
var import_element143 = __toESM(require_element(), 1);
var import_compose57 = __toESM(require_compose(), 1);
var import_data81 = __toESM(require_data(), 1);
var import_jsx_runtime270 = __toESM(require_jsx_runtime(), 1);
var LIST_VIEW_CONTENT_PANEL_SLOT = /* @__PURE__ */ Symbol("ListViewContentPopover");
var { Fill, Slot: Slot2 } = (0, import_components69.createSlotFill)(LIST_VIEW_CONTENT_PANEL_SLOT);
function useInspectorPopoverPlacement() {
const isMobile = (0, import_compose57.useViewportMatch)("medium", "<");
return !isMobile ? {
popoverProps: {
placement: "left-start",
offset: 35,
resize: false
}
} : {};
}
function ListViewContentPopover({ listViewRef }) {
const { popoverProps: popoverProps3 } = useInspectorPopoverPlacement();
const fills = (0, import_components69.__experimentalUseSlotFills)(LIST_VIEW_CONTENT_PANEL_SLOT);
const hasFills = Boolean(fills && fills.length);
const { selectedClientId, isOpen } = (0, import_data81.useSelect)((select3) => {
const { getSelectedBlockClientId: getSelectedBlockClientId2 } = select3(store);
const privateSelectors = unlock(select3(store));
return {
selectedClientId: getSelectedBlockClientId2(),
isOpen: privateSelectors.isListViewContentPanelOpen()
};
}, []);
const [anchorElement, setAnchorElement] = (0, import_element143.useState)(null);
(0, import_element143.useLayoutEffect)(() => {
if (!selectedClientId || !listViewRef?.current) {
setAnchorElement(null);
return;
}
const element = listViewRef.current.querySelector(
`[data-block="${selectedClientId}"]`
);
setAnchorElement(element);
}, [selectedClientId, listViewRef]);
const { closeListViewContentPanel: closeListViewContentPanel2 } = unlock(
(0, import_data81.useDispatch)(store)
);
if (!isOpen || !hasFills || !anchorElement) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime270.jsx)(
import_components69.Popover,
{
...popoverProps3 ?? {},
className: "block-editor-inspector-list-view-content-popover",
anchor: anchorElement,
onClose: closeListViewContentPanel2,
children: /* @__PURE__ */ (0, import_jsx_runtime270.jsx)("div", { style: { width: "280px" }, children: /* @__PURE__ */ (0, import_jsx_runtime270.jsx)(Slot2, {}) })
}
);
}
// packages/block-editor/build-module/components/inspector-controls/fill.mjs
var import_jsx_runtime271 = __toESM(require_jsx_runtime(), 1);
var PATTERN_EDITING_GROUPS = ["content", "list"];
function InspectorControlsFill({
children,
group = "default",
__experimentalGroup,
resetAllFilter
}) {
if (__experimentalGroup) {
(0, import_deprecated10.default)(
"`__experimentalGroup` property in `InspectorControlsFill`",
{
since: "6.2",
version: "6.4",
alternative: "`group`"
}
);
group = __experimentalGroup;
}
const context = useBlockEditContext();
const Fill5 = groups_default[group]?.Fill;
if (!Fill5) {
(0, import_warning5.default)(`Unknown InspectorControls group "${group}" provided.`);
return null;
}
if (context[mayDisplayPatternEditingControlsKey]) {
const isTemplatePart9 = context.name === "core/template-part";
const isPatternEditingGroup = PATTERN_EDITING_GROUPS.includes(group);
const canShowGroup = isTemplatePart9 || isPatternEditingGroup;
if (!canShowGroup) {
return null;
}
}
if (!context[mayDisplayPatternEditingControlsKey] && !context[mayDisplayControlsKey]) {
return null;
}
if (group === "content" && !!context[isInListViewBlockSupportTreeKey] && !!context[mayDisplayPatternEditingControlsKey]) {
if (context[mayDisplayControlsKey]) {
return /* @__PURE__ */ (0, import_jsx_runtime271.jsx)(import_components70.__experimentalStyleProvider, { document, children: /* @__PURE__ */ (0, import_jsx_runtime271.jsx)(Fill, { children }) });
}
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime271.jsx)(import_components70.__experimentalStyleProvider, { document, children: /* @__PURE__ */ (0, import_jsx_runtime271.jsx)(Fill5, { children: (fillProps) => {
return /* @__PURE__ */ (0, import_jsx_runtime271.jsx)(
ToolsPanelInspectorControl,
{
fillProps,
children,
resetAllFilter
}
);
} }) });
}
function RegisterResetAll({ resetAllFilter, children }) {
const { registerResetAllFilter, deregisterResetAllFilter } = (0, import_element144.useContext)(import_components70.__experimentalToolsPanelContext);
const selectedState = useBlockStyleState();
const scopedResetAllFilter = (0, import_element144.useMemo)(
() => scopeResetAllFilterToState(selectedState, resetAllFilter),
[resetAllFilter, selectedState]
);
(0, import_element144.useEffect)(() => {
if (scopedResetAllFilter && registerResetAllFilter && deregisterResetAllFilter) {
registerResetAllFilter(scopedResetAllFilter);
return () => {
deregisterResetAllFilter(scopedResetAllFilter);
};
}
}, [
scopedResetAllFilter,
registerResetAllFilter,
deregisterResetAllFilter
]);
return children;
}
function ToolsPanelInspectorControl({ children, resetAllFilter, fillProps }) {
const { forwardedContext = [] } = fillProps;
const innerMarkup = /* @__PURE__ */ (0, import_jsx_runtime271.jsx)(RegisterResetAll, { resetAllFilter, children });
return forwardedContext.reduce(
(inner, [Provider3, props]) => /* @__PURE__ */ (0, import_jsx_runtime271.jsx)(Provider3, { ...props, children: inner }),
innerMarkup
);
}
// packages/block-editor/build-module/components/inspector-controls/slot.mjs
var import_components73 = __toESM(require_components(), 1);
var import_element147 = __toESM(require_element(), 1);
var import_warning6 = __toESM(require_warning(), 1);
var import_deprecated11 = __toESM(require_deprecated(), 1);
// packages/block-editor/build-module/components/inspector-controls/block-support-tools-panel.mjs
var import_components71 = __toESM(require_components(), 1);
var import_data82 = __toESM(require_data(), 1);
var import_element145 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/global-styles/utils.mjs
var import_compose58 = __toESM(require_compose(), 1);
function useToolsPanelDropdownMenuProps() {
const isMobile = (0, import_compose58.useViewportMatch)("medium", "<");
return !isMobile ? {
popoverProps: {
placement: "left-start",
// For non-mobile, inner sidebar width (248px) - button width (24px) - border (1px) + padding (16px) + spacing (20px)
offset: 259
}
} : {};
}
function scopeSelector2(scope, selector3) {
if (!scope || !selector3) {
return selector3;
}
const scopes = scope.split(",");
const selectors4 = selector3.split(",");
const selectorsScoped = [];
scopes.forEach((outer) => {
selectors4.forEach((inner) => {
selectorsScoped.push(`${outer.trim()} ${inner.trim()}`);
});
});
return selectorsScoped.join(", ");
}
// packages/block-editor/build-module/components/inspector-controls/block-support-tools-panel.mjs
var import_jsx_runtime272 = __toESM(require_jsx_runtime(), 1);
function BlockSupportToolsPanel({ children, group, label }) {
const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data82.useDispatch)(store);
const {
getBlockAttributes: getBlockAttributes3,
getBlockName: getBlockName2,
getMultiSelectedBlockClientIds: getMultiSelectedBlockClientIds2,
getSelectedBlockClientId: getSelectedBlockClientId2,
hasMultiSelection: hasMultiSelection2
} = (0, import_data82.useSelect)(store);
const dropdownMenuProps = useToolsPanelDropdownMenuProps();
const panelId = getSelectedBlockClientId2();
const resetAll = (0, import_element145.useCallback)(
(resetFilters = []) => {
const newAttributes = {};
const clientIds = hasMultiSelection2() ? getMultiSelectedBlockClientIds2() : [panelId];
clientIds.forEach((clientId) => {
const blockAttributes = getBlockAttributes3(clientId) || {};
const { style } = blockAttributes;
let newBlockAttributes = { style };
const resetContext = {
attributes: blockAttributes,
clientId,
name: getBlockName2(clientId)
};
resetFilters.forEach((resetFilter) => {
newBlockAttributes = {
...newBlockAttributes,
...resetFilter(newBlockAttributes, resetContext)
};
});
newBlockAttributes = {
...newBlockAttributes,
style: cleanEmptyObject(newBlockAttributes.style)
};
newAttributes[clientId] = newBlockAttributes;
});
updateBlockAttributes2(clientIds, newAttributes, true);
},
[
getBlockAttributes3,
getBlockName2,
getMultiSelectedBlockClientIds2,
hasMultiSelection2,
panelId,
updateBlockAttributes2
]
);
return /* @__PURE__ */ (0, import_jsx_runtime272.jsx)(
import_components71.__experimentalToolsPanel,
{
className: `${group}-block-support-panel`,
label,
resetAll,
panelId,
hasInnerWrapper: true,
shouldRenderPlaceholderItems: true,
__experimentalFirstVisibleItemClass: "first",
__experimentalLastVisibleItemClass: "last",
dropdownMenuProps,
children
},
panelId
);
}
// packages/block-editor/build-module/components/inspector-controls/block-support-slot-container.mjs
var import_components72 = __toESM(require_components(), 1);
var import_element146 = __toESM(require_element(), 1);
var import_jsx_runtime273 = __toESM(require_jsx_runtime(), 1);
function BlockSupportSlotContainer({
Slot: Slot10,
fillProps,
...props
}) {
const toolsPanelContext = (0, import_element146.useContext)(import_components72.__experimentalToolsPanelContext);
const computedFillProps = (0, import_element146.useMemo)(
() => ({
...fillProps ?? {},
forwardedContext: [
...fillProps?.forwardedContext ?? [],
[import_components72.__experimentalToolsPanelContext.Provider, { value: toolsPanelContext }]
]
}),
[toolsPanelContext, fillProps]
);
return /* @__PURE__ */ (0, import_jsx_runtime273.jsx)(Slot10, { ...props, fillProps: computedFillProps, bubblesVirtually: true });
}
// packages/block-editor/build-module/components/inspector-controls/slot.mjs
var import_jsx_runtime274 = __toESM(require_jsx_runtime(), 1);
function InspectorControlsSlot({ __experimentalGroup, group = "default", label, fillProps, ...props }, ref) {
if (__experimentalGroup) {
(0, import_deprecated11.default)(
"`__experimentalGroup` property in `InspectorControlsSlot`",
{
since: "6.2",
version: "6.4",
alternative: "`group`"
}
);
group = __experimentalGroup;
}
const slotFill = groups_default[group];
const fills = (0, import_components73.__experimentalUseSlotFills)(slotFill?.name);
if (!slotFill) {
(0, import_warning6.default)(`Unknown InspectorControls group "${group}" provided.`);
return null;
}
if (!fills?.length) {
return null;
}
const { Slot: Slot10 } = slotFill;
if (label) {
return /* @__PURE__ */ (0, import_jsx_runtime274.jsx)(BlockSupportToolsPanel, { group, label, children: /* @__PURE__ */ (0, import_jsx_runtime274.jsx)(
BlockSupportSlotContainer,
{
...props,
fillProps,
Slot: Slot10
}
) });
}
return /* @__PURE__ */ (0, import_jsx_runtime274.jsx)(
Slot10,
{
...props,
ref,
fillProps,
bubblesVirtually: true
}
);
}
var slot_default = (0, import_element147.forwardRef)(InspectorControlsSlot);
// packages/block-editor/build-module/components/inspector-controls/index.mjs
var import_jsx_runtime275 = __toESM(require_jsx_runtime(), 1);
var InspectorControls = InspectorControlsFill;
InspectorControls.Slot = slot_default;
var InspectorAdvancedControls = (props) => {
return /* @__PURE__ */ (0, import_jsx_runtime275.jsx)(InspectorControlsFill, { ...props, group: "advanced" });
};
InspectorAdvancedControls.Slot = function Slot3(props) {
return /* @__PURE__ */ (0, import_jsx_runtime275.jsx)(slot_default, { ...props, group: "advanced" });
};
InspectorAdvancedControls.slotName = "InspectorAdvancedControls";
var inspector_controls_default = InspectorControls;
// packages/block-editor/build-module/components/use-block-display-information/index.mjs
var import_data83 = __toESM(require_data(), 1);
var import_blocks48 = __toESM(require_blocks(), 1);
var import_i18n71 = __toESM(require_i18n(), 1);
function getPositionTypeLabel(attributes) {
const positionType = attributes?.style?.position?.type;
if (positionType === "sticky") {
return (0, import_i18n71.__)("Sticky");
}
if (positionType === "fixed") {
return (0, import_i18n71.__)("Fixed");
}
return null;
}
function useBlockDisplayInformation(clientId) {
return (0, import_data83.useSelect)(
(select3) => {
if (!clientId) {
return null;
}
const blockEditorSelect = select3(store);
const {
getBlockName: getBlockName2,
getBlockAttributes: getBlockAttributes3,
getBlock: getBlock2,
__experimentalGetParsedPattern: __experimentalGetParsedPattern2
} = blockEditorSelect;
const { getBlockType: getBlockType29, getActiveBlockVariation } = select3(import_blocks48.store);
const blockName = getBlockName2(clientId);
const blockType = getBlockType29(blockName);
if (!blockType) {
return null;
}
const attributes = getBlockAttributes3(clientId);
const { isSectionBlock: isSectionBlock2 } = unlock(blockEditorSelect);
const patternName = attributes?.metadata?.patternName;
if (patternName && isSectionBlock2(clientId)) {
const pattern = __experimentalGetParsedPattern2(patternName);
const positionLabel2 = getPositionTypeLabel(attributes);
return {
isSynced: false,
title: (0, import_i18n71.__)("Pattern"),
icon: symbol_default,
description: pattern?.description || (0, import_i18n71.__)("A block pattern."),
anchor: attributes?.anchor,
positionLabel: positionLabel2,
positionType: attributes?.style?.position?.type,
name: pattern?.title || attributes?.metadata?.name
};
}
const match2 = getActiveBlockVariation(
blockName,
attributes,
void 0,
getBlock2?.(clientId)?.innerContent
);
const isSynced = (0, import_blocks48.isReusableBlock)(blockType) || (0, import_blocks48.isTemplatePart)(blockType);
const syncedTitle = isSynced ? (0, import_blocks48.__experimentalGetBlockLabel)(blockType, attributes) : void 0;
const title = syncedTitle || blockType.title;
const positionLabel = getPositionTypeLabel(attributes);
const blockTypeInfo = {
isSynced,
title,
icon: blockType.icon,
description: blockType.description,
anchor: attributes?.anchor,
positionLabel,
positionType: attributes?.style?.position?.type,
name: attributes?.metadata?.name
};
if (!match2) {
return blockTypeInfo;
}
return {
isSynced,
title: match2.title || blockType.title,
icon: match2.icon || blockType.icon,
description: match2.description || blockType.description,
anchor: attributes?.anchor,
positionLabel,
positionType: attributes?.style?.position?.type,
name: attributes?.metadata?.name
};
},
[clientId]
);
}
// packages/block-editor/build-module/hooks/position.mjs
var import_jsx_runtime276 = __toESM(require_jsx_runtime(), 1);
var POSITION_SUPPORT_KEY = "position";
var DEFAULT_OPTION = {
key: "default",
value: "",
label: (0, import_i18n72.__)("Default")
};
var STICKY_OPTION = {
key: "sticky",
value: "sticky",
label: (0, import_i18n72._x)("Sticky", "Name for the value of the CSS position property"),
hint: (0, import_i18n72.__)(
"The block will stick to the top of the window instead of scrolling."
)
};
var FIXED_OPTION = {
key: "fixed",
value: "fixed",
label: (0, import_i18n72._x)("Fixed", "Name for the value of the CSS position property"),
hint: (0, import_i18n72.__)("The block will not move when the page is scrolled.")
};
var POSITION_SIDES = ["top", "right", "bottom", "left"];
var VALID_POSITION_TYPES = ["sticky", "fixed"];
function getPositionCSS({ selector: selector3, style }) {
let output = "";
const { type: positionType } = style?.position || {};
if (!VALID_POSITION_TYPES.includes(positionType)) {
return output;
}
output += `${selector3} {`;
output += `position: ${positionType};`;
POSITION_SIDES.forEach((side) => {
if (style?.position?.[side] !== void 0) {
output += `${side}: ${style.position[side]};`;
}
});
if (positionType === "sticky" || positionType === "fixed") {
output += `z-index: 10`;
}
output += `}`;
return output;
}
function hasStickyPositionSupport(blockType) {
const support = (0, import_blocks49.getBlockSupport)(blockType, POSITION_SUPPORT_KEY);
return !!(true === support || support?.sticky);
}
function hasFixedPositionSupport(blockType) {
const support = (0, import_blocks49.getBlockSupport)(blockType, POSITION_SUPPORT_KEY);
return !!(true === support || support?.fixed);
}
function hasPositionSupport(blockType) {
const support = (0, import_blocks49.getBlockSupport)(blockType, POSITION_SUPPORT_KEY);
return !!support;
}
function hasStickyOrFixedPositionValue(attributes) {
const positionType = attributes?.style?.position?.type;
return positionType === "sticky" || positionType === "fixed";
}
function useIsPositionDisabled({ name: blockName } = {}) {
const [allowFixed, allowSticky] = useSettings(
"position.fixed",
"position.sticky"
);
const isDisabled = !allowFixed && !allowSticky;
return !hasPositionSupport(blockName) || isDisabled;
}
function PositionPanelPure({
style = {},
clientId,
name: blockName,
setAttributes
}) {
const allowFixed = hasFixedPositionSupport(blockName);
const allowSticky = hasStickyPositionSupport(blockName);
const value = style?.position?.type;
const { firstParentClientId } = (0, import_data84.useSelect)(
(select3) => {
const { getBlockParents: getBlockParents2 } = select3(store);
const parents = getBlockParents2(clientId);
return { firstParentClientId: parents[parents.length - 1] };
},
[clientId]
);
const blockInformation = useBlockDisplayInformation(firstParentClientId);
const stickyHelpText = allowSticky && value === STICKY_OPTION.value && blockInformation ? (0, import_i18n72.sprintf)(
/* translators: %s: the name of the parent block. */
(0, import_i18n72.__)(
"The block will stick to the scrollable area of the parent %s block."
),
blockInformation.title
) : null;
const options = (0, import_element148.useMemo)(() => {
const availableOptions = [DEFAULT_OPTION];
if (allowSticky || value === STICKY_OPTION.value) {
availableOptions.push(STICKY_OPTION);
}
if (allowFixed || value === FIXED_OPTION.value) {
availableOptions.push(FIXED_OPTION);
}
return availableOptions;
}, [allowFixed, allowSticky, value]);
const onChangeType = (next) => {
const placementValue = "0px";
const newStyle = {
...style,
position: {
...style?.position,
type: next,
top: next === "sticky" || next === "fixed" ? placementValue : void 0
}
};
setAttributes({
style: cleanEmptyObject(newStyle)
});
};
const selectedOption = value ? options.find((option) => option.value === value) || DEFAULT_OPTION : DEFAULT_OPTION;
const hintIdPrefix = (0, import_element148.useId)();
return options.length > 1 ? /* @__PURE__ */ (0, import_jsx_runtime276.jsx)(inspector_controls_default, { group: "position", children: /* @__PURE__ */ (0, import_jsx_runtime276.jsx)(
SelectControl3,
{
label: (0, import_i18n72.__)("Position"),
hideLabelFromVision: true,
description: stickyHelpText,
items: options,
value: selectedOption,
onValueChange: (selectedItem) => {
onChangeType(selectedItem.value);
},
children: options.map((option) => {
const hintId = option.hint ? `${hintIdPrefix}-${option.key}` : void 0;
return /* @__PURE__ */ (0, import_jsx_runtime276.jsxs)(
SelectControl3.Item,
{
value: option,
label: option.label,
className: "block-editor-hooks__position-control-item",
"aria-describedby": hintId,
children: [
/* @__PURE__ */ (0, import_jsx_runtime276.jsx)("div", { children: option.label }),
option.hint && /* @__PURE__ */ (0, import_jsx_runtime276.jsx)(
"div",
{
id: hintId,
className: "block-editor-hooks__position-control-item-hint",
"aria-hidden": "true",
children: option.hint
}
)
]
},
option.key
);
})
}
) }) : null;
}
var position_default = {
edit: function Edit2(props) {
const isPositionDisabled = useIsPositionDisabled(props);
if (isPositionDisabled) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime276.jsx)(PositionPanelPure, { ...props });
},
useBlockProps: useBlockProps2,
attributeKeys: ["style"],
hasSupport(name) {
return (0, import_blocks49.hasBlockSupport)(name, POSITION_SUPPORT_KEY);
}
};
var POSITION_BLOCK_PROPS_REFERENCE = {};
function useBlockProps2({ name, style }) {
const hasPositionBlockSupport = (0, import_blocks49.hasBlockSupport)(
name,
POSITION_SUPPORT_KEY
);
const isPositionDisabled = useIsPositionDisabled({ name });
const allowPositionStyles = hasPositionBlockSupport && !isPositionDisabled;
const id = (0, import_compose59.useInstanceId)(POSITION_BLOCK_PROPS_REFERENCE);
const positionSelector = `.wp-container-${id}.wp-container-${id}`;
let css;
if (allowPositionStyles) {
css = getPositionCSS({
selector: positionSelector,
style
}) || "";
}
const className = clsx_default({
[`wp-container-${id}`]: allowPositionStyles && !!css,
// Only attach a container class if there is generated CSS to be attached.
[`is-position-${style?.position?.type}`]: allowPositionStyles && !!css && !!style?.position?.type
});
useStyleOverride({ css });
return { className };
}
// packages/block-editor/build-module/components/block-tools/use-block-toolbar-popover-props.mjs
var COMMON_PROPS = {
placement: "top-start"
};
var DEFAULT_PROPS2 = {
...COMMON_PROPS,
flip: false,
shift: true
};
var RESTRICTED_HEIGHT_PROPS = {
...COMMON_PROPS,
flip: true,
shift: false
};
function getProps(contentElement, selectedBlockElement, scrollContainer, toolbarHeight, isSticky) {
if (!contentElement || !selectedBlockElement) {
return DEFAULT_PROPS2;
}
const scrollTop = scrollContainer?.scrollTop || 0;
const blockRect = getElementBounds(selectedBlockElement);
const contentRect = contentElement.getBoundingClientRect();
const topOfContentElementInViewport = scrollTop + contentRect.top;
const viewportHeight = contentElement.ownerDocument.documentElement.clientHeight;
const restrictedTopArea = topOfContentElementInViewport + toolbarHeight;
const hasSpaceForToolbarAbove = blockRect.top > restrictedTopArea;
const isBlockTallerThanViewport = blockRect.height > viewportHeight - toolbarHeight;
if (!isSticky && (hasSpaceForToolbarAbove || isBlockTallerThanViewport)) {
return DEFAULT_PROPS2;
}
return RESTRICTED_HEIGHT_PROPS;
}
function useBlockToolbarPopoverProps({
contentElement,
clientId
}) {
const selectedBlockElement = useBlockElement(clientId);
const [toolbarHeight, setToolbarHeight] = (0, import_element149.useState)(0);
const { blockIndex, isSticky } = (0, import_data85.useSelect)(
(select3) => {
const { getBlockIndex: getBlockIndex2, getBlockAttributes: getBlockAttributes3 } = select3(store);
return {
blockIndex: getBlockIndex2(clientId),
isSticky: hasStickyOrFixedPositionValue(
getBlockAttributes3(clientId)
)
};
},
[clientId]
);
const scrollContainer = (0, import_element149.useMemo)(() => {
if (!contentElement) {
return;
}
return (0, import_dom55.getScrollContainer)(contentElement);
}, [contentElement]);
const [props, setProps] = (0, import_element149.useState)(
() => getProps(
contentElement,
selectedBlockElement,
scrollContainer,
toolbarHeight,
isSticky
)
);
const popoverRef = (0, import_compose60.useRefEffect)((popoverNode) => {
setToolbarHeight(popoverNode.offsetHeight);
}, []);
const updateProps = (0, import_element149.useCallback)(
() => setProps(
getProps(
contentElement,
selectedBlockElement,
scrollContainer,
toolbarHeight,
isSticky
)
),
[
contentElement,
selectedBlockElement,
scrollContainer,
toolbarHeight,
isSticky
]
);
(0, import_element149.useLayoutEffect)(updateProps, [blockIndex, updateProps]);
(0, import_element149.useLayoutEffect)(() => {
if (!contentElement || !selectedBlockElement) {
return;
}
const contentView = contentElement?.ownerDocument?.defaultView;
contentView?.addEventListener?.("resize", updateProps);
let resizeObserver;
const blockView = selectedBlockElement?.ownerDocument?.defaultView;
if (blockView?.ResizeObserver) {
resizeObserver = new blockView.ResizeObserver(updateProps);
resizeObserver.observe(selectedBlockElement);
}
return () => {
contentView?.removeEventListener?.("resize", updateProps);
if (resizeObserver) {
resizeObserver.disconnect();
}
};
}, [updateProps, contentElement, selectedBlockElement]);
return {
...props,
ref: popoverRef
};
}
// packages/block-editor/build-module/components/block-tools/use-selected-block-tool-props.mjs
var import_data86 = __toESM(require_data(), 1);
function useSelectedBlockToolProps(clientId) {
const selectedBlockProps = (0, import_data86.useSelect)(
(select3) => {
const {
getBlockRootClientId: getBlockRootClientId2,
getBlockParents: getBlockParents2,
__experimentalGetBlockListSettingsForBlocks: __experimentalGetBlockListSettingsForBlocks2,
isBlockInsertionPointVisible: isBlockInsertionPointVisible2,
getBlockInsertionPoint: getBlockInsertionPoint2,
getBlockOrder: getBlockOrder2,
hasMultiSelection: hasMultiSelection2,
getLastMultiSelectedBlockClientId: getLastMultiSelectedBlockClientId2
} = select3(store);
const blockParentsClientIds = getBlockParents2(clientId);
const parentBlockListSettings = __experimentalGetBlockListSettingsForBlocks2(
blockParentsClientIds
);
const capturingClientId = blockParentsClientIds.find(
(parentClientId) => parentBlockListSettings[parentClientId]?.__experimentalCaptureToolbars
);
let isInsertionPointVisible = false;
if (isBlockInsertionPointVisible2()) {
const insertionPoint2 = getBlockInsertionPoint2();
const order = getBlockOrder2(insertionPoint2.rootClientId);
isInsertionPointVisible = order[insertionPoint2.index] === clientId;
}
return {
capturingClientId,
isInsertionPointVisible,
lastClientId: hasMultiSelection2() ? getLastMultiSelectedBlockClientId2() : null,
rootClientId: getBlockRootClientId2(clientId)
};
},
[clientId]
);
return selectedBlockProps;
}
// packages/block-editor/build-module/components/block-tools/empty-block-inserter.mjs
var import_jsx_runtime277 = __toESM(require_jsx_runtime(), 1);
function EmptyBlockInserter({
clientId,
__unstableContentRef
}) {
const {
capturingClientId,
isInsertionPointVisible,
lastClientId,
rootClientId
} = useSelectedBlockToolProps(clientId);
const popoverProps3 = useBlockToolbarPopoverProps({
contentElement: __unstableContentRef?.current,
clientId
});
return /* @__PURE__ */ (0, import_jsx_runtime277.jsx)(
cover_default,
{
clientId: capturingClientId || clientId,
bottomClientId: lastClientId,
className: clsx_default(
"block-editor-block-list__block-side-inserter-popover",
{
"is-insertion-point-visible": isInsertionPointVisible
}
),
__unstableContentRef,
...popoverProps3,
children: /* @__PURE__ */ (0, import_jsx_runtime277.jsx)("div", { className: "block-editor-block-list__empty-block-inserter", children: /* @__PURE__ */ (0, import_jsx_runtime277.jsx)(
inserter_default,
{
position: "bottom right",
rootClientId,
clientId,
__experimentalIsQuick: true
}
) })
}
);
}
// packages/block-editor/build-module/components/block-tools/block-toolbar-popover.mjs
var import_data120 = __toESM(require_data(), 1);
var import_element175 = __toESM(require_element(), 1);
var import_keyboard_shortcuts9 = __toESM(require_keyboard_shortcuts(), 1);
// packages/block-editor/build-module/components/block-toolbar/index.mjs
var import_i18n101 = __toESM(require_i18n(), 1);
var import_data119 = __toESM(require_data(), 1);
var import_element174 = __toESM(require_element(), 1);
var import_compose67 = __toESM(require_compose(), 1);
var import_blocks75 = __toESM(require_blocks(), 1);
var import_components113 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/block-mover/index.mjs
var import_components76 = __toESM(require_components(), 1);
var import_data89 = __toESM(require_data(), 1);
var import_i18n75 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/block-draggable/index.mjs
var import_blocks50 = __toESM(require_blocks(), 1);
var import_components74 = __toESM(require_components(), 1);
var import_data87 = __toESM(require_data(), 1);
var import_element151 = __toESM(require_element(), 1);
var import_compose61 = __toESM(require_compose(), 1);
// packages/block-editor/build-module/components/block-draggable/use-scroll-when-dragging.mjs
var import_dom57 = __toESM(require_dom(), 1);
var import_element150 = __toESM(require_element(), 1);
var SCROLL_INACTIVE_DISTANCE_PX = 50;
var SCROLL_INTERVAL_MS = 25;
var PIXELS_PER_SECOND_PER_PERCENTAGE = 1e3;
var VELOCITY_MULTIPLIER = PIXELS_PER_SECOND_PER_PERCENTAGE * (SCROLL_INTERVAL_MS / 1e3);
function useScrollWhenDragging() {
const dragStartYRef = (0, import_element150.useRef)(null);
const velocityYRef = (0, import_element150.useRef)(null);
const scrollParentYRef = (0, import_element150.useRef)(null);
const scrollEditorIntervalRef = (0, import_element150.useRef)(null);
(0, import_element150.useEffect)(
() => () => {
if (scrollEditorIntervalRef.current) {
clearInterval(scrollEditorIntervalRef.current);
scrollEditorIntervalRef.current = null;
}
},
[]
);
const startScrolling = (0, import_element150.useCallback)((event) => {
dragStartYRef.current = event.clientY;
scrollParentYRef.current = (0, import_dom57.getScrollContainer)(event.target);
scrollEditorIntervalRef.current = setInterval(() => {
if (scrollParentYRef.current && velocityYRef.current) {
const newTop = scrollParentYRef.current.scrollTop + velocityYRef.current;
scrollParentYRef.current.scroll({
top: newTop
});
}
}, SCROLL_INTERVAL_MS);
}, []);
const scrollOnDragOver = (0, import_element150.useCallback)((event) => {
if (!scrollParentYRef.current) {
return;
}
const scrollParentHeight = scrollParentYRef.current.offsetHeight;
const offsetDragStartPosition = dragStartYRef.current - scrollParentYRef.current.offsetTop;
const offsetDragPosition = event.clientY - scrollParentYRef.current.offsetTop;
if (event.clientY > offsetDragStartPosition) {
const moveableDistance = Math.max(
scrollParentHeight - offsetDragStartPosition - SCROLL_INACTIVE_DISTANCE_PX,
0
);
const dragDistance = Math.max(
offsetDragPosition - offsetDragStartPosition - SCROLL_INACTIVE_DISTANCE_PX,
0
);
const distancePercentage = moveableDistance === 0 || dragDistance === 0 ? 0 : dragDistance / moveableDistance;
velocityYRef.current = VELOCITY_MULTIPLIER * distancePercentage;
} else if (event.clientY < offsetDragStartPosition) {
const moveableDistance = Math.max(
offsetDragStartPosition - SCROLL_INACTIVE_DISTANCE_PX,
0
);
const dragDistance = Math.max(
offsetDragStartPosition - offsetDragPosition - SCROLL_INACTIVE_DISTANCE_PX,
0
);
const distancePercentage = moveableDistance === 0 || dragDistance === 0 ? 0 : dragDistance / moveableDistance;
velocityYRef.current = -VELOCITY_MULTIPLIER * distancePercentage;
} else {
velocityYRef.current = 0;
}
}, []);
const stopScrolling = () => {
dragStartYRef.current = null;
scrollParentYRef.current = null;
if (scrollEditorIntervalRef.current) {
clearInterval(scrollEditorIntervalRef.current);
scrollEditorIntervalRef.current = null;
}
};
return [startScrolling, scrollOnDragOver, stopScrolling];
}
// packages/block-editor/build-module/components/block-draggable/index.mjs
var import_jsx_runtime278 = __toESM(require_jsx_runtime(), 1);
var BlockDraggable = ({
appendToOwnerDocument,
children,
clientIds,
cloneClassname,
elementId,
onDragStart,
onDragEnd,
fadeWhenDisabled = false,
dragComponent
}) => {
const {
srcRootClientId,
isDraggable,
icon,
visibleInserter,
getBlockType: getBlockType29
} = (0, import_data87.useSelect)(
(select3) => {
const {
canMoveBlocks: canMoveBlocks2,
getBlockRootClientId: getBlockRootClientId22,
getBlockName: getBlockName2,
getBlockAttributes: getBlockAttributes3,
isBlockInsertionPointVisible: isBlockInsertionPointVisible2
} = select3(store);
const { getBlockType: _getBlockType, getActiveBlockVariation } = select3(import_blocks50.store);
const rootClientId = getBlockRootClientId22(clientIds[0]);
const blockName = getBlockName2(clientIds[0]);
const variation = getActiveBlockVariation(
blockName,
getBlockAttributes3(clientIds[0])
);
return {
srcRootClientId: rootClientId,
isDraggable: canMoveBlocks2(clientIds),
icon: variation?.icon || _getBlockType(blockName)?.icon,
visibleInserter: isBlockInsertionPointVisible2(),
getBlockType: _getBlockType
};
},
[clientIds]
);
const isDraggingRef = (0, import_element151.useRef)(false);
const [startScrolling, scrollOnDragOver, stopScrolling] = useScrollWhenDragging();
const { getAllowedBlocks: getAllowedBlocks2, getBlockNamesByClientId: getBlockNamesByClientId2, getBlockRootClientId: getBlockRootClientId2 } = (0, import_data87.useSelect)(store);
const { startDraggingBlocks: startDraggingBlocks2, stopDraggingBlocks: stopDraggingBlocks2 } = (0, import_data87.useDispatch)(store);
(0, import_element151.useEffect)(() => {
return () => {
if (isDraggingRef.current) {
stopDraggingBlocks2();
}
};
}, []);
const blockEl = useBlockElement(clientIds[0]);
const editorRoot = blockEl?.closest("body");
(0, import_element151.useEffect)(() => {
if (!editorRoot || !fadeWhenDisabled) {
return;
}
const onDragOver = (event) => {
if (!event.target.closest("[data-block]")) {
return;
}
const draggedBlockNames = getBlockNamesByClientId2(clientIds);
const targetClientId = event.target.closest("[data-block]").getAttribute("data-block");
const allowedBlocks = getAllowedBlocks2(targetClientId);
const targetBlockName = getBlockNamesByClientId2([
targetClientId
])[0];
let dropTargetValid;
if (allowedBlocks?.length === 0) {
const targetRootClientId = getBlockRootClientId2(targetClientId);
const targetRootBlockName = getBlockNamesByClientId2([
targetRootClientId
])[0];
const rootAllowedBlocks = getAllowedBlocks2(targetRootClientId);
dropTargetValid = isDropTargetValid(
getBlockType29,
rootAllowedBlocks,
draggedBlockNames,
targetRootBlockName
);
} else {
dropTargetValid = isDropTargetValid(
getBlockType29,
allowedBlocks,
draggedBlockNames,
targetBlockName
);
}
if (!dropTargetValid && !visibleInserter) {
window?.document?.body?.classList?.add(
"block-draggable-invalid-drag-token"
);
} else {
window?.document?.body?.classList?.remove(
"block-draggable-invalid-drag-token"
);
}
};
const throttledOnDragOver = (0, import_compose61.throttle)(onDragOver, 200);
editorRoot.addEventListener("dragover", throttledOnDragOver);
return () => {
editorRoot.removeEventListener("dragover", throttledOnDragOver);
};
}, [
clientIds,
editorRoot,
fadeWhenDisabled,
getAllowedBlocks2,
getBlockNamesByClientId2,
getBlockRootClientId2,
getBlockType29,
visibleInserter
]);
if (!isDraggable) {
return children({ draggable: false });
}
const transferData = {
type: "block",
srcClientIds: clientIds,
srcRootClientId
};
return /* @__PURE__ */ (0, import_jsx_runtime278.jsx)(
import_components74.Draggable,
{
appendToOwnerDocument,
cloneClassname,
__experimentalTransferDataType: "wp-blocks",
transferData,
onDragStart: (event) => {
window.requestAnimationFrame(() => {
startDraggingBlocks2(clientIds);
isDraggingRef.current = true;
startScrolling(event);
if (onDragStart) {
onDragStart();
}
});
},
onDragOver: scrollOnDragOver,
onDragEnd: () => {
stopDraggingBlocks2();
isDraggingRef.current = false;
stopScrolling();
if (onDragEnd) {
onDragEnd();
}
},
__experimentalDragComponent: (
// Check against `undefined` so that `null` can be used to disable
// the default drag component.
dragComponent !== void 0 ? dragComponent : /* @__PURE__ */ (0, import_jsx_runtime278.jsx)(
BlockDraggableChip,
{
count: clientIds.length,
icon,
fadeWhenDisabled: true
}
)
),
elementId,
children: ({ onDraggableStart, onDraggableEnd }) => {
return children({
draggable: true,
onDragStart: onDraggableStart,
onDragEnd: onDraggableEnd
});
}
}
);
};
var block_draggable_default = BlockDraggable;
// packages/block-editor/build-module/components/block-mover/button.mjs
var import_blocks51 = __toESM(require_blocks(), 1);
var import_components75 = __toESM(require_components(), 1);
var import_compose62 = __toESM(require_compose(), 1);
var import_data88 = __toESM(require_data(), 1);
var import_element152 = __toESM(require_element(), 1);
var import_i18n74 = __toESM(require_i18n(), 1);
var import_keycodes10 = __toESM(require_keycodes(), 1);
// packages/block-editor/build-module/components/block-mover/mover-description.mjs
var import_i18n73 = __toESM(require_i18n(), 1);
var getMovementDirection = (moveDirection, orientation) => {
if (moveDirection === "up") {
if (orientation === "horizontal") {
return (0, import_i18n73.isRTL)() ? "right" : "left";
}
return "up";
} else if (moveDirection === "down") {
if (orientation === "horizontal") {
return (0, import_i18n73.isRTL)() ? "left" : "right";
}
return "down";
}
return null;
};
function getBlockMoverDescription(selectedCount, type, firstIndex, isFirst, isLast, dir, orientation) {
const position = firstIndex + 1;
if (selectedCount > 1) {
return getMultiBlockMoverDescription(
selectedCount,
firstIndex,
isFirst,
isLast,
dir,
orientation
);
}
if (isFirst && isLast) {
return (0, import_i18n73.sprintf)(
// translators: %s: Type of block (i.e. Text, Image etc)
(0, import_i18n73.__)("Block %s is the only block, and cannot be moved"),
type
);
}
if (dir > 0 && !isLast) {
const movementDirection = getMovementDirection("down", orientation);
if (movementDirection === "down") {
return (0, import_i18n73.sprintf)(
// translators: 1: Type of block (i.e. Text, Image etc), 2: Position of selected block, 3: New position
(0, import_i18n73.__)(
"Move %1$s block from position %2$d down to position %3$d"
),
type,
position,
position + 1
);
}
if (movementDirection === "left") {
return (0, import_i18n73.sprintf)(
// translators: 1: Type of block (i.e. Text, Image etc), 2: Position of selected block, 3: New position
(0, import_i18n73.__)(
"Move %1$s block from position %2$d left to position %3$d"
),
type,
position,
position + 1
);
}
if (movementDirection === "right") {
return (0, import_i18n73.sprintf)(
// translators: 1: Type of block (i.e. Text, Image etc), 2: Position of selected block, 3: New position
(0, import_i18n73.__)(
"Move %1$s block from position %2$d right to position %3$d"
),
type,
position,
position + 1
);
}
}
if (dir > 0 && isLast) {
const movementDirection = getMovementDirection("down", orientation);
if (movementDirection === "down") {
return (0, import_i18n73.sprintf)(
// translators: 1: Type of block (i.e. Text, Image etc)
(0, import_i18n73.__)(
"Block %1$s is at the end of the content and can\u2019t be moved down"
),
type
);
}
if (movementDirection === "left") {
return (0, import_i18n73.sprintf)(
// translators: 1: Type of block (i.e. Text, Image etc)
(0, import_i18n73.__)(
"Block %1$s is at the end of the content and can\u2019t be moved left"
),
type
);
}
if (movementDirection === "right") {
return (0, import_i18n73.sprintf)(
// translators: 1: Type of block (i.e. Text, Image etc)
(0, import_i18n73.__)(
"Block %1$s is at the end of the content and can\u2019t be moved right"
),
type
);
}
}
if (dir < 0 && !isFirst) {
const movementDirection = getMovementDirection("up", orientation);
if (movementDirection === "up") {
return (0, import_i18n73.sprintf)(
// translators: 1: Type of block (i.e. Text, Image etc), 2: Position of selected block, 3: New position
(0, import_i18n73.__)("Move %1$s block from position %2$d up to position %3$d"),
type,
position,
position - 1
);
}
if (movementDirection === "left") {
return (0, import_i18n73.sprintf)(
// translators: 1: Type of block (i.e. Text, Image etc), 2: Position of selected block, 3: New position
(0, import_i18n73.__)(
"Move %1$s block from position %2$d left to position %3$d"
),
type,
position,
position - 1
);
}
if (movementDirection === "right") {
return (0, import_i18n73.sprintf)(
// translators: 1: Type of block (i.e. Text, Image etc), 2: Position of selected block, 3: New position
(0, import_i18n73.__)(
"Move %1$s block from position %2$d right to position %3$d"
),
type,
position,
position - 1
);
}
}
if (dir < 0 && isFirst) {
const movementDirection = getMovementDirection("up", orientation);
if (movementDirection === "up") {
return (0, import_i18n73.sprintf)(
// translators: 1: Type of block (i.e. Text, Image etc)
(0, import_i18n73.__)(
"Block %1$s is at the beginning of the content and can\u2019t be moved up"
),
type
);
}
if (movementDirection === "left") {
return (0, import_i18n73.sprintf)(
// translators: 1: Type of block (i.e. Text, Image etc)
(0, import_i18n73.__)(
"Block %1$s is at the beginning of the content and can\u2019t be moved left"
),
type
);
}
if (movementDirection === "right") {
return (0, import_i18n73.sprintf)(
// translators: 1: Type of block (i.e. Text, Image etc)
(0, import_i18n73.__)(
"Block %1$s is at the beginning of the content and can\u2019t be moved right"
),
type
);
}
}
}
function getMultiBlockMoverDescription(selectedCount, firstIndex, isFirst, isLast, dir, orientation) {
const position = firstIndex + 1;
if (isFirst && isLast) {
return (0, import_i18n73.__)("All blocks are selected, and cannot be moved");
}
if (dir > 0 && !isLast) {
const movementDirection = getMovementDirection("down", orientation);
if (movementDirection === "down") {
return (0, import_i18n73.sprintf)(
// translators: 1: Number of selected blocks, 2: Position of selected blocks
(0, import_i18n73.__)("Move %1$d blocks from position %2$d down by one place"),
selectedCount,
position
);
}
if (movementDirection === "left") {
return (0, import_i18n73.sprintf)(
// translators: 1: Number of selected blocks, 2: Position of selected blocks
(0, import_i18n73.__)("Move %1$d blocks from position %2$d left by one place"),
selectedCount,
position
);
}
if (movementDirection === "right") {
return (0, import_i18n73.sprintf)(
// translators: 1: Number of selected blocks, 2: Position of selected blocks
(0, import_i18n73.__)("Move %1$d blocks from position %2$d right by one place"),
selectedCount,
position
);
}
}
if (dir > 0 && isLast) {
const movementDirection = getMovementDirection("down", orientation);
if (movementDirection === "down") {
return (0, import_i18n73.__)(
"Blocks cannot be moved down as they are already at the bottom"
);
}
if (movementDirection === "left") {
return (0, import_i18n73.__)(
"Blocks cannot be moved left as they are already are at the leftmost position"
);
}
if (movementDirection === "right") {
return (0, import_i18n73.__)(
"Blocks cannot be moved right as they are already are at the rightmost position"
);
}
}
if (dir < 0 && !isFirst) {
const movementDirection = getMovementDirection("up", orientation);
if (movementDirection === "up") {
return (0, import_i18n73.sprintf)(
// translators: 1: Number of selected blocks, 2: Position of selected blocks
(0, import_i18n73.__)("Move %1$d blocks from position %2$d up by one place"),
selectedCount,
position
);
}
if (movementDirection === "left") {
return (0, import_i18n73.sprintf)(
// translators: 1: Number of selected blocks, 2: Position of selected blocks
(0, import_i18n73.__)("Move %1$d blocks from position %2$d left by one place"),
selectedCount,
position
);
}
if (movementDirection === "right") {
return (0, import_i18n73.sprintf)(
// translators: 1: Number of selected blocks, 2: Position of selected blocks
(0, import_i18n73.__)("Move %1$d blocks from position %2$d right by one place"),
selectedCount,
position
);
}
}
if (dir < 0 && isFirst) {
const movementDirection = getMovementDirection("up", orientation);
if (movementDirection === "up") {
return (0, import_i18n73.__)(
"Blocks cannot be moved up as they are already at the top"
);
}
if (movementDirection === "left") {
return (0, import_i18n73.__)(
"Blocks cannot be moved left as they are already are at the leftmost position"
);
}
if (movementDirection === "right") {
return (0, import_i18n73.__)(
"Blocks cannot be moved right as they are already are at the rightmost position"
);
}
}
}
// packages/block-editor/build-module/components/block-mover/button.mjs
var import_jsx_runtime279 = __toESM(require_jsx_runtime(), 1);
var getArrowIcon = (direction, orientation) => {
if (direction === "up") {
if (orientation === "horizontal") {
return (0, import_i18n74.isRTL)() ? chevron_right_default : chevron_left_default;
}
return chevron_up_default;
} else if (direction === "down") {
if (orientation === "horizontal") {
return (0, import_i18n74.isRTL)() ? chevron_left_default : chevron_right_default;
}
return chevron_down_default;
}
return null;
};
var getMovementDirectionLabel = (moveDirection, orientation) => {
if (moveDirection === "up") {
if (orientation === "horizontal") {
return (0, import_i18n74.isRTL)() ? (0, import_i18n74.__)("Move right") : (0, import_i18n74.__)("Move left");
}
return (0, import_i18n74.__)("Move up");
} else if (moveDirection === "down") {
if (orientation === "horizontal") {
return (0, import_i18n74.isRTL)() ? (0, import_i18n74.__)("Move left") : (0, import_i18n74.__)("Move right");
}
return (0, import_i18n74.__)("Move down");
}
return null;
};
var BlockMoverButton = (0, import_element152.forwardRef)(
({ clientIds, direction, orientation: moverOrientation, ...props }, ref) => {
const instanceId = (0, import_compose62.useInstanceId)(BlockMoverButton);
const normalizedClientIds = (0, import_element152.useMemo)(
() => Array.isArray(clientIds) ? clientIds : [clientIds],
[clientIds]
);
const blocksCount = normalizedClientIds.length;
const isMobileViewport = (0, import_compose62.useViewportMatch)("small", "<");
const {
blockType,
isDisabled,
rootClientId,
isFirst,
isLast,
firstIndex,
orientation = "vertical"
} = (0, import_data88.useSelect)(
(select3) => {
const {
getBlockIndex: getBlockIndex2,
getBlockRootClientId: getBlockRootClientId2,
getBlockOrder: getBlockOrder2,
getBlock: getBlock2,
getBlockListSettings: getBlockListSettings2
} = select3(store);
const firstClientId = normalizedClientIds[0];
const blockRootClientId = getBlockRootClientId2(firstClientId);
const firstBlockIndex = getBlockIndex2(firstClientId);
const lastBlockIndex = getBlockIndex2(
normalizedClientIds[normalizedClientIds.length - 1]
);
const blockOrder = getBlockOrder2(blockRootClientId);
const block = getBlock2(firstClientId);
const isFirstBlock = firstBlockIndex === 0;
const isLastBlock = lastBlockIndex === blockOrder.length - 1;
const { orientation: blockListOrientation } = getBlockListSettings2(blockRootClientId) || {};
return {
blockType: block ? (0, import_blocks51.getBlockType)(block.name) : null,
isDisabled: direction === "up" ? isFirstBlock : isLastBlock,
rootClientId: blockRootClientId,
firstIndex: firstBlockIndex,
isFirst: isFirstBlock,
isLast: isLastBlock,
orientation: moverOrientation || blockListOrientation
};
},
[direction, moverOrientation, normalizedClientIds]
);
const { moveBlocksDown: moveBlocksDown2, moveBlocksUp: moveBlocksUp2 } = (0, import_data88.useDispatch)(store);
const moverFunction = direction === "up" ? moveBlocksUp2 : moveBlocksDown2;
const onClick = (event) => {
moverFunction(clientIds, rootClientId);
if (props.onClick) {
props.onClick(event);
}
};
const descriptionId = `block-editor-block-mover-button__description-${instanceId}`;
return /* @__PURE__ */ (0, import_jsx_runtime279.jsxs)(import_jsx_runtime279.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime279.jsx)(
import_components75.Button,
{
__next40pxDefaultSize: true,
ref,
className: clsx_default(
"block-editor-block-mover-button",
`is-${direction}-button`
),
icon: getArrowIcon(direction, orientation),
label: getMovementDirectionLabel(
direction,
orientation
),
tooltipPosition: !isMobileViewport && direction === "down" && orientation === "vertical" ? "bottom" : "top",
"aria-describedby": descriptionId,
...props,
onClick: isDisabled ? null : onClick,
disabled: isDisabled,
accessibleWhenDisabled: true,
shortcut: direction === "up" ? import_keycodes10.displayShortcut.secondary("t") : import_keycodes10.displayShortcut.secondary("y")
}
),
/* @__PURE__ */ (0, import_jsx_runtime279.jsx)(VisuallyHidden, { id: descriptionId, children: getBlockMoverDescription(
blocksCount,
blockType && blockType.title,
firstIndex,
isFirst,
isLast,
direction === "up" ? -1 : 1,
orientation
) })
] });
}
);
var BlockMoverUpButton = (0, import_element152.forwardRef)((props, ref) => {
return /* @__PURE__ */ (0, import_jsx_runtime279.jsx)(BlockMoverButton, { direction: "up", ref, ...props });
});
var BlockMoverDownButton = (0, import_element152.forwardRef)((props, ref) => {
return /* @__PURE__ */ (0, import_jsx_runtime279.jsx)(BlockMoverButton, { direction: "down", ref, ...props });
});
// packages/block-editor/build-module/components/block-mover/index.mjs
var import_jsx_runtime280 = __toESM(require_jsx_runtime(), 1);
function BlockMover({ clientIds, hideDragHandle }) {
const {
canMove,
rootClientId,
isFirst,
isLast,
orientation,
isManualGrid
} = (0, import_data89.useSelect)(
(select3) => {
const {
getBlockIndex: getBlockIndex2,
getBlockListSettings: getBlockListSettings2,
canMoveBlocks: canMoveBlocks2,
getBlockOrder: getBlockOrder2,
getBlockRootClientId: getBlockRootClientId2,
getBlockAttributes: getBlockAttributes3
} = select3(store);
const normalizedClientIds = Array.isArray(clientIds) ? clientIds : [clientIds];
const firstClientId = normalizedClientIds[0];
const _rootClientId = getBlockRootClientId2(firstClientId);
const firstIndex = getBlockIndex2(firstClientId);
const lastIndex = getBlockIndex2(
normalizedClientIds[normalizedClientIds.length - 1]
);
const blockOrder = getBlockOrder2(_rootClientId);
const { layout = {} } = getBlockAttributes3(_rootClientId) ?? {};
return {
canMove: canMoveBlocks2(clientIds),
rootClientId: _rootClientId,
isFirst: firstIndex === 0,
isLast: lastIndex === blockOrder.length - 1,
orientation: getBlockListSettings2(_rootClientId)?.orientation,
isManualGrid: layout.type === "grid" && layout.isManualPlacement && window.__experimentalEnableGridInteractivity
};
},
[clientIds]
);
if (!canMove || isFirst && isLast && !rootClientId || hideDragHandle && isManualGrid) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime280.jsxs)(
import_components76.ToolbarGroup,
{
className: clsx_default("block-editor-block-mover", {
"is-horizontal": orientation === "horizontal"
}),
children: [
!hideDragHandle && /* @__PURE__ */ (0, import_jsx_runtime280.jsx)(block_draggable_default, { clientIds, fadeWhenDisabled: true, children: (draggableProps) => /* @__PURE__ */ (0, import_jsx_runtime280.jsx)(
import_components76.Button,
{
__next40pxDefaultSize: true,
icon: drag_handle_default,
className: "block-editor-block-mover__drag-handle",
label: (0, import_i18n75.__)("Drag"),
tabIndex: "-1",
...draggableProps
}
) }),
!isManualGrid && /* @__PURE__ */ (0, import_jsx_runtime280.jsxs)("div", { className: "block-editor-block-mover__move-button-container", children: [
/* @__PURE__ */ (0, import_jsx_runtime280.jsx)(import_components76.ToolbarItem, { children: (itemProps) => /* @__PURE__ */ (0, import_jsx_runtime280.jsx)(
BlockMoverUpButton,
{
clientIds,
...itemProps
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime280.jsx)(import_components76.ToolbarItem, { children: (itemProps) => /* @__PURE__ */ (0, import_jsx_runtime280.jsx)(
BlockMoverDownButton,
{
clientIds,
...itemProps
}
) })
] })
]
}
);
}
var block_mover_default = BlockMover;
// packages/block-editor/build-module/components/block-parent-selector/index.mjs
var import_components77 = __toESM(require_components(), 1);
var import_data91 = __toESM(require_data(), 1);
var import_i18n76 = __toESM(require_i18n(), 1);
var import_element154 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/block-toolbar/utils.mjs
var import_data90 = __toESM(require_data(), 1);
var import_element153 = __toESM(require_element(), 1);
var { clearTimeout: clearTimeout2, setTimeout: setTimeout2 } = window;
var DEBOUNCE_TIMEOUT = 200;
function useDebouncedShowGestures({
ref,
isFocused,
highlightParent,
debounceTimeout = DEBOUNCE_TIMEOUT
}) {
const { getSelectedBlockClientId: getSelectedBlockClientId2, getBlockRootClientId: getBlockRootClientId2 } = (0, import_data90.useSelect)(store);
const { toggleBlockHighlight: toggleBlockHighlight2 } = (0, import_data90.useDispatch)(store);
const timeoutRef = (0, import_element153.useRef)();
const isDistractionFree = (0, import_data90.useSelect)(
(select3) => select3(store).getSettings().isDistractionFree,
[]
);
const handleOnChange = (nextIsFocused) => {
if (nextIsFocused && isDistractionFree) {
return;
}
const selectedBlockClientId = getSelectedBlockClientId2();
const clientId = highlightParent ? getBlockRootClientId2(selectedBlockClientId) : selectedBlockClientId;
toggleBlockHighlight2(clientId, nextIsFocused);
};
const getIsHovered = () => {
return ref?.current && ref.current.matches(":hover");
};
const shouldHideGestures = () => {
const isHovered = getIsHovered();
return !isFocused && !isHovered;
};
const clearTimeoutRef = () => {
const timeout = timeoutRef.current;
if (timeout && clearTimeout2) {
clearTimeout2(timeout);
}
};
const debouncedShowGestures = (event) => {
if (event) {
event.stopPropagation();
}
clearTimeoutRef();
handleOnChange(true);
};
const debouncedHideGestures = (event) => {
if (event) {
event.stopPropagation();
}
clearTimeoutRef();
timeoutRef.current = setTimeout2(() => {
if (shouldHideGestures()) {
handleOnChange(false);
}
}, debounceTimeout);
};
(0, import_element153.useEffect)(
() => () => {
handleOnChange(false);
clearTimeoutRef();
},
[]
);
return {
debouncedShowGestures,
debouncedHideGestures
};
}
function useShowHoveredOrFocusedGestures({
ref,
highlightParent = false,
debounceTimeout = DEBOUNCE_TIMEOUT
}) {
const [isFocused, setIsFocused] = (0, import_element153.useState)(false);
const { debouncedShowGestures, debouncedHideGestures } = useDebouncedShowGestures({
ref,
debounceTimeout,
isFocused,
highlightParent
});
const registerRef = (0, import_element153.useRef)(false);
const isFocusedWithin = () => {
return ref?.current && ref.current.contains(ref.current.ownerDocument.activeElement);
};
(0, import_element153.useEffect)(() => {
const node = ref.current;
const handleOnFocus = () => {
if (isFocusedWithin()) {
setIsFocused(true);
debouncedShowGestures();
}
};
const handleOnBlur = () => {
if (!isFocusedWithin()) {
setIsFocused(false);
debouncedHideGestures();
}
};
if (node && !registerRef.current) {
node.addEventListener("focus", handleOnFocus, true);
node.addEventListener("blur", handleOnBlur, true);
registerRef.current = true;
}
return () => {
if (node) {
node.removeEventListener("focus", handleOnFocus);
node.removeEventListener("blur", handleOnBlur);
}
};
}, [
ref,
registerRef,
setIsFocused,
debouncedShowGestures,
debouncedHideGestures
]);
return {
onMouseMove: debouncedShowGestures,
onMouseLeave: debouncedHideGestures
};
}
// packages/block-editor/build-module/components/block-parent-selector/index.mjs
var import_jsx_runtime281 = __toESM(require_jsx_runtime(), 1);
function BlockParentSelector() {
const { selectBlock: selectBlock2 } = (0, import_data91.useDispatch)(store);
const { parentClientId } = (0, import_data91.useSelect)((select3) => {
const {
getBlockParents: getBlockParents2,
getSelectedBlockClientId: getSelectedBlockClientId2,
getParentSectionBlock: getParentSectionBlock2
} = unlock(select3(store));
const selectedBlockClientId = getSelectedBlockClientId2();
const parentSection = getParentSectionBlock2(selectedBlockClientId);
const parents = getBlockParents2(selectedBlockClientId);
const _parentClientId = parentSection ?? parents[parents.length - 1];
return {
parentClientId: _parentClientId
};
}, []);
const blockInformation = useBlockDisplayInformation(parentClientId);
const nodeRef = (0, import_element154.useRef)();
const showHoveredOrFocusedGestures = useShowHoveredOrFocusedGestures({
ref: nodeRef,
highlightParent: true
});
return /* @__PURE__ */ (0, import_jsx_runtime281.jsx)(
"div",
{
className: "block-editor-block-parent-selector",
ref: nodeRef,
...showHoveredOrFocusedGestures,
children: /* @__PURE__ */ (0, import_jsx_runtime281.jsx)(
import_components77.ToolbarButton,
{
className: "block-editor-block-parent-selector__button",
onClick: () => selectBlock2(parentClientId),
label: (0, import_i18n76.sprintf)(
/* translators: %s: Name of the block's parent. */
(0, import_i18n76.__)("Select parent block: %s"),
blockInformation?.title
),
showTooltip: true,
icon: /* @__PURE__ */ (0, import_jsx_runtime281.jsx)(block_icon_default, { icon: blockInformation?.icon })
}
)
},
parentClientId
);
}
// packages/block-editor/build-module/components/block-controls/fill.mjs
var import_components79 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/block-controls/groups.mjs
var import_components78 = __toESM(require_components(), 1);
var BlockControlsDefault = (0, import_components78.createSlotFill)("BlockControls");
var BlockControlsBlock = (0, import_components78.createSlotFill)("BlockControlsBlock");
var BlockControlsInline = (0, import_components78.createSlotFill)("BlockFormatControls");
var BlockControlsOther = (0, import_components78.createSlotFill)("BlockControlsOther");
var BlockControlsParent = (0, import_components78.createSlotFill)("BlockControlsParent");
var BlockControlsStyleState = (0, import_components78.createSlotFill)("BlockControlsStyleState");
var groups2 = {
default: BlockControlsDefault,
block: BlockControlsBlock,
inline: BlockControlsInline,
other: BlockControlsOther,
parent: BlockControlsParent,
"style-state": BlockControlsStyleState
};
var groups_default2 = groups2;
// packages/block-editor/build-module/components/block-controls/hook.mjs
function useBlockControlsFill(group, shareWithChildBlocks) {
const context = useBlockEditContext();
if (context[mayDisplayControlsKey]) {
return groups_default2[group]?.Fill;
}
if (context[mayDisplayParentControlsKey] && shareWithChildBlocks) {
return groups_default2.parent.Fill;
}
return null;
}
// packages/block-editor/build-module/components/block-controls/fill.mjs
var import_jsx_runtime282 = __toESM(require_jsx_runtime(), 1);
function BlockControlsFill({
group = "default",
controls,
children,
__experimentalShareWithChildBlocks = false
}) {
const Fill5 = useBlockControlsFill(
group,
__experimentalShareWithChildBlocks
);
if (!Fill5) {
return null;
}
const innerMarkup = /* @__PURE__ */ (0, import_jsx_runtime282.jsxs)(import_jsx_runtime282.Fragment, { children: [
group === "default" && /* @__PURE__ */ (0, import_jsx_runtime282.jsx)(import_components79.ToolbarGroup, { controls }),
children
] });
return /* @__PURE__ */ (0, import_jsx_runtime282.jsx)(import_components79.__experimentalStyleProvider, { document, children: /* @__PURE__ */ (0, import_jsx_runtime282.jsx)(Fill5, { children: (fillProps) => {
const { forwardedContext = [] } = fillProps;
return forwardedContext.reduce(
(inner, [Provider3, props]) => /* @__PURE__ */ (0, import_jsx_runtime282.jsx)(Provider3, { ...props, children: inner }),
innerMarkup
);
} }) });
}
// packages/block-editor/build-module/components/block-controls/slot.mjs
var import_element155 = __toESM(require_element(), 1);
var import_components80 = __toESM(require_components(), 1);
var import_warning7 = __toESM(require_warning(), 1);
var import_jsx_runtime283 = __toESM(require_jsx_runtime(), 1);
var { ComponentsContext } = unlock(import_components80.privateApis);
function BlockControlsSlot({ group = "default", ...props }) {
const toolbarState = (0, import_element155.useContext)(import_components80.__experimentalToolbarContext);
const contextState = (0, import_element155.useContext)(ComponentsContext);
const fillProps = (0, import_element155.useMemo)(
() => ({
forwardedContext: [
[import_components80.__experimentalToolbarContext.Provider, { value: toolbarState }],
[ComponentsContext.Provider, { value: contextState }]
]
}),
[toolbarState, contextState]
);
const slotFill = groups_default2[group];
const fills = (0, import_components80.__experimentalUseSlotFills)(slotFill.name);
if (!slotFill) {
(0, import_warning7.default)(`Unknown BlockControls group "${group}" provided.`);
return null;
}
if (!fills?.length) {
return null;
}
const { Slot: Slot10 } = slotFill;
const slot = /* @__PURE__ */ (0, import_jsx_runtime283.jsx)(Slot10, { ...props, bubblesVirtually: true, fillProps });
if (group === "default") {
return slot;
}
return /* @__PURE__ */ (0, import_jsx_runtime283.jsx)(import_components80.ToolbarGroup, { children: slot });
}
// packages/block-editor/build-module/components/block-controls/index.mjs
var import_jsx_runtime284 = __toESM(require_jsx_runtime(), 1);
var BlockControls = BlockControlsFill;
BlockControls.Slot = BlockControlsSlot;
var BlockFormatControls = (props) => {
return /* @__PURE__ */ (0, import_jsx_runtime284.jsx)(BlockControlsFill, { group: "inline", ...props });
};
BlockFormatControls.Slot = function Slot4(props) {
return /* @__PURE__ */ (0, import_jsx_runtime284.jsx)(BlockControlsSlot, { group: "inline", ...props });
};
var block_controls_default = BlockControls;
// packages/block-editor/build-module/components/block-toolbar/block-toolbar-last-item.mjs
var import_components81 = __toESM(require_components(), 1);
var { Fill: __unstableBlockToolbarLastItem, Slot: Slot5 } = (0, import_components81.createSlotFill)(
"__unstableBlockToolbarLastItem"
);
__unstableBlockToolbarLastItem.Slot = Slot5;
var block_toolbar_last_item_default = __unstableBlockToolbarLastItem;
// packages/block-editor/build-module/components/block-settings-menu/index.mjs
var import_components97 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/block-settings-menu/block-settings-dropdown.mjs
var import_blocks63 = __toESM(require_blocks(), 1);
var import_components95 = __toESM(require_components(), 1);
var import_data105 = __toESM(require_data(), 1);
var import_element163 = __toESM(require_element(), 1);
var import_i18n88 = __toESM(require_i18n(), 1);
var import_keyboard_shortcuts7 = __toESM(require_keyboard_shortcuts(), 1);
var import_compose64 = __toESM(require_compose(), 1);
// packages/block-editor/build-module/components/block-actions/index.mjs
var import_data93 = __toESM(require_data(), 1);
var import_blocks54 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/components/use-paste-styles/index.mjs
var import_element156 = __toESM(require_element(), 1);
var import_blocks53 = __toESM(require_blocks(), 1);
var import_data92 = __toESM(require_data(), 1);
var import_notices8 = __toESM(require_notices(), 1);
var import_i18n77 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/hooks/supports.mjs
var import_blocks52 = __toESM(require_blocks(), 1);
var ALIGN_SUPPORT_KEY = "align";
var BORDER_SUPPORT_KEY = "__experimentalBorder";
var COLOR_SUPPORT_KEY = "color";
var CUSTOM_CLASS_NAME_SUPPORT_KEY = "customClassName";
var FONT_FAMILY_SUPPORT_KEY = "typography.__experimentalFontFamily";
var FONT_SIZE_SUPPORT_KEY = "typography.fontSize";
var LINE_HEIGHT_SUPPORT_KEY = "typography.lineHeight";
var FONT_STYLE_SUPPORT_KEY = "typography.__experimentalFontStyle";
var FONT_WEIGHT_SUPPORT_KEY = "typography.__experimentalFontWeight";
var TEXT_ALIGN_SUPPORT_KEY = "typography.textAlign";
var TEXT_COLUMNS_SUPPORT_KEY = "typography.textColumns";
var TEXT_DECORATION_SUPPORT_KEY = "typography.__experimentalTextDecoration";
var WRITING_MODE_SUPPORT_KEY = "typography.__experimentalWritingMode";
var TEXT_TRANSFORM_SUPPORT_KEY = "typography.__experimentalTextTransform";
var LETTER_SPACING_SUPPORT_KEY = "typography.__experimentalLetterSpacing";
var LAYOUT_SUPPORT_KEY = "layout";
var TYPOGRAPHY_SUPPORT_KEYS = [
LINE_HEIGHT_SUPPORT_KEY,
FONT_SIZE_SUPPORT_KEY,
FONT_STYLE_SUPPORT_KEY,
FONT_WEIGHT_SUPPORT_KEY,
FONT_FAMILY_SUPPORT_KEY,
TEXT_ALIGN_SUPPORT_KEY,
TEXT_COLUMNS_SUPPORT_KEY,
TEXT_DECORATION_SUPPORT_KEY,
TEXT_TRANSFORM_SUPPORT_KEY,
WRITING_MODE_SUPPORT_KEY,
LETTER_SPACING_SUPPORT_KEY
];
var EFFECTS_SUPPORT_KEYS = ["shadow"];
var SPACING_SUPPORT_KEY = "spacing";
var styleSupportKeys = [
...EFFECTS_SUPPORT_KEYS,
...TYPOGRAPHY_SUPPORT_KEYS,
BORDER_SUPPORT_KEY,
COLOR_SUPPORT_KEY,
SPACING_SUPPORT_KEY
];
var hasAlignSupport = (nameOrType) => (0, import_blocks52.hasBlockSupport)(nameOrType, ALIGN_SUPPORT_KEY);
function hasBorderSupport(nameOrType, feature = "any") {
const support = (0, import_blocks52.getBlockSupport)(nameOrType, BORDER_SUPPORT_KEY);
if (support === true) {
return true;
}
if (feature === "any") {
return !!(support?.color || support?.radius || support?.width || support?.style);
}
return !!support?.[feature];
}
var hasGradientSupport = (nameOrType) => {
const colorSupport = (0, import_blocks52.getBlockSupport)(nameOrType, COLOR_SUPPORT_KEY);
return colorSupport !== null && typeof colorSupport === "object" && !!colorSupport.gradients;
};
var hasBackgroundColorSupport = (nameOrType) => {
const colorSupport = (0, import_blocks52.getBlockSupport)(nameOrType, COLOR_SUPPORT_KEY);
return colorSupport && colorSupport.background !== false;
};
var hasTextAlignSupport = (nameOrType) => (0, import_blocks52.hasBlockSupport)(nameOrType, TEXT_ALIGN_SUPPORT_KEY);
var hasTextColorSupport = (nameOrType) => {
const colorSupport = (0, import_blocks52.getBlockSupport)(nameOrType, COLOR_SUPPORT_KEY);
return colorSupport && colorSupport.text !== false;
};
var hasCustomClassNameSupport = (nameOrType) => (0, import_blocks52.hasBlockSupport)(nameOrType, CUSTOM_CLASS_NAME_SUPPORT_KEY, true);
var hasFontFamilySupport = (nameOrType) => (0, import_blocks52.hasBlockSupport)(nameOrType, FONT_FAMILY_SUPPORT_KEY);
var hasFontSizeSupport = (nameOrType) => (0, import_blocks52.hasBlockSupport)(nameOrType, FONT_SIZE_SUPPORT_KEY);
var hasLayoutSupport = (nameOrType) => (0, import_blocks52.hasBlockSupport)(nameOrType, LAYOUT_SUPPORT_KEY);
var hasStyleSupport = (nameOrType) => styleSupportKeys.some((key) => (0, import_blocks52.hasBlockSupport)(nameOrType, key));
// packages/block-editor/build-module/components/use-paste-styles/index.mjs
function hasSerializedBlocks(text) {
try {
const blocks2 = (0, import_blocks53.parse)(text, {
__unstableSkipMigrationLogs: true,
__unstableSkipAutop: true
});
if (blocks2.length === 1 && blocks2[0].name === "core/freeform") {
return false;
}
return true;
} catch {
return false;
}
}
var STYLE_ATTRIBUTES = {
align: hasAlignSupport,
borderColor: (nameOrType) => hasBorderSupport(nameOrType, "color"),
backgroundColor: hasBackgroundColorSupport,
textAlign: hasTextAlignSupport,
textColor: hasTextColorSupport,
gradient: hasGradientSupport,
className: hasCustomClassNameSupport,
fontFamily: hasFontFamilySupport,
fontSize: hasFontSizeSupport,
layout: hasLayoutSupport,
style: hasStyleSupport
};
function getStyleAttributes(sourceBlock, targetBlock) {
return Object.entries(STYLE_ATTRIBUTES).reduce(
(attributes, [attributeKey, hasSupport]) => {
if (hasSupport(sourceBlock.name) && hasSupport(targetBlock.name)) {
attributes[attributeKey] = sourceBlock.attributes[attributeKey];
}
return attributes;
},
{}
);
}
function recursivelyUpdateBlockAttributes(targetBlocks, sourceBlocks, updateBlockAttributes2) {
for (let index2 = 0; index2 < Math.min(sourceBlocks.length, targetBlocks.length); index2 += 1) {
updateBlockAttributes2(
targetBlocks[index2].clientId,
getStyleAttributes(sourceBlocks[index2], targetBlocks[index2])
);
recursivelyUpdateBlockAttributes(
targetBlocks[index2].innerBlocks,
sourceBlocks[index2].innerBlocks,
updateBlockAttributes2
);
}
}
function usePasteStyles() {
const registry = (0, import_data92.useRegistry)();
const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data92.useDispatch)(store);
const { createSuccessNotice, createWarningNotice, createErrorNotice } = (0, import_data92.useDispatch)(import_notices8.store);
return (0, import_element156.useCallback)(
async (targetBlocks) => {
let html = "";
try {
if (!window.navigator.clipboard) {
createErrorNotice(
(0, import_i18n77.__)(
"Unable to paste styles. This feature is only available on secure (https) sites in supporting browsers."
),
{ type: "snackbar" }
);
return;
}
html = await window.navigator.clipboard.readText();
} catch {
createErrorNotice(
(0, import_i18n77.__)(
"Unable to paste styles. Please allow browser clipboard permissions before continuing."
),
{
type: "snackbar"
}
);
return;
}
if (!html || !hasSerializedBlocks(html)) {
createWarningNotice(
(0, import_i18n77.__)(
"Unable to paste styles. Block styles couldn't be found within the copied content."
),
{
type: "snackbar"
}
);
return;
}
const copiedBlocks = (0, import_blocks53.parse)(html);
if (copiedBlocks.length === 1) {
registry.batch(() => {
recursivelyUpdateBlockAttributes(
targetBlocks,
targetBlocks.map(() => copiedBlocks[0]),
updateBlockAttributes2
);
});
} else {
registry.batch(() => {
recursivelyUpdateBlockAttributes(
targetBlocks,
copiedBlocks,
updateBlockAttributes2
);
});
}
if (targetBlocks.length === 1) {
const title = (0, import_blocks53.getBlockType)(targetBlocks[0].name)?.title;
createSuccessNotice(
(0, import_i18n77.sprintf)(
// Translators: %s: Name of the block being pasted, e.g. "Paragraph".
(0, import_i18n77.__)("Pasted styles to %s."),
title
),
{ type: "snackbar" }
);
} else {
createSuccessNotice(
(0, import_i18n77.sprintf)(
// Translators: %d: The number of the blocks.
(0, import_i18n77.__)("Pasted styles to %d blocks."),
targetBlocks.length
),
{ type: "snackbar" }
);
}
},
[
registry.batch,
updateBlockAttributes2,
createSuccessNotice,
createWarningNotice,
createErrorNotice
]
);
}
// packages/block-editor/build-module/components/block-actions/index.mjs
function BlockActions({
clientIds,
children,
__experimentalUpdateSelection: updateSelection
}) {
const { getDefaultBlockName: getDefaultBlockName8, getGroupingBlockName } = (0, import_data93.useSelect)(import_blocks54.store);
const selected = (0, import_data93.useSelect)(
(select3) => {
const {
canInsertBlockType: canInsertBlockType2,
getBlockRootClientId: getBlockRootClientId2,
getBlocksByClientId: getBlocksByClientId22,
getDirectInsertBlock: getDirectInsertBlock2,
canRemoveBlocks: canRemoveBlocks2
} = select3(store);
const blocks2 = getBlocksByClientId22(clientIds);
const rootClientId = getBlockRootClientId2(clientIds[0]);
const canInsertDefaultBlock = canInsertBlockType2(
getDefaultBlockName8(),
rootClientId
);
const directInsertBlock = rootClientId ? getDirectInsertBlock2(rootClientId) : null;
return {
canRemove: canRemoveBlocks2(clientIds),
canInsertBlock: blocks2.every((block) => {
return (canInsertDefaultBlock || !!directInsertBlock) && canInsertBlockType2(block.name, rootClientId);
}),
canCopyStyles: blocks2.every((block) => {
return !!block && ((0, import_blocks54.hasBlockSupport)(block.name, "color") || (0, import_blocks54.hasBlockSupport)(block.name, "typography"));
}),
canDuplicate: blocks2.every((block) => {
return !!block && (0, import_blocks54.hasBlockSupport)(block.name, "multiple", true) && canInsertBlockType2(block.name, rootClientId);
})
};
},
[clientIds, getDefaultBlockName8]
);
const { getBlocksByClientId: getBlocksByClientId2, getBlocks: getBlocks2 } = (0, import_data93.useSelect)(store);
const { canRemove, canInsertBlock, canCopyStyles, canDuplicate } = selected;
const {
removeBlocks: removeBlocks2,
replaceBlocks: replaceBlocks2,
duplicateBlocks: duplicateBlocks2,
insertAfterBlock: insertAfterBlock2,
insertBeforeBlock: insertBeforeBlock2,
flashBlock: flashBlock2
} = (0, import_data93.useDispatch)(store);
const pasteStyles = usePasteStyles();
return children({
canCopyStyles,
canDuplicate,
canInsertBlock,
canRemove,
onDuplicate() {
return duplicateBlocks2(clientIds, updateSelection);
},
onRemove() {
return removeBlocks2(clientIds, updateSelection);
},
onInsertBefore() {
insertBeforeBlock2(clientIds[0]);
},
onInsertAfter() {
insertAfterBlock2(clientIds[clientIds.length - 1]);
},
onGroup() {
if (!clientIds.length) {
return;
}
const groupingBlockName = getGroupingBlockName();
const newBlocks = (0, import_blocks54.switchToBlockType)(
getBlocksByClientId2(clientIds),
groupingBlockName
);
if (!newBlocks) {
return;
}
replaceBlocks2(clientIds, newBlocks);
},
onUngroup() {
if (!clientIds.length) {
return;
}
const innerBlocks = getBlocks2(clientIds[0]);
if (!innerBlocks.length) {
return;
}
replaceBlocks2(clientIds, innerBlocks);
},
onCopy() {
if (clientIds.length === 1) {
flashBlock2(clientIds[0]);
}
},
async onPasteStyles() {
await pasteStyles(getBlocksByClientId2(clientIds));
}
});
}
// packages/block-editor/build-module/components/collab/note-icon-slot.mjs
var import_components82 = __toESM(require_components(), 1);
var NoteIconSlotFill = (0, import_components82.createSlotFill)(/* @__PURE__ */ Symbol("NoteIconSlotFill"));
var note_icon_slot_default = NoteIconSlotFill;
// packages/block-editor/build-module/components/block-settings-menu/block-html-convert-button.mjs
var import_i18n78 = __toESM(require_i18n(), 1);
var import_components83 = __toESM(require_components(), 1);
var import_blocks55 = __toESM(require_blocks(), 1);
var import_data94 = __toESM(require_data(), 1);
var import_jsx_runtime285 = __toESM(require_jsx_runtime(), 1);
function BlockHTMLConvertButton({ clientId }) {
const block = (0, import_data94.useSelect)(
(select3) => select3(store).getBlock(clientId),
[clientId]
);
const { replaceBlocks: replaceBlocks2 } = (0, import_data94.useDispatch)(store);
if (!block || block.name !== "core/html") {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime285.jsx)(
import_components83.MenuItem,
{
onClick: () => replaceBlocks2(
clientId,
(0, import_blocks55.rawHandler)({ HTML: (0, import_blocks55.getBlockContent)(block) })
),
children: (0, import_i18n78.__)("Convert to Blocks")
}
);
}
var block_html_convert_button_default = BlockHTMLConvertButton;
// packages/block-editor/build-module/components/block-settings-menu/block-settings-menu-first-item.mjs
var import_components84 = __toESM(require_components(), 1);
var { Fill: __unstableBlockSettingsMenuFirstItem, Slot: Slot6 } = (0, import_components84.createSlotFill)(
"__unstableBlockSettingsMenuFirstItem"
);
__unstableBlockSettingsMenuFirstItem.Slot = Slot6;
var block_settings_menu_first_item_default = __unstableBlockSettingsMenuFirstItem;
// packages/block-editor/build-module/components/block-settings-menu-controls/index.mjs
var import_components93 = __toESM(require_components(), 1);
var import_blocks62 = __toESM(require_blocks(), 1);
var import_data103 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/convert-to-group-buttons/index.mjs
var import_components86 = __toESM(require_components(), 1);
var import_i18n80 = __toESM(require_i18n(), 1);
var import_blocks58 = __toESM(require_blocks(), 1);
var import_data97 = __toESM(require_data(), 1);
var import_keycodes11 = __toESM(require_keycodes(), 1);
// packages/block-editor/build-module/components/convert-to-group-buttons/use-convert-to-group-button-props.mjs
var import_blocks56 = __toESM(require_blocks(), 1);
var import_data95 = __toESM(require_data(), 1);
function useConvertToGroupButtonProps(selectedClientIds) {
return (0, import_data95.useSelect)(
(select3) => {
const {
getBlocksByClientId: getBlocksByClientId2,
getSelectedBlockClientIds: getSelectedBlockClientIds2,
isUngroupable: isUngroupable2,
isGroupable: isGroupable2
} = select3(store);
const { getGroupingBlockName, getBlockType: getBlockType29 } = select3(import_blocks56.store);
const clientIds = selectedClientIds?.length ? selectedClientIds : getSelectedBlockClientIds2();
const blocksSelection = getBlocksByClientId2(clientIds);
const [firstSelectedBlock] = blocksSelection;
const _isUngroupable = clientIds.length === 1 && isUngroupable2(clientIds[0]);
return {
clientIds,
isGroupable: isGroupable2(clientIds),
isUngroupable: _isUngroupable,
blocksSelection,
groupingBlockName: getGroupingBlockName(),
onUngroup: _isUngroupable && getBlockType29(firstSelectedBlock.name)?.transforms?.ungroup
};
},
[selectedClientIds]
);
}
// packages/block-editor/build-module/components/convert-to-group-buttons/toolbar.mjs
var import_data96 = __toESM(require_data(), 1);
var import_blocks57 = __toESM(require_blocks(), 1);
var import_components85 = __toESM(require_components(), 1);
var import_i18n79 = __toESM(require_i18n(), 1);
var import_jsx_runtime286 = __toESM(require_jsx_runtime(), 1);
var layouts = {
group: { type: "constrained" },
row: { type: "flex", flexWrap: "nowrap" },
stack: { type: "flex", orientation: "vertical" },
grid: { type: "grid" }
};
function BlockGroupToolbar() {
const { blocksSelection, clientIds, groupingBlockName, isGroupable: isGroupable2 } = useConvertToGroupButtonProps();
const { replaceBlocks: replaceBlocks2 } = (0, import_data96.useDispatch)(store);
const { canRemove, variations } = (0, import_data96.useSelect)(
(select3) => {
const { canRemoveBlocks: canRemoveBlocks2 } = select3(store);
const { getBlockVariations: getBlockVariations2 } = select3(import_blocks57.store);
return {
canRemove: canRemoveBlocks2(clientIds),
variations: getBlockVariations2(
groupingBlockName,
"transform"
)
};
},
[clientIds, groupingBlockName]
);
const onConvertToGroup = (layout) => {
const newBlocks = (0, import_blocks57.switchToBlockType)(
blocksSelection,
groupingBlockName
);
if (typeof layout !== "string") {
layout = "group";
}
if (newBlocks && newBlocks.length > 0) {
newBlocks[0].attributes.layout = layouts[layout];
replaceBlocks2(clientIds, newBlocks);
}
};
const onConvertToRow = () => onConvertToGroup("row");
const onConvertToStack = () => onConvertToGroup("stack");
const onConvertToGrid = () => onConvertToGroup("grid");
if (!isGroupable2 || !canRemove) {
return null;
}
const canInsertRow = !!variations.find(
({ name }) => name === "group-row"
);
const canInsertStack = !!variations.find(
({ name }) => name === "group-stack"
);
const canInsertGrid = !!variations.find(
({ name }) => name === "group-grid"
);
return /* @__PURE__ */ (0, import_jsx_runtime286.jsxs)(import_components85.ToolbarGroup, { children: [
/* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
import_components85.ToolbarButton,
{
icon: group_default,
label: (0, import_i18n79._x)("Group", "action: convert blocks to group"),
onClick: onConvertToGroup
}
),
canInsertRow && /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
import_components85.ToolbarButton,
{
icon: row_default,
label: (0, import_i18n79._x)("Row", "action: convert blocks to row"),
onClick: onConvertToRow
}
),
canInsertStack && /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
import_components85.ToolbarButton,
{
icon: stack_default,
label: (0, import_i18n79._x)("Stack", "action: convert blocks to stack"),
onClick: onConvertToStack
}
),
canInsertGrid && /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
import_components85.ToolbarButton,
{
icon: grid_default,
label: (0, import_i18n79._x)("Grid", "action: convert blocks to grid"),
onClick: onConvertToGrid
}
)
] });
}
var toolbar_default = BlockGroupToolbar;
// packages/block-editor/build-module/components/convert-to-group-buttons/index.mjs
var import_jsx_runtime287 = __toESM(require_jsx_runtime(), 1);
function ConvertToGroupButton({
clientIds,
isGroupable: isGroupable2,
isUngroupable: isUngroupable2,
onUngroup,
blocksSelection,
groupingBlockName,
onClose = () => {
}
}) {
const { getSelectedBlockClientIds: getSelectedBlockClientIds2 } = (0, import_data97.useSelect)(store);
const { replaceBlocks: replaceBlocks2 } = (0, import_data97.useDispatch)(store);
const onConvertToGroup = () => {
const newBlocks = (0, import_blocks58.switchToBlockType)(
blocksSelection,
groupingBlockName
);
if (newBlocks) {
replaceBlocks2(clientIds, newBlocks);
}
};
const onConvertFromGroup = () => {
let innerBlocks = blocksSelection[0].innerBlocks;
if (!innerBlocks.length) {
return;
}
if (onUngroup) {
innerBlocks = onUngroup(
blocksSelection[0].attributes,
blocksSelection[0].innerBlocks
);
}
replaceBlocks2(clientIds, innerBlocks);
};
if (!isGroupable2 && !isUngroupable2) {
return null;
}
const selectedBlockClientIds = getSelectedBlockClientIds2();
return /* @__PURE__ */ (0, import_jsx_runtime287.jsxs)(import_jsx_runtime287.Fragment, { children: [
isGroupable2 && /* @__PURE__ */ (0, import_jsx_runtime287.jsx)(
import_components86.MenuItem,
{
shortcut: selectedBlockClientIds.length > 1 ? import_keycodes11.displayShortcut.primary("g") : void 0,
onClick: () => {
onConvertToGroup();
onClose();
},
children: (0, import_i18n80._x)("Group", "verb")
}
),
isUngroupable2 && /* @__PURE__ */ (0, import_jsx_runtime287.jsx)(
import_components86.MenuItem,
{
onClick: () => {
onConvertFromGroup();
onClose();
},
children: (0, import_i18n80._x)(
"Ungroup",
"Ungrouping blocks from within a grouping block back into individual blocks within the Editor"
)
}
)
] });
}
// packages/block-editor/build-module/components/block-lock/menu-item.mjs
var import_i18n82 = __toESM(require_i18n(), 1);
var import_element158 = __toESM(require_element(), 1);
var import_components88 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/block-lock/use-block-lock.mjs
var import_data98 = __toESM(require_data(), 1);
function useBlockLock(clientId) {
return (0, import_data98.useSelect)(
(select3) => {
const {
canLockBlockType: canLockBlockType2,
getBlockName: getBlockName2,
isEditLockedBlock: isEditLockedBlock2,
isMoveLockedBlock: isMoveLockedBlock2,
isRemoveLockedBlock: isRemoveLockedBlock2,
isLockedBlock: isLockedBlock2
} = unlock(select3(store));
return {
isEditLocked: isEditLockedBlock2(clientId),
isMoveLocked: isMoveLockedBlock2(clientId),
isRemoveLocked: isRemoveLockedBlock2(clientId),
canLock: canLockBlockType2(getBlockName2(clientId)),
isLocked: isLockedBlock2(clientId)
};
},
[clientId]
);
}
// packages/block-editor/build-module/components/block-lock/modal.mjs
var import_i18n81 = __toESM(require_i18n(), 1);
var import_element157 = __toESM(require_element(), 1);
var import_components87 = __toESM(require_components(), 1);
var import_data99 = __toESM(require_data(), 1);
var import_blocks59 = __toESM(require_blocks(), 1);
var import_jsx_runtime288 = __toESM(require_jsx_runtime(), 1);
var ALLOWS_EDIT_LOCKING = ["core/navigation"];
function getTemplateLockValue(lock5) {
if (lock5.remove && lock5.move) {
return "all";
}
if (lock5.remove && !lock5.move) {
return "insert";
}
return false;
}
function BlockLockModal({ clientId, onClose }) {
const [lock5, setLock] = (0, import_element157.useState)({ move: false, remove: false });
const { isEditLocked, isMoveLocked, isRemoveLocked } = useBlockLock(clientId);
const { allowsEditLocking, templateLock, hasTemplateLock } = (0, import_data99.useSelect)(
(select3) => {
const { getBlockName: getBlockName2, getBlockAttributes: getBlockAttributes3 } = select3(store);
const blockName = getBlockName2(clientId);
const blockType = (0, import_blocks59.getBlockType)(blockName);
return {
allowsEditLocking: ALLOWS_EDIT_LOCKING.includes(blockName),
templateLock: getBlockAttributes3(clientId)?.templateLock,
hasTemplateLock: !!blockType?.attributes?.templateLock
};
},
[clientId]
);
const [applyTemplateLock, setApplyTemplateLock] = (0, import_element157.useState)(
!!templateLock
);
const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data99.useDispatch)(store);
const blockInformation = useBlockDisplayInformation(clientId);
(0, import_element157.useEffect)(() => {
setLock({
move: isMoveLocked,
remove: isRemoveLocked,
...allowsEditLocking ? { edit: isEditLocked } : {}
});
}, [isEditLocked, isMoveLocked, isRemoveLocked, allowsEditLocking]);
const isAllChecked = Object.values(lock5).every(Boolean);
const isMixed = Object.values(lock5).some(Boolean) && !isAllChecked;
const isDirty = lock5.move !== isMoveLocked || lock5.remove !== isRemoveLocked || allowsEditLocking && lock5.edit !== isEditLocked || hasTemplateLock && applyTemplateLock !== !!templateLock;
return /* @__PURE__ */ (0, import_jsx_runtime288.jsx)(
import_components87.Modal,
{
title: (0, import_i18n81.sprintf)(
/* translators: %s: Name of the block. */
(0, import_i18n81.__)("Lock %s"),
blockInformation.title
),
overlayClassName: "block-editor-block-lock-modal",
onRequestClose: onClose,
size: "small",
children: /* @__PURE__ */ (0, import_jsx_runtime288.jsxs)(
"form",
{
onSubmit: (event) => {
event.preventDefault();
if (!isDirty) {
return;
}
updateBlockAttributes2([clientId], {
lock: lock5,
templateLock: applyTemplateLock ? getTemplateLockValue(lock5) : void 0
});
onClose();
},
children: [
/* @__PURE__ */ (0, import_jsx_runtime288.jsxs)("fieldset", { className: "block-editor-block-lock-modal__options", children: [
/* @__PURE__ */ (0, import_jsx_runtime288.jsx)("legend", { children: (0, import_i18n81.__)("Select the features you want to lock") }),
/* @__PURE__ */ (0, import_jsx_runtime288.jsx)(
"ul",
{
role: "list",
className: "block-editor-block-lock-modal__checklist",
children: /* @__PURE__ */ (0, import_jsx_runtime288.jsxs)("li", { children: [
/* @__PURE__ */ (0, import_jsx_runtime288.jsx)(
import_components87.CheckboxControl,
{
className: "block-editor-block-lock-modal__options-all",
label: (0, import_i18n81.__)("Lock all"),
checked: isAllChecked,
indeterminate: isMixed,
onChange: (newValue) => setLock({
move: newValue,
remove: newValue,
...allowsEditLocking ? { edit: newValue } : {}
})
}
),
/* @__PURE__ */ (0, import_jsx_runtime288.jsxs)(
"ul",
{
role: "list",
className: "block-editor-block-lock-modal__checklist",
children: [
allowsEditLocking && /* @__PURE__ */ (0, import_jsx_runtime288.jsxs)("li", { className: "block-editor-block-lock-modal__checklist-item", children: [
/* @__PURE__ */ (0, import_jsx_runtime288.jsx)(
import_components87.CheckboxControl,
{
label: (0, import_i18n81.__)("Lock editing"),
checked: !!lock5.edit,
onChange: (edit) => setLock((prevLock) => ({
...prevLock,
edit
}))
}
),
/* @__PURE__ */ (0, import_jsx_runtime288.jsx)(
import_components87.Icon,
{
className: "block-editor-block-lock-modal__lock-icon",
icon: lock5.edit ? lock_default : unlock_default
}
)
] }),
/* @__PURE__ */ (0, import_jsx_runtime288.jsxs)("li", { className: "block-editor-block-lock-modal__checklist-item", children: [
/* @__PURE__ */ (0, import_jsx_runtime288.jsx)(
import_components87.CheckboxControl,
{
label: (0, import_i18n81.__)("Lock movement"),
checked: lock5.move,
onChange: (move) => setLock((prevLock) => ({
...prevLock,
move
}))
}
),
/* @__PURE__ */ (0, import_jsx_runtime288.jsx)(
import_components87.Icon,
{
className: "block-editor-block-lock-modal__lock-icon",
icon: lock5.move ? lock_default : unlock_default
}
)
] }),
/* @__PURE__ */ (0, import_jsx_runtime288.jsxs)("li", { className: "block-editor-block-lock-modal__checklist-item", children: [
/* @__PURE__ */ (0, import_jsx_runtime288.jsx)(
import_components87.CheckboxControl,
{
label: (0, import_i18n81.__)("Lock removal"),
checked: lock5.remove,
onChange: (remove5) => setLock((prevLock) => ({
...prevLock,
remove: remove5
}))
}
),
/* @__PURE__ */ (0, import_jsx_runtime288.jsx)(
import_components87.Icon,
{
className: "block-editor-block-lock-modal__lock-icon",
icon: lock5.remove ? lock_default : unlock_default
}
)
] })
]
}
)
] })
}
),
hasTemplateLock && /* @__PURE__ */ (0, import_jsx_runtime288.jsx)(
import_components87.ToggleControl,
{
className: "block-editor-block-lock-modal__template-lock",
label: (0, import_i18n81.__)("Apply to all blocks inside"),
checked: applyTemplateLock,
disabled: lock5.move && !lock5.remove,
onChange: () => setApplyTemplateLock(!applyTemplateLock)
}
)
] }),
/* @__PURE__ */ (0, import_jsx_runtime288.jsxs)(
import_components87.Flex,
{
className: "block-editor-block-lock-modal__actions",
justify: "flex-end",
expanded: false,
children: [
/* @__PURE__ */ (0, import_jsx_runtime288.jsx)(import_components87.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime288.jsx)(
import_components87.Button,
{
variant: "tertiary",
onClick: onClose,
__next40pxDefaultSize: true,
children: (0, import_i18n81.__)("Cancel")
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime288.jsx)(import_components87.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime288.jsx)(
import_components87.Button,
{
variant: "primary",
type: "submit",
disabled: !isDirty,
accessibleWhenDisabled: true,
__next40pxDefaultSize: true,
children: (0, import_i18n81.__)("Apply")
}
) })
]
}
)
]
}
)
}
);
}
// packages/block-editor/build-module/components/block-lock/menu-item.mjs
var import_jsx_runtime289 = __toESM(require_jsx_runtime(), 1);
function BlockLockMenuItem({ clientId }) {
const { canLock, isLocked } = useBlockLock(clientId);
const [isModalOpen, toggleModal] = (0, import_element158.useReducer)(
(isActive) => !isActive,
false
);
if (!canLock) {
return null;
}
const label = isLocked ? (0, import_i18n82.__)("Unlock") : (0, import_i18n82.__)("Lock");
return /* @__PURE__ */ (0, import_jsx_runtime289.jsxs)(import_jsx_runtime289.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime289.jsx)(
import_components88.MenuItem,
{
icon: isLocked ? unlock_default : lock_outline_default,
onClick: toggleModal,
"aria-expanded": isModalOpen,
"aria-haspopup": "dialog",
children: label
}
),
isModalOpen && /* @__PURE__ */ (0, import_jsx_runtime289.jsx)(BlockLockModal, { clientId, onClose: toggleModal })
] });
}
// packages/block-editor/build-module/components/block-lock/toolbar.mjs
var import_i18n83 = __toESM(require_i18n(), 1);
var import_components89 = __toESM(require_components(), 1);
var import_element159 = __toESM(require_element(), 1);
var import_jsx_runtime290 = __toESM(require_jsx_runtime(), 1);
function BlockLockToolbar({ clientId }) {
const { canLock, isLocked } = useBlockLock(clientId);
const [isModalOpen, toggleModal] = (0, import_element159.useReducer)(
(isActive) => !isActive,
false
);
const hasLockButtonShownRef = (0, import_element159.useRef)(false);
(0, import_element159.useEffect)(() => {
if (isLocked) {
hasLockButtonShownRef.current = true;
}
}, [isLocked]);
if (!isLocked && !hasLockButtonShownRef.current) {
return null;
}
let label = isLocked ? (0, import_i18n83.__)("Unlock") : (0, import_i18n83.__)("Lock");
if (!canLock && isLocked) {
label = (0, import_i18n83.__)("Locked");
}
return /* @__PURE__ */ (0, import_jsx_runtime290.jsxs)(import_jsx_runtime290.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime290.jsx)(import_components89.ToolbarGroup, { className: "block-editor-block-lock-toolbar", children: /* @__PURE__ */ (0, import_jsx_runtime290.jsx)(
import_components89.ToolbarButton,
{
disabled: !canLock,
icon: isLocked ? lock_default : unlock_default,
label,
onClick: toggleModal,
"aria-expanded": isModalOpen,
"aria-haspopup": "dialog"
}
) }),
isModalOpen && /* @__PURE__ */ (0, import_jsx_runtime290.jsx)(BlockLockModal, { clientId, onClose: toggleModal })
] });
}
// packages/block-editor/build-module/components/block-settings-menu/block-mode-toggle.mjs
var import_i18n84 = __toESM(require_i18n(), 1);
var import_components90 = __toESM(require_components(), 1);
var import_blocks60 = __toESM(require_blocks(), 1);
var import_data100 = __toESM(require_data(), 1);
var import_jsx_runtime291 = __toESM(require_jsx_runtime(), 1);
var noop11 = () => {
};
function BlockModeToggle({ clientId, onToggle = noop11 }) {
const { blockType, mode: mode2, enabled } = (0, import_data100.useSelect)(
(select3) => {
const { getBlock: getBlock2, getBlockMode: getBlockMode2, getSettings: getSettings7 } = select3(store);
const block = getBlock2(clientId);
return {
mode: getBlockMode2(clientId),
blockType: block ? (0, import_blocks60.getBlockType)(block.name) : null,
enabled: getSettings7().codeEditingEnabled && !!block?.isValid
};
},
[clientId]
);
const { toggleBlockMode: toggleBlockMode2 } = (0, import_data100.useDispatch)(store);
if (!blockType || !(0, import_blocks60.hasBlockSupport)(blockType, "html", true) || !enabled) {
return null;
}
const label = mode2 === "visual" ? (0, import_i18n84.__)("Edit as HTML") : (0, import_i18n84.__)("Edit visually");
return /* @__PURE__ */ (0, import_jsx_runtime291.jsx)(
import_components90.MenuItem,
{
onClick: () => {
toggleBlockMode2(clientId);
onToggle();
},
children: label
}
);
}
// packages/block-editor/build-module/components/block-rename/rename-control.mjs
var import_components92 = __toESM(require_components(), 1);
var import_i18n86 = __toESM(require_i18n(), 1);
var import_element161 = __toESM(require_element(), 1);
var import_data102 = __toESM(require_data(), 1);
var import_keyboard_shortcuts6 = __toESM(require_keyboard_shortcuts(), 1);
// packages/block-editor/build-module/components/block-rename/modal.mjs
var import_components91 = __toESM(require_components(), 1);
var import_i18n85 = __toESM(require_i18n(), 1);
var import_element160 = __toESM(require_element(), 1);
var import_a11y11 = __toESM(require_a11y(), 1);
var import_data101 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/block-rename/is-empty-string.mjs
function isEmptyString(testString) {
return testString?.trim()?.length === 0;
}
// packages/block-editor/build-module/components/block-rename/modal.mjs
var import_jsx_runtime292 = __toESM(require_jsx_runtime(), 1);
function BlockRenameModal({ clientId, onClose }) {
const [editedBlockName, setEditedBlockName] = (0, import_element160.useState)();
const blockInformation = useBlockDisplayInformation(clientId);
const { metadata } = (0, import_data101.useSelect)(
(select3) => {
const { getBlockAttributes: getBlockAttributes3 } = select3(store);
return {
metadata: getBlockAttributes3(clientId)?.metadata
};
},
[clientId]
);
const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data101.useDispatch)(store);
const blockName = metadata?.name || "";
const originalBlockName = blockInformation?.title;
const hasOverridesWarning = !!blockName && !!metadata?.bindings && Object.values(metadata.bindings).some(
(binding) => binding.source === "core/pattern-overrides"
);
const nameHasChanged = editedBlockName !== void 0 && editedBlockName !== blockName;
const nameIsOriginal = editedBlockName === originalBlockName;
const nameIsEmpty = isEmptyString(editedBlockName);
const isNameValid = nameHasChanged || nameIsOriginal;
const autoSelectInputText = (event) => event.target.select();
const handleSubmit = () => {
const newName = nameIsOriginal || nameIsEmpty ? void 0 : editedBlockName;
const message2 = nameIsOriginal || nameIsEmpty ? (0, import_i18n85.sprintf)(
/* translators: %s: new name/label for the block */
(0, import_i18n85.__)('Block name reset to: "%s".'),
editedBlockName
) : (0, import_i18n85.sprintf)(
/* translators: %s: new name/label for the block */
(0, import_i18n85.__)('Block name changed to: "%s".'),
editedBlockName
);
(0, import_a11y11.speak)(message2, "assertive");
updateBlockAttributes2([clientId], {
metadata: cleanEmptyObject({
...metadata,
name: newName
})
});
onClose();
};
return /* @__PURE__ */ (0, import_jsx_runtime292.jsx)(
import_components91.Modal,
{
title: (0, import_i18n85.__)("Rename"),
onRequestClose: onClose,
overlayClassName: "block-editor-block-rename-modal",
focusOnMount: "firstContentElement",
size: "small",
children: /* @__PURE__ */ (0, import_jsx_runtime292.jsx)(
"form",
{
onSubmit: (e2) => {
e2.preventDefault();
if (!isNameValid) {
return;
}
handleSubmit();
},
children: /* @__PURE__ */ (0, import_jsx_runtime292.jsxs)(import_components91.__experimentalVStack, { spacing: "3", children: [
/* @__PURE__ */ (0, import_jsx_runtime292.jsx)(
import_components91.TextControl,
{
value: editedBlockName ?? blockName,
label: (0, import_i18n85.__)("Name"),
help: hasOverridesWarning ? (0, import_i18n85.__)(
"This block allows overrides. Changing the name can cause problems with content entered into instances of this pattern."
) : void 0,
placeholder: originalBlockName,
onChange: setEditedBlockName,
onFocus: autoSelectInputText
}
),
/* @__PURE__ */ (0, import_jsx_runtime292.jsxs)(import_components91.__experimentalHStack, { justify: "right", children: [
/* @__PURE__ */ (0, import_jsx_runtime292.jsx)(
import_components91.Button,
{
__next40pxDefaultSize: true,
variant: "tertiary",
onClick: onClose,
children: (0, import_i18n85.__)("Cancel")
}
),
/* @__PURE__ */ (0, import_jsx_runtime292.jsx)(
import_components91.Button,
{
__next40pxDefaultSize: true,
accessibleWhenDisabled: true,
disabled: !isNameValid,
variant: "primary",
type: "submit",
children: (0, import_i18n85.__)("Save")
}
)
] })
] })
}
)
}
);
}
// packages/block-editor/build-module/components/block-rename/rename-control.mjs
var import_jsx_runtime293 = __toESM(require_jsx_runtime(), 1);
function BlockRenameControl({ clientId }) {
const [renamingBlock, setRenamingBlock] = (0, import_element161.useState)(false);
const shortcut = (0, import_data102.useSelect)(
(select3) => select3(import_keyboard_shortcuts6.store).getShortcutRepresentation(
"core/block-editor/rename"
),
[]
);
return /* @__PURE__ */ (0, import_jsx_runtime293.jsxs)(import_jsx_runtime293.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime293.jsx)(
import_components92.MenuItem,
{
onClick: () => {
setRenamingBlock(true);
},
"aria-expanded": renamingBlock,
"aria-haspopup": "dialog",
shortcut,
children: (0, import_i18n86.__)("Rename")
}
),
renamingBlock && /* @__PURE__ */ (0, import_jsx_runtime293.jsx)(
BlockRenameModal,
{
clientId,
onClose: () => setRenamingBlock(false)
}
)
] });
}
// packages/block-editor/build-module/components/block-rename/use-block-rename.mjs
var import_blocks61 = __toESM(require_blocks(), 1);
function useBlockRename(name) {
return {
canRename: !!name && (0, import_blocks61.getBlockSupport)(name, "renaming", true)
};
}
// packages/block-editor/build-module/components/block-settings-menu-controls/index.mjs
var import_jsx_runtime294 = __toESM(require_jsx_runtime(), 1);
var { Fill: Fill2, Slot: Slot7 } = (0, import_components93.createSlotFill)("BlockSettingsMenuControls");
var BlockSettingsMenuControlsSlot = ({ fillProps, clientIds = null }) => {
const {
selectedBlocks,
selectedClientIds,
isContentOnly,
canToggleSelectedBlocksVisibility,
canEdit
} = (0, import_data103.useSelect)(
(select3) => {
const {
getBlocksByClientId: getBlocksByClientId2,
getBlockNamesByClientId: getBlockNamesByClientId2,
getSelectedBlockClientIds: getSelectedBlockClientIds2,
getBlockEditingMode: getBlockEditingMode2,
canEditBlock: canEditBlock2
} = select3(store);
const ids = clientIds !== null ? clientIds : getSelectedBlockClientIds2();
return {
selectedBlocks: getBlockNamesByClientId2(ids),
selectedClientIds: ids,
isContentOnly: getBlockEditingMode2(ids[0]) === "contentOnly",
canToggleSelectedBlocksVisibility: getBlocksByClientId2(
ids
).every(
(block) => (0, import_blocks62.hasBlockSupport)(block.name, "visibility", true)
),
canEdit: canEditBlock2(ids[0])
};
},
[clientIds]
);
const { canLock } = useBlockLock(selectedClientIds[0]);
const { canRename } = useBlockRename(selectedBlocks[0]);
const showLockButton = selectedClientIds.length === 1 && canLock && !isContentOnly;
const showRenameButton = selectedClientIds.length === 1 && canRename && !isContentOnly;
const showVisibilityButton = canToggleSelectedBlocksVisibility && !isContentOnly;
const convertToGroupButtonProps = useConvertToGroupButtonProps(selectedClientIds);
const { isGroupable: isGroupable2, isUngroupable: isUngroupable2 } = convertToGroupButtonProps;
const showConvertToGroupButton = (isGroupable2 || isUngroupable2) && !isContentOnly;
return /* @__PURE__ */ (0, import_jsx_runtime294.jsx)(
Slot7,
{
fillProps: {
...fillProps,
canEdit,
selectedBlocks,
selectedClientIds
},
children: (fills) => {
if (!fills?.length > 0 && !showConvertToGroupButton && !showLockButton) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime294.jsxs)(import_components93.MenuGroup, { children: [
showConvertToGroupButton && /* @__PURE__ */ (0, import_jsx_runtime294.jsx)(
ConvertToGroupButton,
{
...convertToGroupButtonProps,
onClose: fillProps?.onClose
}
),
canEdit && showLockButton && /* @__PURE__ */ (0, import_jsx_runtime294.jsx)(
BlockLockMenuItem,
{
clientId: selectedClientIds[0]
}
),
canEdit && showRenameButton && /* @__PURE__ */ (0, import_jsx_runtime294.jsx)(
BlockRenameControl,
{
clientId: selectedClientIds[0]
}
),
canEdit && showVisibilityButton && /* @__PURE__ */ (0, import_jsx_runtime294.jsx)(
BlockVisibilityViewportMenuItem,
{
clientIds: selectedClientIds
}
),
fills,
canEdit && fillProps?.count === 1 && !isContentOnly && /* @__PURE__ */ (0, import_jsx_runtime294.jsx)(
BlockModeToggle,
{
clientId: fillProps?.firstBlockClientId,
onToggle: fillProps?.onClose
}
)
] });
}
}
);
};
function BlockSettingsMenuControls({ ...props }) {
return /* @__PURE__ */ (0, import_jsx_runtime294.jsx)(import_components93.__experimentalStyleProvider, { document, children: /* @__PURE__ */ (0, import_jsx_runtime294.jsx)(Fill2, { ...props }) });
}
BlockSettingsMenuControls.Slot = BlockSettingsMenuControlsSlot;
var block_settings_menu_controls_default = BlockSettingsMenuControls;
// packages/block-editor/build-module/components/block-settings-menu/block-parent-selector-menu-item.mjs
var import_element162 = __toESM(require_element(), 1);
var import_components94 = __toESM(require_components(), 1);
var import_compose63 = __toESM(require_compose(), 1);
var import_data104 = __toESM(require_data(), 1);
var import_i18n87 = __toESM(require_i18n(), 1);
var import_jsx_runtime295 = __toESM(require_jsx_runtime(), 1);
function BlockParentSelectorMenuItem({
parentClientId,
parentBlockType
}) {
const isSmallViewport = (0, import_compose63.useViewportMatch)("medium", "<");
const { selectBlock: selectBlock2 } = (0, import_data104.useDispatch)(store);
const menuItemRef = (0, import_element162.useRef)();
const gesturesProps = useShowHoveredOrFocusedGestures({
ref: menuItemRef,
highlightParent: true
});
if (!isSmallViewport) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime295.jsx)(
import_components94.MenuItem,
{
...gesturesProps,
ref: menuItemRef,
icon: /* @__PURE__ */ (0, import_jsx_runtime295.jsx)(block_icon_default, { icon: parentBlockType.icon }),
onClick: () => selectBlock2(parentClientId),
children: (0, import_i18n87.sprintf)(
/* translators: %s: Name of the block's parent. */
(0, import_i18n87.__)("Select parent block (%s)"),
parentBlockType.title
)
}
);
}
// packages/block-editor/build-module/components/block-settings-menu/block-settings-dropdown.mjs
var import_jsx_runtime296 = __toESM(require_jsx_runtime(), 1);
var POPOVER_PROPS4 = {
className: "block-editor-block-settings-menu__popover",
placement: "bottom-start"
};
function CopyMenuItem({
clientIds,
onCopy,
label,
shortcut,
eventType = "copy",
__experimentalUpdateSelection: updateSelection = false
}) {
const { getBlocksByClientId: getBlocksByClientId2 } = (0, import_data105.useSelect)(store);
const { removeBlocks: removeBlocks2 } = (0, import_data105.useDispatch)(store);
const notifyCopy = useNotifyCopy();
const ref = (0, import_compose64.useCopyToClipboard)(
() => (0, import_blocks63.serialize)(getBlocksByClientId2(clientIds)),
() => {
switch (eventType) {
case "copy":
case "copyStyles":
onCopy();
notifyCopy(eventType, clientIds);
break;
case "cut":
notifyCopy(eventType, clientIds);
removeBlocks2(clientIds, updateSelection);
break;
default:
break;
}
}
);
const copyMenuItemLabel = label ? label : (0, import_i18n88.__)("Copy");
return /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(import_components95.MenuItem, { ref, shortcut, children: copyMenuItemLabel });
}
function BlockSettingsDropdown({
block,
clientIds,
children,
__experimentalSelectBlock,
isContentOnlyListView,
...props
}) {
const count = clientIds.length;
const firstBlockClientId = clientIds[0];
const {
firstParentClientId,
parentBlockType,
previousBlockClientId,
selectedBlockClientIds,
isContentOnly,
isZoomOut: isZoomOut2,
canEdit,
canMove,
isFirst,
isLast
} = (0, import_data105.useSelect)(
(select3) => {
const {
getBlockName: getBlockName2,
getBlockRootClientId: getBlockRootClientId2,
getPreviousBlockClientId: getPreviousBlockClientId2,
getSelectedBlockClientIds: getSelectedBlockClientIds22,
getBlockAttributes: getBlockAttributes3,
getBlockEditingMode: getBlockEditingMode2,
isZoomOut: _isZoomOut,
canEditBlock: canEditBlock2,
canMoveBlocks: canMoveBlocks2,
getBlockIndex: getBlockIndex2,
getBlockCount: getBlockCount2
} = unlock(select3(store));
const { getActiveBlockVariation } = select3(import_blocks63.store);
const _firstParentClientId = getBlockRootClientId2(firstBlockClientId);
const parentBlockName = _firstParentClientId && getBlockName2(_firstParentClientId);
return {
firstParentClientId: _firstParentClientId,
parentBlockType: _firstParentClientId && (getActiveBlockVariation(
parentBlockName,
getBlockAttributes3(_firstParentClientId)
) || (0, import_blocks63.getBlockType)(parentBlockName)),
previousBlockClientId: getPreviousBlockClientId2(firstBlockClientId),
selectedBlockClientIds: getSelectedBlockClientIds22(),
isContentOnly: getBlockEditingMode2(firstBlockClientId) === "contentOnly",
isZoomOut: _isZoomOut(),
canEdit: canEditBlock2(firstBlockClientId),
canMove: canMoveBlocks2(clientIds),
isFirst: getBlockIndex2(firstBlockClientId) === 0,
isLast: getBlockIndex2(firstBlockClientId) === getBlockCount2(_firstParentClientId) - 1
};
},
[firstBlockClientId, clientIds]
);
const { getBlockOrder: getBlockOrder2, getSelectedBlockClientIds: getSelectedBlockClientIds2 } = (0, import_data105.useSelect)(store);
const { moveBlocksDown: moveBlocksDown2, moveBlocksUp: moveBlocksUp2 } = (0, import_data105.useDispatch)(store);
const shortcuts = (0, import_data105.useSelect)((select3) => {
const { getShortcutRepresentation } = select3(import_keyboard_shortcuts7.store);
return {
copy: getShortcutRepresentation("core/block-editor/copy"),
cut: getShortcutRepresentation("core/block-editor/cut"),
duplicate: getShortcutRepresentation(
"core/block-editor/duplicate"
),
remove: getShortcutRepresentation("core/block-editor/remove"),
insertAfter: getShortcutRepresentation(
"core/block-editor/insert-after"
),
insertBefore: getShortcutRepresentation(
"core/block-editor/insert-before"
)
};
}, []);
const hasSelectedBlocks = selectedBlockClientIds.length > 0;
async function updateSelectionAfterDuplicate(clientIdsPromise) {
if (!__experimentalSelectBlock) {
return;
}
const ids = await clientIdsPromise;
if (ids && ids[0]) {
__experimentalSelectBlock(ids[0], false);
}
}
function updateSelectionAfterRemove() {
if (!__experimentalSelectBlock) {
return;
}
let blockToFocus = previousBlockClientId || firstParentClientId;
if (!blockToFocus) {
blockToFocus = getBlockOrder2()[0];
}
const shouldUpdateSelection = hasSelectedBlocks && getSelectedBlockClientIds2().length === 0;
__experimentalSelectBlock(blockToFocus, shouldUpdateSelection);
}
const parentBlockIsSelected = selectedBlockClientIds?.includes(firstParentClientId);
const shouldShowBlockParentMenuItem = !parentBlockIsSelected && !!firstParentClientId;
return /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(
BlockActions,
{
clientIds,
__experimentalUpdateSelection: !__experimentalSelectBlock,
children: ({
canCopyStyles,
canDuplicate,
canInsertBlock,
canRemove,
onDuplicate,
onInsertAfter,
onInsertBefore,
onRemove,
onCopy,
onPasteStyles
}) => {
const isEmpty4 = !canRemove && !canDuplicate && !canInsertBlock && isContentOnly;
if (isEmpty4) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(
import_components95.DropdownMenu,
{
icon: more_vertical_default,
label: (0, import_i18n88.__)("Options"),
className: "block-editor-block-settings-menu",
popoverProps: POPOVER_PROPS4,
noIcons: true,
...props,
children: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime296.jsxs)(import_jsx_runtime296.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime296.jsxs)(import_components95.MenuGroup, { children: [
/* @__PURE__ */ (0, import_jsx_runtime296.jsx)(
block_settings_menu_first_item_default.Slot,
{
fillProps: { onClose }
}
),
shouldShowBlockParentMenuItem && /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(
BlockParentSelectorMenuItem,
{
parentClientId: firstParentClientId,
parentBlockType
}
),
canMove && isContentOnlyListView && /* @__PURE__ */ (0, import_jsx_runtime296.jsxs)(import_jsx_runtime296.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime296.jsx)(
import_components95.MenuItem,
{
icon: chevron_up_default,
disabled: isFirst,
accessibleWhenDisabled: true,
onClick: (0, import_compose64.pipe)(onClose, () => {
moveBlocksUp2(
clientIds,
firstParentClientId
);
}),
children: (0, import_i18n88.__)("Move up")
}
),
/* @__PURE__ */ (0, import_jsx_runtime296.jsx)(
import_components95.MenuItem,
{
icon: chevron_down_default,
disabled: isLast,
accessibleWhenDisabled: true,
onClick: (0, import_compose64.pipe)(onClose, () => {
moveBlocksDown2(
clientIds,
firstParentClientId
);
}),
children: (0, import_i18n88.__)("Move down")
}
)
] }),
canEdit && count === 1 && /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(
block_html_convert_button_default,
{
clientId: firstBlockClientId
}
),
!isContentOnly && /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(
CopyMenuItem,
{
clientIds,
onCopy,
shortcut: shortcuts.copy
}
),
canRemove && !isContentOnly && /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(
CopyMenuItem,
{
clientIds,
label: (0, import_i18n88.__)("Cut"),
eventType: "cut",
shortcut: shortcuts.cut,
__experimentalUpdateSelection: !__experimentalSelectBlock
}
),
canDuplicate && /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(
import_components95.MenuItem,
{
onClick: (0, import_compose64.pipe)(
onClose,
onDuplicate,
updateSelectionAfterDuplicate
),
shortcut: shortcuts.duplicate,
children: (0, import_i18n88.__)("Duplicate")
}
),
canInsertBlock && !isZoomOut2 && /* @__PURE__ */ (0, import_jsx_runtime296.jsxs)(import_jsx_runtime296.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime296.jsx)(
import_components95.MenuItem,
{
onClick: (0, import_compose64.pipe)(
onClose,
onInsertBefore
),
shortcut: shortcuts.insertBefore,
children: (0, import_i18n88.__)("Add before")
}
),
/* @__PURE__ */ (0, import_jsx_runtime296.jsx)(
import_components95.MenuItem,
{
onClick: (0, import_compose64.pipe)(
onClose,
onInsertAfter
),
shortcut: shortcuts.insertAfter,
children: (0, import_i18n88.__)("Add after")
}
)
] }),
canEdit && count === 1 && /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(
note_icon_slot_default.Slot,
{
fillProps: {
clientId: firstBlockClientId,
onClose
}
}
)
] }),
canCopyStyles && !isContentOnly && /* @__PURE__ */ (0, import_jsx_runtime296.jsxs)(import_components95.MenuGroup, { children: [
/* @__PURE__ */ (0, import_jsx_runtime296.jsx)(
CopyMenuItem,
{
clientIds,
onCopy,
label: (0, import_i18n88.__)("Copy styles"),
eventType: "copyStyles"
}
),
canEdit && /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(import_components95.MenuItem, { onClick: onPasteStyles, children: (0, import_i18n88.__)("Paste styles") })
] }),
!isContentOnly && /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(
block_settings_menu_controls_default.Slot,
{
fillProps: {
onClose,
count,
firstBlockClientId
},
clientIds
}
),
typeof children === "function" ? children({ onClose }) : import_element163.Children.map(
(child) => (0, import_element163.cloneElement)(child, { onClose })
),
canRemove && /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(import_components95.MenuGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(
import_components95.MenuItem,
{
onClick: (0, import_compose64.pipe)(
onClose,
onRemove,
updateSelectionAfterRemove
),
shortcut: shortcuts.remove,
children: (0, import_i18n88.__)("Delete")
}
) })
] })
}
);
}
}
);
}
var block_settings_dropdown_default = BlockSettingsDropdown;
// packages/block-editor/build-module/components/collab/note-icon-toolbar-slot.mjs
var import_components96 = __toESM(require_components(), 1);
var NoteIconToolbarSlotFill = (0, import_components96.createSlotFill)(
/* @__PURE__ */ Symbol("NoteIconToolbarSlotFill")
);
var note_icon_toolbar_slot_default = NoteIconToolbarSlotFill;
// packages/block-editor/build-module/components/block-settings-menu/index.mjs
var import_jsx_runtime297 = __toESM(require_jsx_runtime(), 1);
function BlockSettingsMenu({ clientIds, ...props }) {
return /* @__PURE__ */ (0, import_jsx_runtime297.jsxs)(import_components97.ToolbarGroup, { children: [
/* @__PURE__ */ (0, import_jsx_runtime297.jsx)(note_icon_toolbar_slot_default.Slot, {}),
/* @__PURE__ */ (0, import_jsx_runtime297.jsx)(import_components97.ToolbarItem, { children: (toggleProps) => /* @__PURE__ */ (0, import_jsx_runtime297.jsx)(
block_settings_dropdown_default,
{
clientIds,
toggleProps,
...props
}
) })
] });
}
var block_settings_menu_default = BlockSettingsMenu;
// packages/block-editor/build-module/components/block-edit-visually-button/index.mjs
var import_components98 = __toESM(require_components(), 1);
var import_i18n89 = __toESM(require_i18n(), 1);
var import_data106 = __toESM(require_data(), 1);
var import_jsx_runtime298 = __toESM(require_jsx_runtime(), 1);
function BlockEditVisuallyButton({ clientIds }) {
const clientId = clientIds.length === 1 ? clientIds[0] : void 0;
const canEditVisually = (0, import_data106.useSelect)(
(select3) => !!clientId && select3(store).getBlockMode(clientId) === "html",
[clientId]
);
const { toggleBlockMode: toggleBlockMode2 } = (0, import_data106.useDispatch)(store);
if (!canEditVisually) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime298.jsx)(import_components98.ToolbarGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime298.jsx)(
import_components98.ToolbarButton,
{
onClick: () => {
toggleBlockMode2(clientId);
},
children: (0, import_i18n89.__)("Edit visually")
}
) });
}
// packages/block-editor/build-module/components/navigable-toolbar/index.mjs
var import_components99 = __toESM(require_components(), 1);
var import_element164 = __toESM(require_element(), 1);
var import_data107 = __toESM(require_data(), 1);
var import_deprecated12 = __toESM(require_deprecated(), 1);
var import_dom58 = __toESM(require_dom(), 1);
var import_keyboard_shortcuts8 = __toESM(require_keyboard_shortcuts(), 1);
var import_keycodes12 = __toESM(require_keycodes(), 1);
var import_jsx_runtime299 = __toESM(require_jsx_runtime(), 1);
function hasOnlyToolbarItem(elements) {
const dataProp = "toolbarItem";
return !elements.some((element) => !(dataProp in element.dataset));
}
function getAllFocusableToolbarItemsIn(container) {
return Array.from(
container.querySelectorAll("[data-toolbar-item]:not([disabled])")
);
}
function hasFocusWithin(container) {
return container.contains(container.ownerDocument.activeElement);
}
function focusFirstTabbableIn(container) {
const [firstTabbable] = import_dom58.focus.tabbable.find(container);
if (firstTabbable) {
firstTabbable.focus({
// When focusing newly mounted toolbars,
// the position of the popover is often not right on the first render
// This prevents the layout shifts when focusing the dialogs.
preventScroll: true
});
}
}
function useIsAccessibleToolbar(toolbarRef) {
const initialAccessibleToolbarState = true;
const [isAccessibleToolbar, setIsAccessibleToolbar] = (0, import_element164.useState)(
initialAccessibleToolbarState
);
const determineIsAccessibleToolbar = (0, import_element164.useCallback)(() => {
const tabbables = import_dom58.focus.tabbable.find(toolbarRef.current);
const onlyToolbarItem = hasOnlyToolbarItem(tabbables);
if (!onlyToolbarItem) {
(0, import_deprecated12.default)("Using custom components as toolbar controls", {
since: "5.6",
alternative: "ToolbarItem, ToolbarButton or ToolbarDropdownMenu components",
link: "https://developer.wordpress.org/block-editor/components/toolbar-button/#inside-blockcontrols"
});
}
setIsAccessibleToolbar(onlyToolbarItem);
}, [toolbarRef]);
(0, import_element164.useLayoutEffect)(() => {
const observer = new window.MutationObserver(
determineIsAccessibleToolbar
);
observer.observe(toolbarRef.current, {
childList: true,
subtree: true
});
return () => observer.disconnect();
}, [determineIsAccessibleToolbar, isAccessibleToolbar, toolbarRef]);
return isAccessibleToolbar;
}
function useToolbarFocus({
toolbarRef,
focusOnMount,
isAccessibleToolbar,
defaultIndex,
onIndexChange,
shouldUseKeyboardFocusShortcut,
focusEditorOnEscape
}) {
const [initialFocusOnMount] = (0, import_element164.useState)(focusOnMount);
const [initialIndex] = (0, import_element164.useState)(defaultIndex);
const focusToolbar = (0, import_element164.useCallback)(() => {
focusFirstTabbableIn(toolbarRef.current);
}, [toolbarRef]);
const focusToolbarViaShortcut = () => {
if (shouldUseKeyboardFocusShortcut) {
focusToolbar();
}
};
(0, import_keyboard_shortcuts8.useShortcut)("core/block-editor/focus-toolbar", focusToolbarViaShortcut);
(0, import_element164.useEffect)(() => {
if (initialFocusOnMount) {
focusToolbar();
}
}, [isAccessibleToolbar, initialFocusOnMount, focusToolbar]);
(0, import_element164.useEffect)(() => {
const navigableToolbarRef = toolbarRef.current;
let raf2 = 0;
if (!initialFocusOnMount && !hasFocusWithin(navigableToolbarRef)) {
raf2 = window.requestAnimationFrame(() => {
const items = getAllFocusableToolbarItemsIn(navigableToolbarRef);
const index2 = initialIndex || 0;
if (items[index2] && hasFocusWithin(navigableToolbarRef)) {
items[index2].focus({
// When focusing newly mounted toolbars,
// the position of the popover is often not right on the first render
// This prevents the layout shifts when focusing the dialogs.
preventScroll: true
});
}
});
}
return () => {
window.cancelAnimationFrame(raf2);
if (!onIndexChange || !navigableToolbarRef) {
return;
}
const items = getAllFocusableToolbarItemsIn(navigableToolbarRef);
const index2 = items.findIndex((item) => item.tabIndex === 0);
onIndexChange(index2);
};
}, [initialIndex, initialFocusOnMount, onIndexChange, toolbarRef]);
const { getLastFocus: getLastFocus2 } = unlock((0, import_data107.useSelect)(store));
(0, import_element164.useEffect)(() => {
const navigableToolbarRef = toolbarRef.current;
if (focusEditorOnEscape) {
const handleKeyDown = (event) => {
const lastFocus2 = getLastFocus2();
if (event.keyCode === import_keycodes12.ESCAPE && lastFocus2?.current) {
event.preventDefault();
lastFocus2.current.focus();
}
};
navigableToolbarRef.addEventListener("keydown", handleKeyDown);
return () => {
navigableToolbarRef.removeEventListener(
"keydown",
handleKeyDown
);
};
}
}, [focusEditorOnEscape, getLastFocus2, toolbarRef]);
}
function NavigableToolbar({
children,
focusOnMount,
focusEditorOnEscape = false,
shouldUseKeyboardFocusShortcut = true,
__experimentalInitialIndex: initialIndex,
__experimentalOnIndexChange: onIndexChange,
orientation = "horizontal",
...props
}) {
const toolbarRef = (0, import_element164.useRef)();
const isAccessibleToolbar = useIsAccessibleToolbar(toolbarRef);
useToolbarFocus({
toolbarRef,
focusOnMount,
defaultIndex: initialIndex,
onIndexChange,
isAccessibleToolbar,
shouldUseKeyboardFocusShortcut,
focusEditorOnEscape
});
if (isAccessibleToolbar) {
return /* @__PURE__ */ (0, import_jsx_runtime299.jsx)(
import_components99.Toolbar,
{
label: props["aria-label"],
ref: toolbarRef,
orientation,
...props,
children
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime299.jsx)(
import_components99.NavigableMenu,
{
orientation,
role: "toolbar",
ref: toolbarRef,
...props,
children
}
);
}
// packages/block-editor/build-module/components/block-toolbar/use-has-block-toolbar.mjs
var import_data108 = __toESM(require_data(), 1);
var import_blocks64 = __toESM(require_blocks(), 1);
function useHasBlockToolbar() {
const enabled = (0, import_data108.useSelect)((select3) => {
const { getBlockEditingMode: getBlockEditingMode2, getBlockName: getBlockName2, getBlockSelectionStart: getBlockSelectionStart2 } = select3(store);
const selectedBlockClientId = getBlockSelectionStart2();
const blockType = selectedBlockClientId && (0, import_blocks64.getBlockType)(getBlockName2(selectedBlockClientId));
return blockType && (0, import_blocks64.hasBlockSupport)(blockType, "__experimentalToolbar", true) && getBlockEditingMode2(selectedBlockClientId) !== "disabled";
}, []);
return enabled;
}
// packages/block-editor/build-module/components/block-toolbar/change-design.mjs
var import_components100 = __toESM(require_components(), 1);
var import_i18n90 = __toESM(require_i18n(), 1);
var import_blocks65 = __toESM(require_blocks(), 1);
var import_element165 = __toESM(require_element(), 1);
var import_data109 = __toESM(require_data(), 1);
var import_jsx_runtime300 = __toESM(require_jsx_runtime(), 1);
var EMPTY_ARRAY9 = [];
var MAX_PATTERNS_TO_SHOW = 6;
var POPOVER_PROPS5 = {
placement: "bottom-start"
};
function ChangeDesign({ clientId }) {
const { categories, currentPatternName, patterns } = (0, import_data109.useSelect)(
(select3) => {
const {
getBlockAttributes: getBlockAttributes3,
getBlockRootClientId: getBlockRootClientId2,
__experimentalGetAllowedPatterns: __experimentalGetAllowedPatterns2
} = select3(store);
const attributes = getBlockAttributes3(clientId);
const _categories = attributes?.metadata?.categories || EMPTY_ARRAY9;
const rootBlock = getBlockRootClientId2(clientId);
const _patterns = _categories.length > 0 ? __experimentalGetAllowedPatterns2(rootBlock) : EMPTY_ARRAY9;
return {
categories: _categories,
currentPatternName: attributes?.metadata?.patternName,
patterns: _patterns
};
},
[clientId]
);
const { replaceBlocks: replaceBlocks2 } = (0, import_data109.useDispatch)(store);
const sameCategoryPatternsWithSingleWrapper = (0, import_element165.useMemo)(() => {
if (categories.length === 0 || !patterns || patterns.length === 0) {
return EMPTY_ARRAY9;
}
return patterns.filter((pattern) => {
const isCorePattern = pattern.source === "core" || pattern.source?.startsWith("pattern-directory") && pattern.source !== "pattern-directory/theme";
return (
// Check if the pattern has only one top level block,
// otherwise we may switch to a pattern that doesn't have replacement suggestions.
pattern.blocks.length === 1 && // We exclude the core patterns and pattern directory patterns that are not theme patterns.
!isCorePattern && // Exclude current pattern.
currentPatternName !== pattern.name && pattern.categories?.some((category) => {
return categories.includes(category);
}) && // Check if the pattern is not a synced pattern.
(pattern.syncStatus === "unsynced" || !pattern.id)
);
}).slice(0, MAX_PATTERNS_TO_SHOW);
}, [categories, currentPatternName, patterns]);
if (sameCategoryPatternsWithSingleWrapper.length < 2) {
return null;
}
const onClickPattern = (pattern) => {
const newBlocks = (pattern.blocks ?? []).map((block) => {
return (0, import_blocks65.cloneBlock)(block);
});
newBlocks[0].attributes.metadata = {
...newBlocks[0].attributes.metadata,
categories
};
replaceBlocks2(clientId, newBlocks);
};
return /* @__PURE__ */ (0, import_jsx_runtime300.jsx)(
import_components100.Dropdown,
{
popoverProps: POPOVER_PROPS5,
renderToggle: ({ onToggle, isOpen }) => {
return /* @__PURE__ */ (0, import_jsx_runtime300.jsx)(import_components100.ToolbarGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime300.jsx)(
import_components100.ToolbarButton,
{
onClick: () => onToggle(!isOpen),
"aria-expanded": isOpen,
children: (0, import_i18n90.__)("Change design")
}
) });
},
renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime300.jsx)(
import_components100.__experimentalDropdownContentWrapper,
{
className: "block-editor-block-toolbar-change-design-content-wrapper",
paddingSize: "none",
children: /* @__PURE__ */ (0, import_jsx_runtime300.jsx)(
block_patterns_list_default,
{
blockPatterns: sameCategoryPatternsWithSingleWrapper,
onClickPattern,
showTitlesAsTooltip: true
}
)
}
)
}
);
}
// packages/block-editor/build-module/components/block-toolbar/switch-section-style.mjs
var import_components101 = __toESM(require_components(), 1);
var import_i18n92 = __toESM(require_i18n(), 1);
var import_data112 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/block-styles/use-styles-for-block.mjs
var import_data110 = __toESM(require_data(), 1);
var import_blocks66 = __toESM(require_blocks(), 1);
var import_element166 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/block-styles/utils.mjs
var import_token_list = __toESM(require_token_list(), 1);
var import_i18n91 = __toESM(require_i18n(), 1);
function getActiveStyle(styles, className) {
for (const style of new import_token_list.default(className).values()) {
if (style.indexOf("is-style-") === -1) {
continue;
}
const potentialStyleName = style.substring(9);
const activeStyle = styles?.find(
({ name }) => name === potentialStyleName
);
if (activeStyle) {
return activeStyle;
}
}
return getDefaultStyle(styles);
}
function replaceActiveStyle(className, activeStyle, newStyle) {
const list = new import_token_list.default(className);
if (activeStyle) {
list.remove("is-style-" + activeStyle.name);
}
list.add("is-style-" + newStyle.name);
return list.value;
}
function getRenderedStyles(styles) {
if (!styles || styles.length === 0) {
return [];
}
return getDefaultStyle(styles) ? styles : [
{
name: "default",
label: (0, import_i18n91._x)("Default", "block style"),
isDefault: true
},
...styles
];
}
function getDefaultStyle(styles) {
return styles?.find((style) => style.isDefault);
}
// packages/block-editor/build-module/components/block-styles/use-styles-for-block.mjs
function useGenericPreviewBlock(block, type) {
return (0, import_element166.useMemo)(() => {
const example = type?.example;
const blockName = type?.name;
if (example && blockName) {
return (0, import_blocks66.getBlockFromExample)(blockName, {
attributes: example.attributes,
innerBlocks: example.innerBlocks,
innerContent: example.innerContent
});
}
if (block) {
return (0, import_blocks66.cloneBlock)(block);
}
}, [block, type?.example, type?.name]);
}
function useStylesForBlocks({ clientId, onSwitch }) {
const selector3 = (select3) => {
const { getBlock: getBlock2 } = select3(store);
const block2 = getBlock2(clientId);
if (!block2) {
return {};
}
const blockType2 = (0, import_blocks66.getBlockType)(block2.name);
const { getBlockStyles: getBlockStyles2 } = select3(import_blocks66.store);
return {
block: !blockType2?.example ? block2 : null,
blockType: blockType2,
styles: getBlockStyles2(block2.name),
className: block2.attributes.className || ""
};
};
const { styles, block, blockType, className } = (0, import_data110.useSelect)(selector3, [
clientId
]);
const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data110.useDispatch)(store);
const stylesToRender = getRenderedStyles(styles);
const activeStyle = getActiveStyle(stylesToRender, className);
const genericPreviewBlock = useGenericPreviewBlock(block, blockType);
const onSelect = (style) => {
const styleClassName = replaceActiveStyle(
className,
activeStyle,
style
);
updateBlockAttributes2(clientId, {
className: styleClassName
});
onSwitch();
};
return {
onSelect,
stylesToRender,
activeStyle,
genericPreviewBlock,
className
};
}
// packages/block-editor/build-module/hooks/block-style-variation.mjs
var import_blocks67 = __toESM(require_blocks(), 1);
var import_data111 = __toESM(require_data(), 1);
var import_element167 = __toESM(require_element(), 1);
var import_jsx_runtime301 = __toESM(require_jsx_runtime(), 1);
var VARIATION_PREFIX = "is-style-";
function getVariationMatches(className) {
if (!className) {
return [];
}
return className.split(/\s+/).reduce((matches, name) => {
if (name.startsWith(VARIATION_PREFIX)) {
const match2 = name.slice(VARIATION_PREFIX.length);
if (match2 !== "default") {
matches.push(match2);
}
}
return matches;
}, []);
}
function getVariationNameFromClass(className, registeredStyles = []) {
const matches = getVariationMatches(className);
if (!matches) {
return null;
}
for (const variation of matches) {
if (registeredStyles.some((style) => style.name === variation)) {
return variation;
}
}
return null;
}
function OverrideStyles({ override }) {
usePrivateStyleOverride(override);
}
function BlockStyleVariationOverridesWithConfig({ config: config2 }) {
const { overrides } = (0, import_data111.useSelect)(
(select3) => ({
overrides: unlock(select3(store)).getStyleOverrides()
}),
[]
);
const { getBlockName: getBlockName2 } = (0, import_data111.useSelect)(store);
const overridesWithConfig = (0, import_element167.useMemo)(() => {
if (!overrides?.length) {
return;
}
const newOverrides = [];
const overriddenClientIds = [];
for (const [, override] of overrides) {
if (override?.variation && override?.clientId && /*
* Because this component overwrites existing style overrides,
* filter out any overrides that are already present in the store.
*/
!overriddenClientIds.includes(override.clientId)) {
const blockName = getBlockName2(override.clientId);
const configStyles = config2?.styles?.blocks?.[blockName]?.variations?.[override.variation];
if (configStyles) {
const variationConfig = {
settings: config2?.settings,
// The variation style data is all that is needed to generate
// the styles for the current application to a block. The variation
// name is updated to match the instance specific class name.
styles: {
blocks: {
[blockName]: {
variations: {
[`${override.variation}-${override.clientId}`]: configStyles
}
}
}
}
};
const blockSelectors = getBlockSelectors(
(0, import_blocks67.getBlockTypes)(),
override.clientId
);
const hasBlockGapSupport = false;
const hasFallbackGapSupport = true;
const disableLayoutStyles = true;
const disableRootPadding = true;
const variationStyles = transformToStyles(
variationConfig,
blockSelectors,
hasBlockGapSupport,
hasFallbackGapSupport,
disableLayoutStyles,
disableRootPadding,
{
blockGap: false,
blockStyles: true,
layoutStyles: false,
marginReset: false,
presets: false,
rootPadding: false,
variationStyles: true
}
);
newOverrides.push({
id: `${override.variation}-${override.clientId}`,
css: variationStyles,
__unstableType: "variation",
variation: override.variation,
// The clientId will be stored with the override and used to ensure
// the order of overrides matches the order of blocks so that the
// correct CSS cascade is maintained.
clientId: override.clientId
});
overriddenClientIds.push(override.clientId);
}
}
}
return newOverrides;
}, [config2, overrides, getBlockName2]);
if (!overridesWithConfig || !overridesWithConfig.length) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime301.jsx)(import_jsx_runtime301.Fragment, { children: overridesWithConfig.map((override) => /* @__PURE__ */ (0, import_jsx_runtime301.jsx)(OverrideStyles, { override }, override.id)) });
}
function getVariationStylesWithRefValues(globalStyles, name, variation) {
if (!globalStyles?.styles?.blocks?.[name]?.variations?.[variation]) {
return;
}
const replaceRefs = (variationStyles) => {
Object.keys(variationStyles).forEach((key) => {
const value = variationStyles[key];
if (typeof value === "object" && value !== null) {
if (value.ref !== void 0) {
if (typeof value.ref !== "string" || value.ref.trim() === "") {
delete variationStyles[key];
} else {
const refValue = getValueFromObjectPath2(
globalStyles,
value.ref
);
if (refValue) {
variationStyles[key] = refValue;
} else {
delete variationStyles[key];
}
}
} else {
replaceRefs(value);
if (Object.keys(value).length === 0) {
delete variationStyles[key];
}
}
}
});
};
const styles = JSON.parse(
JSON.stringify(
globalStyles.styles.blocks[name].variations[variation]
)
);
replaceRefs(styles);
return styles;
}
function useBlockStyleVariation(name, variation, clientId) {
const { globalSettings, globalStyles } = (0, import_data111.useSelect)((select3) => {
const settings2 = select3(store).getSettings();
return {
globalSettings: settings2.__experimentalFeatures,
globalStyles: settings2[globalStylesDataKey]
};
}, []);
return (0, import_element167.useMemo)(() => {
const variationStyles = getVariationStylesWithRefValues(
{
settings: globalSettings,
styles: globalStyles
},
name,
variation
);
return {
settings: globalSettings,
// The variation style data is all that is needed to generate
// the styles for the current application to a block. The variation
// name is updated to match the instance specific class name.
styles: {
blocks: {
[name]: {
variations: {
[`${variation}-${clientId}`]: variationStyles
}
}
}
}
};
}, [globalSettings, globalStyles, variation, clientId, name]);
}
function useBlockProps3({ name, className, clientId }) {
const { getBlockStyles: getBlockStyles2 } = (0, import_data111.useSelect)(import_blocks67.store);
const registeredStyles = getBlockStyles2(name);
const variation = getVariationNameFromClass(className, registeredStyles);
const variationClass = `${VARIATION_PREFIX}${variation}-${clientId}`;
const { settings: settings2, styles } = useBlockStyleVariation(
name,
variation,
clientId
);
const variationStyles = (0, import_element167.useMemo)(() => {
if (!variation) {
return;
}
const variationConfig = { settings: settings2, styles };
const blockSelectors = getBlockSelectors((0, import_blocks67.getBlockTypes)(), clientId);
const hasBlockGapSupport = false;
const hasFallbackGapSupport = true;
const disableLayoutStyles = true;
const disableRootPadding = true;
return transformToStyles(
variationConfig,
blockSelectors,
hasBlockGapSupport,
hasFallbackGapSupport,
disableLayoutStyles,
disableRootPadding,
{
blockGap: false,
blockStyles: true,
layoutStyles: false,
marginReset: false,
presets: false,
rootPadding: false,
variationStyles: true
}
);
}, [variation, settings2, styles, clientId]);
usePrivateStyleOverride({
id: `variation-${clientId}`,
css: variationStyles,
__unstableType: "variation",
variation,
// The clientId will be stored with the override and used to ensure
// the order of overrides matches the order of blocks so that the
// correct CSS cascade is maintained.
clientId
});
return variation ? { className: variationClass } : {};
}
var block_style_variation_default = {
hasSupport: () => true,
attributeKeys: ["className"],
isMatch: ({ className }) => getVariationMatches(className).length > 0,
useBlockProps: useBlockProps3
};
// packages/block-editor/build-module/components/block-toolbar/switch-section-style.mjs
var import_jsx_runtime302 = __toESM(require_jsx_runtime(), 1);
var styleIcon = /* @__PURE__ */ (0, import_jsx_runtime302.jsxs)(
import_components101.SVG,
{
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg",
width: "24",
height: "24",
"aria-hidden": "true",
focusable: "false",
children: [
/* @__PURE__ */ (0, import_jsx_runtime302.jsx)(import_components101.Path, { d: "M17.2 10.9c-.5-1-1.2-2.1-2.1-3.2-.6-.9-1.3-1.7-2.1-2.6L12 4l-1 1.1c-.6.9-1.3 1.7-2 2.6-.8 1.2-1.5 2.3-2 3.2-.6 1.2-1 2.2-1 3 0 3.4 2.7 6.1 6.1 6.1s6.1-2.7 6.1-6.1c0-.8-.3-1.8-1-3z" }),
/* @__PURE__ */ (0, import_jsx_runtime302.jsx)(
import_components101.Path,
{
stroke: "currentColor",
strokeWidth: "1.5",
d: "M17.2 10.9c-.5-1-1.2-2.1-2.1-3.2-.6-.9-1.3-1.7-2.1-2.6L12 4l-1 1.1c-.6.9-1.3 1.7-2 2.6-.8 1.2-1.5 2.3-2 3.2-.6 1.2-1 2.2-1 3 0 3.4 2.7 6.1 6.1 6.1s6.1-2.7 6.1-6.1c0-.8-.3-1.8-1-3z"
}
)
]
}
);
function SwitchSectionStyle({ clientId }) {
const { stylesToRender, activeStyle, className } = useStylesForBlocks({
clientId
});
const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data112.useDispatch)(store);
const { globalSettings, globalStyles, blockName } = (0, import_data112.useSelect)(
(select3) => {
const settings2 = select3(store).getSettings();
return {
globalSettings: settings2.__experimentalFeatures,
globalStyles: settings2[globalStylesDataKey],
blockName: select3(store).getBlockName(clientId)
};
},
[clientId]
);
const activeStyleBackground = activeStyle?.name ? getVariationStylesWithRefValues(
{
settings: globalSettings,
styles: globalStyles
},
blockName,
activeStyle.name
)?.color?.background : void 0;
if (!stylesToRender || stylesToRender.length === 0) {
return null;
}
const handleStyleSwitch = () => {
const currentIndex = stylesToRender.findIndex(
(style) => style.name === activeStyle.name
);
const nextIndex = (currentIndex + 1) % stylesToRender.length;
const nextStyle = stylesToRender[nextIndex];
const styleClassName = replaceActiveStyle(
className,
activeStyle,
nextStyle
);
updateBlockAttributes2(clientId, {
className: styleClassName
});
};
return /* @__PURE__ */ (0, import_jsx_runtime302.jsx)(import_components101.ToolbarGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime302.jsx)(
import_components101.ToolbarButton,
{
onClick: handleStyleSwitch,
label: (0, import_i18n92.__)("Shuffle styles"),
children: /* @__PURE__ */ (0, import_jsx_runtime302.jsx)(
import_components101.Icon,
{
icon: styleIcon,
style: {
fill: activeStyleBackground || "transparent"
}
}
)
}
) });
}
var switch_section_style_default = SwitchSectionStyle;
// packages/block-editor/build-module/components/block-toolbar/edit-section-button.mjs
var import_components102 = __toESM(require_components(), 1);
var import_i18n93 = __toESM(require_i18n(), 1);
var import_data114 = __toESM(require_data(), 1);
var import_blocks68 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/hooks/use-content-only-section-edit.mjs
var import_data113 = __toESM(require_data(), 1);
function useContentOnlySectionEdit(clientId) {
const {
isSectionBlock: isSectionBlock2,
isWithinSection,
isWithinEditedSection,
isEditingContentOnlySection,
editedContentOnlySection: editedContentOnlySection2
} = (0, import_data113.useSelect)(
(select3) => {
const {
isSectionBlock: _isSectionBlock,
getParentSectionBlock: getParentSectionBlock2,
getEditedContentOnlySection: getEditedContentOnlySection2,
isWithinEditedContentOnlySection: isWithinEditedContentOnlySection2
} = unlock(select3(store));
const editedSection = getEditedContentOnlySection2();
return {
isSectionBlock: _isSectionBlock(clientId),
isWithinSection: _isSectionBlock(clientId) || !!getParentSectionBlock2(clientId),
isWithinEditedSection: isWithinEditedContentOnlySection2(clientId),
isEditingContentOnlySection: editedSection === clientId,
editedContentOnlySection: editedSection
};
},
[clientId]
);
const blockEditorActions = (0, import_data113.useDispatch)(store);
const { editContentOnlySection: editContentOnlySection2, stopEditingContentOnlySection: stopEditingContentOnlySection2 } = unlock(blockEditorActions);
return {
isSectionBlock: isSectionBlock2,
isWithinSection,
isWithinEditedSection,
isEditingContentOnlySection,
editedContentOnlySection: editedContentOnlySection2,
editContentOnlySection: editContentOnlySection2,
stopEditingContentOnlySection: stopEditingContentOnlySection2
};
}
// packages/block-editor/build-module/components/block-toolbar/edit-section-button.mjs
var import_jsx_runtime303 = __toESM(require_jsx_runtime(), 1);
function EditSectionButton({ clientId }) {
const {
isSectionBlock: isSectionBlock2,
isEditingContentOnlySection,
editContentOnlySection: editContentOnlySection2,
stopEditingContentOnlySection: stopEditingContentOnlySection2
} = useContentOnlySectionEdit(clientId);
const blockType = (0, import_data114.useSelect)(
(select3) => {
if (!clientId) {
return null;
}
const { getBlockName: getBlockName2 } = select3(store);
const blockName = getBlockName2(clientId);
return blockName ? { name: blockName } : null;
},
[clientId]
);
if (!clientId || !isSectionBlock2 && !isEditingContentOnlySection || (0, import_blocks68.isReusableBlock)(blockType) || (0, import_blocks68.isTemplatePart)(blockType)) {
return null;
}
const isEditing = isEditingContentOnlySection;
const handleClick = () => {
if (isEditing) {
stopEditingContentOnlySection2();
} else {
editContentOnlySection2(clientId);
}
};
return /* @__PURE__ */ (0, import_jsx_runtime303.jsx)(import_components102.ToolbarGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime303.jsx)(import_components102.ToolbarButton, { onClick: handleClick, children: isEditing ? (
/* translators: Button label to leave pattern editing mode. */
(0, import_i18n93.__)("Exit pattern")
) : (
/* translators: Button label to enter pattern editing mode. */
(0, import_i18n93.__)("Edit pattern")
) }) });
}
// packages/block-editor/build-module/components/block-toolbar/block-toolbar-icon.mjs
var import_components112 = __toESM(require_components(), 1);
var import_i18n100 = __toESM(require_i18n(), 1);
var import_data118 = __toESM(require_data(), 1);
var import_blocks74 = __toESM(require_blocks(), 1);
var import_preferences2 = __toESM(require_preferences(), 1);
// packages/block-editor/build-module/components/block-switcher/index.mjs
var import_i18n97 = __toESM(require_i18n(), 1);
var import_components109 = __toESM(require_components(), 1);
var import_blocks73 = __toESM(require_blocks(), 1);
var import_data116 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/block-switcher/block-transformations-menu.mjs
var import_i18n94 = __toESM(require_i18n(), 1);
var import_components105 = __toESM(require_components(), 1);
var import_blocks70 = __toESM(require_blocks(), 1);
var import_element169 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/block-switcher/preview-block-popover.mjs
var import_components103 = __toESM(require_components(), 1);
var import_compose65 = __toESM(require_compose(), 1);
var import_jsx_runtime304 = __toESM(require_jsx_runtime(), 1);
function PreviewBlockPopover({
blocks: blocks2,
placement = "right-start",
offset: offset4 = 16,
anchor
}) {
const isMobile = (0, import_compose65.useViewportMatch)("medium", "<");
if (isMobile) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime304.jsx)("div", { className: "block-editor-block-switcher__popover-preview-container", children: /* @__PURE__ */ (0, import_jsx_runtime304.jsx)(
import_components103.Popover,
{
className: "block-editor-block-switcher__popover-preview",
placement,
focusOnMount: false,
offset: offset4,
anchor,
children: /* @__PURE__ */ (0, import_jsx_runtime304.jsx)("div", { className: "block-editor-block-switcher__preview", children: /* @__PURE__ */ (0, import_jsx_runtime304.jsx)(block_preview_default, { viewportWidth: 601, blocks: blocks2 }) })
}
) });
}
// packages/block-editor/build-module/components/block-switcher/block-variation-transformations.mjs
var import_components104 = __toESM(require_components(), 1);
var import_blocks69 = __toESM(require_blocks(), 1);
var import_data115 = __toESM(require_data(), 1);
var import_element168 = __toESM(require_element(), 1);
var import_jsx_runtime305 = __toESM(require_jsx_runtime(), 1);
var EMPTY_OBJECT3 = {};
function useBlockVariationTransforms({ clientIds, blocks: blocks2 }) {
const { activeBlockVariation, blockVariationTransformations } = (0, import_data115.useSelect)(
(select3) => {
const { getBlockAttributes: getBlockAttributes3, canRemoveBlocks: canRemoveBlocks2 } = select3(store);
const { getActiveBlockVariation, getBlockVariations: getBlockVariations2 } = select3(import_blocks69.store);
const canRemove = canRemoveBlocks2(clientIds);
if (blocks2.length !== 1 || !canRemove) {
return EMPTY_OBJECT3;
}
const [firstBlock] = blocks2;
return {
blockVariationTransformations: getBlockVariations2(
firstBlock.name,
"transform"
),
activeBlockVariation: getActiveBlockVariation(
firstBlock.name,
getBlockAttributes3(firstBlock.clientId)
)
};
},
[clientIds, blocks2]
);
const transformations = (0, import_element168.useMemo)(() => {
return blockVariationTransformations?.filter(
({ name }) => name !== activeBlockVariation?.name
);
}, [blockVariationTransformations, activeBlockVariation]);
return transformations;
}
var BlockVariationTransformations = ({
transformations,
onSelect,
blocks: blocks2
}) => {
const [hoveredTransformItemName, setHoveredTransformItemName] = (0, import_element168.useState)();
return /* @__PURE__ */ (0, import_jsx_runtime305.jsxs)(import_jsx_runtime305.Fragment, { children: [
hoveredTransformItemName && /* @__PURE__ */ (0, import_jsx_runtime305.jsx)(
PreviewBlockPopover,
{
blocks: (0, import_blocks69.cloneBlock)(
blocks2[0],
transformations.find(
({ name }) => name === hoveredTransformItemName
).attributes
)
}
),
transformations?.map((item) => /* @__PURE__ */ (0, import_jsx_runtime305.jsx)(
BlockVariationTransformationItem,
{
item,
onSelect,
setHoveredTransformItemName
},
item.name
))
] });
};
function BlockVariationTransformationItem({
item,
onSelect,
setHoveredTransformItemName
}) {
const { name, icon, title } = item;
return /* @__PURE__ */ (0, import_jsx_runtime305.jsxs)(
import_components104.MenuItem,
{
className: (0, import_blocks69.getBlockMenuDefaultClassName)(name),
onClick: (event) => {
event.preventDefault();
onSelect(name);
},
onMouseLeave: () => setHoveredTransformItemName(null),
onMouseEnter: () => setHoveredTransformItemName(name),
onFocus: () => setHoveredTransformItemName(name),
onBlur: () => setHoveredTransformItemName(null),
children: [
/* @__PURE__ */ (0, import_jsx_runtime305.jsx)(block_icon_default, { icon, showColors: true }),
title
]
}
);
}
var block_variation_transformations_default = BlockVariationTransformations;
// packages/block-editor/build-module/components/block-switcher/block-transformations-menu.mjs
var import_jsx_runtime306 = __toESM(require_jsx_runtime(), 1);
function useGroupedTransforms(possibleBlockTransformations) {
const priorityContentTransformationBlocks = {
"core/paragraph": 1,
"core/heading": 2,
"core/list": 3,
"core/quote": 4
};
const transformations = (0, import_element169.useMemo)(() => {
const priorityTextTransformsNames = Object.keys(
priorityContentTransformationBlocks
);
const groupedPossibleTransforms = possibleBlockTransformations.reduce(
(accumulator, item) => {
const { name } = item;
if (priorityTextTransformsNames.includes(name)) {
accumulator.priorityTextTransformations.push(item);
} else {
accumulator.restTransformations.push(item);
}
return accumulator;
},
{ priorityTextTransformations: [], restTransformations: [] }
);
if (groupedPossibleTransforms.priorityTextTransformations.length === 1 && groupedPossibleTransforms.priorityTextTransformations[0].name === "core/quote") {
const singleQuote = groupedPossibleTransforms.priorityTextTransformations.pop();
groupedPossibleTransforms.restTransformations.push(singleQuote);
}
return groupedPossibleTransforms;
}, [possibleBlockTransformations]);
transformations.priorityTextTransformations.sort(
({ name: currentName }, { name: nextName }) => {
return priorityContentTransformationBlocks[currentName] < priorityContentTransformationBlocks[nextName] ? -1 : 1;
}
);
return transformations;
}
var BlockTransformationsMenu = ({
className,
possibleBlockTransformations,
possibleBlockVariationTransformations,
onSelect,
onSelectVariation,
blocks: blocks2
}) => {
const [hoveredTransformItem, setHoveredTransformItem] = (0, import_element169.useState)();
const { priorityTextTransformations, restTransformations } = useGroupedTransforms(possibleBlockTransformations);
const hasBothContentTransformations = priorityTextTransformations.length && restTransformations.length;
const restTransformItems = !!restTransformations.length && /* @__PURE__ */ (0, import_jsx_runtime306.jsx)(
RestTransformationItems,
{
restTransformations,
onSelect,
setHoveredTransformItem
}
);
return /* @__PURE__ */ (0, import_jsx_runtime306.jsxs)(import_jsx_runtime306.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime306.jsxs)(import_components105.MenuGroup, { label: (0, import_i18n94.__)("Transform to"), className, children: [
hoveredTransformItem && /* @__PURE__ */ (0, import_jsx_runtime306.jsx)(
PreviewBlockPopover,
{
blocks: (0, import_blocks70.switchToBlockType)(
blocks2,
hoveredTransformItem.name,
hoveredTransformItem.variationName
)
}
),
!!possibleBlockVariationTransformations?.length && /* @__PURE__ */ (0, import_jsx_runtime306.jsx)(
block_variation_transformations_default,
{
transformations: possibleBlockVariationTransformations,
blocks: blocks2,
onSelect: onSelectVariation
}
),
priorityTextTransformations.map((item) => /* @__PURE__ */ (0, import_jsx_runtime306.jsx)(
BlockTransformationItem,
{
item,
onSelect,
setHoveredTransformItem
},
item.id || item.name
)),
!hasBothContentTransformations && restTransformItems
] }),
!!hasBothContentTransformations && /* @__PURE__ */ (0, import_jsx_runtime306.jsx)(import_components105.MenuGroup, { className, children: restTransformItems })
] });
};
function RestTransformationItems({
restTransformations,
onSelect,
setHoveredTransformItem
}) {
return restTransformations.map((item) => /* @__PURE__ */ (0, import_jsx_runtime306.jsx)(
BlockTransformationItem,
{
item,
onSelect,
setHoveredTransformItem
},
item.id || item.name
));
}
function BlockTransformationItem({
item,
onSelect,
setHoveredTransformItem
}) {
const { name, icon, title, isDisabled } = item;
return /* @__PURE__ */ (0, import_jsx_runtime306.jsxs)(
import_components105.MenuItem,
{
className: (0, import_blocks70.getBlockMenuDefaultClassName)(name),
onClick: (event) => {
event.preventDefault();
onSelect(name, item.variationName);
},
disabled: isDisabled,
onMouseLeave: () => setHoveredTransformItem(null),
onMouseEnter: () => setHoveredTransformItem(item),
onFocus: () => setHoveredTransformItem(item),
onBlur: () => setHoveredTransformItem(null),
children: [
/* @__PURE__ */ (0, import_jsx_runtime306.jsx)(block_icon_default, { icon, showColors: true }),
title
]
}
);
}
var block_transformations_menu_default = BlockTransformationsMenu;
// packages/block-editor/build-module/components/block-switcher/block-styles-menu.mjs
var import_i18n95 = __toESM(require_i18n(), 1);
var import_components107 = __toESM(require_components(), 1);
var import_element170 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/block-styles/menu-items.mjs
var import_components106 = __toESM(require_components(), 1);
var import_jsx_runtime307 = __toESM(require_jsx_runtime(), 1);
var noop12 = () => {
};
function BlockStylesMenuItems({
stylesToRender,
activeStyle,
onSelect = noop12,
onHoverStyle = noop12
}) {
if (!stylesToRender || stylesToRender.length === 0) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime307.jsx)(import_jsx_runtime307.Fragment, { children: stylesToRender.map((style) => {
const menuItemText = style.label || style.name;
return /* @__PURE__ */ (0, import_jsx_runtime307.jsx)(
import_components106.MenuItem,
{
icon: activeStyle.name === style.name ? check_default : null,
onClick: () => onSelect(style),
onFocus: () => onHoverStyle(style),
onBlur: () => onHoverStyle(null),
onMouseEnter: () => onHoverStyle(style),
onMouseLeave: () => onHoverStyle(null),
children: /* @__PURE__ */ (0, import_jsx_runtime307.jsx)(
import_components106.__experimentalText,
{
as: "span",
limit: 18,
ellipsizeMode: "tail",
truncate: true,
children: menuItemText
}
)
},
style.name
);
}) });
}
// packages/block-editor/build-module/components/block-switcher/block-styles-menu.mjs
var import_jsx_runtime308 = __toESM(require_jsx_runtime(), 1);
function BlockStylesMenu({ hoveredBlock, onSwitch }) {
const { clientId } = hoveredBlock;
const [hoveredStyle, setHoveredStyle] = (0, import_element170.useState)(null);
const {
onSelect,
stylesToRender,
activeStyle,
genericPreviewBlock,
className
} = useStylesForBlocks({
clientId,
onSwitch
});
const previewBlocks = (0, import_element170.useMemo)(() => {
if (!hoveredStyle || !genericPreviewBlock) {
return null;
}
const previewClassName = replaceActiveStyle(
className,
activeStyle,
hoveredStyle
);
return [
{
...genericPreviewBlock,
attributes: {
...genericPreviewBlock.attributes || {},
className: previewClassName
}
}
];
}, [hoveredStyle, genericPreviewBlock, className, activeStyle]);
if (!stylesToRender || stylesToRender.length === 0) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime308.jsxs)(
import_components107.MenuGroup,
{
label: (0, import_i18n95.__)("Styles"),
className: "block-editor-block-switcher__styles__menugroup",
children: [
previewBlocks && /* @__PURE__ */ (0, import_jsx_runtime308.jsx)(PreviewBlockPopover, { blocks: previewBlocks }),
/* @__PURE__ */ (0, import_jsx_runtime308.jsx)(
BlockStylesMenuItems,
{
stylesToRender,
activeStyle,
onSelect,
onHoverStyle: setHoveredStyle
}
)
]
}
);
}
// packages/block-editor/build-module/components/block-switcher/pattern-transformations-menu.mjs
var import_i18n96 = __toESM(require_i18n(), 1);
var import_element172 = __toESM(require_element(), 1);
var import_compose66 = __toESM(require_compose(), 1);
var import_components108 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/block-switcher/use-transformed-patterns.mjs
var import_element171 = __toESM(require_element(), 1);
var import_blocks72 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/components/block-switcher/utils.mjs
var import_blocks71 = __toESM(require_blocks(), 1);
var getMatchingBlockByName = (block, selectedBlockName, consumedBlocks = /* @__PURE__ */ new Set()) => {
const { clientId, name, innerBlocks = [] } = block;
if (consumedBlocks.has(clientId)) {
return;
}
if (name === selectedBlockName) {
return block;
}
for (const innerBlock of innerBlocks) {
const match2 = getMatchingBlockByName(
innerBlock,
selectedBlockName,
consumedBlocks
);
if (match2) {
return match2;
}
}
};
var getRetainedBlockAttributes = (name, attributes) => {
const contentAttributes = (0, import_blocks71.getBlockAttributesNamesByRole)(name, "content");
if (!contentAttributes?.length) {
return attributes;
}
return contentAttributes.reduce((_accumulator, attribute) => {
if (attributes[attribute]) {
_accumulator[attribute] = attributes[attribute];
}
return _accumulator;
}, {});
};
// packages/block-editor/build-module/components/block-switcher/use-transformed-patterns.mjs
var transformMatchingBlock = (match2, selectedBlock) => {
const retainedBlockAttributes = getRetainedBlockAttributes(
selectedBlock.name,
selectedBlock.attributes
);
match2.attributes = {
...match2.attributes,
...retainedBlockAttributes
};
};
var getPatternTransformedBlocks = (selectedBlocks, patternBlocks) => {
const _patternBlocks = patternBlocks.map(
(block) => (0, import_blocks72.cloneBlock)(block)
);
const consumedBlocks = /* @__PURE__ */ new Set();
for (const selectedBlock of selectedBlocks) {
let isMatch = false;
for (const patternBlock of _patternBlocks) {
const match2 = getMatchingBlockByName(
patternBlock,
selectedBlock.name,
consumedBlocks
);
if (!match2) {
continue;
}
isMatch = true;
consumedBlocks.add(match2.clientId);
transformMatchingBlock(match2, selectedBlock);
break;
}
if (!isMatch) {
return;
}
}
return _patternBlocks;
};
var useTransformedPatterns = (patterns, selectedBlocks) => {
return (0, import_element171.useMemo)(
() => patterns.reduce((accumulator, _pattern) => {
const transformedBlocks = getPatternTransformedBlocks(
selectedBlocks,
_pattern.blocks
);
if (transformedBlocks) {
accumulator.push({
..._pattern,
transformedBlocks
});
}
return accumulator;
}, []),
[patterns, selectedBlocks]
);
};
var use_transformed_patterns_default = useTransformedPatterns;
// packages/block-editor/build-module/components/block-switcher/pattern-transformations-menu.mjs
var import_jsx_runtime309 = __toESM(require_jsx_runtime(), 1);
function PatternTransformationsMenu({
blocks: blocks2,
patterns: statePatterns,
onSelect
}) {
const [showTransforms, setShowTransforms] = (0, import_element172.useState)(false);
const patterns = use_transformed_patterns_default(statePatterns, blocks2);
if (!patterns.length) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime309.jsxs)(import_components108.MenuGroup, { className: "block-editor-block-switcher__pattern__transforms__menugroup", children: [
showTransforms && /* @__PURE__ */ (0, import_jsx_runtime309.jsx)(
PreviewPatternsPopover,
{
patterns,
onSelect
}
),
/* @__PURE__ */ (0, import_jsx_runtime309.jsx)(
import_components108.MenuItem,
{
onClick: (event) => {
event.preventDefault();
setShowTransforms(!showTransforms);
},
icon: chevron_right_default,
children: (0, import_i18n96.__)("Patterns")
}
)
] });
}
function PreviewPatternsPopover({ patterns, onSelect }) {
const isMobile = (0, import_compose66.useViewportMatch)("medium", "<");
return /* @__PURE__ */ (0, import_jsx_runtime309.jsx)("div", { className: "block-editor-block-switcher__popover-preview-container", children: /* @__PURE__ */ (0, import_jsx_runtime309.jsx)(
import_components108.Popover,
{
className: "block-editor-block-switcher__popover-preview",
placement: isMobile ? "bottom" : "right-start",
offset: 16,
children: /* @__PURE__ */ (0, import_jsx_runtime309.jsx)("div", { className: "block-editor-block-switcher__preview is-pattern-list-preview", children: /* @__PURE__ */ (0, import_jsx_runtime309.jsx)(
BlockPatternsList2,
{
patterns,
onSelect
}
) })
}
) });
}
function BlockPatternsList2({ patterns, onSelect }) {
return /* @__PURE__ */ (0, import_jsx_runtime309.jsx)(
import_components108.Composite,
{
role: "listbox",
className: "block-editor-block-switcher__preview-patterns-container",
"aria-label": (0, import_i18n96.__)("Patterns list"),
children: patterns.map((pattern) => /* @__PURE__ */ (0, import_jsx_runtime309.jsx)(
BlockPattern2,
{
pattern,
onSelect
},
pattern.name
))
}
);
}
function BlockPattern2({ pattern, onSelect }) {
const baseClassName = "block-editor-block-switcher__preview-patterns-container";
const descriptionId = (0, import_compose66.useInstanceId)(
BlockPattern2,
`${baseClassName}-list__item-description`
);
return /* @__PURE__ */ (0, import_jsx_runtime309.jsxs)("div", { className: `${baseClassName}-list__list-item`, children: [
/* @__PURE__ */ (0, import_jsx_runtime309.jsxs)(
import_components108.Composite.Item,
{
render: /* @__PURE__ */ (0, import_jsx_runtime309.jsx)(
"div",
{
role: "option",
"aria-label": pattern.title,
"aria-describedby": pattern.description ? descriptionId : void 0,
className: `${baseClassName}-list__item`
}
),
onClick: () => onSelect(pattern.transformedBlocks),
children: [
/* @__PURE__ */ (0, import_jsx_runtime309.jsx)(
block_preview_default,
{
blocks: pattern.transformedBlocks,
viewportWidth: pattern.viewportWidth || 500
}
),
/* @__PURE__ */ (0, import_jsx_runtime309.jsx)("div", { className: `${baseClassName}-list__item-title`, children: pattern.title })
]
}
),
!!pattern.description && /* @__PURE__ */ (0, import_jsx_runtime309.jsx)(VisuallyHidden, { id: descriptionId, children: pattern.description })
] });
}
var pattern_transformations_menu_default = PatternTransformationsMenu;
// packages/block-editor/build-module/components/block-switcher/index.mjs
var import_jsx_runtime310 = __toESM(require_jsx_runtime(), 1);
function BlockSwitcherDropdownMenuContents({ onClose, clientIds }) {
const { replaceBlocks: replaceBlocks2, multiSelect: multiSelect2, updateBlockAttributes: updateBlockAttributes2 } = (0, import_data116.useDispatch)(store);
const {
possibleBlockTransformations,
patterns,
blocks: blocks2,
isUsingBindings,
canRemove,
hasBlockStyles
} = (0, import_data116.useSelect)(
(select3) => {
const {
getBlockAttributes: getBlockAttributes3,
getBlocksByClientId: getBlocksByClientId2,
getBlockRootClientId: getBlockRootClientId2,
getBlockTransformItems: getBlockTransformItems2,
__experimentalGetPatternTransformItems: __experimentalGetPatternTransformItems2,
canRemoveBlocks: canRemoveBlocks2,
getBlockName: getBlockName2
} = select3(store);
const { getBlockStyles: getBlockStyles2 } = select3(import_blocks73.store);
const rootClientId = getBlockRootClientId2(clientIds[0]);
const _blocks = getBlocksByClientId2(clientIds);
const _isSingleBlock = clientIds.length === 1;
const _blockName = _isSingleBlock && getBlockName2(clientIds[0]);
const _hasBlockStyles = _isSingleBlock && !!getBlockStyles2(_blockName)?.length;
return {
blocks: _blocks,
possibleBlockTransformations: getBlockTransformItems2(
_blocks,
rootClientId
),
patterns: __experimentalGetPatternTransformItems2(
_blocks,
rootClientId
),
isUsingBindings: clientIds.every(
(clientId) => !!getBlockAttributes3(clientId)?.metadata?.bindings
),
canRemove: canRemoveBlocks2(clientIds),
hasBlockStyles: _hasBlockStyles
};
},
[clientIds]
);
const blockVariationTransformations = useBlockVariationTransforms({
clientIds,
blocks: blocks2
});
function selectForMultipleBlocks(insertedBlocks) {
if (insertedBlocks.length > 1) {
multiSelect2(
insertedBlocks[0].clientId,
insertedBlocks[insertedBlocks.length - 1].clientId
);
}
}
function onBlockTransform(name, variationName) {
const newBlocks = (0, import_blocks73.switchToBlockType)(blocks2, name, variationName);
replaceBlocks2(clientIds, newBlocks);
selectForMultipleBlocks(newBlocks);
}
function onBlockVariationTransform(name) {
updateBlockAttributes2(blocks2[0].clientId, {
...blockVariationTransformations.find(
({ name: variationName }) => variationName === name
).attributes
});
}
function onPatternTransform(transformedBlocks) {
replaceBlocks2(clientIds, transformedBlocks);
selectForMultipleBlocks(transformedBlocks);
}
const isSingleBlock = blocks2.length === 1;
const isSynced = isSingleBlock && ((0, import_blocks73.isTemplatePart)(blocks2[0]) || (0, import_blocks73.isReusableBlock)(blocks2[0]));
const hasPossibleBlockTransformations = !!possibleBlockTransformations?.length && canRemove && !isSynced;
const hasPossibleBlockVariationTransformations = !!blockVariationTransformations?.length;
const hasPatternTransformation = !!patterns?.length && canRemove;
const hasBlockOrBlockVariationTransforms = hasPossibleBlockTransformations || hasPossibleBlockVariationTransformations;
const hasContents = hasBlockStyles || hasBlockOrBlockVariationTransforms || hasPatternTransformation;
if (!hasContents) {
return /* @__PURE__ */ (0, import_jsx_runtime310.jsx)("p", { className: "block-editor-block-switcher__no-transforms", children: (0, import_i18n97.__)("No transforms.") });
}
const connectedBlockDescription = isSingleBlock ? (0, import_i18n97._x)(
"This block is connected.",
"block toolbar button label and description"
) : (0, import_i18n97._x)(
"These blocks are connected.",
"block toolbar button label and description"
);
return /* @__PURE__ */ (0, import_jsx_runtime310.jsxs)("div", { className: "block-editor-block-switcher__container", children: [
hasPatternTransformation && /* @__PURE__ */ (0, import_jsx_runtime310.jsx)(
pattern_transformations_menu_default,
{
blocks: blocks2,
patterns,
onSelect: (transformedBlocks) => {
onPatternTransform(transformedBlocks);
onClose();
}
}
),
hasBlockOrBlockVariationTransforms && /* @__PURE__ */ (0, import_jsx_runtime310.jsx)(
block_transformations_menu_default,
{
className: "block-editor-block-switcher__transforms__menugroup",
possibleBlockTransformations,
possibleBlockVariationTransformations: blockVariationTransformations,
blocks: blocks2,
onSelect: (name, variationName) => {
onBlockTransform(name, variationName);
onClose();
},
onSelectVariation: (name) => {
onBlockVariationTransform(name);
onClose();
}
}
),
hasBlockStyles && /* @__PURE__ */ (0, import_jsx_runtime310.jsx)(
BlockStylesMenu,
{
hoveredBlock: blocks2[0],
onSwitch: onClose
}
),
isUsingBindings && /* @__PURE__ */ (0, import_jsx_runtime310.jsx)(import_components109.MenuGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime310.jsx)(import_components109.__experimentalText, { className: "block-editor-block-switcher__binding-indicator", children: connectedBlockDescription }) })
] });
}
var BlockSwitcher = ({ children, clientIds, label, text }) => {
const isSingleBlock = clientIds.length === 1;
const blockSwitcherDescription = isSingleBlock ? (0, import_i18n97.__)("Change block type or style") : (0, import_i18n97.sprintf)(
/* translators: %d: number of blocks. */
(0, import_i18n97._n)(
"Change type of %d block",
"Change type of %d blocks",
clientIds.length
),
clientIds.length
);
return /* @__PURE__ */ (0, import_jsx_runtime310.jsx)(import_components109.ToolbarGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime310.jsx)(import_components109.ToolbarItem, { children: (toggleProps) => /* @__PURE__ */ (0, import_jsx_runtime310.jsx)(
import_components109.DropdownMenu,
{
className: "block-editor-block-switcher",
label,
popoverProps: {
placement: "bottom-start",
className: "block-editor-block-switcher__popover"
},
icon: children,
text,
toggleProps: {
description: blockSwitcherDescription,
...toggleProps
},
menuProps: { orientation: "both" },
children: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime310.jsx)(
BlockSwitcherDropdownMenuContents,
{
onClose,
clientIds
}
)
}
) }) });
};
var block_switcher_default = BlockSwitcher;
// packages/block-editor/build-module/components/block-toolbar/block-styles-dropdown.mjs
var import_i18n98 = __toESM(require_i18n(), 1);
var import_components110 = __toESM(require_components(), 1);
var import_jsx_runtime311 = __toESM(require_jsx_runtime(), 1);
function BlockStylesDropdown({
clientIds,
children,
label,
text
}) {
return /* @__PURE__ */ (0, import_jsx_runtime311.jsx)(import_components110.ToolbarGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime311.jsx)(import_components110.ToolbarItem, { children: (toggleProps) => /* @__PURE__ */ (0, import_jsx_runtime311.jsx)(
import_components110.DropdownMenu,
{
className: "block-editor-block-switcher",
label,
popoverProps: {
placement: "bottom-start",
className: "block-editor-block-switcher__popover"
},
icon: children,
text,
toggleProps: {
description: (0, import_i18n98.__)("Change block style"),
...toggleProps
},
menuProps: { orientation: "both" },
children: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime311.jsx)("div", { className: "block-editor-block-switcher__container", children: /* @__PURE__ */ (0, import_jsx_runtime311.jsx)(
BlockStylesMenu,
{
hoveredBlock: {
clientId: clientIds[0]
},
onSwitch: onClose
}
) })
}
) }) });
}
// packages/block-editor/build-module/components/block-toolbar/pattern-overrides-dropdown.mjs
var import_components111 = __toESM(require_components(), 1);
var import_i18n99 = __toESM(require_i18n(), 1);
var import_element173 = __toESM(require_element(), 1);
var import_data117 = __toESM(require_data(), 1);
var import_jsx_runtime312 = __toESM(require_jsx_runtime(), 1);
function PatternOverridesPopoverContent({ clientIds, blockTitle }) {
const blockMetaName = (0, import_data117.useSelect)(
(select3) => {
const { getBlockAttributes: getBlockAttributes3 } = select3(store);
return getBlockAttributes3(clientIds?.[0])?.metadata?.name;
},
[clientIds]
);
const isSingleBlock = clientIds.length === 1;
let description;
if (isSingleBlock && blockMetaName) {
description = (0, import_i18n99.sprintf)(
/* translators: 1: The block type's name. 2: The block's user-provided name (the same as the override name). */
(0, import_i18n99.__)('This %1$s is editable using the "%2$s" override.'),
blockTitle.toLowerCase(),
blockMetaName
);
} else {
description = (0, import_i18n99.__)("These blocks are editable using overrides.");
}
return /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(import_components111.__experimentalText, { children: description });
}
function PatternOverridesDropdown({
icon,
clientIds,
blockTitle,
label
}) {
const [isOpen, setIsOpen] = (0, import_element173.useState)(false);
const anchorRef = (0, import_element173.useRef)();
return /* @__PURE__ */ (0, import_jsx_runtime312.jsxs)(import_jsx_runtime312.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
import_components111.ToolbarButton,
{
ref: anchorRef,
className: "block-editor-block-toolbar__pattern-overrides-indicator",
icon,
label,
onClick: () => setIsOpen(!isOpen),
"aria-expanded": isOpen
}
),
isOpen && /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
import_components111.Popover,
{
anchor: anchorRef.current,
onClose: () => setIsOpen(false),
placement: "bottom-start",
offset: 16,
className: "block-editor-block-toolbar__pattern-overrides-popover",
children: /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
PatternOverridesPopoverContent,
{
clientIds,
blockTitle
}
)
}
)
] });
}
// packages/block-editor/build-module/components/block-toolbar/block-toolbar-icon.mjs
var import_jsx_runtime313 = __toESM(require_jsx_runtime(), 1);
function getBlockIconVariant({ select: select3, clientIds }) {
const {
getBlockName: getBlockName2,
getBlockAttributes: getBlockAttributes3,
getBlockParentsByBlockName: getBlockParentsByBlockName2,
canRemoveBlocks: canRemoveBlocks2,
getTemplateLock: getTemplateLock2,
getBlockEditingMode: getBlockEditingMode2,
canEditBlock: canEditBlock2,
isSectionBlock: isSectionBlock2
} = unlock(select3(store));
const { getBlockStyles: getBlockStyles2 } = select3(import_blocks74.store);
const hasTemplateLock = clientIds.some(
(id) => getTemplateLock2(id) === "contentOnly"
);
const isSingleBlock = clientIds.length === 1;
const blockName = isSingleBlock && getBlockName2(clientIds[0]);
const hasBlockStyles = isSingleBlock && !!getBlockStyles2(blockName)?.length;
const hasPatternNameInSelection = clientIds.some(
(id) => !!getBlockAttributes3(id)?.metadata?.patternName && isSectionBlock2(id)
);
const hasPatternOverrides = clientIds.every(
(clientId) => hasPatternOverridesDefaultBinding(
getBlockAttributes3(clientId)?.metadata?.bindings
)
);
const hasParentPattern = clientIds.every(
(clientId) => getBlockParentsByBlockName2(clientId, "core/block", true).length > 0
);
const canRemove = canRemoveBlocks2(clientIds);
const canEdit = clientIds.every((clientId) => canEditBlock2(clientId));
const editingMode = getBlockEditingMode2(clientIds[0]);
const isDefaultEditingMode = editingMode === "default";
const isContentOnlyMode = editingMode === "contentOnly";
const _hideTransformsForSections = hasPatternNameInSelection;
const _showBlockSwitcher = !_hideTransformsForSections && isDefaultEditingMode && (hasBlockStyles || canRemove) && !hasTemplateLock && canEdit;
const _showPatternOverrides = hasPatternOverrides && hasParentPattern;
if (_showBlockSwitcher) {
return "switcher";
} else if (isContentOnlyMode && hasBlockStyles && !hasPatternOverrides && canEdit) {
return "styles-only";
} else if (_showPatternOverrides) {
return "pattern-overrides";
}
return "default";
}
function getBlockIcon({ select: select3, clientIds }) {
const { getBlockName: getBlockName2, getBlockAttributes: getBlockAttributes3, getBlock: getBlock2, isSectionBlock: isSectionBlock2 } = unlock(select3(store));
const _isSingleBlock = clientIds.length === 1;
const firstClientId = clientIds[0];
const blockAttributes = getBlockAttributes3(firstClientId);
if (_isSingleBlock && blockAttributes?.metadata?.patternName && isSectionBlock2(firstClientId)) {
return symbol_default;
}
const blockName = getBlockName2(firstClientId);
const blockType = (0, import_blocks74.getBlockType)(blockName);
if (_isSingleBlock) {
const { getActiveBlockVariation } = select3(import_blocks74.store);
const match2 = getActiveBlockVariation(
blockName,
blockAttributes,
void 0,
getBlock2?.(firstClientId)?.innerContent
);
return match2?.icon || blockType?.icon;
}
const blockNames = clientIds.map((id) => getBlockName2(id));
const isSelectionOfSameType = new Set(blockNames).size === 1;
return isSelectionOfSameType ? blockType?.icon : copy_default;
}
function BlockToolbarIcon({ clientIds, isSynced }) {
const { icon, showIconLabels, variant } = (0, import_data118.useSelect)(
(select3) => {
return {
icon: getBlockIcon({ select: select3, clientIds }),
showIconLabels: select3(import_preferences2.store).get(
"core",
"showIconLabels"
),
variant: getBlockIconVariant({
select: select3,
clientIds
})
};
},
[clientIds]
);
const blockTitle = useBlockDisplayTitle({
clientId: clientIds?.[0],
maximumLength: 35
});
const isSingleBlock = clientIds.length === 1;
const showBlockTitle = isSingleBlock && isSynced && !showIconLabels;
const label = isSingleBlock ? blockTitle : (0, import_i18n100.__)("Multiple blocks selected");
const text = showBlockTitle && blockTitle ? blockTitle : void 0;
const BlockIconElement = /* @__PURE__ */ (0, import_jsx_runtime313.jsx)(
block_icon_default,
{
className: "block-editor-block-toolbar__block-icon",
icon
}
);
if (variant === "switcher") {
return /* @__PURE__ */ (0, import_jsx_runtime313.jsx)(
block_switcher_default,
{
clientIds,
label,
text,
children: BlockIconElement
}
);
}
if (variant === "styles-only") {
return /* @__PURE__ */ (0, import_jsx_runtime313.jsx)(
BlockStylesDropdown,
{
clientIds,
label,
text,
children: BlockIconElement
}
);
}
if (variant === "pattern-overrides") {
return /* @__PURE__ */ (0, import_jsx_runtime313.jsx)(
PatternOverridesDropdown,
{
icon: BlockIconElement,
clientIds,
blockTitle,
label
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime313.jsx)(
import_components112.ToolbarButton,
{
disabled: true,
className: "block-editor-block-toolbar__block-icon-button",
title: label,
icon: BlockIconElement,
text
}
);
}
// packages/block-editor/build-module/components/block-toolbar/index.mjs
var import_jsx_runtime314 = __toESM(require_jsx_runtime(), 1);
function PrivateBlockToolbar({
hideDragHandle,
focusOnMount,
__experimentalInitialIndex,
__experimentalOnIndexChange,
variant = "unstyled"
}) {
const {
blockClientId,
blockClientIds,
isDefaultEditingMode,
blockType,
toolbarKey,
shouldShowVisualToolbar,
showParentSelector,
isUsingBindings,
isSectionContainer,
hasContentOnlyLocking,
showShuffleButton,
showSlots,
showGroupButtons,
showLockButtons,
showBlockVisibilityButton,
showSwitchSectionStyleButton,
areSelectedBlocksHiddenOnViewport,
showStyleStateSlot,
canEdit
} = (0, import_data119.useSelect)((select3) => {
const { canEditBlock: canEditBlock2 } = select3(store);
const {
getBlockName: getBlockName2,
getBlockMode: getBlockMode2,
getBlockParents: getBlockParents2,
getSelectedBlockClientIds: getSelectedBlockClientIds2,
isBlockValid: isBlockValid2,
getBlockEditingMode: getBlockEditingMode2,
getBlockAttributes: getBlockAttributes3,
getSettings: getSettings7,
getTemplateLock: getTemplateLock2,
getParentSectionBlock: getParentSectionBlock2,
isZoomOut: isZoomOut2,
isSectionBlock: isSectionBlock2,
isBlockHiddenAtViewport: isBlockHiddenAtViewport2,
getSelectedBlockStyleState: getSelectedBlockStyleState2,
isResponsiveEditing: isResponsiveEditing3
} = unlock(select3(store));
const selectedBlockClientIds = getSelectedBlockClientIds2();
const selectedBlockClientId = selectedBlockClientIds[0];
const parents = getBlockParents2(selectedBlockClientId);
const parentSection = getParentSectionBlock2(selectedBlockClientId);
const parentClientId = parentSection ?? parents[parents.length - 1];
const parentBlockName = getBlockName2(parentClientId);
const parentBlockType = (0, import_blocks75.getBlockType)(parentBlockName);
const editingMode = getBlockEditingMode2(selectedBlockClientId);
const _isDefaultEditingMode = editingMode === "default";
const _blockName = getBlockName2(selectedBlockClientId);
const isValid2 = selectedBlockClientIds.every(
(id) => isBlockValid2(id)
);
const isVisual = selectedBlockClientIds.every(
(id) => getBlockMode2(id) === "visual"
);
const _isUsingBindings = selectedBlockClientIds.every(
(clientId) => !!getBlockAttributes3(clientId)?.metadata?.bindings
);
const _hasTemplateLock = selectedBlockClientIds.some(
(id) => getTemplateLock2(id) === "contentOnly"
);
const _isZoomOut = isZoomOut2();
const _isSectionBlock = isSectionBlock2(selectedBlockClientId);
const _canEditBlock = canEditBlock2(selectedBlockClientId);
const _showSwitchSectionStyleButton = _canEditBlock && (_isZoomOut || _isSectionBlock);
const _currentDeviceType = getSettings7()?.[deviceTypeKey]?.toLowerCase() || "desktop";
const _areSelectedBlocksHiddenOnViewport = selectedBlockClientIds.length > 0 && selectedBlockClientIds.every(
(id) => isBlockHiddenAtViewport2(id, _currentDeviceType)
);
const _isEditingResponsiveStyleState = isResponsiveEditing3() && hasViewportBlockStyleState(
getSelectedBlockStyleState2(selectedBlockClientId)
);
return {
blockClientId: selectedBlockClientId,
blockClientIds: selectedBlockClientIds,
isDefaultEditingMode: _isDefaultEditingMode,
blockType: selectedBlockClientId && (0, import_blocks75.getBlockType)(_blockName),
shouldShowVisualToolbar: isValid2 && isVisual,
toolbarKey: `${selectedBlockClientId}${parentClientId}`,
showParentSelector: !_isZoomOut && parentBlockType && editingMode !== "contentOnly" && getBlockEditingMode2(parentClientId) !== "disabled" && (0, import_blocks75.hasBlockSupport)(
parentBlockType,
"__experimentalParentSelector",
true
) && selectedBlockClientIds.length === 1,
isUsingBindings: _isUsingBindings,
isSectionContainer: _isSectionBlock,
hasContentOnlyLocking: _hasTemplateLock,
showShuffleButton: _isZoomOut,
showSlots: !_isZoomOut && !_isEditingResponsiveStyleState,
showStyleStateSlot: !_isZoomOut && _isEditingResponsiveStyleState,
showGroupButtons: !_isZoomOut,
showLockButtons: !_isZoomOut,
showBlockVisibilityButton: !_isZoomOut,
showSwitchSectionStyleButton: _showSwitchSectionStyleButton,
areSelectedBlocksHiddenOnViewport: _areSelectedBlocksHiddenOnViewport,
canEdit: _canEditBlock
};
}, []);
const toolbarWrapperRef = (0, import_element174.useRef)(null);
const nodeRef = (0, import_element174.useRef)();
const showHoveredOrFocusedGestures = useShowHoveredOrFocusedGestures({
ref: nodeRef
});
const isLargeViewport = !(0, import_compose67.useViewportMatch)("medium", "<");
const hasBlockToolbar = useHasBlockToolbar();
if (!hasBlockToolbar) {
return null;
}
const isMultiToolbar = blockClientIds.length > 1;
const isSynced = (0, import_blocks75.isReusableBlock)(blockType) || (0, import_blocks75.isTemplatePart)(blockType);
const classes = clsx_default("block-editor-block-contextual-toolbar", {
"has-parent": showParentSelector
});
const innerClasses = clsx_default("block-editor-block-toolbar", {
"is-synced": isSynced,
"is-connected": isUsingBindings
});
return /* @__PURE__ */ (0, import_jsx_runtime314.jsx)(
NavigableToolbar,
{
focusEditorOnEscape: true,
className: classes,
"aria-label": (0, import_i18n101.__)("Block tools"),
variant: variant === "toolbar" ? void 0 : variant,
focusOnMount,
__experimentalInitialIndex,
__experimentalOnIndexChange,
children: /* @__PURE__ */ (0, import_jsx_runtime314.jsxs)("div", { ref: toolbarWrapperRef, className: innerClasses, children: [
showParentSelector && !isMultiToolbar && isLargeViewport && /* @__PURE__ */ (0, import_jsx_runtime314.jsx)(BlockParentSelector, {}),
(shouldShowVisualToolbar || isMultiToolbar) && /* @__PURE__ */ (0, import_jsx_runtime314.jsx)("div", { ref: nodeRef, ...showHoveredOrFocusedGestures, children: /* @__PURE__ */ (0, import_jsx_runtime314.jsxs)(import_components113.ToolbarGroup, { className: "block-editor-block-toolbar__block-controls", children: [
/* @__PURE__ */ (0, import_jsx_runtime314.jsx)(
BlockToolbarIcon,
{
clientIds: blockClientIds,
isSynced
}
),
isDefaultEditingMode && showBlockVisibilityButton && /* @__PURE__ */ (0, import_jsx_runtime314.jsx)(
BlockVisibilityViewportToolbar,
{
clientIds: blockClientIds
}
),
!isMultiToolbar && isDefaultEditingMode && showLockButtons && /* @__PURE__ */ (0, import_jsx_runtime314.jsx)(
BlockLockToolbar,
{
clientId: blockClientId
}
),
/* @__PURE__ */ (0, import_jsx_runtime314.jsx)(
block_mover_default,
{
clientIds: blockClientIds,
hideDragHandle
}
)
] }) }),
!areSelectedBlocksHiddenOnViewport && !hasContentOnlyLocking && shouldShowVisualToolbar && isMultiToolbar && showGroupButtons && /* @__PURE__ */ (0, import_jsx_runtime314.jsx)(toolbar_default, {}),
!isMultiToolbar && canEdit && /* @__PURE__ */ (0, import_jsx_runtime314.jsx)(EditSectionButton, { clientId: blockClientIds[0] }),
!areSelectedBlocksHiddenOnViewport && showShuffleButton && /* @__PURE__ */ (0, import_jsx_runtime314.jsx)(ChangeDesign, { clientId: blockClientIds[0] }),
!areSelectedBlocksHiddenOnViewport && showSwitchSectionStyleButton && /* @__PURE__ */ (0, import_jsx_runtime314.jsx)(switch_section_style_default, { clientId: blockClientIds[0] }),
!areSelectedBlocksHiddenOnViewport && shouldShowVisualToolbar && /* @__PURE__ */ (0, import_jsx_runtime314.jsxs)(import_jsx_runtime314.Fragment, { children: [
!isSectionContainer && /* @__PURE__ */ (0, import_jsx_runtime314.jsxs)(import_jsx_runtime314.Fragment, { children: [
showSlots && /* @__PURE__ */ (0, import_jsx_runtime314.jsxs)(import_jsx_runtime314.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime314.jsx)(
block_controls_default.Slot,
{
group: "parent",
className: "block-editor-block-toolbar__slot"
}
),
/* @__PURE__ */ (0, import_jsx_runtime314.jsx)(
block_controls_default.Slot,
{
group: "block",
className: "block-editor-block-toolbar__slot"
}
),
/* @__PURE__ */ (0, import_jsx_runtime314.jsx)(block_controls_default.Slot, { className: "block-editor-block-toolbar__slot" }),
/* @__PURE__ */ (0, import_jsx_runtime314.jsx)(
block_controls_default.Slot,
{
group: "inline",
className: "block-editor-block-toolbar__slot"
}
)
] }),
showStyleStateSlot && /* @__PURE__ */ (0, import_jsx_runtime314.jsx)(
block_controls_default.Slot,
{
group: "style-state",
className: "block-editor-block-toolbar__slot"
}
)
] }),
showSlots && /* @__PURE__ */ (0, import_jsx_runtime314.jsxs)(import_jsx_runtime314.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime314.jsx)(
block_controls_default.Slot,
{
group: "other",
className: "block-editor-block-toolbar__slot"
}
),
/* @__PURE__ */ (0, import_jsx_runtime314.jsx)(block_toolbar_last_item_default.Slot, {})
] })
] }),
/* @__PURE__ */ (0, import_jsx_runtime314.jsx)(BlockEditVisuallyButton, { clientIds: blockClientIds }),
/* @__PURE__ */ (0, import_jsx_runtime314.jsx)(block_settings_menu_default, { clientIds: blockClientIds })
] })
},
toolbarKey
);
}
function BlockToolbar({ hideDragHandle, variant }) {
return /* @__PURE__ */ (0, import_jsx_runtime314.jsx)(
PrivateBlockToolbar,
{
hideDragHandle,
variant,
focusOnMount: void 0,
__experimentalInitialIndex: void 0,
__experimentalOnIndexChange: void 0
}
);
}
// packages/block-editor/build-module/components/block-tools/block-toolbar-popover.mjs
var import_jsx_runtime315 = __toESM(require_jsx_runtime(), 1);
function BlockToolbarPopover({
clientId,
isTyping: isTyping3,
__unstableContentRef
}) {
const { capturingClientId, isInsertionPointVisible, lastClientId } = useSelectedBlockToolProps(clientId);
const initialToolbarItemIndexRef = (0, import_element175.useRef)();
(0, import_element175.useEffect)(() => {
initialToolbarItemIndexRef.current = void 0;
}, [clientId]);
const { stopTyping: stopTyping2 } = (0, import_data120.useDispatch)(store);
const isToolbarForcedRef = (0, import_element175.useRef)(false);
(0, import_keyboard_shortcuts9.useShortcut)("core/block-editor/focus-toolbar", () => {
isToolbarForcedRef.current = true;
stopTyping2(true);
});
(0, import_element175.useEffect)(() => {
isToolbarForcedRef.current = false;
});
const clientIdToPositionOver = capturingClientId || clientId;
const popoverProps3 = useBlockToolbarPopoverProps({
contentElement: __unstableContentRef?.current,
clientId: clientIdToPositionOver
});
return !isTyping3 && /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(
PrivateBlockPopover,
{
clientId: clientIdToPositionOver,
bottomClientId: lastClientId,
className: clsx_default("block-editor-block-list__block-popover", {
"is-insertion-point-visible": isInsertionPointVisible
}),
resize: false,
...popoverProps3,
__unstableContentRef,
children: /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(
PrivateBlockToolbar,
{
focusOnMount: isToolbarForcedRef.current,
__experimentalInitialIndex: initialToolbarItemIndexRef.current,
__experimentalOnIndexChange: (index2) => {
initialToolbarItemIndexRef.current = index2;
},
variant: "toolbar"
}
)
}
);
}
// packages/block-editor/build-module/components/block-tools/zoom-out-mode-inserters.mjs
var import_data121 = __toESM(require_data(), 1);
var import_element176 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/block-tools/zoom-out-mode-inserter-button.mjs
var import_components114 = __toESM(require_components(), 1);
var import_i18n102 = __toESM(require_i18n(), 1);
var import_jsx_runtime316 = __toESM(require_jsx_runtime(), 1);
function ZoomOutModeInserterButton({ onClick }) {
return /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(
import_components114.Button,
{
variant: "primary",
icon: plus_default,
size: "compact",
className: clsx_default(
"block-editor-button-pattern-inserter__button",
"block-editor-block-tools__zoom-out-mode-inserter-button"
),
onClick,
label: (0, import_i18n102._x)(
"Add pattern",
"Generic label for pattern inserter button"
)
}
);
}
var zoom_out_mode_inserter_button_default = ZoomOutModeInserterButton;
// packages/block-editor/build-module/components/block-tools/zoom-out-mode-inserters.mjs
var import_jsx_runtime317 = __toESM(require_jsx_runtime(), 1);
function ZoomOutModeInserters() {
const [isReady, setIsReady] = (0, import_element176.useState)(false);
const {
hasSelection,
blockOrder,
setInserterIsOpened,
sectionRootClientId,
selectedBlockClientId,
blockInsertionPoint,
insertionPointVisible
} = (0, import_data121.useSelect)((select3) => {
const {
getSettings: getSettings7,
getBlockOrder: getBlockOrder2,
getSelectionStart: getSelectionStart2,
getSelectedBlockClientId: getSelectedBlockClientId2,
getSectionRootClientId: getSectionRootClientId2,
getBlockInsertionPoint: getBlockInsertionPoint2,
isBlockInsertionPointVisible: isBlockInsertionPointVisible2
} = unlock(select3(store));
const root = getSectionRootClientId2();
return {
hasSelection: !!getSelectionStart2().clientId,
blockOrder: getBlockOrder2(root),
sectionRootClientId: root,
setInserterIsOpened: getSettings7().__experimentalSetIsInserterOpened,
selectedBlockClientId: getSelectedBlockClientId2(),
blockInsertionPoint: getBlockInsertionPoint2(),
insertionPointVisible: isBlockInsertionPointVisible2()
};
}, []);
const { showInsertionPoint: showInsertionPoint2 } = unlock((0, import_data121.useDispatch)(store));
(0, import_element176.useEffect)(() => {
const timeout = setTimeout(() => {
setIsReady(true);
}, 500);
return () => {
clearTimeout(timeout);
};
}, []);
if (!isReady || !hasSelection) {
return null;
}
const previousClientId = selectedBlockClientId;
const index2 = blockOrder.findIndex(
(clientId) => selectedBlockClientId === clientId
);
const insertionIndex = index2 + 1;
const nextClientId = blockOrder[insertionIndex];
if (insertionPointVisible && blockInsertionPoint?.index === insertionIndex) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime317.jsx)(
inbetween_default,
{
previousClientId,
nextClientId,
children: /* @__PURE__ */ (0, import_jsx_runtime317.jsx)(
zoom_out_mode_inserter_button_default,
{
onClick: () => {
setInserterIsOpened({
rootClientId: sectionRootClientId,
insertionIndex,
tab: "patterns",
category: "all"
});
showInsertionPoint2(sectionRootClientId, insertionIndex, {
operation: "insert"
});
}
}
)
}
);
}
var zoom_out_mode_inserters_default = ZoomOutModeInserters;
// packages/block-editor/build-module/components/block-tools/use-show-block-tools.mjs
var import_data122 = __toESM(require_data(), 1);
var import_blocks76 = __toESM(require_blocks(), 1);
function useShowBlockTools() {
return (0, import_data122.useSelect)((select3) => {
const {
getSelectedBlockClientId: getSelectedBlockClientId2,
getFirstMultiSelectedBlockClientId: getFirstMultiSelectedBlockClientId2,
getBlock: getBlock2,
getBlockMode: getBlockMode2,
getSettings: getSettings7,
isTyping: isTyping3,
isBlockInterfaceHidden: isBlockInterfaceHidden3
} = unlock(select3(store));
const clientId = getSelectedBlockClientId2() || getFirstMultiSelectedBlockClientId2();
const block = getBlock2(clientId);
const hasSelectedBlock2 = !!clientId && !!block;
const isEmptyDefaultBlock = hasSelectedBlock2 && (0, import_blocks76.isUnmodifiedDefaultBlock)(block, "content") && getBlockMode2(clientId) !== "html";
const _showEmptyBlockSideInserter = clientId && !isTyping3() && isEmptyDefaultBlock;
const _showBlockToolbarPopover = !isBlockInterfaceHidden3() && !getSettings7().hasFixedToolbar && !_showEmptyBlockSideInserter && hasSelectedBlock2 && !isEmptyDefaultBlock;
return {
showEmptyBlockSideInserter: _showEmptyBlockSideInserter,
showBlockToolbarPopover: _showBlockToolbarPopover
};
}, []);
}
// packages/block-editor/build-module/components/block-tools/index.mjs
var import_jsx_runtime318 = __toESM(require_jsx_runtime(), 1);
function selector2(select3) {
const {
getSelectedBlockClientId: getSelectedBlockClientId2,
getFirstMultiSelectedBlockClientId: getFirstMultiSelectedBlockClientId2,
getSettings: getSettings7,
isTyping: isTyping3,
isDragging: isDragging3,
isZoomOut: isZoomOut2,
getViewportModalClientIds: getViewportModalClientIds2
} = unlock(select3(store));
const clientId = getSelectedBlockClientId2() || getFirstMultiSelectedBlockClientId2();
return {
clientId,
hasFixedToolbar: getSettings7().hasFixedToolbar,
isTyping: isTyping3(),
isZoomOutMode: isZoomOut2(),
isDragging: isDragging3(),
viewportModalClientIds: getViewportModalClientIds2(),
blockVisibilitySetting: select3(store).getSettings().__experimentalFeatures?.blockVisibility?.allowEditing
};
}
function BlockTools({
children,
__unstableContentRef,
...props
}) {
const {
clientId,
hasFixedToolbar,
isTyping: isTyping3,
isZoomOutMode,
isDragging: isDragging3,
viewportModalClientIds: viewportModalClientIds2,
blockVisibilitySetting
} = (0, import_data123.useSelect)(selector2, []);
const isMatch = (0, import_keyboard_shortcuts10.__unstableUseShortcutEventMatch)();
const {
getBlocksByClientId: getBlocksByClientId2,
getSelectedBlockClientIds: getSelectedBlockClientIds2,
getBlockRootClientId: getBlockRootClientId2,
getBlockEditingMode: getBlockEditingMode2,
getBlockName: getBlockName2,
isGroupable: isGroupable2,
getEditedContentOnlySection: getEditedContentOnlySection2,
canEditBlock: canEditBlock2
} = unlock((0, import_data123.useSelect)(store));
const { getGroupingBlockName } = (0, import_data123.useSelect)(import_blocks77.store);
const { showEmptyBlockSideInserter, showBlockToolbarPopover } = useShowBlockTools();
const pasteStyles = usePasteStyles();
const [renamingBlockClientId, setRenamingBlockClientId] = (0, import_element177.useState)(null);
const { canRename } = useBlockRename(
getBlockName2(getSelectedBlockClientIds2()[0])
);
const {
duplicateBlocks: duplicateBlocks2,
removeBlocks: removeBlocks2,
replaceBlocks: replaceBlocks2,
insertAfterBlock: insertAfterBlock2,
insertBeforeBlock: insertBeforeBlock2,
selectBlock: selectBlock2,
moveBlocksUp: moveBlocksUp2,
moveBlocksDown: moveBlocksDown2,
expandBlock: expandBlock2,
stopEditingContentOnlySection: stopEditingContentOnlySection2,
showViewportModal: showViewportModal2,
hideViewportModal: hideViewportModal2
} = unlock((0, import_data123.useDispatch)(store));
function onKeyDown(event) {
if (event.defaultPrevented) {
return;
}
if (isMatch("core/block-editor/move-up", event) || isMatch("core/block-editor/move-down", event)) {
const clientIds = getSelectedBlockClientIds2();
if (clientIds.length) {
event.preventDefault();
const rootClientId = getBlockRootClientId2(clientIds[0]);
const direction = isMatch("core/block-editor/move-up", event) ? "up" : "down";
if (direction === "up") {
moveBlocksUp2(clientIds, rootClientId);
} else {
moveBlocksDown2(clientIds, rootClientId);
}
const blockLength = Array.isArray(clientIds) ? clientIds.length : 1;
const message2 = (0, import_i18n103.sprintf)(
// translators: %d: the name of the block that has been moved
(0, import_i18n103._n)(
"%d block moved.",
"%d blocks moved.",
clientIds.length
),
blockLength
);
(0, import_a11y12.speak)(message2);
}
} else if (isMatch("core/block-editor/duplicate", event)) {
const clientIds = getSelectedBlockClientIds2();
if (clientIds.length) {
event.preventDefault();
duplicateBlocks2(clientIds);
}
} else if (isMatch("core/block-editor/remove", event)) {
const clientIds = getSelectedBlockClientIds2();
if (clientIds.length) {
event.preventDefault();
removeBlocks2(clientIds);
}
} else if (isMatch("core/block-editor/paste-styles", event)) {
const clientIds = getSelectedBlockClientIds2();
if (clientIds.length) {
event.preventDefault();
const blocks2 = getBlocksByClientId2(clientIds);
pasteStyles(blocks2);
}
} else if (isMatch("core/block-editor/insert-after", event)) {
const clientIds = getSelectedBlockClientIds2();
if (clientIds.length) {
event.preventDefault();
insertAfterBlock2(clientIds[clientIds.length - 1]);
}
} else if (isMatch("core/block-editor/insert-before", event)) {
const clientIds = getSelectedBlockClientIds2();
if (clientIds.length) {
event.preventDefault();
insertBeforeBlock2(clientIds[0]);
}
} else if (isMatch("core/block-editor/unselect", event)) {
if (event.target.closest("[role=toolbar]")) {
return;
}
const clientIds = getSelectedBlockClientIds2();
if (clientIds.length > 1) {
event.preventDefault();
selectBlock2(clientIds[0]);
}
} else if (isMatch("core/block-editor/collapse-list-view", event)) {
if ((0, import_dom59.isTextField)(event.target) || (0, import_dom59.isTextField)(
event.target?.contentWindow?.document?.activeElement
)) {
return;
}
event.preventDefault();
expandBlock2(clientId);
} else if (isMatch("core/block-editor/group", event)) {
const clientIds = getSelectedBlockClientIds2();
if (clientIds.length > 1 && isGroupable2(clientIds)) {
event.preventDefault();
const blocks2 = getBlocksByClientId2(clientIds);
const groupingBlockName = getGroupingBlockName();
const newBlocks = (0, import_blocks77.switchToBlockType)(
blocks2,
groupingBlockName
);
replaceBlocks2(clientIds, newBlocks);
(0, import_a11y12.speak)((0, import_i18n103.__)("Selected blocks are grouped."));
}
} else if (isMatch("core/block-editor/rename", event)) {
const clientIds = getSelectedBlockClientIds2();
if (clientIds.length === 1) {
const isContentOnly = getBlockEditingMode2(clientIds[0]) === "contentOnly";
const canRenameBlock = canRename && !isContentOnly && canEditBlock2(clientIds[0]);
if (canRenameBlock) {
event.preventDefault();
setRenamingBlockClientId(clientIds[0]);
}
}
} else if (isMatch("core/block-editor/toggle-block-visibility", event)) {
if (blockVisibilitySetting === false) {
return;
}
const clientIds = getSelectedBlockClientIds2();
if (clientIds.length) {
event.preventDefault();
const blocks2 = getBlocksByClientId2(clientIds);
const supportsBlockVisibility = blocks2.every(
(block) => (0, import_blocks77.hasBlockSupport)(block.name, "visibility", true)
);
if (!supportsBlockVisibility) {
return;
}
if (clientIds.some(
(id) => getBlockEditingMode2(id) !== "default" || !canEditBlock2(id)
)) {
return;
}
showViewportModal2(clientIds);
}
}
if (isMatch("core/block-editor/stop-editing-as-blocks", event)) {
if (getEditedContentOnlySection2()) {
stopEditingContentOnlySection2();
}
}
}
const blockToolbarRef = use_popover_scroll_default(__unstableContentRef);
const blockToolbarAfterRef = use_popover_scroll_default(__unstableContentRef);
return (
// eslint-disable-next-line jsx-a11y/no-static-element-interactions
/* @__PURE__ */ (0, import_jsx_runtime318.jsxs)(
"div",
{
...props,
onKeyDown,
className: clsx_default(props.className, {
"block-editor-block-tools--is-dragging": isDragging3
}),
children: [
/* @__PURE__ */ (0, import_jsx_runtime318.jsxs)(InsertionPointOpenRef.Provider, { value: (0, import_element177.useRef)(false), children: [
!isTyping3 && !isZoomOutMode && /* @__PURE__ */ (0, import_jsx_runtime318.jsx)(
InsertionPoint,
{
__unstableContentRef
}
),
showEmptyBlockSideInserter && /* @__PURE__ */ (0, import_jsx_runtime318.jsx)(
EmptyBlockInserter,
{
__unstableContentRef,
clientId
}
),
showBlockToolbarPopover && /* @__PURE__ */ (0, import_jsx_runtime318.jsx)(
BlockToolbarPopover,
{
__unstableContentRef,
clientId,
isTyping: isTyping3
}
),
!isZoomOutMode && !hasFixedToolbar && /* @__PURE__ */ (0, import_jsx_runtime318.jsx)(
import_components115.Popover.Slot,
{
name: "block-toolbar",
ref: blockToolbarRef
}
),
children,
/* @__PURE__ */ (0, import_jsx_runtime318.jsx)(
import_components115.Popover.Slot,
{
name: "__unstable-block-tools-after",
ref: blockToolbarAfterRef
}
),
isZoomOutMode && !isDragging3 && /* @__PURE__ */ (0, import_jsx_runtime318.jsx)(
zoom_out_mode_inserters_default,
{
__unstableContentRef
}
)
] }),
renamingBlockClientId && /* @__PURE__ */ (0, import_jsx_runtime318.jsx)(
BlockRenameModal,
{
clientId: renamingBlockClientId,
onClose: () => setRenamingBlockClientId(null)
}
),
viewportModalClientIds2 && /* @__PURE__ */ (0, import_jsx_runtime318.jsx)(
BlockVisibilityModal,
{
clientIds: viewportModalClientIds2,
onClose: hideViewportModal2
}
)
]
}
)
);
}
// packages/block-editor/build-module/components/observe-typing/index.mjs
var import_compose68 = __toESM(require_compose(), 1);
var import_data124 = __toESM(require_data(), 1);
var import_dom60 = __toESM(require_dom(), 1);
var import_keycodes13 = __toESM(require_keycodes(), 1);
var import_jsx_runtime319 = __toESM(require_jsx_runtime(), 1);
var KEY_DOWN_ELIGIBLE_KEY_CODES = /* @__PURE__ */ new Set([
import_keycodes13.UP,
import_keycodes13.RIGHT,
import_keycodes13.DOWN,
import_keycodes13.LEFT,
import_keycodes13.ENTER,
import_keycodes13.BACKSPACE
]);
function isKeyDownEligibleForStartTyping(event) {
const { keyCode, shiftKey } = event;
return !shiftKey && KEY_DOWN_ELIGIBLE_KEY_CODES.has(keyCode);
}
function useMouseMoveTypingReset() {
const isTyping3 = (0, import_data124.useSelect)(
(select3) => select3(store).isTyping(),
[]
);
const { stopTyping: stopTyping2 } = (0, import_data124.useDispatch)(store);
return (0, import_compose68.useRefEffect)(
(node) => {
if (!isTyping3) {
return;
}
const { ownerDocument: ownerDocument2 } = node;
let lastClientX;
let lastClientY;
function stopTypingOnMouseMove(event) {
const { clientX, clientY } = event;
if (lastClientX && lastClientY && (lastClientX !== clientX || lastClientY !== clientY)) {
stopTyping2();
}
lastClientX = clientX;
lastClientY = clientY;
}
ownerDocument2.addEventListener(
"mousemove",
stopTypingOnMouseMove
);
return () => {
ownerDocument2.removeEventListener(
"mousemove",
stopTypingOnMouseMove
);
};
},
[isTyping3, stopTyping2]
);
}
function useTypingObserver() {
const isTyping3 = (0, import_data124.useSelect)(
(select3) => select3(store).isTyping(),
[]
);
const { startTyping: startTyping2, stopTyping: stopTyping2 } = (0, import_data124.useDispatch)(store);
const ref1 = useMouseMoveTypingReset();
const ref2 = (0, import_compose68.useRefEffect)(
(node) => {
if (isTyping3) {
let stopTypingOnNonTextField2 = function(event) {
const { target } = event;
timerId = defaultView.setTimeout(() => {
if (!(0, import_dom60.isTextField)(target)) {
stopTyping2();
}
});
}, stopTypingOnEscapeKey2 = function(event) {
const { keyCode } = event;
if (keyCode === import_keycodes13.ESCAPE || keyCode === import_keycodes13.TAB) {
stopTyping2();
}
}, stopTypingOnSelectionUncollapse2 = function() {
const selection2 = defaultView.getSelection();
if (!selection2.isCollapsed) {
stopTyping2();
}
};
var stopTypingOnNonTextField = stopTypingOnNonTextField2, stopTypingOnEscapeKey = stopTypingOnEscapeKey2, stopTypingOnSelectionUncollapse = stopTypingOnSelectionUncollapse2;
let timerId;
const { defaultView } = node.ownerDocument;
node.addEventListener("focus", stopTypingOnNonTextField2);
node.addEventListener("keydown", stopTypingOnEscapeKey2);
node.ownerDocument.addEventListener(
"selectionchange",
stopTypingOnSelectionUncollapse2
);
return () => {
defaultView.clearTimeout(timerId);
node.removeEventListener(
"focus",
stopTypingOnNonTextField2
);
node.removeEventListener(
"keydown",
stopTypingOnEscapeKey2
);
node.ownerDocument.removeEventListener(
"selectionchange",
stopTypingOnSelectionUncollapse2
);
};
}
function startTypingInTextField(event) {
const { type, target } = event;
if (!(0, import_dom60.isTextField)(target) || !node.contains(target)) {
return;
}
if (type === "keydown" && !isKeyDownEligibleForStartTyping(event)) {
return;
}
startTyping2();
}
node.addEventListener("keypress", startTypingInTextField);
node.addEventListener("keydown", startTypingInTextField);
return () => {
node.removeEventListener("keypress", startTypingInTextField);
node.removeEventListener("keydown", startTypingInTextField);
};
},
[isTyping3, startTyping2, stopTyping2]
);
return (0, import_compose68.useMergeRefs)([ref1, ref2]);
}
function ObserveTyping({ children }) {
return /* @__PURE__ */ (0, import_jsx_runtime319.jsx)("div", { ref: useTypingObserver(), children });
}
var observe_typing_default = ObserveTyping;
// packages/block-editor/build-module/components/use-block-commands/index.mjs
var import_i18n104 = __toESM(require_i18n(), 1);
var import_blocks78 = __toESM(require_blocks(), 1);
var import_data125 = __toESM(require_data(), 1);
var import_commands = __toESM(require_commands(), 1);
var getTransformCommands = () => function useTransformCommands() {
const { replaceBlocks: replaceBlocks2, multiSelect: multiSelect2 } = (0, import_data125.useDispatch)(store);
const {
blocks: blocks2,
clientIds,
canRemove,
possibleBlockTransformations,
invalidSelection
} = (0, import_data125.useSelect)((select3) => {
const {
getBlockRootClientId: getBlockRootClientId2,
getBlockTransformItems: getBlockTransformItems2,
getSelectedBlockClientIds: getSelectedBlockClientIds2,
getBlocksByClientId: getBlocksByClientId2,
canRemoveBlocks: canRemoveBlocks2
} = select3(store);
const selectedBlockClientIds = getSelectedBlockClientIds2();
const selectedBlocks = getBlocksByClientId2(
selectedBlockClientIds
);
if (selectedBlocks.filter((block) => !block).length > 0) {
return {
invalidSelection: true
};
}
const rootClientId = getBlockRootClientId2(
selectedBlockClientIds[0]
);
return {
blocks: selectedBlocks,
clientIds: selectedBlockClientIds,
possibleBlockTransformations: getBlockTransformItems2(
selectedBlocks,
rootClientId
),
canRemove: canRemoveBlocks2(selectedBlockClientIds),
invalidSelection: false
};
}, []);
if (invalidSelection) {
return {
isLoading: false,
commands: []
};
}
const isTemplate = blocks2.length === 1 && (0, import_blocks78.isTemplatePart)(blocks2[0]);
function selectForMultipleBlocks(insertedBlocks) {
if (insertedBlocks.length > 1) {
multiSelect2(
insertedBlocks[0].clientId,
insertedBlocks[insertedBlocks.length - 1].clientId
);
}
}
function onBlockTransform(name, variationName) {
const newBlocks = (0, import_blocks78.switchToBlockType)(blocks2, name, variationName);
replaceBlocks2(clientIds, newBlocks);
selectForMultipleBlocks(newBlocks);
}
const hasPossibleBlockTransformations = !!possibleBlockTransformations.length && canRemove && !isTemplate;
if (!clientIds || clientIds.length < 1 || !hasPossibleBlockTransformations) {
return { isLoading: false, commands: [] };
}
const commands = possibleBlockTransformations.map(
(transformation) => {
const { id, name, title, icon, variationName } = transformation;
const blockIcon = !icon?.src || icon?.src === "block-default" ? {
src: block_default_default
} : icon;
return {
name: "core/block-editor/transform-to-" + (id || name).replace(/\//g, "-"),
/* translators: %s: Block or block variation name. */
label: (0, import_i18n104.sprintf)((0, import_i18n104.__)("Transform to %s"), title),
icon: blockIcon?.src,
category: "command",
callback: ({ close }) => {
onBlockTransform(name, variationName);
close();
}
};
}
);
return { isLoading: false, commands };
};
var getQuickActionsCommands = () => function useQuickActionsCommands() {
const {
clientIds,
isUngroupable: isUngroupable2,
isGroupable: isGroupable2,
blockVisibilitySetting
} = (0, import_data125.useSelect)((select3) => {
const {
getSelectedBlockClientIds: getSelectedBlockClientIds2,
getSettings: getSettings7,
isUngroupable: _isUngroupable,
isGroupable: _isGroupable
} = select3(store);
const selectedBlockClientIds = getSelectedBlockClientIds2();
return {
clientIds: selectedBlockClientIds,
isUngroupable: _isUngroupable(),
isGroupable: _isGroupable(),
blockVisibilitySetting: getSettings7().__experimentalFeatures?.blockVisibility?.allowEditing
};
}, []);
const {
canInsertBlockType: canInsertBlockType2,
getBlockRootClientId: getBlockRootClientId2,
getBlocksByClientId: getBlocksByClientId2,
canRemoveBlocks: canRemoveBlocks2,
isBlockHiddenAnywhere: isBlockHiddenAnywhere2
} = unlock((0, import_data125.useSelect)(store));
const { getBlockEditingMode: getBlockEditingMode2 } = (0, import_data125.useSelect)(store);
const { getDefaultBlockName: getDefaultBlockName8, getGroupingBlockName } = (0, import_data125.useSelect)(import_blocks78.store);
const blocks2 = getBlocksByClientId2(clientIds);
const blockEditorDispatch = (0, import_data125.useDispatch)(store);
const {
removeBlocks: removeBlocks2,
replaceBlocks: replaceBlocks2,
duplicateBlocks: duplicateBlocks2,
insertAfterBlock: insertAfterBlock2,
insertBeforeBlock: insertBeforeBlock2
} = blockEditorDispatch;
const onGroup = () => {
if (!blocks2.length) {
return;
}
const groupingBlockName = getGroupingBlockName();
const newBlocks = (0, import_blocks78.switchToBlockType)(blocks2, groupingBlockName);
if (!newBlocks) {
return;
}
replaceBlocks2(clientIds, newBlocks);
};
const onUngroup = () => {
if (!blocks2.length) {
return;
}
const innerBlocks = blocks2[0].innerBlocks;
if (!innerBlocks.length) {
return;
}
replaceBlocks2(clientIds, innerBlocks);
};
if (!clientIds || clientIds.length < 1) {
return { isLoading: false, commands: [] };
}
const { showViewportModal: showViewportModal2 } = unlock(blockEditorDispatch);
const rootClientId = getBlockRootClientId2(clientIds[0]);
const canInsertDefaultBlock = canInsertBlockType2(
getDefaultBlockName8(),
rootClientId
);
const canDuplicate = blocks2.every((block) => {
return !!block && (0, import_blocks78.hasBlockSupport)(block.name, "multiple", true) && canInsertBlockType2(block.name, rootClientId);
});
const canRemove = canRemoveBlocks2(clientIds);
const commands = [];
if (canDuplicate) {
commands.push({
name: "duplicate",
label: (0, import_i18n104.__)("Duplicate"),
callback: () => duplicateBlocks2(clientIds, true),
icon: copy_default
});
}
if (canInsertDefaultBlock) {
commands.push(
{
name: "add-before",
label: (0, import_i18n104.__)("Add before"),
callback: () => {
const clientId = Array.isArray(clientIds) ? clientIds[0] : clientId;
insertBeforeBlock2(clientId);
},
icon: plus_default
},
{
name: "add-after",
label: (0, import_i18n104.__)("Add after"),
callback: () => {
const clientId = Array.isArray(clientIds) ? clientIds[clientIds.length - 1] : clientId;
insertAfterBlock2(clientId);
},
icon: plus_default
}
);
}
if (isGroupable2) {
commands.push({
name: "Group",
label: (0, import_i18n104.__)("Group"),
callback: onGroup,
icon: group_default
});
}
if (isUngroupable2) {
commands.push({
name: "ungroup",
label: (0, import_i18n104.__)("Ungroup"),
callback: onUngroup,
icon: ungroup_default
});
}
if (canRemove) {
commands.push({
name: "remove",
label: (0, import_i18n104.__)("Delete"),
callback: () => removeBlocks2(clientIds, true),
icon: trash_default
});
}
const supportsVisibility = blocks2.every(
(block) => !!block && (0, import_blocks78.hasBlockSupport)(block.name, "visibility", true)
);
const allBlocksDefaultMode = clientIds.every(
(id) => getBlockEditingMode2(id) === "default"
);
if (supportsVisibility && allBlocksDefaultMode && blockVisibilitySetting !== false) {
const hasHiddenBlock = clientIds.some(
(id) => isBlockHiddenAnywhere2(id)
);
commands.push({
name: "toggle-visibility",
label: hasHiddenBlock ? (0, import_i18n104.__)("Show") : (0, import_i18n104.__)("Hide"),
callback: () => showViewportModal2(clientIds),
icon: hasHiddenBlock ? seen_default : unseen_default
});
}
return {
isLoading: false,
commands: commands.map((command) => ({
...command,
name: "core/block-editor/action-" + command.name,
category: "command",
callback: ({ close }) => {
command.callback();
close();
}
}))
};
};
var useBlockCommands = () => {
(0, import_commands.useCommandLoader)({
name: "core/block-editor/blockTransforms",
hook: getTransformCommands()
});
(0, import_commands.useCommandLoader)({
name: "core/block-editor/blockQuickActions",
hook: getQuickActionsCommands(),
context: "block-selection-edit"
});
};
// packages/block-editor/build-module/components/block-canvas/index.mjs
var import_jsx_runtime320 = __toESM(require_jsx_runtime(), 1);
var BlockCanvasCover = (0, import_components116.createSlotFill)(/* @__PURE__ */ Symbol("BlockCanvasCover"));
function BlockCanvasCoverWrapper({ children }) {
return /* @__PURE__ */ (0, import_jsx_runtime320.jsx)(
"div",
{
className: "block-canvas-cover",
style: {
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: "100%",
pointerEvents: "none"
},
children
}
);
}
var EDITOR_STYLE_TRANSFORM_OPTIONS = {
// Don't transform selectors that already specify `.editor-styles-wrapper`.
ignoredSelectors: [/\.editor-styles-wrapper/gi]
};
function ExperimentalBlockCanvas({
shouldIframe = true,
height = "300px",
children = /* @__PURE__ */ (0, import_jsx_runtime320.jsx)(BlockList, {}),
styles,
contentRef: contentRefProp,
iframeProps
}) {
useBlockCommands();
const isTabletViewport = (0, import_compose69.useViewportMatch)("medium", "<");
const resetTypingRef = useMouseMoveTypingReset();
const clearerRef = useBlockSelectionClearer();
const localRef = (0, import_element178.useRef)();
const contentRef = (0, import_compose69.useMergeRefs)([
contentRefProp,
clearerRef,
localRef,
useTypingObserver()
]);
const zoomLevel2 = (0, import_data126.useSelect)(
(select3) => unlock(select3(store)).getZoomLevel(),
[]
);
const zoomOutIframeProps = zoomLevel2 !== 100 && !isTabletViewport ? {
scale: zoomLevel2,
frameSize: "40px"
} : {};
if (!shouldIframe) {
return /* @__PURE__ */ (0, import_jsx_runtime320.jsxs)(
BlockTools,
{
__unstableContentRef: localRef,
style: { height, display: "flex" },
children: [
/* @__PURE__ */ (0, import_jsx_runtime320.jsx)(BlockCanvasCover.Slot, { fillProps: { containerRef: localRef }, children: (covers) => covers.map((cover, index2) => /* @__PURE__ */ (0, import_jsx_runtime320.jsx)(BlockCanvasCoverWrapper, { children: cover }, index2)) }),
/* @__PURE__ */ (0, import_jsx_runtime320.jsx)(
editor_styles_default,
{
styles,
scope: ":where(.editor-styles-wrapper)",
transformOptions: EDITOR_STYLE_TRANSFORM_OPTIONS
}
),
/* @__PURE__ */ (0, import_jsx_runtime320.jsx)(
writing_flow_default,
{
ref: contentRef,
className: "editor-styles-wrapper",
tabIndex: -1,
style: {
height: "100%",
width: "100%",
overflow: "auto"
},
children
}
)
]
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime320.jsx)(
BlockTools,
{
__unstableContentRef: localRef,
style: { height, display: "flex" },
children: /* @__PURE__ */ (0, import_jsx_runtime320.jsxs)(
iframe_default,
{
...iframeProps,
...zoomOutIframeProps,
ref: resetTypingRef,
contentRef,
style: {
...iframeProps?.style
},
name: "editor-canvas",
children: [
/* @__PURE__ */ (0, import_jsx_runtime320.jsx)(BlockCanvasCover.Slot, { fillProps: { containerRef: localRef }, children: (covers) => covers.map((cover, index2) => /* @__PURE__ */ (0, import_jsx_runtime320.jsx)(BlockCanvasCoverWrapper, { children: cover }, index2)) }),
/* @__PURE__ */ (0, import_jsx_runtime320.jsx)(editor_styles_default, { styles }),
children
]
}
)
}
);
}
function BlockCanvas({ children, height, styles }) {
return /* @__PURE__ */ (0, import_jsx_runtime320.jsx)(ExperimentalBlockCanvas, { height, styles, children });
}
var block_canvas_default = BlockCanvas;
// packages/block-editor/build-module/components/color-style-selector/index.mjs
var import_components117 = __toESM(require_components(), 1);
var import_i18n105 = __toESM(require_i18n(), 1);
var import_keycodes14 = __toESM(require_keycodes(), 1);
var import_deprecated13 = __toESM(require_deprecated(), 1);
var import_jsx_runtime321 = __toESM(require_jsx_runtime(), 1);
var ColorSelectorSVGIcon = () => /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(import_components117.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", children: /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(import_components117.Path, { d: "M7.434 5l3.18 9.16H8.538l-.692-2.184H4.628l-.705 2.184H2L5.18 5h2.254zm-1.13 1.904h-.115l-1.148 3.593H7.44L6.304 6.904zM14.348 7.006c1.853 0 2.9.876 2.9 2.374v4.78h-1.79v-.914h-.114c-.362.64-1.123 1.022-2.031 1.022-1.346 0-2.292-.826-2.292-2.108 0-1.27.972-2.006 2.71-2.107l1.696-.102V9.38c0-.584-.42-.914-1.18-.914-.667 0-1.112.228-1.264.647h-1.701c.12-1.295 1.307-2.107 3.066-2.107zm1.079 4.1l-1.416.09c-.793.056-1.18.342-1.18.844 0 .52.45.837 1.091.837.857 0 1.505-.545 1.505-1.256v-.515z" }) });
var ColorSelectorIcon = ({ style, className }) => {
return /* @__PURE__ */ (0, import_jsx_runtime321.jsx)("div", { className: "block-library-colors-selector__icon-container", children: /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
"div",
{
className: `${className} block-library-colors-selector__state-selection`,
style,
children: /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(ColorSelectorSVGIcon, {})
}
) });
};
var renderToggleComponent = ({ TextColor, BackgroundColor }) => function ToggleComponent({ onToggle, isOpen }) {
const openOnArrowDown = (event) => {
if (!isOpen && event.keyCode === import_keycodes14.DOWN) {
event.preventDefault();
onToggle();
}
};
return /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(import_components117.ToolbarGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
import_components117.ToolbarButton,
{
className: "components-toolbar__control block-library-colors-selector__toggle",
label: (0, import_i18n105.__)("Open Colors Selector"),
onClick: onToggle,
onKeyDown: openOnArrowDown,
icon: /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(BackgroundColor, { children: /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(TextColor, { children: /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(ColorSelectorIcon, {}) }) })
}
) });
};
var BlockColorsStyleSelector = ({ children, ...other }) => {
(0, import_deprecated13.default)(`wp.blockEditor.BlockColorsStyleSelector`, {
alternative: "block supports API",
since: "6.1",
version: "6.3"
});
return /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
import_components117.Dropdown,
{
popoverProps: { placement: "bottom-start" },
className: "block-library-colors-selector",
contentClassName: "block-library-colors-selector__popover",
renderToggle: renderToggleComponent(other),
renderContent: () => children
}
);
};
var color_style_selector_default = BlockColorsStyleSelector;
// packages/block-editor/build-module/components/block-navigation/dropdown.mjs
var import_deprecated15 = __toESM(require_deprecated(), 1);
var import_components124 = __toESM(require_components(), 1);
var import_i18n114 = __toESM(require_i18n(), 1);
var import_data138 = __toESM(require_data(), 1);
var import_element196 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/list-view/index.mjs
var import_compose75 = __toESM(require_compose(), 1);
var import_components123 = __toESM(require_components(), 1);
var import_data137 = __toESM(require_data(), 1);
var import_deprecated14 = __toESM(require_deprecated(), 1);
var import_element195 = __toESM(require_element(), 1);
var import_i18n113 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/list-view/branch.mjs
var import_components121 = __toESM(require_components(), 1);
var import_element188 = __toESM(require_element(), 1);
var import_data130 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/list-view/appender.mjs
var import_compose70 = __toESM(require_compose(), 1);
var import_a11y13 = __toESM(require_a11y(), 1);
var import_data127 = __toESM(require_data(), 1);
var import_element181 = __toESM(require_element(), 1);
var import_i18n106 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/list-view/context.mjs
var import_element179 = __toESM(require_element(), 1);
var ListViewContext = (0, import_element179.createContext)({});
ListViewContext.displayName = "ListViewContext";
var useListViewContext = () => (0, import_element179.useContext)(ListViewContext);
// packages/block-editor/build-module/components/list-view/aria-referenced-text.mjs
var import_element180 = __toESM(require_element(), 1);
var import_jsx_runtime322 = __toESM(require_jsx_runtime(), 1);
function AriaReferencedText({ children, ...props }) {
const ref = (0, import_element180.useRef)();
(0, import_element180.useEffect)(() => {
if (ref.current) {
ref.current.textContent = ref.current.textContent;
}
}, [children]);
return /* @__PURE__ */ (0, import_jsx_runtime322.jsx)("div", { hidden: true, ...props, ref, children });
}
// packages/block-editor/build-module/components/list-view/appender.mjs
var import_jsx_runtime323 = __toESM(require_jsx_runtime(), 1);
var Appender = (0, import_element181.forwardRef)(
({ nestingLevel, blockCount, clientId, ...props }, ref) => {
const { insertedBlock, setInsertedBlock } = useListViewContext();
const instanceId = (0, import_compose70.useInstanceId)(Appender);
const { directInsert, hideInserter } = (0, import_data127.useSelect)(
(select3) => {
const { getBlockListSettings: getBlockListSettings2, getTemplateLock: getTemplateLock2, isZoomOut: isZoomOut2 } = unlock(select3(store));
const settings2 = getBlockListSettings2(clientId);
const directInsertValue = settings2?.directInsert || false;
const hideInserterValue = !!getTemplateLock2(clientId) || isZoomOut2();
return {
directInsert: directInsertValue,
hideInserter: hideInserterValue
};
},
[clientId]
);
const blockTitle = useBlockDisplayTitle({
clientId,
context: "list-view"
});
const insertedBlockTitle = useBlockDisplayTitle({
clientId: insertedBlock?.clientId,
context: "list-view"
});
(0, import_element181.useEffect)(() => {
if (!insertedBlockTitle?.length) {
return;
}
(0, import_a11y13.speak)(
(0, import_i18n106.sprintf)(
// translators: %s: name of block being inserted (i.e. Paragraph, Image, Group etc)
(0, import_i18n106.__)("%s block inserted"),
insertedBlockTitle
),
"assertive"
);
}, [insertedBlockTitle]);
if (hideInserter) {
return null;
}
const descriptionId = `list-view-appender__${instanceId}`;
const description = (0, import_i18n106.sprintf)(
/* translators: 1: The name of the block. 2: The numerical position of the block. 3: The level of nesting for the block. */
(0, import_i18n106.__)("Append to %1$s block at position %2$d, Level %3$d"),
blockTitle,
blockCount + 1,
nestingLevel
);
return /* @__PURE__ */ (0, import_jsx_runtime323.jsxs)("div", { className: "list-view-appender", children: [
/* @__PURE__ */ (0, import_jsx_runtime323.jsx)(
inserter_default,
{
ref,
rootClientId: clientId,
position: "bottom right",
isAppender: true,
selectBlockOnInsert: false,
shouldDirectInsert: directInsert,
__experimentalIsQuick: true,
...props,
toggleProps: { "aria-describedby": descriptionId },
onSelectOrClose: (maybeInsertedBlock) => {
if (maybeInsertedBlock?.clientId) {
setInsertedBlock(maybeInsertedBlock);
}
}
}
),
/* @__PURE__ */ (0, import_jsx_runtime323.jsx)(AriaReferencedText, { id: descriptionId, children: description })
] });
}
);
// packages/block-editor/build-module/components/list-view/block.mjs
var import_blocks79 = __toESM(require_blocks(), 1);
var import_components120 = __toESM(require_components(), 1);
var import_compose72 = __toESM(require_compose(), 1);
var import_element187 = __toESM(require_element(), 1);
var import_data129 = __toESM(require_data(), 1);
var import_i18n109 = __toESM(require_i18n(), 1);
var import_keycodes16 = __toESM(require_keycodes(), 1);
var import_is_shallow_equal2 = __toESM(require_is_shallow_equal(), 1);
var import_keyboard_shortcuts11 = __toESM(require_keyboard_shortcuts(), 1);
var import_a11y14 = __toESM(require_a11y(), 1);
// packages/block-editor/build-module/components/list-view/leaf.mjs
var import_components118 = __toESM(require_components(), 1);
var import_compose71 = __toESM(require_compose(), 1);
var import_element182 = __toESM(require_element(), 1);
var import_jsx_runtime324 = __toESM(require_jsx_runtime(), 1);
var AnimatedTreeGridRow = animated(import_components118.__experimentalTreeGridRow);
var ListViewLeaf = (0, import_element182.forwardRef)(
({
isDragged,
isSelected,
position,
level,
rowCount,
children,
className,
path,
...props
}, ref) => {
const animationRef = use_moving_animation_default({
clientId: props["data-block"],
enableAnimation: true,
triggerAnimationOnChange: path
});
const mergedRef = (0, import_compose71.useMergeRefs)([ref, animationRef]);
return /* @__PURE__ */ (0, import_jsx_runtime324.jsx)(
AnimatedTreeGridRow,
{
ref: mergedRef,
className: clsx_default("block-editor-list-view-leaf", className),
level,
positionInSet: position,
setSize: rowCount,
isExpanded: void 0,
...props,
children
}
);
}
);
var leaf_default = ListViewLeaf;
// packages/block-editor/build-module/components/list-view/use-list-view-scroll-into-view.mjs
var import_dom61 = __toESM(require_dom(), 1);
var import_element183 = __toESM(require_element(), 1);
function useListViewScrollIntoView({
isSelected,
selectedClientIds,
rowItemRef
}) {
const isSingleSelection = selectedClientIds.length === 1;
(0, import_element183.useLayoutEffect)(() => {
if (!isSelected || !isSingleSelection || !rowItemRef.current) {
return;
}
const scrollContainer = (0, import_dom61.getScrollContainer)(rowItemRef.current);
const { ownerDocument: ownerDocument2 } = rowItemRef.current;
const windowScroll = scrollContainer === ownerDocument2.body || scrollContainer === ownerDocument2.documentElement;
if (windowScroll || !scrollContainer) {
return;
}
const rowRect = rowItemRef.current.getBoundingClientRect();
const scrollContainerRect = scrollContainer.getBoundingClientRect();
if (rowRect.top < scrollContainerRect.top || rowRect.bottom > scrollContainerRect.bottom) {
rowItemRef.current.scrollIntoView();
}
}, [isSelected, isSingleSelection, rowItemRef]);
}
// packages/block-editor/build-module/components/list-view/block-contents.mjs
var import_element186 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/list-view/block-select-button.mjs
var import_components119 = __toESM(require_components(), 1);
var import_element185 = __toESM(require_element(), 1);
var import_keycodes15 = __toESM(require_keycodes(), 1);
// packages/block-editor/build-module/components/list-view/expander.mjs
var import_i18n107 = __toESM(require_i18n(), 1);
var import_jsx_runtime325 = __toESM(require_jsx_runtime(), 1);
function ListViewExpander({ onClick }) {
return (
// Keyboard events are handled by TreeGrid see: components/src/tree-grid/index.js
//
// The expander component is implemented as a pseudo element in the w3 example
// https://www.w3.org/TR/wai-aria-practices/examples/treegrid/treegrid-1.html
//
// We've mimicked this by adding an icon with aria-hidden set to true to hide this from the accessibility tree.
// For the current tree grid implementation, please do not try to make this a button.
/* @__PURE__ */ (0, import_jsx_runtime325.jsx)(
"span",
{
className: "block-editor-list-view__expander",
onClick: onClick ? (event) => onClick(event, { forceToggle: true }) : void 0,
"aria-hidden": "true",
"data-testid": "list-view-expander",
children: /* @__PURE__ */ (0, import_jsx_runtime325.jsx)(icon_default, { icon: (0, import_i18n107.isRTL)() ? chevron_left_small_default : chevron_right_small_default })
}
)
);
}
// packages/block-editor/build-module/components/list-view/use-list-view-images.mjs
var import_element184 = __toESM(require_element(), 1);
var import_data128 = __toESM(require_data(), 1);
var MAX_IMAGES = 3;
var IMAGE_GETTERS = {
"core/image": ({ clientId, attributes }) => {
if (attributes.url) {
return {
url: attributes.url,
alt: attributes.alt || "",
clientId
};
}
},
"core/cover": ({ clientId, attributes }) => {
if (attributes.backgroundType === "image" && attributes.url) {
return {
url: attributes.url,
alt: attributes.alt || "",
clientId
};
}
},
"core/media-text": ({ clientId, attributes }) => {
if (attributes.mediaType === "image" && attributes.mediaUrl) {
return {
url: attributes.mediaUrl,
alt: attributes.mediaAlt || "",
clientId
};
}
},
"core/gallery": ({ innerBlocks }) => {
const images = [];
const getValues = !!innerBlocks?.length ? IMAGE_GETTERS[innerBlocks[0].name] : void 0;
if (!getValues) {
return images;
}
for (const innerBlock of innerBlocks) {
const img = getValues(innerBlock);
if (img) {
images.push(img);
}
if (images.length >= MAX_IMAGES) {
return images;
}
}
return images;
}
};
function getImagesFromBlock(block, isExpanded) {
const getImages = IMAGE_GETTERS[block.name];
const images = !!getImages ? getImages(block) : void 0;
if (!images) {
return [];
}
if (!Array.isArray(images)) {
return [images];
}
return isExpanded ? [] : images;
}
function useListViewImages({ clientId, isExpanded }) {
const { block } = (0, import_data128.useSelect)(
(select3) => {
return { block: select3(store).getBlock(clientId) };
},
[clientId]
);
const images = (0, import_element184.useMemo)(() => {
return getImagesFromBlock(block, isExpanded);
}, [block, isExpanded]);
return images;
}
// packages/block-editor/build-module/components/list-view/block-select-button.mjs
var import_jsx_runtime326 = __toESM(require_jsx_runtime(), 1);
var { Badge: WCBadge3 } = unlock(import_components119.privateApis);
function ListViewBlockSelectButton({
className,
block: { clientId },
onClick,
onContextMenu,
onMouseDown,
onToggleExpanded,
tabIndex,
onFocus,
onDragStart,
onDragEnd,
draggable,
isExpanded,
ariaDescribedBy,
visibilityLabel,
isDisabled = false
}, ref) {
const blockInformation = useBlockDisplayInformation(clientId);
const blockTitle = useBlockDisplayTitle({
clientId,
context: "list-view"
});
const { isLocked } = useBlockLock(clientId);
const shouldShowLockIcon = isLocked;
const isSticky = blockInformation?.positionType === "sticky";
const images = useListViewImages({ clientId, isExpanded });
const onDragStartHandler = (event) => {
event.dataTransfer.clearData();
onDragStart?.(event);
};
function onKeyDown(event) {
if (event.keyCode === import_keycodes15.ENTER || event.keyCode === import_keycodes15.SPACE) {
onClick(event);
}
}
return (
// Disabled list view items intentionally omit href so TreeGrid skips them.
// eslint-disable-next-line jsx-a11y/anchor-is-valid
/* @__PURE__ */ (0, import_jsx_runtime326.jsxs)(
"a",
{
className: clsx_default(
"block-editor-list-view-block-select-button",
className
),
onClick,
onContextMenu,
onKeyDown,
onMouseDown,
ref,
tabIndex,
onFocus,
onDragStart: onDragStartHandler,
onDragEnd,
draggable,
href: isDisabled ? void 0 : `#block-${clientId}`,
"aria-disabled": isDisabled ? true : void 0,
"aria-describedby": ariaDescribedBy,
"aria-expanded": isExpanded,
children: [
/* @__PURE__ */ (0, import_jsx_runtime326.jsx)(ListViewExpander, { onClick: onToggleExpanded }),
/* @__PURE__ */ (0, import_jsx_runtime326.jsx)(
block_icon_default,
{
icon: blockInformation?.icon,
showColors: true,
context: "list-view"
}
),
/* @__PURE__ */ (0, import_jsx_runtime326.jsxs)(
import_components119.__experimentalHStack,
{
alignment: "center",
className: "block-editor-list-view-block-select-button__label-wrapper",
justify: "flex-start",
spacing: 1,
children: [
/* @__PURE__ */ (0, import_jsx_runtime326.jsx)("span", { className: "block-editor-list-view-block-select-button__title", children: /* @__PURE__ */ (0, import_jsx_runtime326.jsx)(import_components119.__experimentalTruncate, { ellipsizeMode: "auto", children: blockTitle }) }),
blockInformation?.anchor && /* @__PURE__ */ (0, import_jsx_runtime326.jsx)("span", { className: "block-editor-list-view-block-select-button__anchor-wrapper", children: /* @__PURE__ */ (0, import_jsx_runtime326.jsx)(WCBadge3, { className: "block-editor-list-view-block-select-button__anchor", children: blockInformation.anchor }) }),
isSticky && /* @__PURE__ */ (0, import_jsx_runtime326.jsx)("span", { className: "block-editor-list-view-block-select-button__sticky", children: /* @__PURE__ */ (0, import_jsx_runtime326.jsx)(icon_default, { icon: pin_small_default }) }),
images.length ? /* @__PURE__ */ (0, import_jsx_runtime326.jsx)(
"span",
{
className: "block-editor-list-view-block-select-button__images",
"aria-hidden": true,
children: images.map((image, index2) => /* @__PURE__ */ (0, import_jsx_runtime326.jsx)(
"span",
{
className: "block-editor-list-view-block-select-button__image",
style: {
backgroundImage: `url(${image.url})`,
zIndex: images.length - index2
// Ensure the first image is on top, and subsequent images are behind.
}
},
image.clientId
))
}
) : null,
!!visibilityLabel && // The tooltip below is a sighted-hover affordance for
// the (decorative) visibility icon. The same
// `visibilityLabel` is exposed to assistive technology
// via the row's `aria-describedby`, which references the
// hidden `AriaReferencedText` rendered by the parent
// `ListViewBlock`.
/* @__PURE__ */ (0, import_jsx_runtime326.jsxs)(tooltip_exports.Root, { children: [
/* @__PURE__ */ (0, import_jsx_runtime326.jsx)(
tooltip_exports.Trigger,
{
render: /* @__PURE__ */ (0, import_jsx_runtime326.jsx)(
"span",
{
className: "block-editor-list-view-block-select-button__block-visibility",
"aria-hidden": "true",
children: /* @__PURE__ */ (0, import_jsx_runtime326.jsx)(icon_default, { icon: unseen_default })
}
)
}
),
/* @__PURE__ */ (0, import_jsx_runtime326.jsx)(tooltip_exports.Popup, { children: visibilityLabel })
] }),
shouldShowLockIcon && /* @__PURE__ */ (0, import_jsx_runtime326.jsx)("span", { className: "block-editor-list-view-block-select-button__lock", children: /* @__PURE__ */ (0, import_jsx_runtime326.jsx)(icon_default, { icon: lock_small_default }) })
]
}
)
]
}
)
);
}
var block_select_button_default = (0, import_element185.forwardRef)(ListViewBlockSelectButton);
// packages/block-editor/build-module/components/list-view/block-contents.mjs
var import_jsx_runtime327 = __toESM(require_jsx_runtime(), 1);
var ListViewBlockContents = (0, import_element186.forwardRef)(
({
onClick,
onToggleExpanded,
block,
isSelected,
position,
siblingBlockCount,
level,
isExpanded,
selectedClientIds,
...props
}, ref) => {
const { clientId } = block;
const { AdditionalBlockContent, insertedBlock, setInsertedBlock } = useListViewContext();
const draggableClientIds = selectedClientIds.includes(clientId) ? selectedClientIds : [clientId];
return /* @__PURE__ */ (0, import_jsx_runtime327.jsxs)(import_jsx_runtime327.Fragment, { children: [
AdditionalBlockContent && /* @__PURE__ */ (0, import_jsx_runtime327.jsx)(
AdditionalBlockContent,
{
block,
insertedBlock,
setInsertedBlock
}
),
/* @__PURE__ */ (0, import_jsx_runtime327.jsx)(
block_draggable_default,
{
appendToOwnerDocument: true,
clientIds: draggableClientIds,
cloneClassname: "block-editor-list-view-draggable-chip",
children: ({ draggable, onDragStart, onDragEnd }) => /* @__PURE__ */ (0, import_jsx_runtime327.jsx)(
block_select_button_default,
{
ref,
className: "block-editor-list-view-block-contents",
block,
onClick,
onToggleExpanded,
isSelected,
position,
siblingBlockCount,
level,
draggable,
onDragStart,
onDragEnd,
isExpanded,
...props
}
)
}
)
] });
}
);
var block_contents_default = ListViewBlockContents;
// packages/block-editor/build-module/components/list-view/utils.mjs
var import_i18n108 = __toESM(require_i18n(), 1);
var import_dom62 = __toESM(require_dom(), 1);
var getBlockPositionDescription = (position, siblingCount, level) => (0, import_i18n108.sprintf)(
/* translators: 1: The numerical position of the block. 2: The total number of blocks. 3. The level of nesting for the block. */
(0, import_i18n108.__)("Block %1$d of %2$d, Level %3$d."),
position,
siblingCount,
level
);
var getBlockPropertiesDescription = (blockInformation, isLocked) => [
blockInformation?.positionLabel ? `${(0, import_i18n108.sprintf)(
// translators: %s: Position of selected block, e.g. "Sticky" or "Fixed".
(0, import_i18n108.__)("Position: %s"),
blockInformation.positionLabel
)}.` : void 0,
isLocked ? (0, import_i18n108.__)("This block is locked.") : void 0
].filter(Boolean).join(" ");
var isClientIdSelected = (clientId, selectedBlockClientIds) => Array.isArray(selectedBlockClientIds) && selectedBlockClientIds.length ? selectedBlockClientIds.indexOf(clientId) !== -1 : selectedBlockClientIds === clientId;
function getCommonDepthClientIds(startId, endId, startParents, endParents) {
const startPath = [...startParents, startId];
const endPath = [...endParents, endId];
const depth = Math.min(startPath.length, endPath.length) - 1;
const start2 = startPath[depth];
const end = endPath[depth];
return {
start: start2,
end
};
}
function focusListItem(focusClientId, treeGridElement) {
if (!treeGridElement) {
return;
}
const selector3 = `[role=row][data-block="${focusClientId}"]`;
return new Promise((resolve) => {
if (treeGridElement.querySelector(selector3)) {
return resolve(treeGridElement.querySelector(selector3));
}
let timer = null;
const observer = new window.MutationObserver(() => {
if (treeGridElement.querySelector(selector3)) {
clearTimeout(timer);
observer.disconnect();
resolve(treeGridElement.querySelector(selector3));
}
});
observer.observe(treeGridElement, {
childList: true,
subtree: true
});
timer = setTimeout(() => {
observer.disconnect();
resolve(null);
}, 3e3);
}).then((element) => {
if (element && element.isConnected) {
import_dom62.focus.focusable.find(element)?.[0]?.focus();
}
});
}
function getDragDisplacementValues({
blockIndexes,
blockDropTargetIndex,
blockDropPosition,
clientId,
firstDraggedBlockIndex,
isDragged
}) {
let displacement;
let isNesting;
let isAfterDraggedBlocks;
if (!isDragged) {
isNesting = false;
const thisBlockIndex = blockIndexes[clientId];
isAfterDraggedBlocks = thisBlockIndex > firstDraggedBlockIndex;
if (blockDropTargetIndex !== void 0 && blockDropTargetIndex !== null && firstDraggedBlockIndex !== void 0) {
if (thisBlockIndex !== void 0) {
if (thisBlockIndex >= firstDraggedBlockIndex && thisBlockIndex < blockDropTargetIndex) {
displacement = "up";
} else if (thisBlockIndex < firstDraggedBlockIndex && thisBlockIndex >= blockDropTargetIndex) {
displacement = "down";
} else {
displacement = "normal";
}
isNesting = typeof blockDropTargetIndex === "number" && blockDropTargetIndex - 1 === thisBlockIndex && blockDropPosition === "inside";
}
} else if (blockDropTargetIndex === null && firstDraggedBlockIndex !== void 0) {
if (thisBlockIndex !== void 0 && thisBlockIndex >= firstDraggedBlockIndex) {
displacement = "up";
} else {
displacement = "normal";
}
} else if (blockDropTargetIndex !== void 0 && blockDropTargetIndex !== null && firstDraggedBlockIndex === void 0) {
if (thisBlockIndex !== void 0) {
if (thisBlockIndex < blockDropTargetIndex) {
displacement = "normal";
} else {
displacement = "down";
}
}
} else if (blockDropTargetIndex === null) {
displacement = "normal";
}
}
return {
displacement,
isNesting,
isAfterDraggedBlocks
};
}
// packages/block-editor/build-module/components/list-view/block.mjs
var import_jsx_runtime328 = __toESM(require_jsx_runtime(), 1);
function ListViewBlock({
block: { clientId },
displacement,
isAfterDraggedBlocks,
isDragged,
isNesting,
isSelected,
isBranchSelected,
selectBlock: selectBlock2,
position,
level,
rowCount,
siblingBlockCount,
showBlockMovers,
path,
isExpanded,
selectedClientIds,
isSyncedBranch
}) {
const cellRef = (0, import_element187.useRef)(null);
const rowRef = (0, import_element187.useRef)(null);
const settingsRef = (0, import_element187.useRef)(null);
const [isHovered, setIsHovered] = (0, import_element187.useState)(false);
const [settingsAnchorRect, setSettingsAnchorRect] = (0, import_element187.useState)();
const [isRenameModalOpen, setIsRenameModalOpen] = (0, import_element187.useState)(false);
const { isLocked } = useBlockLock(clientId);
const isFirstSelectedBlock = isSelected && selectedClientIds[0] === clientId;
const isLastSelectedBlock = isSelected && selectedClientIds[selectedClientIds.length - 1] === clientId;
const {
toggleBlockHighlight: toggleBlockHighlight2,
duplicateBlocks: duplicateBlocks2,
multiSelect: multiSelect2,
replaceBlocks: replaceBlocks2,
removeBlocks: removeBlocks2,
insertAfterBlock: insertAfterBlock2,
insertBeforeBlock: insertBeforeBlock2,
showViewportModal: showViewportModal2,
stopEditingContentOnlySection: stopEditingContentOnlySection2
} = unlock((0, import_data129.useDispatch)(store));
const debouncedToggleBlockHighlight = (0, import_compose72.useDebounce)(
toggleBlockHighlight2,
50
);
const {
canInsertBlockType: canInsertBlockType2,
getSelectedBlockClientIds: getSelectedBlockClientIds2,
getPreviousBlockClientId: getPreviousBlockClientId2,
getBlockRootClientId: getBlockRootClientId2,
getBlockOrder: getBlockOrder2,
getBlockParents: getBlockParents2,
getBlockEditingMode: getBlockEditingMode2,
getBlocksByClientId: getBlocksByClientId2,
canEditBlock: canEditBlock2,
canMoveBlock: canMoveBlock2,
canRemoveBlocks: canRemoveBlocks2,
isGroupable: isGroupable2
} = (0, import_data129.useSelect)(store);
const { getGroupingBlockName } = (0, import_data129.useSelect)(import_blocks79.store);
const blockInformation = useBlockDisplayInformation(clientId);
const pasteStyles = usePasteStyles();
const {
block,
blockName,
blockEditingMode,
allowRightClickOverrides,
editedSection,
viewportSettings,
blockVisibilitySetting
} = (0, import_data129.useSelect)(
(select3) => {
const {
getBlock: getBlock2,
getBlockName: getBlockName2,
getBlockEditingMode: getBlockEditingModeForClientId,
getSettings: getSettings7,
getEditedContentOnlySection: getEditedContentOnlySection2
} = unlock(select3(store));
const settings2 = getSettings7();
return {
block: getBlock2(clientId),
blockName: getBlockName2(clientId),
blockEditingMode: getBlockEditingModeForClientId(clientId),
allowRightClickOverrides: settings2.allowRightClickOverrides,
editedSection: getEditedContentOnlySection2(),
viewportSettings: settings2.__experimentalFeatures?.viewport,
blockVisibilitySetting: settings2.__experimentalFeatures?.blockVisibility?.allowEditing
};
},
[clientId]
);
const isDisabled = blockEditingMode === "disabled";
const { canRename } = useBlockRename(blockName);
const showBlockActions = (
// When a block hides its toolbar it also hides the block settings menu,
// since that menu is part of the toolbar in the editor canvas.
// List View respects this by also hiding the block settings menu.
(0, import_blocks79.hasBlockSupport)(blockName, "__experimentalToolbar", true)
);
const instanceId = (0, import_compose72.useInstanceId)(ListViewBlock);
const descriptionId = `list-view-block-select-button__description-${instanceId}`;
const {
expand,
collapse,
collapseAll,
BlockSettingsMenu: BlockSettingsMenu2,
listViewInstanceId,
expandedState,
setInsertedBlock,
treeGridElementRef,
rootClientId
} = useListViewContext();
const isMatch = (0, import_keyboard_shortcuts11.__unstableUseShortcutEventMatch)();
function getBlocksToUpdate() {
const selectedBlockClientIds = getSelectedBlockClientIds2();
const isUpdatingSelectedBlocks = selectedBlockClientIds.includes(clientId);
const firstBlockClientId = isUpdatingSelectedBlocks ? selectedBlockClientIds[0] : clientId;
const firstBlockRootClientId = getBlockRootClientId2(firstBlockClientId);
const blocksToUpdate = isUpdatingSelectedBlocks ? selectedBlockClientIds : [clientId];
return {
blocksToUpdate,
firstBlockClientId,
firstBlockRootClientId,
selectedBlockClientIds
};
}
async function onKeyDown(event) {
if (event.defaultPrevented) {
return;
}
if (event.target.closest("[role=dialog]")) {
return;
}
if (editedSection && isMatch("core/block-editor/unselect", event)) {
event.stopPropagation();
event.preventDefault();
stopEditingContentOnlySection2();
return;
}
const isDeleteKey = [import_keycodes16.BACKSPACE, import_keycodes16.DELETE].includes(event.keyCode);
if (isMatch("core/block-editor/unselect", event) && selectedClientIds.length > 0) {
event.stopPropagation();
event.preventDefault();
selectBlock2(event, void 0);
} else if (isDeleteKey || isMatch("core/block-editor/remove", event)) {
const {
blocksToUpdate: blocksToDelete,
firstBlockClientId,
firstBlockRootClientId,
selectedBlockClientIds
} = getBlocksToUpdate();
if (!canRemoveBlocks2(blocksToDelete)) {
return;
}
let blockToFocus = getPreviousBlockClientId2(firstBlockClientId) ?? // If the previous block is not found (when the first block is deleted),
// fallback to focus the parent block.
firstBlockRootClientId;
removeBlocks2(blocksToDelete, false);
const shouldUpdateSelection = selectedBlockClientIds.length > 0 && getSelectedBlockClientIds2().length === 0;
if (!blockToFocus) {
blockToFocus = getBlockOrder2()[0];
}
updateFocusAndSelection(blockToFocus, shouldUpdateSelection);
} else if (isMatch("core/block-editor/paste-styles", event)) {
event.preventDefault();
const { blocksToUpdate } = getBlocksToUpdate();
const blocks2 = getBlocksByClientId2(blocksToUpdate);
pasteStyles(blocks2);
} else if (isMatch("core/block-editor/duplicate", event)) {
event.preventDefault();
const { blocksToUpdate, firstBlockRootClientId } = getBlocksToUpdate();
const canDuplicate = getBlocksByClientId2(blocksToUpdate).every(
(blockToUpdate) => {
return !!blockToUpdate && (0, import_blocks79.hasBlockSupport)(
blockToUpdate.name,
"multiple",
true
) && canInsertBlockType2(
blockToUpdate.name,
firstBlockRootClientId
);
}
);
if (canDuplicate) {
const updatedBlocks = await duplicateBlocks2(
blocksToUpdate,
false
);
if (updatedBlocks?.length) {
updateFocusAndSelection(updatedBlocks[0], false);
}
}
} else if (isMatch("core/block-editor/insert-before", event)) {
event.preventDefault();
const { blocksToUpdate } = getBlocksToUpdate();
await insertBeforeBlock2(blocksToUpdate[0]);
const newlySelectedBlocks = getSelectedBlockClientIds2();
updateFocusAndSelection(newlySelectedBlocks[0], false);
} else if (isMatch("core/block-editor/insert-after", event)) {
event.preventDefault();
const { blocksToUpdate } = getBlocksToUpdate();
await insertAfterBlock2(blocksToUpdate.at(-1));
const newlySelectedBlocks = getSelectedBlockClientIds2();
updateFocusAndSelection(newlySelectedBlocks[0], false);
} else if (isMatch("core/block-editor/select-all", event)) {
event.preventDefault();
const { firstBlockRootClientId, selectedBlockClientIds } = getBlocksToUpdate();
const blockClientIds = getBlockOrder2(firstBlockRootClientId);
if (!blockClientIds.length) {
return;
}
if ((0, import_is_shallow_equal2.isShallowEqual)(selectedBlockClientIds, blockClientIds)) {
if (firstBlockRootClientId && firstBlockRootClientId !== rootClientId) {
updateFocusAndSelection(firstBlockRootClientId, true);
return;
}
}
multiSelect2(
blockClientIds[0],
blockClientIds[blockClientIds.length - 1],
null
);
} else if (isMatch("core/block-editor/collapse-list-view", event)) {
event.preventDefault();
const { firstBlockClientId } = getBlocksToUpdate();
const blockParents = getBlockParents2(firstBlockClientId, false);
collapseAll();
expand(blockParents);
} else if (isMatch("core/block-editor/group", event)) {
const { blocksToUpdate } = getBlocksToUpdate();
if (blocksToUpdate.length > 1 && isGroupable2(blocksToUpdate)) {
event.preventDefault();
const blocks2 = getBlocksByClientId2(blocksToUpdate);
const groupingBlockName = getGroupingBlockName();
const newBlocks = (0, import_blocks79.switchToBlockType)(
blocks2,
groupingBlockName
);
replaceBlocks2(blocksToUpdate, newBlocks);
(0, import_a11y14.speak)((0, import_i18n109.__)("Selected blocks are grouped."));
const newlySelectedBlocks = getSelectedBlockClientIds2();
updateFocusAndSelection(newlySelectedBlocks[0], false);
}
} else if (isMatch("core/block-editor/toggle-block-visibility", event)) {
if (blockVisibilitySetting === false) {
return;
}
event.preventDefault();
const { blocksToUpdate } = getBlocksToUpdate();
const blocks2 = getBlocksByClientId2(blocksToUpdate);
const supportsBlockVisibility = blocks2.every(
(_block) => (0, import_blocks79.hasBlockSupport)(_block.name, "visibility", true)
);
if (!supportsBlockVisibility) {
return;
}
if (blocksToUpdate.some(
(id) => getBlockEditingMode2(id) !== "default"
)) {
return;
}
showViewportModal2(blocksToUpdate);
} else if (isMatch("core/block-editor/rename", event)) {
const { blocksToUpdate } = getBlocksToUpdate();
const isContentOnly = getBlockEditingMode2(blocksToUpdate[0]) === "contentOnly";
if (blocksToUpdate.length === 1 && canRename && !isContentOnly) {
event.preventDefault();
setIsRenameModalOpen(true);
}
}
}
const onMouseEnter = (0, import_element187.useCallback)(() => {
setIsHovered(true);
debouncedToggleBlockHighlight(clientId, true);
}, [clientId, setIsHovered, debouncedToggleBlockHighlight]);
const onMouseLeave = (0, import_element187.useCallback)(() => {
setIsHovered(false);
debouncedToggleBlockHighlight(clientId, false);
}, [clientId, setIsHovered, debouncedToggleBlockHighlight]);
const selectEditorBlock = (0, import_element187.useCallback)(
(event) => {
const isKeyboardActivation = event?.detail === 0;
selectBlock2(event, clientId, isKeyboardActivation ? -1 : null);
event.preventDefault();
},
[clientId, selectBlock2]
);
const updateFocusAndSelection = (0, import_element187.useCallback)(
(focusClientId, shouldSelectBlock) => {
if (shouldSelectBlock) {
selectBlock2(void 0, focusClientId, null, null);
}
focusListItem(focusClientId, treeGridElementRef?.current);
},
[selectBlock2, treeGridElementRef]
);
const toggleExpanded = (0, import_element187.useCallback)(
(event) => {
event.preventDefault();
event.stopPropagation();
if (isExpanded === true) {
collapse(clientId);
} else if (isExpanded === false) {
expand(clientId);
}
},
[clientId, expand, collapse, isExpanded]
);
const onContextMenu = (0, import_element187.useCallback)(
(event) => {
const { ownerDocument: ownerDocument2 } = settingsRef?.current || {};
if (!ownerDocument2 || !ownerDocument2.hasFocus()) {
return;
}
if (showBlockActions && allowRightClickOverrides) {
settingsRef.current?.click();
setSettingsAnchorRect(
new window.DOMRect(event.clientX, event.clientY, 0, 0)
);
event.preventDefault();
}
},
[allowRightClickOverrides, settingsRef, showBlockActions]
);
const onMouseDown = (0, import_element187.useCallback)(
(event) => {
if (allowRightClickOverrides && event.button === 2) {
event.preventDefault();
}
},
[allowRightClickOverrides]
);
const settingsPopoverAnchor = (0, import_element187.useMemo)(() => {
const { ownerDocument: ownerDocument2 } = rowRef?.current || {};
if (!settingsAnchorRect || !ownerDocument2) {
return void 0;
}
return {
ownerDocument: ownerDocument2,
getBoundingClientRect() {
return settingsAnchorRect;
}
};
}, [settingsAnchorRect]);
const clearSettingsAnchorRect = (0, import_element187.useCallback)(() => {
setSettingsAnchorRect(void 0);
}, [setSettingsAnchorRect]);
useListViewScrollIntoView({
isSelected,
rowItemRef: rowRef,
selectedClientIds
});
if (!block) {
return null;
}
const blockPositionDescription = getBlockPositionDescription(
position,
siblingBlockCount,
level
);
const blockPropertiesDescription = getBlockPropertiesDescription(
blockInformation,
isLocked
);
const blockVisibilityDescription = getBlockVisibilityLabel(
block?.attributes?.metadata?.blockVisibility,
viewportSettings
);
const hasSiblings = siblingBlockCount > 0;
const canShowBlockActions = showBlockActions && !isDisabled;
const hasRenderedMovers = showBlockMovers && hasSiblings && !isDisabled;
const moverCellClassName = clsx_default(
"block-editor-list-view-block__mover-cell",
{ "is-visible": isHovered || isSelected }
);
const listViewBlockSettingsClassName = clsx_default(
"block-editor-list-view-block__menu-cell",
{ "is-visible": isHovered || isFirstSelectedBlock }
);
let colSpan;
if (hasRenderedMovers) {
colSpan = 2;
} else if (!canShowBlockActions) {
colSpan = 3;
}
const classes = clsx_default({
"is-selected": isSelected,
"is-first-selected": isFirstSelectedBlock,
"is-last-selected": isLastSelectedBlock,
"is-branch-selected": isBranchSelected,
"is-synced-branch": isSyncedBranch,
"is-dragging": isDragged,
"has-single-cell": !showBlockActions,
"is-synced": blockInformation?.isSynced,
"is-draggable": canMoveBlock2 && !isDisabled,
"is-displacement-normal": displacement === "normal",
"is-displacement-up": displacement === "up",
"is-displacement-down": displacement === "down",
"is-after-dragged-blocks": isAfterDraggedBlocks,
"is-nesting": isNesting,
"is-disabled": isDisabled
});
const dropdownClientIds = selectedClientIds.includes(clientId) ? selectedClientIds : [clientId];
const getListViewBlockTabIndex = (rovingTabIndex) => {
if (isDisabled) {
return -1;
}
if (isSelected && selectedClientIds.length === 1) {
return 0;
}
return rovingTabIndex;
};
return /* @__PURE__ */ (0, import_jsx_runtime328.jsxs)(
leaf_default,
{
className: classes,
isDragged,
onKeyDown,
onMouseEnter: isDisabled ? void 0 : onMouseEnter,
onMouseLeave: isDisabled ? void 0 : onMouseLeave,
onFocus: isDisabled ? void 0 : onMouseEnter,
onBlur: isDisabled ? void 0 : onMouseLeave,
level,
position,
rowCount,
path,
id: `list-view-${listViewInstanceId}-block-${clientId}`,
"data-block": clientId,
"data-expanded": canEditBlock2 ? isExpanded : void 0,
ref: rowRef,
children: [
/* @__PURE__ */ (0, import_jsx_runtime328.jsx)(
import_components120.__experimentalTreeGridCell,
{
className: "block-editor-list-view-block__contents-cell",
colSpan,
ref: cellRef,
"aria-selected": !!isSelected,
children: ({ ref, tabIndex, onFocus }) => /* @__PURE__ */ (0, import_jsx_runtime328.jsxs)("div", { className: "block-editor-list-view-block__contents-container", children: [
/* @__PURE__ */ (0, import_jsx_runtime328.jsx)(
block_contents_default,
{
block,
onClick: selectEditorBlock,
onContextMenu: isDisabled ? void 0 : onContextMenu,
onMouseDown,
onToggleExpanded: isDisabled ? void 0 : toggleExpanded,
isSelected,
position,
siblingBlockCount,
level,
ref,
tabIndex: getListViewBlockTabIndex(tabIndex),
onFocus,
isExpanded: canEditBlock2 ? isExpanded : void 0,
selectedClientIds,
ariaDescribedBy: descriptionId,
visibilityLabel: blockVisibilityDescription,
isDisabled
}
),
/* @__PURE__ */ (0, import_jsx_runtime328.jsx)(AriaReferencedText, { id: descriptionId, children: [
blockPositionDescription,
blockPropertiesDescription,
blockVisibilityDescription
].filter(Boolean).join(" ") })
] })
}
),
hasRenderedMovers && /* @__PURE__ */ (0, import_jsx_runtime328.jsx)(import_jsx_runtime328.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime328.jsxs)(
import_components120.__experimentalTreeGridCell,
{
className: moverCellClassName,
withoutGridItem: true,
children: [
/* @__PURE__ */ (0, import_jsx_runtime328.jsx)(import_components120.__experimentalTreeGridItem, { children: ({ ref, tabIndex, onFocus }) => /* @__PURE__ */ (0, import_jsx_runtime328.jsx)(
BlockMoverUpButton,
{
orientation: "vertical",
clientIds: [clientId],
ref,
tabIndex,
onFocus
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime328.jsx)(import_components120.__experimentalTreeGridItem, { children: ({ ref, tabIndex, onFocus }) => /* @__PURE__ */ (0, import_jsx_runtime328.jsx)(
BlockMoverDownButton,
{
orientation: "vertical",
clientIds: [clientId],
ref,
tabIndex,
onFocus
}
) })
]
}
) }),
canShowBlockActions && BlockSettingsMenu2 && /* @__PURE__ */ (0, import_jsx_runtime328.jsx)(
import_components120.__experimentalTreeGridCell,
{
className: listViewBlockSettingsClassName,
"aria-selected": !!isSelected,
ref: settingsRef,
children: ({ ref, tabIndex, onFocus }) => /* @__PURE__ */ (0, import_jsx_runtime328.jsx)(
BlockSettingsMenu2,
{
clientIds: dropdownClientIds,
block,
icon: more_vertical_default,
label: (0, import_i18n109.__)("Options"),
popoverProps: {
anchor: settingsPopoverAnchor
// Used to position the settings at the cursor on right-click.
},
toggleProps: {
ref,
className: "block-editor-list-view-block__menu",
tabIndex,
onClick: clearSettingsAnchorRect,
onFocus,
size: "small"
},
disableOpenOnArrowDown: true,
expand,
expandedState,
setInsertedBlock,
__experimentalSelectBlock: updateFocusAndSelection,
isContentOnlyListView: !!rootClientId && getBlockEditingMode2(rootClientId) === "contentOnly"
}
)
}
),
isRenameModalOpen && /* @__PURE__ */ (0, import_jsx_runtime328.jsx)(
BlockRenameModal,
{
clientId,
onClose: () => setIsRenameModalOpen(false)
}
)
]
}
);
}
var block_default3 = (0, import_element187.memo)(ListViewBlock);
// packages/block-editor/build-module/components/list-view/branch.mjs
var import_jsx_runtime329 = __toESM(require_jsx_runtime(), 1);
function countBlocks(block, expandedState, draggedClientIds, isExpandedByDefault) {
const isDragged = draggedClientIds?.includes(block.clientId);
if (isDragged) {
return 0;
}
const isExpanded = expandedState[block.clientId] ?? isExpandedByDefault;
if (isExpanded) {
return 1 + block.innerBlocks.reduce(
countReducer(
expandedState,
draggedClientIds,
isExpandedByDefault
),
0
);
}
return 1;
}
var countReducer = (expandedState, draggedClientIds, isExpandedByDefault) => (count, block) => {
const isDragged = draggedClientIds?.includes(block.clientId);
if (isDragged) {
return count;
}
const isExpanded = expandedState[block.clientId] ?? isExpandedByDefault;
if (isExpanded && block.innerBlocks.length > 0) {
return count + countBlocks(
block,
expandedState,
draggedClientIds,
isExpandedByDefault
);
}
return count + 1;
};
var noop13 = () => {
};
function ListViewBranch(props) {
const {
blocks: blocks2,
selectBlock: selectBlock2 = noop13,
showBlockMovers,
selectedClientIds,
level = 1,
path = "",
isBranchSelected = false,
listPosition = 0,
fixedListWindow,
isExpanded,
parentId,
shouldShowInnerBlocks = true,
isSyncedBranch = false,
showAppender: showAppenderProp = true
} = props;
const parentBlockInformation = useBlockDisplayInformation(parentId);
const syncedBranch = isSyncedBranch || !!parentBlockInformation?.isSynced;
const canParentExpand = (0, import_data130.useSelect)(
(select3) => {
if (!parentId) {
return true;
}
return select3(store).canEditBlock(parentId);
},
[parentId]
);
const {
blockDropPosition,
blockDropTargetIndex,
firstDraggedBlockIndex,
blockIndexes,
expandedState,
draggedClientIds
} = useListViewContext();
const nextPositionRef = (0, import_element188.useRef)();
if (!canParentExpand) {
return null;
}
const showAppender = showAppenderProp && level === 1;
const filteredBlocks = blocks2.filter(Boolean);
const blockCount = filteredBlocks.length;
const rowCount = showAppender ? blockCount + 1 : blockCount;
nextPositionRef.current = listPosition;
return /* @__PURE__ */ (0, import_jsx_runtime329.jsxs)(import_jsx_runtime329.Fragment, { children: [
filteredBlocks.map((block, index2) => {
const { clientId, innerBlocks } = block;
if (index2 > 0) {
nextPositionRef.current += countBlocks(
filteredBlocks[index2 - 1],
expandedState,
draggedClientIds,
isExpanded
);
}
const isDragged = !!draggedClientIds?.includes(clientId);
const { displacement, isAfterDraggedBlocks, isNesting } = getDragDisplacementValues({
blockIndexes,
blockDropTargetIndex,
blockDropPosition,
clientId,
firstDraggedBlockIndex,
isDragged
});
const { itemInView } = fixedListWindow;
const blockInView = itemInView(nextPositionRef.current);
const position = index2 + 1;
const updatedPath = path.length > 0 ? `${path}_${position}` : `${position}`;
const hasNestedBlocks = !!innerBlocks?.length;
const shouldExpand = hasNestedBlocks && shouldShowInnerBlocks ? expandedState[clientId] ?? isExpanded : void 0;
const isSelected = isClientIdSelected(
clientId,
selectedClientIds
);
const isSelectedBranch = isBranchSelected || isSelected && hasNestedBlocks;
const showBlock = isDragged || blockInView || isSelected && clientId === selectedClientIds[0] || index2 === 0 || index2 === blockCount - 1;
return /* @__PURE__ */ (0, import_jsx_runtime329.jsxs)(import_data130.AsyncModeProvider, { value: !isSelected, children: [
showBlock && /* @__PURE__ */ (0, import_jsx_runtime329.jsx)(
block_default3,
{
block,
selectBlock: selectBlock2,
isSelected,
isBranchSelected: isSelectedBranch,
isDragged,
level,
position,
rowCount,
siblingBlockCount: blockCount,
showBlockMovers,
path: updatedPath,
isExpanded: isDragged ? false : shouldExpand,
listPosition: nextPositionRef.current,
selectedClientIds,
isSyncedBranch: syncedBranch,
displacement,
isAfterDraggedBlocks,
isNesting
}
),
!showBlock && /* @__PURE__ */ (0, import_jsx_runtime329.jsx)("tr", { children: /* @__PURE__ */ (0, import_jsx_runtime329.jsx)("td", { className: "block-editor-list-view-placeholder" }) }),
hasNestedBlocks && shouldExpand && !isDragged && /* @__PURE__ */ (0, import_jsx_runtime329.jsx)(
ListViewBranch,
{
parentId: clientId,
blocks: innerBlocks,
selectBlock: selectBlock2,
showBlockMovers,
level: level + 1,
path: updatedPath,
listPosition: nextPositionRef.current + 1,
fixedListWindow,
isBranchSelected: isSelectedBranch,
selectedClientIds,
isExpanded,
isSyncedBranch: syncedBranch
}
)
] }, clientId);
}),
showAppender && /* @__PURE__ */ (0, import_jsx_runtime329.jsx)(
import_components121.__experimentalTreeGridRow,
{
level,
setSize: rowCount,
positionInSet: rowCount,
isExpanded: true,
children: /* @__PURE__ */ (0, import_jsx_runtime329.jsx)(import_components121.__experimentalTreeGridCell, { children: (treeGridCellProps) => /* @__PURE__ */ (0, import_jsx_runtime329.jsx)(
Appender,
{
clientId: parentId,
nestingLevel: level,
blockCount,
...treeGridCellProps
}
) })
}
)
] });
}
var branch_default = (0, import_element188.memo)(ListViewBranch);
// packages/block-editor/build-module/components/list-view/drop-indicator.mjs
var import_components122 = __toESM(require_components(), 1);
var import_dom63 = __toESM(require_dom(), 1);
var import_element189 = __toESM(require_element(), 1);
var import_i18n110 = __toESM(require_i18n(), 1);
var import_jsx_runtime330 = __toESM(require_jsx_runtime(), 1);
function ListViewDropIndicatorPreview({
draggedBlockClientId,
listViewRef,
blockDropTarget
}) {
const blockInformation = useBlockDisplayInformation(draggedBlockClientId);
const blockTitle = useBlockDisplayTitle({
clientId: draggedBlockClientId,
context: "list-view"
});
const { rootClientId, clientId, dropPosition } = blockDropTarget || {};
const [rootBlockElement, blockElement] = (0, import_element189.useMemo)(() => {
if (!listViewRef.current) {
return [];
}
const _rootBlockElement = rootClientId ? listViewRef.current.querySelector(
`[data-block="${rootClientId}"]`
) : void 0;
const _blockElement = clientId ? listViewRef.current.querySelector(
`[data-block="${clientId}"]`
) : void 0;
return [_rootBlockElement, _blockElement];
}, [listViewRef, rootClientId, clientId]);
const targetElement = blockElement || rootBlockElement;
const rtl = (0, import_i18n110.isRTL)();
const getDropIndicatorWidth = (0, import_element189.useCallback)(
(targetElementRect, indent) => {
if (!targetElement) {
return 0;
}
let width = targetElement.offsetWidth;
const scrollContainer = (0, import_dom63.getScrollContainer)(
targetElement,
"horizontal"
);
const ownerDocument2 = targetElement.ownerDocument;
const windowScroll = scrollContainer === ownerDocument2.body || scrollContainer === ownerDocument2.documentElement;
if (scrollContainer && !windowScroll) {
const scrollContainerRect = scrollContainer.getBoundingClientRect();
const distanceBetweenContainerAndTarget = (0, import_i18n110.isRTL)() ? scrollContainerRect.right - targetElementRect.right : targetElementRect.left - scrollContainerRect.left;
const scrollContainerWidth = scrollContainer.clientWidth;
if (scrollContainerWidth < width + distanceBetweenContainerAndTarget) {
width = scrollContainerWidth - distanceBetweenContainerAndTarget;
}
if (!rtl && targetElementRect.left + indent < scrollContainerRect.left) {
width -= scrollContainerRect.left - targetElementRect.left;
return width;
}
if (rtl && targetElementRect.right - indent > scrollContainerRect.right) {
width -= targetElementRect.right - scrollContainerRect.right;
return width;
}
}
return width - indent;
},
[rtl, targetElement]
);
const style = (0, import_element189.useMemo)(() => {
if (!targetElement) {
return {};
}
const targetElementRect = targetElement.getBoundingClientRect();
return {
width: getDropIndicatorWidth(targetElementRect, 0)
};
}, [getDropIndicatorWidth, targetElement]);
const horizontalScrollOffsetStyle = (0, import_element189.useMemo)(() => {
if (!targetElement) {
return {};
}
const scrollContainer = (0, import_dom63.getScrollContainer)(targetElement);
const ownerDocument2 = targetElement.ownerDocument;
const windowScroll = scrollContainer === ownerDocument2.body || scrollContainer === ownerDocument2.documentElement;
if (scrollContainer && !windowScroll) {
const scrollContainerRect = scrollContainer.getBoundingClientRect();
const targetElementRect = targetElement.getBoundingClientRect();
const distanceBetweenContainerAndTarget = rtl ? scrollContainerRect.right - targetElementRect.right : targetElementRect.left - scrollContainerRect.left;
if (!rtl && scrollContainerRect.left > targetElementRect.left) {
return {
transform: `translateX( ${distanceBetweenContainerAndTarget}px )`
};
}
if (rtl && scrollContainerRect.right < targetElementRect.right) {
return {
transform: `translateX( ${distanceBetweenContainerAndTarget * -1}px )`
};
}
}
return {};
}, [rtl, targetElement]);
const ariaLevel = (0, import_element189.useMemo)(() => {
if (!rootBlockElement) {
return 1;
}
const _ariaLevel = parseInt(
rootBlockElement.getAttribute("aria-level"),
10
);
return _ariaLevel ? _ariaLevel + 1 : 1;
}, [rootBlockElement]);
const hasAdjacentSelectedBranch = (0, import_element189.useMemo)(() => {
if (!targetElement) {
return false;
}
return targetElement.classList.contains("is-branch-selected");
}, [targetElement]);
const popoverAnchor = (0, import_element189.useMemo)(() => {
const isValidDropPosition = dropPosition === "top" || dropPosition === "bottom" || dropPosition === "inside";
if (!targetElement || !isValidDropPosition) {
return void 0;
}
return {
contextElement: targetElement,
getBoundingClientRect() {
const rect = targetElement.getBoundingClientRect();
let left = rect.left;
let top = 0;
const scrollContainer = (0, import_dom63.getScrollContainer)(
targetElement,
"horizontal"
);
const doc = targetElement.ownerDocument;
const windowScroll = scrollContainer === doc.body || scrollContainer === doc.documentElement;
if (scrollContainer && !windowScroll) {
const scrollContainerRect = scrollContainer.getBoundingClientRect();
const scrollbarWidth = rtl ? scrollContainer.offsetWidth - scrollContainer.clientWidth : 0;
if (left < scrollContainerRect.left + scrollbarWidth) {
left = scrollContainerRect.left + scrollbarWidth;
}
}
if (dropPosition === "top") {
top = rect.top - rect.height * 2;
} else {
top = rect.top;
}
const width = getDropIndicatorWidth(rect, 0);
const height = rect.height;
return new window.DOMRect(left, top, width, height);
}
};
}, [targetElement, dropPosition, getDropIndicatorWidth, rtl]);
if (!targetElement) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime330.jsx)(
import_components122.Popover,
{
animate: false,
anchor: popoverAnchor,
focusOnMount: false,
className: "block-editor-list-view-drop-indicator--preview",
variant: "unstyled",
flip: false,
resize: true,
children: /* @__PURE__ */ (0, import_jsx_runtime330.jsx)(
"div",
{
style,
className: clsx_default(
"block-editor-list-view-drop-indicator__line",
{
"block-editor-list-view-drop-indicator__line--darker": hasAdjacentSelectedBranch
}
),
children: /* @__PURE__ */ (0, import_jsx_runtime330.jsxs)(
"div",
{
className: "block-editor-list-view-leaf",
"aria-level": ariaLevel,
children: [
/* @__PURE__ */ (0, import_jsx_runtime330.jsxs)(
"div",
{
className: clsx_default(
"block-editor-list-view-block-select-button",
"block-editor-list-view-block-contents"
),
style: horizontalScrollOffsetStyle,
children: [
/* @__PURE__ */ (0, import_jsx_runtime330.jsx)(ListViewExpander, { onClick: () => {
} }),
/* @__PURE__ */ (0, import_jsx_runtime330.jsx)(
block_icon_default,
{
icon: blockInformation?.icon,
showColors: true,
context: "list-view"
}
),
/* @__PURE__ */ (0, import_jsx_runtime330.jsx)(
import_components122.__experimentalHStack,
{
alignment: "center",
className: "block-editor-list-view-block-select-button__label-wrapper",
justify: "flex-start",
spacing: 1,
children: /* @__PURE__ */ (0, import_jsx_runtime330.jsx)("span", { className: "block-editor-list-view-block-select-button__title", children: /* @__PURE__ */ (0, import_jsx_runtime330.jsx)(import_components122.__experimentalTruncate, { ellipsizeMode: "auto", children: blockTitle }) })
}
)
]
}
),
/* @__PURE__ */ (0, import_jsx_runtime330.jsx)("div", { className: "block-editor-list-view-block__menu-cell" })
]
}
)
}
)
}
);
}
// packages/block-editor/build-module/components/list-view/use-block-selection.mjs
var import_a11y15 = __toESM(require_a11y(), 1);
var import_i18n111 = __toESM(require_i18n(), 1);
var import_data131 = __toESM(require_data(), 1);
var import_element190 = __toESM(require_element(), 1);
var import_keycodes17 = __toESM(require_keycodes(), 1);
var import_blocks80 = __toESM(require_blocks(), 1);
function useBlockSelection() {
const { clearSelectedBlock: clearSelectedBlock2, multiSelect: multiSelect2, selectBlock: selectBlock2 } = (0, import_data131.useDispatch)(store);
const {
getBlockName: getBlockName2,
getBlockParents: getBlockParents2,
getBlockSelectionStart: getBlockSelectionStart2,
getSelectedBlockClientIds: getSelectedBlockClientIds2,
hasMultiSelection: hasMultiSelection2,
hasSelectedBlock: hasSelectedBlock2
} = (0, import_data131.useSelect)(store);
const { getBlockType: getBlockType29 } = (0, import_data131.useSelect)(import_blocks80.store);
const updateBlockSelection = (0, import_element190.useCallback)(
async (event, clientId, destinationClientId, focusPosition) => {
if (!event?.shiftKey && event?.keyCode !== import_keycodes17.ESCAPE) {
selectBlock2(clientId, focusPosition);
return;
}
event.preventDefault();
const isOnlyDeselection = event.type === "keydown" && event.keyCode === import_keycodes17.ESCAPE;
const isKeyPress = event.type === "keydown" && (event.keyCode === import_keycodes17.UP || event.keyCode === import_keycodes17.DOWN || event.keyCode === import_keycodes17.HOME || event.keyCode === import_keycodes17.END);
if (!isKeyPress && !hasSelectedBlock2() && !hasMultiSelection2()) {
selectBlock2(clientId, null);
return;
}
const selectedBlocks = getSelectedBlockClientIds2();
const clientIdWithParents = [
...getBlockParents2(clientId),
clientId
];
if (isOnlyDeselection || isKeyPress && !selectedBlocks.some(
(blockId) => clientIdWithParents.includes(blockId)
)) {
await clearSelectedBlock2();
}
if (!isOnlyDeselection) {
let startTarget = getBlockSelectionStart2();
let endTarget = clientId;
if (isKeyPress) {
if (!hasSelectedBlock2() && !hasMultiSelection2()) {
startTarget = clientId;
}
if (destinationClientId) {
endTarget = destinationClientId;
}
}
const startParents = getBlockParents2(startTarget);
const endParents = getBlockParents2(endTarget);
const { start: start2, end } = getCommonDepthClientIds(
startTarget,
endTarget,
startParents,
endParents
);
await multiSelect2(start2, end, null);
}
const updatedSelectedBlocks = getSelectedBlockClientIds2();
if ((event.keyCode === import_keycodes17.HOME || event.keyCode === import_keycodes17.END) && updatedSelectedBlocks.length > 1) {
return;
}
const selectionDiff = selectedBlocks.filter(
(blockId) => !updatedSelectedBlocks.includes(blockId)
);
let label;
if (selectionDiff.length === 1) {
const title = getBlockType29(
getBlockName2(selectionDiff[0])
)?.title;
if (title) {
label = (0, import_i18n111.sprintf)(
/* translators: %s: block name */
(0, import_i18n111.__)("%s deselected."),
title
);
}
} else if (selectionDiff.length > 1) {
label = (0, import_i18n111.sprintf)(
/* translators: %s: number of deselected blocks */
(0, import_i18n111.__)("%s blocks deselected."),
selectionDiff.length
);
}
if (label) {
(0, import_a11y15.speak)(label, "assertive");
}
},
[
clearSelectedBlock2,
getBlockName2,
getBlockType29,
getBlockParents2,
getBlockSelectionStart2,
getSelectedBlockClientIds2,
hasMultiSelection2,
hasSelectedBlock2,
multiSelect2,
selectBlock2
]
);
return {
updateBlockSelection
};
}
// packages/block-editor/build-module/components/list-view/use-list-view-block-indexes.mjs
var import_element191 = __toESM(require_element(), 1);
function useListViewBlockIndexes(blocks2) {
const blockIndexes = (0, import_element191.useMemo)(() => {
const indexes = {};
let currentGlobalIndex = 0;
const traverseBlocks = (blockList) => {
blockList.forEach((block) => {
indexes[block.clientId] = currentGlobalIndex;
currentGlobalIndex++;
if (block.innerBlocks.length > 0) {
traverseBlocks(block.innerBlocks);
}
});
};
traverseBlocks(blocks2);
return indexes;
}, [blocks2]);
return blockIndexes;
}
// packages/block-editor/build-module/components/list-view/use-list-view-client-ids.mjs
var import_data132 = __toESM(require_data(), 1);
function useListViewClientIds({ blocks: blocks2, rootClientId }) {
return (0, import_data132.useSelect)(
(select3) => {
const {
getDraggedBlockClientIds: getDraggedBlockClientIds2,
getSelectedBlockClientIds: getSelectedBlockClientIds2,
getListViewClientIdsTree: getListViewClientIdsTree2
} = unlock(select3(store));
return {
selectedClientIds: getSelectedBlockClientIds2(),
draggedClientIds: getDraggedBlockClientIds2(),
clientIdsTree: blocks2 ?? getListViewClientIdsTree2(rootClientId)
};
},
[blocks2, rootClientId]
);
}
// packages/block-editor/build-module/components/list-view/use-list-view-collapse-items.mjs
var import_element192 = __toESM(require_element(), 1);
var import_data133 = __toESM(require_data(), 1);
function useListViewCollapseItems({ collapseAll, expand }) {
const { expandedBlock: expandedBlock2, getBlockParents: getBlockParents2 } = (0, import_data133.useSelect)((select3) => {
const { getBlockParents: _getBlockParents, getExpandedBlock: getExpandedBlock2 } = unlock(
select3(store)
);
return {
expandedBlock: getExpandedBlock2(),
getBlockParents: _getBlockParents
};
}, []);
(0, import_element192.useEffect)(() => {
if (expandedBlock2) {
const blockParents = getBlockParents2(expandedBlock2, false);
collapseAll();
expand(blockParents);
}
}, [collapseAll, expand, expandedBlock2, getBlockParents2]);
}
// packages/block-editor/build-module/components/list-view/use-list-view-drop-zone.mjs
var import_data134 = __toESM(require_data(), 1);
var import_element193 = __toESM(require_element(), 1);
var import_compose73 = __toESM(require_compose(), 1);
var import_i18n112 = __toESM(require_i18n(), 1);
var NESTING_LEVEL_INDENTATION = 24;
function isUpGesture(point, rect, nestingLevel = 1, rtl = false) {
const blockIndentPosition = rtl ? rect.right - nestingLevel * NESTING_LEVEL_INDENTATION : rect.left + nestingLevel * NESTING_LEVEL_INDENTATION;
return rtl ? point.x > blockIndentPosition : point.x < blockIndentPosition;
}
function getDesiredRelativeParentLevel(point, rect, nestingLevel = 1, rtl = false) {
const blockIndentPosition = rtl ? rect.right - nestingLevel * NESTING_LEVEL_INDENTATION : rect.left + nestingLevel * NESTING_LEVEL_INDENTATION;
const distanceBetweenPointAndBlockIndentPosition = rtl ? blockIndentPosition - point.x : point.x - blockIndentPosition;
const desiredParentLevel = Math.round(
distanceBetweenPointAndBlockIndentPosition / NESTING_LEVEL_INDENTATION
);
return Math.abs(desiredParentLevel);
}
function getCandidateBlockParents(candidateBlockData, blocksData) {
const candidateBlockParents = [];
let currentBlockData = candidateBlockData;
while (currentBlockData) {
candidateBlockParents.push({ ...currentBlockData });
currentBlockData = blocksData.find(
(blockData) => blockData.clientId === currentBlockData.rootClientId
);
}
return candidateBlockParents;
}
function getNextNonDraggedBlock(blocksData, index2) {
const nextBlockData = blocksData[index2 + 1];
if (nextBlockData && nextBlockData.isDraggedBlock) {
return getNextNonDraggedBlock(blocksData, index2 + 1);
}
return nextBlockData;
}
function isNestingGesture(point, rect, nestingLevel = 1, rtl = false) {
const blockIndentPosition = rtl ? rect.right - nestingLevel * NESTING_LEVEL_INDENTATION : rect.left + nestingLevel * NESTING_LEVEL_INDENTATION;
const isNestingHorizontalGesture = rtl ? point.x < blockIndentPosition - NESTING_LEVEL_INDENTATION : point.x > blockIndentPosition + NESTING_LEVEL_INDENTATION;
return isNestingHorizontalGesture && point.y < rect.bottom;
}
var ALLOWED_DROP_EDGES = ["top", "bottom"];
function getListViewDropTarget(blocksData, position, rtl = false) {
let candidateEdge;
let candidateBlockData;
let candidateDistance;
let candidateRect;
let candidateBlockIndex;
for (let i2 = 0; i2 < blocksData.length; i2++) {
const blockData = blocksData[i2];
if (blockData.isDraggedBlock) {
continue;
}
const rect = blockData.element.getBoundingClientRect();
const [distance, edge] = getDistanceToNearestEdge(
position,
rect,
ALLOWED_DROP_EDGES
);
const isCursorWithinBlock = isPointContainedByRect(position, rect);
if (candidateDistance === void 0 || distance < candidateDistance || isCursorWithinBlock) {
candidateDistance = distance;
const index2 = blocksData.indexOf(blockData);
const previousBlockData = blocksData[index2 - 1];
if (edge === "top" && previousBlockData && previousBlockData.rootClientId === blockData.rootClientId && !previousBlockData.isDraggedBlock) {
candidateBlockData = previousBlockData;
candidateEdge = "bottom";
candidateRect = previousBlockData.element.getBoundingClientRect();
candidateBlockIndex = index2 - 1;
} else {
candidateBlockData = blockData;
candidateEdge = edge;
candidateRect = rect;
candidateBlockIndex = index2;
}
if (isCursorWithinBlock) {
break;
}
}
}
if (!candidateBlockData) {
return;
}
const candidateBlockParents = getCandidateBlockParents(
candidateBlockData,
blocksData
);
const isDraggingBelow = candidateEdge === "bottom";
if (isDraggingBelow && candidateBlockData.canInsertDraggedBlocksAsChild && (candidateBlockData.innerBlockCount > 0 && candidateBlockData.isExpanded || isNestingGesture(
position,
candidateRect,
candidateBlockParents.length,
rtl
))) {
const newBlockIndex = candidateBlockData.isExpanded ? 0 : candidateBlockData.innerBlockCount || 0;
return {
rootClientId: candidateBlockData.clientId,
clientId: candidateBlockData.clientId,
blockIndex: newBlockIndex,
dropPosition: "inside"
};
}
if (isDraggingBelow && candidateBlockData.rootClientId && isUpGesture(
position,
candidateRect,
candidateBlockParents.length,
rtl
)) {
const nextBlock = getNextNonDraggedBlock(
blocksData,
candidateBlockIndex
);
const currentLevel = candidateBlockData.nestingLevel;
const nextLevel = nextBlock ? nextBlock.nestingLevel : 1;
if (currentLevel && nextLevel) {
const desiredRelativeLevel = getDesiredRelativeParentLevel(
position,
candidateRect,
candidateBlockParents.length,
rtl
);
const targetParentIndex = Math.max(
Math.min(desiredRelativeLevel, currentLevel - nextLevel),
0
);
if (candidateBlockParents[targetParentIndex]) {
let newBlockIndex = candidateBlockData.blockIndex;
if (candidateBlockParents[targetParentIndex].nestingLevel === nextBlock?.nestingLevel) {
newBlockIndex = nextBlock?.blockIndex;
} else {
for (let i2 = candidateBlockIndex; i2 >= 0; i2--) {
const blockData = blocksData[i2];
if (blockData.rootClientId === candidateBlockParents[targetParentIndex].rootClientId) {
newBlockIndex = blockData.blockIndex + 1;
break;
}
}
}
return {
rootClientId: candidateBlockParents[targetParentIndex].rootClientId,
clientId: candidateBlockData.clientId,
blockIndex: newBlockIndex,
dropPosition: candidateEdge
};
}
}
}
if (!candidateBlockData.canInsertDraggedBlocksAsSibling) {
return;
}
const offset4 = isDraggingBelow ? 1 : 0;
return {
rootClientId: candidateBlockData.rootClientId,
clientId: candidateBlockData.clientId,
blockIndex: candidateBlockData.blockIndex + offset4,
dropPosition: candidateEdge
};
}
var EXPAND_THROTTLE_OPTIONS = {
leading: false,
// Don't call the function immediately on the first call.
trailing: true
// Do call the function on the last call.
};
function useListViewDropZone({
dropZoneElement,
expandedState,
setExpandedState
}) {
const {
getBlockRootClientId: getBlockRootClientId2,
getBlockIndex: getBlockIndex2,
getBlockCount: getBlockCount2,
getDraggedBlockClientIds: getDraggedBlockClientIds2,
canInsertBlocks: canInsertBlocks2
} = (0, import_data134.useSelect)(store);
const [target, setTarget] = (0, import_element193.useState)();
const { rootClientId: targetRootClientId, blockIndex: targetBlockIndex } = target || {};
const onBlockDrop2 = useOnBlockDrop(targetRootClientId, targetBlockIndex);
const rtl = (0, import_i18n112.isRTL)();
const previousRootClientId = (0, import_compose73.usePrevious)(targetRootClientId);
const maybeExpandBlock = (0, import_element193.useCallback)(
(_expandedState, _target) => {
const { rootClientId } = _target || {};
if (!rootClientId) {
return;
}
if (_target?.dropPosition === "inside" && !_expandedState[rootClientId]) {
setExpandedState({
type: "expand",
clientIds: [rootClientId]
});
}
},
[setExpandedState]
);
const throttledMaybeExpandBlock = (0, import_compose73.useThrottle)(
maybeExpandBlock,
500,
EXPAND_THROTTLE_OPTIONS
);
(0, import_element193.useEffect)(() => {
if (target?.dropPosition !== "inside" || previousRootClientId !== target?.rootClientId) {
throttledMaybeExpandBlock.cancel();
return;
}
throttledMaybeExpandBlock(expandedState, target);
}, [
expandedState,
previousRootClientId,
target,
throttledMaybeExpandBlock
]);
const draggedBlockClientIds = getDraggedBlockClientIds2();
const throttled = (0, import_compose73.useThrottle)(
(0, import_element193.useCallback)(
(event, currentTarget) => {
const position = { x: event.clientX, y: event.clientY };
const isBlockDrag = !!draggedBlockClientIds?.length;
const blockElements = Array.from(
currentTarget.querySelectorAll("[data-block]")
);
const blocksData = blockElements.map((blockElement) => {
const clientId = blockElement.dataset.block;
const isExpanded = blockElement.dataset.expanded === "true";
const isDraggedBlock = blockElement.classList.contains("is-dragging");
const nestingLevel = parseInt(
blockElement.getAttribute("aria-level"),
10
);
const rootClientId = getBlockRootClientId2(clientId);
return {
clientId,
isExpanded,
rootClientId,
blockIndex: getBlockIndex2(clientId),
element: blockElement,
nestingLevel: nestingLevel || void 0,
isDraggedBlock: isBlockDrag ? isDraggedBlock : false,
innerBlockCount: getBlockCount2(clientId),
canInsertDraggedBlocksAsSibling: isBlockDrag ? canInsertBlocks2(
draggedBlockClientIds,
rootClientId
) : true,
canInsertDraggedBlocksAsChild: isBlockDrag ? canInsertBlocks2(draggedBlockClientIds, clientId) : true
};
});
const newTarget = getListViewDropTarget(
blocksData,
position,
rtl
);
if (newTarget) {
setTarget(newTarget);
}
},
[
canInsertBlocks2,
draggedBlockClientIds,
getBlockCount2,
getBlockIndex2,
getBlockRootClientId2,
rtl
]
),
50
);
const ref = (0, import_compose73.__experimentalUseDropZone)({
dropZoneElement,
onDrop(event) {
throttled.cancel();
if (target) {
onBlockDrop2(event);
}
setTarget(void 0);
},
onDragLeave() {
throttled.cancel();
setTarget(null);
},
onDragOver(event) {
throttled(event, event.currentTarget);
},
onDragEnd() {
throttled.cancel();
setTarget(void 0);
}
});
return { ref, target };
}
// packages/block-editor/build-module/components/list-view/use-list-view-expand-selected-item.mjs
var import_element194 = __toESM(require_element(), 1);
var import_data135 = __toESM(require_data(), 1);
function useListViewExpandSelectedItem({
firstSelectedBlockClientId,
setExpandedState
}) {
const [selectedTreeId, setSelectedTreeId] = (0, import_element194.useState)(null);
const { selectedBlockParentClientIds } = (0, import_data135.useSelect)(
(select3) => {
const { getBlockParents: getBlockParents2 } = select3(store);
return {
selectedBlockParentClientIds: getBlockParents2(
firstSelectedBlockClientId,
false
)
};
},
[firstSelectedBlockClientId]
);
(0, import_element194.useEffect)(() => {
if (selectedTreeId === firstSelectedBlockClientId) {
return;
}
if (selectedBlockParentClientIds?.length) {
setExpandedState({
type: "expand",
clientIds: selectedBlockParentClientIds
});
}
}, [
firstSelectedBlockClientId,
selectedBlockParentClientIds,
selectedTreeId,
setExpandedState
]);
return {
setSelectedTreeId
};
}
// packages/block-editor/build-module/components/list-view/use-clipboard-handler.mjs
var import_data136 = __toESM(require_data(), 1);
var import_compose74 = __toESM(require_compose(), 1);
function useClipboardHandler2({ selectBlock: selectBlock2 }) {
const registry = (0, import_data136.useRegistry)();
const {
getBlockOrder: getBlockOrder2,
getBlockRootClientId: getBlockRootClientId2,
getBlocksByClientId: getBlocksByClientId2,
getPreviousBlockClientId: getPreviousBlockClientId2,
getSelectedBlockClientIds: getSelectedBlockClientIds2,
getSettings: getSettings7,
canInsertBlockType: canInsertBlockType2,
canRemoveBlocks: canRemoveBlocks2
} = (0, import_data136.useSelect)(store);
const { flashBlock: flashBlock2, removeBlocks: removeBlocks2, replaceBlocks: replaceBlocks2, insertBlocks: insertBlocks2 } = (0, import_data136.useDispatch)(store);
const notifyCopy = useNotifyCopy();
return (0, import_compose74.useRefEffect)((node) => {
function updateFocusAndSelection(focusClientId, shouldSelectBlock) {
if (shouldSelectBlock) {
selectBlock2(void 0, focusClientId, null, null);
}
focusListItem(focusClientId, node);
}
function getBlocksToUpdate(clientId) {
const selectedBlockClientIds = getSelectedBlockClientIds2();
const isUpdatingSelectedBlocks = selectedBlockClientIds.includes(clientId);
const firstBlockClientId = isUpdatingSelectedBlocks ? selectedBlockClientIds[0] : clientId;
const firstBlockRootClientId = getBlockRootClientId2(firstBlockClientId);
const blocksToUpdate = isUpdatingSelectedBlocks ? selectedBlockClientIds : [clientId];
return {
blocksToUpdate,
firstBlockClientId,
firstBlockRootClientId,
originallySelectedBlockClientIds: selectedBlockClientIds
};
}
function handler(event) {
if (event.defaultPrevented) {
return;
}
if (!node.contains(event.target.ownerDocument.activeElement)) {
return;
}
const listViewRow = event.target.ownerDocument.activeElement?.closest(
"[role=row]"
);
const clientId = listViewRow?.dataset?.block;
if (!clientId) {
return;
}
const {
blocksToUpdate: selectedBlockClientIds,
firstBlockClientId,
firstBlockRootClientId,
originallySelectedBlockClientIds
} = getBlocksToUpdate(clientId);
if (selectedBlockClientIds.length === 0) {
return;
}
event.preventDefault();
if (event.type === "copy" || event.type === "cut") {
if (selectedBlockClientIds.length === 1) {
flashBlock2(selectedBlockClientIds[0]);
}
notifyCopy(event.type, selectedBlockClientIds);
const blocks2 = getBlocksByClientId2(selectedBlockClientIds);
setClipboardBlocks(event, blocks2, registry);
}
if (event.type === "cut") {
if (!canRemoveBlocks2(selectedBlockClientIds)) {
return;
}
let blockToFocus = getPreviousBlockClientId2(firstBlockClientId) ?? // If the previous block is not found (when the first block is deleted),
// fallback to focus the parent block.
firstBlockRootClientId;
removeBlocks2(selectedBlockClientIds, false);
const shouldUpdateSelection = originallySelectedBlockClientIds.length > 0 && getSelectedBlockClientIds2().length === 0;
if (!blockToFocus) {
blockToFocus = getBlockOrder2()[0];
}
updateFocusAndSelection(blockToFocus, shouldUpdateSelection);
} else if (event.type === "paste") {
const {
__experimentalCanUserUseUnfilteredHTML: canUserUseUnfilteredHTML
} = getSettings7();
const blocks2 = getPasteBlocks(
event,
canUserUseUnfilteredHTML
);
if (selectedBlockClientIds.length === 1) {
const [selectedBlockClientId] = selectedBlockClientIds;
if (blocks2.every(
(block) => canInsertBlockType2(
block.name,
selectedBlockClientId
)
)) {
insertBlocks2(
blocks2,
void 0,
selectedBlockClientId
);
updateFocusAndSelection(blocks2[0]?.clientId, false);
return;
}
}
replaceBlocks2(
selectedBlockClientIds,
blocks2,
blocks2.length - 1,
-1
);
updateFocusAndSelection(blocks2[0]?.clientId, false);
}
}
node.ownerDocument.addEventListener("copy", handler);
node.ownerDocument.addEventListener("cut", handler);
node.ownerDocument.addEventListener("paste", handler);
return () => {
node.ownerDocument.removeEventListener("copy", handler);
node.ownerDocument.removeEventListener("cut", handler);
node.ownerDocument.removeEventListener("paste", handler);
};
}, []);
}
// packages/block-editor/build-module/components/list-view/index.mjs
var import_jsx_runtime331 = __toESM(require_jsx_runtime(), 1);
var expanded = (state, action) => {
if (action.type === "clear") {
return {};
}
if (Array.isArray(action.clientIds)) {
return {
...state,
...action.clientIds.reduce(
(newState, id) => ({
...newState,
[id]: action.type === "expand"
}),
{}
)
};
}
return state;
};
var BLOCK_LIST_ITEM_HEIGHT = 32;
function ListViewComponent({
id,
blocks: blocks2,
dropZoneElement,
showBlockMovers = false,
isExpanded = false,
showAppender = false,
blockSettingsMenu: BlockSettingsMenu2 = BlockSettingsDropdown,
rootClientId,
description,
onSelect,
additionalBlockContent: AdditionalBlockContent
}, ref) {
if (blocks2) {
(0, import_deprecated14.default)(
"`blocks` property in `wp.blockEditor.__experimentalListView`",
{
since: "6.3",
alternative: "`rootClientId` property"
}
);
}
const instanceId = (0, import_compose75.useInstanceId)(ListViewComponent);
const { clientIdsTree, draggedClientIds, selectedClientIds } = useListViewClientIds({ blocks: blocks2, rootClientId });
const blockIndexes = useListViewBlockIndexes(clientIdsTree);
const { getBlock: getBlock2, getSelectedBlockClientIds: getSelectedBlockClientIds2 } = (0, import_data137.useSelect)(store);
const { visibleBlockCount } = (0, import_data137.useSelect)(
(select3) => {
const { getGlobalBlockCount: getGlobalBlockCount2, getClientIdsOfDescendants: getClientIdsOfDescendants2 } = select3(store);
const draggedBlockCount = draggedClientIds?.length > 0 ? getClientIdsOfDescendants2(draggedClientIds).length + 1 : 0;
return {
visibleBlockCount: getGlobalBlockCount2() - draggedBlockCount
};
},
[draggedClientIds]
);
const { updateBlockSelection } = useBlockSelection();
const [expandedState, setExpandedState] = (0, import_element195.useReducer)(expanded, {});
const [insertedBlock, setInsertedBlock] = (0, import_element195.useState)(null);
const { setSelectedTreeId } = useListViewExpandSelectedItem({
firstSelectedBlockClientId: selectedClientIds[0],
setExpandedState
});
const selectEditorBlock = (0, import_element195.useCallback)(
/**
* @param {MouseEvent | KeyboardEvent | undefined} event
* @param {string} blockClientId
* @param {null | undefined | -1 | 1} focusPosition
*/
(event, blockClientId, focusPosition) => {
updateBlockSelection(event, blockClientId, null, focusPosition);
setSelectedTreeId(blockClientId);
if (onSelect) {
onSelect(getBlock2(blockClientId));
}
},
[setSelectedTreeId, updateBlockSelection, onSelect, getBlock2]
);
const { ref: dropZoneRef, target: blockDropTarget } = useListViewDropZone({
dropZoneElement,
expandedState,
setExpandedState
});
const elementRef = (0, import_element195.useRef)();
const clipBoardRef = useClipboardHandler2({
selectBlock: selectEditorBlock
});
const focusSelectedBlock = (0, import_element195.useCallback)(
(node) => {
const [firstSelectedClientId] = getSelectedBlockClientIds2();
if (firstSelectedClientId && node) {
focusListItem(firstSelectedClientId, node);
}
},
[getSelectedBlockClientIds2]
);
const treeGridRef = (0, import_compose75.useMergeRefs)([
clipBoardRef,
focusSelectedBlock,
elementRef,
dropZoneRef,
ref
]);
const expand = (0, import_element195.useCallback)(
(clientId) => {
if (!clientId) {
return;
}
const clientIds = Array.isArray(clientId) ? clientId : [clientId];
setExpandedState({ type: "expand", clientIds });
},
[setExpandedState]
);
const collapse = (0, import_element195.useCallback)(
(clientId) => {
if (!clientId) {
return;
}
setExpandedState({ type: "collapse", clientIds: [clientId] });
},
[setExpandedState]
);
const collapseAll = (0, import_element195.useCallback)(() => {
setExpandedState({ type: "clear" });
}, [setExpandedState]);
const expandRow = (0, import_element195.useCallback)(
(row) => {
expand(row?.dataset?.block);
},
[expand]
);
const collapseRow = (0, import_element195.useCallback)(
(row) => {
collapse(row?.dataset?.block);
},
[collapse]
);
const focusRow = (0, import_element195.useCallback)(
(event, startRow, endRow) => {
if (event.shiftKey) {
updateBlockSelection(
event,
startRow?.dataset?.block,
endRow?.dataset?.block
);
}
},
[updateBlockSelection]
);
useListViewCollapseItems({
collapseAll,
expand
});
const firstDraggedBlockClientId = draggedClientIds?.[0];
const { blockDropTargetIndex, blockDropPosition, firstDraggedBlockIndex } = (0, import_element195.useMemo)(() => {
let _blockDropTargetIndex, _firstDraggedBlockIndex;
if (blockDropTarget?.clientId) {
const foundBlockIndex = blockIndexes[blockDropTarget.clientId];
_blockDropTargetIndex = foundBlockIndex === void 0 || blockDropTarget?.dropPosition === "top" ? foundBlockIndex : foundBlockIndex + 1;
} else if (blockDropTarget === null) {
_blockDropTargetIndex = null;
}
if (firstDraggedBlockClientId) {
const foundBlockIndex = blockIndexes[firstDraggedBlockClientId];
_firstDraggedBlockIndex = foundBlockIndex === void 0 || blockDropTarget?.dropPosition === "top" ? foundBlockIndex : foundBlockIndex + 1;
}
return {
blockDropTargetIndex: _blockDropTargetIndex,
blockDropPosition: blockDropTarget?.dropPosition,
firstDraggedBlockIndex: _firstDraggedBlockIndex
};
}, [blockDropTarget, blockIndexes, firstDraggedBlockClientId]);
const contextValue = (0, import_element195.useMemo)(
() => ({
blockDropPosition,
blockDropTargetIndex,
blockIndexes,
draggedClientIds,
expandedState,
expand,
firstDraggedBlockIndex,
collapse,
collapseAll,
BlockSettingsMenu: BlockSettingsMenu2,
listViewInstanceId: instanceId,
AdditionalBlockContent,
insertedBlock,
setInsertedBlock,
treeGridElementRef: elementRef,
rootClientId
}),
[
blockDropPosition,
blockDropTargetIndex,
blockIndexes,
draggedClientIds,
expandedState,
expand,
firstDraggedBlockIndex,
collapse,
collapseAll,
BlockSettingsMenu2,
instanceId,
AdditionalBlockContent,
insertedBlock,
setInsertedBlock,
rootClientId
]
);
const [fixedListWindow] = (0, import_compose75.__experimentalUseFixedWindowList)(
elementRef,
BLOCK_LIST_ITEM_HEIGHT,
visibleBlockCount,
{
// Ensure that the windowing logic is recalculated when the expanded state changes.
// This is necessary because expanding a collapsed block in a short list view can
// switch the list view to a tall list view with a scrollbar, and vice versa.
// When this happens, the windowing logic needs to be recalculated to ensure that
// the correct number of blocks are rendered, by rechecking for a scroll container.
expandedState,
useWindowing: true,
windowOverscan: 40
}
);
if (!clientIdsTree.length && !showAppender) {
return null;
}
const describedById = description && `block-editor-list-view-description-${instanceId}`;
return /* @__PURE__ */ (0, import_jsx_runtime331.jsxs)(import_data137.AsyncModeProvider, { value: true, children: [
/* @__PURE__ */ (0, import_jsx_runtime331.jsx)(
ListViewDropIndicatorPreview,
{
draggedBlockClientId: firstDraggedBlockClientId,
listViewRef: elementRef,
blockDropTarget
}
),
description && /* @__PURE__ */ (0, import_jsx_runtime331.jsx)(VisuallyHidden, { id: describedById, children: description }),
/* @__PURE__ */ (0, import_jsx_runtime331.jsx)(
import_components123.__experimentalTreeGrid,
{
id,
className: clsx_default("block-editor-list-view-tree", {
"is-dragging": draggedClientIds?.length > 0 && blockDropTargetIndex !== void 0
}),
"aria-label": (0, import_i18n113.__)("Block navigation structure"),
ref: treeGridRef,
onCollapseRow: collapseRow,
onExpandRow: expandRow,
onFocusRow: focusRow,
applicationAriaLabel: (0, import_i18n113.__)("Block navigation structure"),
"aria-describedby": describedById,
style: {
"--wp-admin--list-view-dragged-items-height": draggedClientIds?.length ? `${BLOCK_LIST_ITEM_HEIGHT * (draggedClientIds.length - 1)}px` : null
},
children: /* @__PURE__ */ (0, import_jsx_runtime331.jsx)(ListViewContext.Provider, { value: contextValue, children: /* @__PURE__ */ (0, import_jsx_runtime331.jsx)(
branch_default,
{
blocks: clientIdsTree,
parentId: rootClientId,
selectBlock: selectEditorBlock,
showBlockMovers,
fixedListWindow,
selectedClientIds,
isExpanded,
showAppender
}
) })
}
)
] });
}
var PrivateListView = (0, import_element195.forwardRef)(ListViewComponent);
var list_view_default2 = (0, import_element195.forwardRef)((props, ref) => {
return /* @__PURE__ */ (0, import_jsx_runtime331.jsx)(
PrivateListView,
{
ref,
...props,
showAppender: false,
rootClientId: null,
onSelect: null,
additionalBlockContent: null,
blockSettingsMenu: void 0
}
);
});
// packages/block-editor/build-module/components/block-navigation/dropdown.mjs
var import_jsx_runtime332 = __toESM(require_jsx_runtime(), 1);
function BlockNavigationDropdownToggle({
isEnabled,
onToggle,
isOpen,
innerRef,
...props
}) {
return /* @__PURE__ */ (0, import_jsx_runtime332.jsx)(
import_components124.Button,
{
__next40pxDefaultSize: true,
...props,
ref: innerRef,
icon: list_view_default,
"aria-expanded": isOpen,
"aria-haspopup": "true",
onClick: isEnabled ? onToggle : void 0,
label: (0, import_i18n114.__)("List view"),
className: "block-editor-block-navigation",
"aria-disabled": !isEnabled
}
);
}
function BlockNavigationDropdown({ isDisabled, ...props }, ref) {
(0, import_deprecated15.default)("wp.blockEditor.BlockNavigationDropdown", {
since: "6.1",
alternative: "wp.components.Dropdown and wp.blockEditor.ListView"
});
const hasBlocks = (0, import_data138.useSelect)(
(select3) => !!select3(store).getBlockCount(),
[]
);
const isEnabled = hasBlocks && !isDisabled;
return /* @__PURE__ */ (0, import_jsx_runtime332.jsx)(
import_components124.Dropdown,
{
contentClassName: "block-editor-block-navigation__popover",
popoverProps: { placement: "bottom-start" },
renderToggle: ({ isOpen, onToggle }) => /* @__PURE__ */ (0, import_jsx_runtime332.jsx)(
BlockNavigationDropdownToggle,
{
...props,
innerRef: ref,
isOpen,
onToggle,
isEnabled
}
),
renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime332.jsxs)("div", { className: "block-editor-block-navigation__container", children: [
/* @__PURE__ */ (0, import_jsx_runtime332.jsx)("p", { className: "block-editor-block-navigation__label", children: (0, import_i18n114.__)("List view") }),
/* @__PURE__ */ (0, import_jsx_runtime332.jsx)(list_view_default2, {})
] })
}
);
}
var dropdown_default = (0, import_element196.forwardRef)(BlockNavigationDropdown);
// packages/block-editor/build-module/components/block-styles/index.mjs
var import_element197 = __toESM(require_element(), 1);
var import_data139 = __toESM(require_data(), 1);
var import_compose76 = __toESM(require_compose(), 1);
var import_components125 = __toESM(require_components(), 1);
var import_i18n115 = __toESM(require_i18n(), 1);
var import_jsx_runtime333 = __toESM(require_jsx_runtime(), 1);
var noop14 = () => {
};
function BlockStyles({ clientId, onSwitch = noop14, onHoverClassName = noop14 }) {
const canEdit = (0, import_data139.useSelect)(
(select3) => select3(store).canEditBlock(clientId),
[clientId]
);
const {
onSelect,
stylesToRender,
activeStyle,
genericPreviewBlock,
className
} = useStylesForBlocks({
clientId,
onSwitch
});
const [hoveredStyle, setHoveredStyle] = (0, import_element197.useState)(null);
const [blockStylesAnchor, setBlockStylesAnchor] = (0, import_element197.useState)(null);
const dropdownMenuProps = useToolsPanelDropdownMenuProps();
const previewBlocks = (0, import_element197.useMemo)(() => {
if (!hoveredStyle || !genericPreviewBlock) {
return null;
}
const previewClassName = replaceActiveStyle(
className,
activeStyle,
hoveredStyle
);
return [
{
...genericPreviewBlock,
attributes: {
...genericPreviewBlock.attributes || {},
className: previewClassName
}
}
];
}, [hoveredStyle, genericPreviewBlock, className, activeStyle]);
if (!canEdit || !stylesToRender || stylesToRender.length === 0) {
return null;
}
const debouncedSetHoveredStyle = (0, import_compose76.debounce)(setHoveredStyle, 250);
const onSelectStylePreview = (style) => {
onSelect(style);
onHoverClassName(null);
setHoveredStyle(null);
debouncedSetHoveredStyle.cancel();
};
const styleItemHandler = (item) => {
if (hoveredStyle === item) {
debouncedSetHoveredStyle.cancel();
return;
}
debouncedSetHoveredStyle(item);
onHoverClassName(item?.name ?? null);
};
const defaultStyle = getDefaultStyle(stylesToRender);
const hasValue = () => {
return activeStyle?.name !== defaultStyle?.name;
};
const onDeselect = () => {
onSelectStylePreview(defaultStyle);
};
return /* @__PURE__ */ (0, import_jsx_runtime333.jsx)(
import_components125.__experimentalToolsPanel,
{
label: (0, import_i18n115.__)("Styles"),
resetAll: onDeselect,
panelId: clientId,
hasInnerWrapper: true,
dropdownMenuProps,
children: /* @__PURE__ */ (0, import_jsx_runtime333.jsx)(
import_components125.__experimentalToolsPanelItem,
{
hasValue,
label: (0, import_i18n115.__)("Variation"),
onDeselect,
isShownByDefault: true,
panelId: clientId,
children: /* @__PURE__ */ (0, import_jsx_runtime333.jsxs)(
"div",
{
ref: setBlockStylesAnchor,
className: "block-editor-block-styles",
children: [
/* @__PURE__ */ (0, import_jsx_runtime333.jsx)("div", { className: "block-editor-block-styles__variants", children: stylesToRender.map((style) => {
const buttonText = style.label || style.name;
return /* @__PURE__ */ (0, import_jsx_runtime333.jsx)(
import_components125.Button,
{
__next40pxDefaultSize: true,
className: clsx_default(
"block-editor-block-styles__item",
{
"is-active": activeStyle.name === style.name
}
),
variant: "secondary",
label: buttonText,
onMouseEnter: () => styleItemHandler(style),
onFocus: () => styleItemHandler(style),
onMouseLeave: () => styleItemHandler(null),
onBlur: () => styleItemHandler(null),
onClick: () => onSelectStylePreview(style),
"aria-current": activeStyle.name === style.name,
children: /* @__PURE__ */ (0, import_jsx_runtime333.jsx)(
import_components125.__experimentalTruncate,
{
numberOfLines: 1,
className: "block-editor-block-styles__item-text",
children: buttonText
}
)
},
style.name
);
}) }),
previewBlocks && /* @__PURE__ */ (0, import_jsx_runtime333.jsx)(
PreviewBlockPopover,
{
blocks: previewBlocks,
placement: "left-start",
offset: 34,
anchor: blockStylesAnchor
}
)
]
}
)
}
)
}
);
}
var block_styles_default = BlockStyles;
// packages/block-editor/build-module/components/block-heading-level-dropdown/index.mjs
var import_components127 = __toESM(require_components(), 1);
var import_i18n116 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/block-heading-level-dropdown/heading-level-icon.mjs
var import_components126 = __toESM(require_components(), 1);
var import_jsx_runtime334 = __toESM(require_jsx_runtime(), 1);
var LEVEL_TO_PATH = {
0: paragraph_default,
1: heading_level_1_default,
2: heading_level_2_default,
3: heading_level_3_default,
4: heading_level_4_default,
5: heading_level_5_default,
6: heading_level_6_default
};
function HeadingLevelIcon({ level }) {
if (LEVEL_TO_PATH[level]) {
return /* @__PURE__ */ (0, import_jsx_runtime334.jsx)(import_components126.Icon, { icon: LEVEL_TO_PATH[level] });
}
return null;
}
// packages/block-editor/build-module/components/block-heading-level-dropdown/index.mjs
var import_jsx_runtime335 = __toESM(require_jsx_runtime(), 1);
var HEADING_LEVELS = [1, 2, 3, 4, 5, 6];
var POPOVER_PROPS6 = {
className: "block-library-heading-level-dropdown"
};
function HeadingLevelDropdown({
options = HEADING_LEVELS,
value,
onChange
}) {
const validOptions = options.filter(
(option) => option === 0 || HEADING_LEVELS.includes(option)
).sort((a2, b2) => a2 - b2);
return /* @__PURE__ */ (0, import_jsx_runtime335.jsx)(
import_components127.ToolbarDropdownMenu,
{
popoverProps: POPOVER_PROPS6,
icon: /* @__PURE__ */ (0, import_jsx_runtime335.jsx)(HeadingLevelIcon, { level: value }),
label: (0, import_i18n116.__)("Change level"),
controls: validOptions.map((targetLevel) => {
const isActive = targetLevel === value;
return {
icon: /* @__PURE__ */ (0, import_jsx_runtime335.jsx)(HeadingLevelIcon, { level: targetLevel }),
title: targetLevel === 0 ? (0, import_i18n116.__)("Paragraph") : (0, import_i18n116.sprintf)(
// translators: %d: heading level e.g: "1", "2", "3"
(0, import_i18n116.__)("Heading %d"),
targetLevel
),
isActive,
onClick() {
onChange(targetLevel);
},
role: "menuitemradio"
};
})
}
);
}
// packages/block-editor/build-module/components/block-variation-picker/index.mjs
var import_i18n117 = __toESM(require_i18n(), 1);
var import_components128 = __toESM(require_components(), 1);
var import_jsx_runtime336 = __toESM(require_jsx_runtime(), 1);
function BlockVariationPicker({
icon = layout_default,
label = (0, import_i18n117.__)("Choose variation"),
instructions = (0, import_i18n117.__)("Select a variation to start with:"),
variations,
onSelect,
allowSkip
}) {
const classes = clsx_default("block-editor-block-variation-picker", {
"has-many-variations": variations.length > 4
});
return /* @__PURE__ */ (0, import_jsx_runtime336.jsxs)(
import_components128.Placeholder,
{
icon,
label,
instructions,
className: classes,
children: [
/* @__PURE__ */ (0, import_jsx_runtime336.jsx)(
"ul",
{
className: "block-editor-block-variation-picker__variations",
role: "list",
"aria-label": (0, import_i18n117.__)("Block variations"),
children: variations.map((variation) => /* @__PURE__ */ (0, import_jsx_runtime336.jsxs)("li", { children: [
/* @__PURE__ */ (0, import_jsx_runtime336.jsx)(
import_components128.Button,
{
__next40pxDefaultSize: true,
variant: "tertiary",
icon: variation.icon && variation.icon.src ? variation.icon.src : variation.icon,
iconSize: 48,
onClick: () => onSelect(variation),
className: "block-editor-block-variation-picker__variation",
label: variation.description || variation.title
}
),
/* @__PURE__ */ (0, import_jsx_runtime336.jsx)("span", { className: "block-editor-block-variation-picker__variation-label", children: variation.title })
] }, variation.name))
}
),
allowSkip && /* @__PURE__ */ (0, import_jsx_runtime336.jsx)("div", { className: "block-editor-block-variation-picker__skip", children: /* @__PURE__ */ (0, import_jsx_runtime336.jsx)(
import_components128.Button,
{
__next40pxDefaultSize: true,
variant: "link",
onClick: () => onSelect(),
children: (0, import_i18n117.__)("Skip")
}
) })
]
}
);
}
var block_variation_picker_default = BlockVariationPicker;
// packages/block-editor/build-module/components/block-pattern-setup/index.mjs
var import_data141 = __toESM(require_data(), 1);
var import_blocks81 = __toESM(require_blocks(), 1);
var import_components130 = __toESM(require_components(), 1);
var import_element198 = __toESM(require_element(), 1);
var import_compose77 = __toESM(require_compose(), 1);
var import_i18n119 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/block-pattern-setup/setup-toolbar.mjs
var import_i18n118 = __toESM(require_i18n(), 1);
var import_components129 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/block-pattern-setup/constants.mjs
var VIEWMODES = {
carousel: "carousel",
grid: "grid"
};
// packages/block-editor/build-module/components/block-pattern-setup/setup-toolbar.mjs
var import_jsx_runtime337 = __toESM(require_jsx_runtime(), 1);
var Actions = ({ onBlockPatternSelect }) => /* @__PURE__ */ (0, import_jsx_runtime337.jsx)("div", { className: "block-editor-block-pattern-setup__actions", children: /* @__PURE__ */ (0, import_jsx_runtime337.jsx)(
import_components129.Button,
{
__next40pxDefaultSize: true,
variant: "primary",
onClick: onBlockPatternSelect,
children: (0, import_i18n118.__)("Choose")
}
) });
var CarouselNavigation = ({
handlePrevious,
handleNext,
activeSlide,
totalSlides
}) => /* @__PURE__ */ (0, import_jsx_runtime337.jsxs)("div", { className: "block-editor-block-pattern-setup__navigation", children: [
/* @__PURE__ */ (0, import_jsx_runtime337.jsx)(
import_components129.Button,
{
size: "compact",
icon: (0, import_i18n118.isRTL)() ? chevron_right_default : chevron_left_default,
label: (0, import_i18n118.__)("Previous pattern"),
onClick: handlePrevious,
disabled: activeSlide === 0,
accessibleWhenDisabled: true
}
),
/* @__PURE__ */ (0, import_jsx_runtime337.jsx)(
import_components129.Button,
{
size: "compact",
icon: (0, import_i18n118.isRTL)() ? chevron_left_default : chevron_right_default,
label: (0, import_i18n118.__)("Next pattern"),
onClick: handleNext,
disabled: activeSlide === totalSlides - 1,
accessibleWhenDisabled: true
}
)
] });
var SetupToolbar = ({
viewMode,
setViewMode,
handlePrevious,
handleNext,
activeSlide,
totalSlides,
onBlockPatternSelect
}) => {
const isCarouselView = viewMode === VIEWMODES.carousel;
const displayControls = /* @__PURE__ */ (0, import_jsx_runtime337.jsxs)("div", { className: "block-editor-block-pattern-setup__display-controls", children: [
/* @__PURE__ */ (0, import_jsx_runtime337.jsx)(
import_components129.Button,
{
size: "compact",
icon: stretch_full_width_default,
label: (0, import_i18n118.__)("Carousel view"),
onClick: () => setViewMode(VIEWMODES.carousel),
isPressed: isCarouselView
}
),
/* @__PURE__ */ (0, import_jsx_runtime337.jsx)(
import_components129.Button,
{
size: "compact",
icon: grid_default,
label: (0, import_i18n118.__)("Grid view"),
onClick: () => setViewMode(VIEWMODES.grid),
isPressed: viewMode === VIEWMODES.grid
}
)
] });
return /* @__PURE__ */ (0, import_jsx_runtime337.jsxs)("div", { className: "block-editor-block-pattern-setup__toolbar", children: [
isCarouselView && /* @__PURE__ */ (0, import_jsx_runtime337.jsx)(
CarouselNavigation,
{
handlePrevious,
handleNext,
activeSlide,
totalSlides
}
),
displayControls,
isCarouselView && /* @__PURE__ */ (0, import_jsx_runtime337.jsx)(Actions, { onBlockPatternSelect })
] });
};
var setup_toolbar_default = SetupToolbar;
// packages/block-editor/build-module/components/block-pattern-setup/use-patterns-setup.mjs
var import_data140 = __toESM(require_data(), 1);
function usePatternsSetup(clientId, blockName, filterPatternsFn) {
return (0, import_data140.useSelect)(
(select3) => {
const {
getBlockRootClientId: getBlockRootClientId2,
getPatternsByBlockTypes: getPatternsByBlockTypes2,
__experimentalGetAllowedPatterns: __experimentalGetAllowedPatterns2
} = select3(store);
const rootClientId = getBlockRootClientId2(clientId);
if (filterPatternsFn) {
return __experimentalGetAllowedPatterns2(rootClientId).filter(
filterPatternsFn
);
}
return getPatternsByBlockTypes2(blockName, rootClientId);
},
[clientId, blockName, filterPatternsFn]
);
}
var use_patterns_setup_default = usePatternsSetup;
// packages/block-editor/build-module/components/block-pattern-setup/index.mjs
var import_jsx_runtime338 = __toESM(require_jsx_runtime(), 1);
var SetupContent = ({
viewMode,
activeSlide,
patterns,
onBlockPatternSelect,
showTitles
}) => {
const containerClass = "block-editor-block-pattern-setup__container";
if (viewMode === VIEWMODES.carousel) {
const slideClass = /* @__PURE__ */ new Map([
[activeSlide, "active-slide"],
[activeSlide - 1, "previous-slide"],
[activeSlide + 1, "next-slide"]
]);
return /* @__PURE__ */ (0, import_jsx_runtime338.jsx)("div", { className: "block-editor-block-pattern-setup__carousel", children: /* @__PURE__ */ (0, import_jsx_runtime338.jsx)("div", { className: containerClass, children: /* @__PURE__ */ (0, import_jsx_runtime338.jsx)("div", { className: "carousel-container", children: patterns.map((pattern, index2) => /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
BlockPatternSlide,
{
active: index2 === activeSlide,
className: slideClass.get(index2) || "",
pattern
},
pattern.name
)) }) }) });
}
return /* @__PURE__ */ (0, import_jsx_runtime338.jsx)("div", { className: "block-editor-block-pattern-setup__grid", children: /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
import_components130.Composite,
{
role: "listbox",
className: containerClass,
"aria-label": (0, import_i18n119.__)("Patterns list"),
children: patterns.map((pattern) => /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
BlockPattern3,
{
pattern,
onSelect: onBlockPatternSelect,
showTitles
},
pattern.name
))
}
) });
};
function BlockPattern3({ pattern, onSelect, showTitles }) {
const baseClassName = "block-editor-block-pattern-setup-list";
const { blocks: blocks2, description, viewportWidth = 700 } = pattern;
const descriptionId = (0, import_compose77.useInstanceId)(
BlockPattern3,
`${baseClassName}__item-description`
);
return /* @__PURE__ */ (0, import_jsx_runtime338.jsx)("div", { className: `${baseClassName}__list-item`, children: /* @__PURE__ */ (0, import_jsx_runtime338.jsxs)(
import_components130.Composite.Item,
{
render: /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
"div",
{
"aria-describedby": description ? descriptionId : void 0,
"aria-label": pattern.title,
className: `${baseClassName}__item`
}
),
id: `${baseClassName}__pattern__${pattern.name}`,
role: "option",
onClick: () => onSelect(blocks2),
children: [
/* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
block_preview_default,
{
blocks: blocks2,
viewportWidth
}
),
showTitles && /* @__PURE__ */ (0, import_jsx_runtime338.jsx)("div", { className: `${baseClassName}__item-title`, children: pattern.title }),
!!description && /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(VisuallyHidden, { id: descriptionId, children: description })
]
}
) });
}
function BlockPatternSlide({ active, className, pattern, minHeight }) {
const { blocks: blocks2, title, description } = pattern;
const descriptionId = (0, import_compose77.useInstanceId)(
BlockPatternSlide,
"block-editor-block-pattern-setup-list__item-description"
);
return /* @__PURE__ */ (0, import_jsx_runtime338.jsxs)(
"div",
{
"aria-hidden": !active,
role: "img",
className: `pattern-slide ${className}`,
"aria-label": title,
"aria-describedby": description ? descriptionId : void 0,
children: [
/* @__PURE__ */ (0, import_jsx_runtime338.jsx)(block_preview_default, { blocks: blocks2, minHeight }),
!!description && /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(VisuallyHidden, { id: descriptionId, children: description })
]
}
);
}
var BlockPatternSetup = ({
clientId,
blockName,
filterPatternsFn,
onBlockPatternSelect,
initialViewMode = VIEWMODES.carousel,
showTitles = false
}) => {
const [viewMode, setViewMode] = (0, import_element198.useState)(initialViewMode);
const [activeSlide, setActiveSlide] = (0, import_element198.useState)(0);
const { replaceBlock: replaceBlock2 } = (0, import_data141.useDispatch)(store);
const patterns = use_patterns_setup_default(clientId, blockName, filterPatternsFn);
if (!patterns?.length) {
return null;
}
const onBlockPatternSelectDefault = (blocks2) => {
const clonedBlocks = blocks2.map((block) => (0, import_blocks81.cloneBlock)(block));
replaceBlock2(clientId, clonedBlocks);
};
const onPatternSelectCallback = onBlockPatternSelect || onBlockPatternSelectDefault;
return /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(import_jsx_runtime338.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime338.jsxs)(
"div",
{
className: `block-editor-block-pattern-setup view-mode-${viewMode}`,
children: [
/* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
SetupContent,
{
viewMode,
activeSlide,
patterns,
onBlockPatternSelect: onPatternSelectCallback,
showTitles
}
),
/* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
setup_toolbar_default,
{
viewMode,
setViewMode,
activeSlide,
totalSlides: patterns.length,
handleNext: () => {
setActiveSlide(
(active) => Math.min(active + 1, patterns.length - 1)
);
},
handlePrevious: () => {
setActiveSlide(
(active) => Math.max(active - 1, 0)
);
},
onBlockPatternSelect: () => {
onPatternSelectCallback(
patterns[activeSlide].blocks
);
}
}
)
]
}
) });
};
var block_pattern_setup_default = BlockPatternSetup;
// packages/block-editor/build-module/components/block-variation-transforms/index.mjs
var import_blocks82 = __toESM(require_blocks(), 1);
var import_i18n120 = __toESM(require_i18n(), 1);
var import_components131 = __toESM(require_components(), 1);
var import_data142 = __toESM(require_data(), 1);
var import_element199 = __toESM(require_element(), 1);
var import_jsx_runtime339 = __toESM(require_jsx_runtime(), 1);
var { Menu: Menu3 } = unlock(import_components131.privateApis);
function VariationsButtons({
className,
onSelectVariation,
selectedValue,
variations
}) {
return /* @__PURE__ */ (0, import_jsx_runtime339.jsxs)("fieldset", { className, children: [
/* @__PURE__ */ (0, import_jsx_runtime339.jsx)(VisuallyHidden, { render: /* @__PURE__ */ (0, import_jsx_runtime339.jsx)("legend", {}), children: (0, import_i18n120.__)("Transform to variation") }),
variations.map((variation) => /* @__PURE__ */ (0, import_jsx_runtime339.jsx)(
import_components131.Button,
{
__next40pxDefaultSize: true,
size: "compact",
icon: /* @__PURE__ */ (0, import_jsx_runtime339.jsx)(block_icon_default, { icon: variation.icon, showColors: true }),
isPressed: selectedValue === variation.name,
label: selectedValue === variation.name ? variation.title : (0, import_i18n120.sprintf)(
/* translators: %s: Block or block variation name. */
(0, import_i18n120.__)("Transform to %s"),
variation.title
),
onClick: () => onSelectVariation(variation.name),
"aria-label": variation.title,
showTooltip: true
},
variation.name
))
] });
}
function VariationsDropdown({
className,
onSelectVariation,
selectedValue,
variations
}) {
return /* @__PURE__ */ (0, import_jsx_runtime339.jsx)("div", { className, children: /* @__PURE__ */ (0, import_jsx_runtime339.jsxs)(Menu3, { children: [
/* @__PURE__ */ (0, import_jsx_runtime339.jsx)(
Menu3.TriggerButton,
{
render: /* @__PURE__ */ (0, import_jsx_runtime339.jsx)(
import_components131.Button,
{
className: "block-editor-block-variation-transforms__button",
__next40pxDefaultSize: true,
variant: "secondary",
children: (0, import_i18n120.__)("Transform to variation")
}
)
}
),
/* @__PURE__ */ (0, import_jsx_runtime339.jsx)(Menu3.Popover, { position: "bottom", children: /* @__PURE__ */ (0, import_jsx_runtime339.jsx)(Menu3.Group, { children: variations.map((variation) => /* @__PURE__ */ (0, import_jsx_runtime339.jsxs)(
Menu3.RadioItem,
{
value: variation.name,
checked: selectedValue === variation.name,
onChange: () => onSelectVariation(variation.name),
children: [
/* @__PURE__ */ (0, import_jsx_runtime339.jsx)(Menu3.ItemLabel, { children: variation.title }),
variation.description && /* @__PURE__ */ (0, import_jsx_runtime339.jsx)(Menu3.ItemHelpText, { children: variation.description })
]
},
variation.name
)) }) })
] }) });
}
function VariationsToggleGroupControl({
className,
onSelectVariation,
selectedValue,
variations
}) {
return /* @__PURE__ */ (0, import_jsx_runtime339.jsx)("div", { className, children: /* @__PURE__ */ (0, import_jsx_runtime339.jsx)(
import_components131.__experimentalToggleGroupControl,
{
label: (0, import_i18n120.__)("Transform to variation"),
value: selectedValue,
hideLabelFromVision: true,
onChange: onSelectVariation,
children: variations.map((variation) => /* @__PURE__ */ (0, import_jsx_runtime339.jsx)(
import_components131.__experimentalToggleGroupControlOptionIcon,
{
icon: /* @__PURE__ */ (0, import_jsx_runtime339.jsx)(block_icon_default, { icon: variation.icon, showColors: true }),
value: variation.name,
label: selectedValue === variation.name ? variation.title : (0, import_i18n120.sprintf)(
/* translators: %s: Block or block variation name. */
(0, import_i18n120.__)("Transform to %s"),
variation.title
)
},
variation.name
))
}
) });
}
function BlockVariationTransforms({ blockClientId }) {
const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data142.useDispatch)(store);
const {
activeBlockVariation,
variations,
canEdit,
isContentOnly,
isSection
} = (0, import_data142.useSelect)(
(select3) => {
const { getActiveBlockVariation, getBlockVariations: getBlockVariations2 } = select3(import_blocks82.store);
const {
getBlockName: getBlockName2,
getBlockAttributes: getBlockAttributes3,
getBlockEditingMode: getBlockEditingMode2,
isSectionBlock: isSectionBlock2
} = unlock(select3(store));
const { canEditBlock: canEditBlock2 } = select3(store);
const name = blockClientId && getBlockName2(blockClientId);
const { hasContentRoleAttribute } = unlock(select3(import_blocks82.store));
const isContentBlock4 = hasContentRoleAttribute(name);
return {
activeBlockVariation: getActiveBlockVariation(
name,
getBlockAttributes3(blockClientId),
"transform"
),
variations: name && getBlockVariations2(name, "transform"),
canEdit: canEditBlock2(blockClientId),
isContentOnly: getBlockEditingMode2(blockClientId) === "contentOnly" && !isContentBlock4,
isSection: isSectionBlock2(blockClientId)
};
},
[blockClientId]
);
const selectedValue = activeBlockVariation?.name;
const hasUniqueIcons = (0, import_element199.useMemo)(() => {
const variationIcons = /* @__PURE__ */ new Set();
if (!variations) {
return false;
}
variations.forEach((variation) => {
if (variation.icon) {
variationIcons.add(variation.icon?.src || variation.icon);
}
});
return variationIcons.size === variations.length;
}, [variations]);
const onSelectVariation = (variationName) => {
updateBlockAttributes2(blockClientId, {
...variations.find(({ name }) => name === variationName).attributes
});
};
if (!variations?.length || !canEdit || isContentOnly || isSection) {
return null;
}
const baseClass = "block-editor-block-variation-transforms";
const showButtons = variations.length > 6;
const ButtonComponent = showButtons ? VariationsButtons : VariationsToggleGroupControl;
const Component6 = hasUniqueIcons ? ButtonComponent : VariationsDropdown;
return /* @__PURE__ */ (0, import_jsx_runtime339.jsx)(
Component6,
{
className: baseClass,
onSelectVariation,
selectedValue,
variations
}
);
}
var block_variation_transforms_default = BlockVariationTransforms;
// packages/block-editor/build-module/components/block-vertical-alignment-control/ui.mjs
var import_i18n121 = __toESM(require_i18n(), 1);
var import_components132 = __toESM(require_components(), 1);
var import_jsx_runtime340 = __toESM(require_jsx_runtime(), 1);
var BLOCK_ALIGNMENTS_CONTROLS2 = {
top: {
icon: justify_top_default,
title: (0, import_i18n121._x)("Align top", "Block vertical alignment setting")
},
center: {
icon: justify_center_vertical_default,
title: (0, import_i18n121._x)("Align middle", "Block vertical alignment setting")
},
bottom: {
icon: justify_bottom_default,
title: (0, import_i18n121._x)("Align bottom", "Block vertical alignment setting")
},
stretch: {
icon: justify_stretch_vertical_default,
title: (0, import_i18n121._x)("Stretch to fill", "Block vertical alignment setting")
},
"space-between": {
icon: justify_space_between_vertical_default,
title: (0, import_i18n121._x)("Space between", "Block vertical alignment setting")
}
};
var DEFAULT_CONTROLS2 = ["top", "center", "bottom"];
var DEFAULT_CONTROL2 = "top";
function BlockVerticalAlignmentUI({
value,
onChange,
controls = DEFAULT_CONTROLS2,
isCollapsed: isCollapsed3 = true,
isToolbar
}) {
function applyOrUnset(align) {
return () => onChange(value === align ? void 0 : align);
}
const activeAlignment = BLOCK_ALIGNMENTS_CONTROLS2[value];
const defaultAlignmentControl = BLOCK_ALIGNMENTS_CONTROLS2[DEFAULT_CONTROL2];
const UIComponent = isToolbar ? import_components132.ToolbarGroup : import_components132.ToolbarDropdownMenu;
const extraProps = isToolbar ? { isCollapsed: isCollapsed3 } : {};
return /* @__PURE__ */ (0, import_jsx_runtime340.jsx)(
UIComponent,
{
icon: activeAlignment ? activeAlignment.icon : defaultAlignmentControl.icon,
label: (0, import_i18n121._x)(
"Change vertical alignment",
"Block vertical alignment setting label"
),
controls: controls.map((control) => {
return {
...BLOCK_ALIGNMENTS_CONTROLS2[control],
isActive: value === control,
role: isCollapsed3 ? "menuitemradio" : void 0,
onClick: applyOrUnset(control)
};
}),
...extraProps
}
);
}
var ui_default3 = BlockVerticalAlignmentUI;
// packages/block-editor/build-module/components/block-vertical-alignment-control/index.mjs
var import_jsx_runtime341 = __toESM(require_jsx_runtime(), 1);
var BlockVerticalAlignmentControl = (props) => {
return /* @__PURE__ */ (0, import_jsx_runtime341.jsx)(ui_default3, { ...props, isToolbar: false });
};
var BlockVerticalAlignmentToolbar = (props) => {
return /* @__PURE__ */ (0, import_jsx_runtime341.jsx)(ui_default3, { ...props, isToolbar: true });
};
// packages/block-editor/build-module/components/border-radius-control/index.mjs
var import_components137 = __toESM(require_components(), 1);
var import_element201 = __toESM(require_element(), 1);
var import_i18n125 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/border-radius-control/linked-button.mjs
var import_components133 = __toESM(require_components(), 1);
var import_i18n122 = __toESM(require_i18n(), 1);
var import_jsx_runtime342 = __toESM(require_jsx_runtime(), 1);
function LinkedButton({ isLinked, ...props }) {
const label = isLinked ? (0, import_i18n122.__)("Unlink radii") : (0, import_i18n122.__)("Link radii");
return /* @__PURE__ */ (0, import_jsx_runtime342.jsx)(
import_components133.Button,
{
...props,
className: "components-border-radius-control__linked-button",
size: "small",
icon: isLinked ? link_default : link_off_default,
iconSize: 24,
label
}
);
}
// packages/block-editor/build-module/components/border-radius-control/utils.mjs
var import_components134 = __toESM(require_components(), 1);
function mode(inputArray) {
const arr = [...inputArray];
return arr.sort(
(a2, b2) => inputArray.filter((v2) => v2 === b2).length - inputArray.filter((v2) => v2 === a2).length
).shift();
}
function getAllValue(values = {}) {
if (typeof values === "string") {
return values;
}
const parsedQuantitiesAndUnits = Object.values(values).map((value2) => {
const newValue = (0, import_components134.__experimentalParseQuantityAndUnitFromRawValue)(value2);
if (typeof value2 === "string" && newValue[0] === void 0) {
return [value2, ""];
}
return newValue;
});
const allValues = parsedQuantitiesAndUnits.map(
(value2) => value2[0] ?? ""
);
const allUnits = parsedQuantitiesAndUnits.map((value2) => value2[1]);
const value = allValues.every((v2) => v2 === allValues[0]) ? allValues[0] : "";
const unit = mode(allUnits);
const allValue = value === 0 || value ? `${value}${unit || ""}` : void 0;
return allValue;
}
function hasMixedValues(values = {}) {
if (typeof values === "string") {
return false;
}
if (!values || typeof values !== "object") {
return false;
}
const cornerValues = Object.values(values);
if (cornerValues.length === 0) {
return false;
}
const firstValue = cornerValues[0];
const allSame = cornerValues.every((value) => value === firstValue);
return !allSame;
}
function hasDefinedValues(values) {
if (!values) {
return false;
}
if (typeof values === "string") {
return true;
}
const filteredValues = Object.values(values).filter((value) => {
return !!value || value === 0;
});
return !!filteredValues.length;
}
// packages/block-editor/build-module/components/preset-input-control/index.mjs
var import_components136 = __toESM(require_components(), 1);
var import_compose78 = __toESM(require_compose(), 1);
var import_i18n123 = __toESM(require_i18n(), 1);
var import_element200 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/preset-input-control/constants.mjs
var ICON_SIZE = 24;
var RANGE_CONTROL_MAX_SIZE2 = 8;
var CUSTOM_VALUE_SETTINGS = {
px: { max: 300, steps: 1 },
"%": { max: 100, steps: 1 },
vw: { max: 100, steps: 1 },
vh: { max: 100, steps: 1 },
em: { max: 10, steps: 0.1 },
rem: { max: 10, steps: 0.1 },
svw: { max: 100, steps: 1 },
lvw: { max: 100, steps: 1 },
dvw: { max: 100, steps: 1 },
svh: { max: 100, steps: 1 },
lvh: { max: 100, steps: 1 },
dvh: { max: 100, steps: 1 },
vi: { max: 100, steps: 1 },
svi: { max: 100, steps: 1 },
lvi: { max: 100, steps: 1 },
dvi: { max: 100, steps: 1 },
vb: { max: 100, steps: 1 },
svb: { max: 100, steps: 1 },
lvb: { max: 100, steps: 1 },
dvb: { max: 100, steps: 1 },
vmin: { max: 100, steps: 1 },
svmin: { max: 100, steps: 1 },
lvmin: { max: 100, steps: 1 },
dvmin: { max: 100, steps: 1 },
vmax: { max: 100, steps: 1 },
svmax: { max: 100, steps: 1 },
lvmax: { max: 100, steps: 1 },
dvmax: { max: 100, steps: 1 }
};
// packages/block-editor/build-module/components/preset-input-control/utils.mjs
var isValuePreset = (value, slug) => {
if (!value?.includes) {
return false;
}
return value === "0" || value.includes(`var:preset|${slug}|`);
};
function getPresetSlug(value, presetType) {
if (!value) {
return;
}
if (value === "0" || value === "default") {
return value;
}
const slug = value.match(
new RegExp(`var:preset\\|${presetType}\\|(.+)`)
);
return slug ? slug[1] : void 0;
}
function getSliderValueFromPreset(presetValue, presets, presetType) {
if (presetValue === void 0) {
return 0;
}
const slug = parseFloat(presetValue, 10) === 0 ? "0" : getPresetSlug(presetValue, presetType);
const sliderValue = presets.findIndex((size4) => {
return String(size4.slug) === slug;
});
return sliderValue !== -1 ? sliderValue : NaN;
}
function getCustomValueFromPreset2(value, presets, presetType) {
if (!isValuePreset(value, presetType)) {
return value;
}
const slug = parseFloat(value, 10) === 0 ? "0" : getPresetSlug(value, presetType);
const preset = presets.find((size4) => String(size4.slug) === slug);
return preset?.size;
}
function getPresetValueFromCustomValue2(value, spacingSizes, presetType) {
if (!value || isValuePreset(value, presetType) || value === "0") {
return value;
}
const spacingMatch = spacingSizes.find(
(size4) => String(size4.size) === String(value)
);
if (spacingMatch?.slug) {
return `var:preset|${presetType}|${spacingMatch.slug}`;
}
return value;
}
// packages/block-editor/build-module/components/preset-input-control/custom-value-controls.mjs
var import_components135 = __toESM(require_components(), 1);
var import_jsx_runtime343 = __toESM(require_jsx_runtime(), 1);
function CustomValueControls({
allowNegativeOnDrag,
ariaLabel,
allPlaceholder,
minValue,
parsedQuantity,
computedUnit,
units: units2,
isMixed,
step,
max: max2,
showTooltip,
value,
minimumCustomValue,
onCustomValueChange,
onCustomValueSliderChange,
onUnitChange,
onMouseOut,
onMouseOver,
setMinValue
}) {
const unitControl = /* @__PURE__ */ (0, import_jsx_runtime343.jsx)(
import_components135.__experimentalUnitControl,
{
className: "preset-input-control__unit-control",
disableUnits: isMixed,
hideLabelFromVision: true,
label: ariaLabel,
min: minValue,
onChange: onCustomValueChange,
onUnitChange,
onBlur: onMouseOut,
onFocus: onMouseOver,
onMouseOut,
onMouseOver,
units: units2,
value: [parsedQuantity, computedUnit].join(""),
placeholder: allPlaceholder,
onDragStart: () => {
if (allowNegativeOnDrag && value?.charAt(0) === "-") {
setMinValue(0);
}
},
onDrag: () => {
if (allowNegativeOnDrag && value?.charAt(0) === "-") {
setMinValue(0);
}
},
onDragEnd: () => {
if (allowNegativeOnDrag) {
setMinValue(minimumCustomValue);
}
}
}
);
const wrappedUnitControl = showTooltip ? /* @__PURE__ */ (0, import_jsx_runtime343.jsxs)(tooltip_exports.Root, { children: [
/* @__PURE__ */ (0, import_jsx_runtime343.jsx)(
tooltip_exports.Trigger,
{
render: /* @__PURE__ */ (0, import_jsx_runtime343.jsx)("div", { className: "preset-input-control__tooltip-wrapper", children: unitControl })
}
),
/* @__PURE__ */ (0, import_jsx_runtime343.jsx)(tooltip_exports.Popup, { children: ariaLabel })
] }) : unitControl;
return /* @__PURE__ */ (0, import_jsx_runtime343.jsxs)(import_jsx_runtime343.Fragment, { children: [
wrappedUnitControl,
/* @__PURE__ */ (0, import_jsx_runtime343.jsx)(
import_components135.RangeControl,
{
className: "preset-input-control__custom-value-range",
hideLabelFromVision: true,
initialPosition: 0,
label: ariaLabel,
max: max2,
min: 0,
onBlur: onMouseOut,
onChange: onCustomValueSliderChange,
onFocus: onMouseOver,
onMouseOut,
onMouseOver,
step,
value: parsedQuantity,
withInputField: false
}
)
] });
}
// packages/block-editor/build-module/components/preset-input-control/index.mjs
var import_jsx_runtime344 = __toESM(require_jsx_runtime(), 1);
function PresetInputControl({
allowNegativeOnDrag = false,
ariaLabel,
className: classNameProp,
customValueSettings = CUSTOM_VALUE_SETTINGS,
disableCustomValues,
icon,
isMixed,
value: valueProp,
minimumCustomValue,
onChange,
onMouseOut,
onMouseOver,
onUnitChange,
presets = [],
presetType,
selectedUnit,
showTooltip,
units: units2
}) {
const value = (0, import_element200.useMemo)(
() => getPresetValueFromCustomValue2(valueProp, presets, presetType),
[valueProp, presets, presetType]
);
const className = classNameProp ?? "preset-input-control";
const marks = presets.slice(1, presets.length - 1).map((_newValue, index2) => ({
value: index2 + 1,
label: void 0
}));
const hasPresets = marks.length > 0;
const showRangeControl = presets.length <= RANGE_CONTROL_MAX_SIZE2;
const allPlaceholder = isMixed ? (0, import_i18n123.__)("Mixed") : null;
const [minValue, setMinValue] = (0, import_element200.useState)(minimumCustomValue);
const [showCustomValueControl, setShowCustomValueControl] = (0, import_element200.useState)(
!disableCustomValues && value !== void 0 && !isValuePreset(value, presetType)
);
let currentValue = null;
const previousValue = (0, import_compose78.usePrevious)(value);
(0, import_element200.useEffect)(() => {
if (!!value && previousValue !== value && !isValuePreset(value, presetType) && showCustomValueControl !== true) {
setShowCustomValueControl(true);
}
}, [value, previousValue, presetType, showCustomValueControl]);
const showCustomValueInSelectList = !showRangeControl && !showCustomValueControl && value !== void 0 && (!isValuePreset(value, presetType) || isValuePreset(value, presetType) && isMixed);
let selectListOptions = presets;
if (showCustomValueInSelectList) {
selectListOptions = [
...presets,
{
name: !isMixed ? (
// translators: %s: A custom measurement, e.g. a number followed by a unit like 12px.
(0, import_i18n123.sprintf)((0, import_i18n123.__)("Custom (%s)"), value)
) : (0, import_i18n123.__)("Mixed"),
slug: "custom",
size: value
}
];
currentValue = selectListOptions.length - 1;
} else if (!isMixed) {
currentValue = !showCustomValueControl ? getSliderValueFromPreset(value, presets, presetType) : getCustomValueFromPreset2(value, presets, presetType);
}
const options = selectListOptions.map((size4, index2) => ({
key: index2,
name: size4.name
}));
const resolvedPresetValue = isValuePreset(value, presetType) ? getCustomValueFromPreset2(value, presets, presetType) : value;
const [parsedQuantity, parsedUnit] = (0, import_components136.__experimentalParseQuantityAndUnitFromRawValue)(resolvedPresetValue);
const computedUnit = parsedUnit || selectedUnit || "px";
const unitConfig = units2?.find((item) => item.value === computedUnit);
const step = unitConfig?.step ?? customValueSettings[computedUnit]?.steps ?? 0.1;
const max2 = unitConfig?.max ?? customValueSettings[computedUnit]?.max ?? 10;
const handleCustomValueChange = (newValue) => {
if (newValue === void 0 || newValue === "") {
onChange(void 0);
return;
}
if (isNaN(parseFloat(newValue))) {
return;
}
onChange(newValue);
};
const handleCustomValueSliderChange = (next) => {
onChange([next, computedUnit].join(""));
};
const customTooltipContent = (newValue) => value === void 0 ? void 0 : presets[newValue]?.name;
const getNewPresetValue = (next, controlType) => {
const newValue = parseInt(next, 10);
if (controlType === "selectList") {
if (newValue === 0 && presets[0]?.slug === "0") {
return "0";
}
if (newValue === 0) {
return void 0;
}
} else if (newValue === 0) {
return "0";
}
return `var:preset|${presetType}|${presets[next]?.slug}`;
};
return /* @__PURE__ */ (0, import_jsx_runtime344.jsxs)(
import_components136.__experimentalHStack,
{
className: `preset-input-control__wrapper ${className}__wrapper`,
children: [
icon && /* @__PURE__ */ (0, import_jsx_runtime344.jsx)(
import_components136.Icon,
{
className: "preset-input-control__icon",
icon,
size: ICON_SIZE
}
),
(!hasPresets || showCustomValueControl) && /* @__PURE__ */ (0, import_jsx_runtime344.jsx)(
CustomValueControls,
{
allowNegativeOnDrag,
ariaLabel,
allPlaceholder,
minValue,
parsedQuantity,
computedUnit,
units: units2,
isMixed,
step,
max: max2,
showTooltip,
value,
minimumCustomValue,
onCustomValueChange: handleCustomValueChange,
onCustomValueSliderChange: handleCustomValueSliderChange,
onUnitChange,
onMouseOut,
onMouseOver,
setMinValue
}
),
hasPresets && showRangeControl && !showCustomValueControl && /* @__PURE__ */ (0, import_jsx_runtime344.jsx)(
import_components136.RangeControl,
{
"aria-valuenow": currentValue,
"aria-valuetext": presets[currentValue]?.name,
className: "preset-input-control__preset-range",
hideLabelFromVision: true,
initialPosition: 0,
label: ariaLabel,
max: presets.length - 1,
marks,
min: 0,
onBlur: onMouseOut,
onChange: (newValue) => onChange(getNewPresetValue(newValue)),
onFocus: onMouseOver,
onMouseDown: (event) => {
const nearStart = event?.nativeEvent?.offsetX < 35;
if (nearStart && value === void 0) {
onChange("0");
}
},
onMouseOut,
onMouseOver,
renderTooltipContent: customTooltipContent,
step: 1,
value: currentValue,
withInputField: false
}
),
hasPresets && !showRangeControl && !showCustomValueControl && /* @__PURE__ */ (0, import_jsx_runtime344.jsx)(
import_components136.CustomSelectControl,
{
className: "preset-input-control__custom-select-control",
hideLabelFromVision: true,
label: ariaLabel,
onBlur: onMouseOut,
onChange: (selection2) => {
if (showCustomValueInSelectList && selection2.selectedItem.key === options.length - 1) {
setShowCustomValueControl(true);
} else {
onChange(
getNewPresetValue(
selection2.selectedItem.key,
"selectList"
)
);
}
},
onFocus: onMouseOver,
onMouseOut,
onMouseOver,
options,
value: (
// passing empty string as a fallback to continue using the
// component in controlled mode
options.find(
(option) => option.key === currentValue
) || ""
)
}
),
hasPresets && !disableCustomValues && /* @__PURE__ */ (0, import_jsx_runtime344.jsx)(
import_components136.Button,
{
className: "preset-input-control__custom-toggle",
icon: settings_default,
iconSize: ICON_SIZE,
isPressed: showCustomValueControl,
label: showCustomValueControl ? (0, import_i18n123.__)("Use preset") : (0, import_i18n123.__)("Set custom value"),
onClick: () => {
setShowCustomValueControl(!showCustomValueControl);
},
size: "small"
}
)
]
}
);
}
// packages/block-editor/build-module/components/border-radius-control/constants.mjs
var import_i18n124 = __toESM(require_i18n(), 1);
var RANGE_CONTROL_MAX_SIZE3 = 8;
var EMPTY_ARRAY10 = [];
var CORNERS = {
all: (0, import_i18n124.__)("Border radius"),
topLeft: (0, import_i18n124.__)("Top left"),
topRight: (0, import_i18n124.__)("Top right"),
bottomLeft: (0, import_i18n124.__)("Bottom left"),
bottomRight: (0, import_i18n124.__)("Bottom right")
};
var ICONS2 = {
all: corner_all_default,
topLeft: corner_top_left_default,
topRight: corner_top_right_default,
bottomLeft: corner_bottom_left_default,
bottomRight: corner_bottom_right_default
};
var MIN_BORDER_RADIUS_VALUE = 0;
// packages/block-editor/build-module/components/border-radius-control/index.mjs
var import_jsx_runtime345 = __toESM(require_jsx_runtime(), 1);
function useBorderRadiusSizes(presets) {
const defaultSizes = presets?.default ?? EMPTY_ARRAY10;
const customSizes = presets?.custom ?? EMPTY_ARRAY10;
const themeSizes = presets?.theme ?? EMPTY_ARRAY10;
return (0, import_element201.useMemo)(() => {
const sizes = [
{ name: (0, import_i18n125.__)("None"), slug: "0", size: 0 },
...customSizes,
...themeSizes,
...defaultSizes
];
return sizes.length > RANGE_CONTROL_MAX_SIZE3 ? [
{
name: (0, import_i18n125.__)("Default"),
slug: "default",
size: void 0
},
...sizes
] : sizes;
}, [customSizes, themeSizes, defaultSizes]);
}
function getCornerValue(values, corner) {
if (corner === "all") {
return getAllValue(values);
}
if (typeof values === "string") {
return values;
}
return values?.[corner];
}
function getCornerUnit(selectedUnits, corner) {
if (corner === "all") {
return selectedUnits.flat;
}
return selectedUnits[corner];
}
function createCornerChangeHandler(corner, values, onChange) {
return (newValue) => {
if (corner === "all") {
onChange({
topLeft: newValue,
topRight: newValue,
bottomLeft: newValue,
bottomRight: newValue
});
} else {
const currentValues = typeof values !== "string" ? values || {} : {
topLeft: values,
topRight: values,
bottomLeft: values,
bottomRight: values
};
onChange({
...currentValues,
[corner]: newValue
});
}
};
}
function createCornerUnitChangeHandler(corner, selectedUnits, setSelectedUnits) {
return (newUnit) => {
const newUnits = { ...selectedUnits };
if (corner === "all") {
newUnits.flat = newUnit;
newUnits.topLeft = newUnit;
newUnits.topRight = newUnit;
newUnits.bottomLeft = newUnit;
newUnits.bottomRight = newUnit;
} else {
newUnits[corner] = newUnit;
}
setSelectedUnits(newUnits);
};
}
function BorderRadiusControl({ onChange, values, presets }) {
const [isLinked, setIsLinked] = (0, import_element201.useState)(
!hasDefinedValues(values) || !hasMixedValues(values)
);
const options = useBorderRadiusSizes(presets);
const [selectedUnits, setSelectedUnits] = (0, import_element201.useState)({
flat: typeof values === "string" ? (0, import_components137.__experimentalParseQuantityAndUnitFromRawValue)(values)[1] : void 0,
topLeft: (0, import_components137.__experimentalParseQuantityAndUnitFromRawValue)(values?.topLeft)[1],
topRight: (0, import_components137.__experimentalParseQuantityAndUnitFromRawValue)(values?.topRight)[1],
bottomLeft: (0, import_components137.__experimentalParseQuantityAndUnitFromRawValue)(values?.bottomLeft)[1],
bottomRight: (0, import_components137.__experimentalParseQuantityAndUnitFromRawValue)(
values?.bottomRight
)[1]
});
const [availableUnits] = useSettings("spacing.units");
const units2 = (0, import_components137.__experimentalUseCustomUnits)({
availableUnits: availableUnits || ["px", "em", "rem"]
});
const toggleLinked = () => setIsLinked(!isLinked);
return /* @__PURE__ */ (0, import_jsx_runtime345.jsxs)("fieldset", { className: "components-border-radius-control", children: [
/* @__PURE__ */ (0, import_jsx_runtime345.jsxs)(import_components137.__experimentalHStack, { className: "components-border-radius-control__header", children: [
/* @__PURE__ */ (0, import_jsx_runtime345.jsx)(import_components137.BaseControl.VisualLabel, { as: "legend", children: (0, import_i18n125.__)("Radius") }),
/* @__PURE__ */ (0, import_jsx_runtime345.jsx)(LinkedButton, { onClick: toggleLinked, isLinked })
] }),
isLinked ? /* @__PURE__ */ (0, import_jsx_runtime345.jsx)(
PresetInputControl,
{
ariaLabel: CORNERS.all,
className: "components-border-radius-control",
icon: ICONS2.all,
minimumCustomValue: MIN_BORDER_RADIUS_VALUE,
onChange: createCornerChangeHandler(
"all",
values,
onChange
),
onUnitChange: createCornerUnitChangeHandler(
"all",
selectedUnits,
setSelectedUnits
),
presets: options,
presetType: "border-radius",
selectedUnit: getCornerUnit(selectedUnits, "all"),
showTooltip: true,
units: units2,
value: getCornerValue(values, "all")
}
) : /* @__PURE__ */ (0, import_jsx_runtime345.jsx)(import_components137.__experimentalVStack, { children: [
"topLeft",
"topRight",
"bottomLeft",
"bottomRight"
].map((corner) => /* @__PURE__ */ (0, import_jsx_runtime345.jsx)(
PresetInputControl,
{
ariaLabel: CORNERS[corner],
className: "components-border-radius-control",
icon: ICONS2[corner],
minimumCustomValue: MIN_BORDER_RADIUS_VALUE,
onChange: createCornerChangeHandler(
corner,
values,
onChange
),
onUnitChange: createCornerUnitChangeHandler(
corner,
selectedUnits,
setSelectedUnits
),
presets: options,
presetType: "border-radius",
selectedUnit: getCornerUnit(
selectedUnits,
corner
),
showTooltip: true,
units: units2,
value: getCornerValue(values, corner)
},
corner
)) })
] });
}
// packages/block-editor/build-module/components/color-palette/index.mjs
var import_components138 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/color-palette/with-color-context.mjs
var import_compose79 = __toESM(require_compose(), 1);
var import_jsx_runtime346 = __toESM(require_jsx_runtime(), 1);
var with_color_context_default = (0, import_compose79.createHigherOrderComponent)((WrappedComponent) => {
return function WithColorContext(props) {
const [
defaultColors,
themeColors,
customColors,
enableCustomColors,
enableDefaultColors
] = useSettings(
"color.palette.default",
"color.palette.theme",
"color.palette.custom",
"color.custom",
"color.defaultPalette"
);
const _colors = enableDefaultColors ? [
...themeColors || [],
...defaultColors || [],
...customColors || []
] : [...themeColors || [], ...customColors || []];
const { colors: colors2 = _colors, disableCustomColors = !enableCustomColors } = props;
const hasColorsToChoose = colors2 && colors2.length > 0 || !disableCustomColors;
return /* @__PURE__ */ (0, import_jsx_runtime346.jsx)(
WrappedComponent,
{
...{
...props,
colors: colors2,
disableCustomColors,
hasColorsToChoose
}
}
);
};
}, "withColorContext");
// packages/block-editor/build-module/components/color-palette/index.mjs
var color_palette_default = with_color_context_default(import_components138.ColorPalette);
// packages/block-editor/build-module/components/colors-gradients/control.mjs
var import_i18n126 = __toESM(require_i18n(), 1);
var import_components139 = __toESM(require_components(), 1);
var import_jsx_runtime347 = __toESM(require_jsx_runtime(), 1);
var { Tabs: Tabs3 } = unlock(import_components139.privateApis);
var colorsAndGradientKeys = [
"colors",
"disableCustomColors",
"gradients",
"disableCustomGradients"
];
var TAB_IDS = { color: "color", gradient: "gradient" };
function ColorGradientControlInner({
colors: colors2,
gradients,
disableCustomColors,
disableCustomGradients,
__experimentalIsRenderedInSidebar,
className,
label,
onColorChange,
onGradientChange,
colorValue,
colorSlug,
gradientValue,
clearable,
showTitle = true,
enableAlpha,
headingLevel,
noticeProps
}) {
const canChooseAColor = onColorChange && (colors2 && colors2.length > 0 || !disableCustomColors);
const canChooseAGradient = onGradientChange && (gradients && gradients.length > 0 || !disableCustomGradients);
if (!canChooseAColor && !canChooseAGradient) {
return null;
}
const colorPaletteOnChange = canChooseAGradient ? (newColor, _index, newSlug) => {
onColorChange(newColor, newSlug);
onGradientChange();
} : (newColor, _index, newSlug) => onColorChange(newColor, newSlug);
const colorPalette = /* @__PURE__ */ (0, import_jsx_runtime347.jsx)(
import_components139.ColorPalette,
{
value: colorValue,
selectedSlug: colorSlug,
onChange: colorPaletteOnChange,
...{ colors: colors2, disableCustomColors },
__experimentalIsRenderedInSidebar,
clearable,
enableAlpha,
headingLevel
}
);
const tabPanels = {
// The `ColorPalette` must stay at a stable position in the tree whether
// or not a notice is present. Wrapping it in a `VStack` only when a
// notice appears remounts it, which resets the custom color picker back
// to the swatch view mid-edit. Keep `ColorPalette` first and toggle only
// the trailing notice after it, so the palette holds a stable index and
// the notice sits at the bottom of the popover.
[TAB_IDS.color]: /* @__PURE__ */ (0, import_jsx_runtime347.jsxs)(import_jsx_runtime347.Fragment, { children: [
colorPalette,
noticeProps && /* @__PURE__ */ (0, import_jsx_runtime347.jsx)(import_components139.Notice, { isDismissible: false, ...noticeProps })
] }),
[TAB_IDS.gradient]: /* @__PURE__ */ (0, import_jsx_runtime347.jsx)(
import_components139.GradientPicker,
{
value: gradientValue,
onChange: canChooseAColor ? (newGradient) => {
onGradientChange(newGradient);
onColorChange();
} : onGradientChange,
...{ gradients, disableCustomGradients },
__experimentalIsRenderedInSidebar,
clearable,
headingLevel
}
)
};
const renderPanelType = (type) => /* @__PURE__ */ (0, import_jsx_runtime347.jsx)("div", { className: "block-editor-color-gradient-control__panel", children: tabPanels[type] });
return /* @__PURE__ */ (0, import_jsx_runtime347.jsx)(
import_components139.BaseControl,
{
className: clsx_default(
"block-editor-color-gradient-control",
className
),
children: /* @__PURE__ */ (0, import_jsx_runtime347.jsx)("fieldset", { className: "block-editor-color-gradient-control__fieldset", children: /* @__PURE__ */ (0, import_jsx_runtime347.jsxs)(import_components139.__experimentalVStack, { spacing: 1, children: [
showTitle && /* @__PURE__ */ (0, import_jsx_runtime347.jsx)("legend", { children: /* @__PURE__ */ (0, import_jsx_runtime347.jsx)("div", { className: "block-editor-color-gradient-control__color-indicator", children: /* @__PURE__ */ (0, import_jsx_runtime347.jsx)(import_components139.BaseControl.VisualLabel, { children: label }) }) }),
canChooseAColor && canChooseAGradient && /* @__PURE__ */ (0, import_jsx_runtime347.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime347.jsxs)(
Tabs3,
{
defaultTabId: gradientValue ? TAB_IDS.gradient : !!canChooseAColor && TAB_IDS.color,
children: [
/* @__PURE__ */ (0, import_jsx_runtime347.jsxs)(Tabs3.TabList, { children: [
/* @__PURE__ */ (0, import_jsx_runtime347.jsx)(Tabs3.Tab, { tabId: TAB_IDS.color, children: (0, import_i18n126.__)("Color") }),
/* @__PURE__ */ (0, import_jsx_runtime347.jsx)(Tabs3.Tab, { tabId: TAB_IDS.gradient, children: (0, import_i18n126.__)("Gradient") })
] }),
/* @__PURE__ */ (0, import_jsx_runtime347.jsx)(
Tabs3.TabPanel,
{
tabId: TAB_IDS.color,
className: "block-editor-color-gradient-control__panel",
focusable: false,
children: tabPanels.color
}
),
/* @__PURE__ */ (0, import_jsx_runtime347.jsx)(
Tabs3.TabPanel,
{
tabId: TAB_IDS.gradient,
className: "block-editor-color-gradient-control__panel",
focusable: false,
children: tabPanels.gradient
}
)
]
}
) }),
!canChooseAGradient && renderPanelType(TAB_IDS.color),
!canChooseAColor && renderPanelType(TAB_IDS.gradient)
] }) })
}
);
}
function ColorGradientControlSelect(props) {
const [colors2, gradients, customColors, customGradients] = useSettings(
"color.palette",
"color.gradients",
"color.custom",
"color.customGradient"
);
return /* @__PURE__ */ (0, import_jsx_runtime347.jsx)(
ColorGradientControlInner,
{
colors: colors2,
gradients,
disableCustomColors: !customColors,
disableCustomGradients: !customGradients,
...props
}
);
}
function ColorGradientControl(props) {
if (colorsAndGradientKeys.every((key) => props.hasOwnProperty(key))) {
return /* @__PURE__ */ (0, import_jsx_runtime347.jsx)(ColorGradientControlInner, { ...props });
}
return /* @__PURE__ */ (0, import_jsx_runtime347.jsx)(ColorGradientControlSelect, { ...props });
}
var control_default = ColorGradientControl;
// packages/block-editor/build-module/components/color-palette/control.mjs
var import_jsx_runtime348 = __toESM(require_jsx_runtime(), 1);
function ColorPaletteControl({
onChange,
value,
...otherProps
}) {
return /* @__PURE__ */ (0, import_jsx_runtime348.jsx)(
control_default,
{
...otherProps,
onColorChange: onChange,
colorValue: value,
gradients: [],
disableCustomGradients: true
}
);
}
// packages/block-editor/build-module/components/contrast-checker/index.mjs
var import_i18n127 = __toESM(require_i18n(), 1);
var import_components140 = __toESM(require_components(), 1);
var import_a11y17 = __toESM(require_a11y(), 1);
var import_jsx_runtime349 = __toESM(require_jsx_runtime(), 1);
k([names_default, a11y_default]);
function getContrastWarning({
backgroundColor,
fallbackBackgroundColor,
fallbackTextColor,
fallbackLinkColor,
fontSize,
// Font size value in pixels.
isLargeText,
textColor,
linkColor,
messageOverride,
enableAlphaChecker = false
}) {
const currentBackgroundColor = backgroundColor || fallbackBackgroundColor;
if (!currentBackgroundColor) {
return null;
}
const currentTextColor = textColor || fallbackTextColor;
const currentLinkColor = linkColor || fallbackLinkColor;
if (!currentTextColor && !currentLinkColor) {
return null;
}
const textColors = [
{
color: currentTextColor,
description: (0, import_i18n127.__)("text color")
},
{
color: currentLinkColor,
description: (0, import_i18n127.__)("link color")
}
];
const colordBackgroundColor = w(currentBackgroundColor);
const backgroundColorHasTransparency = colordBackgroundColor.alpha() < 1;
const backgroundColorBrightness = colordBackgroundColor.brightness();
const isReadableOptions = {
level: "AA",
size: isLargeText || isLargeText !== false && fontSize >= 24 ? "large" : "small"
};
let message2 = "";
let speakMessage = "";
for (const item of textColors) {
if (!item.color) {
continue;
}
const colordTextColor = w(item.color);
const isColordTextReadable = colordTextColor.isReadable(
colordBackgroundColor,
isReadableOptions
);
const textHasTransparency = colordTextColor.alpha() < 1;
if (!isColordTextReadable) {
if (backgroundColorHasTransparency || textHasTransparency) {
continue;
}
if (messageOverride) {
message2 = messageOverride;
speakMessage = messageOverride;
break;
}
message2 = backgroundColorBrightness < colordTextColor.brightness() ? (0, import_i18n127.sprintf)(
// translators: %s is a type of text color, e.g., "text color" or "link color".
(0, import_i18n127.__)(
"This color combination may be hard for people to read. Try using a darker background color and/or a brighter %s."
),
item.description
) : (0, import_i18n127.sprintf)(
// translators: %s is a type of text color, e.g., "text color" or "link color".
(0, import_i18n127.__)(
"This color combination may be hard for people to read. Try using a brighter background color and/or a darker %s."
),
item.description
);
speakMessage = (0, import_i18n127.__)(
"This color combination may be hard for people to read."
);
break;
}
if (textHasTransparency && enableAlphaChecker) {
message2 = (0, import_i18n127.__)("Transparent text may be hard for people to read.");
speakMessage = (0, import_i18n127.__)(
"Transparent text may be hard for people to read."
);
}
}
if (!message2) {
return null;
}
return { message: message2, speakMessage };
}
function ContrastChecker(props) {
const warning6 = getContrastWarning(props);
if (!warning6) {
return null;
}
(0, import_a11y17.speak)(warning6.speakMessage);
return /* @__PURE__ */ (0, import_jsx_runtime349.jsx)("div", { className: "block-editor-contrast-checker", children: /* @__PURE__ */ (0, import_jsx_runtime349.jsx)(
import_components140.Notice,
{
spokenMessage: null,
status: "warning",
isDismissible: false,
children: warning6.message
}
) });
}
var contrast_checker_default = ContrastChecker;
// packages/block-editor/build-module/components/date-format-picker/index.mjs
var import_i18n128 = __toESM(require_i18n(), 1);
var import_date = __toESM(require_date(), 1);
var import_element202 = __toESM(require_element(), 1);
var import_components141 = __toESM(require_components(), 1);
var import_jsx_runtime350 = __toESM(require_jsx_runtime(), 1);
var exampleDate = /* @__PURE__ */ new Date();
exampleDate.setDate(20);
exampleDate.setMonth(exampleDate.getMonth() - 3);
if (exampleDate.getMonth() === 4) {
exampleDate.setMonth(3);
}
function DateFormatPicker({
format: format6,
defaultFormat,
onChange
}) {
return /* @__PURE__ */ (0, import_jsx_runtime350.jsxs)(
import_components141.__experimentalVStack,
{
as: "fieldset",
spacing: 4,
className: "block-editor-date-format-picker",
children: [
/* @__PURE__ */ (0, import_jsx_runtime350.jsx)(VisuallyHidden, { render: /* @__PURE__ */ (0, import_jsx_runtime350.jsx)("legend", {}), children: (0, import_i18n128.__)("Date format") }),
/* @__PURE__ */ (0, import_jsx_runtime350.jsx)(
import_components141.ToggleControl,
{
label: (0, import_i18n128.__)("Default format"),
help: `${(0, import_i18n128.__)("Example:")} ${(0, import_date.dateI18n)(
defaultFormat,
exampleDate
)}`,
checked: !format6,
onChange: (checked) => onChange(checked ? null : defaultFormat)
}
),
format6 && /* @__PURE__ */ (0, import_jsx_runtime350.jsx)(NonDefaultControls, { format: format6, onChange })
]
}
);
}
function NonDefaultControls({ format: format6, onChange }) {
const suggestedFormats = [
.../* @__PURE__ */ new Set([
/* translators: See https://www.php.net/manual/datetime.format.php */
"Y-m-d",
/* translators: See https://www.php.net/manual/datetime.format.php */
(0, import_i18n128._x)("n/j/Y", "short date format"),
/* translators: See https://www.php.net/manual/datetime.format.php */
(0, import_i18n128._x)("n/j/Y g:i A", "short date format with time"),
/* translators: See https://www.php.net/manual/datetime.format.php */
(0, import_i18n128._x)("M j, Y", "medium date format"),
/* translators: See https://www.php.net/manual/datetime.format.php */
(0, import_i18n128._x)("M j, Y g:i A", "medium date format with time"),
/* translators: See https://www.php.net/manual/datetime.format.php */
(0, import_i18n128._x)("F j, Y", "long date format"),
/* translators: See https://www.php.net/manual/datetime.format.php */
(0, import_i18n128._x)("M j", "short date format without the year")
])
];
const suggestedOptions = [
...suggestedFormats.map((suggestedFormat, index2) => ({
key: `suggested-${index2}`,
name: (0, import_date.dateI18n)(suggestedFormat, exampleDate),
format: suggestedFormat
})),
{
key: "human-diff",
name: (0, import_date.humanTimeDiff)(exampleDate),
format: "human-diff"
}
];
const customOption = {
key: "custom",
name: (0, import_i18n128.__)("Custom"),
className: "block-editor-date-format-picker__custom-format-select-control__custom-option",
hint: (0, import_i18n128.__)("Enter your own date format")
};
const [isCustom, setIsCustom] = (0, import_element202.useState)(
() => !!format6 && !suggestedOptions.some((option) => option.format === format6)
);
return /* @__PURE__ */ (0, import_jsx_runtime350.jsxs)(import_components141.__experimentalVStack, { children: [
/* @__PURE__ */ (0, import_jsx_runtime350.jsx)(
import_components141.CustomSelectControl,
{
label: (0, import_i18n128.__)("Choose a format"),
options: [...suggestedOptions, customOption],
value: isCustom ? customOption : suggestedOptions.find(
(option) => option.format === format6
) ?? customOption,
onChange: ({ selectedItem }) => {
if (selectedItem === customOption) {
setIsCustom(true);
} else {
setIsCustom(false);
onChange(selectedItem.format);
}
}
}
),
isCustom && /* @__PURE__ */ (0, import_jsx_runtime350.jsx)(
import_components141.TextControl,
{
label: (0, import_i18n128.__)("Custom format"),
hideLabelFromVision: true,
help: (0, import_element202.createInterpolateElement)(
(0, import_i18n128.__)(
"Enter a date or time <Link>format string</Link>."
),
{
Link: /* @__PURE__ */ (0, import_jsx_runtime350.jsx)(
import_components141.ExternalLink,
{
href: (0, import_i18n128.__)(
"https://wordpress.org/documentation/article/customize-date-and-time-format/"
)
}
)
}
),
value: format6,
onChange: (value) => onChange(value)
}
)
] });
}
// packages/block-editor/build-module/components/duotone-control/index.mjs
var import_components142 = __toESM(require_components(), 1);
var import_i18n129 = __toESM(require_i18n(), 1);
var import_keycodes18 = __toESM(require_keycodes(), 1);
var import_compose80 = __toESM(require_compose(), 1);
var import_jsx_runtime351 = __toESM(require_jsx_runtime(), 1);
function DuotoneControl({
id: idProp,
colorPalette,
duotonePalette,
disableCustomColors,
disableCustomDuotone,
value,
onChange
}) {
let toolbarIcon;
if (value === "unset") {
toolbarIcon = /* @__PURE__ */ (0, import_jsx_runtime351.jsx)(import_components142.ColorIndicator, { className: "block-editor-duotone-control__unset-indicator" });
} else if (value) {
toolbarIcon = /* @__PURE__ */ (0, import_jsx_runtime351.jsx)(import_components142.DuotoneSwatch, { values: value });
} else {
toolbarIcon = /* @__PURE__ */ (0, import_jsx_runtime351.jsx)(icon_default, { icon: filter_default });
}
const actionLabel = (0, import_i18n129.__)("Apply duotone filter");
const id = (0, import_compose80.useInstanceId)(DuotoneControl, "duotone-control", idProp);
const descriptionId = `${id}__description`;
return /* @__PURE__ */ (0, import_jsx_runtime351.jsx)(
import_components142.Dropdown,
{
popoverProps: {
className: "block-editor-duotone-control__popover",
headerTitle: (0, import_i18n129.__)("Duotone")
},
renderToggle: ({ isOpen, onToggle }) => {
const openOnArrowDown = (event) => {
if (!isOpen && event.keyCode === import_keycodes18.DOWN) {
event.preventDefault();
onToggle();
}
};
return /* @__PURE__ */ (0, import_jsx_runtime351.jsx)(
import_components142.ToolbarButton,
{
showTooltip: true,
onClick: onToggle,
"aria-haspopup": "true",
"aria-expanded": isOpen,
onKeyDown: openOnArrowDown,
label: actionLabel,
icon: toolbarIcon
}
);
},
renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime351.jsxs)(import_components142.MenuGroup, { label: (0, import_i18n129.__)("Duotone"), children: [
/* @__PURE__ */ (0, import_jsx_runtime351.jsx)("p", { children: (0, import_i18n129.__)(
"Create a two-tone color effect without losing your original image."
) }),
/* @__PURE__ */ (0, import_jsx_runtime351.jsx)(
import_components142.DuotonePicker,
{
"aria-label": actionLabel,
"aria-describedby": descriptionId,
colorPalette,
duotonePalette,
disableCustomColors,
disableCustomDuotone,
value,
onChange
}
)
] })
}
);
}
var duotone_control_default = DuotoneControl;
// packages/block-editor/build-module/components/font-appearance-control/index.mjs
var import_components143 = __toESM(require_components(), 1);
var import_element203 = __toESM(require_element(), 1);
var import_i18n133 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/utils/get-font-styles-and-weights.mjs
var import_i18n132 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/utils/format-font-style.mjs
var import_i18n130 = __toESM(require_i18n(), 1);
function formatFontStyle(fontStyle) {
if (!fontStyle) {
return {};
}
if (typeof fontStyle === "object") {
return fontStyle;
}
let name;
switch (fontStyle) {
case "normal":
name = (0, import_i18n130._x)("Regular", "font style");
break;
case "italic":
name = (0, import_i18n130._x)("Italic", "font style");
break;
case "oblique":
name = (0, import_i18n130._x)("Oblique", "font style");
break;
default:
name = fontStyle;
break;
}
return { name, value: fontStyle };
}
// packages/block-editor/build-module/utils/format-font-weight.mjs
var import_i18n131 = __toESM(require_i18n(), 1);
function formatFontWeight(fontWeight) {
if (!fontWeight) {
return {};
}
if (typeof fontWeight === "object") {
return fontWeight;
}
let name;
switch (fontWeight) {
case "normal":
case "400":
name = (0, import_i18n131._x)("Regular", "font weight");
break;
case "bold":
case "700":
name = (0, import_i18n131._x)("Bold", "font weight");
break;
case "100":
name = (0, import_i18n131._x)("Thin", "font weight");
break;
case "200":
name = (0, import_i18n131._x)("Extra Light", "font weight");
break;
case "300":
name = (0, import_i18n131._x)("Light", "font weight");
break;
case "500":
name = (0, import_i18n131._x)("Medium", "font weight");
break;
case "600":
name = (0, import_i18n131._x)("Semi Bold", "font weight");
break;
case "800":
name = (0, import_i18n131._x)("Extra Bold", "font weight");
break;
case "900":
name = (0, import_i18n131._x)("Black", "font weight");
break;
case "1000":
name = (0, import_i18n131._x)("Extra Black", "font weight");
break;
default:
name = fontWeight;
break;
}
return { name, value: fontWeight };
}
// packages/block-editor/build-module/utils/get-font-styles-and-weights.mjs
var FONT_STYLES = [
{
name: (0, import_i18n132._x)("Regular", "font style"),
value: "normal"
},
{
name: (0, import_i18n132._x)("Italic", "font style"),
value: "italic"
}
];
var FONT_WEIGHTS = [
{
name: (0, import_i18n132._x)("Thin", "font weight"),
value: "100"
},
{
name: (0, import_i18n132._x)("Extra Light", "font weight"),
value: "200"
},
{
name: (0, import_i18n132._x)("Light", "font weight"),
value: "300"
},
{
name: (0, import_i18n132._x)("Regular", "font weight"),
value: "400"
},
{
name: (0, import_i18n132._x)("Medium", "font weight"),
value: "500"
},
{
name: (0, import_i18n132._x)("Semi Bold", "font weight"),
value: "600"
},
{
name: (0, import_i18n132._x)("Bold", "font weight"),
value: "700"
},
{
name: (0, import_i18n132._x)("Extra Bold", "font weight"),
value: "800"
},
{
name: (0, import_i18n132._x)("Black", "font weight"),
value: "900"
},
{
name: (0, import_i18n132._x)("Extra Black", "font weight"),
value: "1000"
}
];
function getFontStylesAndWeights(fontFamilyFaces) {
let fontStyles = [];
let fontWeights = [];
const combinedStyleAndWeightOptions = [];
const isSystemFont = !fontFamilyFaces || fontFamilyFaces?.length === 0;
let isVariableFont = false;
fontFamilyFaces?.forEach((face) => {
if ("string" === typeof face.fontWeight && /\s/.test(face.fontWeight.trim())) {
isVariableFont = true;
const [startStr, endStr] = face.fontWeight.split(" ");
const startValue = parseInt(startStr.slice(0, 1));
const endValue = endStr === "1000" ? 10 : parseInt(endStr.slice(0, 1));
for (let i2 = startValue; i2 <= endValue; i2++) {
const fontWeightValue = `${i2.toString()}00`;
if (!fontWeights.some(
(weight) => weight.value === fontWeightValue
)) {
fontWeights.push(formatFontWeight(fontWeightValue));
}
}
}
const fontWeight = formatFontWeight(
"number" === typeof face.fontWeight ? face.fontWeight.toString() : face.fontWeight
);
const fontStyle = formatFontStyle(face.fontStyle);
if (fontStyle && Object.keys(fontStyle).length) {
if (!fontStyles.some(
(style) => style.value === fontStyle.value
)) {
fontStyles.push(fontStyle);
}
}
if (fontWeight && Object.keys(fontWeight).length) {
if (!fontWeights.some(
(weight) => weight.value === fontWeight.value
)) {
if (!isVariableFont) {
fontWeights.push(fontWeight);
}
}
}
});
if (!fontWeights.some((weight) => (weight.value ?? "") >= "600")) {
fontWeights.push({
name: (0, import_i18n132._x)("Bold", "font weight"),
value: "700"
});
}
if (!fontStyles.some((style) => style.value === "italic")) {
fontStyles.push({
name: (0, import_i18n132._x)("Italic", "font style"),
value: "italic"
});
}
if (isSystemFont) {
fontStyles = FONT_STYLES;
fontWeights = FONT_WEIGHTS;
}
fontStyles = fontStyles.length === 0 ? FONT_STYLES : fontStyles;
fontWeights = fontWeights.length === 0 ? FONT_WEIGHTS : fontWeights;
fontStyles.forEach(({ name: styleName, value: styleValue }) => {
fontWeights.forEach(({ name: weightName, value: weightValue }) => {
const optionName = styleValue === "normal" ? weightName : (0, import_i18n132.sprintf)(
/* translators: 1: Font weight name. 2: Font style name. */
(0, import_i18n132._x)("%1$s %2$s", "font"),
weightName ?? "",
styleName ?? ""
);
combinedStyleAndWeightOptions.push({
key: `${styleValue}-${weightValue}`,
name: optionName ?? "",
style: {
fontStyle: styleValue,
fontWeight: weightValue
}
});
});
});
return {
fontStyles,
fontWeights,
combinedStyleAndWeightOptions,
isSystemFont,
isVariableFont
};
}
// packages/block-editor/build-module/components/font-appearance-control/index.mjs
var import_jsx_runtime352 = __toESM(require_jsx_runtime(), 1);
var getFontAppearanceLabel = (hasFontStyles, hasFontWeights) => {
if (!hasFontStyles) {
return (0, import_i18n133.__)("Font weight");
}
if (!hasFontWeights) {
return (0, import_i18n133.__)("Font style");
}
return (0, import_i18n133.__)("Appearance");
};
function FontAppearanceControl(props) {
const {
/**
* Start opting into the larger default height that will become the default size in a future version.
*
* @deprecated Default behavior since WordPress 7.1. Prop can be safely removed.
*/
__next40pxDefaultSize: _next40pxDefaultSize,
onChange,
hasFontStyles = true,
hasFontWeights = true,
fontFamilyFaces,
value: { fontStyle, fontWeight },
...otherProps
} = props;
const hasStylesOrWeights = hasFontStyles || hasFontWeights;
const label = getFontAppearanceLabel(hasFontStyles, hasFontWeights);
const defaultOption = {
key: "default",
name: (0, import_i18n133.__)("Default"),
style: { fontStyle: void 0, fontWeight: void 0 }
};
const { fontStyles, fontWeights, combinedStyleAndWeightOptions } = getFontStylesAndWeights(fontFamilyFaces);
const combineOptions = () => {
const combinedOptions = [defaultOption];
if (combinedStyleAndWeightOptions) {
combinedOptions.push(...combinedStyleAndWeightOptions);
}
return combinedOptions;
};
const styleOptions = () => {
const combinedOptions = [defaultOption];
fontStyles.forEach(({ name, value }) => {
combinedOptions.push({
key: value,
name,
style: { fontStyle: value, fontWeight: void 0 }
});
});
return combinedOptions;
};
const weightOptions = () => {
const combinedOptions = [defaultOption];
fontWeights.forEach(({ name, value }) => {
combinedOptions.push({
key: value,
name,
style: { fontStyle: void 0, fontWeight: value }
});
});
return combinedOptions;
};
const selectOptions = (0, import_element203.useMemo)(() => {
if (hasFontStyles && hasFontWeights) {
return combineOptions();
}
return hasFontStyles ? styleOptions() : weightOptions();
}, [
props.options,
fontStyles,
fontWeights,
combinedStyleAndWeightOptions
]);
const currentSelection = selectOptions.find(
(option) => option.style.fontStyle === fontStyle && option.style.fontWeight === fontWeight
) || selectOptions[0];
const getDescribedBy = () => {
if (!currentSelection) {
return (0, import_i18n133.__)("No selected font appearance");
}
if (!hasFontStyles) {
return (0, import_i18n133.sprintf)(
// translators: %s: Currently selected font weight.
(0, import_i18n133.__)("Currently selected font weight: %s"),
currentSelection.name
);
}
if (!hasFontWeights) {
return (0, import_i18n133.sprintf)(
// translators: %s: Currently selected font style.
(0, import_i18n133.__)("Currently selected font style: %s"),
currentSelection.name
);
}
return (0, import_i18n133.sprintf)(
// translators: %s: Currently selected font appearance.
(0, import_i18n133.__)("Currently selected font appearance: %s"),
currentSelection.name
);
};
return hasStylesOrWeights && /* @__PURE__ */ (0, import_jsx_runtime352.jsx)(
import_components143.CustomSelectControl,
{
...otherProps,
className: "components-font-appearance-control",
label,
describedBy: getDescribedBy(),
options: selectOptions,
value: currentSelection,
onChange: ({ selectedItem }) => onChange(selectedItem.style)
}
);
}
// packages/block-editor/build-module/components/font-family/index.mjs
var import_components144 = __toESM(require_components(), 1);
var import_i18n134 = __toESM(require_i18n(), 1);
var import_jsx_runtime353 = __toESM(require_jsx_runtime(), 1);
function FontFamilyControl({
/**
* Start opting into the larger default height that will become the default size in a future version.
*
* @deprecated Default behavior since WordPress 7.1. Prop can be safely removed.
*/
__next40pxDefaultSize: _next40pxDefaultSize,
value = "",
onChange,
fontFamilies,
className,
...props
}) {
const [blockLevelFontFamilies] = useSettings("typography.fontFamilies");
if (!fontFamilies) {
fontFamilies = blockLevelFontFamilies;
}
if (!fontFamilies || fontFamilies.length === 0) {
return null;
}
const options = [
{
key: "",
name: (0, import_i18n134.__)("Default")
},
...fontFamilies.map(({ fontFamily, name }) => ({
key: fontFamily,
name: name || fontFamily,
style: { fontFamily }
}))
];
const selectedValue = options.find((option) => option.key === value) ?? "";
return /* @__PURE__ */ (0, import_jsx_runtime353.jsx)(
import_components144.CustomSelectControl,
{
label: (0, import_i18n134.__)("Font"),
value: selectedValue,
onChange: ({ selectedItem }) => onChange(selectedItem.key),
options,
className: clsx_default("block-editor-font-family-control", className),
...props
}
);
}
// packages/block-editor/build-module/components/letter-spacing-control/index.mjs
var import_components145 = __toESM(require_components(), 1);
var import_i18n135 = __toESM(require_i18n(), 1);
var import_jsx_runtime354 = __toESM(require_jsx_runtime(), 1);
function LetterSpacingControl({
value,
onChange,
__unstableInputWidth = "60px",
...otherProps
}) {
const [availableUnits] = useSettings("spacing.units");
const units2 = (0, import_components145.__experimentalUseCustomUnits)({
availableUnits: availableUnits || ["px", "em", "rem"],
defaultValues: { px: 2, em: 0.2, rem: 0.2 }
});
return /* @__PURE__ */ (0, import_jsx_runtime354.jsx)(
import_components145.__experimentalUnitControl,
{
...otherProps,
label: (0, import_i18n135.__)("Letter spacing"),
value,
__unstableInputWidth,
units: units2,
onChange
}
);
}
// packages/block-editor/build-module/components/text-decoration-control/index.mjs
var import_i18n136 = __toESM(require_i18n(), 1);
var import_components146 = __toESM(require_components(), 1);
var import_jsx_runtime355 = __toESM(require_jsx_runtime(), 1);
var TEXT_DECORATIONS = [
{
label: (0, import_i18n136.__)("None"),
value: "none",
icon: reset_default
},
{
label: (0, import_i18n136.__)("Underline"),
value: "underline",
icon: format_underline_default
},
{
label: (0, import_i18n136.__)("Strikethrough"),
value: "line-through",
icon: format_strikethrough_default
}
];
function TextDecorationControl({
value,
onChange,
className
}) {
return /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(
import_components146.__experimentalToggleGroupControl,
{
isDeselectable: true,
label: (0, import_i18n136.__)("Decoration"),
className: clsx_default(
"block-editor-text-decoration-control",
className
),
value,
onChange: (newValue) => {
onChange(newValue === value ? void 0 : newValue);
},
children: TEXT_DECORATIONS.map((option) => {
return /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(
import_components146.__experimentalToggleGroupControlOptionIcon,
{
value: option.value,
icon: option.icon,
label: option.label
},
option.value
);
})
}
);
}
// packages/block-editor/build-module/components/text-transform-control/index.mjs
var import_i18n137 = __toESM(require_i18n(), 1);
var import_components147 = __toESM(require_components(), 1);
var import_jsx_runtime356 = __toESM(require_jsx_runtime(), 1);
var TEXT_TRANSFORMS = [
{
label: (0, import_i18n137.__)("None"),
value: "none",
icon: reset_default
},
{
label: (0, import_i18n137.__)("Uppercase"),
value: "uppercase",
icon: format_uppercase_default
},
{
label: (0, import_i18n137.__)("Lowercase"),
value: "lowercase",
icon: format_lowercase_default
},
{
label: (0, import_i18n137.__)("Capitalize"),
value: "capitalize",
icon: format_capitalize_default
}
];
function TextTransformControl({ className, value, onChange }) {
return /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(
import_components147.__experimentalToggleGroupControl,
{
isDeselectable: true,
label: (0, import_i18n137.__)("Letter case"),
className: clsx_default(
"block-editor-text-transform-control",
className
),
value,
onChange: (newValue) => {
onChange(newValue === value ? void 0 : newValue);
},
children: TEXT_TRANSFORMS.map((option) => {
return /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(
import_components147.__experimentalToggleGroupControlOptionIcon,
{
value: option.value,
icon: option.icon,
label: option.label
},
option.value
);
})
}
);
}
// packages/block-editor/build-module/components/writing-mode-control/index.mjs
var import_i18n138 = __toESM(require_i18n(), 1);
var import_components148 = __toESM(require_components(), 1);
var import_jsx_runtime357 = __toESM(require_jsx_runtime(), 1);
var WRITING_MODES = [
{
label: (0, import_i18n138.__)("Horizontal"),
value: "horizontal-tb",
icon: text_horizontal_default
},
{
label: (0, import_i18n138.__)("Vertical"),
value: (0, import_i18n138.isRTL)() ? "vertical-lr" : "vertical-rl",
icon: text_vertical_default
}
];
function WritingModeControl({ className, value, onChange }) {
return /* @__PURE__ */ (0, import_jsx_runtime357.jsx)(
import_components148.__experimentalToggleGroupControl,
{
isDeselectable: true,
label: (0, import_i18n138.__)("Orientation"),
className: clsx_default("block-editor-writing-mode-control", className),
value,
onChange: (newValue) => {
onChange(newValue === value ? void 0 : newValue);
},
children: WRITING_MODES.map((option) => {
return /* @__PURE__ */ (0, import_jsx_runtime357.jsx)(
import_components148.__experimentalToggleGroupControlOptionIcon,
{
value: option.value,
icon: option.icon,
label: option.label
},
option.value
);
})
}
);
}
// packages/block-editor/build-module/components/colors-gradients/dropdown.mjs
var import_components149 = __toESM(require_components(), 1);
var import_element204 = __toESM(require_element(), 1);
var import_i18n139 = __toESM(require_i18n(), 1);
var import_jsx_runtime358 = __toESM(require_jsx_runtime(), 1);
var WithToolsPanelItem = ({ setting, children, panelId, ...props }) => {
const clearValue = () => {
if (setting.colorValue) {
setting.onColorChange();
} else if (setting.gradientValue) {
setting.onGradientChange();
}
};
return /* @__PURE__ */ (0, import_jsx_runtime358.jsx)(
import_components149.__experimentalToolsPanelItem,
{
hasValue: () => {
return !!setting.colorValue || !!setting.gradientValue;
},
label: setting.label,
onDeselect: clearValue,
isShownByDefault: setting.isShownByDefault !== void 0 ? setting.isShownByDefault : true,
...props,
className: clsx_default(
"block-editor-color-gradient-item",
"block-editor-tools-panel-color-gradient-settings__item"
),
panelId,
resetAllFilter: setting.resetAllFilter,
children
}
);
};
var LabeledColorIndicator = ({ colorValue, label }) => /* @__PURE__ */ (0, import_jsx_runtime358.jsxs)(import_components149.__experimentalHStack, { justify: "flex-start", children: [
/* @__PURE__ */ (0, import_jsx_runtime358.jsx)(
import_components149.ColorIndicator,
{
className: "block-editor-panel-color-gradient-settings__color-indicator",
colorValue
}
),
/* @__PURE__ */ (0, import_jsx_runtime358.jsx)(
import_components149.FlexItem,
{
className: "block-editor-panel-color-gradient-settings__color-name",
title: label,
children: label
}
)
] });
var renderToggle = (settings2) => function Toggle2({ onToggle, isOpen }) {
const {
clearable,
colorValue,
gradientValue,
onColorChange,
onGradientChange,
label
} = settings2;
const colorButtonRef = (0, import_element204.useRef)(void 0);
const toggleProps = {
onClick: onToggle,
className: clsx_default(
"block-editor-panel-color-gradient-settings__dropdown",
{ "is-open": isOpen }
),
"aria-expanded": isOpen,
ref: colorButtonRef
};
const clearValue = () => {
if (colorValue) {
onColorChange();
} else if (gradientValue) {
onGradientChange();
}
};
const value = colorValue ?? gradientValue;
return /* @__PURE__ */ (0, import_jsx_runtime358.jsxs)(import_jsx_runtime358.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime358.jsx)(import_components149.Button, { __next40pxDefaultSize: true, ...toggleProps, children: /* @__PURE__ */ (0, import_jsx_runtime358.jsx)(
LabeledColorIndicator,
{
colorValue: value,
label
}
) }),
clearable && value && /* @__PURE__ */ (0, import_jsx_runtime358.jsx)(
import_components149.Button,
{
__next40pxDefaultSize: true,
label: (0, import_i18n139.__)("Reset"),
className: "block-editor-panel-color-gradient-settings__reset",
size: "small",
icon: reset_default,
onClick: () => {
clearValue();
if (isOpen) {
onToggle();
}
colorButtonRef.current?.focus();
}
}
)
] });
};
function ColorGradientSettingsDropdown({
colors: colors2,
disableCustomColors,
disableCustomGradients,
enableAlpha,
gradients,
settings: settings2,
__experimentalIsRenderedInSidebar,
...props
}) {
let popoverProps3;
if (__experimentalIsRenderedInSidebar) {
popoverProps3 = {
placement: "left-start",
offset: 36,
shift: true
};
}
return /* @__PURE__ */ (0, import_jsx_runtime358.jsx)(import_jsx_runtime358.Fragment, { children: settings2.map((setting, index2) => {
const controlProps = {
clearable: false,
colorValue: setting.colorValue,
colors: colors2,
disableCustomColors,
disableCustomGradients,
enableAlpha,
gradientValue: setting.gradientValue,
gradients,
label: setting.label,
onColorChange: setting.onColorChange,
onGradientChange: setting.onGradientChange,
showTitle: false,
__experimentalIsRenderedInSidebar,
...setting
};
const toggleSettings = {
clearable: setting.clearable,
label: setting.label,
colorValue: setting.colorValue,
gradientValue: setting.gradientValue,
onColorChange: setting.onColorChange,
onGradientChange: setting.onGradientChange
};
return setting && // If not in an `ItemGroup` wrap the dropdown in a
// `ToolsPanelItem`
/* @__PURE__ */ (0, import_jsx_runtime358.jsx)(
WithToolsPanelItem,
{
setting,
...props,
children: /* @__PURE__ */ (0, import_jsx_runtime358.jsx)(
import_components149.Dropdown,
{
popoverProps: popoverProps3,
className: "block-editor-tools-panel-color-gradient-settings__dropdown",
renderToggle: renderToggle(toggleSettings),
renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime358.jsx)(import_components149.__experimentalDropdownContentWrapper, { paddingSize: "none", children: /* @__PURE__ */ (0, import_jsx_runtime358.jsx)("div", { className: "block-editor-panel-color-gradient-settings__dropdown-content", children: /* @__PURE__ */ (0, import_jsx_runtime358.jsx)(
control_default,
{
...controlProps
}
) }) })
}
)
},
index2
);
}) });
}
// packages/block-editor/build-module/components/colors-gradients/panel-color-gradient-settings.mjs
var import_components150 = __toESM(require_components(), 1);
var import_data143 = __toESM(require_data(), 1);
var import_compose81 = __toESM(require_compose(), 1);
// packages/block-editor/build-module/components/colors-gradients/use-multiple-origin-colors-and-gradients.mjs
var import_element205 = __toESM(require_element(), 1);
var import_i18n140 = __toESM(require_i18n(), 1);
function useMultipleOriginColorsAndGradients() {
const [
enableCustomColors,
customColors,
themeColors,
defaultColors,
shouldDisplayDefaultColors,
enableCustomGradients,
customGradients,
themeGradients,
defaultGradients,
shouldDisplayDefaultGradients
] = useSettings(
"color.custom",
"color.palette.custom",
"color.palette.theme",
"color.palette.default",
"color.defaultPalette",
"color.customGradient",
"color.gradients.custom",
"color.gradients.theme",
"color.gradients.default",
"color.defaultGradients"
);
const colorGradientSettings = {
disableCustomColors: !enableCustomColors,
disableCustomGradients: !enableCustomGradients
};
colorGradientSettings.colors = (0, import_element205.useMemo)(() => {
const result = [];
if (themeColors && themeColors.length) {
result.push({
name: (0, import_i18n140._x)(
"Theme",
"Indicates this palette comes from the theme."
),
slug: "theme",
colors: themeColors
});
}
if (shouldDisplayDefaultColors && defaultColors && defaultColors.length) {
result.push({
name: (0, import_i18n140._x)(
"Default",
"Indicates this palette comes from WordPress."
),
slug: "default",
colors: defaultColors
});
}
if (customColors && customColors.length) {
result.push({
name: (0, import_i18n140._x)(
"Custom",
"Indicates this palette is created by the user."
),
slug: "custom",
colors: customColors
});
}
return result;
}, [
customColors,
themeColors,
defaultColors,
shouldDisplayDefaultColors
]);
colorGradientSettings.gradients = (0, import_element205.useMemo)(() => {
const result = [];
if (themeGradients && themeGradients.length) {
result.push({
name: (0, import_i18n140._x)(
"Theme",
"Indicates this palette comes from the theme."
),
slug: "theme",
gradients: themeGradients
});
}
if (shouldDisplayDefaultGradients && defaultGradients && defaultGradients.length) {
result.push({
name: (0, import_i18n140._x)(
"Default",
"Indicates this palette comes from WordPress."
),
slug: "default",
gradients: defaultGradients
});
}
if (customGradients && customGradients.length) {
result.push({
name: (0, import_i18n140._x)(
"Custom",
"Indicates this palette is created by the user."
),
slug: "custom",
gradients: customGradients
});
}
return result;
}, [
customGradients,
themeGradients,
defaultGradients,
shouldDisplayDefaultGradients
]);
colorGradientSettings.hasColorsOrGradients = !!colorGradientSettings.colors.length || !!colorGradientSettings.gradients.length;
return colorGradientSettings;
}
// packages/block-editor/build-module/components/colors-gradients/panel-color-gradient-settings.mjs
var import_jsx_runtime359 = __toESM(require_jsx_runtime(), 1);
var colorsAndGradientKeys2 = [
"colors",
"disableCustomColors",
"gradients",
"disableCustomGradients"
];
var PanelColorGradientSettingsInner = ({
className,
colors: colors2,
gradients,
disableCustomColors,
disableCustomGradients,
children,
settings: settings2,
title,
showTitle = true,
__experimentalIsRenderedInSidebar,
enableAlpha
}) => {
const panelId = (0, import_compose81.useInstanceId)(PanelColorGradientSettingsInner);
const { batch } = (0, import_data143.useRegistry)();
if ((!colors2 || colors2.length === 0) && (!gradients || gradients.length === 0) && disableCustomColors && disableCustomGradients && settings2?.every(
(setting) => (!setting.colors || setting.colors.length === 0) && (!setting.gradients || setting.gradients.length === 0) && (setting.disableCustomColors === void 0 || setting.disableCustomColors) && (setting.disableCustomGradients === void 0 || setting.disableCustomGradients)
)) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime359.jsxs)(
import_components150.__experimentalToolsPanel,
{
className: clsx_default(
"block-editor-panel-color-gradient-settings",
className
),
label: showTitle ? title : void 0,
resetAll: () => {
batch(() => {
settings2.forEach(
({
colorValue,
gradientValue,
onColorChange,
onGradientChange
}) => {
if (colorValue) {
onColorChange();
} else if (gradientValue) {
onGradientChange();
}
}
);
});
},
panelId,
__experimentalFirstVisibleItemClass: "first",
__experimentalLastVisibleItemClass: "last",
children: [
/* @__PURE__ */ (0, import_jsx_runtime359.jsx)(
ColorGradientSettingsDropdown,
{
settings: settings2,
panelId,
...{
colors: colors2,
gradients,
disableCustomColors,
disableCustomGradients,
__experimentalIsRenderedInSidebar,
enableAlpha
}
}
),
!!children && /* @__PURE__ */ (0, import_jsx_runtime359.jsxs)(import_jsx_runtime359.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime359.jsx)(import_components150.__experimentalSpacer, { marginY: 4 }),
" ",
children
] })
]
}
);
};
var PanelColorGradientSettingsSelect = (props) => {
const colorGradientSettings = useMultipleOriginColorsAndGradients();
return /* @__PURE__ */ (0, import_jsx_runtime359.jsx)(
PanelColorGradientSettingsInner,
{
...{ ...colorGradientSettings, ...props }
}
);
};
var PanelColorGradientSettings = (props) => {
if (colorsAndGradientKeys2.every((key) => props.hasOwnProperty(key))) {
return /* @__PURE__ */ (0, import_jsx_runtime359.jsx)(PanelColorGradientSettingsInner, { ...props });
}
return /* @__PURE__ */ (0, import_jsx_runtime359.jsx)(PanelColorGradientSettingsSelect, { ...props });
};
var panel_color_gradient_settings_default = PanelColorGradientSettings;
// packages/block-editor/build-module/components/dimension-control/index.mjs
var import_element206 = __toESM(require_element(), 1);
var import_components151 = __toESM(require_components(), 1);
var import_i18n141 = __toESM(require_i18n(), 1);
var import_jsx_runtime360 = __toESM(require_jsx_runtime(), 1);
var EMPTY_ARRAY11 = [];
var DIMENSION_CUSTOM_VALUE_SETTINGS = {
...CUSTOM_VALUE_SETTINGS,
px: { max: 1e3, steps: 1 },
em: { max: 50, steps: 0.1 },
rem: { max: 50, steps: 0.1 }
};
function useDimensionSizes(presets) {
const defaultSizes = presets?.default ?? EMPTY_ARRAY11;
const customSizes = presets?.custom ?? EMPTY_ARRAY11;
const themeSizes = presets?.theme ?? EMPTY_ARRAY11;
return (0, import_element206.useMemo)(() => {
const sizes = [
{ name: (0, import_i18n141.__)("None"), slug: "0", size: 0 },
...customSizes,
...themeSizes,
...defaultSizes
];
return sizes;
}, [customSizes, themeSizes, defaultSizes]);
}
function DimensionControl({
label = (0, import_i18n141.__)("Dimension"),
onChange,
value,
dimensionSizes: dimensionSizesProp
}) {
const [dimensionSizesFromSettings, availableUnits] = useSettings(
"dimensions.dimensionSizes",
"spacing.units"
);
const dimensionSizes = dimensionSizesProp ?? dimensionSizesFromSettings;
const units2 = (0, import_components151.__experimentalUseCustomUnits)({
availableUnits: availableUnits || [
"%",
"px",
"em",
"rem",
"vh",
"vw"
]
});
const options = useDimensionSizes(dimensionSizes);
const [selectedUnit, setSelectedUnit] = (0, import_element206.useState)(() => {
const [, unit] = (0, import_components151.__experimentalParseQuantityAndUnitFromRawValue)(value);
return unit || units2[0]?.value || "px";
});
const handleUnitChange = (newUnit) => {
const [currentValue, currentUnit] = (0, import_components151.__experimentalParseQuantityAndUnitFromRawValue)(value);
if (["em", "rem"].includes(newUnit) && currentUnit === "px") {
onChange((currentValue / 16).toFixed(2) + newUnit);
} else if (["em", "rem"].includes(currentUnit) && newUnit === "px") {
onChange(Math.round(currentValue * 16) + newUnit);
} else if ([
"%",
"vw",
"svw",
"lvw",
"dvw",
"vh",
"svh",
"lvh",
"dvh",
"vi",
"svi",
"lvi",
"dvi",
"vb",
"svb",
"lvb",
"dvb",
"vmin",
"svmin",
"lvmin",
"dvmin",
"vmax",
"svmax",
"lvmax",
"dvmax"
].includes(newUnit) && currentValue > 100) {
onChange(100 + newUnit);
}
setSelectedUnit(newUnit);
};
return /* @__PURE__ */ (0, import_jsx_runtime360.jsxs)("fieldset", { className: "block-editor-dimension-control", children: [
/* @__PURE__ */ (0, import_jsx_runtime360.jsx)(import_components151.BaseControl.VisualLabel, { as: "legend", children: label }),
/* @__PURE__ */ (0, import_jsx_runtime360.jsx)(
PresetInputControl,
{
ariaLabel: label,
className: "block-editor-dimension-control",
customValueSettings: DIMENSION_CUSTOM_VALUE_SETTINGS,
minimumCustomValue: 0,
onChange,
onUnitChange: handleUnitChange,
presets: options,
presetType: "dimension",
selectedUnit,
showTooltip: true,
units: units2,
value
}
)
] });
}
// packages/block-editor/build-module/components/height-control/index.mjs
var import_element207 = __toESM(require_element(), 1);
var import_components152 = __toESM(require_components(), 1);
var import_i18n142 = __toESM(require_i18n(), 1);
var import_deprecated16 = __toESM(require_deprecated(), 1);
var import_jsx_runtime361 = __toESM(require_jsx_runtime(), 1);
var RANGE_CONTROL_CUSTOM_SETTINGS = {
px: { max: 1e3, step: 1 },
"%": { max: 100, step: 1 },
vw: { max: 100, step: 1 },
vh: { max: 100, step: 1 },
em: { max: 50, step: 0.1 },
rem: { max: 50, step: 0.1 },
svw: { max: 100, step: 1 },
lvw: { max: 100, step: 1 },
dvw: { max: 100, step: 1 },
svh: { max: 100, step: 1 },
lvh: { max: 100, step: 1 },
dvh: { max: 100, step: 1 },
vi: { max: 100, step: 1 },
svi: { max: 100, step: 1 },
lvi: { max: 100, step: 1 },
dvi: { max: 100, step: 1 },
vb: { max: 100, step: 1 },
svb: { max: 100, step: 1 },
lvb: { max: 100, step: 1 },
dvb: { max: 100, step: 1 },
vmin: { max: 100, step: 1 },
svmin: { max: 100, step: 1 },
lvmin: { max: 100, step: 1 },
dvmin: { max: 100, step: 1 },
vmax: { max: 100, step: 1 },
svmax: { max: 100, step: 1 },
lvmax: { max: 100, step: 1 },
dvmax: { max: 100, step: 1 }
};
function HeightControl({
label = (0, import_i18n142.__)("Height"),
onChange,
value
}) {
(0, import_deprecated16.default)("wp.blockEditor.HeightControl", {
since: "7.0",
version: "7.2",
alternative: "wp.blockEditor.DimensionControl"
});
const customRangeValue = parseFloat(value);
const [availableUnits] = useSettings("spacing.units");
const units2 = (0, import_components152.__experimentalUseCustomUnits)({
availableUnits: availableUnits || [
"%",
"px",
"em",
"rem",
"vh",
"vw"
]
});
const selectedUnit = (0, import_element207.useMemo)(
() => (0, import_components152.__experimentalParseQuantityAndUnitFromRawValue)(value),
[value]
)[1] || units2[0]?.value || "px";
const handleSliderChange = (next) => {
onChange([next, selectedUnit].join(""));
};
const handleUnitChange = (newUnit) => {
const [currentValue, currentUnit] = (0, import_components152.__experimentalParseQuantityAndUnitFromRawValue)(value);
if (["em", "rem"].includes(newUnit) && currentUnit === "px") {
onChange((currentValue / 16).toFixed(2) + newUnit);
} else if (["em", "rem"].includes(currentUnit) && newUnit === "px") {
onChange(Math.round(currentValue * 16) + newUnit);
} else if ([
"%",
"vw",
"svw",
"lvw",
"dvw",
"vh",
"svh",
"lvh",
"dvh",
"vi",
"svi",
"lvi",
"dvi",
"vb",
"svb",
"lvb",
"dvb",
"vmin",
"svmin",
"lvmin",
"dvmin",
"vmax",
"svmax",
"lvmax",
"dvmax"
].includes(newUnit) && currentValue > 100) {
onChange(100 + newUnit);
}
};
return /* @__PURE__ */ (0, import_jsx_runtime361.jsxs)("fieldset", { className: "block-editor-height-control", children: [
/* @__PURE__ */ (0, import_jsx_runtime361.jsx)(import_components152.BaseControl.VisualLabel, { as: "legend", children: label }),
/* @__PURE__ */ (0, import_jsx_runtime361.jsxs)(import_components152.Flex, { children: [
/* @__PURE__ */ (0, import_jsx_runtime361.jsx)(import_components152.FlexItem, { isBlock: true, children: /* @__PURE__ */ (0, import_jsx_runtime361.jsx)(
import_components152.__experimentalUnitControl,
{
value,
units: units2,
onChange,
onUnitChange: handleUnitChange,
min: 0,
label,
hideLabelFromVision: true
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime361.jsx)(import_components152.FlexItem, { isBlock: true, children: /* @__PURE__ */ (0, import_jsx_runtime361.jsx)(import_components152.__experimentalSpacer, { marginX: 2, marginBottom: 0, children: /* @__PURE__ */ (0, import_jsx_runtime361.jsx)(
import_components152.RangeControl,
{
value: customRangeValue,
min: 0,
max: RANGE_CONTROL_CUSTOM_SETTINGS[selectedUnit]?.max ?? 100,
step: RANGE_CONTROL_CUSTOM_SETTINGS[selectedUnit]?.step ?? 0.1,
withInputField: false,
onChange: handleSliderChange,
label,
hideLabelFromVision: true
}
) }) })
] })
] });
}
// packages/block-editor/build-module/components/image-editor/index.mjs
var import_components158 = __toESM(require_components(), 1);
var import_deprecated17 = __toESM(require_deprecated(), 1);
// node_modules/react-easy-crop/index.module.js
var React117 = __toESM(require_react());
var import_normalize_wheel = __toESM(require_normalize_wheel());
function getCropSize(mediaWidth, mediaHeight, containerWidth, containerHeight, aspect, rotation) {
if (rotation === void 0) {
rotation = 0;
}
var _a = rotateSize(mediaWidth, mediaHeight, rotation), width = _a.width, height = _a.height;
var fittingWidth = Math.min(width, containerWidth);
var fittingHeight = Math.min(height, containerHeight);
if (fittingWidth > fittingHeight * aspect) {
return {
width: fittingHeight * aspect,
height: fittingHeight
};
}
return {
width: fittingWidth,
height: fittingWidth / aspect
};
}
function getMediaZoom(mediaSize) {
return mediaSize.width > mediaSize.height ? mediaSize.width / mediaSize.naturalWidth : mediaSize.height / mediaSize.naturalHeight;
}
function restrictPosition(position, mediaSize, cropSize, zoom, rotation) {
if (rotation === void 0) {
rotation = 0;
}
var _a = rotateSize(mediaSize.width, mediaSize.height, rotation), width = _a.width, height = _a.height;
return {
x: restrictPositionCoord(position.x, width, cropSize.width, zoom),
y: restrictPositionCoord(position.y, height, cropSize.height, zoom)
};
}
function restrictPositionCoord(position, mediaSize, cropSize, zoom) {
var maxPosition = mediaSize * zoom / 2 - cropSize / 2;
return clamp3(position, -maxPosition, maxPosition);
}
function getDistanceBetweenPoints(pointA, pointB) {
return Math.sqrt(Math.pow(pointA.y - pointB.y, 2) + Math.pow(pointA.x - pointB.x, 2));
}
function getRotationBetweenPoints(pointA, pointB) {
return Math.atan2(pointB.y - pointA.y, pointB.x - pointA.x) * 180 / Math.PI;
}
function computeCroppedArea(crop, mediaSize, cropSize, aspect, zoom, rotation, restrictPosition2) {
if (rotation === void 0) {
rotation = 0;
}
if (restrictPosition2 === void 0) {
restrictPosition2 = true;
}
var limitAreaFn = restrictPosition2 ? limitArea : noOp;
var mediaBBoxSize = rotateSize(mediaSize.width, mediaSize.height, rotation);
var mediaNaturalBBoxSize = rotateSize(mediaSize.naturalWidth, mediaSize.naturalHeight, rotation);
var croppedAreaPercentages = {
x: limitAreaFn(100, ((mediaBBoxSize.width - cropSize.width / zoom) / 2 - crop.x / zoom) / mediaBBoxSize.width * 100),
y: limitAreaFn(100, ((mediaBBoxSize.height - cropSize.height / zoom) / 2 - crop.y / zoom) / mediaBBoxSize.height * 100),
width: limitAreaFn(100, cropSize.width / mediaBBoxSize.width * 100 / zoom),
height: limitAreaFn(100, cropSize.height / mediaBBoxSize.height * 100 / zoom)
};
var widthInPixels = Math.round(limitAreaFn(mediaNaturalBBoxSize.width, croppedAreaPercentages.width * mediaNaturalBBoxSize.width / 100));
var heightInPixels = Math.round(limitAreaFn(mediaNaturalBBoxSize.height, croppedAreaPercentages.height * mediaNaturalBBoxSize.height / 100));
var isImgWiderThanHigh = mediaNaturalBBoxSize.width >= mediaNaturalBBoxSize.height * aspect;
var sizePixels = isImgWiderThanHigh ? {
width: Math.round(heightInPixels * aspect),
height: heightInPixels
} : {
width: widthInPixels,
height: Math.round(widthInPixels / aspect)
};
var croppedAreaPixels = __assign(__assign({}, sizePixels), {
x: Math.round(limitAreaFn(mediaNaturalBBoxSize.width - sizePixels.width, croppedAreaPercentages.x * mediaNaturalBBoxSize.width / 100)),
y: Math.round(limitAreaFn(mediaNaturalBBoxSize.height - sizePixels.height, croppedAreaPercentages.y * mediaNaturalBBoxSize.height / 100))
});
return {
croppedAreaPercentages,
croppedAreaPixels
};
}
function limitArea(max2, value) {
return Math.min(max2, Math.max(0, value));
}
function noOp(_max, value) {
return value;
}
function getInitialCropFromCroppedAreaPercentages(croppedAreaPercentages, mediaSize, rotation, cropSize, minZoom, maxZoom) {
var mediaBBoxSize = rotateSize(mediaSize.width, mediaSize.height, rotation);
var zoom = clamp3(cropSize.width / mediaBBoxSize.width * (100 / croppedAreaPercentages.width), minZoom, maxZoom);
var crop = {
x: zoom * mediaBBoxSize.width / 2 - cropSize.width / 2 - mediaBBoxSize.width * zoom * (croppedAreaPercentages.x / 100),
y: zoom * mediaBBoxSize.height / 2 - cropSize.height / 2 - mediaBBoxSize.height * zoom * (croppedAreaPercentages.y / 100)
};
return {
crop,
zoom
};
}
function getZoomFromCroppedAreaPixels(croppedAreaPixels, mediaSize, cropSize) {
var mediaZoom = getMediaZoom(mediaSize);
return cropSize.height > cropSize.width ? cropSize.height / (croppedAreaPixels.height * mediaZoom) : cropSize.width / (croppedAreaPixels.width * mediaZoom);
}
function getInitialCropFromCroppedAreaPixels(croppedAreaPixels, mediaSize, rotation, cropSize, minZoom, maxZoom) {
if (rotation === void 0) {
rotation = 0;
}
var mediaNaturalBBoxSize = rotateSize(mediaSize.naturalWidth, mediaSize.naturalHeight, rotation);
var zoom = clamp3(getZoomFromCroppedAreaPixels(croppedAreaPixels, mediaSize, cropSize), minZoom, maxZoom);
var cropZoom = cropSize.height > cropSize.width ? cropSize.height / croppedAreaPixels.height : cropSize.width / croppedAreaPixels.width;
var crop = {
x: ((mediaNaturalBBoxSize.width - croppedAreaPixels.width) / 2 - croppedAreaPixels.x) * cropZoom,
y: ((mediaNaturalBBoxSize.height - croppedAreaPixels.height) / 2 - croppedAreaPixels.y) * cropZoom
};
return {
crop,
zoom
};
}
function getCenter(a2, b2) {
return {
x: (b2.x + a2.x) / 2,
y: (b2.y + a2.y) / 2
};
}
function getRadianAngle(degreeValue) {
return degreeValue * Math.PI / 180;
}
function rotateSize(width, height, rotation) {
var rotRad = getRadianAngle(rotation);
return {
width: Math.abs(Math.cos(rotRad) * width) + Math.abs(Math.sin(rotRad) * height),
height: Math.abs(Math.sin(rotRad) * width) + Math.abs(Math.cos(rotRad) * height)
};
}
function clamp3(value, min2, max2) {
return Math.min(Math.max(value, min2), max2);
}
function classNames() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return args.filter(function(value) {
if (typeof value === "string" && value.length > 0) {
return true;
}
return false;
}).join(" ").trim();
}
var css_248z = ".reactEasyCrop_Container {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n overflow: hidden;\n user-select: none;\n touch-action: none;\n cursor: move;\n display: flex;\n justify-content: center;\n align-items: center;\n}\n\n.reactEasyCrop_Image,\n.reactEasyCrop_Video {\n will-change: transform; /* this improves performances and prevent painting issues on iOS Chrome */\n}\n\n.reactEasyCrop_Contain {\n max-width: 100%;\n max-height: 100%;\n margin: auto;\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n}\n.reactEasyCrop_Cover_Horizontal {\n width: 100%;\n height: auto;\n}\n.reactEasyCrop_Cover_Vertical {\n width: auto;\n height: 100%;\n}\n\n.reactEasyCrop_CropArea {\n position: absolute;\n left: 50%;\n top: 50%;\n transform: translate(-50%, -50%);\n border: 1px solid rgba(255, 255, 255, 0.5);\n box-sizing: border-box;\n box-shadow: 0 0 0 9999em;\n color: rgba(0, 0, 0, 0.5);\n overflow: hidden;\n}\n\n.reactEasyCrop_CropAreaRound {\n border-radius: 50%;\n}\n\n.reactEasyCrop_CropAreaGrid::before {\n content: ' ';\n box-sizing: border-box;\n position: absolute;\n border: 1px solid rgba(255, 255, 255, 0.5);\n top: 0;\n bottom: 0;\n left: 33.33%;\n right: 33.33%;\n border-top: 0;\n border-bottom: 0;\n}\n\n.reactEasyCrop_CropAreaGrid::after {\n content: ' ';\n box-sizing: border-box;\n position: absolute;\n border: 1px solid rgba(255, 255, 255, 0.5);\n top: 33.33%;\n bottom: 33.33%;\n left: 0;\n right: 0;\n border-left: 0;\n border-right: 0;\n}\n";
var MIN_ZOOM = 1;
var MAX_ZOOM = 3;
var KEYBOARD_STEP = 1;
var Cropper = (
/** @class */
(function(_super) {
__extends(Cropper2, _super);
function Cropper2() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.cropperRef = React117.createRef();
_this.imageRef = React117.createRef();
_this.videoRef = React117.createRef();
_this.containerPosition = {
x: 0,
y: 0
};
_this.containerRef = null;
_this.styleRef = null;
_this.containerRect = null;
_this.mediaSize = {
width: 0,
height: 0,
naturalWidth: 0,
naturalHeight: 0
};
_this.dragStartPosition = {
x: 0,
y: 0
};
_this.dragStartCrop = {
x: 0,
y: 0
};
_this.gestureZoomStart = 0;
_this.gestureRotationStart = 0;
_this.isTouching = false;
_this.lastPinchDistance = 0;
_this.lastPinchRotation = 0;
_this.rafDragTimeout = null;
_this.rafPinchTimeout = null;
_this.wheelTimer = null;
_this.currentDoc = typeof document !== "undefined" ? document : null;
_this.currentWindow = typeof window !== "undefined" ? window : null;
_this.resizeObserver = null;
_this.previousCropSize = null;
_this.isInitialized = false;
_this.state = {
cropSize: null,
hasWheelJustStarted: false,
mediaObjectFit: void 0
};
_this.initResizeObserver = function() {
if (typeof window.ResizeObserver === "undefined" || !_this.containerRef) {
return;
}
var isFirstResize = true;
_this.resizeObserver = new window.ResizeObserver(function(entries) {
if (isFirstResize) {
isFirstResize = false;
return;
}
_this.computeSizes();
});
_this.resizeObserver.observe(_this.containerRef);
};
_this.preventZoomSafari = function(e2) {
return e2.preventDefault();
};
_this.cleanEvents = function() {
if (!_this.currentDoc) return;
_this.currentDoc.removeEventListener("mousemove", _this.onMouseMove);
_this.currentDoc.removeEventListener("mouseup", _this.onDragStopped);
_this.currentDoc.removeEventListener("touchmove", _this.onTouchMove);
_this.currentDoc.removeEventListener("touchend", _this.onDragStopped);
_this.currentDoc.removeEventListener("gesturechange", _this.onGestureChange);
_this.currentDoc.removeEventListener("gestureend", _this.onGestureEnd);
_this.currentDoc.removeEventListener("scroll", _this.onScroll);
};
_this.clearScrollEvent = function() {
if (_this.containerRef) _this.containerRef.removeEventListener("wheel", _this.onWheel);
if (_this.wheelTimer) {
clearTimeout(_this.wheelTimer);
}
};
_this.onMediaLoad = function() {
var cropSize = _this.computeSizes();
if (cropSize) {
_this.previousCropSize = cropSize;
_this.emitCropData();
_this.setInitialCrop(cropSize);
_this.isInitialized = true;
}
if (_this.props.onMediaLoaded) {
_this.props.onMediaLoaded(_this.mediaSize);
}
};
_this.setInitialCrop = function(cropSize) {
if (_this.props.initialCroppedAreaPercentages) {
var _a = getInitialCropFromCroppedAreaPercentages(_this.props.initialCroppedAreaPercentages, _this.mediaSize, _this.props.rotation, cropSize, _this.props.minZoom, _this.props.maxZoom), crop = _a.crop, zoom = _a.zoom;
_this.props.onCropChange(crop);
_this.props.onZoomChange && _this.props.onZoomChange(zoom);
} else if (_this.props.initialCroppedAreaPixels) {
var _b = getInitialCropFromCroppedAreaPixels(_this.props.initialCroppedAreaPixels, _this.mediaSize, _this.props.rotation, cropSize, _this.props.minZoom, _this.props.maxZoom), crop = _b.crop, zoom = _b.zoom;
_this.props.onCropChange(crop);
_this.props.onZoomChange && _this.props.onZoomChange(zoom);
}
};
_this.computeSizes = function() {
var _a, _b, _c, _d, _e, _f;
var mediaRef = _this.imageRef.current || _this.videoRef.current;
if (mediaRef && _this.containerRef) {
_this.containerRect = _this.containerRef.getBoundingClientRect();
_this.saveContainerPosition();
var containerAspect = _this.containerRect.width / _this.containerRect.height;
var naturalWidth = ((_a = _this.imageRef.current) === null || _a === void 0 ? void 0 : _a.naturalWidth) || ((_b = _this.videoRef.current) === null || _b === void 0 ? void 0 : _b.videoWidth) || 0;
var naturalHeight = ((_c = _this.imageRef.current) === null || _c === void 0 ? void 0 : _c.naturalHeight) || ((_d = _this.videoRef.current) === null || _d === void 0 ? void 0 : _d.videoHeight) || 0;
var isMediaScaledDown = mediaRef.offsetWidth < naturalWidth || mediaRef.offsetHeight < naturalHeight;
var mediaAspect = naturalWidth / naturalHeight;
var renderedMediaSize = void 0;
if (isMediaScaledDown) {
switch (_this.state.mediaObjectFit) {
default:
case "contain":
renderedMediaSize = containerAspect > mediaAspect ? {
width: _this.containerRect.height * mediaAspect,
height: _this.containerRect.height
} : {
width: _this.containerRect.width,
height: _this.containerRect.width / mediaAspect
};
break;
case "horizontal-cover":
renderedMediaSize = {
width: _this.containerRect.width,
height: _this.containerRect.width / mediaAspect
};
break;
case "vertical-cover":
renderedMediaSize = {
width: _this.containerRect.height * mediaAspect,
height: _this.containerRect.height
};
break;
}
} else {
renderedMediaSize = {
width: mediaRef.offsetWidth,
height: mediaRef.offsetHeight
};
}
_this.mediaSize = __assign(__assign({}, renderedMediaSize), {
naturalWidth,
naturalHeight
});
if (_this.props.setMediaSize) {
_this.props.setMediaSize(_this.mediaSize);
}
var cropSize = _this.props.cropSize ? _this.props.cropSize : getCropSize(_this.mediaSize.width, _this.mediaSize.height, _this.containerRect.width, _this.containerRect.height, _this.props.aspect, _this.props.rotation);
if (((_e = _this.state.cropSize) === null || _e === void 0 ? void 0 : _e.height) !== cropSize.height || ((_f = _this.state.cropSize) === null || _f === void 0 ? void 0 : _f.width) !== cropSize.width) {
_this.props.onCropSizeChange && _this.props.onCropSizeChange(cropSize);
}
_this.setState({
cropSize
}, _this.recomputeCropPosition);
if (_this.props.setCropSize) {
_this.props.setCropSize(cropSize);
}
return cropSize;
}
};
_this.saveContainerPosition = function() {
if (_this.containerRef) {
var bounds = _this.containerRef.getBoundingClientRect();
_this.containerPosition = {
x: bounds.left,
y: bounds.top
};
}
};
_this.onMouseDown = function(e2) {
if (!_this.currentDoc) return;
e2.preventDefault();
_this.currentDoc.addEventListener("mousemove", _this.onMouseMove);
_this.currentDoc.addEventListener("mouseup", _this.onDragStopped);
_this.saveContainerPosition();
_this.onDragStart(Cropper2.getMousePoint(e2));
};
_this.onMouseMove = function(e2) {
return _this.onDrag(Cropper2.getMousePoint(e2));
};
_this.onScroll = function(e2) {
if (!_this.currentDoc) return;
e2.preventDefault();
_this.saveContainerPosition();
};
_this.onTouchStart = function(e2) {
if (!_this.currentDoc) return;
_this.isTouching = true;
if (_this.props.onTouchRequest && !_this.props.onTouchRequest(e2)) {
return;
}
_this.currentDoc.addEventListener("touchmove", _this.onTouchMove, {
passive: false
});
_this.currentDoc.addEventListener("touchend", _this.onDragStopped);
_this.saveContainerPosition();
if (e2.touches.length === 2) {
_this.onPinchStart(e2);
} else if (e2.touches.length === 1) {
_this.onDragStart(Cropper2.getTouchPoint(e2.touches[0]));
}
};
_this.onTouchMove = function(e2) {
e2.preventDefault();
if (e2.touches.length === 2) {
_this.onPinchMove(e2);
} else if (e2.touches.length === 1) {
_this.onDrag(Cropper2.getTouchPoint(e2.touches[0]));
}
};
_this.onGestureStart = function(e2) {
if (!_this.currentDoc) return;
e2.preventDefault();
_this.currentDoc.addEventListener("gesturechange", _this.onGestureChange);
_this.currentDoc.addEventListener("gestureend", _this.onGestureEnd);
_this.gestureZoomStart = _this.props.zoom;
_this.gestureRotationStart = _this.props.rotation;
};
_this.onGestureChange = function(e2) {
e2.preventDefault();
if (_this.isTouching) {
return;
}
var point = Cropper2.getMousePoint(e2);
var newZoom = _this.gestureZoomStart - 1 + e2.scale;
_this.setNewZoom(newZoom, point, {
shouldUpdatePosition: true
});
if (_this.props.onRotationChange) {
var newRotation = _this.gestureRotationStart + e2.rotation;
_this.props.onRotationChange(newRotation);
}
};
_this.onGestureEnd = function(e2) {
_this.cleanEvents();
};
_this.onDragStart = function(_a) {
var _b, _c;
var x2 = _a.x, y2 = _a.y;
_this.dragStartPosition = {
x: x2,
y: y2
};
_this.dragStartCrop = __assign({}, _this.props.crop);
(_c = (_b = _this.props).onInteractionStart) === null || _c === void 0 ? void 0 : _c.call(_b);
};
_this.onDrag = function(_a) {
var x2 = _a.x, y2 = _a.y;
if (!_this.currentWindow) return;
if (_this.rafDragTimeout) _this.currentWindow.cancelAnimationFrame(_this.rafDragTimeout);
_this.rafDragTimeout = _this.currentWindow.requestAnimationFrame(function() {
if (!_this.state.cropSize) return;
if (x2 === void 0 || y2 === void 0) return;
var offsetX = x2 - _this.dragStartPosition.x;
var offsetY = y2 - _this.dragStartPosition.y;
var requestedPosition = {
x: _this.dragStartCrop.x + offsetX,
y: _this.dragStartCrop.y + offsetY
};
var newPosition = _this.props.restrictPosition ? restrictPosition(requestedPosition, _this.mediaSize, _this.state.cropSize, _this.props.zoom, _this.props.rotation) : requestedPosition;
_this.props.onCropChange(newPosition);
});
};
_this.onDragStopped = function() {
var _a, _b;
_this.isTouching = false;
_this.cleanEvents();
_this.emitCropData();
(_b = (_a = _this.props).onInteractionEnd) === null || _b === void 0 ? void 0 : _b.call(_a);
};
_this.onWheel = function(e2) {
if (!_this.currentWindow) return;
if (_this.props.onWheelRequest && !_this.props.onWheelRequest(e2)) {
return;
}
e2.preventDefault();
var point = Cropper2.getMousePoint(e2);
var pixelY = (0, import_normalize_wheel.default)(e2).pixelY;
var newZoom = _this.props.zoom - pixelY * _this.props.zoomSpeed / 200;
_this.setNewZoom(newZoom, point, {
shouldUpdatePosition: true
});
if (!_this.state.hasWheelJustStarted) {
_this.setState({
hasWheelJustStarted: true
}, function() {
var _a, _b;
return (_b = (_a = _this.props).onInteractionStart) === null || _b === void 0 ? void 0 : _b.call(_a);
});
}
if (_this.wheelTimer) {
clearTimeout(_this.wheelTimer);
}
_this.wheelTimer = _this.currentWindow.setTimeout(function() {
return _this.setState({
hasWheelJustStarted: false
}, function() {
var _a, _b;
return (_b = (_a = _this.props).onInteractionEnd) === null || _b === void 0 ? void 0 : _b.call(_a);
});
}, 250);
};
_this.getPointOnContainer = function(_a, containerTopLeft) {
var x2 = _a.x, y2 = _a.y;
if (!_this.containerRect) {
throw new Error("The Cropper is not mounted");
}
return {
x: _this.containerRect.width / 2 - (x2 - containerTopLeft.x),
y: _this.containerRect.height / 2 - (y2 - containerTopLeft.y)
};
};
_this.getPointOnMedia = function(_a) {
var x2 = _a.x, y2 = _a.y;
var _b = _this.props, crop = _b.crop, zoom = _b.zoom;
return {
x: (x2 + crop.x) / zoom,
y: (y2 + crop.y) / zoom
};
};
_this.setNewZoom = function(zoom, point, _a) {
var _b = _a === void 0 ? {} : _a, _c = _b.shouldUpdatePosition, shouldUpdatePosition = _c === void 0 ? true : _c;
if (!_this.state.cropSize || !_this.props.onZoomChange) return;
var newZoom = clamp3(zoom, _this.props.minZoom, _this.props.maxZoom);
if (shouldUpdatePosition) {
var zoomPoint = _this.getPointOnContainer(point, _this.containerPosition);
var zoomTarget = _this.getPointOnMedia(zoomPoint);
var requestedPosition = {
x: zoomTarget.x * newZoom - zoomPoint.x,
y: zoomTarget.y * newZoom - zoomPoint.y
};
var newPosition = _this.props.restrictPosition ? restrictPosition(requestedPosition, _this.mediaSize, _this.state.cropSize, newZoom, _this.props.rotation) : requestedPosition;
_this.props.onCropChange(newPosition);
}
_this.props.onZoomChange(newZoom);
};
_this.getCropData = function() {
if (!_this.state.cropSize) {
return null;
}
var restrictedPosition = _this.props.restrictPosition ? restrictPosition(_this.props.crop, _this.mediaSize, _this.state.cropSize, _this.props.zoom, _this.props.rotation) : _this.props.crop;
return computeCroppedArea(restrictedPosition, _this.mediaSize, _this.state.cropSize, _this.getAspect(), _this.props.zoom, _this.props.rotation, _this.props.restrictPosition);
};
_this.emitCropData = function() {
var cropData = _this.getCropData();
if (!cropData) return;
var croppedAreaPercentages = cropData.croppedAreaPercentages, croppedAreaPixels = cropData.croppedAreaPixels;
if (_this.props.onCropComplete) {
_this.props.onCropComplete(croppedAreaPercentages, croppedAreaPixels);
}
if (_this.props.onCropAreaChange) {
_this.props.onCropAreaChange(croppedAreaPercentages, croppedAreaPixels);
}
};
_this.emitCropAreaChange = function() {
var cropData = _this.getCropData();
if (!cropData) return;
var croppedAreaPercentages = cropData.croppedAreaPercentages, croppedAreaPixels = cropData.croppedAreaPixels;
if (_this.props.onCropAreaChange) {
_this.props.onCropAreaChange(croppedAreaPercentages, croppedAreaPixels);
}
};
_this.recomputeCropPosition = function() {
if (!_this.state.cropSize) return;
var adjustedCrop = _this.props.crop;
if (_this.isInitialized && _this.previousCropSize) {
var sizeChanged = Math.abs(_this.previousCropSize.width - _this.state.cropSize.width) > 1e-6 || Math.abs(_this.previousCropSize.height - _this.state.cropSize.height) > 1e-6;
if (sizeChanged) {
var scaleX = _this.state.cropSize.width / _this.previousCropSize.width;
var scaleY = _this.state.cropSize.height / _this.previousCropSize.height;
adjustedCrop = {
x: _this.props.crop.x * scaleX,
y: _this.props.crop.y * scaleY
};
}
}
var newPosition = _this.props.restrictPosition ? restrictPosition(adjustedCrop, _this.mediaSize, _this.state.cropSize, _this.props.zoom, _this.props.rotation) : adjustedCrop;
_this.previousCropSize = _this.state.cropSize;
_this.props.onCropChange(newPosition);
_this.emitCropData();
};
_this.onKeyDown = function(event) {
var _a, _b;
var _c = _this.props, crop = _c.crop, onCropChange = _c.onCropChange, keyboardStep = _c.keyboardStep, zoom = _c.zoom, rotation = _c.rotation;
var step = keyboardStep;
if (!_this.state.cropSize) return;
if (event.shiftKey) {
step *= 0.2;
}
var newCrop = __assign({}, crop);
switch (event.key) {
case "ArrowUp":
newCrop.y -= step;
event.preventDefault();
break;
case "ArrowDown":
newCrop.y += step;
event.preventDefault();
break;
case "ArrowLeft":
newCrop.x -= step;
event.preventDefault();
break;
case "ArrowRight":
newCrop.x += step;
event.preventDefault();
break;
default:
return;
}
if (_this.props.restrictPosition) {
newCrop = restrictPosition(newCrop, _this.mediaSize, _this.state.cropSize, zoom, rotation);
}
if (!event.repeat) {
(_b = (_a = _this.props).onInteractionStart) === null || _b === void 0 ? void 0 : _b.call(_a);
}
onCropChange(newCrop);
};
_this.onKeyUp = function(event) {
var _a, _b;
switch (event.key) {
case "ArrowUp":
case "ArrowDown":
case "ArrowLeft":
case "ArrowRight":
event.preventDefault();
break;
default:
return;
}
_this.emitCropData();
(_b = (_a = _this.props).onInteractionEnd) === null || _b === void 0 ? void 0 : _b.call(_a);
};
return _this;
}
Cropper2.prototype.componentDidMount = function() {
if (!this.currentDoc || !this.currentWindow) return;
if (this.containerRef) {
if (this.containerRef.ownerDocument) {
this.currentDoc = this.containerRef.ownerDocument;
}
if (this.currentDoc.defaultView) {
this.currentWindow = this.currentDoc.defaultView;
}
this.initResizeObserver();
if (typeof window.ResizeObserver === "undefined") {
this.currentWindow.addEventListener("resize", this.computeSizes);
}
this.props.zoomWithScroll && this.containerRef.addEventListener("wheel", this.onWheel, {
passive: false
});
this.containerRef.addEventListener("gesturestart", this.onGestureStart);
}
this.currentDoc.addEventListener("scroll", this.onScroll);
if (!this.props.disableAutomaticStylesInjection) {
this.styleRef = this.currentDoc.createElement("style");
this.styleRef.setAttribute("type", "text/css");
if (this.props.nonce) {
this.styleRef.setAttribute("nonce", this.props.nonce);
}
this.styleRef.innerHTML = css_248z;
this.currentDoc.head.appendChild(this.styleRef);
}
if (this.imageRef.current && this.imageRef.current.complete) {
this.onMediaLoad();
}
if (this.props.setImageRef) {
this.props.setImageRef(this.imageRef);
}
if (this.props.setVideoRef) {
this.props.setVideoRef(this.videoRef);
}
if (this.props.setCropperRef) {
this.props.setCropperRef(this.cropperRef);
}
};
Cropper2.prototype.componentWillUnmount = function() {
var _a, _b;
if (!this.currentDoc || !this.currentWindow) return;
if (typeof window.ResizeObserver === "undefined") {
this.currentWindow.removeEventListener("resize", this.computeSizes);
}
(_a = this.resizeObserver) === null || _a === void 0 ? void 0 : _a.disconnect();
if (this.containerRef) {
this.containerRef.removeEventListener("gesturestart", this.preventZoomSafari);
}
if (this.styleRef) {
(_b = this.styleRef.parentNode) === null || _b === void 0 ? void 0 : _b.removeChild(this.styleRef);
}
this.cleanEvents();
this.props.zoomWithScroll && this.clearScrollEvent();
};
Cropper2.prototype.componentDidUpdate = function(prevProps) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j;
if (prevProps.rotation !== this.props.rotation) {
this.computeSizes();
this.recomputeCropPosition();
} else if (prevProps.aspect !== this.props.aspect) {
this.computeSizes();
} else if (prevProps.objectFit !== this.props.objectFit) {
this.computeSizes();
} else if (prevProps.zoom !== this.props.zoom) {
this.recomputeCropPosition();
} else if (((_a = prevProps.cropSize) === null || _a === void 0 ? void 0 : _a.height) !== ((_b = this.props.cropSize) === null || _b === void 0 ? void 0 : _b.height) || ((_c = prevProps.cropSize) === null || _c === void 0 ? void 0 : _c.width) !== ((_d = this.props.cropSize) === null || _d === void 0 ? void 0 : _d.width)) {
this.computeSizes();
} else if (((_e = prevProps.crop) === null || _e === void 0 ? void 0 : _e.x) !== ((_f = this.props.crop) === null || _f === void 0 ? void 0 : _f.x) || ((_g = prevProps.crop) === null || _g === void 0 ? void 0 : _g.y) !== ((_h = this.props.crop) === null || _h === void 0 ? void 0 : _h.y)) {
this.emitCropAreaChange();
}
if (prevProps.zoomWithScroll !== this.props.zoomWithScroll && this.containerRef) {
this.props.zoomWithScroll ? this.containerRef.addEventListener("wheel", this.onWheel, {
passive: false
}) : this.clearScrollEvent();
}
if (prevProps.video !== this.props.video) {
(_j = this.videoRef.current) === null || _j === void 0 ? void 0 : _j.load();
}
var objectFit = this.getObjectFit();
if (objectFit !== this.state.mediaObjectFit) {
this.setState({
mediaObjectFit: objectFit
}, this.computeSizes);
}
};
Cropper2.prototype.getAspect = function() {
var _a = this.props, cropSize = _a.cropSize, aspect = _a.aspect;
if (cropSize) {
return cropSize.width / cropSize.height;
}
return aspect;
};
Cropper2.prototype.getObjectFit = function() {
var _a, _b, _c, _d;
if (this.props.objectFit === "cover") {
var mediaRef = this.imageRef.current || this.videoRef.current;
if (mediaRef && this.containerRef) {
this.containerRect = this.containerRef.getBoundingClientRect();
var containerAspect = this.containerRect.width / this.containerRect.height;
var naturalWidth = ((_a = this.imageRef.current) === null || _a === void 0 ? void 0 : _a.naturalWidth) || ((_b = this.videoRef.current) === null || _b === void 0 ? void 0 : _b.videoWidth) || 0;
var naturalHeight = ((_c = this.imageRef.current) === null || _c === void 0 ? void 0 : _c.naturalHeight) || ((_d = this.videoRef.current) === null || _d === void 0 ? void 0 : _d.videoHeight) || 0;
var mediaAspect = naturalWidth / naturalHeight;
return mediaAspect < containerAspect ? "horizontal-cover" : "vertical-cover";
}
return "horizontal-cover";
}
return this.props.objectFit;
};
Cropper2.prototype.onPinchStart = function(e2) {
var pointA = Cropper2.getTouchPoint(e2.touches[0]);
var pointB = Cropper2.getTouchPoint(e2.touches[1]);
this.lastPinchDistance = getDistanceBetweenPoints(pointA, pointB);
this.lastPinchRotation = getRotationBetweenPoints(pointA, pointB);
this.onDragStart(getCenter(pointA, pointB));
};
Cropper2.prototype.onPinchMove = function(e2) {
var _this = this;
if (!this.currentDoc || !this.currentWindow) return;
var pointA = Cropper2.getTouchPoint(e2.touches[0]);
var pointB = Cropper2.getTouchPoint(e2.touches[1]);
var center = getCenter(pointA, pointB);
this.onDrag(center);
if (this.rafPinchTimeout) this.currentWindow.cancelAnimationFrame(this.rafPinchTimeout);
this.rafPinchTimeout = this.currentWindow.requestAnimationFrame(function() {
var distance = getDistanceBetweenPoints(pointA, pointB);
var newZoom = _this.props.zoom * (distance / _this.lastPinchDistance);
_this.setNewZoom(newZoom, center, {
shouldUpdatePosition: false
});
_this.lastPinchDistance = distance;
var rotation = getRotationBetweenPoints(pointA, pointB);
var newRotation = _this.props.rotation + (rotation - _this.lastPinchRotation);
_this.props.onRotationChange && _this.props.onRotationChange(newRotation);
_this.lastPinchRotation = rotation;
});
};
Cropper2.prototype.render = function() {
var _this = this;
var _a;
var _b = this.props, image = _b.image, video = _b.video, mediaProps = _b.mediaProps, cropperProps = _b.cropperProps, transform = _b.transform, _c = _b.crop, x2 = _c.x, y2 = _c.y, rotation = _b.rotation, zoom = _b.zoom, cropShape = _b.cropShape, showGrid = _b.showGrid, roundCropAreaPixels = _b.roundCropAreaPixels, _d = _b.style, containerStyle = _d.containerStyle, cropAreaStyle = _d.cropAreaStyle, mediaStyle = _d.mediaStyle, _e = _b.classes, containerClassName = _e.containerClassName, cropAreaClassName = _e.cropAreaClassName, mediaClassName = _e.mediaClassName;
var objectFit = (_a = this.state.mediaObjectFit) !== null && _a !== void 0 ? _a : this.getObjectFit();
return React117.createElement("div", {
onMouseDown: this.onMouseDown,
onTouchStart: this.onTouchStart,
ref: function ref(el) {
return _this.containerRef = el;
},
"data-testid": "container",
style: containerStyle,
className: classNames("reactEasyCrop_Container", containerClassName)
}, image ? React117.createElement("img", __assign({
alt: "",
className: classNames("reactEasyCrop_Image", objectFit === "contain" && "reactEasyCrop_Contain", objectFit === "horizontal-cover" && "reactEasyCrop_Cover_Horizontal", objectFit === "vertical-cover" && "reactEasyCrop_Cover_Vertical", mediaClassName)
}, mediaProps, {
src: image,
ref: this.imageRef,
style: __assign(__assign({}, mediaStyle), {
transform: transform || "translate(".concat(x2, "px, ").concat(y2, "px) rotate(").concat(rotation, "deg) scale(").concat(zoom, ")")
}),
onLoad: this.onMediaLoad
})) : video && React117.createElement("video", __assign({
autoPlay: true,
playsInline: true,
loop: true,
muted: true,
className: classNames("reactEasyCrop_Video", objectFit === "contain" && "reactEasyCrop_Contain", objectFit === "horizontal-cover" && "reactEasyCrop_Cover_Horizontal", objectFit === "vertical-cover" && "reactEasyCrop_Cover_Vertical", mediaClassName)
}, mediaProps, {
ref: this.videoRef,
onLoadedMetadata: this.onMediaLoad,
style: __assign(__assign({}, mediaStyle), {
transform: transform || "translate(".concat(x2, "px, ").concat(y2, "px) rotate(").concat(rotation, "deg) scale(").concat(zoom, ")")
}),
controls: false
}), (Array.isArray(video) ? video : [{
src: video
}]).map(function(item) {
return React117.createElement("source", __assign({
key: item.src
}, item));
})), this.state.cropSize && React117.createElement("div", __assign({
ref: this.cropperRef,
style: __assign(__assign({}, cropAreaStyle), {
width: roundCropAreaPixels ? Math.round(this.state.cropSize.width) : this.state.cropSize.width,
height: roundCropAreaPixels ? Math.round(this.state.cropSize.height) : this.state.cropSize.height
}),
tabIndex: 0,
onKeyDown: this.onKeyDown,
onKeyUp: this.onKeyUp,
"data-testid": "cropper",
className: classNames("reactEasyCrop_CropArea", cropShape === "round" && "reactEasyCrop_CropAreaRound", showGrid && "reactEasyCrop_CropAreaGrid", cropAreaClassName)
}, cropperProps)));
};
Cropper2.defaultProps = {
zoom: 1,
rotation: 0,
aspect: 4 / 3,
maxZoom: MAX_ZOOM,
minZoom: MIN_ZOOM,
cropShape: "rect",
objectFit: "contain",
showGrid: true,
style: {},
classes: {},
mediaProps: {},
cropperProps: {},
zoomSpeed: 1,
restrictPosition: true,
zoomWithScroll: true,
keyboardStep: KEYBOARD_STEP
};
Cropper2.getMousePoint = function(e2) {
return {
x: Number(e2.clientX),
y: Number(e2.clientY)
};
};
Cropper2.getTouchPoint = function(touch) {
return {
x: Number(touch.clientX),
y: Number(touch.clientY)
};
};
return Cropper2;
})(React117.Component)
);
// packages/image-cropper/build-module/components/image-cropper/index.mjs
var import_element210 = __toESM(require_element(), 1);
// packages/image-cropper/build-module/provider/index.mjs
var import_element209 = __toESM(require_element(), 1);
// node_modules/dequal/dist/index.mjs
var has = Object.prototype.hasOwnProperty;
function find(iter, tar, key) {
for (key of iter.keys()) {
if (dequal(key, tar)) return key;
}
}
function dequal(foo, bar) {
var ctor, len, tmp;
if (foo === bar) return true;
if (foo && bar && (ctor = foo.constructor) === bar.constructor) {
if (ctor === Date) return foo.getTime() === bar.getTime();
if (ctor === RegExp) return foo.toString() === bar.toString();
if (ctor === Array) {
if ((len = foo.length) === bar.length) {
while (len-- && dequal(foo[len], bar[len])) ;
}
return len === -1;
}
if (ctor === Set) {
if (foo.size !== bar.size) {
return false;
}
for (len of foo) {
tmp = len;
if (tmp && typeof tmp === "object") {
tmp = find(bar, tmp);
if (!tmp) return false;
}
if (!bar.has(tmp)) return false;
}
return true;
}
if (ctor === Map) {
if (foo.size !== bar.size) {
return false;
}
for (len of foo) {
tmp = len[0];
if (tmp && typeof tmp === "object") {
tmp = find(bar, tmp);
if (!tmp) return false;
}
if (!dequal(len[1], bar.get(tmp))) {
return false;
}
}
return true;
}
if (ctor === ArrayBuffer) {
foo = new Uint8Array(foo);
bar = new Uint8Array(bar);
} else if (ctor === DataView) {
if ((len = foo.byteLength) === bar.byteLength) {
while (len-- && foo.getInt8(len) === bar.getInt8(len)) ;
}
return len === -1;
}
if (ArrayBuffer.isView(foo)) {
if ((len = foo.byteLength) === bar.byteLength) {
while (len-- && foo[len] === bar[len]) ;
}
return len === -1;
}
if (!ctor || typeof foo === "object") {
len = 0;
for (ctor in foo) {
if (has.call(foo, ctor) && ++len && !has.call(bar, ctor)) return false;
if (!(ctor in bar) || !dequal(foo[ctor], bar[ctor])) return false;
}
return Object.keys(bar).length === len;
}
}
return foo !== foo && bar !== bar;
}
// packages/image-cropper/build-module/provider/use-image-cropper.mjs
var import_element208 = __toESM(require_element(), 1);
// packages/image-cropper/build-module/constants.mjs
var MIN_ZOOM2 = 1;
var MAX_ZOOM2 = 5;
// packages/image-cropper/build-module/utils.mjs
var normalizeRotation = (rotation) => {
if (rotation >= 0) {
return rotation % 360;
}
return (360 + rotation % 360) % 360;
};
var createImage = (url) => new Promise((resolve, reject) => {
const image = new Image();
image.addEventListener("load", () => resolve(image));
image.addEventListener("error", (error2) => reject(error2));
image.setAttribute("crossOrigin", "anonymous");
image.src = url;
});
function getRadianAngle2(degreeValue) {
return degreeValue * Math.PI / 180;
}
function rotateSize2(width, height, rotation) {
const rotRad = getRadianAngle2(rotation);
return {
width: Math.abs(Math.cos(rotRad) * width) + Math.abs(Math.sin(rotRad) * height),
height: Math.abs(Math.sin(rotRad) * width) + Math.abs(Math.cos(rotRad) * height)
};
}
async function getCroppedImage(imageSrc, pixelCrop, rotation = 0, flip4 = { horizontal: false, vertical: false }) {
try {
const image = await createImage(imageSrc);
const canvas = document.createElement("canvas");
const ctx2 = canvas.getContext("2d");
if (!ctx2) {
return null;
}
const rotRad = getRadianAngle2(rotation);
const { width: boundingBoxWidth, height: boundingBoxHeight } = rotateSize2(image.width, image.height, rotation);
canvas.width = boundingBoxWidth;
canvas.height = boundingBoxHeight;
ctx2.translate(boundingBoxWidth / 2, boundingBoxHeight / 2);
ctx2.rotate(rotRad);
ctx2.scale(flip4.horizontal ? -1 : 1, flip4.vertical ? -1 : 1);
ctx2.translate(-image.width / 2, -image.height / 2);
ctx2.drawImage(image, 0, 0);
const croppedCanvas = document.createElement("canvas");
const croppedCtx = croppedCanvas.getContext("2d");
if (!croppedCtx) {
return null;
}
croppedCanvas.width = pixelCrop.width;
croppedCanvas.height = pixelCrop.height;
croppedCtx.drawImage(
canvas,
pixelCrop.x,
pixelCrop.y,
pixelCrop.width,
pixelCrop.height,
0,
0,
pixelCrop.width,
pixelCrop.height
);
return new Promise((resolve) => {
croppedCanvas.toBlob((file) => {
if (file) {
resolve(URL.createObjectURL(file));
}
}, "image/jpeg");
});
} catch {
return null;
}
}
// packages/image-cropper/build-module/provider/use-image-cropper.mjs
var DEFAULT_INITIAL_STATE = {
crop: {
x: 0,
y: 0,
width: 100,
height: 100
},
zoom: MIN_ZOOM2,
rotation: 0,
aspectRatio: 1,
flip: {
horizontal: false,
vertical: false
}
};
var DEFAULT_CROP_MEDIA_POSITION = {
x: 0,
y: 0
};
var DEFAULT_CROPPER_STATE = {
crop: DEFAULT_CROP_MEDIA_POSITION,
croppedArea: DEFAULT_INITIAL_STATE.crop,
croppedAreaPixels: null,
zoom: DEFAULT_INITIAL_STATE.zoom,
rotation: DEFAULT_INITIAL_STATE.rotation,
flip: DEFAULT_INITIAL_STATE.flip,
aspectRatio: DEFAULT_INITIAL_STATE.aspectRatio,
mediaSize: null
};
function useCropper() {
const [cropperState, setInternalCropperState] = (0, import_element208.useState)(
DEFAULT_CROPPER_STATE
);
const [resetState, setInternalResetState] = (0, import_element208.useState)(null);
const setCropperState = (0, import_element208.useCallback)(
(newState) => {
setInternalCropperState((prev) => {
const updates = typeof newState === "function" ? newState(prev) : newState;
const normalizedUpdates = { ...updates };
if ("rotation" in normalizedUpdates && normalizedUpdates.rotation !== void 0) {
normalizedUpdates.rotation = normalizeRotation(
normalizedUpdates.rotation
);
}
return { ...prev, ...normalizedUpdates };
});
},
[]
);
const setResetState = (0, import_element208.useCallback)(
(newResetState = null) => {
if (!newResetState) {
setInternalResetState(null);
setCropperState(DEFAULT_CROPPER_STATE);
return;
}
if (typeof newResetState === "object") {
const initialState = {
...DEFAULT_INITIAL_STATE,
...newResetState
};
setInternalResetState(initialState);
setCropperState(initialState);
}
},
[setCropperState, setInternalResetState]
);
const reset = (0, import_element208.useCallback)(() => {
if (resetState) {
const resetUpdates = {
// Reset media position to center
crop: { x: 0, y: 0 },
// Reset cropped area pixels (will be recalculated)
croppedAreaPixels: null
};
if (resetState.crop) {
resetUpdates.croppedArea = resetState.crop;
}
if (resetState.zoom !== void 0) {
resetUpdates.zoom = resetState.zoom;
}
if (resetState.rotation !== void 0) {
resetUpdates.rotation = resetState.rotation;
}
if (resetState.aspectRatio !== void 0) {
resetUpdates.aspectRatio = resetState.aspectRatio;
}
if (resetState.flip !== void 0) {
resetUpdates.flip = resetState.flip;
}
setCropperState(resetUpdates);
} else {
setCropperState({ ...DEFAULT_CROPPER_STATE });
}
}, [resetState, setCropperState]);
const isDirty = (0, import_element208.useMemo)(() => {
if (resetState) {
const currentState2 = {
crop: cropperState.croppedAreaPixels || cropperState.croppedArea,
zoom: cropperState.zoom,
rotation: normalizeRotation(cropperState.rotation),
aspectRatio: cropperState.aspectRatio,
flip: cropperState.flip
};
return false === dequal(currentState2, resetState);
}
const currentState = {
crop: cropperState.croppedArea,
zoom: cropperState.zoom,
rotation: normalizeRotation(cropperState.rotation),
aspectRatio: cropperState.aspectRatio,
flip: cropperState.flip
};
return false === dequal(currentState, DEFAULT_INITIAL_STATE);
}, [cropperState, resetState]);
const getCroppedImage2 = (0, import_element208.useCallback)(
async (src) => {
if (!cropperState.croppedAreaPixels) {
return null;
}
return getCroppedImage(
src,
cropperState.croppedAreaPixels,
cropperState.rotation,
cropperState.flip
);
},
[
cropperState.croppedAreaPixels,
cropperState.rotation,
cropperState.flip
]
);
return (0, import_element208.useMemo)(
() => ({
cropperState,
setCropperState,
resetState,
setResetState,
isDirty,
reset,
getCroppedImage: getCroppedImage2
}),
[
cropperState,
setCropperState,
resetState,
setResetState,
isDirty,
reset,
getCroppedImage2
]
);
}
// packages/image-cropper/build-module/provider/index.mjs
var import_jsx_runtime362 = __toESM(require_jsx_runtime(), 1);
var ImageCropperContext = (0, import_element209.createContext)({
cropperState: {
crop: { x: 0, y: 0 },
croppedArea: { x: 0, y: 0, width: 100, height: 100 },
croppedAreaPixels: null,
zoom: MIN_ZOOM2,
rotation: 0,
aspectRatio: 1,
flip: { horizontal: false, vertical: false },
mediaSize: null
},
setCropperState: () => {
},
resetState: null,
setResetState: () => {
},
isDirty: false,
reset: () => {
},
getCroppedImage: () => Promise.resolve(null)
});
function ImageCropperProvider({
children
}) {
const cropperApi = useCropper();
const contextValue = (0, import_element209.useMemo)(() => {
return {
...cropperApi
};
}, [cropperApi]);
return /* @__PURE__ */ (0, import_jsx_runtime362.jsx)(ImageCropperContext.Provider, { value: contextValue, children });
}
var useImageCropper = () => {
const context = (0, import_element209.useContext)(ImageCropperContext);
if (!context) {
throw new Error("Missing ImageCropperContext");
}
return context;
};
// packages/image-cropper/build-module/components/image-cropper/index.mjs
var import_jsx_runtime363 = __toESM(require_jsx_runtime(), 1);
function ImageCropper({
src,
onLoad,
minZoom = MIN_ZOOM2,
maxZoom = MAX_ZOOM2,
...props
}) {
const { cropperState, setCropperState } = useImageCropper();
const { crop, zoom, rotation, aspectRatio, flip: flip4 } = cropperState;
const setCrop = (newCrop) => setCropperState({ crop: newCrop });
const setZoom = (newZoom) => setCropperState({ zoom: newZoom });
const setRotation = (newRotation) => setCropperState({ rotation: newRotation });
const setMediaSize = (newMediaSize) => setCropperState({ mediaSize: newMediaSize });
const onCropComplete = (0, import_element210.useCallback)(
(areaPercentage, areaPixels) => {
setCropperState({
croppedArea: areaPercentage,
croppedAreaPixels: areaPixels
});
},
[setCropperState]
);
return /* @__PURE__ */ (0, import_jsx_runtime363.jsx)(
Cropper,
{
classes: {
containerClassName: "image-cropper__container",
cropAreaClassName: "image-cropper__crop-area",
mediaClassName: "image-cropper__image"
},
minZoom,
maxZoom,
rotation,
image: src,
setMediaSize,
crop,
zoom,
aspect: aspectRatio,
onCropChange: setCrop,
onZoomChange: setZoom,
onCropComplete,
onMediaLoaded: (loadedMediaSize) => {
onLoad?.(loadedMediaSize);
},
onRotationChange: setRotation,
transform: [
`translate(${crop.x}px, ${crop.y}px)`,
`rotateZ(${rotation}deg)`,
`rotateY(${flip4.horizontal ? 180 : 0}deg)`,
`rotateX(${flip4.vertical ? 180 : 0}deg)`,
`scale(${zoom})`
].join(" "),
...props
}
);
}
// packages/block-editor/build-module/components/image-editor/aspect-ratio-dropdown.mjs
var import_components153 = __toESM(require_components(), 1);
var import_i18n144 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/image-editor/constants.mjs
var MIN_ZOOM3 = 100;
var MAX_ZOOM3 = 300;
var POPOVER_PROPS7 = {
placement: "bottom-start"
};
// packages/block-editor/build-module/components/image-editor/context.mjs
var import_element213 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/image-editor/use-save-image.mjs
var import_data144 = __toESM(require_data(), 1);
var import_element211 = __toESM(require_element(), 1);
var import_i18n143 = __toESM(require_i18n(), 1);
var import_notices9 = __toESM(require_notices(), 1);
var import_dom64 = __toESM(require_dom(), 1);
var messages = {
crop: (0, import_i18n143.__)("Image cropped."),
rotate: (0, import_i18n143.__)("Image rotated."),
cropAndRotate: (0, import_i18n143.__)("Image cropped and rotated.")
};
function useSaveImage({
crop,
rotation,
url,
id,
onSaveImage,
onFinishEditing
}) {
const { createErrorNotice, createSuccessNotice } = (0, import_data144.useDispatch)(import_notices9.store);
const [isInProgress, setIsInProgress] = (0, import_element211.useState)(false);
const { editMediaEntity } = (0, import_data144.useSelect)((select3) => {
const settings2 = select3(store).getSettings();
return {
editMediaEntity: settings2?.[mediaEditKey]
};
}, []);
const cancel = (0, import_element211.useCallback)(() => {
setIsInProgress(false);
onFinishEditing();
}, [onFinishEditing]);
const apply = (0, import_element211.useCallback)(async () => {
if (!editMediaEntity) {
onFinishEditing();
createErrorNotice(
(0, import_i18n143.__)("Sorry, you are not allowed to edit images on this site."),
{
id: "image-editing-error",
type: "snackbar"
}
);
return;
}
setIsInProgress(true);
const modifiers = [];
if (rotation > 0) {
modifiers.push({
type: "rotate",
args: {
angle: rotation
}
});
}
if (crop.width < 99.9 || crop.height < 99.9) {
modifiers.push({
type: "crop",
args: {
left: crop.x,
top: crop.y,
width: crop.width,
height: crop.height
}
});
}
if (modifiers.length === 0) {
setIsInProgress(false);
onFinishEditing();
return;
}
const modifierType = modifiers.length === 1 ? modifiers[0].type : "cropAndRotate";
try {
const savedImage = await editMediaEntity(
id,
{
src: url,
modifiers
},
{ throwOnError: true }
);
if (savedImage) {
onSaveImage({
id: savedImage.id,
url: savedImage.source_url
});
createSuccessNotice(messages[modifierType], {
type: "snackbar",
actions: [
{
label: (0, import_i18n143.__)("Undo"),
onClick: () => {
onSaveImage({
id,
url
});
}
}
]
});
}
} catch (error2) {
createErrorNotice(
(0, import_i18n143.sprintf)(
/* translators: %s: Error message. */
(0, import_i18n143.__)("Could not edit image. %s"),
(0, import_dom64.__unstableStripHTML)(error2.message)
),
{
id: "image-editing-error",
type: "snackbar"
}
);
} finally {
setIsInProgress(false);
onFinishEditing();
}
}, [
crop,
rotation,
id,
url,
onSaveImage,
createErrorNotice,
createSuccessNotice,
onFinishEditing,
editMediaEntity
]);
return (0, import_element211.useMemo)(
() => ({
isInProgress,
apply,
cancel
}),
[isInProgress, apply, cancel]
);
}
// packages/block-editor/build-module/components/image-editor/use-transform-image.mjs
var import_element212 = __toESM(require_element(), 1);
var import_hooks6 = __toESM(require_hooks(), 1);
function useTransformImage({
url,
naturalWidth,
naturalHeight
}) {
const [editedUrl, setEditedUrl] = (0, import_element212.useState)();
const { cropperState, setCropperState } = useImageCropper();
const { zoom, aspectRatio, crop, croppedArea } = cropperState;
const setZoom = (0, import_element212.useCallback)(
(newZoom) => {
setCropperState({ zoom: newZoom });
},
[setCropperState]
);
const setAspectRatio = (0, import_element212.useCallback)(
(newAspect) => {
setCropperState({ aspectRatio: newAspect });
},
[setCropperState]
);
const defaultAspect = naturalWidth / naturalHeight;
const rotatedAspect = naturalHeight / naturalWidth;
(0, import_element212.useEffect)(() => {
setAspectRatio(defaultAspect);
}, []);
const [internalRotation, setInternalRotation] = (0, import_element212.useState)(0);
const rotateClockwise = (0, import_element212.useCallback)(() => {
const angle = (internalRotation + 90) % 360;
let naturalAspectRatio = defaultAspect;
const isDefaultAspect = defaultAspect === aspectRatio || rotatedAspect === aspectRatio;
const shouldResetAspect = zoom !== 1 || !isDefaultAspect;
if (internalRotation % 180 === 90) {
naturalAspectRatio = 1 / defaultAspect;
}
if (angle === 0) {
setEditedUrl();
setInternalRotation(angle);
const newAspectRatio = shouldResetAspect ? aspectRatio : defaultAspect;
setCropperState({
aspectRatio: newAspectRatio,
crop: {
x: -(crop.y * naturalAspectRatio),
y: crop.x * naturalAspectRatio
}
});
return;
}
function editImage(event) {
const canvas = document.createElement("canvas");
let translateX = 0;
let translateY = 0;
if (angle % 180) {
canvas.width = event.target.height;
canvas.height = event.target.width;
} else {
canvas.width = event.target.width;
canvas.height = event.target.height;
}
if (angle === 90 || angle === 180) {
translateX = canvas.width;
}
if (angle === 270 || angle === 180) {
translateY = canvas.height;
}
const context = canvas.getContext("2d");
context.translate(translateX, translateY);
context.rotate(angle * Math.PI / 180);
context.drawImage(event.target, 0, 0);
canvas.toBlob((blob) => {
setEditedUrl(URL.createObjectURL(blob));
setInternalRotation(angle);
const newAspectRatio = shouldResetAspect ? aspectRatio : canvas.width / canvas.height;
setCropperState({
aspectRatio: newAspectRatio,
crop: {
x: -(crop.y * naturalAspectRatio),
y: crop.x * naturalAspectRatio
}
});
});
}
const el = new window.Image();
el.src = url;
el.onload = editImage;
const imgCrossOrigin = (0, import_hooks6.applyFilters)(
"media.crossOrigin",
void 0,
url
);
if (typeof imgCrossOrigin === "string") {
el.crossOrigin = imgCrossOrigin;
}
}, [
internalRotation,
defaultAspect,
url,
setCropperState,
crop,
zoom,
aspectRatio,
rotatedAspect,
setInternalRotation
]);
return (0, import_element212.useMemo)(
() => ({
editedUrl,
setEditedUrl,
crop: croppedArea,
zoom,
setZoom,
rotation: internalRotation,
rotateClockwise,
aspect: aspectRatio,
setAspect: setAspectRatio,
defaultAspect
}),
[
editedUrl,
croppedArea,
zoom,
setZoom,
internalRotation,
rotateClockwise,
aspectRatio,
setAspectRatio,
defaultAspect
]
);
}
// packages/block-editor/build-module/components/image-editor/context.mjs
var import_jsx_runtime364 = __toESM(require_jsx_runtime(), 1);
var ImageEditingContext = (0, import_element213.createContext)({});
ImageEditingContext.displayName = "ImageEditingContext";
var useImageEditingContext = () => (0, import_element213.useContext)(ImageEditingContext);
function ImageEditingProvider({
id,
url,
naturalWidth,
naturalHeight,
onFinishEditing,
onSaveImage,
children
}) {
const transformImage = useTransformImage({
url,
naturalWidth,
naturalHeight
});
const saveImage = useSaveImage({
id,
url,
onSaveImage,
onFinishEditing,
...transformImage
});
const providerValue = (0, import_element213.useMemo)(
() => ({
...transformImage,
...saveImage
}),
[transformImage, saveImage]
);
return /* @__PURE__ */ (0, import_jsx_runtime364.jsx)(ImageEditingContext.Provider, { value: providerValue, children });
}
// packages/block-editor/build-module/components/image-editor/aspect-ratio-dropdown.mjs
var import_jsx_runtime365 = __toESM(require_jsx_runtime(), 1);
function AspectRatioGroup({
aspectRatios,
isDisabled,
label,
onClick,
value
}) {
return /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(import_components153.MenuGroup, { label, children: aspectRatios.map(({ name, slug, ratio }) => /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(
import_components153.MenuItem,
{
disabled: isDisabled,
onClick: () => {
onClick(ratio);
},
role: "menuitemradio",
isSelected: ratio === value,
icon: ratio === value ? check_default : void 0,
children: name
},
slug
)) });
}
function ratioToNumber(str) {
const [a2, b2, ...rest] = str.split("/").map(Number);
if (a2 <= 0 || b2 <= 0 || Number.isNaN(a2) || Number.isNaN(b2) || rest.length) {
return NaN;
}
return b2 ? a2 / b2 : a2;
}
function presetRatioAsNumber({ ratio, ...rest }) {
return {
ratio: ratioToNumber(ratio),
...rest
};
}
function AspectRatioDropdown({ toggleProps }) {
const { isInProgress, aspect, setAspect, defaultAspect } = useImageEditingContext();
const [defaultRatios, themeRatios, showDefaultRatios] = useSettings(
"dimensions.aspectRatios.default",
"dimensions.aspectRatios.theme",
"dimensions.defaultAspectRatios"
);
return /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(
import_components153.DropdownMenu,
{
icon: aspect_ratio_default,
label: (0, import_i18n144.__)("Aspect Ratio"),
popoverProps: POPOVER_PROPS7,
toggleProps,
children: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime365.jsxs)(import_jsx_runtime365.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime365.jsx)(
AspectRatioGroup,
{
isDisabled: isInProgress,
onClick: (newAspect) => {
setAspect(newAspect);
onClose();
},
value: aspect,
aspectRatios: [
// All ratios should be mirrored in AspectRatioTool in @wordpress/block-editor.
{
slug: "original",
name: (0, import_i18n144.__)("Original"),
ratio: defaultAspect
},
...showDefaultRatios ? defaultRatios.map(presetRatioAsNumber).filter(({ ratio }) => ratio === 1) : []
]
}
),
themeRatios?.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(
AspectRatioGroup,
{
label: (0, import_i18n144.__)("Theme"),
isDisabled: isInProgress,
onClick: (newAspect) => {
setAspect(newAspect);
onClose();
},
value: aspect,
aspectRatios: themeRatios
}
),
showDefaultRatios && /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(
AspectRatioGroup,
{
label: (0, import_i18n144.__)("Landscape"),
isDisabled: isInProgress,
onClick: (newAspect) => {
setAspect(newAspect);
onClose();
},
value: aspect,
aspectRatios: defaultRatios.map(presetRatioAsNumber).filter(({ ratio }) => ratio > 1)
}
),
showDefaultRatios && /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(
AspectRatioGroup,
{
label: (0, import_i18n144.__)("Portrait"),
isDisabled: isInProgress,
onClick: (newAspect) => {
setAspect(newAspect);
onClose();
},
value: aspect,
aspectRatios: defaultRatios.map(presetRatioAsNumber).filter(({ ratio }) => ratio < 1)
}
)
] })
}
);
}
// packages/block-editor/build-module/components/image-editor/cropper.mjs
var import_components154 = __toESM(require_components(), 1);
var import_compose82 = __toESM(require_compose(), 1);
var import_jsx_runtime366 = __toESM(require_jsx_runtime(), 1);
function ImageCropper2({
url,
width,
height,
naturalHeight,
naturalWidth,
borderProps
}) {
const { isInProgress, editedUrl, rotation } = useImageEditingContext();
const [contentResizeListener, { width: clientWidth }] = (0, import_compose82.useResizeObserver)();
let editedHeight = height || clientWidth * naturalHeight / naturalWidth;
if (rotation % 180 === 90) {
editedHeight = clientWidth * naturalWidth / naturalHeight;
}
const area = /* @__PURE__ */ (0, import_jsx_runtime366.jsxs)(
"div",
{
className: clsx_default(
"wp-block-image__crop-area",
borderProps?.className,
{
"is-applying": isInProgress
}
),
style: {
...borderProps?.style,
width: width || clientWidth,
height: editedHeight
},
children: [
/* @__PURE__ */ (0, import_jsx_runtime366.jsx)(ImageCropper, { src: editedUrl || url }),
isInProgress && /* @__PURE__ */ (0, import_jsx_runtime366.jsx)(import_components154.Spinner, {})
]
}
);
return /* @__PURE__ */ (0, import_jsx_runtime366.jsxs)(import_jsx_runtime366.Fragment, { children: [
contentResizeListener,
area
] });
}
// packages/block-editor/build-module/components/image-editor/zoom-dropdown.mjs
var import_components155 = __toESM(require_components(), 1);
var import_i18n145 = __toESM(require_i18n(), 1);
var import_jsx_runtime367 = __toESM(require_jsx_runtime(), 1);
function ZoomDropdown() {
const { isInProgress, zoom, setZoom } = useImageEditingContext();
return /* @__PURE__ */ (0, import_jsx_runtime367.jsx)(
import_components155.Dropdown,
{
contentClassName: "wp-block-image__zoom",
popoverProps: POPOVER_PROPS7,
renderToggle: ({ isOpen, onToggle }) => /* @__PURE__ */ (0, import_jsx_runtime367.jsx)(
import_components155.ToolbarButton,
{
icon: search_default,
label: (0, import_i18n145.__)("Zoom"),
onClick: onToggle,
"aria-expanded": isOpen,
disabled: isInProgress
}
),
renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime367.jsx)(import_components155.__experimentalDropdownContentWrapper, { paddingSize: "medium", children: /* @__PURE__ */ (0, import_jsx_runtime367.jsx)(
import_components155.RangeControl,
{
label: (0, import_i18n145.__)("Zoom"),
min: MIN_ZOOM3,
max: MAX_ZOOM3,
value: Math.round(zoom * 100),
onChange: (newZoom) => setZoom(newZoom / 100)
}
) })
}
);
}
// packages/block-editor/build-module/components/image-editor/rotation-button.mjs
var import_components156 = __toESM(require_components(), 1);
var import_i18n146 = __toESM(require_i18n(), 1);
var import_jsx_runtime368 = __toESM(require_jsx_runtime(), 1);
function RotationButton() {
const { isInProgress, rotateClockwise } = useImageEditingContext();
return /* @__PURE__ */ (0, import_jsx_runtime368.jsx)(
import_components156.ToolbarButton,
{
icon: rotate_right_default,
label: (0, import_i18n146.__)("Rotate"),
onClick: rotateClockwise,
disabled: isInProgress
}
);
}
// packages/block-editor/build-module/components/image-editor/form-controls.mjs
var import_components157 = __toESM(require_components(), 1);
var import_i18n147 = __toESM(require_i18n(), 1);
var import_jsx_runtime369 = __toESM(require_jsx_runtime(), 1);
function FormControls() {
const { isInProgress, apply, cancel } = useImageEditingContext();
return /* @__PURE__ */ (0, import_jsx_runtime369.jsxs)(import_jsx_runtime369.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime369.jsx)(import_components157.ToolbarButton, { onClick: apply, disabled: isInProgress, children: (0, import_i18n147.__)("Apply") }),
/* @__PURE__ */ (0, import_jsx_runtime369.jsx)(import_components157.ToolbarButton, { onClick: cancel, children: (0, import_i18n147.__)("Cancel") })
] });
}
// packages/block-editor/build-module/components/image-editor/index.mjs
var import_jsx_runtime370 = __toESM(require_jsx_runtime(), 1);
function ImageEditor({
id,
url,
width,
height,
naturalHeight,
naturalWidth,
onSaveImage,
onFinishEditing,
borderProps
}) {
(0, import_deprecated17.default)("wp.blockEditor.__experimentalImageEditor", {
since: "7.1",
hint: "The Media Editor modal is now the default crop experience for core blocks. This component will be removed in a future major release."
});
return /* @__PURE__ */ (0, import_jsx_runtime370.jsx)(ImageCropperProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime370.jsxs)(
ImageEditingProvider,
{
id,
url,
naturalWidth,
naturalHeight,
onSaveImage,
onFinishEditing,
children: [
/* @__PURE__ */ (0, import_jsx_runtime370.jsx)(
ImageCropper2,
{
borderProps,
url,
width,
height,
naturalHeight,
naturalWidth
}
),
/* @__PURE__ */ (0, import_jsx_runtime370.jsxs)(block_controls_default, { children: [
/* @__PURE__ */ (0, import_jsx_runtime370.jsxs)(import_components158.ToolbarGroup, { children: [
/* @__PURE__ */ (0, import_jsx_runtime370.jsx)(ZoomDropdown, {}),
/* @__PURE__ */ (0, import_jsx_runtime370.jsx)(import_components158.ToolbarItem, { children: (toggleProps) => /* @__PURE__ */ (0, import_jsx_runtime370.jsx)(
AspectRatioDropdown,
{
toggleProps
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime370.jsx)(RotationButton, {})
] }),
/* @__PURE__ */ (0, import_jsx_runtime370.jsx)(import_components158.ToolbarGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime370.jsx)(FormControls, {}) })
] })
]
}
) });
}
// packages/block-editor/build-module/components/image-size-control/index.mjs
var import_components159 = __toESM(require_components(), 1);
var import_i18n148 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/image-size-control/use-dimension-handler.mjs
var import_element214 = __toESM(require_element(), 1);
function useDimensionHandler(customHeight, customWidth, defaultHeight, defaultWidth, onChange) {
const [currentWidth, setCurrentWidth] = (0, import_element214.useState)(
customWidth ?? defaultWidth ?? ""
);
const [currentHeight, setCurrentHeight] = (0, import_element214.useState)(
customHeight ?? defaultHeight ?? ""
);
(0, import_element214.useEffect)(() => {
if (customWidth === void 0 && defaultWidth !== void 0) {
setCurrentWidth(defaultWidth);
}
if (customHeight === void 0 && defaultHeight !== void 0) {
setCurrentHeight(defaultHeight);
}
}, [defaultWidth, defaultHeight]);
(0, import_element214.useEffect)(() => {
if (customWidth !== void 0 && Number.parseInt(customWidth) !== Number.parseInt(currentWidth)) {
setCurrentWidth(customWidth);
}
if (customHeight !== void 0 && Number.parseInt(customHeight) !== Number.parseInt(currentHeight)) {
setCurrentHeight(customHeight);
}
}, [customWidth, customHeight]);
const updateDimension = (dimension, value) => {
const parsedValue = value === "" ? void 0 : parseInt(value, 10);
if (dimension === "width") {
setCurrentWidth(parsedValue);
} else {
setCurrentHeight(parsedValue);
}
onChange({
[dimension]: parsedValue
});
};
const updateDimensions = (nextHeight, nextWidth) => {
setCurrentHeight(nextHeight ?? defaultHeight);
setCurrentWidth(nextWidth ?? defaultWidth);
onChange({ height: nextHeight, width: nextWidth });
};
return {
currentHeight,
currentWidth,
updateDimension,
updateDimensions
};
}
// packages/block-editor/build-module/components/image-size-control/index.mjs
var import_jsx_runtime371 = __toESM(require_jsx_runtime(), 1);
var IMAGE_SIZE_PRESETS = [25, 50, 75, 100];
var noop15 = () => {
};
function getScaledWidthAndHeight(scale, imageWidth, imageHeight) {
const scaledWidth = Math.round(imageWidth * (scale / 100));
const scaledHeight = Math.round(imageHeight * (scale / 100));
return {
scaledWidth,
scaledHeight
};
}
function ImageSizeControl({
imageSizeHelp,
imageWidth,
imageHeight,
imageSizeOptions = [],
isResizable = true,
slug,
width,
height,
onChange,
onChangeImage = noop15
}) {
const { currentHeight, currentWidth, updateDimension, updateDimensions } = useDimensionHandler(height, width, imageHeight, imageWidth, onChange);
const handleUpdateDimensions = (scale) => {
if (void 0 === scale) {
updateDimensions();
return;
}
const { scaledWidth, scaledHeight } = getScaledWidthAndHeight(
scale,
imageWidth,
imageHeight
);
updateDimensions(scaledHeight, scaledWidth);
};
const selectedValue = IMAGE_SIZE_PRESETS.find((scale) => {
const { scaledWidth, scaledHeight } = getScaledWidthAndHeight(
scale,
imageWidth,
imageHeight
);
return currentWidth === scaledWidth && currentHeight === scaledHeight;
});
return /* @__PURE__ */ (0, import_jsx_runtime371.jsxs)(import_components159.__experimentalVStack, { className: "block-editor-image-size-control", spacing: "4", children: [
imageSizeOptions && imageSizeOptions.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime371.jsx)(
import_components159.SelectControl,
{
label: (0, import_i18n148.__)("Resolution"),
value: slug,
options: imageSizeOptions,
onChange: onChangeImage,
help: imageSizeHelp
}
),
isResizable && /* @__PURE__ */ (0, import_jsx_runtime371.jsxs)(import_jsx_runtime371.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime371.jsxs)(import_components159.__experimentalHStack, { align: "baseline", spacing: "4", children: [
/* @__PURE__ */ (0, import_jsx_runtime371.jsx)(
import_components159.__experimentalNumberControl,
{
label: (0, import_i18n148.__)("Width"),
value: currentWidth,
min: 1,
onChange: (value) => updateDimension("width", value)
}
),
/* @__PURE__ */ (0, import_jsx_runtime371.jsx)(
import_components159.__experimentalNumberControl,
{
label: (0, import_i18n148.__)("Height"),
value: currentHeight,
min: 1,
onChange: (value) => updateDimension("height", value)
}
)
] }),
/* @__PURE__ */ (0, import_jsx_runtime371.jsx)(
import_components159.__experimentalToggleGroupControl,
{
label: (0, import_i18n148.__)("Image size presets"),
hideLabelFromVision: true,
onChange: handleUpdateDimensions,
value: selectedValue,
isBlock: true,
children: IMAGE_SIZE_PRESETS.map((scale) => {
return /* @__PURE__ */ (0, import_jsx_runtime371.jsx)(
import_components159.__experimentalToggleGroupControlOption,
{
value: scale,
label: (0, import_i18n148.sprintf)(
/* translators: %d: Percentage value. */
(0, import_i18n148.__)("%d%%"),
scale
)
},
scale
);
})
}
)
] })
] });
}
// packages/block-editor/build-module/components/justify-content-control/ui.mjs
var import_components160 = __toESM(require_components(), 1);
var import_i18n149 = __toESM(require_i18n(), 1);
var import_jsx_runtime372 = __toESM(require_jsx_runtime(), 1);
var icons = {
left: justify_left_default,
center: justify_center_default,
right: justify_right_default,
"space-between": justify_space_between_default,
stretch: justify_stretch_default
};
function JustifyContentUI({
allowedControls = ["left", "center", "right", "space-between"],
isCollapsed: isCollapsed3 = true,
onChange,
value,
popoverProps: popoverProps3,
isToolbar
}) {
const handleClick = (next) => {
if (next === value) {
onChange(void 0);
} else {
onChange(next);
}
};
const icon = value ? icons[value] : icons.left;
const allControls = [
{
name: "left",
icon: justify_left_default,
title: (0, import_i18n149.__)("Justify items left"),
isActive: "left" === value,
onClick: () => handleClick("left")
},
{
name: "center",
icon: justify_center_default,
title: (0, import_i18n149.__)("Justify items center"),
isActive: "center" === value,
onClick: () => handleClick("center")
},
{
name: "right",
icon: justify_right_default,
title: (0, import_i18n149.__)("Justify items right"),
isActive: "right" === value,
onClick: () => handleClick("right")
},
{
name: "space-between",
icon: justify_space_between_default,
title: (0, import_i18n149.__)("Space between items"),
isActive: "space-between" === value,
onClick: () => handleClick("space-between")
},
{
name: "stretch",
icon: justify_stretch_default,
title: (0, import_i18n149.__)("Stretch items"),
isActive: "stretch" === value,
onClick: () => handleClick("stretch")
}
];
const UIComponent = isToolbar ? import_components160.ToolbarGroup : import_components160.ToolbarDropdownMenu;
const extraProps = isToolbar ? { isCollapsed: isCollapsed3 } : {};
return /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(
UIComponent,
{
icon,
popoverProps: popoverProps3,
label: (0, import_i18n149.__)("Change items justification"),
controls: allControls.filter(
(elem) => allowedControls.includes(elem.name)
),
...extraProps
}
);
}
var ui_default4 = JustifyContentUI;
// packages/block-editor/build-module/components/justify-content-control/index.mjs
var import_jsx_runtime373 = __toESM(require_jsx_runtime(), 1);
var JustifyContentControl = (props) => {
return /* @__PURE__ */ (0, import_jsx_runtime373.jsx)(ui_default4, { ...props, isToolbar: false });
};
var JustifyToolbar = (props) => {
return /* @__PURE__ */ (0, import_jsx_runtime373.jsx)(ui_default4, { ...props, isToolbar: true });
};
// packages/block-editor/build-module/components/link-control/index.mjs
var import_components168 = __toESM(require_components(), 1);
var import_i18n159 = __toESM(require_i18n(), 1);
var import_element222 = __toESM(require_element(), 1);
var import_compose86 = __toESM(require_compose(), 1);
var import_dom67 = __toESM(require_dom(), 1);
var import_keycodes19 = __toESM(require_keycodes(), 1);
var import_is_shallow_equal3 = __toESM(require_is_shallow_equal(), 1);
var import_data148 = __toESM(require_data(), 1);
var import_preferences4 = __toESM(require_preferences(), 1);
var import_deprecated21 = __toESM(require_deprecated(), 1);
var import_url6 = __toESM(require_url(), 1);
// packages/block-editor/build-module/components/link-control/settings-drawer.mjs
var import_components161 = __toESM(require_components(), 1);
var import_compose83 = __toESM(require_compose(), 1);
var import_i18n150 = __toESM(require_i18n(), 1);
var import_element215 = __toESM(require_element(), 1);
var import_jsx_runtime374 = __toESM(require_jsx_runtime(), 1);
function LinkSettingsDrawer({ children, settingsOpen, setSettingsOpen }) {
const prefersReducedMotion = (0, import_compose83.useReducedMotion)();
const MaybeAnimatePresence = prefersReducedMotion ? import_element215.Fragment : import_components161.__unstableAnimatePresence;
const MaybeMotionDiv = prefersReducedMotion ? "div" : import_components161.__unstableMotion.div;
const id = (0, import_compose83.useInstanceId)(LinkSettingsDrawer);
const settingsDrawerId = `link-control-settings-drawer-${id}`;
return /* @__PURE__ */ (0, import_jsx_runtime374.jsxs)(import_jsx_runtime374.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime374.jsx)(
import_components161.Button,
{
__next40pxDefaultSize: true,
className: "block-editor-link-control__drawer-toggle",
"aria-expanded": settingsOpen,
onClick: () => setSettingsOpen(!settingsOpen),
icon: (0, import_i18n150.isRTL)() ? chevron_left_small_default : chevron_right_small_default,
"aria-controls": settingsDrawerId,
children: (0, import_i18n150._x)("Advanced", "Additional link settings")
}
),
/* @__PURE__ */ (0, import_jsx_runtime374.jsx)(MaybeAnimatePresence, { children: settingsOpen && /* @__PURE__ */ (0, import_jsx_runtime374.jsx)(
MaybeMotionDiv,
{
className: "block-editor-link-control__drawer",
hidden: !settingsOpen,
id: settingsDrawerId,
initial: "collapsed",
animate: "open",
exit: "collapsed",
variants: {
open: { opacity: 1, height: "auto" },
collapsed: { opacity: 0, height: 0 }
},
transition: {
duration: 0.1
},
children: /* @__PURE__ */ (0, import_jsx_runtime374.jsx)("div", { className: "block-editor-link-control__drawer-inner", children })
}
) })
] });
}
var settings_drawer_default = LinkSettingsDrawer;
// packages/block-editor/build-module/components/link-control/search-input.mjs
var import_element218 = __toESM(require_element(), 1);
var import_i18n155 = __toESM(require_i18n(), 1);
var import_deprecated20 = __toESM(require_deprecated(), 1);
// packages/block-editor/build-module/components/link-control/search-results.mjs
var import_i18n154 = __toESM(require_i18n(), 1);
var import_components164 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/link-control/search-create-button.mjs
var import_i18n151 = __toESM(require_i18n(), 1);
var import_components162 = __toESM(require_components(), 1);
var import_element216 = __toESM(require_element(), 1);
var import_jsx_runtime375 = __toESM(require_jsx_runtime(), 1);
var LinkControlSearchCreate = ({
searchTerm,
onClick,
itemProps,
buttonText
}) => {
if (!searchTerm) {
return null;
}
let text;
if (buttonText) {
text = typeof buttonText === "function" ? buttonText(searchTerm) : buttonText;
} else {
text = (0, import_element216.createInterpolateElement)(
(0, import_i18n151.sprintf)(
/* translators: %s: search term. */
(0, import_i18n151.__)("Create: <mark>%s</mark>"),
searchTerm
),
{ mark: /* @__PURE__ */ (0, import_jsx_runtime375.jsx)("mark", {}) }
);
}
return /* @__PURE__ */ (0, import_jsx_runtime375.jsx)(
import_components162.MenuItem,
{
...itemProps,
iconPosition: "left",
icon: plus_default,
className: "block-editor-link-control__search-item",
onClick,
children: text
}
);
};
var search_create_button_default = LinkControlSearchCreate;
// packages/block-editor/build-module/components/link-control/search-item.mjs
var import_i18n152 = __toESM(require_i18n(), 1);
var import_components163 = __toESM(require_components(), 1);
var import_dom65 = __toESM(require_dom(), 1);
var import_url3 = __toESM(require_url(), 1);
var import_compose84 = __toESM(require_compose(), 1);
var import_deprecated18 = __toESM(require_deprecated(), 1);
var import_jsx_runtime376 = __toESM(require_jsx_runtime(), 1);
var TYPES = {
post: {
icon: post_list_default,
label: (0, import_i18n152.__)("Post")
},
page: {
icon: page_default,
label: (0, import_i18n152.__)("Page")
},
post_tag: {
icon: tag_default,
label: (0, import_i18n152.__)("Tag")
},
category: {
icon: category_default,
label: (0, import_i18n152.__)("Category")
},
attachment: {
icon: file_default,
label: (0, import_i18n152.__)("Attachment")
}
};
function SearchItemIcon({ isURL: isURL4, suggestion }) {
let icon = null;
if (isURL4) {
icon = globe_default;
} else if (suggestion.type in TYPES) {
icon = TYPES[suggestion.type].icon;
if (suggestion.type === "page") {
if (suggestion.isFrontPage) {
icon = home_default;
}
if (suggestion.isBlogHome) {
icon = verse_default;
}
}
}
if (icon) {
return /* @__PURE__ */ (0, import_jsx_runtime376.jsx)(
icon_default,
{
className: "block-editor-link-control__search-item-icon",
icon
}
);
}
return null;
}
function addLeadingSlash(url) {
const trimmedURL = url?.trim();
if (!trimmedURL?.length) {
return url;
}
return url?.replace(/^\/?/, "/");
}
function removeTrailingSlash(url) {
const trimmedURL = url?.trim();
if (!trimmedURL?.length) {
return url;
}
return url?.replace(/\/$/, "");
}
var partialRight = (fn, ...partialArgs) => (...args) => fn(...args, ...partialArgs);
var defaultTo = (d2) => (v2) => {
return v2 === null || v2 === void 0 || v2 !== v2 ? d2 : v2;
};
function getURLForDisplay(url) {
if (!url) {
return url;
}
return (0, import_compose84.pipe)(
import_url3.safeDecodeURI,
import_url3.getPath,
defaultTo(""),
partialRight(import_url3.filterURLForDisplay, 24),
removeTrailingSlash,
addLeadingSlash
)(url);
}
var LinkControlSearchItem = ({
itemProps,
suggestion,
searchTerm,
onClick,
isURL: isURL4 = false,
shouldShowType = false
}) => {
const info = isURL4 ? (0, import_i18n152.__)("Press ENTER to add this link") : getURLForDisplay(suggestion.url);
return /* @__PURE__ */ (0, import_jsx_runtime376.jsx)(
import_components163.MenuItem,
{
...itemProps,
info,
iconPosition: "left",
icon: /* @__PURE__ */ (0, import_jsx_runtime376.jsx)(SearchItemIcon, { suggestion, isURL: isURL4 }),
onClick,
shortcut: shouldShowType && getVisualTypeName(suggestion),
className: "block-editor-link-control__search-item",
children: /* @__PURE__ */ (0, import_jsx_runtime376.jsx)(
import_components163.TextHighlight,
{
text: (0, import_dom65.__unstableStripHTML)(suggestion.title),
highlight: searchTerm
}
)
}
);
};
function getVisualTypeName(suggestion) {
if (suggestion.isFrontPage) {
return (0, import_i18n152.__)("Front page");
}
if (suggestion.isBlogHome) {
return (0, import_i18n152.__)("Blog home");
}
if (suggestion.type in TYPES) {
return TYPES[suggestion.type].label;
}
return suggestion.type;
}
var search_item_default = LinkControlSearchItem;
var __experimentalLinkControlSearchItem = (props) => {
(0, import_deprecated18.default)("wp.blockEditor.__experimentalLinkControlSearchItem", {
since: "6.8"
});
return /* @__PURE__ */ (0, import_jsx_runtime376.jsx)(LinkControlSearchItem, { ...props });
};
// packages/block-editor/build-module/components/link-control/constants.mjs
var import_i18n153 = __toESM(require_i18n(), 1);
var CREATE_TYPE = "__CREATE__";
var TEL_TYPE = "tel";
var URL_TYPE = "link";
var MAILTO_TYPE = "mailto";
var INTERNAL_TYPE = "internal";
var LINK_ENTRY_TYPES = [
URL_TYPE,
MAILTO_TYPE,
TEL_TYPE,
INTERNAL_TYPE
];
var DEFAULT_LINK_SETTINGS = [
{
id: "opensInNewTab",
title: (0, import_i18n153.__)("Open in new tab")
}
];
// packages/block-editor/build-module/components/link-control/search-results.mjs
var import_deprecated19 = __toESM(require_deprecated(), 1);
var import_jsx_runtime377 = __toESM(require_jsx_runtime(), 1);
function LinkControlSearchResults({
withCreateSuggestion,
currentInputValue,
handleSuggestionClick,
suggestionsListProps,
buildSuggestionItemProps,
suggestions,
selectedSuggestion,
isLoading,
isInitialSuggestions,
createSuggestionButtonText,
suggestionsQuery
}) {
const resultsListClasses = clsx_default(
"block-editor-link-control__search-results",
{
"is-loading": isLoading
}
);
const isSingleDirectEntryResult = suggestions.length === 1 && LINK_ENTRY_TYPES.includes(suggestions[0].type);
const shouldShowCreateSuggestion = withCreateSuggestion && !isSingleDirectEntryResult && !isInitialSuggestions;
const shouldShowSuggestionsTypes = !suggestionsQuery?.type;
const labelText = isInitialSuggestions ? (0, import_i18n154.__)("Suggestions") : (0, import_i18n154.sprintf)(
/* translators: %s: search term. */
(0, import_i18n154.__)('Search results for "%s"'),
currentInputValue
);
return /* @__PURE__ */ (0, import_jsx_runtime377.jsx)("div", { className: "block-editor-link-control__search-results-wrapper", children: /* @__PURE__ */ (0, import_jsx_runtime377.jsx)(
"div",
{
...suggestionsListProps,
className: resultsListClasses,
"aria-label": labelText,
children: /* @__PURE__ */ (0, import_jsx_runtime377.jsx)(import_components164.MenuGroup, { children: suggestions.map((suggestion, index2) => {
if (shouldShowCreateSuggestion && CREATE_TYPE === suggestion.type) {
return /* @__PURE__ */ (0, import_jsx_runtime377.jsx)(
search_create_button_default,
{
searchTerm: currentInputValue,
buttonText: createSuggestionButtonText,
onClick: () => handleSuggestionClick(suggestion),
itemProps: buildSuggestionItemProps(
suggestion,
index2
),
isSelected: index2 === selectedSuggestion
},
suggestion.type
);
}
if (CREATE_TYPE === suggestion.type) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime377.jsx)(
search_item_default,
{
itemProps: buildSuggestionItemProps(
suggestion,
index2
),
suggestion,
index: index2,
onClick: () => {
handleSuggestionClick(suggestion);
},
isSelected: index2 === selectedSuggestion,
isURL: LINK_ENTRY_TYPES.includes(
suggestion.type
),
searchTerm: currentInputValue,
shouldShowType: shouldShowSuggestionsTypes,
isFrontPage: suggestion?.isFrontPage,
isBlogHome: suggestion?.isBlogHome
},
`${suggestion.id}-${suggestion.type}`
);
}) })
}
) });
}
var search_results_default2 = LinkControlSearchResults;
var __experimentalLinkControlSearchResults = (props) => {
(0, import_deprecated19.default)("wp.blockEditor.__experimentalLinkControlSearchResults", {
since: "6.8"
});
return /* @__PURE__ */ (0, import_jsx_runtime377.jsx)(LinkControlSearchResults, { ...props });
};
// packages/block-editor/build-module/components/link-control/use-search-handler.mjs
var import_element217 = __toESM(require_element(), 1);
var import_data145 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/link-control/normalize-url.mjs
var import_url4 = __toESM(require_url(), 1);
function normalizeUrl(url) {
const trimmedUrl = url?.trim();
if (!trimmedUrl) {
return { url: trimmedUrl, type: URL_TYPE };
}
let type = URL_TYPE;
const protocol = (0, import_url4.getProtocol)(trimmedUrl) || "";
if (protocol.includes("mailto")) {
type = MAILTO_TYPE;
} else if (protocol.includes("tel")) {
type = TEL_TYPE;
} else if (trimmedUrl?.startsWith("#")) {
type = INTERNAL_TYPE;
}
if (isHashLink(trimmedUrl) || isRelativePath(trimmedUrl) || trimmedUrl.startsWith("?") || protocol) {
return { url: trimmedUrl, type };
}
return { url: (0, import_url4.prependHTTPS)(trimmedUrl), type };
}
// packages/block-editor/build-module/components/link-control/use-search-handler.mjs
var handleNoop = () => Promise.resolve([]);
var handleDirectEntry = (val) => {
const { url, type } = normalizeUrl(val);
return Promise.resolve([
{
id: val,
title: val,
url,
type
}
]);
};
var handleEntitySearch = async (val, suggestionsQuery, fetchSearchSuggestions, withCreateSuggestion, pageOnFront, pageForPosts) => {
const { isInitialSuggestions } = suggestionsQuery;
const results = await fetchSearchSuggestions(val, suggestionsQuery);
results.map((result) => {
if (Number(result.id) === pageOnFront) {
result.isFrontPage = true;
return result;
} else if (Number(result.id) === pageForPosts) {
result.isBlogHome = true;
return result;
}
return result;
});
if (isInitialSuggestions) {
return results;
}
return isURLLike(val) || !withCreateSuggestion ? results : results.concat({
// the `id` prop is intentionally omitted here because it
// is never exposed as part of the component's public API.
// see: https://github.com/WordPress/gutenberg/pull/19775#discussion_r378931316.
title: val,
// Must match the existing `<input>`s text value.
url: val,
// Must match the existing `<input>`s text value.
type: CREATE_TYPE
});
};
function useSearchHandler(suggestionsQuery, allowDirectEntry, withCreateSuggestion) {
const { fetchSearchSuggestions, pageOnFront, pageForPosts } = (0, import_data145.useSelect)(
(select3) => {
const { getSettings: getSettings7 } = select3(store);
return {
pageOnFront: getSettings7().pageOnFront,
pageForPosts: getSettings7().pageForPosts,
fetchSearchSuggestions: getSettings7().__experimentalFetchLinkSuggestions
};
},
[]
);
const directEntryHandler = allowDirectEntry ? handleDirectEntry : handleNoop;
return (0, import_element217.useCallback)(
(val, { isInitialSuggestions }) => {
return isURLLike(val) ? directEntryHandler(val, { isInitialSuggestions }) : handleEntitySearch(
val,
{ ...suggestionsQuery, isInitialSuggestions },
fetchSearchSuggestions,
withCreateSuggestion,
pageOnFront,
pageForPosts
);
},
[
directEntryHandler,
fetchSearchSuggestions,
pageOnFront,
pageForPosts,
suggestionsQuery,
withCreateSuggestion
]
);
}
// packages/block-editor/build-module/components/link-control/search-input.mjs
var import_jsx_runtime378 = __toESM(require_jsx_runtime(), 1);
var noopSearchHandler = () => Promise.resolve([]);
var noop16 = () => {
};
var LinkControlSearchInput = (0, import_element218.forwardRef)(
({
value,
children,
currentLink = {},
className = null,
placeholder = null,
withCreateSuggestion = false,
onCreateSuggestion = noop16,
onChange = noop16,
onSelect = noop16,
showSuggestions = true,
renderSuggestions = (props) => /* @__PURE__ */ (0, import_jsx_runtime378.jsx)(search_results_default2, { ...props }),
fetchSuggestions = null,
allowDirectEntry = true,
showInitialSuggestions = false,
suggestionsQuery = {},
withURLSuggestion = true,
createSuggestionButtonText,
hideLabelFromVision = false,
suffix,
isEntity = false,
customValidity: customValidityProp
}, ref) => {
const genericSearchHandler = useSearchHandler(
suggestionsQuery,
allowDirectEntry,
withCreateSuggestion,
withURLSuggestion
);
const searchHandler = showSuggestions ? fetchSuggestions || genericSearchHandler : noopSearchHandler;
const [focusedSuggestion, setFocusedSuggestion] = (0, import_element218.useState)();
const onInputChange = (selection2, suggestion) => {
onChange(selection2);
setFocusedSuggestion(suggestion);
};
const handleRenderSuggestions = (props) => renderSuggestions({
...props,
withCreateSuggestion,
createSuggestionButtonText,
suggestionsQuery,
handleSuggestionClick: (suggestion) => {
if (props.handleSuggestionClick) {
props.handleSuggestionClick(suggestion);
}
onSuggestionSelected(suggestion);
}
});
const onSuggestionSelected = async (selectedSuggestion) => {
let suggestion = selectedSuggestion;
if (CREATE_TYPE === selectedSuggestion.type) {
try {
suggestion = await onCreateSuggestion(
selectedSuggestion.title
);
if (suggestion?.url) {
onSelect(suggestion);
}
} catch {
}
return;
}
if (allowDirectEntry || suggestion && Object.keys(suggestion).length >= 1) {
const { id, url, kind, type, ...restLinkProps } = currentLink ?? {};
onSelect(
// Some direct entries don't have types or IDs, and we still need to clear the previous ones.
{ ...restLinkProps, ...suggestion },
suggestion
);
}
};
const _placeholder = placeholder ?? (0, import_i18n155.__)("Search or type URL");
const label = hideLabelFromVision && placeholder !== "" ? _placeholder : (0, import_i18n155.__)("Link");
return /* @__PURE__ */ (0, import_jsx_runtime378.jsxs)("div", { className: "block-editor-link-control__search-input-container", children: [
/* @__PURE__ */ (0, import_jsx_runtime378.jsx)(
url_input_default,
{
disableSuggestions: currentLink?.url === value,
label,
hideLabelFromVision,
className,
value,
onChange: onInputChange,
placeholder: _placeholder,
__experimentalRenderSuggestions: showSuggestions ? handleRenderSuggestions : null,
__experimentalFetchLinkSuggestions: searchHandler,
__experimentalHandleURLSuggestions: true,
__experimentalShowInitialSuggestions: showInitialSuggestions,
customValidity: customValidityProp,
required: false,
onSubmit: (suggestion, event) => {
const hasSuggestion = suggestion || focusedSuggestion;
if (!hasSuggestion && !value?.trim()?.length) {
event.preventDefault();
} else {
onSuggestionSelected(
hasSuggestion || { url: value }
);
}
},
inputRef: ref,
suffix,
disabled: isEntity
}
),
children
] });
}
);
var search_input_default = LinkControlSearchInput;
var __experimentalLinkControlSearchInput = (props) => {
(0, import_deprecated20.default)("wp.blockEditor.__experimentalLinkControlSearchInput", {
since: "6.8"
});
return /* @__PURE__ */ (0, import_jsx_runtime378.jsx)(LinkControlSearchInput, { ...props });
};
// packages/block-editor/build-module/components/link-control/link-preview.mjs
var import_i18n156 = __toESM(require_i18n(), 1);
var import_components166 = __toESM(require_components(), 1);
var import_compose85 = __toESM(require_compose(), 1);
var import_url5 = __toESM(require_url(), 1);
var import_dom66 = __toESM(require_dom(), 1);
var import_data147 = __toESM(require_data(), 1);
var import_notices10 = __toESM(require_notices(), 1);
var import_preferences3 = __toESM(require_preferences(), 1);
// packages/block-editor/build-module/components/link-control/viewer-slot.mjs
var import_components165 = __toESM(require_components(), 1);
var { Slot: ViewerSlot, Fill: ViewerFill } = (0, import_components165.createSlotFill)(
"BlockEditorLinkControlViewer"
);
// packages/block-editor/build-module/components/link-control/use-rich-url-data.mjs
var import_data146 = __toESM(require_data(), 1);
var import_element219 = __toESM(require_element(), 1);
function reducer(state, action) {
switch (action.type) {
case "RESOLVED":
return {
...state,
isFetching: false,
richData: action.richData
};
case "ERROR":
return {
...state,
isFetching: false,
richData: null
};
case "LOADING":
return {
...state,
isFetching: true
};
default:
throw new Error(`Unexpected action type ${action.type}`);
}
}
function useRemoteUrlData(url) {
const [state, dispatch] = (0, import_element219.useReducer)(reducer, {
richData: null,
isFetching: false
});
const { fetchRichUrlData } = (0, import_data146.useSelect)((select3) => {
const { getSettings: getSettings7 } = select3(store);
return {
fetchRichUrlData: getSettings7().__experimentalFetchRichUrlData
};
}, []);
(0, import_element219.useEffect)(() => {
if (url?.length && fetchRichUrlData && typeof AbortController !== "undefined") {
dispatch({
type: "LOADING"
});
const controller = new window.AbortController();
const signal = controller.signal;
fetchRichUrlData(url, {
signal
}).then((urlData) => {
dispatch({
type: "RESOLVED",
richData: urlData
});
}).catch(() => {
if (!signal.aborted) {
dispatch({
type: "ERROR"
});
}
});
return () => {
controller.abort();
};
}
}, [url]);
return state;
}
var use_rich_url_data_default = useRemoteUrlData;
// packages/block-editor/build-module/components/link-control/link-preview.mjs
var import_jsx_runtime379 = __toESM(require_jsx_runtime(), 1);
var { Badge: WCBadge4 } = unlock(import_components166.privateApis);
function LinkPreview({
value,
onEditClick,
hasRichPreviews = false,
hasUnlinkControl = false,
onRemove
}) {
const showIconLabels = (0, import_data147.useSelect)(
(select3) => select3(import_preferences3.store).get("core", "showIconLabels"),
[]
);
const showRichPreviews = hasRichPreviews ? value?.url : null;
const { richData, isFetching } = use_rich_url_data_default(showRichPreviews);
const hasRichData = richData && Object.keys(richData).length;
const displayURL = value && (0, import_url5.filterURLForDisplay)((0, import_url5.safeDecodeURI)(value.url), 24) || "";
const isEmptyURL = !value?.url?.length;
const displayTitle = !isEmptyURL && (0, import_dom66.__unstableStripHTML)(
value?.entityTitle || richData?.title || value?.title || displayURL
);
let icon;
if (richData?.icon) {
icon = /* @__PURE__ */ (0, import_jsx_runtime379.jsx)("img", { src: richData?.icon, alt: "" });
} else if (isEmptyURL) {
icon = /* @__PURE__ */ (0, import_jsx_runtime379.jsx)(icon_default, { icon: info_default, size: 32 });
} else {
icon = /* @__PURE__ */ (0, import_jsx_runtime379.jsx)(icon_default, { icon: globe_default });
}
const { createNotice } = (0, import_data147.useDispatch)(import_notices10.store);
const ref = (0, import_compose85.useCopyToClipboard)(value.url, () => {
createNotice("info", (0, import_i18n156.__)("Link copied to clipboard."), {
isDismissible: true,
type: "snackbar"
});
});
return /* @__PURE__ */ (0, import_jsx_runtime379.jsx)(
import_components166.Flex,
{
role: "group",
"aria-label": (0, import_i18n156.__)("Manage link"),
className: clsx_default("block-editor-link-control__preview", {
"is-current": true,
"is-rich": hasRichData,
"is-fetching": !!isFetching,
"is-preview": true,
"is-error": isEmptyURL,
"is-url-title": displayTitle === displayURL
}),
children: /* @__PURE__ */ (0, import_jsx_runtime379.jsxs)(import_components166.Flex, { gap: 0, align: "flex-start", children: [
/* @__PURE__ */ (0, import_jsx_runtime379.jsxs)(
import_components166.Flex,
{
className: "block-editor-link-control__link-information",
role: "figure",
"aria-label": (
/* translators: Accessibility text for the link preview when editing a link. */
(0, import_i18n156.__)("Link information")
),
justify: "start",
align: "flex-start",
children: [
value?.image ? /* @__PURE__ */ (0, import_jsx_runtime379.jsx)(
import_components166.Flex,
{
className: "block-editor-link-control__preview-image",
justify: "center",
children: /* @__PURE__ */ (0, import_jsx_runtime379.jsx)("img", { src: value?.image, alt: "" })
}
) : /* @__PURE__ */ (0, import_jsx_runtime379.jsx)(
import_components166.Flex,
{
className: clsx_default(
"block-editor-link-control__preview-icon",
{
"is-image": richData?.icon
}
),
justify: "center",
children: icon
}
),
/* @__PURE__ */ (0, import_jsx_runtime379.jsx)(
import_components166.Flex,
{
className: "block-editor-link-control__preview-details",
direction: "column",
gap: 2,
children: !isEmptyURL ? /* @__PURE__ */ (0, import_jsx_runtime379.jsxs)(import_jsx_runtime379.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime379.jsx)(
import_components166.ExternalLink,
{
className: "block-editor-link-control__preview-title",
href: value.url,
children: /* @__PURE__ */ (0, import_jsx_runtime379.jsx)(import_components166.__experimentalTruncate, { numberOfLines: 1, children: displayTitle })
}
),
/* @__PURE__ */ (0, import_jsx_runtime379.jsx)("span", { className: "block-editor-link-control__preview-info", children: /* @__PURE__ */ (0, import_jsx_runtime379.jsx)(import_components166.__experimentalTruncate, { numberOfLines: 1, children: displayURL }) }),
value?.badges?.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime379.jsx)(
import_components166.__experimentalHStack,
{
className: "block-editor-link-control__preview-badges",
alignment: "left",
gap: 1,
children: value.badges.map(
(badge, index2) => /* @__PURE__ */ (0, import_jsx_runtime379.jsx)(
WCBadge4,
{
intent: badge.intent,
children: badge.label
},
`${badge.label}|${badge.intent}|${index2}`
)
)
}
)
] }) : /* @__PURE__ */ (0, import_jsx_runtime379.jsx)("span", { className: "block-editor-link-control__preview-error-notice", children: (0, import_i18n156.__)("Link is empty") })
}
)
]
}
),
/* @__PURE__ */ (0, import_jsx_runtime379.jsx)(
import_components166.Button,
{
icon: pencil_default,
label: (0, import_i18n156.__)("Edit link"),
onClick: onEditClick,
size: "compact",
showTooltip: !showIconLabels
}
),
hasUnlinkControl && /* @__PURE__ */ (0, import_jsx_runtime379.jsx)(
import_components166.Button,
{
icon: link_off_default,
label: (0, import_i18n156.__)("Remove link"),
onClick: onRemove,
size: "compact",
showTooltip: !showIconLabels
}
),
/* @__PURE__ */ (0, import_jsx_runtime379.jsx)(
import_components166.Button,
{
icon: copy_small_default,
label: (0, import_i18n156.__)("Copy link"),
ref,
accessibleWhenDisabled: true,
disabled: isEmptyURL,
size: "compact",
showTooltip: !showIconLabels
}
),
/* @__PURE__ */ (0, import_jsx_runtime379.jsx)(ViewerSlot, { fillProps: value })
] })
}
);
}
// packages/block-editor/build-module/components/link-control/settings.mjs
var import_i18n157 = __toESM(require_i18n(), 1);
var import_components167 = __toESM(require_components(), 1);
var import_jsx_runtime380 = __toESM(require_jsx_runtime(), 1);
var noop17 = () => {
};
var LinkControlSettings = ({ value, onChange = noop17, settings: settings2 }) => {
if (!settings2 || !settings2.length) {
return null;
}
const handleSettingChange = (setting) => (newValue) => {
onChange({
...value,
[setting.id]: newValue
});
};
const theSettings = settings2.map((setting) => {
if ("render" in setting) {
if (typeof setting.render === "function") {
const renderedContent = setting.render(
setting,
value,
onChange
);
return /* @__PURE__ */ (0, import_jsx_runtime380.jsx)(
"div",
{
className: "block-editor-link-control__setting",
children: renderedContent
},
setting.id
);
}
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime380.jsx)(
import_components167.CheckboxControl,
{
className: "block-editor-link-control__setting",
label: setting.title,
onChange: handleSettingChange(setting),
checked: value ? !!value[setting.id] : false,
help: setting?.help
},
setting.id
);
}).filter(Boolean);
return /* @__PURE__ */ (0, import_jsx_runtime380.jsxs)("fieldset", { className: "block-editor-link-control__settings", children: [
/* @__PURE__ */ (0, import_jsx_runtime380.jsx)(VisuallyHidden, { render: /* @__PURE__ */ (0, import_jsx_runtime380.jsx)("legend", {}), children: (0, import_i18n157.__)("Currently selected link settings") }),
theSettings
] });
};
var settings_default2 = LinkControlSettings;
// packages/block-editor/build-module/components/link-control/use-create-page.mjs
var import_i18n158 = __toESM(require_i18n(), 1);
var import_element220 = __toESM(require_element(), 1);
function useCreatePage(handleCreatePage) {
const cancelableCreateSuggestion = (0, import_element220.useRef)();
const [isCreatingPage, setIsCreatingPage] = (0, import_element220.useState)(false);
const [errorMessage, setErrorMessage] = (0, import_element220.useState)(null);
const createPage = async function(suggestionTitle) {
setIsCreatingPage(true);
setErrorMessage(null);
try {
cancelableCreateSuggestion.current = makeCancelable(
// Using Promise.resolve to allow createSuggestion to return a
// non-Promise based value.
Promise.resolve(handleCreatePage(suggestionTitle))
);
return await cancelableCreateSuggestion.current.promise;
} catch (error2) {
if (error2 && error2.isCanceled) {
return;
}
setErrorMessage(
error2.message || (0, import_i18n158.__)(
"An unknown error occurred during creation. Please try again."
)
);
throw error2;
} finally {
setIsCreatingPage(false);
}
};
(0, import_element220.useEffect)(() => {
return () => {
if (cancelableCreateSuggestion.current) {
cancelableCreateSuggestion.current.cancel();
}
};
}, []);
return {
createPage,
isCreatingPage,
errorMessage
};
}
var makeCancelable = (promise) => {
let hasCanceled_ = false;
const wrappedPromise = new Promise((resolve, reject) => {
promise.then(
(val) => hasCanceled_ ? reject({ isCanceled: true }) : resolve(val),
(error2) => hasCanceled_ ? reject({ isCanceled: true }) : reject(error2)
);
});
return {
promise: wrappedPromise,
cancel() {
hasCanceled_ = true;
}
};
};
// packages/block-editor/build-module/components/link-control/use-internal-value.mjs
var import_element221 = __toESM(require_element(), 1);
var import_fast_deep_equal = __toESM(require_fast_deep_equal(), 1);
function useInternalValue(value) {
const [internalValue, setInternalValue] = (0, import_element221.useState)(value || {});
const [previousValue, setPreviousValue] = (0, import_element221.useState)(value);
if (!(0, import_fast_deep_equal.default)(value, previousValue)) {
setPreviousValue(value);
setInternalValue(value);
}
const setInternalURLInputValue = (nextValue) => {
setInternalValue({
...internalValue,
url: nextValue
});
};
const setInternalTextInputValue = (nextValue) => {
setInternalValue({
...internalValue,
title: nextValue
});
};
const createSetInternalSettingValueHandler = (settingsKeys) => (nextValue) => {
const settingsUpdates = Object.keys(nextValue).reduce(
(acc, key) => {
if (settingsKeys.includes(key)) {
acc[key] = nextValue[key];
}
return acc;
},
{}
);
setInternalValue({
...internalValue,
...settingsUpdates
});
};
return [
internalValue,
setInternalValue,
setInternalURLInputValue,
setInternalTextInputValue,
createSetInternalSettingValueHandler
];
}
// packages/block-editor/build-module/components/link-control/index.mjs
var import_jsx_runtime381 = __toESM(require_jsx_runtime(), 1);
var noop18 = () => {
};
var PREFERENCE_SCOPE = "core/block-editor";
var PREFERENCE_KEY = "linkControlSettingsDrawer";
function LinkControl({
searchInputPlaceholder,
value,
settings: settings2 = DEFAULT_LINK_SETTINGS,
onChange = noop18,
onInputChange,
onRemove,
onCancel,
noDirectEntry = false,
showSuggestions = true,
showInitialSuggestions,
forceIsEditingLink,
createSuggestion,
withCreateSuggestion,
inputValue: propInputValue = "",
suggestionsQuery = {},
noURLSuggestion = false,
createSuggestionButtonText,
hasRichPreviews = false,
hasTextControl = false,
renderControlBottom = null,
handleEntities = false
}) {
if (withCreateSuggestion === void 0 && createSuggestion) {
withCreateSuggestion = true;
}
const [settingsOpen, setSettingsOpen] = (0, import_element222.useState)(false);
const [customValidity, setCustomValidity] = (0, import_element222.useState)(void 0);
const { advancedSettingsPreference } = (0, import_data148.useSelect)((select3) => {
const prefsStore = select3(import_preferences4.store);
return {
advancedSettingsPreference: prefsStore.get(PREFERENCE_SCOPE, PREFERENCE_KEY) ?? false
};
}, []);
const { set: setPreference } = (0, import_data148.useDispatch)(import_preferences4.store);
const setSettingsOpenWithPreference = (prefVal) => {
if (setPreference) {
setPreference(PREFERENCE_SCOPE, PREFERENCE_KEY, prefVal);
}
setSettingsOpen(prefVal);
};
const isSettingsOpen = advancedSettingsPreference || settingsOpen;
const isMountingRef = (0, import_element222.useRef)(true);
const wrapperNode = (0, import_element222.useRef)();
const textInputRef = (0, import_element222.useRef)();
const searchInputRef = (0, import_element222.useRef)();
const entityUrlFallbackRef = (0, import_element222.useRef)();
const settingsKeys = settings2.map(({ id }) => id);
const [
internalControlValue,
setInternalControlValue,
setInternalURLInputValue,
setInternalTextInputValue,
createSetInternalSettingValueHandler
] = useInternalValue(value);
const handleInputChange = (newValue) => {
setInternalURLInputValue(newValue);
onInputChange?.(newValue);
};
const isEntity = handleEntities && !!internalControlValue?.id;
const baseId = (0, import_compose86.useInstanceId)(LinkControl, "link-control");
const helpTextId = isEntity ? `${baseId}__help` : null;
const valueHasChanges = value && !(0, import_is_shallow_equal3.isShallowEqualObjects)(internalControlValue, value);
const [isEditingLink, setIsEditingLink] = (0, import_element222.useState)(
forceIsEditingLink !== void 0 ? forceIsEditingLink : !value || !value.url
);
const { createPage, isCreatingPage, errorMessage } = useCreatePage(createSuggestion);
(0, import_element222.useEffect)(() => {
if (forceIsEditingLink === void 0) {
return;
}
setIsEditingLink(forceIsEditingLink);
}, [forceIsEditingLink]);
(0, import_element222.useEffect)(() => {
if (isMountingRef.current) {
return;
}
const nextFocusTarget = import_dom67.focus.focusable.find(wrapperNode.current)[0] || wrapperNode.current;
nextFocusTarget.focus();
}, [isEditingLink, isCreatingPage]);
(0, import_element222.useEffect)(() => {
isMountingRef.current = false;
return () => {
isMountingRef.current = true;
};
}, []);
const prevInputValueRef = (0, import_element222.useRef)();
(0, import_element222.useEffect)(() => {
if (prevInputValueRef.current === void 0) {
prevInputValueRef.current = propInputValue;
return;
}
if (prevInputValueRef.current !== propInputValue) {
console.warn(
"LinkControl: The inputValue prop is uncontrolled and only sets the initial value. onInputChange is an observer for the input value. Changes to inputValue from the parent will not update the search input."
);
prevInputValueRef.current = propInputValue;
}
}, [propInputValue]);
(0, import_element222.useEffect)(() => {
if (customValidity?.type === "invalid") {
const inputElement = searchInputRef.current;
if (inputElement && typeof inputElement.reportValidity === "function") {
inputElement.reportValidity();
}
}
}, [customValidity]);
const hasLinkValue = value?.url?.trim()?.length > 0;
const stopEditing = () => {
setIsEditingLink(false);
};
const validateUrl = (urlToValidate) => {
const invalidResult = {
type: "invalid",
message: (0, import_i18n159.__)("Please enter a valid URL.")
};
const validResult = {
type: "valid"
};
const trimmedValue = urlToValidate?.trim();
if (!trimmedValue?.length || !isURLLike(trimmedValue)) {
return invalidResult;
}
if (isHashLink(trimmedValue) || isRelativePath(trimmedValue)) {
return validResult;
}
const urlToCheck = (0, import_url6.prependHTTPS)(trimmedValue);
return (0, import_url6.isURL)(urlToCheck) ? validResult : invalidResult;
};
const handleSelectSuggestion = (updatedValue) => {
const isEntitySuggestion = updatedValue && updatedValue.id && updatedValue.type && !LINK_ENTRY_TYPES.includes(updatedValue.type);
if (!isEntitySuggestion) {
const urlToValidate = updatedValue?.url || currentUrlInputValue;
const validation = validateUrl(urlToValidate);
if (validation.type === "invalid") {
setCustomValidity(validation);
return;
}
const { url: normalizedUrl } = normalizeUrl(urlToValidate);
updatedValue = {
...updatedValue,
url: normalizedUrl
};
}
if (updatedValue?.kind === "taxonomy" && updatedValue?.url) {
entityUrlFallbackRef.current = updatedValue.url;
}
const nonSettingsChanges = Object.keys(updatedValue).reduce(
(acc, key) => {
if (!settingsKeys.includes(key)) {
acc[key] = updatedValue[key];
}
return acc;
},
{}
);
onChange({
...internalControlValue,
...nonSettingsChanges,
// As title is not a setting, it must be manually applied
// in such a way as to preserve the users changes over
// any "title" value provided by the "suggestion".
title: internalControlValue?.title || updatedValue?.title
});
setCustomValidity(void 0);
stopEditing();
};
const validateAndSetValidity = () => {
if (currentInputIsEmpty) {
return false;
}
const trimmedValue = currentUrlInputValue.trim();
const isEntityLink = internalControlValue && internalControlValue.id && internalControlValue.type && !LINK_ENTRY_TYPES.includes(internalControlValue.type);
const urlUnchanged = value?.url === trimmedValue;
if (isEntityLink && urlUnchanged) {
setCustomValidity(void 0);
return true;
}
const validation = validateUrl(currentUrlInputValue);
if (validation.type === "invalid") {
setCustomValidity(validation);
return false;
}
setCustomValidity(void 0);
return true;
};
const submitUrlValue = () => {
if (valueHasChanges) {
onChange({
...value,
...internalControlValue,
url: normalizeUrl(currentUrlInputValue).url
});
}
stopEditing();
setCustomValidity(void 0);
};
const handleSubmit = () => {
if (!validateAndSetValidity()) {
return;
}
submitUrlValue();
};
const handleSubmitWithEnter = (event) => {
const { keyCode } = event;
if (keyCode === import_keycodes19.ENTER && !currentInputIsEmpty) {
event.preventDefault();
handleSubmit();
}
};
const resetInternalValues = () => {
setInternalControlValue(value);
};
const handleCancel = (event) => {
event.preventDefault();
event.stopPropagation();
resetInternalValues();
setCustomValidity(void 0);
if (hasLinkValue) {
stopEditing();
} else {
onRemove?.();
}
onCancel?.();
};
const [shouldFocusSearchInput, setShouldFocusSearchInput] = (0, import_element222.useState)(false);
const handleUnlink = () => {
const { id, kind, type, ...restValue } = internalControlValue;
setInternalControlValue({
...restValue,
id: void 0,
kind: void 0,
type: void 0,
url: void 0
});
setShouldFocusSearchInput(true);
};
(0, import_element222.useEffect)(() => {
if (shouldFocusSearchInput) {
searchInputRef.current?.focus();
setShouldFocusSearchInput(false);
}
}, [shouldFocusSearchInput]);
const currentUrlInputValue = internalControlValue?.url !== void 0 ? internalControlValue.url : propInputValue || "";
const currentInputIsEmpty = !currentUrlInputValue?.trim()?.length;
(0, import_element222.useEffect)(() => {
setCustomValidity(void 0);
}, [currentUrlInputValue]);
const isUrlValid = !customValidity;
const shownUnlinkControl = onRemove && value && !isEditingLink && !isCreatingPage;
const showActions = isEditingLink && hasLinkValue;
const showTextControl = hasLinkValue && hasTextControl;
const isEditing = (isEditingLink || !value) && !isCreatingPage;
const isDisabled = currentInputIsEmpty || !isUrlValid || value && !valueHasChanges;
const showSettings = !!settings2?.length && isEditingLink && hasLinkValue;
const previewValue = (0, import_element222.useMemo)(() => {
if (value?.kind === "taxonomy" && !value?.url && entityUrlFallbackRef.current) {
return {
...value,
url: entityUrlFallbackRef.current
};
}
return value;
}, [value]);
return /* @__PURE__ */ (0, import_jsx_runtime381.jsxs)(
"div",
{
tabIndex: -1,
ref: wrapperNode,
className: "block-editor-link-control",
children: [
isCreatingPage && /* @__PURE__ */ (0, import_jsx_runtime381.jsxs)("div", { className: "block-editor-link-control__loading", children: [
/* @__PURE__ */ (0, import_jsx_runtime381.jsx)(import_components168.Spinner, {}),
" ",
(0, import_i18n159.__)("Creating"),
"\u2026"
] }),
isEditing && /* @__PURE__ */ (0, import_jsx_runtime381.jsxs)(import_jsx_runtime381.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime381.jsxs)(
"div",
{
className: clsx_default({
"block-editor-link-control__search-input-wrapper": true,
"has-text-control": showTextControl,
"has-actions": showActions
}),
children: [
showTextControl && /* @__PURE__ */ (0, import_jsx_runtime381.jsx)(
import_components168.TextControl,
{
ref: textInputRef,
className: "block-editor-link-control__field block-editor-link-control__text-content",
label: (0, import_i18n159.__)("Text"),
value: internalControlValue?.title,
onChange: setInternalTextInputValue,
onKeyDown: handleSubmitWithEnter
}
),
/* @__PURE__ */ (0, import_jsx_runtime381.jsx)(
search_input_default,
{
ref: searchInputRef,
currentLink: value,
className: "block-editor-link-control__field block-editor-link-control__search-input",
placeholder: searchInputPlaceholder,
value: currentUrlInputValue,
withCreateSuggestion,
onCreateSuggestion: createPage,
onChange: handleInputChange,
onSelect: handleSelectSuggestion,
showInitialSuggestions,
allowDirectEntry: !noDirectEntry,
showSuggestions,
suggestionsQuery,
withURLSuggestion: !noURLSuggestion,
createSuggestionButtonText,
hideLabelFromVision: !showTextControl,
isEntity,
customValidity,
suffix: /* @__PURE__ */ (0, import_jsx_runtime381.jsx)(
SearchSuffixControl,
{
isEntity,
showActions,
isDisabled,
onUnlink: handleUnlink,
onSubmit: handleSubmit,
helpTextId
}
)
}
),
isEntity && helpTextId && /* @__PURE__ */ (0, import_jsx_runtime381.jsx)(
"p",
{
id: helpTextId,
className: "block-editor-link-control__help",
children: (0, import_i18n159.sprintf)(
/* translators: %s: entity type (e.g., page, post) */
(0, import_i18n159.__)("Synced with the selected %s."),
internalControlValue?.type || "item"
)
}
)
]
}
),
errorMessage && /* @__PURE__ */ (0, import_jsx_runtime381.jsx)(
import_components168.Notice,
{
className: "block-editor-link-control__search-error",
status: "error",
isDismissible: false,
children: errorMessage
}
)
] }),
value && !isEditingLink && !isCreatingPage && /* @__PURE__ */ (0, import_jsx_runtime381.jsx)(
LinkPreview,
{
value: previewValue,
onEditClick: () => setIsEditingLink(true),
hasRichPreviews,
hasUnlinkControl: shownUnlinkControl,
onRemove: () => {
onRemove();
setIsEditingLink(true);
}
},
previewValue?.url
),
showSettings && /* @__PURE__ */ (0, import_jsx_runtime381.jsx)("div", { className: "block-editor-link-control__tools", children: !currentInputIsEmpty && /* @__PURE__ */ (0, import_jsx_runtime381.jsx)(
settings_drawer_default,
{
settingsOpen: isSettingsOpen,
setSettingsOpen: setSettingsOpenWithPreference,
children: /* @__PURE__ */ (0, import_jsx_runtime381.jsx)(
settings_default2,
{
value: internalControlValue,
settings: settings2,
onChange: createSetInternalSettingValueHandler(
settingsKeys
)
}
)
}
) }),
showActions && /* @__PURE__ */ (0, import_jsx_runtime381.jsxs)(
import_components168.__experimentalHStack,
{
justify: "right",
className: "block-editor-link-control__search-actions",
children: [
/* @__PURE__ */ (0, import_jsx_runtime381.jsx)(
import_components168.Button,
{
__next40pxDefaultSize: true,
variant: "tertiary",
onClick: handleCancel,
children: (0, import_i18n159.__)("Cancel")
}
),
/* @__PURE__ */ (0, import_jsx_runtime381.jsx)(
import_components168.Button,
{
__next40pxDefaultSize: true,
variant: "primary",
onClick: isDisabled ? noop18 : handleSubmit,
className: "block-editor-link-control__search-submit",
"aria-disabled": isDisabled,
children: (0, import_i18n159.__)("Apply")
}
)
]
}
),
!isCreatingPage && renderControlBottom && renderControlBottom()
]
}
);
}
function SearchSuffixControl({
isEntity,
showActions,
isDisabled,
onUnlink,
onSubmit,
helpTextId
}) {
if (isEntity) {
return /* @__PURE__ */ (0, import_jsx_runtime381.jsx)(
import_components168.Button,
{
icon: link_off_default,
onClick: onUnlink,
"aria-describedby": helpTextId,
showTooltip: true,
label: (0, import_i18n159.__)("Unsync and edit"),
__next40pxDefaultSize: true
}
);
}
if (showActions) {
return void 0;
}
return /* @__PURE__ */ (0, import_jsx_runtime381.jsx)(import_components168.__experimentalInputControlSuffixWrapper, { variant: "control", children: /* @__PURE__ */ (0, import_jsx_runtime381.jsx)(
import_components168.Button,
{
onClick: isDisabled ? noop18 : onSubmit,
label: (0, import_i18n159.__)("Submit"),
icon: keyboard_return_default,
className: "block-editor-link-control__search-submit",
"aria-disabled": isDisabled,
size: "small"
}
) });
}
LinkControl.ViewerFill = ViewerFill;
LinkControl.DEFAULT_LINK_SETTINGS = DEFAULT_LINK_SETTINGS;
var DeprecatedExperimentalLinkControl = (props) => {
(0, import_deprecated21.default)("wp.blockEditor.__experimentalLinkControl", {
since: "6.8",
alternative: "wp.blockEditor.LinkControl"
});
return /* @__PURE__ */ (0, import_jsx_runtime381.jsx)(LinkControl, { ...props });
};
DeprecatedExperimentalLinkControl.ViewerFill = LinkControl.ViewerFill;
DeprecatedExperimentalLinkControl.DEFAULT_LINK_SETTINGS = LinkControl.DEFAULT_LINK_SETTINGS;
var link_control_default = LinkControl;
// packages/block-editor/build-module/components/line-height-control/index.mjs
var import_i18n160 = __toESM(require_i18n(), 1);
var import_components169 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/line-height-control/utils.mjs
var BASE_DEFAULT_VALUE = 1.5;
var STEP = 0.01;
var SPIN_FACTOR = 10;
var RESET_VALUE = "";
function isLineHeightDefined(lineHeight) {
return lineHeight !== void 0 && lineHeight !== RESET_VALUE;
}
// packages/block-editor/build-module/components/line-height-control/index.mjs
var import_jsx_runtime382 = __toESM(require_jsx_runtime(), 1);
var LineHeightControl = ({
/**
* Start opting into the larger default height that will become the default size in a future version.
*
* @deprecated Default behavior since WordPress 7.1. Prop can be safely removed.
*/
__next40pxDefaultSize: _next40pxDefaultSize,
value: lineHeight,
onChange,
__unstableInputWidth = "60px",
...otherProps
}) => {
const isDefined = isLineHeightDefined(lineHeight);
const adjustNextValue = (nextValue, wasTypedOrPasted) => {
if (isDefined) {
return nextValue;
}
const spin = STEP * SPIN_FACTOR;
switch (`${nextValue}`) {
case `${spin}`:
return BASE_DEFAULT_VALUE + spin;
case "0": {
if (wasTypedOrPasted) {
return nextValue;
}
return BASE_DEFAULT_VALUE - spin;
}
case "":
return BASE_DEFAULT_VALUE;
default:
return nextValue;
}
};
const stateReducer = (state, action) => {
const wasTypedOrPasted = ["insertText", "insertFromPaste"].includes(
action.payload.event.nativeEvent?.inputType
);
const value2 = adjustNextValue(state.value, wasTypedOrPasted);
return { ...state, value: value2 };
};
const value = isDefined ? lineHeight : RESET_VALUE;
const handleOnChange = (nextValue, { event }) => {
if (nextValue === "") {
onChange();
return;
}
if (event.type === "click") {
onChange(adjustNextValue(`${nextValue}`, false));
return;
}
onChange(`${nextValue}`);
};
return /* @__PURE__ */ (0, import_jsx_runtime382.jsx)("div", { className: "block-editor-line-height-control", children: /* @__PURE__ */ (0, import_jsx_runtime382.jsx)(
import_components169.__experimentalNumberControl,
{
...otherProps,
__unstableInputWidth,
__unstableStateReducer: stateReducer,
onChange: handleOnChange,
label: (0, import_i18n160.__)("Line height"),
placeholder: BASE_DEFAULT_VALUE,
step: STEP,
spinFactor: SPIN_FACTOR,
value,
min: 0,
spinControls: "custom"
}
) });
};
var line_height_control_default = LineHeightControl;
// packages/block-editor/build-module/components/media-replace-flow/index.mjs
var import_i18n161 = __toESM(require_i18n(), 1);
var import_a11y18 = __toESM(require_a11y(), 1);
var import_components170 = __toESM(require_components(), 1);
var import_data149 = __toESM(require_data(), 1);
var import_keycodes20 = __toESM(require_keycodes(), 1);
var import_compose87 = __toESM(require_compose(), 1);
var import_dom68 = __toESM(require_dom(), 1);
var import_notices11 = __toESM(require_notices(), 1);
var import_element223 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/media-placeholder/utils.mjs
function getComputedAcceptAttribute(allowedTypes, allowedMimeTypes, accept) {
if (accept) {
return accept;
}
if (!allowedMimeTypes || typeof allowedMimeTypes !== "object" || Object.keys(allowedMimeTypes).length === 0) {
if (allowedTypes && allowedTypes.length > 0) {
return allowedTypes.map((type) => `${type}/*`).join(",");
}
return void 0;
}
if (!allowedTypes || allowedTypes.length === 0) {
return void 0;
}
const acceptedMimeTypes = [];
for (const [, mimeType] of Object.entries(allowedMimeTypes)) {
const isAllowed = allowedTypes.some((allowedType) => {
if (allowedType.includes("/")) {
return mimeType === allowedType;
}
return mimeType.startsWith(`${allowedType}/`);
});
if (isAllowed) {
acceptedMimeTypes.push(mimeType);
}
}
if (acceptedMimeTypes.length > 0) {
return acceptedMimeTypes.join(",");
}
return allowedTypes.map((type) => `${type}/*`).join(",");
}
// packages/block-editor/build-module/components/media-replace-flow/index.mjs
var import_jsx_runtime383 = __toESM(require_jsx_runtime(), 1);
var noop19 = () => {
};
var uniqueId = 0;
var MediaReplaceFlow = ({
mediaURL,
mediaId,
mediaIds,
allowedTypes,
accept,
onError,
onSelect,
onSelectURL,
onReset,
onToggleFeaturedImage,
useFeaturedImage,
onFilesUpload = noop19,
name = (0, import_i18n161.__)("Replace"),
createNotice,
removeNotice,
children,
multiple = false,
addToGallery,
handleUpload = true,
variant,
popoverProps: popoverProps3,
renderToggle: renderToggle3,
className
}) => {
const { mediaUpload: mediaUpload2, allowedMimeTypes } = (0, import_data149.useSelect)((select3) => {
const { getSettings: getSettings7 } = select3(store);
const settings2 = getSettings7();
return {
mediaUpload: settings2.mediaUpload,
allowedMimeTypes: settings2.allowedMimeTypes
};
}, []);
const errorNoticeID = `block-editor/media-replace-flow/error-notice/${++uniqueId}`;
const computedAccept = (0, import_element223.useMemo)(
() => getComputedAcceptAttribute(
allowedTypes,
allowedMimeTypes,
accept
),
[allowedTypes, allowedMimeTypes, accept]
);
const onUploadError = (message2) => {
const safeMessage = (0, import_dom68.__unstableStripHTML)(message2);
if (onError) {
onError(safeMessage);
return;
}
setTimeout(() => {
createNotice("error", safeMessage, {
speak: true,
id: errorNoticeID,
isDismissible: true
});
}, 1e3);
};
const selectMedia = (media, closeMenu) => {
if (useFeaturedImage && onToggleFeaturedImage) {
onToggleFeaturedImage();
}
closeMenu();
onSelect(media);
(0, import_a11y18.speak)((0, import_i18n161.__)("The media file has been replaced"));
removeNotice(errorNoticeID);
};
const uploadFiles = (event, closeMenu) => {
const files = event.target.files;
if (!handleUpload) {
closeMenu();
return onSelect(files);
}
onFilesUpload(files);
mediaUpload2({
allowedTypes,
filesList: files,
onFileChange: ([media]) => {
selectMedia(media, closeMenu);
},
onError: onUploadError
});
};
const openOnArrowDown = (event) => {
if (event.keyCode === import_keycodes20.DOWN) {
event.preventDefault();
event.target.click();
}
};
const onlyAllowsImages = () => {
if (!allowedTypes || allowedTypes.length === 0) {
return false;
}
return allowedTypes.every(
(allowedType) => allowedType === "image" || allowedType.startsWith("image/")
);
};
const gallery = multiple && onlyAllowsImages();
const mergedPopoverProps = {
...popoverProps3,
variant
};
return /* @__PURE__ */ (0, import_jsx_runtime383.jsx)(
import_components170.Dropdown,
{
popoverProps: mergedPopoverProps,
className,
contentClassName: clsx_default(
"block-editor-media-replace-flow__options",
variant && `is-variant-${variant}`
),
renderToggle: ({ isOpen, onToggle }) => {
if (renderToggle3) {
return renderToggle3({
"aria-expanded": isOpen,
"aria-haspopup": "true",
onClick: onToggle,
onKeyDown: openOnArrowDown,
children: name
});
}
return /* @__PURE__ */ (0, import_jsx_runtime383.jsx)(
import_components170.ToolbarButton,
{
"aria-expanded": isOpen,
"aria-haspopup": "true",
onClick: onToggle,
onKeyDown: openOnArrowDown,
children: name
}
);
},
renderContent: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime383.jsxs)(import_jsx_runtime383.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime383.jsxs)(import_components170.NavigableMenu, { className: "block-editor-media-replace-flow__media-upload-menu", children: [
/* @__PURE__ */ (0, import_jsx_runtime383.jsxs)(check_default2, { children: [
/* @__PURE__ */ (0, import_jsx_runtime383.jsx)(
media_upload_default,
{
gallery,
addToGallery,
multiple,
value: multiple ? mediaIds : mediaId,
onSelect: (media) => selectMedia(media, onClose),
allowedTypes,
render: ({ open }) => /* @__PURE__ */ (0, import_jsx_runtime383.jsx)(
import_components170.MenuItem,
{
icon: media_default,
onClick: open,
children: (0, import_i18n161.__)("Open Media Library")
}
)
}
),
/* @__PURE__ */ (0, import_jsx_runtime383.jsx)(
import_components170.FormFileUpload,
{
onChange: (event) => {
uploadFiles(event, onClose);
},
accept: computedAccept,
multiple: !!multiple,
render: ({ openFileDialog }) => {
return /* @__PURE__ */ (0, import_jsx_runtime383.jsx)(
import_components170.MenuItem,
{
icon: upload_default,
onClick: () => {
openFileDialog();
},
children: (0, import_i18n161._x)("Upload", "verb")
}
);
}
}
)
] }),
onToggleFeaturedImage && /* @__PURE__ */ (0, import_jsx_runtime383.jsx)(
import_components170.MenuItem,
{
icon: post_featured_image_default,
onClick: onToggleFeaturedImage,
isPressed: useFeaturedImage,
children: (0, import_i18n161.__)("Use featured image")
}
),
typeof children === "function" ? children({ onClose }) : children,
mediaURL && onReset && /* @__PURE__ */ (0, import_jsx_runtime383.jsx)(
import_components170.MenuItem,
{
onClick: () => {
onReset();
onClose();
},
children: (0, import_i18n161.__)("Reset")
}
)
] }),
onSelectURL && /* @__PURE__ */ (0, import_jsx_runtime383.jsxs)("form", { className: "block-editor-media-flow__url-input", children: [
/* @__PURE__ */ (0, import_jsx_runtime383.jsx)("span", { className: "block-editor-media-replace-flow__image-url-label", children: (0, import_i18n161.__)("Current media URL:") }),
/* @__PURE__ */ (0, import_jsx_runtime383.jsx)(
link_control_default,
{
value: { url: mediaURL },
settings: [],
showSuggestions: false,
onChange: ({ url }) => {
onSelectURL(url);
},
searchInputPlaceholder: (0, import_i18n161.__)(
"Paste or type URL"
)
}
)
] })
] })
}
);
};
var media_replace_flow_default = (0, import_compose87.compose)([
(0, import_data149.withDispatch)((dispatch) => {
const { createNotice, removeNotice } = dispatch(import_notices11.store);
return {
createNotice,
removeNotice
};
}),
(0, import_components170.withFilters)("editor.MediaReplaceFlow")
])(MediaReplaceFlow);
// packages/block-editor/build-module/components/media-placeholder/index.mjs
var import_components176 = __toESM(require_components(), 1);
var import_i18n166 = __toESM(require_i18n(), 1);
var import_element226 = __toESM(require_element(), 1);
var import_data151 = __toESM(require_data(), 1);
var import_deprecated23 = __toESM(require_deprecated(), 1);
// packages/block-editor/build-module/components/url-popover/index.mjs
var import_i18n165 = __toESM(require_i18n(), 1);
var import_element225 = __toESM(require_element(), 1);
var import_components175 = __toESM(require_components(), 1);
var import_deprecated22 = __toESM(require_deprecated(), 1);
// packages/block-editor/build-module/components/url-popover/link-viewer.mjs
var import_i18n162 = __toESM(require_i18n(), 1);
var import_components172 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/url-popover/link-viewer-url.mjs
var import_components171 = __toESM(require_components(), 1);
var import_url7 = __toESM(require_url(), 1);
var import_jsx_runtime384 = __toESM(require_jsx_runtime(), 1);
function LinkViewerURL({ url, urlLabel, className }) {
const linkClassName = clsx_default(
className,
"block-editor-url-popover__link-viewer-url"
);
if (!url) {
return /* @__PURE__ */ (0, import_jsx_runtime384.jsx)("span", { className: linkClassName });
}
return /* @__PURE__ */ (0, import_jsx_runtime384.jsx)(import_components171.ExternalLink, { className: linkClassName, href: url, children: urlLabel || (0, import_url7.filterURLForDisplay)((0, import_url7.safeDecodeURI)(url)) });
}
// packages/block-editor/build-module/components/url-popover/link-viewer.mjs
var import_jsx_runtime385 = __toESM(require_jsx_runtime(), 1);
function LinkViewer({
className,
linkClassName,
onEditLinkClick,
url,
urlLabel,
...props
}) {
return /* @__PURE__ */ (0, import_jsx_runtime385.jsxs)(
"div",
{
className: clsx_default(
"block-editor-url-popover__link-viewer",
className
),
...props,
children: [
/* @__PURE__ */ (0, import_jsx_runtime385.jsx)(
LinkViewerURL,
{
url,
urlLabel,
className: linkClassName
}
),
onEditLinkClick && /* @__PURE__ */ (0, import_jsx_runtime385.jsx)(
import_components172.Button,
{
icon: pencil_default,
label: (0, import_i18n162.__)("Edit"),
onClick: onEditLinkClick,
size: "compact"
}
)
]
}
);
}
// packages/block-editor/build-module/components/url-popover/link-editor.mjs
var import_i18n164 = __toESM(require_i18n(), 1);
var import_components174 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/url-input/index.mjs
var import_i18n163 = __toESM(require_i18n(), 1);
var import_element224 = __toESM(require_element(), 1);
var import_keycodes21 = __toESM(require_keycodes(), 1);
var import_components173 = __toESM(require_components(), 1);
var import_compose88 = __toESM(require_compose(), 1);
var import_data150 = __toESM(require_data(), 1);
var import_url8 = __toESM(require_url(), 1);
var import_jsx_runtime386 = __toESM(require_jsx_runtime(), 1);
var import_react15 = __toESM(require_react(), 1);
var { ValidatedInputControl } = unlock(import_components173.privateApis);
function isFunction(maybeFunc) {
return typeof maybeFunc === "function";
}
var URLInput = class extends import_element224.Component {
constructor(props) {
super(props);
this.onChange = this.onChange.bind(this);
this.onFocus = this.onFocus.bind(this);
this.onKeyDown = this.onKeyDown.bind(this);
this.selectLink = this.selectLink.bind(this);
this.handleOnClick = this.handleOnClick.bind(this);
this.bindSuggestionNode = this.bindSuggestionNode.bind(this);
this.autocompleteRef = props.autocompleteRef || (0, import_element224.createRef)();
this.inputRef = props.inputRef || (0, import_element224.createRef)();
this.hasRenderedValidation = { current: false };
this.updateSuggestions = (0, import_compose88.debounce)(
this.updateSuggestions.bind(this),
200
);
this.suggestionNodes = [];
this.suggestionsRequest = null;
this.state = {
suggestions: [],
showSuggestions: false,
suggestionsValue: null,
selectedSuggestion: null,
suggestionsListboxId: "",
suggestionOptionIdPrefix: ""
};
}
componentDidUpdate(prevProps) {
const { showSuggestions, selectedSuggestion } = this.state;
const { value, __experimentalShowInitialSuggestions = false } = this.props;
if (showSuggestions && selectedSuggestion !== null && this.suggestionNodes[selectedSuggestion]) {
this.suggestionNodes[selectedSuggestion].scrollIntoView({
behavior: "instant",
block: "nearest",
inline: "nearest"
});
}
if (prevProps.value !== value && !this.props.disableSuggestions) {
if (value?.length) {
this.updateSuggestions(value);
} else if (__experimentalShowInitialSuggestions) {
this.updateSuggestions();
}
}
}
componentDidMount() {
if (this.shouldShowInitialSuggestions()) {
this.updateSuggestions();
}
}
componentWillUnmount() {
this.suggestionsRequest?.cancel?.();
this.suggestionsRequest = null;
}
bindSuggestionNode(index2) {
return (ref) => {
this.suggestionNodes[index2] = ref;
};
}
shouldShowInitialSuggestions() {
const { __experimentalShowInitialSuggestions = false, value } = this.props;
return __experimentalShowInitialSuggestions && !(value && value.length);
}
updateSuggestions(value = "") {
const {
__experimentalFetchLinkSuggestions: fetchLinkSuggestions,
__experimentalHandleURLSuggestions: handleURLSuggestions
} = this.props;
if (!fetchLinkSuggestions) {
return;
}
const isInitialSuggestions = !value?.length;
value = value.trim();
if (!isInitialSuggestions && (value.length < 2 || !handleURLSuggestions && (0, import_url8.isURL)(value))) {
this.suggestionsRequest?.cancel?.();
this.suggestionsRequest = null;
this.setState({
suggestions: [],
showSuggestions: false,
suggestionsValue: value,
selectedSuggestion: null,
loading: false
});
return;
}
this.setState({
selectedSuggestion: null,
loading: true
});
const request = fetchLinkSuggestions(value, {
isInitialSuggestions
});
request.then((suggestions) => {
if (this.suggestionsRequest !== request) {
return;
}
this.setState({
suggestions,
suggestionsValue: value,
loading: false,
showSuggestions: !!suggestions.length
});
if (!!suggestions.length) {
this.props.debouncedSpeak(
(0, import_i18n163.sprintf)(
/* translators: %d: number of results. */
(0, import_i18n163._n)(
"%d result found, use up and down arrow keys to navigate.",
"%d results found, use up and down arrow keys to navigate.",
suggestions.length
),
suggestions.length
),
"assertive"
);
} else {
this.props.debouncedSpeak(
(0, import_i18n163.__)("No results."),
"assertive"
);
}
}).catch(() => {
if (this.suggestionsRequest !== request) {
return;
}
this.setState({
loading: false
});
}).finally(() => {
if (this.suggestionsRequest === request) {
this.suggestionsRequest = null;
}
});
this.suggestionsRequest = request;
}
onChange(newValue) {
this.props.onChange(newValue);
}
onFocus() {
const { suggestions } = this.state;
const { disableSuggestions, value } = this.props;
if (value && !disableSuggestions && !(suggestions && suggestions.length) && this.suggestionsRequest === null) {
this.updateSuggestions(value);
}
}
onKeyDown(event) {
this.props.onKeyDown?.(event);
const { showSuggestions, selectedSuggestion, suggestions, loading } = this.state;
if (!showSuggestions || !suggestions.length || loading) {
switch (event.keyCode) {
// When UP is pressed, if the caret is at the start of the text, move it to the 0
// position.
case import_keycodes21.UP: {
if (0 !== event.target.selectionStart) {
event.preventDefault();
event.target.setSelectionRange(0, 0);
}
break;
}
// When DOWN is pressed, if the caret is not at the end of the text, move it to the
// last position.
case import_keycodes21.DOWN: {
if (this.props.value.length !== event.target.selectionStart) {
event.preventDefault();
event.target.setSelectionRange(
this.props.value.length,
this.props.value.length
);
}
break;
}
// Submitting while loading should trigger onSubmit.
case import_keycodes21.ENTER: {
if (this.props.onSubmit) {
event.preventDefault();
this.props.onSubmit(null, event);
}
break;
}
}
return;
}
const suggestion = this.state.suggestions[this.state.selectedSuggestion];
switch (event.keyCode) {
case import_keycodes21.UP: {
event.preventDefault();
const previousIndex = !selectedSuggestion ? suggestions.length - 1 : selectedSuggestion - 1;
this.setState({
selectedSuggestion: previousIndex
});
break;
}
case import_keycodes21.DOWN: {
event.preventDefault();
const nextIndex = selectedSuggestion === null || selectedSuggestion === suggestions.length - 1 ? 0 : selectedSuggestion + 1;
this.setState({
selectedSuggestion: nextIndex
});
break;
}
case import_keycodes21.TAB: {
if (this.state.selectedSuggestion !== null) {
this.selectLink(suggestion);
this.props.speak((0, import_i18n163.__)("Link selected."));
}
break;
}
case import_keycodes21.ENTER: {
event.preventDefault();
if (this.state.selectedSuggestion !== null) {
this.selectLink(suggestion);
if (this.props.onSubmit) {
this.props.onSubmit(suggestion, event);
}
} else if (this.props.onSubmit) {
this.props.onSubmit(null, event);
}
break;
}
}
}
selectLink(suggestion) {
this.props.onChange(suggestion.url, suggestion);
this.setState({
selectedSuggestion: null,
showSuggestions: false
});
}
handleOnClick(suggestion) {
this.selectLink(suggestion);
this.inputRef.current.focus();
}
static getDerivedStateFromProps({
value,
instanceId,
disableSuggestions,
__experimentalShowInitialSuggestions = false
}, { showSuggestions }) {
let shouldShowSuggestions = showSuggestions;
const hasValue = value && value.length;
if (!__experimentalShowInitialSuggestions && !hasValue) {
shouldShowSuggestions = false;
}
if (disableSuggestions === true) {
shouldShowSuggestions = false;
}
return {
showSuggestions: shouldShowSuggestions,
suggestionsListboxId: `block-editor-url-input-suggestions-${instanceId}`,
suggestionOptionIdPrefix: `block-editor-url-input-suggestion-${instanceId}`
};
}
render() {
return /* @__PURE__ */ (0, import_jsx_runtime386.jsxs)(import_jsx_runtime386.Fragment, { children: [
this.renderControl(),
this.renderSuggestions()
] });
}
renderControl() {
const {
label = null,
className,
isFullWidth,
instanceId,
placeholder = (0, import_i18n163.__)("Paste URL or type to search"),
__experimentalRenderControl: renderControl,
value = "",
hideLabelFromVision = false,
help = null,
disabled: disabled2 = false,
customValidity,
markWhenOptional
} = this.props;
const {
loading,
showSuggestions,
selectedSuggestion,
suggestionsListboxId,
suggestionOptionIdPrefix
} = this.state;
const inputId = `url-input-control-${instanceId}`;
const controlProps = {
id: inputId,
// Passes attribute to label for the for attribute
label,
className: clsx_default("block-editor-url-input", className, {
"is-full-width": isFullWidth
}),
hideLabelFromVision
};
const inputProps = {
id: inputId,
value,
required: this.props.required ?? true,
type: "text",
name: inputId,
autoComplete: "off",
onChange: disabled2 ? () => {
} : this.onChange,
// Disable onChange when disabled
onFocus: disabled2 ? () => {
} : this.onFocus,
// Disable onFocus when disabled
placeholder,
onKeyDown: disabled2 ? () => {
} : this.onKeyDown,
// Disable onKeyDown when disabled
role: "combobox",
"aria-label": label ? void 0 : (0, import_i18n163.__)("URL"),
// Ensure input always has an accessible label
"aria-expanded": showSuggestions,
"aria-autocomplete": "list",
"aria-owns": suggestionsListboxId,
"aria-activedescendant": selectedSuggestion !== null ? `${suggestionOptionIdPrefix}-${selectedSuggestion}` : void 0,
ref: this.inputRef,
disabled: disabled2,
suffix: this.props.suffix,
help
};
const validationProps = {
customValidity,
// Suppress the "(Required)" indicator in the label.
// The field is still required for validation, but the indicator
// can be hidden when markWhenOptional is set to true.
...markWhenOptional !== void 0 && {
markWhenOptional
}
};
if (renderControl) {
return renderControl(controlProps, inputProps, loading);
}
if (customValidity !== void 0) {
this.hasRenderedValidation.current = true;
}
const MaybeValidatedInputControl = this.hasRenderedValidation.current ? ValidatedInputControl : import_components173.__experimentalInputControl;
return /* @__PURE__ */ (0, import_jsx_runtime386.jsxs)(import_components173.BaseControl, { ...controlProps, children: [
/* @__PURE__ */ (0, import_jsx_runtime386.jsx)(
MaybeValidatedInputControl,
{
...inputProps,
...this.hasRenderedValidation.current ? validationProps : {},
__next40pxDefaultSize: true
}
),
loading && /* @__PURE__ */ (0, import_jsx_runtime386.jsx)(import_components173.Spinner, {})
] });
}
renderSuggestions() {
const {
className,
__experimentalRenderSuggestions: renderSuggestions
} = this.props;
const {
showSuggestions,
suggestions,
suggestionsValue,
selectedSuggestion,
suggestionsListboxId,
suggestionOptionIdPrefix,
loading
} = this.state;
if (!showSuggestions || suggestions.length === 0) {
return null;
}
const suggestionsListProps = {
id: suggestionsListboxId,
ref: this.autocompleteRef,
role: "listbox"
};
const buildSuggestionItemProps = (suggestion, index2) => {
return {
role: "option",
tabIndex: "-1",
id: `${suggestionOptionIdPrefix}-${index2}`,
ref: this.bindSuggestionNode(index2),
"aria-selected": index2 === selectedSuggestion ? true : void 0
};
};
if (isFunction(renderSuggestions)) {
return renderSuggestions({
suggestions,
selectedSuggestion,
suggestionsListProps,
buildSuggestionItemProps,
isLoading: loading,
handleSuggestionClick: this.handleOnClick,
isInitialSuggestions: !suggestionsValue?.length,
currentInputValue: suggestionsValue
});
}
return /* @__PURE__ */ (0, import_jsx_runtime386.jsx)(import_components173.Popover, { placement: "bottom", focusOnMount: false, children: /* @__PURE__ */ (0, import_jsx_runtime386.jsx)(
"div",
{
...suggestionsListProps,
className: clsx_default("block-editor-url-input__suggestions", {
[`${className}__suggestions`]: className
}),
children: suggestions.map((suggestion, index2) => /* @__PURE__ */ (0, import_react15.createElement)(
import_components173.Button,
{
__next40pxDefaultSize: true,
...buildSuggestionItemProps(suggestion, index2),
key: suggestion.id,
className: clsx_default(
"block-editor-url-input__suggestion",
{
"is-selected": index2 === selectedSuggestion
}
),
onClick: () => this.handleOnClick(suggestion)
},
suggestion.title
))
}
) });
}
};
var url_input_default = (0, import_compose88.compose)(
import_compose88.withSafeTimeout,
import_components173.withSpokenMessages,
import_compose88.withInstanceId,
(0, import_data150.withSelect)((select3, props) => {
if (isFunction(props.__experimentalFetchLinkSuggestions)) {
return;
}
const { getSettings: getSettings7 } = select3(store);
return {
__experimentalFetchLinkSuggestions: getSettings7().__experimentalFetchLinkSuggestions
};
})
)(URLInput);
// packages/block-editor/build-module/components/url-popover/link-editor.mjs
var import_jsx_runtime387 = __toESM(require_jsx_runtime(), 1);
function LinkEditor({
autocompleteRef,
className,
onChangeInputValue,
value,
...props
}) {
return /* @__PURE__ */ (0, import_jsx_runtime387.jsxs)(
"form",
{
className: clsx_default(
"block-editor-url-popover__link-editor",
className
),
...props,
children: [
/* @__PURE__ */ (0, import_jsx_runtime387.jsx)(
url_input_default,
{
value,
onChange: onChangeInputValue,
autocompleteRef
}
),
/* @__PURE__ */ (0, import_jsx_runtime387.jsx)(
import_components174.Button,
{
icon: keyboard_return_default,
label: (0, import_i18n164.__)("Apply"),
type: "submit",
size: "compact"
}
)
]
}
);
}
// packages/block-editor/build-module/components/url-popover/index.mjs
var import_jsx_runtime388 = __toESM(require_jsx_runtime(), 1);
var { __experimentalPopoverLegacyPositionToPlacement } = unlock(
import_components175.privateApis
);
var DEFAULT_PLACEMENT = "bottom";
var URLPopover = (0, import_element225.forwardRef)(
({
additionalControls,
children,
renderSettings,
// The DEFAULT_PLACEMENT value is assigned inside the function's body
placement,
focusOnMount = "firstElement",
// Deprecated
position,
// Rest
...popoverProps3
}, ref) => {
if (position !== void 0) {
(0, import_deprecated22.default)("`position` prop in wp.blockEditor.URLPopover", {
since: "6.2",
alternative: "`placement` prop"
});
}
let computedPlacement;
if (placement !== void 0) {
computedPlacement = placement;
} else if (position !== void 0) {
computedPlacement = __experimentalPopoverLegacyPositionToPlacement(position);
}
computedPlacement = computedPlacement || DEFAULT_PLACEMENT;
const [isSettingsExpanded, setIsSettingsExpanded] = (0, import_element225.useState)(false);
const showSettings = !!renderSettings && isSettingsExpanded;
const toggleSettingsVisibility = () => {
setIsSettingsExpanded(!isSettingsExpanded);
};
return /* @__PURE__ */ (0, import_jsx_runtime388.jsxs)(
import_components175.Popover,
{
ref,
role: "dialog",
"aria-modal": "true",
"aria-label": (0, import_i18n165.__)("Edit URL"),
className: "block-editor-url-popover",
focusOnMount,
placement: computedPlacement,
shift: true,
variant: "toolbar",
...popoverProps3,
children: [
/* @__PURE__ */ (0, import_jsx_runtime388.jsx)("div", { className: "block-editor-url-popover__input-container", children: /* @__PURE__ */ (0, import_jsx_runtime388.jsxs)("div", { className: "block-editor-url-popover__row", children: [
children,
!!renderSettings && /* @__PURE__ */ (0, import_jsx_runtime388.jsx)(
import_components175.Button,
{
className: "block-editor-url-popover__settings-toggle",
icon: chevron_down_default,
label: (0, import_i18n165.__)("Link settings"),
onClick: toggleSettingsVisibility,
"aria-expanded": isSettingsExpanded,
size: "compact"
}
)
] }) }),
showSettings && /* @__PURE__ */ (0, import_jsx_runtime388.jsx)("div", { className: "block-editor-url-popover__settings", children: renderSettings() }),
additionalControls && !showSettings && /* @__PURE__ */ (0, import_jsx_runtime388.jsx)("div", { className: "block-editor-url-popover__additional-controls", children: additionalControls })
]
}
);
}
);
URLPopover.LinkEditor = LinkEditor;
URLPopover.LinkViewer = LinkViewer;
var url_popover_default = URLPopover;
// packages/block-editor/build-module/components/media-placeholder/index.mjs
var import_jsx_runtime389 = __toESM(require_jsx_runtime(), 1);
var noop20 = () => {
};
var InsertFromURLPopover = ({
src,
onChange,
onSubmit,
onClose,
popoverAnchor
}) => /* @__PURE__ */ (0, import_jsx_runtime389.jsx)(url_popover_default, { anchor: popoverAnchor, onClose, children: /* @__PURE__ */ (0, import_jsx_runtime389.jsx)(
"form",
{
className: "block-editor-media-placeholder__url-input-form",
onSubmit,
children: /* @__PURE__ */ (0, import_jsx_runtime389.jsx)(
import_components176.__experimentalInputControl,
{
label: (0, import_i18n166.__)("URL"),
type: "text",
hideLabelFromVision: true,
placeholder: (0, import_i18n166.__)("Paste or type URL"),
onChange,
value: src,
suffix: /* @__PURE__ */ (0, import_jsx_runtime389.jsx)(import_components176.__experimentalInputControlSuffixWrapper, { variant: "control", children: /* @__PURE__ */ (0, import_jsx_runtime389.jsx)(
import_components176.Button,
{
size: "small",
icon: keyboard_return_default,
label: (0, import_i18n166.__)("Apply"),
type: "submit"
}
) })
}
)
}
) });
var URLSelectionUI = ({ src, onChangeSrc, onSelectURL }) => {
const [popoverAnchor, setPopoverAnchor] = (0, import_element226.useState)(null);
const [isURLInputVisible, setIsURLInputVisible] = (0, import_element226.useState)(false);
const openURLInput = () => {
setIsURLInputVisible(true);
};
const closeURLInput = () => {
setIsURLInputVisible(false);
popoverAnchor?.focus();
};
const onSubmitSrc = (event) => {
event.preventDefault();
if (src && onSelectURL) {
onSelectURL(src);
closeURLInput();
}
};
return /* @__PURE__ */ (0, import_jsx_runtime389.jsxs)("div", { className: "block-editor-media-placeholder__url-input-container", children: [
/* @__PURE__ */ (0, import_jsx_runtime389.jsx)(
import_components176.Button,
{
__next40pxDefaultSize: true,
className: "block-editor-media-placeholder__button",
onClick: openURLInput,
isPressed: isURLInputVisible,
variant: "secondary",
"aria-haspopup": "dialog",
ref: setPopoverAnchor,
children: (0, import_i18n166.__)("Insert from URL")
}
),
isURLInputVisible && /* @__PURE__ */ (0, import_jsx_runtime389.jsx)(
InsertFromURLPopover,
{
src,
onChange: onChangeSrc,
onSubmit: onSubmitSrc,
onClose: closeURLInput,
popoverAnchor
}
)
] });
};
function MediaPlaceholder({
value = {},
allowedTypes,
className,
icon,
labels = {},
mediaPreview,
notices,
isAppender,
accept,
addToGallery,
multiple = false,
handleUpload = true,
disableDropZone,
disableMediaButtons,
onError,
onSelect,
onCancel,
onSelectURL,
onToggleFeaturedImage,
onDoubleClick,
onFilesPreUpload = noop20,
onHTMLDrop: deprecatedOnHTMLDrop,
children,
mediaLibraryButton,
placeholder,
style
}) {
if (deprecatedOnHTMLDrop) {
(0, import_deprecated23.default)("wp.blockEditor.MediaPlaceholder onHTMLDrop prop", {
since: "6.2",
version: "6.4"
});
}
const { mediaUpload: mediaUpload2, allowedMimeTypes } = (0, import_data151.useSelect)((select3) => {
const { getSettings: getSettings7 } = select3(store);
const settings2 = getSettings7();
return {
mediaUpload: settings2.mediaUpload,
allowedMimeTypes: settings2.allowedMimeTypes
};
}, []);
const [src, setSrc] = (0, import_element226.useState)("");
(0, import_element226.useEffect)(() => {
setSrc(value?.src ?? "");
}, [value?.src]);
const computedAccept = (0, import_element226.useMemo)(
() => getComputedAcceptAttribute(
allowedTypes,
allowedMimeTypes,
accept
),
[allowedTypes, allowedMimeTypes, accept]
);
const onlyAllowsImages = () => {
if (!allowedTypes || allowedTypes.length === 0) {
return false;
}
return allowedTypes.every(
(allowedType) => allowedType === "image" || allowedType.startsWith("image/")
);
};
const onFilesUpload = (files) => {
if (!handleUpload || typeof handleUpload === "function" && !handleUpload(files)) {
return onSelect(files);
}
onFilesPreUpload(files);
let setMedia;
if (multiple) {
if (addToGallery) {
let lastMediaPassed = [];
setMedia = (newMedia) => {
const filteredMedia = (value ?? []).filter((item) => {
if (item.id) {
return !lastMediaPassed.some(
// Be sure to convert to number for comparison.
({ id }) => Number(id) === Number(item.id)
);
}
return !lastMediaPassed.some(
({ urlSlug }) => item.url.includes(urlSlug)
);
});
onSelect(filteredMedia.concat(newMedia));
lastMediaPassed = newMedia.map((media) => {
const cutOffIndex = media.url.lastIndexOf(".");
const urlSlug = media.url.slice(0, cutOffIndex);
return { id: media.id, urlSlug };
});
};
} else {
setMedia = onSelect;
}
} else {
setMedia = ([media]) => onSelect(media);
}
mediaUpload2({
allowedTypes,
filesList: files,
onFileChange: setMedia,
onError,
multiple
});
};
async function handleBlocksDrop(event) {
const { blocks: blocks2 } = parseDropEvent(event);
if (!blocks2?.length) {
return;
}
const uploadedMediaList = await Promise.all(
blocks2.map((block) => {
const blockType = block.name.split("/")[1];
if (block.attributes.id) {
block.attributes.type = blockType;
return block.attributes;
}
return new Promise((resolve, reject) => {
window.fetch(block.attributes.url).then((response) => response.blob()).then(
(blob) => mediaUpload2({
filesList: [blob],
additionalData: {
title: block.attributes.title,
alt_text: block.attributes.alt,
caption: block.attributes.caption,
type: blockType
},
onFileChange: ([media]) => {
if (media.id) {
resolve(media);
}
},
allowedTypes,
onError: reject
})
).catch(() => resolve(block.attributes.url));
});
})
).catch((err) => onError(err));
if (!uploadedMediaList?.length) {
return;
}
onSelect(multiple ? uploadedMediaList : uploadedMediaList[0]);
}
const onUpload = (event) => {
onFilesUpload(event.target.files);
};
const defaultRenderPlaceholder = (content) => {
let { instructions, title } = labels;
if (!mediaUpload2 && !onSelectURL) {
instructions = (0, import_i18n166.__)(
"To edit this block, you need permission to upload media."
);
}
if (instructions === void 0 || title === void 0) {
const typesAllowed = allowedTypes ?? [];
const [firstAllowedType] = typesAllowed;
const isOneType = 1 === typesAllowed.length;
const isAudio = isOneType && "audio" === firstAllowedType;
const isImage = isOneType && "image" === firstAllowedType;
const isVideo = isOneType && "video" === firstAllowedType;
if (instructions === void 0 && mediaUpload2) {
instructions = (0, import_i18n166.__)(
"Drag and drop an image or video, upload, or choose from your library."
);
if (isAudio) {
instructions = (0, import_i18n166.__)(
"Drag and drop an audio file, upload, or choose from your library."
);
} else if (isImage) {
instructions = (0, import_i18n166.__)(
"Drag and drop an image, upload, or choose from your library."
);
} else if (isVideo) {
instructions = (0, import_i18n166.__)(
"Drag and drop a video, upload, or choose from your library."
);
}
}
if (title === void 0) {
title = (0, import_i18n166.__)("Media");
if (isAudio) {
title = (0, import_i18n166.__)("Audio");
} else if (isImage) {
title = (0, import_i18n166.__)("Image");
} else if (isVideo) {
title = (0, import_i18n166.__)("Video");
}
}
}
const placeholderClassName = clsx_default(
"block-editor-media-placeholder",
className,
{
"is-appender": isAppender
}
);
return /* @__PURE__ */ (0, import_jsx_runtime389.jsxs)(
import_components176.Placeholder,
{
icon,
label: title,
instructions,
className: placeholderClassName,
notices,
onDoubleClick,
preview: mediaPreview,
style,
children: [
content,
children
]
}
);
};
const renderPlaceholder = placeholder ?? defaultRenderPlaceholder;
const renderDropZone = () => {
if (disableDropZone) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime389.jsx)(
import_components176.DropZone,
{
onFilesDrop: onFilesUpload,
onDrop: handleBlocksDrop,
isEligible: (dataTransfer) => {
const prefix2 = "wp-block:core/";
const types = [];
for (const type of dataTransfer.types) {
if (type.startsWith(prefix2)) {
types.push(type.slice(prefix2.length));
}
}
return types.every(
(type) => allowedTypes.includes(type)
) && (multiple ? true : types.length === 1);
}
}
);
};
const renderCancelLink = () => {
return onCancel && /* @__PURE__ */ (0, import_jsx_runtime389.jsx)(
import_components176.Button,
{
__next40pxDefaultSize: true,
className: "block-editor-media-placeholder__cancel-button",
title: (0, import_i18n166.__)("Cancel"),
variant: "link",
onClick: onCancel,
children: (0, import_i18n166.__)("Cancel")
}
);
};
const renderUrlSelectionUI = () => {
return onSelectURL && /* @__PURE__ */ (0, import_jsx_runtime389.jsx)(
URLSelectionUI,
{
src,
onChangeSrc: setSrc,
onSelectURL
}
);
};
const renderFeaturedImageToggle = () => {
return onToggleFeaturedImage && /* @__PURE__ */ (0, import_jsx_runtime389.jsx)("div", { className: "block-editor-media-placeholder__url-input-container", children: /* @__PURE__ */ (0, import_jsx_runtime389.jsx)(
import_components176.Button,
{
__next40pxDefaultSize: true,
className: "block-editor-media-placeholder__button",
onClick: onToggleFeaturedImage,
variant: "secondary",
children: (0, import_i18n166.__)("Use featured image")
}
) });
};
const renderMediaUploadChecked = () => {
const defaultButton = ({ open }) => {
return /* @__PURE__ */ (0, import_jsx_runtime389.jsx)(
import_components176.Button,
{
__next40pxDefaultSize: true,
variant: "secondary",
onClick: () => {
open();
},
children: (0, import_i18n166.__)("Media Library")
}
);
};
const libraryButton = mediaLibraryButton ?? defaultButton;
const uploadMediaLibraryButton = /* @__PURE__ */ (0, import_jsx_runtime389.jsx)(
media_upload_default,
{
addToGallery,
gallery: multiple && onlyAllowsImages(),
multiple,
onSelect,
allowedTypes,
mode: "browse",
value: Array.isArray(value) ? value.map(({ id }) => id) : value.id,
render: libraryButton
}
);
if (mediaUpload2 && isAppender) {
return /* @__PURE__ */ (0, import_jsx_runtime389.jsxs)(import_jsx_runtime389.Fragment, { children: [
renderDropZone(),
/* @__PURE__ */ (0, import_jsx_runtime389.jsx)(
import_components176.FormFileUpload,
{
onChange: onUpload,
accept: computedAccept,
multiple: !!multiple,
render: ({ openFileDialog }) => {
const content = /* @__PURE__ */ (0, import_jsx_runtime389.jsxs)(import_jsx_runtime389.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime389.jsx)(
import_components176.Button,
{
__next40pxDefaultSize: true,
variant: "primary",
className: clsx_default(
"block-editor-media-placeholder__button",
"block-editor-media-placeholder__upload-button"
),
onClick: openFileDialog,
children: (0, import_i18n166._x)("Upload", "verb")
}
),
uploadMediaLibraryButton,
renderUrlSelectionUI(),
renderFeaturedImageToggle(),
renderCancelLink()
] });
return renderPlaceholder(content);
}
}
)
] });
}
if (mediaUpload2) {
const content = /* @__PURE__ */ (0, import_jsx_runtime389.jsxs)(import_jsx_runtime389.Fragment, { children: [
renderDropZone(),
/* @__PURE__ */ (0, import_jsx_runtime389.jsx)(
import_components176.FormFileUpload,
{
render: ({ openFileDialog }) => /* @__PURE__ */ (0, import_jsx_runtime389.jsx)(
import_components176.Button,
{
__next40pxDefaultSize: true,
onClick: openFileDialog,
variant: "primary",
className: clsx_default(
"block-editor-media-placeholder__button",
"block-editor-media-placeholder__upload-button"
),
children: (0, import_i18n166._x)("Upload", "verb")
}
),
onChange: onUpload,
accept: computedAccept,
multiple: !!multiple
}
),
uploadMediaLibraryButton,
renderUrlSelectionUI(),
renderFeaturedImageToggle(),
renderCancelLink()
] });
return renderPlaceholder(content);
}
return renderPlaceholder(uploadMediaLibraryButton);
};
if (disableMediaButtons) {
return /* @__PURE__ */ (0, import_jsx_runtime389.jsx)(check_default2, { children: renderDropZone() });
}
return /* @__PURE__ */ (0, import_jsx_runtime389.jsx)(
check_default2,
{
fallback: renderPlaceholder(renderUrlSelectionUI()),
children: renderMediaUploadChecked()
}
);
}
var media_placeholder_default = (0, import_components176.withFilters)("editor.MediaPlaceholder")(MediaPlaceholder);
// packages/block-editor/build-module/components/panel-color-settings/index.mjs
var import_jsx_runtime390 = __toESM(require_jsx_runtime(), 1);
var PanelColorSettings = ({ colorSettings, ...props }) => {
const settings2 = colorSettings.map((setting) => {
if (!setting) {
return setting;
}
const { value, onChange, ...otherSettings } = setting;
return {
...otherSettings,
colorValue: value,
onColorChange: onChange
};
});
return /* @__PURE__ */ (0, import_jsx_runtime390.jsx)(
panel_color_gradient_settings_default,
{
settings: settings2,
gradients: [],
disableCustomGradients: true,
...props
}
);
};
var panel_color_settings_default = PanelColorSettings;
// packages/block-editor/build-module/components/plain-text/index.mjs
var import_react_autosize_textarea2 = __toESM(require_lib(), 1);
var import_element236 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/editable-text/index.mjs
var import_element235 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/rich-text/index.mjs
var import_es65 = __toESM(require_es6(), 1);
var import_element234 = __toESM(require_element(), 1);
var import_data154 = __toESM(require_data(), 1);
var import_compose92 = __toESM(require_compose(), 1);
var import_rich_text19 = __toESM(require_rich_text(), 1);
var import_components180 = __toESM(require_components(), 1);
var import_blocks88 = __toESM(require_blocks(), 1);
var import_deprecated27 = __toESM(require_deprecated(), 1);
var import_i18n169 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/rich-text/format-toolbar-container.mjs
var import_i18n168 = __toESM(require_i18n(), 1);
var import_components178 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/rich-text/format-toolbar/index.mjs
var import_i18n167 = __toESM(require_i18n(), 1);
var import_components177 = __toESM(require_components(), 1);
var import_jsx_runtime391 = __toESM(require_jsx_runtime(), 1);
var POPOVER_PROPS8 = {
placement: "bottom-start"
};
var FormatToolbar = () => {
return /* @__PURE__ */ (0, import_jsx_runtime391.jsxs)(import_jsx_runtime391.Fragment, { children: [
["bold", "italic", "link", "unknown"].map((format6) => /* @__PURE__ */ (0, import_jsx_runtime391.jsx)(
import_components177.Slot,
{
name: `RichText.ToolbarControls.${format6}`
},
format6
)),
/* @__PURE__ */ (0, import_jsx_runtime391.jsx)(import_components177.Slot, { name: "RichText.ToolbarControls", children: (fills) => {
if (!fills.length) {
return null;
}
const allProps = fills.map(([{ props }]) => props);
const hasActive = allProps.some(
({ isActive }) => isActive
);
return /* @__PURE__ */ (0, import_jsx_runtime391.jsx)(import_components177.ToolbarItem, { children: (toggleProps) => /* @__PURE__ */ (0, import_jsx_runtime391.jsx)(
import_components177.DropdownMenu,
{
icon: chevron_down_default,
label: (0, import_i18n167.__)("More"),
toggleProps: {
...toggleProps,
className: clsx_default(
toggleProps.className,
{ "is-pressed": hasActive }
),
description: (0, import_i18n167.__)(
"Displays more block tools"
)
},
controls: orderBy(
fills.map(([{ props }]) => props),
"title"
),
popoverProps: POPOVER_PROPS8
}
) });
} })
] });
};
var format_toolbar_default = FormatToolbar;
// packages/block-editor/build-module/components/rich-text/format-toolbar-container.mjs
var import_jsx_runtime392 = __toESM(require_jsx_runtime(), 1);
function InlineToolbar({ popoverAnchor }) {
return /* @__PURE__ */ (0, import_jsx_runtime392.jsx)(
import_components178.Popover,
{
placement: "top",
focusOnMount: false,
anchor: popoverAnchor,
className: "block-editor-rich-text__inline-format-toolbar",
__unstableSlotName: "block-toolbar",
children: /* @__PURE__ */ (0, import_jsx_runtime392.jsx)(
NavigableToolbar,
{
className: "block-editor-rich-text__inline-format-toolbar-group",
"aria-label": (0, import_i18n168.__)("Format tools"),
children: /* @__PURE__ */ (0, import_jsx_runtime392.jsx)(import_components178.ToolbarGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime392.jsx)(format_toolbar_default, {}) })
}
)
}
);
}
var FormatToolbarContainer = ({ inline: inline4, editableContentElement }) => {
if (inline4) {
return /* @__PURE__ */ (0, import_jsx_runtime392.jsx)(InlineToolbar, { popoverAnchor: editableContentElement });
}
return /* @__PURE__ */ (0, import_jsx_runtime392.jsx)(block_controls_default, { group: "inline", children: /* @__PURE__ */ (0, import_jsx_runtime392.jsx)(format_toolbar_default, {}) });
};
var format_toolbar_container_default = FormatToolbarContainer;
// packages/block-editor/build-module/components/rich-text/use-mark-persistent.mjs
var import_element227 = __toESM(require_element(), 1);
var import_data152 = __toESM(require_data(), 1);
function useMarkPersistent({ html, value }) {
const previousTextRef = (0, import_element227.useRef)();
const hasActiveFormats = !!value.activeFormats?.length;
const { __unstableMarkLastChangeAsPersistent: __unstableMarkLastChangeAsPersistent2 } = (0, import_data152.useDispatch)(store);
(0, import_element227.useLayoutEffect)(() => {
if (!previousTextRef.current) {
previousTextRef.current = value.text;
return;
}
if (previousTextRef.current !== value.text) {
const timeout = window.setTimeout(() => {
__unstableMarkLastChangeAsPersistent2();
}, 1e3);
previousTextRef.current = value.text;
return () => {
window.clearTimeout(timeout);
};
}
__unstableMarkLastChangeAsPersistent2();
}, [html, hasActiveFormats]);
}
// packages/block-editor/build-module/components/rich-text/event-listeners/index.mjs
var import_element229 = __toESM(require_element(), 1);
var import_compose91 = __toESM(require_compose(), 1);
// packages/block-editor/build-module/components/rich-text/event-listeners/before-input-rules.mjs
var import_rich_text5 = __toESM(require_rich_text(), 1);
var import_hooks7 = __toESM(require_hooks(), 1);
var { subscribeOwnedListener } = unlock(import_rich_text5.privateApis);
var wrapSelectionSettings = ["`", '"', "'", "\u201C\u201D", "\u2018\u2019"];
var before_input_rules_default = (props) => (element) => {
function onInput(event) {
const { inputType, data } = event;
const { value, onChange, registry } = props.current;
if (inputType !== "insertText") {
return;
}
if ((0, import_rich_text5.isCollapsed)(value)) {
return;
}
const pair = (0, import_hooks7.applyFilters)(
"blockEditor.wrapSelectionSettings",
wrapSelectionSettings
).find(
([startChar2, endChar2]) => startChar2 === data || endChar2 === data
);
if (!pair) {
return;
}
const [startChar, endChar = startChar] = pair;
const start2 = value.start;
const end = value.end + startChar.length;
let newValue = (0, import_rich_text5.insert)(value, startChar, start2, start2);
newValue = (0, import_rich_text5.insert)(newValue, endChar, end, end);
const {
__unstableMarkLastChangeAsPersistent: __unstableMarkLastChangeAsPersistent2,
__unstableMarkAutomaticChange: __unstableMarkAutomaticChange2
} = registry.dispatch(store);
__unstableMarkLastChangeAsPersistent2();
onChange(newValue);
__unstableMarkAutomaticChange2();
const init = {};
for (const key in event) {
init[key] = event[key];
}
init.data = endChar;
const { ownerDocument: ownerDocument2 } = element;
const { defaultView } = ownerDocument2;
const newEvent = new defaultView.InputEvent("input", init);
window.queueMicrotask(() => {
element.dispatchEvent(newEvent);
});
event.preventDefault();
}
return subscribeOwnedListener(element, "beforeinput", onInput, true);
};
// packages/block-editor/build-module/components/rich-text/event-listeners/input-rules.mjs
var import_rich_text7 = __toESM(require_rich_text(), 1);
var import_blocks83 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/components/rich-text/prevent-event-discovery.mjs
var import_rich_text6 = __toESM(require_rich_text(), 1);
function preventEventDiscovery(value) {
const searchText = "tales of gutenberg";
const addText = " \u{1F421}\u{1F422}\u{1F980}\u{1F424}\u{1F98B}\u{1F418}\u{1F427}\u{1F439}\u{1F981}\u{1F984}\u{1F98D}\u{1F43C}\u{1F43F}\u{1F383}\u{1F434}\u{1F41D}\u{1F406}\u{1F995}\u{1F994}\u{1F331}\u{1F347}\u03C0\u{1F34C}\u{1F409}\u{1F4A7}\u{1F968}\u{1F30C}\u{1F342}\u{1F360}\u{1F966}\u{1F95A}\u{1F95D}\u{1F39F}\u{1F965}\u{1F952}\u{1F6F5}\u{1F956}\u{1F352}\u{1F36F}\u{1F3BE}\u{1F3B2}\u{1F43A}\u{1F41A}\u{1F42E}\u231B\uFE0F";
const { start: start2, text } = value;
if (start2 < searchText.length) {
return value;
}
const charactersBefore = text.slice(start2 - searchText.length, start2);
if (charactersBefore.toLowerCase() !== searchText) {
return value;
}
return (0, import_rich_text6.insert)(value, addText);
}
// packages/block-editor/build-module/components/rich-text/event-listeners/input-rules.mjs
var { subscribeOwnedListener: subscribeOwnedListener2 } = unlock(import_rich_text7.privateApis);
function findSelection(blocks2) {
let i2 = blocks2.length;
while (i2--) {
const attributeKey = retrieveSelectedAttribute(
blocks2[i2].attributes
);
if (attributeKey) {
blocks2[i2].attributes[attributeKey] = blocks2[i2].attributes[attributeKey].toString().replace(START_OF_SELECTED_AREA, "");
return [blocks2[i2].clientId, attributeKey, 0, 0];
}
const nestedSelection = findSelection(blocks2[i2].innerBlocks);
if (nestedSelection) {
return nestedSelection;
}
}
return [];
}
var input_rules_default = (props) => (element) => {
function inputRule() {
const { getValue, onReplace, selectionChange: selectionChange2, registry } = props.current;
if (!onReplace) {
return;
}
const value = getValue();
const { start: start2, text } = value;
const characterBefore = text.slice(start2 - 1, start2);
if (characterBefore !== " ") {
return;
}
const trimmedTextBefore = text.slice(0, start2).trim();
const prefixTransforms = (0, import_blocks83.getBlockTransforms)("from").filter(
({ type }) => type === "prefix"
);
const transformation = (0, import_blocks83.findTransform)(
prefixTransforms,
({ prefix: prefix2 }) => {
return trimmedTextBefore === prefix2;
}
);
if (!transformation) {
return;
}
const content = (0, import_rich_text7.toHTMLString)({
value: (0, import_rich_text7.insert)(value, START_OF_SELECTED_AREA, 0, start2)
});
const block = transformation.transform(content);
selectionChange2(...findSelection([block]));
onReplace([block]);
registry.dispatch(store).__unstableMarkAutomaticChange();
return true;
}
function onInput(event) {
const { inputType, type } = event;
const {
getValue,
onChange,
__unstableAllowPrefixTransformations,
formatTypes,
registry,
onReplace
} = props.current;
if (inputType !== "insertText" && type !== "compositionend") {
return;
}
if (__unstableAllowPrefixTransformations && inputRule()) {
return;
}
const value = getValue();
const transforms = (0, import_blocks83.getBlockTransforms)("from").filter(
(transform) => transform.type === "input"
);
const transformation = (0, import_blocks83.findTransform)(transforms, (item) => {
return item.regExp.test(value.text);
});
if (transformation) {
onReplace(transformation.transform());
registry.dispatch(store).__unstableMarkAutomaticChange();
return;
}
const transformed = formatTypes.reduce(
(accumulator, { __unstableInputRule }) => {
if (__unstableInputRule) {
accumulator = __unstableInputRule(accumulator);
}
return accumulator;
},
preventEventDiscovery(value)
);
const {
__unstableMarkLastChangeAsPersistent: __unstableMarkLastChangeAsPersistent2,
__unstableMarkAutomaticChange: __unstableMarkAutomaticChange2
} = registry.dispatch(store);
if (transformed !== value) {
__unstableMarkLastChangeAsPersistent2();
onChange({
...transformed,
activeFormats: value.activeFormats
});
__unstableMarkAutomaticChange2();
}
}
const unsubscribeInput = subscribeOwnedListener2(
element,
"input",
onInput,
true
);
const unsubscribeCompositionEnd = subscribeOwnedListener2(
element,
"compositionend",
onInput,
true
);
return () => {
unsubscribeInput();
unsubscribeCompositionEnd();
};
};
// packages/block-editor/build-module/components/rich-text/event-listeners/insert-replacement-text.mjs
var import_rich_text8 = __toESM(require_rich_text(), 1);
var { subscribeOwnedListener: subscribeOwnedListener3 } = unlock(import_rich_text8.privateApis);
var insert_replacement_text_default = (props) => (element) => {
function onInput(event) {
if (event.inputType !== "insertReplacementText") {
return;
}
const { registry } = props.current;
registry.dispatch(store).__unstableMarkLastChangeAsPersistent();
}
return subscribeOwnedListener3(element, "beforeinput", onInput);
};
// packages/block-editor/build-module/components/rich-text/event-listeners/remove-browser-shortcuts.mjs
var import_keycodes22 = __toESM(require_keycodes(), 1);
var import_rich_text9 = __toESM(require_rich_text(), 1);
var { subscribeOwnedListener: subscribeOwnedListener4 } = unlock(import_rich_text9.privateApis);
var remove_browser_shortcuts_default = () => (node) => {
function onKeydown(event) {
if (import_keycodes22.isKeyboardEvent.primary(event, "z") || import_keycodes22.isKeyboardEvent.primary(event, "y") || import_keycodes22.isKeyboardEvent.primaryShift(event, "z")) {
event.preventDefault();
}
}
return subscribeOwnedListener4(node, "keydown", onKeydown, true);
};
// packages/block-editor/build-module/components/rich-text/event-listeners/shortcuts.mjs
var import_rich_text10 = __toESM(require_rich_text(), 1);
var { subscribeOwnedListener: subscribeOwnedListener5 } = unlock(import_rich_text10.privateApis);
var shortcuts_default = (props) => (element) => {
const { keyboardShortcuts } = props.current;
function onKeyDown(event) {
for (const keyboardShortcut of keyboardShortcuts.current) {
keyboardShortcut(event);
}
}
return subscribeOwnedListener5(element, "keydown", onKeyDown, true);
};
// packages/block-editor/build-module/components/rich-text/event-listeners/input-events.mjs
var import_rich_text11 = __toESM(require_rich_text(), 1);
var { subscribeOwnedListener: subscribeOwnedListener6 } = unlock(import_rich_text11.privateApis);
var input_events_default = (props) => (element) => {
const { inputEvents } = props.current;
function onInput(event) {
for (const keyboardShortcut of inputEvents.current) {
keyboardShortcut(event);
}
}
return subscribeOwnedListener6(element, "input", onInput);
};
// packages/block-editor/build-module/components/rich-text/event-listeners/undo-automatic-change.mjs
var import_keycodes23 = __toESM(require_keycodes(), 1);
var import_rich_text12 = __toESM(require_rich_text(), 1);
var { subscribeOwnedListener: subscribeOwnedListener7 } = unlock(import_rich_text12.privateApis);
var undo_automatic_change_default = (props) => (element) => {
function onKeyDown(event) {
const { keyCode } = event;
if (event.defaultPrevented) {
return;
}
if (keyCode !== import_keycodes23.BACKSPACE && keyCode !== import_keycodes23.ESCAPE) {
return;
}
const { registry } = props.current;
const { didAutomaticChange: didAutomaticChange2, getSettings: getSettings7 } = registry.select(store);
const { __experimentalUndo } = getSettings7();
if (!__experimentalUndo) {
return;
}
if (!didAutomaticChange2()) {
return;
}
event.preventDefault();
__experimentalUndo();
}
return subscribeOwnedListener7(element, "keydown", onKeyDown);
};
// packages/block-editor/build-module/components/rich-text/event-listeners/paste-handler.mjs
var import_blocks85 = __toESM(require_blocks(), 1);
var import_rich_text13 = __toESM(require_rich_text(), 1);
var import_url9 = __toESM(require_url(), 1);
var import_compose89 = __toESM(require_compose(), 1);
// packages/block-editor/build-module/components/rich-text/utils.mjs
var import_element228 = __toESM(require_element(), 1);
var import_blocks84 = __toESM(require_blocks(), 1);
var import_jsx_runtime393 = __toESM(require_jsx_runtime(), 1);
function addActiveFormats(value, activeFormats) {
if (activeFormats?.length) {
let index2 = value.formats.length;
while (index2--) {
value.formats[index2] = [
...activeFormats,
...value.formats[index2] || []
];
}
}
}
function getMultilineTag(multiline) {
if (multiline !== true && multiline !== "p" && multiline !== "li") {
return;
}
return multiline === true ? "p" : multiline;
}
function getAllowedFormats({ allowedFormats, disableFormats }) {
if (disableFormats) {
return getAllowedFormats.EMPTY_ARRAY;
}
return allowedFormats;
}
getAllowedFormats.EMPTY_ARRAY = [];
// packages/block-editor/build-module/components/rich-text/event-listeners/paste-handler.mjs
var { subscribeDelegatedListener: subscribeDelegatedListener3 } = unlock(import_compose89.privateApis);
var { ownsSelection: ownsSelection2 } = unlock(import_rich_text13.privateApis);
var paste_handler_default = (props) => (element) => {
function _onPaste(event) {
const {
disableFormats,
onChange,
value,
formatTypes,
tagName,
onReplace,
__unstableEmbedURLOnPaste,
preserveWhiteSpace,
pastePlainText,
registry
} = props.current;
if (!element.contains(event.target) && !ownsSelection2(element)) {
return;
}
if (event.defaultPrevented) {
return;
}
const { plainText, html } = getPasteEventData(event);
event.preventDefault();
window.console.log("Received HTML (RichText):\n\n", html);
window.console.log("Received plain text (RichText):\n\n", plainText);
if (disableFormats) {
onChange((0, import_rich_text13.insert)(value, plainText));
return;
}
const isInternal = event.clipboardData.getData("rich-text") === "true";
function pasteInline(content2) {
const transformed = formatTypes.reduce(
(accumulator, { __unstablePasteRule }) => {
if (__unstablePasteRule && accumulator === value) {
accumulator = __unstablePasteRule(value, {
html,
plainText
});
}
return accumulator;
},
value
);
if (transformed !== value) {
onChange(transformed);
} else {
const valueToInsert = (0, import_rich_text13.create)({ html: content2 });
addActiveFormats(valueToInsert, value.activeFormats);
onChange((0, import_rich_text13.insert)(value, valueToInsert));
}
}
if (isInternal) {
pasteInline(html);
return;
}
if (pastePlainText) {
onChange((0, import_rich_text13.insert)(value, (0, import_rich_text13.create)({ text: plainText })));
return;
}
let mode2 = "INLINE";
const trimmedPlainText = plainText.trim();
if (__unstableEmbedURLOnPaste && (0, import_rich_text13.isEmpty)(value) && (0, import_url9.isURL)(trimmedPlainText) && // For the link pasting feature, allow only http(s) protocols.
/^https?:/.test(trimmedPlainText)) {
mode2 = "BLOCKS";
}
const content = (0, import_blocks85.pasteHandler)({
HTML: html,
plainText,
mode: mode2,
tagName,
preserveWhiteSpace
});
if (typeof content === "string") {
pasteInline(content);
return;
}
if (!content.length || !onReplace || !(0, import_rich_text13.isEmpty)(value)) {
return;
}
if (mode2 === "BLOCKS") {
pasteInline(html);
registry.dispatch(store).__unstableMarkLastChangeAsPersistent();
}
onReplace(content, content.length - 1, -1);
}
const { defaultView } = element.ownerDocument;
return subscribeDelegatedListener3(defaultView, "paste", _onPaste);
};
// packages/block-editor/build-module/components/rich-text/event-listeners/delete.mjs
var import_keycodes24 = __toESM(require_keycodes(), 1);
var import_rich_text14 = __toESM(require_rich_text(), 1);
var { subscribeOwnedListener: subscribeOwnedListener8 } = unlock(import_rich_text14.privateApis);
var delete_default = (props) => (element) => {
function onKeyDown(event) {
const { keyCode } = event;
if (event.defaultPrevented) {
return;
}
const { value, onMerge, onRemove } = props.current;
if (keyCode === import_keycodes24.DELETE || keyCode === import_keycodes24.BACKSPACE) {
const { start: start2, end, text } = value;
const isReverse = keyCode === import_keycodes24.BACKSPACE;
const hasActiveFormats = value.activeFormats && !!value.activeFormats.length;
if (!(0, import_rich_text14.isCollapsed)(value) || hasActiveFormats || isReverse && start2 !== 0 || !isReverse && end !== text.length) {
return;
}
if (onMerge) {
onMerge(!isReverse);
} else if (onRemove && (0, import_rich_text14.isEmpty)(value) && isReverse) {
onRemove(!isReverse);
}
event.preventDefault();
}
}
return subscribeOwnedListener8(element, "keydown", onKeyDown);
};
// packages/block-editor/build-module/components/rich-text/event-listeners/enter.mjs
var import_keycodes25 = __toESM(require_keycodes(), 1);
var import_rich_text15 = __toESM(require_rich_text(), 1);
var import_compose90 = __toESM(require_compose(), 1);
var { subscribeOwnedListener: subscribeOwnedListener9, ownsSelection: ownsSelection3 } = unlock(import_rich_text15.privateApis);
var { subscribeDelegatedListener: subscribeDelegatedListener4 } = unlock(import_compose90.privateApis);
var enter_default = (props) => (element) => {
function onKeyDownDeprecated(event) {
if (event.keyCode !== import_keycodes25.ENTER) {
return;
}
const { onReplace, onSplit } = props.current;
if (onReplace && onSplit) {
event.__deprecatedOnSplit = true;
}
}
function onKeyDown(event) {
if (event.defaultPrevented) {
return;
}
if (event.target !== element && !ownsSelection3(element)) {
return;
}
if (event.keyCode !== import_keycodes25.ENTER) {
return;
}
const {
value,
onChange,
disableLineBreaks,
onSplitAtEnd,
onSplitAtDoubleLineEnd,
registry
} = props.current;
event.preventDefault();
const { text, start: start2, end } = value;
if (event.shiftKey) {
if (!disableLineBreaks) {
onChange((0, import_rich_text15.insert)(value, "\n"));
}
} else if (onSplitAtEnd && start2 === end && end === text.length) {
onSplitAtEnd();
} else if (
// For some blocks it's desirable to split at the end of the
// block when there are two line breaks at the end of the
// block, so triple Enter exits the block.
onSplitAtDoubleLineEnd && start2 === end && end === text.length && text.slice(-2) === "\n\n"
) {
registry.batch(() => {
const _value = { ...value };
_value.start = _value.end - 2;
onChange((0, import_rich_text15.remove)(_value));
onSplitAtDoubleLineEnd();
});
} else if (!disableLineBreaks) {
onChange((0, import_rich_text15.insert)(value, "\n"));
}
}
const { defaultView } = element.ownerDocument;
const unsubscribeKeyDown = subscribeDelegatedListener4(
defaultView,
"keydown",
onKeyDown
);
const unsubscribeKeyDownDeprecated = subscribeOwnedListener9(
element,
"keydown",
onKeyDownDeprecated,
true
);
return () => {
unsubscribeKeyDown();
unsubscribeKeyDownDeprecated();
};
};
// packages/block-editor/build-module/components/rich-text/event-listeners/firefox-compat.mjs
var firefox_compat_default = (props) => (element) => {
function onFocus() {
const { registry } = props.current;
if (!registry.select(store).isMultiSelecting()) {
return;
}
const parentEditable = element.parentElement.closest(
'[contenteditable="true"]'
);
if (parentEditable) {
parentEditable.focus();
}
}
element.addEventListener("focus", onFocus);
return () => {
element.removeEventListener("focus", onFocus);
};
};
// packages/block-editor/build-module/components/rich-text/event-listeners/index.mjs
var allEventListeners = [
before_input_rules_default,
input_rules_default,
insert_replacement_text_default,
remove_browser_shortcuts_default,
shortcuts_default,
input_events_default,
undo_automatic_change_default,
paste_handler_default,
delete_default,
enter_default,
firefox_compat_default
];
function useEventListeners(props) {
const propsRef = (0, import_element229.useRef)(props);
(0, import_element229.useInsertionEffect)(() => {
propsRef.current = props;
});
const refEffects = (0, import_element229.useMemo)(
() => allEventListeners.map((refEffect) => refEffect(propsRef)),
[propsRef]
);
return (0, import_compose91.useRefEffect)(
(element) => {
if (!props.isSelected) {
return;
}
const cleanups = refEffects.map((effect) => effect(element));
return () => {
cleanups.forEach((cleanup) => cleanup());
};
},
[refEffects, props.isSelected]
);
}
// packages/block-editor/build-module/components/rich-text/format-edit.mjs
var import_rich_text16 = __toESM(require_rich_text(), 1);
var import_element230 = __toESM(require_element(), 1);
var import_jsx_runtime394 = __toESM(require_jsx_runtime(), 1);
var import_react16 = __toESM(require_react(), 1);
var DEFAULT_BLOCK_CONTEXT = {};
var usesContextKey = /* @__PURE__ */ Symbol("usesContext");
function Edit3({
onChange,
onFocus,
value,
forwardedRef,
settings: settings2,
isVisible
}) {
const {
name,
edit: EditFunction,
[usesContextKey]: usesContext
} = settings2;
const blockContext = (0, import_element230.useContext)(block_context_default);
const context = (0, import_element230.useMemo)(() => {
return usesContext ? Object.fromEntries(
Object.entries(blockContext).filter(
([key]) => usesContext.includes(key)
)
) : DEFAULT_BLOCK_CONTEXT;
}, [usesContext, blockContext]);
if (!EditFunction) {
return null;
}
const activeFormat = (0, import_rich_text16.getActiveFormat)(value, name);
const isActive = activeFormat !== void 0;
const activeObject = (0, import_rich_text16.getActiveObject)(value);
const isObjectActive = activeObject !== void 0 && activeObject.type === name;
return /* @__PURE__ */ (0, import_jsx_runtime394.jsx)(
EditFunction,
{
isActive,
isVisible,
activeAttributes: isActive ? activeFormat.attributes || {} : {},
isObjectActive,
activeObjectAttributes: isObjectActive ? activeObject.attributes || {} : {},
value,
onChange,
onFocus,
contentRef: forwardedRef,
context
},
name
);
}
function FormatEdit({ formatTypes, ...props }) {
return formatTypes.map((settings2) => /* @__PURE__ */ (0, import_react16.createElement)(Edit3, { settings: settings2, ...props, key: settings2.name }));
}
// packages/block-editor/build-module/components/rich-text/content.mjs
var import_element231 = __toESM(require_element(), 1);
var import_blocks86 = __toESM(require_blocks(), 1);
var import_deprecated24 = __toESM(require_deprecated(), 1);
var import_jsx_runtime395 = __toESM(require_jsx_runtime(), 1);
function valueToHTMLString(value, multiline) {
if (rich_text_default.isEmpty(value)) {
const multilineTag = getMultilineTag(multiline);
return multilineTag ? `<${multilineTag}></${multilineTag}>` : "";
}
if (Array.isArray(value)) {
(0, import_deprecated24.default)("wp.blockEditor.RichText value prop as children type", {
since: "6.1",
version: "6.3",
alternative: "value prop as string",
link: "https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/introducing-attributes-and-editable-fields/"
});
return import_blocks86.children.toHTML(value);
}
if (typeof value === "string") {
return value;
}
return value.toHTMLString();
}
function Content3({
value,
tagName: Tag,
multiline,
format: format6,
...props
}) {
value = /* @__PURE__ */ (0, import_jsx_runtime395.jsx)(import_element231.RawHTML, { children: valueToHTMLString(value, multiline) });
return Tag ? /* @__PURE__ */ (0, import_jsx_runtime395.jsx)(Tag, { ...props, children: value }) : value;
}
// packages/block-editor/build-module/components/rich-text/with-deprecations.mjs
var import_element233 = __toESM(require_element(), 1);
var import_blocks87 = __toESM(require_blocks(), 1);
var import_rich_text18 = __toESM(require_rich_text(), 1);
var import_deprecated26 = __toESM(require_deprecated(), 1);
// packages/block-editor/build-module/components/rich-text/multiline.mjs
var import_element232 = __toESM(require_element(), 1);
var import_deprecated25 = __toESM(require_deprecated(), 1);
var import_data153 = __toESM(require_data(), 1);
var import_keycodes26 = __toESM(require_keycodes(), 1);
var import_rich_text17 = __toESM(require_rich_text(), 1);
var import_jsx_runtime396 = __toESM(require_jsx_runtime(), 1);
function RichTextMultiline({
children,
identifier,
tagName: TagName = "div",
value = "",
onChange,
multiline,
...props
}, forwardedRef) {
(0, import_deprecated25.default)("wp.blockEditor.RichText multiline prop", {
since: "6.1",
version: "6.3",
alternative: "nested blocks (InnerBlocks)",
link: "https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/nested-blocks-inner-blocks/"
});
const { clientId } = useBlockEditContext();
const { getSelectionStart: getSelectionStart2, getSelectionEnd: getSelectionEnd2 } = (0, import_data153.useSelect)(store);
const { selectionChange: selectionChange2 } = (0, import_data153.useDispatch)(store);
const multilineTagName = getMultilineTag(multiline);
value = value || `<${multilineTagName}></${multilineTagName}>`;
const padded = `</${multilineTagName}>${value}<${multilineTagName}>`;
const values = padded.split(
`</${multilineTagName}><${multilineTagName}>`
);
values.shift();
values.pop();
function _onChange(newValues) {
onChange(
`<${multilineTagName}>${newValues.join(
`</${multilineTagName}><${multilineTagName}>`
)}</${multilineTagName}>`
);
}
return /* @__PURE__ */ (0, import_jsx_runtime396.jsx)(TagName, { ref: forwardedRef, children: values.map((_value, index2) => {
return /* @__PURE__ */ (0, import_jsx_runtime396.jsx)(
RichTextWrapper,
{
identifier: `${identifier}-${index2}`,
tagName: multilineTagName,
value: _value,
onChange: (newValue) => {
const newValues = values.slice();
newValues[index2] = newValue;
_onChange(newValues);
},
isSelected: void 0,
onKeyDown: (event) => {
if (event.keyCode !== import_keycodes26.ENTER) {
return;
}
event.preventDefault();
const { offset: start2 } = getSelectionStart2();
const { offset: end } = getSelectionEnd2();
if (typeof start2 !== "number" || typeof end !== "number") {
return;
}
const richTextValue = (0, import_rich_text17.create)({ html: _value });
richTextValue.start = start2;
richTextValue.end = end;
const array = (0, import_rich_text17.split)(richTextValue).map(
(v2) => (0, import_rich_text17.toHTMLString)({ value: v2 })
);
const newValues = values.slice();
newValues.splice(index2, 1, ...array);
_onChange(newValues);
selectionChange2(
clientId,
`${identifier}-${index2 + 1}`,
0,
0
);
},
onMerge: (forward) => {
const newValues = values.slice();
let offset4 = 0;
if (forward) {
if (!newValues[index2 + 1]) {
return;
}
newValues.splice(
index2,
2,
newValues[index2] + newValues[index2 + 1]
);
offset4 = newValues[index2].length - 1;
} else {
if (!newValues[index2 - 1]) {
return;
}
newValues.splice(
index2 - 1,
2,
newValues[index2 - 1] + newValues[index2]
);
offset4 = newValues[index2 - 1].length - 1;
}
_onChange(newValues);
selectionChange2(
clientId,
`${identifier}-${index2 - (forward ? 0 : 1)}`,
offset4,
offset4
);
},
...props
},
index2
);
}) });
}
var multiline_default = (0, import_element232.forwardRef)(RichTextMultiline);
// packages/block-editor/build-module/components/rich-text/with-deprecations.mjs
var import_jsx_runtime397 = __toESM(require_jsx_runtime(), 1);
function withDeprecations(Component6) {
return (0, import_element233.forwardRef)((props, ref) => {
let value = props.value;
let onChange = props.onChange;
if (Array.isArray(value)) {
(0, import_deprecated26.default)("wp.blockEditor.RichText value prop as children type", {
since: "6.1",
version: "6.3",
alternative: "value prop as string",
link: "https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/introducing-attributes-and-editable-fields/"
});
value = import_blocks87.children.toHTML(props.value);
onChange = (newValue) => props.onChange(
import_blocks87.children.fromDOM(
(0, import_rich_text18.__unstableCreateElement)(document, newValue).childNodes
)
);
}
const NewComponent = props.multiline ? multiline_default : Component6;
return /* @__PURE__ */ (0, import_jsx_runtime397.jsx)(
NewComponent,
{
...props,
value,
onChange,
ref
}
);
});
}
// packages/block-editor/build-module/components/rich-text/toolbar-button.mjs
var import_components179 = __toESM(require_components(), 1);
var import_keycodes27 = __toESM(require_keycodes(), 1);
var import_jsx_runtime398 = __toESM(require_jsx_runtime(), 1);
function RichTextToolbarButton({
name,
shortcutType,
shortcutCharacter,
...props
}) {
let shortcut;
let fillName = "RichText.ToolbarControls";
if (name) {
fillName += `.${name}`;
}
if (shortcutType && shortcutCharacter) {
shortcut = import_keycodes27.displayShortcut[shortcutType](shortcutCharacter);
}
return /* @__PURE__ */ (0, import_jsx_runtime398.jsx)(import_components179.Fill, { name: fillName, children: /* @__PURE__ */ (0, import_jsx_runtime398.jsx)(import_components179.ToolbarButton, { ...props, shortcut }) });
}
// packages/block-editor/build-module/components/rich-text/index.mjs
var import_jsx_runtime399 = __toESM(require_jsx_runtime(), 1);
var {
useRichText,
KeyboardShortcutContext,
InputEventContext,
RichTextShortcut,
RichTextInputEvent
} = unlock(import_rich_text19.privateApis);
var instanceIdKey = /* @__PURE__ */ Symbol("instanceId");
function RichTextWrapper({
children,
tagName = "div",
value: adjustedValue = "",
onChange: adjustedOnChange,
isSelected: originalIsSelected,
multiline,
inlineToolbar,
wrapperClassName,
autocompleters,
onReplace,
placeholder,
allowedFormats,
withoutInteractiveFormatting,
onRemove,
onMerge,
onSplit,
__unstableOnSplitAtEnd: onSplitAtEnd,
__unstableOnSplitAtDoubleLineEnd: onSplitAtDoubleLineEnd,
identifier,
preserveWhiteSpace,
__unstablePastePlainText: pastePlainText,
__unstableEmbedURLOnPaste,
__unstableDisableFormats: disableFormats,
disableLineBreaks,
__unstableAllowPrefixTransformations,
readOnly,
...props
}, forwardedRef) {
if (onSplit) {
(0, import_deprecated27.default)("wp.blockEditor.RichText onSplit prop", {
since: "6.4",
alternative: 'block.json support key: "splitting"'
});
}
const instanceId = (0, import_compose92.useInstanceId)(RichTextWrapper);
const anchorRef = (0, import_element234.useRef)();
const [anchorElement, setAnchorElement] = (0, import_element234.useState)(null);
const context = useBlockEditContext();
const { clientId, isSelected: isBlockSelected2, name: blockName } = context;
const blockBindings = context[blockBindingsKey];
const blockContext = (0, import_element234.useContext)(block_context_default);
const registry = (0, import_data154.useRegistry)();
const selector3 = (select3) => {
if (!isBlockSelected2) {
return { isSelected: false };
}
const { getSelectionStart: getSelectionStart22, getSelectionEnd: getSelectionEnd22 } = select3(store);
const selectionStart2 = getSelectionStart22();
const selectionEnd2 = getSelectionEnd22();
let isSelected2;
if (originalIsSelected === void 0) {
isSelected2 = selectionStart2.clientId === clientId && selectionEnd2.clientId === clientId && (identifier ? selectionStart2.attributeKey === identifier : selectionStart2[instanceIdKey] === instanceId);
} else if (originalIsSelected) {
isSelected2 = selectionStart2.clientId === clientId;
}
return {
selectionStart: isSelected2 ? selectionStart2.offset : void 0,
selectionEnd: isSelected2 ? selectionEnd2.offset : void 0,
isSelected: isSelected2
};
};
const { selectionStart, selectionEnd, isSelected } = (0, import_data154.useSelect)(selector3, [
clientId,
identifier,
instanceId,
originalIsSelected,
isBlockSelected2
]);
const { disableBoundBlock, bindingsPlaceholder, bindingsLabel } = (0, import_data154.useSelect)(
(select3) => {
if (!blockBindings?.[identifier]) {
return {};
}
const { __experimentalBlockBindingsSupportedAttributes } = select3(store).getSettings();
const bindableAttributes = __experimentalBlockBindingsSupportedAttributes?.[blockName];
if (!bindableAttributes) {
return {};
}
const relatedBinding = blockBindings[identifier];
const blockBindingsSource = (0, import_blocks88.getBlockBindingsSource)(
relatedBinding.source
);
const blockBindingsContext = {};
if (blockBindingsSource?.usesContext?.length) {
for (const key of blockBindingsSource.usesContext) {
blockBindingsContext[key] = blockContext[key];
}
}
const _disableBoundBlock = !blockBindingsSource?.canUserEditValue?.({
select: select3,
context: blockBindingsContext,
args: relatedBinding.args
});
if (adjustedValue.length > 0) {
return {
disableBoundBlock: _disableBoundBlock,
// Null values will make them fall back to the default behavior.
bindingsPlaceholder: null,
bindingsLabel: null
};
}
const { getBlockAttributes: getBlockAttributes3 } = select3(store);
const blockAttributes = getBlockAttributes3(clientId);
let clientSideFieldLabel = null;
if (blockBindingsSource?.getFieldsList) {
const fieldsItems = blockBindingsSource.getFieldsList({
select: select3,
context: blockBindingsContext
});
clientSideFieldLabel = fieldsItems?.find(
(item) => (0, import_es65.default)(item.args, relatedBinding?.args)
)?.label;
}
const bindingKey = clientSideFieldLabel ?? blockBindingsSource?.label;
const _bindingsPlaceholder = _disableBoundBlock ? bindingKey : (0, import_i18n169.sprintf)(
/* translators: %s: connected field label or source label */
(0, import_i18n169.__)("Add %s"),
bindingKey
);
const _bindingsLabel = _disableBoundBlock ? relatedBinding?.args?.key || blockBindingsSource?.label : (0, import_i18n169.sprintf)(
/* translators: %s: source label or key */
(0, import_i18n169.__)("Empty %s; start writing to edit its value"),
relatedBinding?.args?.key || blockBindingsSource?.label
);
return {
disableBoundBlock: _disableBoundBlock,
bindingsPlaceholder: blockAttributes?.placeholder || _bindingsPlaceholder,
bindingsLabel: _bindingsLabel
};
},
[
blockBindings,
identifier,
blockName,
adjustedValue,
clientId,
blockContext
]
);
const isInsidePatternOverrides = !!blockContext?.["pattern/overrides"];
const hasOverrideEnabled = blockBindings?.__default?.source === "core/pattern-overrides";
const shouldDisableForPattern = isInsidePatternOverrides && !hasOverrideEnabled;
const shouldDisableEditing = readOnly || disableBoundBlock || shouldDisableForPattern;
const hasEditableRoot = useHasEditableRoot();
const hasDefaultEditingMode = (0, import_data154.useSelect)(
(select3) => select3(store).getBlockEditingMode(clientId) === "default",
[clientId]
);
const { getSelectionStart: getSelectionStart2, getSelectionEnd: getSelectionEnd2, getBlockRootClientId: getBlockRootClientId2 } = (0, import_data154.useSelect)(store);
const { selectionChange: selectionChange2 } = (0, import_data154.useDispatch)(store);
const adjustedAllowedFormats = getAllowedFormats({
allowedFormats,
disableFormats
});
const hasFormats = !adjustedAllowedFormats || adjustedAllowedFormats.length > 0;
const onSelectionChange = (0, import_element234.useCallback)(
(start2, end) => {
const selection2 = {};
const unset = start2 === void 0 && end === void 0;
const baseSelection = {
clientId,
[identifier ? "attributeKey" : instanceIdKey]: identifier ? identifier : instanceId
};
if (typeof start2 === "number" || unset) {
if (end === void 0 && getBlockRootClientId2(clientId) !== getBlockRootClientId2(getSelectionEnd2().clientId)) {
return;
}
selection2.start = {
...baseSelection,
offset: start2
};
}
if (typeof end === "number" || unset) {
if (start2 === void 0 && getBlockRootClientId2(clientId) !== getBlockRootClientId2(getSelectionStart2().clientId)) {
return;
}
selection2.end = {
...baseSelection,
offset: end
};
}
selectionChange2(selection2);
},
[
clientId,
getBlockRootClientId2,
getSelectionEnd2,
getSelectionStart2,
identifier,
instanceId,
selectionChange2
]
);
const {
value,
getValue,
onChange,
ref: richTextRef,
formatTypes
} = useRichText({
value: adjustedValue,
onChange: adjustedOnChange,
selectionStart,
selectionEnd,
onSelectionChange,
placeholder: bindingsPlaceholder || placeholder,
__unstableIsSelected: isSelected,
__unstableDisableFormats: disableFormats,
preserveWhiteSpace,
__unstableDependencies: [tagName],
allowedFormats: adjustedAllowedFormats,
withoutInteractiveFormatting,
__unstableFormatTypeHandlerContext: (0, import_element234.useMemo)(
() => ({
richTextIdentifier: identifier,
blockClientId: clientId
}),
[identifier, clientId]
)
});
const autocompleteProps = useBlockEditorAutocompleteProps({
onReplace,
completers: autocompleters,
record: value,
onChange
});
const {
"aria-autocomplete": ariaAutocomplete,
"aria-owns": ariaOwns,
"aria-activedescendant": ariaActiveDescendant
} = autocompleteProps;
(0, import_element234.useEffect)(() => {
if (!hasEditableRoot || !isSelected) {
return;
}
const host2 = anchorRef.current?.parentElement?.closest(
'[contenteditable="true"]'
);
if (!host2) {
return;
}
const attributes = {
"aria-autocomplete": ariaAutocomplete,
"aria-owns": ariaOwns,
"aria-activedescendant": ariaActiveDescendant
};
for (const [key, value_] of Object.entries(attributes)) {
if (value_ === void 0) {
host2.removeAttribute(key);
} else {
host2.setAttribute(key, value_);
}
}
return () => {
for (const key of Object.keys(attributes)) {
host2.removeAttribute(key);
}
};
}, [
hasEditableRoot,
isSelected,
ariaAutocomplete,
ariaOwns,
ariaActiveDescendant
]);
useMarkPersistent({ html: adjustedValue, value });
const keyboardShortcuts = (0, import_element234.useRef)(/* @__PURE__ */ new Set());
const inputEvents = (0, import_element234.useRef)(/* @__PURE__ */ new Set());
function onFocus() {
anchorRef.current?.focus();
}
let tabIndex = props.tabIndex;
if (!shouldDisableEditing) {
if (hasEditableRoot && hasDefaultEditingMode && isBlockSelected2) {
tabIndex = props.tabIndex ?? 0;
} else if (hasEditableRoot && props.tabIndex === 0) {
tabIndex = null;
}
}
const TagName = tagName;
return /* @__PURE__ */ (0, import_jsx_runtime399.jsxs)(import_jsx_runtime399.Fragment, { children: [
isSelected && /* @__PURE__ */ (0, import_jsx_runtime399.jsx)(KeyboardShortcutContext.Provider, { value: keyboardShortcuts, children: /* @__PURE__ */ (0, import_jsx_runtime399.jsx)(InputEventContext.Provider, { value: inputEvents, children: /* @__PURE__ */ (0, import_jsx_runtime399.jsxs)(import_components180.Popover.__unstableSlotNameProvider, { value: "__unstable-block-tools-after", children: [
children && children({ value, onChange, onFocus }),
/* @__PURE__ */ (0, import_jsx_runtime399.jsx)(
FormatEdit,
{
value,
onChange,
onFocus,
formatTypes,
forwardedRef: anchorRef
}
)
] }) }) }),
isSelected && hasFormats && /* @__PURE__ */ (0, import_jsx_runtime399.jsx)(
format_toolbar_container_default,
{
inline: inlineToolbar,
editableContentElement: anchorElement
}
),
/* @__PURE__ */ (0, import_jsx_runtime399.jsx)(
TagName,
{
role: "textbox",
"aria-multiline": !disableLineBreaks,
"aria-readonly": shouldDisableEditing,
...props,
draggable: void 0,
"aria-label": bindingsLabel || props["aria-label"] || placeholder,
...autocompleteProps,
ref: (0, import_compose92.useMergeRefs)([
// Rich text ref must be first because its focus listener
// must be set up before any other ref calls .focus() on
// mount.
richTextRef,
forwardedRef,
autocompleteProps.ref,
props.ref,
useEventListeners({
registry,
getValue,
onChange,
__unstableAllowPrefixTransformations,
formatTypes,
onReplace,
selectionChange: selectionChange2,
isSelected,
disableFormats,
value,
tagName,
onSplit,
__unstableEmbedURLOnPaste,
pastePlainText,
onMerge,
onRemove,
disableLineBreaks,
onSplitAtEnd,
onSplitAtDoubleLineEnd,
keyboardShortcuts,
inputEvents
}),
anchorRef,
setAnchorElement
]),
contentEditable: !shouldDisableEditing,
suppressContentEditableWarning: true,
className: clsx_default(
"block-editor-rich-text__editable",
props.className,
"rich-text"
),
tabIndex,
"data-wp-block-attribute-key": identifier
}
)
] });
}
var PrivateRichText = withDeprecations(
(0, import_element234.forwardRef)(RichTextWrapper)
);
PrivateRichText.Content = Content3;
PrivateRichText.isEmpty = (value) => {
return !value || value.length === 0;
};
var PublicForwardedRichTextContainer = (0, import_element234.forwardRef)((props, ref) => {
const context = useBlockEditContext();
const isPreviewMode = context[isPreviewModeKey];
if (isPreviewMode) {
const {
children,
tagName: Tag = "div",
value,
onChange,
isSelected,
multiline,
inlineToolbar,
wrapperClassName,
autocompleters,
onReplace,
placeholder,
allowedFormats,
withoutInteractiveFormatting,
onRemove,
onMerge,
onSplit,
__unstableOnSplitAtEnd,
__unstableOnSplitAtDoubleLineEnd,
identifier,
preserveWhiteSpace,
__unstablePastePlainText,
__unstableEmbedURLOnPaste,
__unstableDisableFormats,
disableLineBreaks,
__unstableAllowPrefixTransformations,
readOnly,
...contentProps
} = props;
return /* @__PURE__ */ (0, import_jsx_runtime399.jsx)(
Tag,
{
ref,
...contentProps,
dangerouslySetInnerHTML: {
__html: valueToHTMLString(value, multiline) || "<br>"
}
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime399.jsx)(PrivateRichText, { ref, ...props, readOnly: false });
});
PublicForwardedRichTextContainer.Content = Content3;
PublicForwardedRichTextContainer.isEmpty = (value) => {
return !value || value.length === 0;
};
var rich_text_default = PublicForwardedRichTextContainer;
// packages/block-editor/build-module/components/editable-text/index.mjs
var import_jsx_runtime400 = __toESM(require_jsx_runtime(), 1);
var EditableText = (0, import_element235.forwardRef)((props, ref) => {
return /* @__PURE__ */ (0, import_jsx_runtime400.jsx)(rich_text_default, { ref, ...props, __unstableDisableFormats: true });
});
EditableText.Content = function Content4({
value = "",
tagName: Tag = "div",
...props
}) {
return /* @__PURE__ */ (0, import_jsx_runtime400.jsx)(Tag, { ...props, children: value });
};
var editable_text_default = EditableText;
// packages/block-editor/build-module/components/plain-text/index.mjs
var import_jsx_runtime401 = __toESM(require_jsx_runtime(), 1);
var PlainText = (0, import_element236.forwardRef)(({ __experimentalVersion, ...props }, ref) => {
if (__experimentalVersion === 2) {
return /* @__PURE__ */ (0, import_jsx_runtime401.jsx)(editable_text_default, { ref, ...props });
}
const { className, onChange, ...remainingProps } = props;
return /* @__PURE__ */ (0, import_jsx_runtime401.jsx)(
import_react_autosize_textarea2.default,
{
ref,
className: clsx_default("block-editor-plain-text", className),
onChange: (event) => onChange(event.target.value),
...remainingProps
}
);
});
var plain_text_default = PlainText;
// packages/block-editor/build-module/components/responsive-block-control/index.mjs
var import_i18n171 = __toESM(require_i18n(), 1);
var import_element237 = __toESM(require_element(), 1);
var import_components181 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/responsive-block-control/label.mjs
var import_compose93 = __toESM(require_compose(), 1);
var import_i18n170 = __toESM(require_i18n(), 1);
var import_jsx_runtime402 = __toESM(require_jsx_runtime(), 1);
function ResponsiveBlockControlLabel({
property,
viewport,
desc
}) {
const instanceId = (0, import_compose93.useInstanceId)(ResponsiveBlockControlLabel);
const accessibleLabel = desc || (0, import_i18n170.sprintf)(
/* translators: 1: property name. 2: viewport name. */
(0, import_i18n170._x)(
"Controls the %1$s property for %2$s viewports.",
"Text labelling a interface as controlling a given layout property (eg: margin) for a given screen size."
),
property,
viewport.label
);
return /* @__PURE__ */ (0, import_jsx_runtime402.jsxs)(import_jsx_runtime402.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime402.jsx)("span", { "aria-describedby": `rbc-desc-${instanceId}`, children: viewport.label }),
/* @__PURE__ */ (0, import_jsx_runtime402.jsx)(
VisuallyHidden,
{
id: `rbc-desc-${instanceId}`,
render: /* @__PURE__ */ (0, import_jsx_runtime402.jsx)("span", {}),
children: accessibleLabel
}
)
] });
}
// packages/block-editor/build-module/components/responsive-block-control/index.mjs
var import_jsx_runtime403 = __toESM(require_jsx_runtime(), 1);
function ResponsiveBlockControl(props) {
const {
title,
property,
toggleLabel,
onIsResponsiveChange,
renderDefaultControl,
renderResponsiveControls,
isResponsive = false,
defaultLabel = {
id: "all",
label: (0, import_i18n171._x)("All", "screen sizes")
},
viewports = [
{
id: "small",
label: (0, import_i18n171.__)("Small screens")
},
{
id: "medium",
label: (0, import_i18n171.__)("Medium screens")
},
{
id: "large",
label: (0, import_i18n171.__)("Large screens")
}
]
} = props;
if (!title || !property || !renderDefaultControl) {
return null;
}
const toggleControlLabel = toggleLabel || (0, import_i18n171.sprintf)(
/* translators: %s: Property value for the control (eg: margin, padding, etc.). */
(0, import_i18n171.__)("Use the same %s on all screen sizes."),
property
);
const toggleHelpText = (0, import_i18n171.__)(
"Choose whether to use the same value for all screen sizes or a unique value for each screen size."
);
const defaultControl = renderDefaultControl(
/* @__PURE__ */ (0, import_jsx_runtime403.jsx)(
ResponsiveBlockControlLabel,
{
property,
viewport: defaultLabel
}
),
defaultLabel
);
const defaultResponsiveControls = () => {
return viewports.map((viewport) => /* @__PURE__ */ (0, import_jsx_runtime403.jsx)(import_element237.Fragment, { children: renderDefaultControl(
/* @__PURE__ */ (0, import_jsx_runtime403.jsx)(
ResponsiveBlockControlLabel,
{
property,
viewport
}
),
viewport
) }, viewport.id));
};
return /* @__PURE__ */ (0, import_jsx_runtime403.jsxs)("fieldset", { className: "block-editor-responsive-block-control", children: [
/* @__PURE__ */ (0, import_jsx_runtime403.jsx)("legend", { className: "block-editor-responsive-block-control__title", children: title }),
/* @__PURE__ */ (0, import_jsx_runtime403.jsxs)("div", { className: "block-editor-responsive-block-control__inner", children: [
/* @__PURE__ */ (0, import_jsx_runtime403.jsx)(
import_components181.ToggleControl,
{
className: "block-editor-responsive-block-control__toggle",
label: toggleControlLabel,
checked: !isResponsive,
onChange: onIsResponsiveChange,
help: toggleHelpText
}
),
/* @__PURE__ */ (0, import_jsx_runtime403.jsxs)(
"div",
{
className: clsx_default(
"block-editor-responsive-block-control__group",
{
"is-responsive": isResponsive
}
),
children: [
!isResponsive && defaultControl,
isResponsive && (renderResponsiveControls ? renderResponsiveControls(viewports) : defaultResponsiveControls())
]
}
)
] })
] });
}
var responsive_block_control_default = ResponsiveBlockControl;
// packages/block-editor/build-module/components/unit-control/index.mjs
var import_components182 = __toESM(require_components(), 1);
var import_jsx_runtime404 = __toESM(require_jsx_runtime(), 1);
function UnitControl6({ units: unitsProp, ...props }) {
const [availableUnits] = useSettings("spacing.units");
const units2 = (0, import_components182.__experimentalUseCustomUnits)({
availableUnits: availableUnits || ["%", "px", "em", "rem", "vw"],
units: unitsProp
});
return /* @__PURE__ */ (0, import_jsx_runtime404.jsx)(import_components182.__experimentalUnitControl, { units: units2, ...props });
}
// packages/block-editor/build-module/components/url-input/button.mjs
var import_i18n172 = __toESM(require_i18n(), 1);
var import_element238 = __toESM(require_element(), 1);
var import_components183 = __toESM(require_components(), 1);
var import_jsx_runtime405 = __toESM(require_jsx_runtime(), 1);
function URLInputButton({ url, onChange }) {
const [expanded2, toggleExpanded] = (0, import_element238.useReducer)(
(isExpanded) => !isExpanded,
false
);
const submitLink = (event) => {
event.preventDefault();
toggleExpanded();
};
return /* @__PURE__ */ (0, import_jsx_runtime405.jsxs)("div", { className: "block-editor-url-input__button", children: [
/* @__PURE__ */ (0, import_jsx_runtime405.jsx)(
import_components183.Button,
{
size: "compact",
icon: link_default,
label: url ? (0, import_i18n172.__)("Edit link") : (0, import_i18n172.__)("Insert link"),
onClick: toggleExpanded,
className: "components-toolbar__control",
isPressed: !!url
}
),
expanded2 && /* @__PURE__ */ (0, import_jsx_runtime405.jsx)(
"form",
{
className: "block-editor-url-input__button-modal",
onSubmit: submitLink,
children: /* @__PURE__ */ (0, import_jsx_runtime405.jsxs)("div", { className: "block-editor-url-input__button-modal-line", children: [
/* @__PURE__ */ (0, import_jsx_runtime405.jsx)(
import_components183.Button,
{
__next40pxDefaultSize: true,
className: "block-editor-url-input__back",
icon: arrow_left_default,
label: (0, import_i18n172.__)("Close"),
onClick: toggleExpanded
}
),
/* @__PURE__ */ (0, import_jsx_runtime405.jsx)(
url_input_default,
{
value: url || "",
onChange,
suffix: /* @__PURE__ */ (0, import_jsx_runtime405.jsx)(import_components183.__experimentalInputControlSuffixWrapper, { variant: "control", children: /* @__PURE__ */ (0, import_jsx_runtime405.jsx)(
import_components183.Button,
{
size: "small",
icon: keyboard_return_default,
label: (0, import_i18n172.__)("Submit"),
type: "submit"
}
) })
}
)
] })
}
)
] });
}
var button_default = URLInputButton;
// packages/block-editor/build-module/components/url-popover/image-url-input-ui.mjs
var import_i18n173 = __toESM(require_i18n(), 1);
var import_element239 = __toESM(require_element(), 1);
var import_dom69 = __toESM(require_dom(), 1);
var import_components184 = __toESM(require_components(), 1);
var import_url10 = __toESM(require_url(), 1);
var import_jsx_runtime406 = __toESM(require_jsx_runtime(), 1);
var LINK_DESTINATION_NONE = "none";
var LINK_DESTINATION_CUSTOM = "custom";
var LINK_DESTINATION_MEDIA = "media";
var LINK_DESTINATION_ATTACHMENT = "attachment";
var NEW_TAB_REL = ["noopener"];
var ImageURLInputUI = ({
linkDestination,
onChangeUrl,
url,
mediaType = "image",
mediaUrl,
mediaLink,
linkTarget,
linkClass,
rel,
showLightboxSetting,
lightboxEnabled,
onSetLightbox,
resetLightbox
}) => {
const [isOpen, setIsOpen] = (0, import_element239.useState)(false);
const [popoverAnchor, setPopoverAnchor] = (0, import_element239.useState)(null);
const openLinkUI = () => {
setIsOpen(true);
};
const [isEditingLink, setIsEditingLink] = (0, import_element239.useState)(false);
const [urlInput, setUrlInput] = (0, import_element239.useState)(null);
const autocompleteRef = (0, import_element239.useRef)(null);
const wrapperRef = (0, import_element239.useRef)();
(0, import_element239.useEffect)(() => {
if (!wrapperRef.current) {
return;
}
const nextFocusTarget = import_dom69.focus.focusable.find(wrapperRef.current)[0] || wrapperRef.current;
nextFocusTarget.focus();
}, [isEditingLink, url, lightboxEnabled]);
const startEditLink = () => {
if (linkDestination === LINK_DESTINATION_MEDIA || linkDestination === LINK_DESTINATION_ATTACHMENT) {
setUrlInput("");
}
setIsEditingLink(true);
};
const stopEditLink = () => {
setIsEditingLink(false);
};
const closeLinkUI = () => {
setUrlInput(null);
stopEditLink();
setIsOpen(false);
};
const getUpdatedLinkTargetSettings = (value) => {
const newLinkTarget = value ? "_blank" : void 0;
let updatedRel;
if (newLinkTarget) {
const rels = (rel ?? "").split(" ");
NEW_TAB_REL.forEach((relVal) => {
if (!rels.includes(relVal)) {
rels.push(relVal);
}
});
updatedRel = rels.join(" ");
} else {
const rels = (rel ?? "").split(" ").filter(
(relVal) => NEW_TAB_REL.includes(relVal) === false
);
updatedRel = rels.length ? rels.join(" ") : void 0;
}
return {
linkTarget: newLinkTarget,
rel: updatedRel
};
};
const onFocusOutside = () => {
return (event) => {
const autocompleteElement = autocompleteRef.current;
if (autocompleteElement && autocompleteElement.contains(event.target)) {
return;
}
setIsOpen(false);
setUrlInput(null);
stopEditLink();
};
};
const onSubmitLinkChange = () => {
return (event) => {
if (urlInput) {
const selectedDestination = getLinkDestinations().find(
(destination) => destination.url === urlInput
)?.linkDestination || LINK_DESTINATION_CUSTOM;
onChangeUrl({
href: (0, import_url10.prependHTTPS)(urlInput),
linkDestination: selectedDestination,
lightbox: { enabled: false }
});
}
stopEditLink();
setUrlInput(null);
event.preventDefault();
};
};
const onLinkRemove = () => {
onChangeUrl({
linkDestination: LINK_DESTINATION_NONE,
href: ""
});
};
const getLinkDestinations = () => {
const linkDestinations = [
{
linkDestination: LINK_DESTINATION_MEDIA,
title: (0, import_i18n173.__)("Link to image file"),
url: mediaType === "image" ? mediaUrl : void 0,
icon: image_default
}
];
if (mediaType === "image" && mediaLink) {
linkDestinations.push({
linkDestination: LINK_DESTINATION_ATTACHMENT,
title: (0, import_i18n173.__)("Link to attachment page"),
url: mediaType === "image" ? mediaLink : void 0,
icon: page_default
});
}
return linkDestinations;
};
const onSetHref = (value) => {
const linkDestinations = getLinkDestinations();
let linkDestinationInput;
if (!value) {
linkDestinationInput = LINK_DESTINATION_NONE;
} else {
linkDestinationInput = (linkDestinations.find((destination) => {
return destination.url === value;
}) || { linkDestination: LINK_DESTINATION_CUSTOM }).linkDestination;
}
onChangeUrl({
linkDestination: linkDestinationInput,
href: value
});
};
const onSetNewTab = (value) => {
const updatedLinkTarget = getUpdatedLinkTargetSettings(value);
onChangeUrl(updatedLinkTarget);
};
const onSetLinkRel = (value) => {
onChangeUrl({ rel: value });
};
const onSetLinkClass = (value) => {
onChangeUrl({ linkClass: value });
};
const advancedOptions = /* @__PURE__ */ (0, import_jsx_runtime406.jsxs)(import_components184.__experimentalVStack, { spacing: "3", children: [
/* @__PURE__ */ (0, import_jsx_runtime406.jsx)(
import_components184.ToggleControl,
{
label: (0, import_i18n173.__)("Open in new tab"),
onChange: onSetNewTab,
checked: linkTarget === "_blank"
}
),
/* @__PURE__ */ (0, import_jsx_runtime406.jsx)(
import_components184.TextControl,
{
label: (0, import_i18n173.__)("Link relation"),
value: rel ?? "",
onChange: onSetLinkRel,
help: (0, import_element239.createInterpolateElement)(
(0, import_i18n173.__)(
"The <a>Link Relation</a> attribute defines the relationship between a linked resource and the current document."
),
{
a: /* @__PURE__ */ (0, import_jsx_runtime406.jsx)(import_components184.ExternalLink, { href: "https://developer.mozilla.org/docs/Web/HTML/Attributes/rel" })
}
)
}
),
/* @__PURE__ */ (0, import_jsx_runtime406.jsx)(
import_components184.TextControl,
{
label: (0, import_i18n173.__)("Link CSS class"),
value: linkClass || "",
onChange: onSetLinkClass
}
)
] });
const linkEditorValue = urlInput !== null ? urlInput : url;
const hideLightboxPanel = !lightboxEnabled || lightboxEnabled && !showLightboxSetting;
const showLinkEditor = !linkEditorValue && hideLightboxPanel;
const urlLabel = (getLinkDestinations().find(
(destination) => destination.linkDestination === linkDestination
) || {}).title;
const PopoverChildren = () => {
if (lightboxEnabled && showLightboxSetting && !url && !isEditingLink) {
return /* @__PURE__ */ (0, import_jsx_runtime406.jsxs)("div", { className: "block-editor-url-popover__expand-on-click", children: [
/* @__PURE__ */ (0, import_jsx_runtime406.jsx)(icon_default, { icon: fullscreen_default }),
/* @__PURE__ */ (0, import_jsx_runtime406.jsxs)("div", { className: "text", children: [
/* @__PURE__ */ (0, import_jsx_runtime406.jsx)("p", { children: (0, import_i18n173.__)("Enlarge on click") }),
/* @__PURE__ */ (0, import_jsx_runtime406.jsx)("p", { className: "description", children: (0, import_i18n173.__)("Scales the image with a lightbox effect") })
] }),
/* @__PURE__ */ (0, import_jsx_runtime406.jsx)(
import_components184.Button,
{
icon: link_off_default,
label: (0, import_i18n173.__)("Disable enlarge on click"),
onClick: () => {
onSetLightbox?.(false);
},
size: "compact"
}
)
] });
} else if (!url || isEditingLink) {
return /* @__PURE__ */ (0, import_jsx_runtime406.jsx)(
url_popover_default.LinkEditor,
{
className: "block-editor-format-toolbar__link-container-content",
value: linkEditorValue,
onChangeInputValue: setUrlInput,
onSubmit: onSubmitLinkChange(),
autocompleteRef
}
);
} else if (url && !isEditingLink) {
return /* @__PURE__ */ (0, import_jsx_runtime406.jsxs)(import_jsx_runtime406.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime406.jsx)(
url_popover_default.LinkViewer,
{
className: "block-editor-format-toolbar__link-container-content",
url,
onEditLinkClick: startEditLink,
urlLabel
}
),
/* @__PURE__ */ (0, import_jsx_runtime406.jsx)(
import_components184.Button,
{
icon: link_off_default,
label: (0, import_i18n173.__)("Remove link"),
onClick: () => {
onLinkRemove();
resetLightbox?.();
},
size: "compact"
}
)
] });
}
};
return /* @__PURE__ */ (0, import_jsx_runtime406.jsxs)(import_jsx_runtime406.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime406.jsx)(
import_components184.ToolbarButton,
{
icon: link_default,
className: "components-toolbar__control",
label: (0, import_i18n173.__)("Link"),
"aria-expanded": isOpen,
onClick: openLinkUI,
ref: setPopoverAnchor,
isActive: !!url || lightboxEnabled && showLightboxSetting
}
),
isOpen && /* @__PURE__ */ (0, import_jsx_runtime406.jsx)(
url_popover_default,
{
ref: wrapperRef,
anchor: popoverAnchor,
onFocusOutside: onFocusOutside(),
onClose: closeLinkUI,
renderSettings: hideLightboxPanel ? () => advancedOptions : null,
additionalControls: showLinkEditor && /* @__PURE__ */ (0, import_jsx_runtime406.jsxs)(import_components184.NavigableMenu, { children: [
getLinkDestinations().map((link) => /* @__PURE__ */ (0, import_jsx_runtime406.jsx)(
import_components184.MenuItem,
{
icon: link.icon,
iconPosition: "left",
onClick: () => {
setUrlInput(null);
onSetHref(link.url);
stopEditLink();
},
children: link.title
},
link.linkDestination
)),
showLightboxSetting && /* @__PURE__ */ (0, import_jsx_runtime406.jsx)(
import_components184.MenuItem,
{
className: "block-editor-url-popover__expand-on-click",
icon: fullscreen_default,
info: (0, import_i18n173.__)(
"Scale the image with a lightbox effect."
),
iconPosition: "left",
onClick: () => {
setUrlInput(null);
onChangeUrl({
linkDestination: LINK_DESTINATION_NONE,
href: ""
});
onSetLightbox?.(true);
stopEditLink();
},
children: (0, import_i18n173.__)("Enlarge on click")
},
"expand-on-click"
)
] }),
offset: 13,
children: PopoverChildren()
}
)
] });
};
// packages/block-editor/build-module/components/spacing-sizes-control/index.mjs
var import_components187 = __toESM(require_components(), 1);
var import_element242 = __toESM(require_element(), 1);
var import_i18n177 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/spacing-sizes-control/hooks/use-spacing-sizes.mjs
var import_element240 = __toESM(require_element(), 1);
var import_i18n174 = __toESM(require_i18n(), 1);
var EMPTY_ARRAY12 = [];
var compare = new Intl.Collator("und", { numeric: true }).compare;
function useSpacingSizes() {
const [
customSpacingSizes,
themeSpacingSizes,
defaultSpacingSizes,
defaultSpacingSizesEnabled
] = useSettings(
"spacing.spacingSizes.custom",
"spacing.spacingSizes.theme",
"spacing.spacingSizes.default",
"spacing.defaultSpacingSizes"
);
const customSizes = customSpacingSizes ?? EMPTY_ARRAY12;
const themeSizes = themeSpacingSizes ?? EMPTY_ARRAY12;
const defaultSizes = defaultSpacingSizes && defaultSpacingSizesEnabled !== false ? defaultSpacingSizes : EMPTY_ARRAY12;
return (0, import_element240.useMemo)(() => {
const sizes = [
{ name: (0, import_i18n174.__)("None"), slug: "0", size: 0 },
...customSizes,
...themeSizes,
...defaultSizes
];
if (sizes.every(({ slug }) => /^[0-9]/.test(slug))) {
sizes.sort((a2, b2) => compare(a2.slug, b2.slug));
}
return sizes.length > RANGE_CONTROL_MAX_SIZE ? [
{
name: (0, import_i18n174.__)("Default"),
slug: "default",
size: void 0
},
...sizes
] : sizes;
}, [customSizes, themeSizes, defaultSizes]);
}
// packages/block-editor/build-module/components/spacing-sizes-control/input-controls/spacing-input-control.mjs
var import_element241 = __toESM(require_element(), 1);
var import_data155 = __toESM(require_data(), 1);
var import_i18n175 = __toESM(require_i18n(), 1);
var import_components185 = __toESM(require_components(), 1);
var import_jsx_runtime407 = __toESM(require_jsx_runtime(), 1);
var CUSTOM_VALUE_SETTINGS2 = {
px: { max: 300, steps: 1 },
"%": { max: 100, steps: 1 },
vw: { max: 100, steps: 1 },
vh: { max: 100, steps: 1 },
em: { max: 10, steps: 0.1 },
rm: { max: 10, steps: 0.1 },
svw: { max: 100, steps: 1 },
lvw: { max: 100, steps: 1 },
dvw: { max: 100, steps: 1 },
svh: { max: 100, steps: 1 },
lvh: { max: 100, steps: 1 },
dvh: { max: 100, steps: 1 },
vi: { max: 100, steps: 1 },
svi: { max: 100, steps: 1 },
lvi: { max: 100, steps: 1 },
dvi: { max: 100, steps: 1 },
vb: { max: 100, steps: 1 },
svb: { max: 100, steps: 1 },
lvb: { max: 100, steps: 1 },
dvb: { max: 100, steps: 1 },
vmin: { max: 100, steps: 1 },
svmin: { max: 100, steps: 1 },
lvmin: { max: 100, steps: 1 },
dvmin: { max: 100, steps: 1 },
vmax: { max: 100, steps: 1 },
svmax: { max: 100, steps: 1 },
lvmax: { max: 100, steps: 1 },
dvmax: { max: 100, steps: 1 }
};
function SpacingInputControl({
icon,
isMixed = false,
minimumCustomValue,
onChange,
onMouseOut,
onMouseOver,
showSideInLabel = true,
side,
spacingSizes,
type,
value,
...restProps
}) {
const disableCustomSpacingSizes = (0, import_data155.useSelect)((select3) => {
const editorSettings = select3(store).getSettings();
return editorSettings?.disableCustomSpacingSizes;
});
const [availableUnits] = useSettings("spacing.units");
const units2 = (0, import_components185.__experimentalUseCustomUnits)({
availableUnits: availableUnits || ["px", "em", "rem"]
});
const presets = (0, import_element241.useMemo)(() => {
return spacingSizes?.map((preset) => ({
name: preset.name,
slug: preset.slug,
size: preset.size
})) || [];
}, [spacingSizes]);
const sideLabel = (ALL_SIDES.includes(side) || ["vertical", "horizontal"].includes(side)) && showSideInLabel ? LABELS[side] : "";
const typeLabel = showSideInLabel ? type?.toLowerCase() : type;
const ariaLabel = (0, import_i18n175.sprintf)(
// translators: 1: The side of the block being modified (top, bottom, left etc.). 2. Type of spacing being modified (padding, margin, etc).
(0, import_i18n175._x)("%1$s %2$s", "spacing"),
sideLabel,
typeLabel
).trim();
const selectedUnit = units2[0]?.value || "px";
return /* @__PURE__ */ (0, import_jsx_runtime407.jsx)(
PresetInputControl,
{
allowNegativeOnDrag: minimumCustomValue < 0,
ariaLabel,
className: "spacing-sizes-control",
customValueSettings: CUSTOM_VALUE_SETTINGS2,
disableCustomValues: disableCustomSpacingSizes,
icon,
isMixed,
minimumCustomValue,
onChange,
onMouseOut,
onMouseOver,
presets,
presetType: "spacing",
selectedUnit,
units: units2,
value,
...restProps
}
);
}
// packages/block-editor/build-module/components/spacing-sizes-control/input-controls/axial.mjs
var import_jsx_runtime408 = __toESM(require_jsx_runtime(), 1);
var groupedSides = ["vertical", "horizontal"];
function AxialInputControls({
minimumCustomValue,
onChange,
onMouseOut,
onMouseOver,
sides: sides2,
spacingSizes,
type,
values
}) {
const createHandleOnChange = (side) => (next) => {
if (!onChange) {
return;
}
const nextValues = {
...Object.keys(values).reduce((acc, key) => {
acc[key] = getPresetValueFromCustomValue(
values[key],
spacingSizes
);
return acc;
}, {})
};
if (side === "vertical") {
nextValues.top = next;
nextValues.bottom = next;
}
if (side === "horizontal") {
nextValues.left = next;
nextValues.right = next;
}
onChange(nextValues);
};
const filteredSides = sides2?.length ? groupedSides.filter((side) => hasAxisSupport(sides2, side)) : groupedSides;
return /* @__PURE__ */ (0, import_jsx_runtime408.jsx)(import_jsx_runtime408.Fragment, { children: filteredSides.map((side) => {
const axisValue = side === "vertical" ? values.top : values.left;
return /* @__PURE__ */ (0, import_jsx_runtime408.jsx)(
SpacingInputControl,
{
icon: ICONS[side],
label: LABELS[side],
minimumCustomValue,
onChange: createHandleOnChange(side),
onMouseOut,
onMouseOver,
side,
spacingSizes,
type,
value: axisValue,
withInputField: false
},
`spacing-sizes-control-${side}`
);
}) });
}
// packages/block-editor/build-module/components/spacing-sizes-control/input-controls/separated.mjs
var import_jsx_runtime409 = __toESM(require_jsx_runtime(), 1);
function SeparatedInputControls({
minimumCustomValue,
onChange,
onMouseOut,
onMouseOver,
sides: sides2,
spacingSizes,
type,
values
}) {
const filteredSides = sides2?.length ? ALL_SIDES.filter((side) => sides2.includes(side)) : ALL_SIDES;
const createHandleOnChange = (side) => (next) => {
const nextValues = {
...Object.keys(values).reduce((acc, key) => {
acc[key] = getPresetValueFromCustomValue(
values[key],
spacingSizes
);
return acc;
}, {})
};
nextValues[side] = next;
onChange(nextValues);
};
return /* @__PURE__ */ (0, import_jsx_runtime409.jsx)(import_jsx_runtime409.Fragment, { children: filteredSides.map((side) => {
return /* @__PURE__ */ (0, import_jsx_runtime409.jsx)(
SpacingInputControl,
{
icon: ICONS[side],
label: LABELS[side],
minimumCustomValue,
onChange: createHandleOnChange(side),
onMouseOut,
onMouseOver,
side,
spacingSizes,
type,
value: values[side],
withInputField: false
},
`spacing-sizes-control-${side}`
);
}) });
}
// packages/block-editor/build-module/components/spacing-sizes-control/input-controls/single.mjs
var import_jsx_runtime410 = __toESM(require_jsx_runtime(), 1);
function SingleInputControl({
minimumCustomValue,
onChange,
onMouseOut,
onMouseOver,
showSideInLabel,
side,
spacingSizes,
type,
values
}) {
const createHandleOnChange = (currentSide) => (next) => {
const nextValues = {
...Object.keys(values).reduce((acc, key) => {
acc[key] = getPresetValueFromCustomValue(
values[key],
spacingSizes
);
return acc;
}, {})
};
nextValues[currentSide] = next;
onChange(nextValues);
};
return /* @__PURE__ */ (0, import_jsx_runtime410.jsx)(
SpacingInputControl,
{
label: LABELS[side],
minimumCustomValue,
onChange: createHandleOnChange(side),
onMouseOut,
onMouseOver,
showSideInLabel,
side,
spacingSizes,
type,
value: values[side],
withInputField: false
}
);
}
// packages/block-editor/build-module/components/spacing-sizes-control/linked-button.mjs
var import_components186 = __toESM(require_components(), 1);
var import_i18n176 = __toESM(require_i18n(), 1);
var import_jsx_runtime411 = __toESM(require_jsx_runtime(), 1);
function LinkedButton2({ isLinked, ...props }) {
const label = isLinked ? (0, import_i18n176.__)("Unlink sides") : (0, import_i18n176.__)("Link sides");
return /* @__PURE__ */ (0, import_jsx_runtime411.jsx)(
import_components186.Button,
{
...props,
size: "small",
icon: isLinked ? link_default : link_off_default,
iconSize: 24,
label
}
);
}
// packages/block-editor/build-module/components/spacing-sizes-control/index.mjs
var import_jsx_runtime412 = __toESM(require_jsx_runtime(), 1);
function SpacingSizesControl({
inputProps,
label: labelProp,
minimumCustomValue = 0,
onChange,
onMouseOut,
onMouseOver,
showSideInLabel = true,
sides: sides2 = ALL_SIDES,
useSelect: useSelect178,
values
}) {
const spacingSizes = useSpacingSizes();
const inputValues = values || DEFAULT_VALUES;
const hasOneSide = sides2?.length === 1;
const hasOnlyAxialSides = sides2?.includes("horizontal") && sides2?.includes("vertical") && sides2?.length === 2;
const [view, setView] = (0, import_element242.useState)(getInitialView(inputValues, sides2));
const toggleLinked = () => {
setView(view === VIEWS.axial ? VIEWS.custom : VIEWS.axial);
};
const handleOnChange = (nextValue) => {
const newValues = { ...values, ...nextValue };
onChange(newValues);
};
const inputControlProps = {
...inputProps,
minimumCustomValue,
onChange: handleOnChange,
onMouseOut,
onMouseOver,
sides: sides2,
spacingSizes,
type: labelProp,
useSelect: useSelect178,
values: inputValues
};
const renderControls = () => {
if (view === VIEWS.axial) {
return /* @__PURE__ */ (0, import_jsx_runtime412.jsx)(AxialInputControls, { ...inputControlProps });
}
if (view === VIEWS.custom) {
return /* @__PURE__ */ (0, import_jsx_runtime412.jsx)(SeparatedInputControls, { ...inputControlProps });
}
return /* @__PURE__ */ (0, import_jsx_runtime412.jsx)(
SingleInputControl,
{
side: view,
...inputControlProps,
showSideInLabel
}
);
};
const sideLabel = ALL_SIDES.includes(view) && showSideInLabel ? LABELS[view] : "";
const label = (0, import_i18n177.sprintf)(
// translators: 1: The side of the block being modified (top, bottom, left etc.). 2. Type of spacing being modified (padding, margin, etc).
(0, import_i18n177._x)("%1$s %2$s", "spacing"),
labelProp,
sideLabel
).trim();
return /* @__PURE__ */ (0, import_jsx_runtime412.jsxs)("fieldset", { className: "spacing-sizes-control", children: [
/* @__PURE__ */ (0, import_jsx_runtime412.jsxs)(import_components187.__experimentalHStack, { className: "spacing-sizes-control__header", children: [
/* @__PURE__ */ (0, import_jsx_runtime412.jsx)(
import_components187.BaseControl.VisualLabel,
{
as: "legend",
className: "spacing-sizes-control__label",
children: label
}
),
!hasOneSide && !hasOnlyAxialSides && /* @__PURE__ */ (0, import_jsx_runtime412.jsx)(
LinkedButton2,
{
label: labelProp,
onClick: toggleLinked,
isLinked: view === VIEWS.axial
}
)
] }),
/* @__PURE__ */ (0, import_jsx_runtime412.jsx)(import_components187.__experimentalVStack, { spacing: 0.5, children: renderControls() })
] });
}
// packages/block-editor/build-module/components/preview-options/index.mjs
var import_deprecated28 = __toESM(require_deprecated(), 1);
function PreviewOptions() {
(0, import_deprecated28.default)("wp.blockEditor.PreviewOptions", {
version: "6.5"
});
return null;
}
// packages/block-editor/build-module/components/use-resize-canvas/index.mjs
var import_deprecated29 = __toESM(require_deprecated(), 1);
function useResizeCanvas() {
(0, import_deprecated29.default)("wp.blockEditor.useResizeCanvas", {
since: "7.1",
hint: "Device preview is now handled by the editor canvas. This hook no longer does anything."
});
}
// packages/block-editor/build-module/components/block-inspector/index.mjs
var import_i18n212 = __toESM(require_i18n(), 1);
var import_blocks103 = __toESM(require_blocks(), 1);
var import_components222 = __toESM(require_components(), 1);
var import_data177 = __toESM(require_data(), 1);
var import_element268 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/block-inspector/edit-contents.mjs
var import_components188 = __toESM(require_components(), 1);
var import_i18n178 = __toESM(require_i18n(), 1);
var import_data156 = __toESM(require_data(), 1);
var import_blocks89 = __toESM(require_blocks(), 1);
var import_jsx_runtime413 = __toESM(require_jsx_runtime(), 1);
function IsolatedEditButton({
block,
onNavigateToEntityRecord,
isSyncedPattern,
isTemplatePartBlock
}) {
const blockAttributes = block?.attributes || {};
const handleClick = () => {
if (isSyncedPattern) {
onNavigateToEntityRecord({
postId: blockAttributes.ref,
postType: "wp_block"
});
} else if (isTemplatePartBlock) {
const { theme: theme2, slug } = blockAttributes;
const templatePartId = theme2 && slug ? `${theme2}//${slug}` : null;
if (templatePartId) {
onNavigateToEntityRecord({
postId: templatePartId,
postType: "wp_template_part"
});
}
}
};
return /* @__PURE__ */ (0, import_jsx_runtime413.jsx)(import_components188.__experimentalVStack, { className: "block-editor-block-inspector-edit-contents", expanded: true, children: /* @__PURE__ */ (0, import_jsx_runtime413.jsx)(
import_components188.Button,
{
className: "block-editor-block-inspector-edit-contents__button",
__next40pxDefaultSize: true,
variant: "secondary",
onClick: handleClick,
children: (0, import_i18n178.__)("Edit original")
}
) });
}
function InlineEditButton({
clientId,
editedContentOnlySection: editedContentOnlySection2,
editContentOnlySection: editContentOnlySection2,
stopEditingContentOnlySection: stopEditingContentOnlySection2
}) {
const { selectBlock: selectBlock2 } = (0, import_data156.useDispatch)(store);
const handleClick = () => {
if (!editedContentOnlySection2) {
editContentOnlySection2(clientId);
selectBlock2(clientId);
} else {
stopEditingContentOnlySection2();
selectBlock2(clientId);
}
};
return /* @__PURE__ */ (0, import_jsx_runtime413.jsx)(import_components188.__experimentalVStack, { className: "block-editor-block-inspector-edit-contents", expanded: true, children: /* @__PURE__ */ (0, import_jsx_runtime413.jsx)(
import_components188.Button,
{
className: "block-editor-block-inspector-edit-contents__button",
__next40pxDefaultSize: true,
variant: "secondary",
onClick: handleClick,
children: editedContentOnlySection2 ? (
/* translators: Button label to leave pattern editing mode. */
(0, import_i18n178.__)("Exit pattern")
) : (
/* translators: Button label to enter pattern editing mode. */
(0, import_i18n178.__)("Edit pattern")
)
}
) });
}
function EditContents({ clientId }) {
const {
isWithinSection,
isWithinEditedSection,
editedContentOnlySection: editedContentOnlySection2,
editContentOnlySection: editContentOnlySection2,
stopEditingContentOnlySection: stopEditingContentOnlySection2
} = useContentOnlySectionEdit(clientId);
const { block, onNavigateToEntityRecord, canEdit } = (0, import_data156.useSelect)(
(select3) => {
const { getBlock: getBlock2, getSettings: getSettings7, canEditBlock: canEditBlock2 } = select3(store);
return {
block: getBlock2(clientId),
onNavigateToEntityRecord: getSettings7().onNavigateToEntityRecord,
canEdit: canEditBlock2(clientId)
};
},
[clientId]
);
if (!canEdit || !isWithinSection && !isWithinEditedSection) {
return null;
}
const isSyncedPattern = (0, import_blocks89.isReusableBlock)(block);
const isTemplatePartBlock = (0, import_blocks89.isTemplatePart)(block);
const shouldUseIsolatedEditor = (isSyncedPattern || isTemplatePartBlock) && onNavigateToEntityRecord;
if (shouldUseIsolatedEditor) {
return /* @__PURE__ */ (0, import_jsx_runtime413.jsx)(
IsolatedEditButton,
{
block,
onNavigateToEntityRecord,
isSyncedPattern,
isTemplatePartBlock
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime413.jsx)(
InlineEditButton,
{
clientId,
editedContentOnlySection: editedContentOnlySection2,
editContentOnlySection: editContentOnlySection2,
stopEditingContentOnlySection: stopEditingContentOnlySection2
}
);
}
// packages/block-editor/build-module/components/skip-to-selected-block/index.mjs
var import_data157 = __toESM(require_data(), 1);
var import_i18n179 = __toESM(require_i18n(), 1);
var import_components189 = __toESM(require_components(), 1);
var import_element243 = __toESM(require_element(), 1);
var import_jsx_runtime414 = __toESM(require_jsx_runtime(), 1);
function SkipToSelectedBlock() {
const selectedBlockClientId = (0, import_data157.useSelect)(
(select3) => select3(store).getBlockSelectionStart(),
[]
);
const ref = (0, import_element243.useRef)();
useBlockElementRef(selectedBlockClientId, ref);
const onClick = () => {
ref.current?.focus();
};
return selectedBlockClientId ? /* @__PURE__ */ (0, import_jsx_runtime414.jsx)(
import_components189.Button,
{
__next40pxDefaultSize: true,
variant: "secondary",
className: "block-editor-skip-to-selected-block",
onClick,
children: (0, import_i18n179.__)("Skip to the selected block")
}
) : null;
}
// packages/block-editor/build-module/components/multi-selection-inspector/index.mjs
var import_i18n180 = __toESM(require_i18n(), 1);
var import_data158 = __toESM(require_data(), 1);
var import_components190 = __toESM(require_components(), 1);
var import_jsx_runtime415 = __toESM(require_jsx_runtime(), 1);
function MultiSelectionInspector() {
const selectedBlockCount = (0, import_data158.useSelect)(
(select3) => select3(store).getSelectedBlockCount(),
[]
);
return /* @__PURE__ */ (0, import_jsx_runtime415.jsxs)(
import_components190.__experimentalHStack,
{
justify: "flex-start",
spacing: 2,
className: "block-editor-multi-selection-inspector__card",
children: [
/* @__PURE__ */ (0, import_jsx_runtime415.jsx)(block_icon_default, { icon: copy_default, showColors: true }),
/* @__PURE__ */ (0, import_jsx_runtime415.jsx)("div", { className: "block-editor-multi-selection-inspector__card-title", children: (0, import_i18n180.sprintf)(
/* translators: %d: number of blocks */
(0, import_i18n180._n)("%d Block", "%d Blocks", selectedBlockCount),
selectedBlockCount
) })
]
}
);
}
// packages/block-editor/build-module/components/block-inspector/inspector-pre-tabs-slot-fill.mjs
var import_components191 = __toESM(require_components(), 1);
var BlockInspectorPreTabsKey = /* @__PURE__ */ Symbol("BlockInspectorPreTabs");
var {
Fill: BlockInspectorPreTabsFill,
Slot: BlockInspectorPreTabsSlot
} = (0, import_components191.createSlotFill)(BlockInspectorPreTabsKey);
// packages/block-editor/build-module/components/inspector-controls-tabs/index.mjs
var import_components219 = __toESM(require_components(), 1);
var import_element266 = __toESM(require_element(), 1);
var import_preferences5 = __toESM(require_preferences(), 1);
var import_data174 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/inspector-controls-tabs/utils.mjs
var import_i18n181 = __toESM(require_i18n(), 1);
var TAB_SETTINGS = {
name: "settings",
title: (0, import_i18n181.__)("Settings"),
value: "settings",
icon: cog_default
};
var TAB_STYLES = {
name: "styles",
title: (0, import_i18n181.__)("Styles"),
value: "styles",
icon: styles_default
};
var TAB_CONTENT = {
name: "content",
title: (0, import_i18n181.__)("Content"),
value: "content",
icon: page_default
};
var TAB_LIST_VIEW = {
name: "list",
title: (0, import_i18n181.__)("List View"),
value: "list-view",
icon: list_view_default
};
// packages/block-editor/build-module/components/inspector-controls-tabs/settings-tab.mjs
var import_components193 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/inspector-controls-tabs/advanced-controls-panel.mjs
var import_components192 = __toESM(require_components(), 1);
var import_i18n182 = __toESM(require_i18n(), 1);
var import_jsx_runtime416 = __toESM(require_jsx_runtime(), 1);
var AdvancedControls = ({ initialOpen = false }) => {
const fills = (0, import_components192.__experimentalUseSlotFills)(InspectorAdvancedControls.slotName);
const privateFills = (0, import_components192.__experimentalUseSlotFills)(
PrivateInspectorControlsAllowedBlocks.name
);
const hasFills = Boolean(fills && fills.length);
const hasPrivateFills = Boolean(privateFills && privateFills.length);
if (!hasFills && !hasPrivateFills) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime416.jsxs)(
import_components192.PanelBody,
{
className: "block-editor-block-inspector__advanced",
title: (0, import_i18n182.__)("Advanced"),
initialOpen,
children: [
/* @__PURE__ */ (0, import_jsx_runtime416.jsx)(inspector_controls_default.Slot, { group: "advanced" }),
/* @__PURE__ */ (0, import_jsx_runtime416.jsx)(PrivateInspectorControlsAllowedBlocks.Slot, {})
]
}
);
};
var advanced_controls_panel_default = AdvancedControls;
// packages/block-editor/build-module/components/inspector-controls-tabs/settings-tab.mjs
var import_jsx_runtime417 = __toESM(require_jsx_runtime(), 1);
var SettingsTab = ({ showAdvancedControls = false }) => {
const defaultFills = (0, import_components193.__experimentalUseSlotFills)(groups_default.default.name);
const bindingsFills = (0, import_components193.__experimentalUseSlotFills)(groups_default.bindings.name);
const hasOtherFills = !!defaultFills?.length || !!bindingsFills?.length;
return /* @__PURE__ */ (0, import_jsx_runtime417.jsxs)(import_jsx_runtime417.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime417.jsx)(inspector_controls_default.Slot, {}),
/* @__PURE__ */ (0, import_jsx_runtime417.jsx)(inspector_controls_default.Slot, { group: "bindings" }),
showAdvancedControls && /* @__PURE__ */ (0, import_jsx_runtime417.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime417.jsx)(advanced_controls_panel_default, { initialOpen: !hasOtherFills }) })
] });
};
var settings_tab_default = SettingsTab;
// packages/block-editor/build-module/components/inspector-controls-tabs/styles-tab.mjs
var import_i18n209 = __toESM(require_i18n(), 1);
var import_data172 = __toESM(require_data(), 1);
var import_element265 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/inspector-controls-tabs/position-controls-panel.mjs
var import_components194 = __toESM(require_components(), 1);
var import_data159 = __toESM(require_data(), 1);
var import_i18n183 = __toESM(require_i18n(), 1);
var import_jsx_runtime418 = __toESM(require_jsx_runtime(), 1);
var PositionControlsPanel = () => {
const { selectedClientIds, selectedBlocks, hasPositionAttribute } = (0, import_data159.useSelect)((select3) => {
const { getBlocksByClientId: getBlocksByClientId2, getSelectedBlockClientIds: getSelectedBlockClientIds2 } = select3(store);
const selectedBlockClientIds = getSelectedBlockClientIds2();
const _selectedBlocks = getBlocksByClientId2(
selectedBlockClientIds
);
return {
selectedClientIds: selectedBlockClientIds,
selectedBlocks: _selectedBlocks,
hasPositionAttribute: _selectedBlocks?.some(
({ attributes }) => !!attributes?.style?.position?.type
)
};
}, []);
const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data159.useDispatch)(store);
const dropdownMenuProps = useToolsPanelDropdownMenuProps();
function resetPosition() {
if (!selectedClientIds?.length || !selectedBlocks?.length) {
return;
}
const attributesByClientId = Object.fromEntries(
selectedBlocks?.map(({ clientId, attributes }) => [
clientId,
{
style: cleanEmptyObject({
...attributes?.style,
position: {
...attributes?.style?.position,
type: void 0,
top: void 0,
right: void 0,
bottom: void 0,
left: void 0
}
})
}
])
);
updateBlockAttributes2(selectedClientIds, attributesByClientId, true);
}
return /* @__PURE__ */ (0, import_jsx_runtime418.jsx)(
import_components194.__experimentalToolsPanel,
{
className: "block-editor-block-inspector__position",
label: (0, import_i18n183.__)("Position"),
resetAll: resetPosition,
dropdownMenuProps,
children: /* @__PURE__ */ (0, import_jsx_runtime418.jsx)(
import_components194.__experimentalToolsPanelItem,
{
isShownByDefault: hasPositionAttribute,
label: (0, import_i18n183.__)("Position"),
hasValue: () => hasPositionAttribute,
onDeselect: resetPosition,
children: /* @__PURE__ */ (0, import_jsx_runtime418.jsx)(inspector_controls_default.Slot, { group: "position" })
}
)
}
);
};
var PositionControls = () => {
const fills = (0, import_components194.__experimentalUseSlotFills)(groups_default.position.name);
const hasFills = Boolean(fills && fills.length);
if (!hasFills) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime418.jsx)(PositionControlsPanel, {});
};
var position_controls_panel_default = PositionControls;
// packages/block-editor/build-module/hooks/border.mjs
var import_blocks91 = __toESM(require_blocks(), 1);
var import_components212 = __toESM(require_components(), 1);
var import_element257 = __toESM(require_element(), 1);
var import_hooks13 = __toESM(require_hooks(), 1);
var import_data164 = __toESM(require_data(), 1);
var import_i18n202 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/global-styles/index.mjs
var global_styles_exports = {};
__export(global_styles_exports, {
AdvancedPanel: () => AdvancedPanel,
BackgroundPanel: () => BackgroundImagePanel2,
BorderPanel: () => BorderPanel,
ColorPanel: () => ColorPanel,
DimensionsPanel: () => DimensionsPanel,
FiltersPanel: () => FiltersPanel,
ImageSettingsPanel: () => ImageSettingsPanel,
StateControl: () => StateControl,
StateControlBadges: () => StateControlBadges,
TypographyPanel: () => TypographyPanel,
useHasBackgroundPanel: () => useHasBackgroundPanel,
useHasBorderPanel: () => useHasBorderPanel,
useHasBorderPanelControls: () => useHasBorderPanelControls,
useHasColorPanel: () => useHasColorPanel,
useHasDimensionsPanel: () => useHasDimensionsPanel,
useHasFiltersPanel: () => useHasFiltersPanel,
useHasImageSettingsPanel: () => useHasImageSettingsPanel,
useHasTypographyPanel: () => useHasTypographyPanel,
useSettingsForBlockElement: () => useSettingsForBlockElement
});
// packages/block-editor/build-module/components/global-styles/hooks.mjs
var import_element244 = __toESM(require_element(), 1);
var import_data160 = __toESM(require_data(), 1);
var import_blocks90 = __toESM(require_blocks(), 1);
var import_i18n184 = __toESM(require_i18n(), 1);
function useSettingsForBlockElement(parentSettings, blockName, element) {
const { supportedStyles, supports } = (0, import_data160.useSelect)(
(select3) => {
return {
supportedStyles: unlock(
select3(import_blocks90.store)
).getSupportedStyles(blockName, element),
supports: select3(import_blocks90.store).getBlockType(blockName)?.supports
};
},
[blockName, element]
);
return (0, import_element244.useMemo)(() => {
const updatedSettings = { ...parentSettings };
if (!supportedStyles.includes("fontSize")) {
updatedSettings.typography = {
...updatedSettings.typography,
fontSizes: {},
customFontSize: false,
defaultFontSizes: false
};
}
if (!supportedStyles.includes("fontFamily")) {
updatedSettings.typography = {
...updatedSettings.typography,
fontFamilies: {}
};
}
updatedSettings.color = {
...updatedSettings.color,
text: updatedSettings.color?.text && supportedStyles.includes("color"),
background: updatedSettings.color?.background && (supportedStyles.includes("background") || supportedStyles.includes("backgroundColor")),
button: updatedSettings.color?.button && supportedStyles.includes("buttonColor"),
heading: updatedSettings.color?.heading && supportedStyles.includes("headingColor"),
link: updatedSettings.color?.link && supportedStyles.includes("linkColor"),
caption: updatedSettings.color?.caption && supportedStyles.includes("captionColor")
};
if (!supportedStyles.includes("background") && !supportedStyles.includes("backgroundGradient")) {
updatedSettings.color.gradients = [];
updatedSettings.color.customGradient = false;
}
if (!supportedStyles.includes("filter")) {
updatedSettings.color.defaultDuotone = false;
updatedSettings.color.customDuotone = false;
}
[
"lineHeight",
"fontStyle",
"fontWeight",
"letterSpacing",
"textAlign",
"textTransform",
"textDecoration",
"textIndent",
"writingMode"
].forEach((key) => {
if (!supportedStyles.includes(key)) {
updatedSettings.typography = {
...updatedSettings.typography,
[key]: false
};
}
});
if (supportedStyles.includes("textIndent")) {
updatedSettings.typography = {
...updatedSettings.typography,
textIndent: updatedSettings.typography?.textIndent ?? "subsequent"
};
}
if (!supportedStyles.includes("columnCount")) {
updatedSettings.typography = {
...updatedSettings.typography,
textColumns: false
};
}
["contentSize", "wideSize"].forEach((key) => {
if (!supportedStyles.includes(key)) {
updatedSettings.layout = {
...updatedSettings.layout,
[key]: false
};
}
});
["padding", "margin", "blockGap"].forEach((key) => {
if (!supportedStyles.includes(key)) {
updatedSettings.spacing = {
...updatedSettings.spacing,
[key]: false
};
}
const sides2 = Array.isArray(supports?.spacing?.[key]) ? supports?.spacing?.[key] : supports?.spacing?.[key]?.sides;
if (sides2?.length && updatedSettings.spacing?.[key]) {
updatedSettings.spacing = {
...updatedSettings.spacing,
[key]: {
...updatedSettings.spacing?.[key],
sides: sides2
}
};
}
});
["aspectRatio", "height", "minHeight", "minWidth", "width"].forEach(
(key) => {
if (!supportedStyles.includes(key)) {
updatedSettings.dimensions = {
...updatedSettings.dimensions,
[key]: false
};
}
}
);
["radius", "color", "style", "width"].forEach((key) => {
if (!supportedStyles.includes(
"border" + key.charAt(0).toUpperCase() + key.slice(1)
)) {
updatedSettings.border = {
...updatedSettings.border,
[key]: false
};
}
});
[
["backgroundImage", "backgroundImage"],
["backgroundSize", "backgroundSize"],
["backgroundGradient", "gradient"]
].forEach(([styleKey, settingKey]) => {
if (!supportedStyles.includes(styleKey)) {
updatedSettings.background = {
...updatedSettings.background,
[settingKey]: false
};
}
});
updatedSettings.shadow = supportedStyles.includes("shadow") ? updatedSettings.shadow : false;
return updatedSettings;
}, [parentSettings, supportedStyles, supports]);
}
function useColorsPerOrigin(settings2) {
const customColors = settings2?.color?.palette?.custom;
const themeColors = settings2?.color?.palette?.theme;
const defaultColors = settings2?.color?.palette?.default;
const shouldDisplayDefaultColors = settings2?.color?.defaultPalette;
return (0, import_element244.useMemo)(() => {
const result = [];
if (themeColors && themeColors.length) {
result.push({
name: (0, import_i18n184._x)(
"Theme",
"Indicates this palette comes from the theme."
),
colors: themeColors
});
}
if (shouldDisplayDefaultColors && defaultColors && defaultColors.length) {
result.push({
name: (0, import_i18n184._x)(
"Default",
"Indicates this palette comes from WordPress."
),
colors: defaultColors
});
}
if (customColors && customColors.length) {
result.push({
name: (0, import_i18n184._x)(
"Custom",
"Indicates this palette is created by the user."
),
colors: customColors
});
}
return result;
}, [
customColors,
themeColors,
defaultColors,
shouldDisplayDefaultColors
]);
}
function useGradientsPerOrigin(settings2) {
const customGradients = settings2?.color?.gradients?.custom;
const themeGradients = settings2?.color?.gradients?.theme;
const defaultGradients = settings2?.color?.gradients?.default;
const shouldDisplayDefaultGradients = settings2?.color?.defaultGradients;
return (0, import_element244.useMemo)(() => {
const result = [];
if (themeGradients && themeGradients.length) {
result.push({
name: (0, import_i18n184._x)(
"Theme",
"Indicates this palette comes from the theme."
),
gradients: themeGradients
});
}
if (shouldDisplayDefaultGradients && defaultGradients && defaultGradients.length) {
result.push({
name: (0, import_i18n184._x)(
"Default",
"Indicates this palette comes from WordPress."
),
gradients: defaultGradients
});
}
if (customGradients && customGradients.length) {
result.push({
name: (0, import_i18n184._x)(
"Custom",
"Indicates this palette is created by the user."
),
gradients: customGradients
});
}
return result;
}, [
customGradients,
themeGradients,
defaultGradients,
shouldDisplayDefaultGradients
]);
}
function useColorGradientSettings(settings2) {
const colors2 = useColorsPerOrigin(settings2);
const gradients = useGradientsPerOrigin(settings2);
const areCustomSolidsEnabled = settings2?.color?.custom;
const areCustomGradientsEnabled = settings2?.color?.customGradient;
const allColors = (0, import_element244.useMemo)(
() => colors2.flatMap(({ colors: originColors }) => originColors),
[colors2]
);
const decodeValue = (rawValue) => getValueFromVariable({ settings: settings2 }, "", rawValue);
const encodeGradientValue = (gradientValue) => {
const allGradients = gradients.flatMap(
({ gradients: originGradients }) => originGradients
);
const gradientObject = allGradients.find(
({ gradient }) => gradient === gradientValue
);
return gradientObject ? "var:preset|gradient|" + gradientObject.slug : gradientValue;
};
return {
colors: colors2,
gradients,
allColors,
areCustomSolidsEnabled,
areCustomGradientsEnabled,
hasSolidColors: colors2.length > 0 || areCustomSolidsEnabled,
hasGradientColors: gradients.length > 0 || areCustomGradientsEnabled,
decodeValue,
encodeGradientValue
};
}
// packages/block-editor/build-module/components/global-styles/typography-panel.mjs
var import_components199 = __toESM(require_components(), 1);
var import_i18n189 = __toESM(require_i18n(), 1);
var import_element248 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/text-alignment-control/index.mjs
var import_i18n185 = __toESM(require_i18n(), 1);
var import_element245 = __toESM(require_element(), 1);
var import_components195 = __toESM(require_components(), 1);
var import_jsx_runtime419 = __toESM(require_jsx_runtime(), 1);
var TEXT_ALIGNMENT_OPTIONS = [
{
label: (0, import_i18n185.__)("Align text left"),
value: "left",
icon: align_left_default
},
{
label: (0, import_i18n185.__)("Align text center"),
value: "center",
icon: align_center_default
},
{
label: (0, import_i18n185.__)("Align text right"),
value: "right",
icon: align_right_default
},
{
label: (0, import_i18n185.__)("Justify text"),
value: "justify",
icon: align_justify_default
}
];
var DEFAULT_OPTIONS = ["left", "center", "right"];
function TextAlignmentControl({
className,
value,
onChange,
options = DEFAULT_OPTIONS
}) {
const validOptions = (0, import_element245.useMemo)(
() => TEXT_ALIGNMENT_OPTIONS.filter(
(option) => options.includes(option.value)
),
[options]
);
if (!validOptions.length) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime419.jsx)(
import_components195.__experimentalToggleGroupControl,
{
isDeselectable: true,
label: (0, import_i18n185.__)("Text alignment"),
className: clsx_default(
"block-editor-text-alignment-control",
className
),
value,
onChange: (newValue) => {
onChange(newValue === value ? void 0 : newValue);
},
children: validOptions.map((option) => {
return /* @__PURE__ */ (0, import_jsx_runtime419.jsx)(
import_components195.__experimentalToggleGroupControlOptionIcon,
{
value: option.value,
icon: option.icon,
label: option.label
},
option.value
);
})
}
);
}
// packages/block-editor/build-module/components/text-indent-control/index.mjs
var import_components196 = __toESM(require_components(), 1);
var import_i18n186 = __toESM(require_i18n(), 1);
var import_jsx_runtime420 = __toESM(require_jsx_runtime(), 1);
function TextIndentControl({
value,
onChange,
__unstableInputWidth = "60px",
withSlider = false,
hasBottomMargin = false,
help,
...otherProps
}) {
const [availableUnits] = useSettings("spacing.units");
const units2 = (0, import_components196.__experimentalUseCustomUnits)({
availableUnits: availableUnits || [
"px",
"em",
"rem",
"ch",
"%",
"vw",
"vh"
],
defaultValues: { px: 16, em: 2, rem: 2, ch: 2 }
});
const [valueQuantity, valueUnit] = (0, import_components196.__experimentalParseQuantityAndUnitFromRawValue)(
value,
units2
);
const isValueUnitRelative = !!valueUnit && ["em", "rem", "%", "ch", "vw", "vh"].includes(valueUnit);
if (!withSlider) {
return /* @__PURE__ */ (0, import_jsx_runtime420.jsx)(
import_components196.__experimentalUnitControl,
{
...otherProps,
label: (0, import_i18n186.__)("Line indent"),
value,
__unstableInputWidth,
units: units2,
onChange,
help
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime420.jsxs)(import_components196.__experimentalView, { style: hasBottomMargin ? { marginBottom: 12 } : void 0, children: [
/* @__PURE__ */ (0, import_jsx_runtime420.jsx)(import_components196.BaseControl.VisualLabel, { children: (0, import_i18n186.__)("Line indent") }),
/* @__PURE__ */ (0, import_jsx_runtime420.jsxs)(import_components196.Flex, { children: [
/* @__PURE__ */ (0, import_jsx_runtime420.jsx)(import_components196.FlexItem, { isBlock: true, children: /* @__PURE__ */ (0, import_jsx_runtime420.jsx)(
import_components196.__experimentalUnitControl,
{
label: (0, import_i18n186.__)("Line indent"),
labelPosition: "top",
hideLabelFromVision: true,
value,
onChange,
units: units2,
__unstableInputWidth,
min: 0
}
) }),
withSlider && /* @__PURE__ */ (0, import_jsx_runtime420.jsx)(import_components196.FlexItem, { isBlock: true, children: /* @__PURE__ */ (0, import_jsx_runtime420.jsx)(import_components196.__experimentalSpacer, { marginX: 2, marginBottom: 0, children: /* @__PURE__ */ (0, import_jsx_runtime420.jsx)(
import_components196.RangeControl,
{
label: (0, import_i18n186.__)("Line indent"),
hideLabelFromVision: true,
value: valueQuantity,
withInputField: false,
onChange: (newValue) => {
if (newValue === void 0) {
onChange?.(void 0);
} else {
onChange?.(
newValue + (valueUnit ?? "px")
);
}
},
min: 0,
max: isValueUnitRelative ? 10 : 100,
step: isValueUnitRelative ? 0.1 : 1,
initialPosition: 0
}
) }) })
] }),
help && /* @__PURE__ */ (0, import_jsx_runtime420.jsx)("p", { className: "components-base-control__help", children: help })
] });
}
// packages/block-editor/build-module/components/global-styles/color-gradient-dropdown-item.mjs
var import_components197 = __toESM(require_components(), 1);
var import_element246 = __toESM(require_element(), 1);
var import_i18n187 = __toESM(require_i18n(), 1);
var import_jsx_runtime421 = __toESM(require_jsx_runtime(), 1);
var { Tabs: Tabs4 } = unlock(import_components197.privateApis);
function DropdownContent({
tabs,
colorGradientControlSettings,
contrastWarning
}) {
const { key: firstTabKey, ...firstTab } = tabs[0] ?? {};
const defaultTabId = tabs.find(
(tab) => tab.userValue !== void 0
)?.key;
return /* @__PURE__ */ (0, import_jsx_runtime421.jsx)(import_components197.__experimentalDropdownContentWrapper, { paddingSize: "none", children: /* @__PURE__ */ (0, import_jsx_runtime421.jsxs)("div", { className: "block-editor-panel-color-gradient-settings__dropdown-content", children: [
tabs.length === 1 && /* @__PURE__ */ (0, import_jsx_runtime421.jsx)(
ColorGradientTab,
{
...firstTab,
colorGradientControlSettings,
contrastWarning
},
firstTabKey
),
tabs.length > 1 && /* @__PURE__ */ (0, import_jsx_runtime421.jsxs)(Tabs4, { defaultTabId, children: [
/* @__PURE__ */ (0, import_jsx_runtime421.jsx)(Tabs4.TabList, { children: tabs.map((tab) => /* @__PURE__ */ (0, import_jsx_runtime421.jsx)(Tabs4.Tab, { tabId: tab.key, children: tab.label }, tab.key)) }),
tabs.map((tab) => {
const { key: tabKey, ...restTabProps } = tab;
return /* @__PURE__ */ (0, import_jsx_runtime421.jsx)(
Tabs4.TabPanel,
{
tabId: tabKey,
focusable: false,
children: /* @__PURE__ */ (0, import_jsx_runtime421.jsx)(
ColorGradientTab,
{
...restTabProps,
colorGradientControlSettings,
contrastWarning
},
tabKey
)
},
tabKey
);
})
] })
] }) });
}
var popoverProps = {
placement: "left-start",
offset: 36,
shift: true
};
var LabeledColorIndicators = ({ indicators, label }) => /* @__PURE__ */ (0, import_jsx_runtime421.jsxs)(import_components197.__experimentalHStack, { justify: "flex-start", children: [
/* @__PURE__ */ (0, import_jsx_runtime421.jsx)(import_components197.__experimentalZStack, { isLayered: false, offset: -8, children: indicators.map((indicator, index2) => /* @__PURE__ */ (0, import_jsx_runtime421.jsx)(import_components197.Flex, { expanded: false, children: /* @__PURE__ */ (0, import_jsx_runtime421.jsx)(import_components197.ColorIndicator, { colorValue: indicator }) }, index2)) }),
/* @__PURE__ */ (0, import_jsx_runtime421.jsx)(import_components197.FlexItem, { className: "block-editor-panel-color-gradient-settings__color-name", children: label })
] });
function ColorGradientTab({
isGradient,
inheritedValue,
inheritedSlug,
userValue,
setValue,
colorGradientControlSettings,
contrastWarning
}) {
return /* @__PURE__ */ (0, import_jsx_runtime421.jsx)(
control_default,
{
...colorGradientControlSettings,
showTitle: false,
enableAlpha: true,
__experimentalIsRenderedInSidebar: true,
colorValue: isGradient ? void 0 : inheritedValue,
colorSlug: isGradient ? void 0 : inheritedSlug,
gradientValue: isGradient ? inheritedValue : void 0,
onColorChange: isGradient ? void 0 : setValue,
onGradientChange: isGradient ? setValue : void 0,
clearable: inheritedValue === userValue,
headingLevel: 3,
noticeProps: !isGradient && contrastWarning ? {
children: contrastWarning,
status: "warning",
spokenMessage: null,
className: "block-editor-panel-color-gradient-settings__contrast-notice"
} : void 0
}
);
}
function ColorGradientDropdownItem({
label,
hasValue,
resetValue,
isShownByDefault,
indicators,
tabs,
colorGradientControlSettings,
panelId,
contrastWarning,
className = "block-editor-tools-panel-color-gradient-settings__item"
}) {
const colorGradientDropdownButtonRef = (0, import_element246.useRef)(void 0);
return /* @__PURE__ */ (0, import_jsx_runtime421.jsx)(
import_components197.__experimentalToolsPanelItem,
{
className: clsx_default("block-editor-color-gradient-item", className),
hasValue,
label,
onDeselect: resetValue,
isShownByDefault,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime421.jsx)(
import_components197.Dropdown,
{
popoverProps,
className: "block-editor-tools-panel-color-gradient-settings__dropdown",
renderToggle: ({ onToggle, isOpen }) => {
const toggleProps = {
onClick: onToggle,
className: clsx_default(
"block-editor-panel-color-gradient-settings__dropdown",
{
"is-open": isOpen,
"has-contrast-warning": !!contrastWarning
}
),
"aria-expanded": isOpen,
ref: colorGradientDropdownButtonRef
};
return /* @__PURE__ */ (0, import_jsx_runtime421.jsxs)(import_jsx_runtime421.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime421.jsx)(import_components197.Button, { ...toggleProps, __next40pxDefaultSize: true, children: /* @__PURE__ */ (0, import_jsx_runtime421.jsx)(
LabeledColorIndicators,
{
indicators,
label
}
) }),
hasValue() && /* @__PURE__ */ (0, import_jsx_runtime421.jsx)(
import_components197.Button,
{
__next40pxDefaultSize: true,
label: (0, import_i18n187.__)("Reset"),
className: "block-editor-panel-color-gradient-settings__reset",
size: "small",
icon: reset_default,
onClick: () => {
resetValue();
if (isOpen) {
onToggle();
}
colorGradientDropdownButtonRef.current?.focus();
}
}
),
contrastWarning && // An icon-only warning that stays visible while a
// contrast warning is in effect. It is not a menu;
// activating it opens the color picker popover where
// the full warning notice is shown, so the indicator
// doubles as a shortcut to where the issue is fixed.
/* @__PURE__ */ (0, import_jsx_runtime421.jsx)(
import_components197.Button,
{
__next40pxDefaultSize: true,
size: "small",
icon: caution_default,
label: (0, import_i18n187.__)("Low contrast"),
className: "block-editor-panel-color-gradient-settings__contrast-warning",
"aria-expanded": isOpen,
onClick: onToggle
}
)
] });
},
renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime421.jsx)(
DropdownContent,
{
tabs,
colorGradientControlSettings,
contrastWarning
}
)
}
)
}
);
}
// packages/block-editor/build-module/components/global-styles/color-panel.mjs
var import_components198 = __toESM(require_components(), 1);
var import_element247 = __toESM(require_element(), 1);
var import_i18n188 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/utils/color-values.mjs
function extractPresetSlug(rawValue, type) {
if (typeof rawValue !== "string") {
return void 0;
}
const userPrefix = `var:preset|${type}|`;
if (rawValue.startsWith(userPrefix)) {
return rawValue.slice(userPrefix.length);
}
const cssVarPrefix = `--wp--preset--${type}--`;
const themeFormatMatch = rawValue.match(
new RegExp(`^var\\(${cssVarPrefix}([^)]+)\\)$`)
);
return themeFormatMatch?.[1];
}
function encodeColorValueWithPalette(allColors, colorValue, slug) {
if (slug) {
return "var:preset|color|" + slug;
}
const colorObject = allColors.find(({ color }) => color === colorValue);
return colorObject ? "var:preset|color|" + colorObject.slug : colorValue;
}
// packages/block-editor/build-module/components/global-styles/color-panel.mjs
var import_jsx_runtime422 = __toESM(require_jsx_runtime(), 1);
function useHasColorPanel(settings2) {
const hasLinkPanel = useHasLinkPanel(settings2);
const hasHeadingPanel = useHasHeadingPanel(settings2);
const hasButtonPanel = useHasButtonPanel(settings2);
const hasCaptionPanel = useHasCaptionPanel(settings2);
return hasLinkPanel || hasHeadingPanel || hasButtonPanel || hasCaptionPanel;
}
function useHasTextPanel(settings2) {
const colors2 = useColorsPerOrigin(settings2);
return settings2?.color?.text && (colors2?.length > 0 || settings2?.color?.custom);
}
function useHasLinkPanel(settings2) {
const colors2 = useColorsPerOrigin(settings2);
return settings2?.color?.link && (colors2?.length > 0 || settings2?.color?.custom);
}
function useHasCaptionPanel(settings2) {
const colors2 = useColorsPerOrigin(settings2);
return settings2?.color?.caption && (colors2?.length > 0 || settings2?.color?.custom);
}
function useHasHeadingPanel(settings2) {
const colors2 = useColorsPerOrigin(settings2);
const gradients = useGradientsPerOrigin(settings2);
return settings2?.color?.heading && (colors2?.length > 0 || settings2?.color?.custom || gradients?.length > 0 || settings2?.color?.customGradient);
}
function useHasButtonPanel(settings2) {
const colors2 = useColorsPerOrigin(settings2);
const gradients = useGradientsPerOrigin(settings2);
return settings2?.color?.button && (colors2?.length > 0 || settings2?.color?.custom || gradients?.length > 0 || settings2?.color?.customGradient);
}
function useHasBackgroundColorPanel(settings2) {
const colors2 = useColorsPerOrigin(settings2);
const gradients = useGradientsPerOrigin(settings2);
return settings2?.color?.background && (colors2?.length > 0 || settings2?.color?.custom || gradients?.length > 0 || settings2?.color?.customGradient);
}
function ColorToolsPanel({
resetAllFilter,
onChange,
value,
panelId,
children,
label
}) {
const dropdownMenuProps = useToolsPanelDropdownMenuProps();
const resetAll = () => {
const updatedValue = resetAllFilter(value);
onChange(updatedValue);
};
return /* @__PURE__ */ (0, import_jsx_runtime422.jsx)(
import_components198.__experimentalToolsPanel,
{
label: label || (0, import_i18n188.__)("Elements"),
resetAll,
panelId,
hasInnerWrapper: true,
headingLevel: 3,
className: "color-block-support-panel",
__experimentalFirstVisibleItemClass: "first",
__experimentalLastVisibleItemClass: "last",
dropdownMenuProps,
children: /* @__PURE__ */ (0, import_jsx_runtime422.jsx)("div", { className: "color-block-support-panel__inner-wrapper", children })
}
);
}
var DEFAULT_CONTROLS3 = {
link: true,
heading: true,
button: true,
caption: true
};
function ColorPanel({
as: Wrapper = ColorToolsPanel,
value,
onChange,
inheritedValue = value,
settings: settings2,
panelId,
defaultControls = DEFAULT_CONTROLS3,
label,
children,
contrastWarning
}) {
const {
colors: colors2,
gradients,
areCustomSolidsEnabled,
areCustomGradientsEnabled,
hasSolidColors,
hasGradientColors,
allColors,
decodeValue,
encodeGradientValue
} = useColorGradientSettings(settings2);
const showLinkPanel = useHasLinkPanel(settings2);
const linkColor = decodeValue(
inheritedValue?.elements?.link?.color?.text
);
const userLinkColor = decodeValue(value?.elements?.link?.color?.text);
const setLinkColor = (newColor, newSlug) => {
onChange(
setImmutably2(
value,
["elements", "link", "color", "text"],
encodeColorValueWithPalette(allColors, newColor, newSlug)
)
);
};
const hoverLinkColor = decodeValue(
inheritedValue?.elements?.link?.[":hover"]?.color?.text
);
const userHoverLinkColor = decodeValue(
value?.elements?.link?.[":hover"]?.color?.text
);
const setHoverLinkColor = (newColor, newSlug) => {
onChange(
setImmutably2(
value,
["elements", "link", ":hover", "color", "text"],
encodeColorValueWithPalette(allColors, newColor, newSlug)
)
);
};
const hasLink = () => !!userLinkColor || !!userHoverLinkColor;
const resetLink = () => {
let newValue = setImmutably2(
value,
["elements", "link", ":hover", "color", "text"],
void 0
);
newValue = setImmutably2(
newValue,
["elements", "link", "color", "text"],
void 0
);
onChange(newValue);
};
const showCaptionPanel = useHasCaptionPanel(settings2);
const showButtonPanel = useHasButtonPanel(settings2);
const showHeadingPanel = useHasHeadingPanel(settings2);
const elements = (0, import_element247.useMemo)(
() => [
{
name: "caption",
label: (0, import_i18n188.__)("Captions"),
showPanel: showCaptionPanel
},
{
name: "button",
label: (0, import_i18n188.__)("Button"),
showPanel: showButtonPanel
},
{
name: "heading",
label: (0, import_i18n188.__)("Heading"),
showPanel: showHeadingPanel
},
{
name: "h1",
label: (0, import_i18n188.__)("H1"),
showPanel: showHeadingPanel
},
{
name: "h2",
label: (0, import_i18n188.__)("H2"),
showPanel: showHeadingPanel
},
{
name: "h3",
label: (0, import_i18n188.__)("H3"),
showPanel: showHeadingPanel
},
{
name: "h4",
label: (0, import_i18n188.__)("H4"),
showPanel: showHeadingPanel
},
{
name: "h5",
label: (0, import_i18n188.__)("H5"),
showPanel: showHeadingPanel
},
{
name: "h6",
label: (0, import_i18n188.__)("H6"),
showPanel: showHeadingPanel
}
],
[showCaptionPanel, showButtonPanel, showHeadingPanel]
);
const resetAllFilter = (0, import_element247.useCallback)(
(previousValue) => {
return {
...previousValue,
elements: {
...previousValue?.elements,
link: {
...previousValue?.elements?.link,
color: void 0,
":hover": {
color: void 0
}
},
...elements.reduce((acc, element) => {
return {
...acc,
[element.name]: {
...previousValue?.elements?.[element.name],
color: void 0
}
};
}, {})
}
};
},
[elements]
);
const items = [
showLinkPanel && {
key: "link",
label: (0, import_i18n188.__)("Link"),
hasValue: hasLink,
resetValue: resetLink,
isShownByDefault: defaultControls.link,
indicators: [linkColor, hoverLinkColor],
contrastWarning,
tabs: [
{
key: "link",
label: (0, import_i18n188.__)("Default"),
inheritedValue: linkColor,
inheritedSlug: extractPresetSlug(
inheritedValue?.elements?.link?.color?.text,
"color"
),
setValue: setLinkColor,
userValue: userLinkColor
},
{
key: "hover",
label: (0, import_i18n188.__)("Hover"),
inheritedValue: hoverLinkColor,
inheritedSlug: extractPresetSlug(
inheritedValue?.elements?.link?.[":hover"]?.color?.text,
"color"
),
setValue: setHoverLinkColor,
userValue: userHoverLinkColor
}
]
}
].filter(Boolean);
elements.forEach(({ name, label: elementLabel, showPanel }) => {
if (!showPanel) {
return;
}
const elementBackgroundColor = decodeValue(
inheritedValue?.elements?.[name]?.color?.background
);
const elementGradient = decodeValue(
inheritedValue?.elements?.[name]?.color?.gradient
);
const elementTextColor = decodeValue(
inheritedValue?.elements?.[name]?.color?.text
);
const elementBackgroundUserColor = decodeValue(
value?.elements?.[name]?.color?.background
);
const elementGradientUserColor = decodeValue(
value?.elements?.[name]?.color?.gradient
);
const elementTextUserColor = decodeValue(
value?.elements?.[name]?.color?.text
);
const hasElement = () => !!(elementTextUserColor || elementBackgroundUserColor || elementGradientUserColor);
const resetElement = () => {
const newValue = setImmutably2(
value,
["elements", name, "color", "background"],
void 0
);
newValue.elements[name].color.gradient = void 0;
newValue.elements[name].color.text = void 0;
onChange(newValue);
};
const setElementTextColor = (newTextColor, newSlug) => {
onChange(
setImmutably2(
value,
["elements", name, "color", "text"],
encodeColorValueWithPalette(
allColors,
newTextColor,
newSlug
)
)
);
};
const setElementBackgroundColor = (newBackgroundColor, newSlug) => {
const newValue = setImmutably2(
value,
["elements", name, "color", "background"],
encodeColorValueWithPalette(
allColors,
newBackgroundColor,
newSlug
)
);
newValue.elements[name].color.gradient = void 0;
onChange(newValue);
};
const setElementGradient = (newGradient) => {
const newValue = setImmutably2(
value,
["elements", name, "color", "gradient"],
encodeGradientValue(newGradient)
);
newValue.elements[name].color.background = void 0;
onChange(newValue);
};
const supportsBackground = name !== "caption";
items.push({
key: name,
label: elementLabel,
hasValue: hasElement,
resetValue: resetElement,
isShownByDefault: defaultControls[name],
indicators: supportsBackground ? [
elementTextColor,
elementGradient ?? elementBackgroundColor
] : [elementTextColor],
tabs: [
hasSolidColors && {
key: "text",
label: (0, import_i18n188.__)("Text"),
inheritedValue: elementTextColor,
inheritedSlug: extractPresetSlug(
inheritedValue?.elements?.[name]?.color?.text,
"color"
),
setValue: setElementTextColor,
userValue: elementTextUserColor
},
hasSolidColors && supportsBackground && {
key: "background",
label: (0, import_i18n188.__)("Background"),
inheritedValue: elementBackgroundColor,
inheritedSlug: extractPresetSlug(
inheritedValue?.elements?.[name]?.color?.background,
"color"
),
setValue: setElementBackgroundColor,
userValue: elementBackgroundUserColor
},
hasGradientColors && supportsBackground && {
key: "gradient",
label: (0, import_i18n188.__)("Gradient"),
inheritedValue: elementGradient,
setValue: setElementGradient,
userValue: elementGradientUserColor,
isGradient: true
}
].filter(Boolean)
});
});
return /* @__PURE__ */ (0, import_jsx_runtime422.jsxs)(
Wrapper,
{
resetAllFilter,
value,
onChange,
panelId,
label,
children: [
items.map((item) => {
const { key, ...restItem } = item;
return /* @__PURE__ */ (0, import_jsx_runtime422.jsx)(
ColorGradientDropdownItem,
{
...restItem,
colorGradientControlSettings: {
colors: colors2,
disableCustomColors: !areCustomSolidsEnabled,
gradients,
disableCustomGradients: !areCustomGradientsEnabled
},
panelId
},
key
);
}),
children
]
}
);
}
// packages/block-editor/build-module/components/global-styles/typography-utils.mjs
function getMergedFontFamiliesAndFontFamilyFaces(settings2, selectedFontFamily) {
const fontFamiliesFromSettings = settings2?.typography?.fontFamilies;
const fontFamilies = ["default", "theme", "custom"].flatMap(
(key) => fontFamiliesFromSettings?.[key] ?? []
);
const fontFamilyFaces = fontFamilies.find(
(family) => family.fontFamily === selectedFontFamily
)?.fontFace ?? [];
return { fontFamilies, fontFamilyFaces };
}
function findNearestFontWeight(availableFontWeights, newFontWeightValue) {
newFontWeightValue = "number" === typeof newFontWeightValue ? newFontWeightValue.toString() : newFontWeightValue;
if (!newFontWeightValue || typeof newFontWeightValue !== "string") {
return "";
}
if (!availableFontWeights || availableFontWeights.length === 0) {
return newFontWeightValue;
}
const nearestFontWeight = availableFontWeights?.reduce(
(nearest, { value: fw }) => {
const currentDiff = Math.abs(
parseInt(fw) - parseInt(newFontWeightValue)
);
const nearestDiff = Math.abs(
parseInt(nearest) - parseInt(newFontWeightValue)
);
return currentDiff < nearestDiff ? fw : nearest;
},
availableFontWeights[0]?.value
);
return nearestFontWeight;
}
function findNearestFontStyle(availableFontStyles, newFontStyleValue) {
if (typeof newFontStyleValue !== "string" || !newFontStyleValue) {
return "";
}
const validStyles = ["normal", "italic", "oblique"];
if (!validStyles.includes(newFontStyleValue)) {
return "";
}
if (!availableFontStyles || availableFontStyles.length === 0 || availableFontStyles.find(
(style) => style.value === newFontStyleValue
)) {
return newFontStyleValue;
}
if (newFontStyleValue === "oblique" && !availableFontStyles.find((style) => style.value === "oblique")) {
return "italic";
}
return "";
}
function findNearestStyleAndWeight(fontFamilyFaces, fontStyle, fontWeight) {
let nearestFontStyle = fontStyle;
let nearestFontWeight = fontWeight;
const { fontStyles, fontWeights, combinedStyleAndWeightOptions } = getFontStylesAndWeights(fontFamilyFaces);
const hasFontStyle = fontStyles?.some(
({ value: fs }) => fs === fontStyle
);
const hasFontWeight = fontWeights?.some(
({ value: fw }) => fw?.toString() === fontWeight?.toString()
);
if (!hasFontStyle) {
nearestFontStyle = fontStyle ? findNearestFontStyle(fontStyles, fontStyle) : combinedStyleAndWeightOptions?.find(
(option) => option.style.fontWeight === findNearestFontWeight(fontWeights, fontWeight)
)?.style?.fontStyle;
}
if (!hasFontWeight) {
nearestFontWeight = fontWeight ? findNearestFontWeight(fontWeights, fontWeight) : combinedStyleAndWeightOptions?.find(
(option) => option.style.fontStyle === (nearestFontStyle || fontStyle)
)?.style?.fontWeight;
}
return { nearestFontStyle, nearestFontWeight };
}
// packages/block-editor/build-module/components/global-styles/typography-panel.mjs
var import_jsx_runtime423 = __toESM(require_jsx_runtime(), 1);
var MIN_TEXT_COLUMNS = 1;
var MAX_TEXT_COLUMNS = 6;
function useHasTypographyPanel(settings2) {
const hasFontFamily = useHasFontFamilyControl(settings2);
const hasLineHeight = useHasLineHeightControl(settings2);
const hasFontAppearance = useHasAppearanceControl(settings2);
const hasLetterSpacing = useHasLetterSpacingControl(settings2);
const hasTextAlign = useHasTextAlignmentControl(settings2);
const hasTextTransform = useHasTextTransformControl(settings2);
const hasTextDecoration = useHasTextDecorationControl(settings2);
const hasTextIndent = useHasTextIndentControl(settings2);
const hasWritingMode = useHasWritingModeControl(settings2);
const hasTextColumns = useHasTextColumnsControl(settings2);
const hasFontSize = useHasFontSizeControl(settings2);
const hasTextColor = useHasTextPanel(settings2);
return hasFontFamily || hasLineHeight || hasFontAppearance || hasLetterSpacing || hasTextAlign || hasTextTransform || hasFontSize || hasTextDecoration || hasTextIndent || hasWritingMode || hasTextColumns || hasTextColor;
}
function useHasFontSizeControl(settings2) {
return settings2?.typography?.defaultFontSizes !== false && settings2?.typography?.fontSizes?.default?.length || settings2?.typography?.fontSizes?.theme?.length || settings2?.typography?.fontSizes?.custom?.length || settings2?.typography?.customFontSize;
}
function useHasFontFamilyControl(settings2) {
return ["default", "theme", "custom"].some(
(key) => settings2?.typography?.fontFamilies?.[key]?.length
);
}
function useHasLineHeightControl(settings2) {
return settings2?.typography?.lineHeight;
}
function useHasAppearanceControl(settings2) {
return settings2?.typography?.fontStyle || settings2?.typography?.fontWeight;
}
function useAppearanceControlLabel(settings2) {
if (!settings2?.typography?.fontStyle) {
return (0, import_i18n189.__)("Font weight");
}
if (!settings2?.typography?.fontWeight) {
return (0, import_i18n189.__)("Font style");
}
return (0, import_i18n189.__)("Appearance");
}
function useHasLetterSpacingControl(settings2) {
return settings2?.typography?.letterSpacing;
}
function useHasTextTransformControl(settings2) {
return settings2?.typography?.textTransform;
}
function useHasTextAlignmentControl(settings2) {
return settings2?.typography?.textAlign;
}
function useHasTextDecorationControl(settings2) {
return settings2?.typography?.textDecoration;
}
function useHasWritingModeControl(settings2) {
return settings2?.typography?.writingMode;
}
function useHasTextColumnsControl(settings2) {
return settings2?.typography?.textColumns;
}
function useHasTextIndentControl(settings2) {
return settings2?.typography?.textIndent;
}
function getMergedFontSizes(settings2) {
const fontSizes = settings2?.typography?.fontSizes;
const defaultFontSizesEnabled = !!settings2?.typography?.defaultFontSizes;
return [
...fontSizes?.custom ?? [],
...fontSizes?.theme ?? [],
...defaultFontSizesEnabled ? fontSizes?.default ?? [] : []
];
}
function TypographyToolsPanel({
resetAllFilter,
onChange,
value,
panelId,
children
}) {
const dropdownMenuProps = useToolsPanelDropdownMenuProps();
const resetAll = () => {
const updatedValue = resetAllFilter(value);
onChange(updatedValue);
};
return /* @__PURE__ */ (0, import_jsx_runtime423.jsx)(
import_components199.__experimentalToolsPanel,
{
label: (0, import_i18n189.__)("Typography"),
resetAll,
panelId,
__experimentalFirstVisibleItemClass: "first",
dropdownMenuProps,
children
}
);
}
var DEFAULT_CONTROLS4 = {
textColor: true,
fontFamily: true,
fontSize: true,
fontAppearance: true,
lineHeight: true,
letterSpacing: true,
textAlign: true,
textTransform: true,
textDecoration: true,
textIndent: true,
writingMode: true,
textColumns: true
};
function TypographyPanel({
as: Wrapper = TypographyToolsPanel,
value,
onChange,
inheritedValue = value,
settings: settings2,
panelId,
defaultControls = DEFAULT_CONTROLS4,
isGlobalStyles = false,
contrastWarning
}) {
const { colors: colors2, allColors, areCustomSolidsEnabled, decodeValue } = useColorGradientSettings(settings2);
const hasTextColorEnabled = useHasTextPanel(settings2);
const textColor = decodeValue(inheritedValue?.color?.text);
const userTextColor = decodeValue(value?.color?.text);
const hasTextColorValue = () => !!value?.color?.text;
const setTextColor = (newColor, newSlug) => {
const encoded = encodeColorValueWithPalette(
allColors,
newColor,
newSlug
);
let changedObject = setImmutably2(value, ["color", "text"], encoded);
if (inheritedValue?.color?.text === inheritedValue?.elements?.link?.color?.text) {
changedObject = setImmutably2(
changedObject,
["elements", "link", "color", "text"],
encoded
);
}
onChange(changedObject);
};
const resetTextColor = () => setTextColor(void 0);
const hasFontFamilyEnabled = useHasFontFamilyControl(settings2);
const fontFamily = decodeValue(inheritedValue?.typography?.fontFamily);
const { fontFamilies, fontFamilyFaces } = (0, import_element248.useMemo)(() => {
return getMergedFontFamiliesAndFontFamilyFaces(settings2, fontFamily);
}, [settings2, fontFamily]);
const setFontFamily = (newValue) => {
const slug = fontFamilies?.find(
({ fontFamily: f2 }) => f2 === newValue
)?.slug;
let updatedValue = setImmutably2(
value,
["typography", "fontFamily"],
slug ? `var:preset|font-family|${slug}` : newValue || void 0
);
const newFontFamilyFaces = fontFamilies?.find(({ fontFamily: f2 }) => f2 === newValue)?.fontFace ?? [];
const { fontStyles, fontWeights } = getFontStylesAndWeights(newFontFamilyFaces);
const hasFontStyle = fontStyles?.some(
({ value: fs }) => fs === fontStyle
);
const hasFontWeight = fontWeights?.some(
({ value: fw }) => fw?.toString() === fontWeight?.toString()
);
if (!hasFontStyle || !hasFontWeight) {
const { nearestFontStyle, nearestFontWeight } = findNearestStyleAndWeight(
newFontFamilyFaces,
fontStyle,
fontWeight
);
if (nearestFontStyle || nearestFontWeight) {
updatedValue = {
...updatedValue,
typography: {
...updatedValue?.typography,
fontStyle: nearestFontStyle || void 0,
fontWeight: nearestFontWeight || void 0
}
};
} else if (fontStyle || fontWeight) {
updatedValue = {
...updatedValue,
typography: {
...updatedValue?.typography,
fontStyle: void 0,
fontWeight: void 0
}
};
}
}
onChange(updatedValue);
};
const hasFontFamily = () => !!value?.typography?.fontFamily;
const resetFontFamily = () => setFontFamily(void 0);
const hasFontSizeEnabled = useHasFontSizeControl(settings2);
const disableCustomFontSizes = !settings2?.typography?.customFontSize;
const mergedFontSizes = getMergedFontSizes(settings2);
const fontSize = decodeValue(inheritedValue?.typography?.fontSize);
const currentFontSizeSlug = (() => {
const rawValue = inheritedValue?.typography?.fontSize;
if (!rawValue || typeof rawValue !== "string") {
return void 0;
}
if (rawValue.startsWith("var:preset|font-size|")) {
return rawValue.replace("var:preset|font-size|", "");
}
const cssVarMatch = rawValue.match(
/^var\(--wp--preset--font-size--([^)]+)\)$/
);
if (cssVarMatch) {
return cssVarMatch[1];
}
return void 0;
})();
const setFontSize = (newValue, metadata) => {
const actualValue = !!metadata?.slug ? `var:preset|font-size|${metadata?.slug}` : newValue;
onChange(
setImmutably2(
value,
["typography", "fontSize"],
actualValue || void 0
)
);
};
const hasFontSize = () => !!value?.typography?.fontSize;
const resetFontSize = () => setFontSize(void 0);
const hasAppearanceControl = useHasAppearanceControl(settings2);
const appearanceControlLabel = useAppearanceControlLabel(settings2);
const hasFontStyles = settings2?.typography?.fontStyle;
const hasFontWeights = settings2?.typography?.fontWeight;
const fontStyle = decodeValue(inheritedValue?.typography?.fontStyle);
const fontWeight = decodeValue(inheritedValue?.typography?.fontWeight);
const setFontAppearance = (0, import_element248.useCallback)(
({ fontStyle: newFontStyle, fontWeight: newFontWeight }) => {
if (newFontStyle !== fontStyle || newFontWeight !== fontWeight) {
onChange({
...value,
typography: {
...value?.typography,
fontStyle: newFontStyle || void 0,
fontWeight: newFontWeight || void 0
}
});
}
},
[fontStyle, fontWeight, onChange, value]
);
const hasFontAppearance = () => !!value?.typography?.fontStyle || !!value?.typography?.fontWeight;
const resetFontAppearance = (0, import_element248.useCallback)(() => {
setFontAppearance({});
}, [setFontAppearance]);
const hasLineHeightEnabled = useHasLineHeightControl(settings2);
const lineHeight = decodeValue(inheritedValue?.typography?.lineHeight);
const setLineHeight = (newValue) => {
onChange(
setImmutably2(
value,
["typography", "lineHeight"],
newValue || void 0
)
);
};
const hasLineHeight = () => value?.typography?.lineHeight !== void 0;
const resetLineHeight = () => setLineHeight(void 0);
const hasLetterSpacingControl = useHasLetterSpacingControl(settings2);
const letterSpacing = decodeValue(
inheritedValue?.typography?.letterSpacing
);
const setLetterSpacing = (newValue) => {
onChange(
setImmutably2(
value,
["typography", "letterSpacing"],
newValue || void 0
)
);
};
const hasLetterSpacing = () => !!value?.typography?.letterSpacing;
const resetLetterSpacing = () => setLetterSpacing(void 0);
const hasTextIndentControl = useHasTextIndentControl(settings2);
const textIndent = decodeValue(inheritedValue?.typography?.textIndent);
const textIndentSetting = settings2?.typography?.textIndent ?? "subsequent";
const isTextIndentAll = textIndentSetting === "all";
const setTextIndentValue = (newValue) => {
onChange(
setImmutably2(
value,
["typography", "textIndent"],
newValue || void 0
)
);
};
const onToggleTextIndentAll = (newValue) => {
onChange({
...value,
settings: {
typography: {
textIndent: newValue ? "all" : "subsequent"
}
}
});
};
const hasTextIndent = () => !!value?.typography?.textIndent;
const resetTextIndent = () => {
onChange(
setImmutably2(value, ["typography", "textIndent"], void 0)
);
};
const textIndentHelp = isTextIndentAll ? (0, import_i18n189.__)("Indents the first line of all paragraphs.") : (0, import_i18n189.__)("Indents the first line of each paragraph after the first one.");
const hasTextColumnsControl = useHasTextColumnsControl(settings2);
const textColumns = decodeValue(inheritedValue?.typography?.textColumns);
const setTextColumns = (newValue) => {
onChange(
setImmutably2(
value,
["typography", "textColumns"],
newValue || void 0
)
);
};
const hasTextColumns = () => !!value?.typography?.textColumns;
const resetTextColumns = () => setTextColumns(void 0);
const hasTextTransformControl = useHasTextTransformControl(settings2);
const textTransform = decodeValue(
inheritedValue?.typography?.textTransform
);
const setTextTransform = (newValue) => {
onChange(
setImmutably2(
value,
["typography", "textTransform"],
newValue || void 0
)
);
};
const hasTextTransform = () => !!value?.typography?.textTransform;
const resetTextTransform = () => setTextTransform(void 0);
const hasTextDecorationControl = useHasTextDecorationControl(settings2);
const textDecoration = decodeValue(
inheritedValue?.typography?.textDecoration
);
const setTextDecoration = (newValue) => {
onChange(
setImmutably2(
value,
["typography", "textDecoration"],
newValue || void 0
)
);
};
const hasTextDecoration = () => !!value?.typography?.textDecoration;
const resetTextDecoration = () => setTextDecoration(void 0);
const hasWritingModeControl = useHasWritingModeControl(settings2);
const writingMode = decodeValue(inheritedValue?.typography?.writingMode);
const setWritingMode = (newValue) => {
onChange(
setImmutably2(
value,
["typography", "writingMode"],
newValue || void 0
)
);
};
const hasWritingMode = () => !!value?.typography?.writingMode;
const resetWritingMode = () => setWritingMode(void 0);
const hasTextAlignmentControl = useHasTextAlignmentControl(settings2);
const textAlign = decodeValue(inheritedValue?.typography?.textAlign);
const setTextAlign = (newValue) => {
onChange(
setImmutably2(
value,
["typography", "textAlign"],
newValue || void 0
)
);
};
const hasTextAlign = () => !!value?.typography?.textAlign;
const resetTextAlign = () => setTextAlign(void 0);
const resetAllFilter = (0, import_element248.useCallback)(
(previousValue) => {
if (!hasTextColorEnabled) {
return {
...previousValue,
typography: {}
};
}
return {
...previousValue,
typography: {},
color: {
...previousValue?.color,
text: void 0
}
};
},
[hasTextColorEnabled]
);
return /* @__PURE__ */ (0, import_jsx_runtime423.jsxs)(
Wrapper,
{
resetAllFilter,
value,
onChange,
panelId,
children: [
hasTextColorEnabled && /* @__PURE__ */ (0, import_jsx_runtime423.jsx)(
ColorGradientDropdownItem,
{
label: (0, import_i18n189.__)("Color"),
hasValue: hasTextColorValue,
resetValue: resetTextColor,
isShownByDefault: defaultControls.textColor,
indicators: [textColor],
contrastWarning,
tabs: [
{
key: "text",
label: (0, import_i18n189.__)("Color"),
inheritedValue: textColor,
inheritedSlug: extractPresetSlug(
inheritedValue?.color?.text,
"color"
),
setValue: setTextColor,
userValue: userTextColor
}
],
colorGradientControlSettings: {
colors: colors2,
disableCustomColors: !areCustomSolidsEnabled
},
panelId
}
),
hasFontFamilyEnabled && /* @__PURE__ */ (0, import_jsx_runtime423.jsx)(
import_components199.__experimentalToolsPanelItem,
{
label: (0, import_i18n189.__)("Font"),
hasValue: hasFontFamily,
onDeselect: resetFontFamily,
isShownByDefault: defaultControls.fontFamily,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime423.jsx)(
FontFamilyControl,
{
fontFamilies,
value: fontFamily,
onChange: setFontFamily
}
)
}
),
hasFontSizeEnabled && /* @__PURE__ */ (0, import_jsx_runtime423.jsx)(
import_components199.__experimentalToolsPanelItem,
{
label: (0, import_i18n189.__)("Size"),
hasValue: hasFontSize,
onDeselect: resetFontSize,
isShownByDefault: defaultControls.fontSize,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime423.jsx)(
import_components199.FontSizePicker,
{
value: currentFontSizeSlug || fontSize,
valueMode: currentFontSizeSlug ? "slug" : "literal",
onChange: setFontSize,
fontSizes: mergedFontSizes,
disableCustomFontSizes,
withReset: false,
withSlider: true
}
)
}
),
hasAppearanceControl && /* @__PURE__ */ (0, import_jsx_runtime423.jsx)(
import_components199.__experimentalToolsPanelItem,
{
label: appearanceControlLabel,
hasValue: hasFontAppearance,
onDeselect: resetFontAppearance,
isShownByDefault: defaultControls.fontAppearance,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime423.jsx)(
FontAppearanceControl,
{
value: {
fontStyle,
fontWeight
},
onChange: setFontAppearance,
hasFontStyles,
hasFontWeights,
fontFamilyFaces
}
)
}
),
hasLineHeightEnabled && /* @__PURE__ */ (0, import_jsx_runtime423.jsx)(
import_components199.__experimentalToolsPanelItem,
{
className: "single-column",
label: (0, import_i18n189.__)("Line height"),
hasValue: hasLineHeight,
onDeselect: resetLineHeight,
isShownByDefault: defaultControls.lineHeight,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime423.jsx)(
line_height_control_default,
{
__unstableInputWidth: "auto",
value: lineHeight,
onChange: setLineHeight
}
)
}
),
hasLetterSpacingControl && /* @__PURE__ */ (0, import_jsx_runtime423.jsx)(
import_components199.__experimentalToolsPanelItem,
{
className: "single-column",
label: (0, import_i18n189.__)("Letter spacing"),
hasValue: hasLetterSpacing,
onDeselect: resetLetterSpacing,
isShownByDefault: defaultControls.letterSpacing,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime423.jsx)(
LetterSpacingControl,
{
value: letterSpacing,
onChange: setLetterSpacing,
__unstableInputWidth: "auto"
}
)
}
),
hasTextIndentControl && /* @__PURE__ */ (0, import_jsx_runtime423.jsxs)(
import_components199.__experimentalToolsPanelItem,
{
label: (0, import_i18n189.__)("Line indent"),
hasValue: hasTextIndent,
onDeselect: resetTextIndent,
isShownByDefault: defaultControls.textIndent,
panelId,
children: [
/* @__PURE__ */ (0, import_jsx_runtime423.jsx)(
TextIndentControl,
{
value: textIndent,
onChange: setTextIndentValue,
__unstableInputWidth: "auto",
withSlider: true,
hasBottomMargin: isGlobalStyles
}
),
isGlobalStyles && /* @__PURE__ */ (0, import_jsx_runtime423.jsx)(
import_components199.ToggleControl,
{
label: (0, import_i18n189.__)("Indent all paragraphs"),
checked: isTextIndentAll,
onChange: onToggleTextIndentAll,
help: textIndentHelp
}
)
]
}
),
hasTextColumnsControl && /* @__PURE__ */ (0, import_jsx_runtime423.jsx)(
import_components199.__experimentalToolsPanelItem,
{
className: "single-column",
label: (0, import_i18n189.__)("Columns"),
hasValue: hasTextColumns,
onDeselect: resetTextColumns,
isShownByDefault: defaultControls.textColumns,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime423.jsx)(
import_components199.__experimentalNumberControl,
{
label: (0, import_i18n189.__)("Columns"),
max: MAX_TEXT_COLUMNS,
min: MIN_TEXT_COLUMNS,
onChange: setTextColumns,
spinControls: "custom",
value: textColumns,
initialPosition: 1
}
)
}
),
hasTextDecorationControl && /* @__PURE__ */ (0, import_jsx_runtime423.jsx)(
import_components199.__experimentalToolsPanelItem,
{
className: "single-column",
label: (0, import_i18n189.__)("Decoration"),
hasValue: hasTextDecoration,
onDeselect: resetTextDecoration,
isShownByDefault: defaultControls.textDecoration,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime423.jsx)(
TextDecorationControl,
{
value: textDecoration,
onChange: setTextDecoration,
size: "__unstable-large",
__unstableInputWidth: "auto"
}
)
}
),
hasWritingModeControl && /* @__PURE__ */ (0, import_jsx_runtime423.jsx)(
import_components199.__experimentalToolsPanelItem,
{
className: "single-column",
label: (0, import_i18n189.__)("Orientation"),
hasValue: hasWritingMode,
onDeselect: resetWritingMode,
isShownByDefault: defaultControls.writingMode,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime423.jsx)(
WritingModeControl,
{
value: writingMode,
onChange: setWritingMode,
size: "__unstable-large"
}
)
}
),
hasTextTransformControl && /* @__PURE__ */ (0, import_jsx_runtime423.jsx)(
import_components199.__experimentalToolsPanelItem,
{
label: (0, import_i18n189.__)("Letter case"),
hasValue: hasTextTransform,
onDeselect: resetTextTransform,
isShownByDefault: defaultControls.textTransform,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime423.jsx)(
TextTransformControl,
{
value: textTransform,
onChange: setTextTransform,
showNone: true,
isBlock: true,
size: "__unstable-large"
}
)
}
),
hasTextAlignmentControl && /* @__PURE__ */ (0, import_jsx_runtime423.jsxs)(
import_components199.__experimentalToolsPanelItem,
{
label: (0, import_i18n189.__)("Text alignment"),
hasValue: hasTextAlign,
onDeselect: resetTextAlign,
isShownByDefault: defaultControls.textAlign,
panelId,
children: [
/* @__PURE__ */ (0, import_jsx_runtime423.jsx)(
TextAlignmentControl,
{
value: textAlign,
onChange: setTextAlign,
options: ["left", "center", "right", "justify"],
size: "__unstable-large"
}
),
textAlign === "justify" && /* @__PURE__ */ (0, import_jsx_runtime423.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime423.jsx)(import_components199.Notice, { status: "warning", isDismissible: false, children: (0, import_i18n189.__)(
"Justified text can reduce readability. For better accessibility, use left-aligned text instead."
) }) })
]
}
)
]
}
);
}
// packages/block-editor/build-module/components/global-styles/dimensions-panel.mjs
var import_i18n192 = __toESM(require_i18n(), 1);
var import_components202 = __toESM(require_components(), 1);
var import_element250 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/child-layout-control/index.mjs
var import_components200 = __toESM(require_components(), 1);
var import_i18n190 = __toESM(require_i18n(), 1);
var import_element249 = __toESM(require_element(), 1);
var import_data162 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/grid/use-get-number-of-blocks-before-cell.mjs
var import_data161 = __toESM(require_data(), 1);
function useGetNumberOfBlocksBeforeCell(gridClientId, numColumns) {
const { getBlockOrder: getBlockOrder2, getBlockAttributes: getBlockAttributes3 } = (0, import_data161.useSelect)(store);
const getNumberOfBlocksBeforeCell = (column, row) => {
const targetIndex = (row - 1) * numColumns + column - 1;
let count = 0;
for (const clientId of getBlockOrder2(gridClientId)) {
const { columnStart, rowStart } = getBlockAttributes3(clientId).style?.layout ?? {};
const cellIndex = (rowStart - 1) * numColumns + columnStart - 1;
if (cellIndex < targetIndex) {
count++;
}
}
return count;
};
return getNumberOfBlocksBeforeCell;
}
// packages/block-editor/build-module/components/child-layout-control/index.mjs
var import_jsx_runtime424 = __toESM(require_jsx_runtime(), 1);
var FLEX_CHILD_LAYOUT_VALUES = {
fit: "fit",
grow: "fill",
max: "fixed",
fixed: "fixedNoShrink"
};
var FLEX_SIZE_VALUES = [
FLEX_CHILD_LAYOUT_VALUES.max,
FLEX_CHILD_LAYOUT_VALUES.fixed
];
function isFlexSizeValue(value) {
return FLEX_SIZE_VALUES.includes(value);
}
function maxSizeLabel(parentLayout) {
const { orientation = "horizontal" } = parentLayout ?? {};
return orientation === "horizontal" ? (0, import_i18n190._x)("Max", "Block with maximum width in flex layout") : (0, import_i18n190._x)("Max", "Block with maximum height in flex layout");
}
function helpText(flexControlValue, parentLayout) {
const { orientation = "horizontal" } = parentLayout ?? {};
if (flexControlValue === FLEX_CHILD_LAYOUT_VALUES.grow) {
return (0, import_i18n190.__)("Stretch to fill available space.");
}
if (flexControlValue === FLEX_CHILD_LAYOUT_VALUES.max && orientation === "horizontal") {
return (0, import_i18n190.__)("Specify a maximum width.");
} else if (flexControlValue === FLEX_CHILD_LAYOUT_VALUES.max) {
return (0, import_i18n190.__)("Specify a maximum height.");
}
if (flexControlValue === FLEX_CHILD_LAYOUT_VALUES.fixed && orientation === "horizontal") {
return (0, import_i18n190.__)("Specify a fixed width.");
} else if (flexControlValue === FLEX_CHILD_LAYOUT_VALUES.fixed) {
return (0, import_i18n190.__)("Specify a fixed height.");
}
return (0, import_i18n190.__)("Fit contents.");
}
function ChildLayoutControl({
value: childLayout = {},
onChange,
parentLayout,
isShownByDefault,
panelId,
showGridSpanDefaults = true
}) {
const {
type: parentType,
default: { type: defaultParentType = "default" } = {}
} = parentLayout ?? {};
const parentLayoutType = parentType || defaultParentType;
if (parentLayoutType === "flex") {
return /* @__PURE__ */ (0, import_jsx_runtime424.jsx)(
FlexControls,
{
childLayout,
onChange,
parentLayout,
isShownByDefault,
panelId
}
);
} else if (parentLayoutType === "grid") {
return /* @__PURE__ */ (0, import_jsx_runtime424.jsx)(
GridControls,
{
childLayout,
onChange,
parentLayout,
isShownByDefault,
panelId,
showGridSpanDefaults
}
);
}
return null;
}
function FlexControls({
childLayout,
onChange,
parentLayout,
isShownByDefault,
panelId
}) {
const { selfStretch, flexSize } = childLayout;
const { orientation = "horizontal" } = parentLayout ?? {};
const flexControlValue = selfStretch || FLEX_CHILD_LAYOUT_VALUES.fit;
const hasFlexSizeValue = isFlexSizeValue(flexControlValue);
const hasFlexValue = () => !!selfStretch;
const flexResetLabel = orientation === "horizontal" ? (0, import_i18n190.__)("Width") : (0, import_i18n190.__)("Height");
const [availableUnits] = useSettings("spacing.units");
const units2 = (0, import_components200.__experimentalUseCustomUnits)({
availableUnits: availableUnits || [
"%",
"px",
"em",
"rem",
"vh",
"vw"
]
});
const resetFlex = () => {
onChange({
selfStretch: void 0,
flexSize: void 0
});
};
(0, import_element249.useEffect)(() => {
if (isFlexSizeValue(selfStretch) && !flexSize) {
onChange({
...childLayout,
selfStretch: FLEX_CHILD_LAYOUT_VALUES.fit
});
}
}, []);
return /* @__PURE__ */ (0, import_jsx_runtime424.jsxs)(
import_components200.__experimentalVStack,
{
as: import_components200.__experimentalToolsPanelItem,
spacing: 2,
hasValue: hasFlexValue,
label: flexResetLabel,
onDeselect: resetFlex,
isShownByDefault,
panelId,
children: [
/* @__PURE__ */ (0, import_jsx_runtime424.jsxs)(
import_components200.__experimentalToggleGroupControl,
{
label: childLayoutOrientation(parentLayout),
value: flexControlValue,
help: helpText(flexControlValue, parentLayout),
onChange: (value) => {
const newFlexSize = isFlexSizeValue(value) ? flexSize : null;
onChange({
selfStretch: value,
flexSize: newFlexSize
});
},
isBlock: true,
children: [
/* @__PURE__ */ (0, import_jsx_runtime424.jsx)(
import_components200.__experimentalToggleGroupControlOption,
{
value: FLEX_CHILD_LAYOUT_VALUES.fit,
label: (0, import_i18n190._x)(
"Fit",
"Intrinsic block width in flex layout"
)
},
FLEX_CHILD_LAYOUT_VALUES.fit
),
/* @__PURE__ */ (0, import_jsx_runtime424.jsx)(
import_components200.__experimentalToggleGroupControlOption,
{
value: FLEX_CHILD_LAYOUT_VALUES.grow,
label: (0, import_i18n190._x)(
"Grow",
"Block with expanding width in flex layout"
)
},
FLEX_CHILD_LAYOUT_VALUES.grow
),
/* @__PURE__ */ (0, import_jsx_runtime424.jsx)(
import_components200.__experimentalToggleGroupControlOption,
{
value: FLEX_CHILD_LAYOUT_VALUES.max,
label: maxSizeLabel(parentLayout)
},
FLEX_CHILD_LAYOUT_VALUES.max
),
/* @__PURE__ */ (0, import_jsx_runtime424.jsx)(
import_components200.__experimentalToggleGroupControlOption,
{
value: FLEX_CHILD_LAYOUT_VALUES.fixed,
label: (0, import_i18n190._x)(
"Fixed",
"Block with fixed width in flex layout"
)
},
FLEX_CHILD_LAYOUT_VALUES.fixed
)
]
}
),
hasFlexSizeValue && /* @__PURE__ */ (0, import_jsx_runtime424.jsx)(
import_components200.__experimentalUnitControl,
{
units: units2,
onChange: (value) => {
onChange({
selfStretch: flexControlValue,
flexSize: value
});
},
value: flexSize,
min: 0,
label: flexResetLabel,
hideLabelFromVision: true
}
)
]
}
);
}
function childLayoutOrientation(parentLayout) {
const { orientation = "horizontal" } = parentLayout ?? {};
return orientation === "horizontal" ? (0, import_i18n190.__)("Width") : (0, import_i18n190.__)("Height");
}
function GridControls({
childLayout,
onChange,
parentLayout,
isShownByDefault,
panelId,
showGridSpanDefaults
}) {
const { columnStart, rowStart, columnSpan, rowSpan } = childLayout;
const { columnCount, rowCount } = parentLayout ?? {};
const rootClientId = (0, import_data162.useSelect)(
(select3) => select3(store).getBlockRootClientId(panelId)
);
const { moveBlocksToPosition: moveBlocksToPosition2, __unstableMarkNextChangeAsNotPersistent: __unstableMarkNextChangeAsNotPersistent2 } = (0, import_data162.useDispatch)(store);
const getNumberOfBlocksBeforeCell = useGetNumberOfBlocksBeforeCell(
rootClientId,
columnCount || 3
);
const hasStartValue = () => !!columnStart || !!rowStart;
const hasSpanValue = () => !!columnSpan || !!rowSpan;
const resetGridStarts = () => {
onChange({
columnStart: void 0,
rowStart: void 0
});
};
const resetGridSpans = () => {
onChange({
columnSpan: void 0,
rowSpan: void 0
});
};
const maxColumnSpan = columnCount ? columnCount - (columnStart ?? 1) + 1 : void 0;
const maxRowSpan = window.__experimentalEnableGridInteractivity && rowCount ? rowCount - (rowStart ?? 1) + 1 : void 0;
const columnSpanValue = columnSpan ?? (showGridSpanDefaults ? 1 : void 0);
const rowSpanValue = rowSpan ?? (showGridSpanDefaults ? 1 : void 0);
return /* @__PURE__ */ (0, import_jsx_runtime424.jsxs)(import_jsx_runtime424.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime424.jsxs)(
import_components200.Flex,
{
as: import_components200.__experimentalToolsPanelItem,
hasValue: hasSpanValue,
label: (0, import_i18n190.__)("Grid span"),
onDeselect: resetGridSpans,
isShownByDefault,
panelId,
children: [
/* @__PURE__ */ (0, import_jsx_runtime424.jsx)(import_components200.FlexItem, { style: { width: "50%" }, children: /* @__PURE__ */ (0, import_jsx_runtime424.jsx)(
import_components200.__experimentalInputControl,
{
label: (0, import_i18n190.__)("Column span"),
type: "number",
onChange: (value) => {
const newColumnSpan = value === "" ? 1 : parseInt(value, 10);
const constrainedValue = maxColumnSpan ? Math.min(newColumnSpan, maxColumnSpan) : newColumnSpan;
onChange({
columnStart,
rowStart,
rowSpan,
columnSpan: constrainedValue
});
},
value: columnSpanValue,
min: 1,
max: maxColumnSpan
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime424.jsx)(import_components200.FlexItem, { style: { width: "50%" }, children: /* @__PURE__ */ (0, import_jsx_runtime424.jsx)(
import_components200.__experimentalInputControl,
{
label: (0, import_i18n190.__)("Row span"),
type: "number",
onChange: (value) => {
const newRowSpan = value === "" ? 1 : parseInt(value, 10);
const constrainedValue = maxRowSpan ? Math.min(newRowSpan, maxRowSpan) : newRowSpan;
onChange({
columnStart,
rowStart,
columnSpan,
rowSpan: constrainedValue
});
},
value: rowSpanValue,
min: 1,
max: maxRowSpan
}
) })
]
}
),
window.__experimentalEnableGridInteractivity && // Use Flex with an explicit width on the FlexItem instead of HStack to
// work around an issue in webkit where inputs with a max attribute are
// sized incorrectly.
/* @__PURE__ */ (0, import_jsx_runtime424.jsxs)(
import_components200.Flex,
{
as: import_components200.__experimentalToolsPanelItem,
hasValue: hasStartValue,
label: (0, import_i18n190.__)("Grid placement"),
onDeselect: resetGridStarts,
isShownByDefault: false,
panelId,
children: [
/* @__PURE__ */ (0, import_jsx_runtime424.jsx)(import_components200.FlexItem, { style: { width: "50%" }, children: /* @__PURE__ */ (0, import_jsx_runtime424.jsx)(
import_components200.__experimentalInputControl,
{
label: (0, import_i18n190.__)("Column"),
type: "number",
onChange: (value) => {
const newColumnStart = value === "" ? 1 : parseInt(value, 10);
onChange({
columnStart: newColumnStart,
rowStart,
columnSpan,
rowSpan
});
__unstableMarkNextChangeAsNotPersistent2();
moveBlocksToPosition2(
[panelId],
rootClientId,
rootClientId,
getNumberOfBlocksBeforeCell(
newColumnStart,
rowStart
)
);
},
value: columnStart ?? 1,
min: 1,
max: columnCount ? columnCount - (columnSpan ?? 1) + 1 : void 0
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime424.jsx)(import_components200.FlexItem, { style: { width: "50%" }, children: /* @__PURE__ */ (0, import_jsx_runtime424.jsx)(
import_components200.__experimentalInputControl,
{
label: (0, import_i18n190.__)("Row"),
type: "number",
onChange: (value) => {
const newRowStart = value === "" ? 1 : parseInt(value, 10);
onChange({
columnStart,
rowStart: newRowStart,
columnSpan,
rowSpan
});
__unstableMarkNextChangeAsNotPersistent2();
moveBlocksToPosition2(
[panelId],
rootClientId,
rootClientId,
getNumberOfBlocksBeforeCell(
columnStart,
newRowStart
)
);
},
value: rowStart ?? 1,
min: 1,
max: rowCount ? rowCount - (rowSpan ?? 1) + 1 : void 0
}
) })
]
}
)
] });
}
// packages/block-editor/build-module/components/dimensions-tool/aspect-ratio-tool.mjs
var import_components201 = __toESM(require_components(), 1);
var import_i18n191 = __toESM(require_i18n(), 1);
var import_jsx_runtime425 = __toESM(require_jsx_runtime(), 1);
function AspectRatioTool({
panelId,
value,
onChange = () => {
},
options,
defaultValue = "auto",
hasValue,
isShownByDefault = true
}) {
const displayValue = value ?? "auto";
const [defaultRatios, themeRatios, showDefaultRatios] = useSettings(
"dimensions.aspectRatios.default",
"dimensions.aspectRatios.theme",
"dimensions.defaultAspectRatios"
);
const themeOptions = themeRatios?.map(({ name, ratio }) => ({
label: name,
value: ratio
}));
const defaultOptions2 = defaultRatios?.map(({ name, ratio }) => ({
label: name,
value: ratio
}));
const aspectRatioOptions = [
{
label: (0, import_i18n191._x)(
"Original",
"Aspect ratio option for dimensions control"
),
value: "auto"
},
...showDefaultRatios ? defaultOptions2 : [],
...themeOptions ? themeOptions : [],
{
label: (0, import_i18n191._x)("Custom", "Aspect ratio option for dimensions control"),
value: "custom",
disabled: true,
hidden: true
}
];
return /* @__PURE__ */ (0, import_jsx_runtime425.jsx)(
import_components201.__experimentalToolsPanelItem,
{
hasValue: hasValue ? hasValue : () => displayValue !== defaultValue,
label: (0, import_i18n191.__)("Aspect ratio"),
onDeselect: () => onChange(void 0),
isShownByDefault,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime425.jsx)(
import_components201.SelectControl,
{
label: (0, import_i18n191.__)("Aspect ratio"),
value: displayValue,
options: options ?? aspectRatioOptions,
onChange
}
)
}
);
}
// packages/block-editor/build-module/components/global-styles/dimensions-panel.mjs
var import_jsx_runtime426 = __toESM(require_jsx_runtime(), 1);
var AXIAL_SIDES = ["horizontal", "vertical"];
function useHasDimensionsPanel(settings2, styleState = DEFAULT_BLOCK_STYLE_STATE2) {
return hasContentSize(settings2) || hasWideSize(settings2) || hasPadding(settings2) || hasMargin(settings2) || hasGap(settings2) || hasHeight(settings2) || hasMinHeight(settings2) || hasMinWidth(settings2) || hasWidth(settings2) || hasAspectRatio(settings2, styleState) || hasChildLayout(settings2, styleState);
}
function hasContentSize(settings2) {
return settings2?.layout?.contentSize;
}
function hasWideSize(settings2) {
return settings2?.layout?.wideSize;
}
function hasPadding(settings2) {
return settings2?.spacing?.padding;
}
function hasMargin(settings2) {
return settings2?.spacing?.margin;
}
function hasGap(settings2) {
return settings2?.spacing?.blockGap;
}
function hasHeight(settings2) {
return settings2?.dimensions?.height;
}
function hasMinHeight(settings2) {
return settings2?.dimensions?.minHeight;
}
function hasMinWidth(settings2) {
return settings2?.dimensions?.minWidth;
}
function hasWidth(settings2) {
return settings2?.dimensions?.width;
}
function hasAspectRatio(settings2, styleState = DEFAULT_BLOCK_STYLE_STATE2) {
return !hasPseudoBlockStyleState(styleState) && settings2?.dimensions?.aspectRatio;
}
function hasChildLayout(settings2, styleState = DEFAULT_BLOCK_STYLE_STATE2) {
if (hasPseudoBlockStyleState(styleState)) {
return false;
}
const {
type: parentLayoutType = "default",
default: { type: defaultParentLayoutType = "default" } = {},
allowSizingOnChildren = false
} = settings2?.parentLayout ?? {};
const support = (defaultParentLayoutType === "flex" || parentLayoutType === "flex" || defaultParentLayoutType === "grid" || parentLayoutType === "grid") && allowSizingOnChildren;
return !!settings2?.layout && support;
}
function hasSpacingPresets(settings2) {
const { defaultSpacingSizes, spacingSizes } = settings2?.spacing || {};
return defaultSpacingSizes !== false && spacingSizes?.default?.length > 0 || spacingSizes?.theme?.length > 0 || spacingSizes?.custom?.length > 0;
}
function filterValuesBySides(values, sides2) {
if (!sides2 || !values) {
return values;
}
const filteredValues = {};
sides2.forEach((side) => {
if (side === "vertical") {
filteredValues.top = values.top;
filteredValues.bottom = values.bottom;
}
if (side === "horizontal") {
filteredValues.left = values.left;
filteredValues.right = values.right;
}
filteredValues[side] = values?.[side];
});
return filteredValues;
}
function splitStyleValue(value) {
if (value && typeof value === "string") {
return {
top: value,
right: value,
bottom: value,
left: value
};
}
return value;
}
function splitGapValue(value, isAxialGap) {
if (!value) {
return value;
}
if (typeof value === "string") {
return isAxialGap ? { top: value, right: value, bottom: value, left: value } : { top: value };
}
return {
...value,
right: value?.left,
bottom: value?.top
};
}
function DimensionsToolsPanel({
resetAllFilter,
onChange,
value,
panelId,
children
}) {
const dropdownMenuProps = useToolsPanelDropdownMenuProps();
const resetAll = () => {
const updatedValue = resetAllFilter(value);
onChange(updatedValue);
};
return /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
import_components202.__experimentalToolsPanel,
{
label: (0, import_i18n192.__)("Dimensions"),
resetAll,
panelId,
dropdownMenuProps,
children
}
);
}
var DEFAULT_CONTROLS5 = {
contentSize: true,
wideSize: true,
padding: true,
margin: true,
blockGap: true,
height: true,
minHeight: true,
minWidth: true,
width: true,
aspectRatio: true,
childLayout: true
};
function DimensionsPanel({
as: Wrapper = DimensionsToolsPanel,
value,
onChange,
inheritedValue = value,
settings: settings2,
panelId,
defaultControls = DEFAULT_CONTROLS5,
onVisualize = () => {
},
// Special case because the layout controls are not part of the dimensions panel
// in global styles but not in block inspector.
includeLayoutControls = false,
styleState = DEFAULT_BLOCK_STYLE_STATE2
}) {
const { dimensions, spacing } = settings2;
const decodeValue = (rawValue) => {
if (rawValue && typeof rawValue === "object") {
return Object.keys(rawValue).reduce((acc, key) => {
acc[key] = getValueFromVariable(
{ settings: { dimensions, spacing } },
"",
rawValue[key]
);
return acc;
}, {});
}
return getValueFromVariable(
{ settings: { dimensions, spacing } },
"",
rawValue
);
};
const showSpacingPresetsControl = hasSpacingPresets(settings2);
const units2 = (0, import_components202.__experimentalUseCustomUnits)({
availableUnits: settings2?.spacing?.units || [
"%",
"px",
"em",
"rem",
"vw"
]
});
const minimumMargin = -Infinity;
const [minMarginValue, setMinMarginValue] = (0, import_element250.useState)(minimumMargin);
const resetAllFilter = (0, import_element250.useCallback)((previousValue) => {
return {
...previousValue,
layout: cleanEmptyObject({
...previousValue?.layout,
contentSize: void 0,
wideSize: void 0,
selfStretch: void 0,
flexSize: void 0,
columnStart: void 0,
rowStart: void 0,
columnSpan: void 0,
rowSpan: void 0
}),
spacing: {
...previousValue?.spacing,
padding: void 0,
margin: void 0,
blockGap: void 0
},
dimensions: {
...previousValue?.dimensions,
height: void 0,
minHeight: void 0,
minWidth: void 0,
aspectRatio: void 0,
width: void 0
}
};
}, []);
const showContentSizeControl = hasContentSize(settings2) && includeLayoutControls;
const contentSizeValue = decodeValue(inheritedValue?.layout?.contentSize);
const setContentSizeValue = (newValue) => {
onChange(
setImmutably2(
value,
["layout", "contentSize"],
newValue || void 0
)
);
};
const hasUserSetContentSizeValue = () => !!value?.layout?.contentSize;
const resetContentSizeValue = () => setContentSizeValue(void 0);
const showWideSizeControl = hasWideSize(settings2) && includeLayoutControls;
const wideSizeValue = decodeValue(inheritedValue?.layout?.wideSize);
const setWideSizeValue = (newValue) => {
onChange(
setImmutably2(
value,
["layout", "wideSize"],
newValue || void 0
)
);
};
const hasUserSetWideSizeValue = () => !!value?.layout?.wideSize;
const resetWideSizeValue = () => setWideSizeValue(void 0);
const showPaddingControl = hasPadding(settings2);
const rawPadding = decodeValue(inheritedValue?.spacing?.padding);
const paddingValues = splitStyleValue(rawPadding);
const paddingSides = Array.isArray(settings2?.spacing?.padding) ? settings2?.spacing?.padding : settings2?.spacing?.padding?.sides;
const isAxialPadding = paddingSides && paddingSides.some((side) => AXIAL_SIDES.includes(side));
const setPaddingValues = (newPaddingValues) => {
const padding = filterValuesBySides(newPaddingValues, paddingSides);
onChange(setImmutably2(value, ["spacing", "padding"], padding));
};
const hasPaddingValue = () => !!value?.spacing?.padding && Object.keys(value?.spacing?.padding).length;
const resetPaddingValue = () => setPaddingValues(void 0);
const onMouseOverPadding = () => onVisualize("padding");
const showMarginControl = hasMargin(settings2);
const rawMargin = decodeValue(inheritedValue?.spacing?.margin);
const marginValues = splitStyleValue(rawMargin);
const marginSides = Array.isArray(settings2?.spacing?.margin) ? settings2?.spacing?.margin : settings2?.spacing?.margin?.sides;
const isAxialMargin = marginSides && marginSides.some((side) => AXIAL_SIDES.includes(side));
const setMarginValues = (newMarginValues) => {
const margin = filterValuesBySides(newMarginValues, marginSides);
onChange(setImmutably2(value, ["spacing", "margin"], margin));
};
const hasMarginValue = () => !!value?.spacing?.margin && Object.keys(value?.spacing?.margin).length;
const resetMarginValue = () => setMarginValues(void 0);
const onMouseOverMargin = () => onVisualize("margin");
const showGapControl = hasGap(settings2);
const gapSides = Array.isArray(settings2?.spacing?.blockGap) ? settings2?.spacing?.blockGap : settings2?.spacing?.blockGap?.sides;
const isAxialGap = gapSides && gapSides.some((side) => AXIAL_SIDES.includes(side));
const gapValue = decodeValue(inheritedValue?.spacing?.blockGap);
const gapValues = splitGapValue(gapValue, isAxialGap);
const setGapValue = (newGapValue) => {
onChange(
setImmutably2(value, ["spacing", "blockGap"], newGapValue)
);
};
const setGapValues = (nextBoxGapValue) => {
if (!nextBoxGapValue) {
setGapValue(null);
}
if (!isAxialGap && nextBoxGapValue?.hasOwnProperty("top")) {
setGapValue(nextBoxGapValue.top);
} else {
setGapValue({
top: nextBoxGapValue?.top,
left: nextBoxGapValue?.left
});
}
};
const resetGapValue = () => setGapValue(void 0);
const hasGapValue = () => !!value?.spacing?.blockGap;
const showMinHeightControl = hasMinHeight(settings2);
const minHeightValue = decodeValue(inheritedValue?.dimensions?.minHeight);
const setMinHeightValue = (newValue) => {
const tempValue = setImmutably2(
value,
["dimensions", "minHeight"],
newValue
);
onChange(
setImmutably2(
tempValue,
["dimensions", "aspectRatio"],
void 0
)
);
};
const resetMinHeightValue = () => {
setMinHeightValue(void 0);
};
const hasMinHeightValue = () => !!value?.dimensions?.minHeight;
const showHeightControl = hasHeight(settings2);
const heightValue = decodeValue(inheritedValue?.dimensions?.height);
const setHeightValue = (newValue) => {
const tempValue = setImmutably2(
value,
["dimensions", "height"],
newValue
);
onChange(
setImmutably2(
tempValue,
["dimensions", "aspectRatio"],
void 0
)
);
};
const resetHeightValue = () => {
setHeightValue(void 0);
};
const hasHeightValue = () => !!value?.dimensions?.height;
const showMinWidthControl = hasMinWidth(settings2);
const minWidthValue = decodeValue(inheritedValue?.dimensions?.minWidth);
const setMinWidthValue = (newValue) => {
onChange(
setImmutably2(value, ["dimensions", "minWidth"], newValue)
);
};
const resetMinWidthValue = () => {
setMinWidthValue(void 0);
};
const hasMinWidthValue = () => !!value?.dimensions?.minWidth;
const showWidthControl = hasWidth(settings2);
const widthValue = decodeValue(inheritedValue?.dimensions?.width);
const setWidthValue = (newValue) => {
onChange(setImmutably2(value, ["dimensions", "width"], newValue));
};
const resetWidthValue = () => {
setWidthValue(void 0);
};
const hasWidthValue = () => !!value?.dimensions?.width;
const showAspectRatioControl = hasAspectRatio(settings2, styleState);
const aspectRatioValue = decodeValue(
inheritedValue?.dimensions?.aspectRatio
);
const setAspectRatioValue = (newValue) => {
const tempValue = setImmutably2(
value,
["dimensions", "aspectRatio"],
newValue
);
onChange(
setImmutably2(tempValue, ["dimensions", "minHeight"], void 0)
);
};
const hasAspectRatioValue = () => !!value?.dimensions?.aspectRatio;
const showChildLayoutControl = hasChildLayout(settings2, styleState);
const childLayout = inheritedValue?.layout;
const setChildLayout = (newChildLayout) => {
onChange({
...value,
layout: {
...value?.layout,
...newChildLayout
}
});
};
const onMouseLeaveControls = () => onVisualize(false);
return /* @__PURE__ */ (0, import_jsx_runtime426.jsxs)(
Wrapper,
{
resetAllFilter,
value,
onChange,
panelId,
children: [
(showContentSizeControl || showWideSizeControl) && /* @__PURE__ */ (0, import_jsx_runtime426.jsx)("span", { className: "span-columns", children: (0, import_i18n192.__)("Set the width of the main content area.") }),
showContentSizeControl && /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
import_components202.__experimentalToolsPanelItem,
{
label: (0, import_i18n192.__)("Content width"),
hasValue: hasUserSetContentSizeValue,
onDeselect: resetContentSizeValue,
isShownByDefault: defaultControls.contentSize ?? DEFAULT_CONTROLS5.contentSize,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
import_components202.__experimentalUnitControl,
{
label: (0, import_i18n192.__)("Content width"),
labelPosition: "top",
value: contentSizeValue || "",
onChange: (nextContentSize) => {
setContentSizeValue(nextContentSize);
},
units: units2,
prefix: /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(import_components202.__experimentalInputControlPrefixWrapper, { variant: "icon", children: /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(icon_default, { icon: align_none_default }) })
}
)
}
),
showWideSizeControl && /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
import_components202.__experimentalToolsPanelItem,
{
label: (0, import_i18n192.__)("Wide width"),
hasValue: hasUserSetWideSizeValue,
onDeselect: resetWideSizeValue,
isShownByDefault: defaultControls.wideSize ?? DEFAULT_CONTROLS5.wideSize,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
import_components202.__experimentalUnitControl,
{
label: (0, import_i18n192.__)("Wide width"),
labelPosition: "top",
value: wideSizeValue || "",
onChange: (nextWideSize) => {
setWideSizeValue(nextWideSize);
},
units: units2,
prefix: /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(import_components202.__experimentalInputControlPrefixWrapper, { variant: "icon", children: /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(icon_default, { icon: stretch_wide_default }) })
}
)
}
),
showPaddingControl && /* @__PURE__ */ (0, import_jsx_runtime426.jsxs)(
import_components202.__experimentalToolsPanelItem,
{
hasValue: hasPaddingValue,
label: (0, import_i18n192.__)("Padding"),
onDeselect: resetPaddingValue,
isShownByDefault: defaultControls.padding ?? DEFAULT_CONTROLS5.padding,
className: clsx_default({
"tools-panel-item-spacing": showSpacingPresetsControl
}),
panelId,
children: [
!showSpacingPresetsControl && /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
import_components202.BoxControl,
{
values: paddingValues,
onChange: setPaddingValues,
label: (0, import_i18n192.__)("Padding"),
sides: paddingSides,
units: units2,
allowReset: false,
splitOnAxis: isAxialPadding,
inputProps: {
onMouseOver: onMouseOverPadding,
onMouseOut: onMouseLeaveControls
}
}
),
showSpacingPresetsControl && /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
SpacingSizesControl,
{
values: paddingValues,
onChange: setPaddingValues,
label: (0, import_i18n192.__)("Padding"),
sides: paddingSides,
units: units2,
allowReset: false,
onMouseOver: onMouseOverPadding,
onMouseOut: onMouseLeaveControls
}
)
]
}
),
showMarginControl && /* @__PURE__ */ (0, import_jsx_runtime426.jsxs)(
import_components202.__experimentalToolsPanelItem,
{
hasValue: hasMarginValue,
label: (0, import_i18n192.__)("Margin"),
onDeselect: resetMarginValue,
isShownByDefault: defaultControls.margin ?? DEFAULT_CONTROLS5.margin,
className: clsx_default({
"tools-panel-item-spacing": showSpacingPresetsControl
}),
panelId,
children: [
!showSpacingPresetsControl && /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
import_components202.BoxControl,
{
values: marginValues,
onChange: setMarginValues,
inputProps: {
min: minMarginValue,
onDragStart: () => {
setMinMarginValue(0);
},
onDragEnd: () => {
setMinMarginValue(minimumMargin);
},
onMouseOver: onMouseOverMargin,
onMouseOut: onMouseLeaveControls
},
label: (0, import_i18n192.__)("Margin"),
sides: marginSides,
units: units2,
allowReset: false,
splitOnAxis: isAxialMargin
}
),
showSpacingPresetsControl && /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
SpacingSizesControl,
{
values: marginValues,
onChange: setMarginValues,
minimumCustomValue: -Infinity,
label: (0, import_i18n192.__)("Margin"),
sides: marginSides,
units: units2,
allowReset: false,
onMouseOver: onMouseOverMargin,
onMouseOut: onMouseLeaveControls
}
)
]
}
),
showGapControl && /* @__PURE__ */ (0, import_jsx_runtime426.jsxs)(
import_components202.__experimentalToolsPanelItem,
{
hasValue: hasGapValue,
label: (0, import_i18n192.__)("Block spacing"),
onDeselect: resetGapValue,
isShownByDefault: defaultControls.blockGap ?? DEFAULT_CONTROLS5.blockGap,
className: clsx_default({
"tools-panel-item-spacing": showSpacingPresetsControl,
"single-column": (
// If UnitControl is used, should be single-column.
!showSpacingPresetsControl && !isAxialGap
)
}),
panelId,
children: [
!showSpacingPresetsControl && (isAxialGap ? /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
import_components202.BoxControl,
{
label: (0, import_i18n192.__)("Block spacing"),
min: 0,
onChange: setGapValues,
units: units2,
sides: gapSides,
values: gapValues,
allowReset: false,
splitOnAxis: isAxialGap
}
) : /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
import_components202.__experimentalUnitControl,
{
label: (0, import_i18n192.__)("Block spacing"),
min: 0,
onChange: setGapValue,
units: units2,
value: gapValue
}
)),
showSpacingPresetsControl && /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
SpacingSizesControl,
{
label: (0, import_i18n192.__)("Block spacing"),
min: 0,
onChange: setGapValues,
showSideInLabel: false,
sides: isAxialGap ? gapSides : ["top"],
values: gapValues,
allowReset: false
}
)
]
}
),
showChildLayoutControl && /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
ChildLayoutControl,
{
value: childLayout,
onChange: setChildLayout,
parentLayout: settings2?.parentLayout,
panelId,
showGridSpanDefaults: !hasViewportBlockStyleState(styleState),
isShownByDefault: defaultControls.childLayout ?? DEFAULT_CONTROLS5.childLayout
}
),
showMinHeightControl && /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
import_components202.__experimentalToolsPanelItem,
{
hasValue: hasMinHeightValue,
label: (0, import_i18n192.__)("Minimum height"),
onDeselect: resetMinHeightValue,
isShownByDefault: defaultControls.minHeight ?? DEFAULT_CONTROLS5.minHeight,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
DimensionControl,
{
label: (0, import_i18n192.__)("Minimum height"),
value: minHeightValue,
onChange: setMinHeightValue,
dimensionSizes: dimensions?.dimensionSizes
}
)
}
),
showMinWidthControl && /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
import_components202.__experimentalToolsPanelItem,
{
hasValue: hasMinWidthValue,
label: (0, import_i18n192.__)("Minimum width"),
onDeselect: resetMinWidthValue,
isShownByDefault: defaultControls.minWidth ?? DEFAULT_CONTROLS5.minWidth,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
DimensionControl,
{
label: (0, import_i18n192.__)("Minimum width"),
value: minWidthValue,
onChange: setMinWidthValue,
dimensionSizes: dimensions?.dimensionSizes
}
)
}
),
showHeightControl && /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
import_components202.__experimentalToolsPanelItem,
{
hasValue: hasHeightValue,
label: (0, import_i18n192.__)("Height"),
onDeselect: resetHeightValue,
isShownByDefault: defaultControls.height ?? DEFAULT_CONTROLS5.height,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
DimensionControl,
{
label: (0, import_i18n192.__)("Height"),
value: heightValue,
onChange: setHeightValue,
dimensionSizes: dimensions?.dimensionSizes
}
)
}
),
showWidthControl && /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
import_components202.__experimentalToolsPanelItem,
{
hasValue: hasWidthValue,
label: (0, import_i18n192.__)("Width"),
onDeselect: resetWidthValue,
isShownByDefault: defaultControls.width ?? DEFAULT_CONTROLS5.width,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
DimensionControl,
{
label: (0, import_i18n192.__)("Width"),
value: widthValue,
onChange: setWidthValue,
dimensionSizes: dimensions?.dimensionSizes
}
)
}
),
showAspectRatioControl && /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
AspectRatioTool,
{
hasValue: hasAspectRatioValue,
value: aspectRatioValue,
onChange: setAspectRatioValue,
panelId,
isShownByDefault: defaultControls.aspectRatio ?? DEFAULT_CONTROLS5.aspectRatio
}
)
]
}
);
}
// packages/block-editor/build-module/components/global-styles/border-panel.mjs
var import_components204 = __toESM(require_components(), 1);
var import_element252 = __toESM(require_element(), 1);
var import_i18n194 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/global-styles/shadow-panel-components.mjs
var import_i18n193 = __toESM(require_i18n(), 1);
var import_components203 = __toESM(require_components(), 1);
var import_element251 = __toESM(require_element(), 1);
var import_jsx_runtime427 = __toESM(require_jsx_runtime(), 1);
var EMPTY_ARRAY13 = [];
function ShadowPopoverContainer({ shadow, onShadowChange, settings: settings2 }) {
const shadows = useShadowPresets(settings2);
return /* @__PURE__ */ (0, import_jsx_runtime427.jsx)("div", { className: "block-editor-global-styles__shadow-popover-container", children: /* @__PURE__ */ (0, import_jsx_runtime427.jsxs)(import_components203.__experimentalVStack, { spacing: 4, children: [
/* @__PURE__ */ (0, import_jsx_runtime427.jsx)(import_components203.__experimentalHeading, { level: 5, children: (0, import_i18n193.__)("Drop shadow") }),
/* @__PURE__ */ (0, import_jsx_runtime427.jsx)(
ShadowPresets,
{
presets: shadows,
activeShadow: shadow,
onSelect: onShadowChange
}
),
/* @__PURE__ */ (0, import_jsx_runtime427.jsx)("div", { className: "block-editor-global-styles__clear-shadow", children: /* @__PURE__ */ (0, import_jsx_runtime427.jsx)(
import_components203.Button,
{
__next40pxDefaultSize: true,
variant: "tertiary",
onClick: () => onShadowChange(void 0),
disabled: !shadow,
accessibleWhenDisabled: true,
children: (0, import_i18n193.__)("Clear")
}
) })
] }) });
}
function ShadowPresets({ presets, activeShadow, onSelect }) {
return !presets ? null : /* @__PURE__ */ (0, import_jsx_runtime427.jsx)(
import_components203.Composite,
{
role: "listbox",
className: "block-editor-global-styles__shadow__list",
"aria-label": (0, import_i18n193.__)("Drop shadows"),
children: presets.map(({ name, slug, shadow }) => /* @__PURE__ */ (0, import_jsx_runtime427.jsx)(
ShadowIndicator,
{
label: name,
isActive: shadow === activeShadow,
type: slug === "unset" ? "unset" : "preset",
onSelect: () => onSelect(shadow === activeShadow ? void 0 : shadow),
shadow
},
slug
))
}
);
}
function ShadowIndicator({ type, label, isActive, onSelect, shadow }) {
return /* @__PURE__ */ (0, import_jsx_runtime427.jsxs)(tooltip_exports.Root, { children: [
/* @__PURE__ */ (0, import_jsx_runtime427.jsx)(
tooltip_exports.Trigger,
{
render: /* @__PURE__ */ (0, import_jsx_runtime427.jsx)(
import_components203.Composite.Item,
{
role: "option",
"aria-label": label,
"aria-selected": isActive,
className: clsx_default(
"block-editor-global-styles__shadow__item",
{
"is-active": isActive
}
),
render: /* @__PURE__ */ (0, import_jsx_runtime427.jsx)(
"button",
{
className: clsx_default(
"block-editor-global-styles__shadow-indicator",
{
unset: type === "unset"
}
),
onClick: onSelect,
style: { boxShadow: shadow },
"aria-label": label,
children: isActive && /* @__PURE__ */ (0, import_jsx_runtime427.jsx)(icon_default, { icon: check_default })
}
)
}
)
}
),
/* @__PURE__ */ (0, import_jsx_runtime427.jsx)(tooltip_exports.Popup, { children: label })
] });
}
function ShadowPopover({ shadow, onShadowChange, settings: settings2 }) {
const popoverProps3 = {
placement: "left-start",
offset: 36,
shift: true
};
return /* @__PURE__ */ (0, import_jsx_runtime427.jsx)(
import_components203.Dropdown,
{
popoverProps: popoverProps3,
className: "block-editor-global-styles__shadow-dropdown",
renderToggle: renderShadowToggle(shadow, onShadowChange),
renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime427.jsx)(import_components203.__experimentalDropdownContentWrapper, { paddingSize: "medium", children: /* @__PURE__ */ (0, import_jsx_runtime427.jsx)(
ShadowPopoverContainer,
{
shadow,
onShadowChange,
settings: settings2
}
) })
}
);
}
function renderShadowToggle(shadow, onShadowChange) {
return function ShadowToggle({ onToggle, isOpen }) {
const shadowButtonRef = (0, import_element251.useRef)(void 0);
const toggleProps = {
onClick: onToggle,
className: clsx_default(
"block-editor-global-styles__shadow-dropdown-toggle",
{ "is-open": isOpen }
),
"aria-expanded": isOpen,
ref: shadowButtonRef
};
const removeButtonProps = {
onClick: () => {
if (isOpen) {
onToggle();
}
onShadowChange(void 0);
shadowButtonRef.current?.focus();
},
className: clsx_default(
"block-editor-global-styles__shadow-editor__remove-button",
{ "is-open": isOpen }
),
label: (0, import_i18n193.__)("Remove")
};
return /* @__PURE__ */ (0, import_jsx_runtime427.jsxs)(import_jsx_runtime427.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime427.jsx)(import_components203.Button, { __next40pxDefaultSize: true, ...toggleProps, children: /* @__PURE__ */ (0, import_jsx_runtime427.jsxs)(import_components203.__experimentalHStack, { justify: "flex-start", children: [
/* @__PURE__ */ (0, import_jsx_runtime427.jsx)(
icon_default,
{
className: "block-editor-global-styles__toggle-icon",
icon: shadow_default,
size: 24
}
),
/* @__PURE__ */ (0, import_jsx_runtime427.jsx)(import_components203.FlexItem, { children: (0, import_i18n193.__)("Drop shadow") })
] }) }),
!!shadow && /* @__PURE__ */ (0, import_jsx_runtime427.jsx)(
import_components203.Button,
{
__next40pxDefaultSize: true,
size: "small",
icon: reset_default,
...removeButtonProps
}
)
] });
};
}
function useShadowPresets(settings2) {
return (0, import_element251.useMemo)(() => {
if (!settings2?.shadow) {
return EMPTY_ARRAY13;
}
const defaultPresetsEnabled = settings2?.shadow?.defaultPresets;
const {
default: defaultShadows,
theme: themeShadows,
custom: customShadows
} = settings2?.shadow?.presets ?? {};
const unsetShadow = {
name: (0, import_i18n193.__)("Unset"),
slug: "unset",
shadow: "none"
};
const shadowPresets = [
...defaultPresetsEnabled && defaultShadows || EMPTY_ARRAY13,
...themeShadows || EMPTY_ARRAY13,
...customShadows || EMPTY_ARRAY13
];
if (shadowPresets.length) {
shadowPresets.unshift(unsetShadow);
}
return shadowPresets;
}, [settings2]);
}
// packages/block-editor/build-module/components/global-styles/border-panel.mjs
var import_jsx_runtime428 = __toESM(require_jsx_runtime(), 1);
function useHasBorderPanel(settings2) {
const controls = Object.values(useHasBorderPanelControls(settings2));
return controls.some(Boolean);
}
function useHasBorderPanelControls(settings2) {
const controls = {
hasBorderColor: useHasBorderColorControl(settings2),
hasBorderRadius: useHasBorderRadiusControl(settings2),
hasBorderStyle: useHasBorderStyleControl(settings2),
hasBorderWidth: useHasBorderWidthControl(settings2),
hasShadow: useHasShadowControl(settings2)
};
return controls;
}
function useHasBorderColorControl(settings2) {
return settings2?.border?.color;
}
function useHasBorderRadiusControl(settings2) {
return settings2?.border?.radius;
}
function useHasBorderStyleControl(settings2) {
return settings2?.border?.style;
}
function useHasBorderWidthControl(settings2) {
return settings2?.border?.width;
}
function useHasShadowControl(settings2) {
const shadows = useShadowPresets(settings2);
return !!settings2?.shadow && shadows.length > 0;
}
function BorderToolsPanel({
resetAllFilter,
onChange,
value,
panelId,
children,
label
}) {
const dropdownMenuProps = useToolsPanelDropdownMenuProps();
const resetAll = () => {
const updatedValue = resetAllFilter(value);
onChange(updatedValue);
};
return /* @__PURE__ */ (0, import_jsx_runtime428.jsx)(
import_components204.__experimentalToolsPanel,
{
label,
resetAll,
panelId,
dropdownMenuProps,
children
}
);
}
var DEFAULT_CONTROLS6 = {
radius: true,
color: true,
width: true,
shadow: true
};
function BorderPanel({
as: Wrapper = BorderToolsPanel,
value,
onChange,
inheritedValue = value,
settings: settings2,
panelId,
name,
defaultControls = DEFAULT_CONTROLS6
}) {
const colors2 = useColorsPerOrigin(settings2);
const areCustomSolidsEnabled = settings2?.color?.custom;
const decodeValue = (0, import_element252.useCallback)(
(rawValue) => getValueFromVariable({ settings: settings2 }, "", rawValue),
[settings2]
);
const encodeColorValue = (colorValue) => {
const allColors = colors2.flatMap(
({ colors: originColors }) => originColors
);
const colorObject = allColors.find(
({ color }) => color === colorValue
);
return colorObject ? "var:preset|color|" + colorObject.slug : colorValue;
};
const border = (0, import_element252.useMemo)(() => {
if ((0, import_components204.__experimentalHasSplitBorders)(inheritedValue?.border)) {
const borderValue = { ...inheritedValue?.border };
["top", "right", "bottom", "left"].forEach((side) => {
borderValue[side] = {
...borderValue[side],
color: decodeValue(borderValue[side]?.color)
};
});
return borderValue;
}
return {
...inheritedValue?.border,
color: inheritedValue?.border?.color ? decodeValue(inheritedValue?.border?.color) : void 0
};
}, [inheritedValue?.border, decodeValue]);
const setBorder = (newBorder) => onChange({ ...value, border: newBorder });
const showBorderColor = useHasBorderColorControl(settings2);
const showBorderStyle = useHasBorderStyleControl(settings2);
const showBorderWidth = useHasBorderWidthControl(settings2);
const showBorderRadius = useHasBorderRadiusControl(settings2);
const borderRadiusValues = (0, import_element252.useMemo)(() => {
if (typeof inheritedValue?.border?.radius !== "object") {
return decodeValue(inheritedValue?.border?.radius);
}
return {
topLeft: decodeValue(inheritedValue?.border?.radius?.topLeft),
topRight: decodeValue(inheritedValue?.border?.radius?.topRight),
bottomLeft: decodeValue(
inheritedValue?.border?.radius?.bottomLeft
),
bottomRight: decodeValue(
inheritedValue?.border?.radius?.bottomRight
)
};
}, [inheritedValue?.border?.radius, decodeValue]);
const setBorderRadius = (newBorderRadius) => setBorder({ ...border, radius: newBorderRadius });
const hasBorderRadius = () => {
const borderValues = value?.border?.radius;
if (typeof borderValues === "object") {
return Object.entries(borderValues).some(Boolean);
}
return !!borderValues;
};
const hasShadowControl = useHasShadowControl(settings2);
const shadow = decodeValue(inheritedValue?.shadow);
const shadowPresets = settings2?.shadow?.presets ?? {};
const mergedShadowPresets = shadowPresets.custom ?? shadowPresets.theme ?? shadowPresets.default ?? [];
const setShadow = (newValue) => {
const slug = mergedShadowPresets?.find(
({ shadow: shadowName }) => shadowName === newValue
)?.slug;
onChange(
setImmutably2(
value,
["shadow"],
slug ? `var:preset|shadow|${slug}` : newValue || void 0
)
);
};
const hasShadow = () => !!value?.shadow;
const resetShadow = () => setShadow(void 0);
const resetBorder = () => {
if (hasBorderRadius()) {
return setBorder({ radius: value?.border?.radius });
}
setBorder(void 0);
};
const onBorderChange = (newBorder) => {
const updatedBorder = { ...newBorder };
if ((0, import_components204.__experimentalHasSplitBorders)(updatedBorder)) {
["top", "right", "bottom", "left"].forEach((side) => {
if (updatedBorder[side]) {
updatedBorder[side] = {
...updatedBorder[side],
color: encodeColorValue(updatedBorder[side]?.color)
};
}
});
} else if (updatedBorder) {
updatedBorder.color = encodeColorValue(updatedBorder.color);
}
setBorder({ radius: border?.radius, ...updatedBorder });
};
const resetAllFilter = (0, import_element252.useCallback)((previousValue) => {
return {
...previousValue,
border: void 0,
shadow: void 0
};
}, []);
const showBorderByDefault = defaultControls?.color || defaultControls?.width;
const hasBorderControl = showBorderColor || showBorderStyle || showBorderWidth || showBorderRadius;
const label = useBorderPanelLabel({
blockName: name,
hasShadowControl,
hasBorderControl
});
return /* @__PURE__ */ (0, import_jsx_runtime428.jsxs)(
Wrapper,
{
resetAllFilter,
value,
onChange,
panelId,
label,
children: [
(showBorderWidth || showBorderColor) && /* @__PURE__ */ (0, import_jsx_runtime428.jsx)(
import_components204.__experimentalToolsPanelItem,
{
hasValue: () => (0, import_components204.__experimentalIsDefinedBorder)(value?.border),
label: (0, import_i18n194.__)("Border"),
onDeselect: () => resetBorder(),
isShownByDefault: showBorderByDefault,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime428.jsx)(
import_components204.BorderBoxControl,
{
colors: colors2,
disableCustomColors: !areCustomSolidsEnabled,
enableAlpha: true,
enableStyle: showBorderStyle,
onChange: onBorderChange,
popoverOffset: 40,
popoverPlacement: "left-start",
value: border,
__experimentalIsRenderedInSidebar: true,
hideLabelFromVision: !hasShadowControl,
label: (0, import_i18n194.__)("Border")
}
)
}
),
showBorderRadius && /* @__PURE__ */ (0, import_jsx_runtime428.jsx)(
import_components204.__experimentalToolsPanelItem,
{
hasValue: hasBorderRadius,
label: (0, import_i18n194.__)("Radius"),
onDeselect: () => setBorderRadius(void 0),
isShownByDefault: defaultControls.radius,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime428.jsx)(
BorderRadiusControl,
{
presets: settings2?.border?.radiusSizes,
values: borderRadiusValues,
onChange: (newValue) => {
setBorderRadius(newValue || void 0);
}
}
)
}
),
hasShadowControl && /* @__PURE__ */ (0, import_jsx_runtime428.jsxs)(
import_components204.__experimentalToolsPanelItem,
{
label: (0, import_i18n194.__)("Shadow"),
hasValue: hasShadow,
onDeselect: resetShadow,
isShownByDefault: defaultControls.shadow,
panelId,
children: [
hasBorderControl ? /* @__PURE__ */ (0, import_jsx_runtime428.jsx)(import_components204.BaseControl.VisualLabel, { as: "legend", children: (0, import_i18n194.__)("Shadow") }) : null,
/* @__PURE__ */ (0, import_jsx_runtime428.jsx)(
ShadowPopover,
{
shadow,
onShadowChange: setShadow,
settings: settings2
}
)
]
}
)
]
}
);
}
// packages/block-editor/build-module/components/global-styles/filters-panel.mjs
var import_components205 = __toESM(require_components(), 1);
var import_i18n195 = __toESM(require_i18n(), 1);
var import_element253 = __toESM(require_element(), 1);
var import_jsx_runtime429 = __toESM(require_jsx_runtime(), 1);
var EMPTY_ARRAY14 = [];
function useMultiOriginColorPresets(settings2, { presetSetting, defaultSetting }) {
const disableDefault = !settings2?.color?.[defaultSetting];
const userPresets = settings2?.color?.[presetSetting]?.custom || EMPTY_ARRAY14;
const themePresets = settings2?.color?.[presetSetting]?.theme || EMPTY_ARRAY14;
const defaultPresets = settings2?.color?.[presetSetting]?.default || EMPTY_ARRAY14;
return (0, import_element253.useMemo)(
() => [
...userPresets,
...themePresets,
...disableDefault ? EMPTY_ARRAY14 : defaultPresets
],
[disableDefault, userPresets, themePresets, defaultPresets]
);
}
function useHasFiltersPanel(settings2) {
return useHasDuotoneControl(settings2);
}
function useHasDuotoneControl(settings2) {
return settings2.color.customDuotone || settings2.color.defaultDuotone || settings2.color.duotone.length > 0;
}
function FiltersToolsPanel({
resetAllFilter,
onChange,
value,
panelId,
children
}) {
const dropdownMenuProps = useToolsPanelDropdownMenuProps();
const resetAll = () => {
const updatedValue = resetAllFilter(value);
onChange(updatedValue);
};
return /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(
import_components205.__experimentalToolsPanel,
{
label: (0, import_i18n195._x)("Filters", "Name for applying graphical effects"),
resetAll,
panelId,
dropdownMenuProps,
children
}
);
}
var DEFAULT_CONTROLS7 = {
duotone: true
};
var popoverProps2 = {
placement: "left-start",
offset: 36,
shift: true,
className: "block-editor-duotone-control__popover",
headerTitle: (0, import_i18n195.__)("Duotone")
};
var LabeledColorIndicator2 = ({ indicator, label }) => /* @__PURE__ */ (0, import_jsx_runtime429.jsxs)(import_components205.__experimentalHStack, { justify: "flex-start", children: [
/* @__PURE__ */ (0, import_jsx_runtime429.jsx)(import_components205.__experimentalZStack, { isLayered: false, offset: -8, children: /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(import_components205.Flex, { expanded: false, children: indicator === "unset" || !indicator ? /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(import_components205.ColorIndicator, { className: "block-editor-duotone-control__unset-indicator" }) : /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(import_components205.DuotoneSwatch, { values: indicator }) }) }),
/* @__PURE__ */ (0, import_jsx_runtime429.jsx)(import_components205.FlexItem, { title: label, children: label })
] });
var renderToggle2 = (duotone, resetDuotone) => function Toggle2({ onToggle, isOpen }) {
const duotoneButtonRef = (0, import_element253.useRef)(void 0);
const toggleProps = {
onClick: onToggle,
className: clsx_default(
"block-editor-global-styles-filters-panel__dropdown-toggle",
{ "is-open": isOpen }
),
"aria-expanded": isOpen,
ref: duotoneButtonRef
};
const removeButtonProps = {
onClick: () => {
if (isOpen) {
onToggle();
}
resetDuotone();
duotoneButtonRef.current?.focus();
},
className: "block-editor-panel-duotone-settings__reset",
label: (0, import_i18n195.__)("Reset")
};
return /* @__PURE__ */ (0, import_jsx_runtime429.jsxs)(import_jsx_runtime429.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime429.jsx)(import_components205.Button, { __next40pxDefaultSize: true, ...toggleProps, children: /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(
LabeledColorIndicator2,
{
indicator: duotone,
label: (0, import_i18n195.__)("Duotone")
}
) }),
duotone && /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(
import_components205.Button,
{
size: "small",
icon: reset_default,
...removeButtonProps
}
)
] });
};
function FiltersPanel({
as: Wrapper = FiltersToolsPanel,
value,
onChange,
inheritedValue = value,
settings: settings2,
panelId,
defaultControls = DEFAULT_CONTROLS7
}) {
const decodeValue = (rawValue) => getValueFromVariable({ settings: settings2 }, "", rawValue);
const hasDuotoneEnabled = useHasDuotoneControl(settings2);
const duotonePalette = useMultiOriginColorPresets(settings2, {
presetSetting: "duotone",
defaultSetting: "defaultDuotone"
});
const colorPalette = useMultiOriginColorPresets(settings2, {
presetSetting: "palette",
defaultSetting: "defaultPalette"
});
const duotone = decodeValue(inheritedValue?.filter?.duotone);
const setDuotone = (newValue) => {
const duotonePreset = duotonePalette.find(({ colors: colors2 }) => {
return colors2 === newValue;
});
const duotoneValue = duotonePreset ? `var:preset|duotone|${duotonePreset.slug}` : newValue;
onChange(
setImmutably2(value, ["filter", "duotone"], duotoneValue)
);
};
const hasDuotone = () => !!value?.filter?.duotone;
const resetDuotone = () => setDuotone(void 0);
const resetAllFilter = (0, import_element253.useCallback)((previousValue) => {
return {
...previousValue,
filter: {
...previousValue.filter,
duotone: void 0
}
};
}, []);
return /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(
Wrapper,
{
resetAllFilter,
value,
onChange,
panelId,
children: hasDuotoneEnabled && /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(
import_components205.__experimentalToolsPanelItem,
{
label: (0, import_i18n195.__)("Duotone"),
hasValue: hasDuotone,
onDeselect: resetDuotone,
isShownByDefault: defaultControls.duotone,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(
import_components205.Dropdown,
{
popoverProps: popoverProps2,
className: "block-editor-global-styles-filters-panel__dropdown",
renderToggle: renderToggle2(duotone, resetDuotone),
renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(import_components205.__experimentalDropdownContentWrapper, { paddingSize: "small", children: /* @__PURE__ */ (0, import_jsx_runtime429.jsxs)(import_components205.MenuGroup, { label: (0, import_i18n195.__)("Duotone"), children: [
/* @__PURE__ */ (0, import_jsx_runtime429.jsx)("p", { children: (0, import_i18n195.__)(
"Create a two-tone color effect without losing your original image."
) }),
/* @__PURE__ */ (0, import_jsx_runtime429.jsx)(
import_components205.DuotonePicker,
{
colorPalette,
duotonePalette,
disableCustomColors: true,
disableCustomDuotone: true,
value: duotone,
onChange: setDuotone
}
)
] }) })
}
)
}
)
}
);
}
// packages/block-editor/build-module/components/global-styles/image-settings-panel.mjs
var import_components206 = __toESM(require_components(), 1);
var import_i18n196 = __toESM(require_i18n(), 1);
var import_jsx_runtime430 = __toESM(require_jsx_runtime(), 1);
function useHasImageSettingsPanel(name, value, inheritedValue) {
return name === "core/image" && inheritedValue?.lightbox?.allowEditing || !!value?.lightbox;
}
function ImageSettingsPanel({
onChange,
value,
inheritedValue,
panelId
}) {
const dropdownMenuProps = useToolsPanelDropdownMenuProps();
const resetLightbox = () => {
onChange(void 0);
};
const onChangeLightbox = (newSetting) => {
onChange({
enabled: newSetting
});
};
let lightboxChecked = false;
if (inheritedValue?.lightbox?.enabled) {
lightboxChecked = inheritedValue.lightbox.enabled;
}
return /* @__PURE__ */ (0, import_jsx_runtime430.jsx)(import_jsx_runtime430.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime430.jsx)(
import_components206.__experimentalToolsPanel,
{
label: (0, import_i18n196._x)("Settings", "Image settings"),
resetAll: resetLightbox,
panelId,
dropdownMenuProps,
children: /* @__PURE__ */ (0, import_jsx_runtime430.jsx)(
import_components206.__experimentalToolsPanelItem,
{
hasValue: () => !!value?.lightbox,
label: (0, import_i18n196.__)("Enlarge on click"),
onDeselect: resetLightbox,
isShownByDefault: true,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime430.jsx)(
import_components206.ToggleControl,
{
label: (0, import_i18n196.__)("Enlarge on click"),
checked: lightboxChecked,
onChange: onChangeLightbox
}
)
}
)
}
) });
}
// packages/block-editor/build-module/components/global-styles/advanced-panel.mjs
var import_components207 = __toESM(require_components(), 1);
var import_element254 = __toESM(require_element(), 1);
var import_i18n197 = __toESM(require_i18n(), 1);
var import_jsx_runtime431 = __toESM(require_jsx_runtime(), 1);
function validateCSS(css) {
if (typeof css === "string" && /<\/?\w/.test(css)) {
return false;
}
return true;
}
function getMarkupValidationError(css) {
return validateCSS(css) ? null : (0, import_i18n197.__)("The custom CSS is invalid. Do not use <> markup.");
}
function getCSSValidationError(css) {
if (!css) {
return null;
}
const markupError = getMarkupValidationError(css);
if (markupError) {
return markupError;
}
const [transformed] = transform_styles_default(
[{ css }],
".for-validation-only"
);
return transformed === null ? (0, import_i18n197.__)("There is an error with your CSS structure.") : null;
}
function AdvancedPanel({
value,
onChange,
inheritedValue = value,
help
}) {
const customCSS = inheritedValue?.css;
const [cssError, setCSSError] = (0, import_element254.useState)(
() => getCSSValidationError(customCSS)
);
function handleOnChange(newValue) {
onChange({
...value,
css: newValue
});
setCSSError(getMarkupValidationError(newValue));
}
function handleOnBlur(event) {
setCSSError(getCSSValidationError(event?.target?.value));
}
return /* @__PURE__ */ (0, import_jsx_runtime431.jsxs)(
Stack,
{
direction: "column",
gap: "md",
className: "block-editor-global-styles-advanced-panel",
children: [
cssError && /* @__PURE__ */ (0, import_jsx_runtime431.jsx)(import_components207.Notice, { status: "error", onRemove: () => setCSSError(null), children: cssError }),
/* @__PURE__ */ (0, import_jsx_runtime431.jsx)(
import_components207.TextareaControl,
{
label: (0, import_i18n197.__)("Additional CSS"),
value: customCSS,
onChange: (newValue) => handleOnChange(newValue),
onBlur: handleOnBlur,
className: "block-editor-global-styles-advanced-panel__custom-css-input",
spellCheck: false,
help
}
)
]
}
);
}
// packages/block-editor/build-module/components/global-styles/background-panel.mjs
var import_components209 = __toESM(require_components(), 1);
var import_element256 = __toESM(require_element(), 1);
var import_i18n199 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/background-image-control/index.mjs
var import_components208 = __toESM(require_components(), 1);
var import_i18n198 = __toESM(require_i18n(), 1);
var import_notices12 = __toESM(require_notices(), 1);
var import_url11 = __toESM(require_url(), 1);
var import_element255 = __toESM(require_element(), 1);
var import_data163 = __toESM(require_data(), 1);
var import_dom70 = __toESM(require_dom(), 1);
var import_blob2 = __toESM(require_blob(), 1);
var import_jsx_runtime432 = __toESM(require_jsx_runtime(), 1);
var IMAGE_BACKGROUND_TYPE = "image";
var BACKGROUND_POPOVER_PROPS = {
placement: "left-start",
offset: 36,
shift: true,
className: "block-editor-global-styles-background-panel__popover"
};
var noop21 = () => {
};
var focusToggleButton = (containerRef) => {
window.requestAnimationFrame(() => {
const [toggleButton] = import_dom70.focus.tabbable.find(containerRef?.current);
if (!toggleButton) {
return;
}
toggleButton.focus();
});
};
function backgroundSizeHelpText(value) {
if (value === "cover" || value === void 0) {
return (0, import_i18n198.__)("Image covers the space evenly.");
}
if (value === "contain") {
return (0, import_i18n198.__)("Image is contained without distortion.");
}
return (0, import_i18n198.__)("Image has a fixed width.");
}
var coordsToBackgroundPosition = (value) => {
if (!value || isNaN(value.x) && isNaN(value.y)) {
return void 0;
}
const x2 = isNaN(value.x) ? 0.5 : value.x;
const y2 = isNaN(value.y) ? 0.5 : value.y;
return `${x2 * 100}% ${y2 * 100}%`;
};
var backgroundPositionToCoords = (value) => {
if (!value) {
return { x: void 0, y: void 0 };
}
let [x2, y2] = value.split(" ").map((v2) => parseFloat(v2) / 100);
x2 = isNaN(x2) ? void 0 : x2;
y2 = isNaN(y2) ? x2 : y2;
return { x: x2, y: y2 };
};
function InspectorImagePreviewItem({
as = "span",
imgUrl,
toggleProps = {},
filename,
label,
onToggleCallback = noop21
}) {
const { isOpen, ...restToggleProps } = toggleProps;
(0, import_element255.useEffect)(() => {
if (typeof isOpen !== "undefined") {
onToggleCallback(isOpen);
}
}, [isOpen, onToggleCallback]);
const renderPreviewContent = () => {
return /* @__PURE__ */ (0, import_jsx_runtime432.jsxs)(import_components208.__experimentalHStack, { className: "block-editor-global-styles-background-panel__inspector-preview-inner", children: [
/* @__PURE__ */ (0, import_jsx_runtime432.jsx)(
"span",
{
className: "block-editor-global-styles-background-panel__inspector-image-indicator",
style: {
backgroundImage: imgUrl ? `url(${imgUrl})` : void 0
}
}
),
/* @__PURE__ */ (0, import_jsx_runtime432.jsxs)(import_components208.FlexBlock, { children: [
/* @__PURE__ */ (0, import_jsx_runtime432.jsx)(
import_components208.__experimentalTruncate,
{
numberOfLines: 1,
className: "block-editor-global-styles-background-panel__inspector-media-replace-title",
children: label
}
),
/* @__PURE__ */ (0, import_jsx_runtime432.jsx)(VisuallyHidden, { render: /* @__PURE__ */ (0, import_jsx_runtime432.jsx)("span", {}), children: imgUrl ? (0, import_i18n198.sprintf)(
/* translators: %s: file name */
(0, import_i18n198.__)("Background image: %s"),
filename || label
) : (0, import_i18n198.__)("No background image selected") })
] })
] });
};
return as === "button" ? /* @__PURE__ */ (0, import_jsx_runtime432.jsx)(import_components208.Button, { __next40pxDefaultSize: true, ...restToggleProps, children: renderPreviewContent() }) : renderPreviewContent();
}
function BackgroundControlsPanel({
label,
filename,
url: imgUrl,
children,
onToggle: onToggleCallback = noop21,
hasImageValue,
onReset,
containerRef
}) {
if (!hasImageValue) {
return;
}
const imgLabel = label || (0, import_url11.getFilename)(imgUrl) || (0, import_i18n198.__)("Image");
return /* @__PURE__ */ (0, import_jsx_runtime432.jsx)(
import_components208.Dropdown,
{
popoverProps: BACKGROUND_POPOVER_PROPS,
renderToggle: ({ onToggle, isOpen }) => {
const toggleProps = {
onClick: onToggle,
className: "block-editor-global-styles-background-panel__dropdown-toggle",
"aria-expanded": isOpen,
"aria-label": (0, import_i18n198.__)(
"Background size, position and repeat options."
),
isOpen
};
return /* @__PURE__ */ (0, import_jsx_runtime432.jsxs)(import_jsx_runtime432.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime432.jsx)(
InspectorImagePreviewItem,
{
imgUrl,
filename,
label: imgLabel,
toggleProps,
as: "button",
onToggleCallback
}
),
onReset && /* @__PURE__ */ (0, import_jsx_runtime432.jsx)(
import_components208.Button,
{
__next40pxDefaultSize: true,
label: (0, import_i18n198.__)("Reset"),
className: "block-editor-global-styles-background-panel__reset",
size: "small",
icon: reset_default,
onClick: () => {
onReset();
if (isOpen) {
onToggle();
}
focusToggleButton(containerRef);
}
}
)
] });
},
renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime432.jsx)(
import_components208.__experimentalDropdownContentWrapper,
{
className: "block-editor-global-styles-background-panel__dropdown-content-wrapper",
paddingSize: "medium",
children
}
)
}
);
}
function LoadingSpinner() {
return /* @__PURE__ */ (0, import_jsx_runtime432.jsx)(import_components208.Placeholder, { className: "block-editor-global-styles-background-panel__loading", children: /* @__PURE__ */ (0, import_jsx_runtime432.jsx)(import_components208.Spinner, {}) });
}
function BackgroundImageControls({
onChange,
style,
inheritedValue,
onRemoveImage = noop21,
onResetImage = noop21,
displayInPanel,
defaultValues,
containerRef
}) {
const [isUploading, setIsUploading] = (0, import_element255.useState)(false);
const { getSettings: getSettings7 } = (0, import_data163.useSelect)(store);
const { id, title, url } = style?.background?.backgroundImage || {
...inheritedValue?.background?.backgroundImage
};
const { createErrorNotice } = (0, import_data163.useDispatch)(import_notices12.store);
const onUploadError = (message2) => {
createErrorNotice(message2, { type: "snackbar" });
setIsUploading(false);
};
const resetBackgroundImage = () => onChange(
setImmutably2(
style,
["background", "backgroundImage"],
void 0
)
);
const onSelectMedia = (media) => {
if (!media || !media.url) {
resetBackgroundImage();
setIsUploading(false);
return;
}
if ((0, import_blob2.isBlobURL)(media.url)) {
setIsUploading(true);
return;
}
if (media.media_type && media.media_type !== IMAGE_BACKGROUND_TYPE || !media.media_type && media.type && media.type !== IMAGE_BACKGROUND_TYPE) {
onUploadError(
(0, import_i18n198.__)("Only images can be used as a background image.")
);
return;
}
const sizeValue = style?.background?.backgroundSize || defaultValues?.backgroundSize;
const positionValue = style?.background?.backgroundPosition;
onChange(
setImmutably2(style, ["background"], {
...style?.background,
backgroundImage: {
url: media.url,
id: media.id,
source: "file",
title: media.title || void 0
},
backgroundPosition: (
/*
* A background image uploaded and set in the editor receives a default background position of '50% 0',
* when the background image size is the equivalent of "Tile".
* This is to increase the chance that the image's focus point is visible.
* This is in-editor only to assist with the user experience.
*/
!positionValue && ("auto" === sizeValue || !sizeValue) ? "50% 0" : positionValue
),
backgroundSize: sizeValue
})
);
setIsUploading(false);
focusToggleButton(containerRef);
};
const onFilesDrop2 = (filesList) => {
getSettings7().mediaUpload({
allowedTypes: [IMAGE_BACKGROUND_TYPE],
filesList,
onFileChange([image]) {
onSelectMedia(image);
},
onError: onUploadError,
multiple: false
});
};
const hasValue = hasBackgroundImageValue(style);
const onRemove = () => onChange(
setImmutably2(style, ["background"], {
backgroundImage: "none"
})
);
const canRemove = !hasValue && hasBackgroundImageValue(inheritedValue);
const imgLabel = title || (0, import_url11.getFilename)(url) || (0, import_i18n198.__)("Image");
return /* @__PURE__ */ (0, import_jsx_runtime432.jsxs)("div", { className: "block-editor-global-styles-background-panel__image-tools-panel-item", children: [
isUploading && /* @__PURE__ */ (0, import_jsx_runtime432.jsx)(LoadingSpinner, {}),
/* @__PURE__ */ (0, import_jsx_runtime432.jsx)(
media_replace_flow_default,
{
mediaId: id,
mediaURL: url,
allowedTypes: [IMAGE_BACKGROUND_TYPE],
accept: "image/*",
onSelect: onSelectMedia,
popoverProps: {
className: clsx_default({
"block-editor-global-styles-background-panel__media-replace-popover": displayInPanel
})
},
name: /* @__PURE__ */ (0, import_jsx_runtime432.jsx)(
InspectorImagePreviewItem,
{
imgUrl: url,
filename: title,
label: imgLabel
}
),
renderToggle: (props) => /* @__PURE__ */ (0, import_jsx_runtime432.jsx)(import_components208.Button, { ...props, __next40pxDefaultSize: true }),
onError: onUploadError,
onReset: () => {
focusToggleButton(containerRef);
onResetImage();
},
children: canRemove && /* @__PURE__ */ (0, import_jsx_runtime432.jsx)(
import_components208.MenuItem,
{
onClick: () => {
focusToggleButton(containerRef);
onRemove();
onRemoveImage();
},
children: (0, import_i18n198.__)("Remove")
}
)
}
),
/* @__PURE__ */ (0, import_jsx_runtime432.jsx)(
import_components208.DropZone,
{
onFilesDrop: onFilesDrop2,
label: (0, import_i18n198.__)("Drop to upload")
}
)
] });
}
function BackgroundSizeControls({
onChange,
style,
inheritedValue,
defaultValues
}) {
const sizeValue = style?.background?.backgroundSize || inheritedValue?.background?.backgroundSize;
const repeatValue = style?.background?.backgroundRepeat || inheritedValue?.background?.backgroundRepeat;
const imageValue = style?.background?.backgroundImage?.url || inheritedValue?.background?.backgroundImage?.url;
const isUploadedImage = style?.background?.backgroundImage?.id;
const positionValue = style?.background?.backgroundPosition || inheritedValue?.background?.backgroundPosition;
const attachmentValue = style?.background?.backgroundAttachment || inheritedValue?.background?.backgroundAttachment;
let currentValueForToggle = !sizeValue && isUploadedImage ? defaultValues?.backgroundSize : sizeValue || "auto";
currentValueForToggle = !["cover", "contain", "auto"].includes(
currentValueForToggle
) ? "auto" : currentValueForToggle;
const repeatCheckedValue = !(repeatValue === "no-repeat" || currentValueForToggle === "cover" && repeatValue === void 0);
const updateBackgroundSize = (next) => {
let nextRepeat = repeatValue;
let nextPosition = positionValue;
if (next === "contain") {
nextRepeat = "no-repeat";
nextPosition = void 0;
}
if (next === "cover") {
nextRepeat = void 0;
nextPosition = void 0;
}
if ((currentValueForToggle === "cover" || currentValueForToggle === "contain") && next === "auto") {
nextRepeat = void 0;
if (!!style?.background?.backgroundImage?.id) {
nextPosition = "50% 0";
}
}
if (!next && currentValueForToggle === "auto") {
next = "auto";
}
onChange(
setImmutably2(style, ["background"], {
...style?.background,
backgroundPosition: nextPosition,
backgroundRepeat: nextRepeat,
backgroundSize: next
})
);
};
const updateBackgroundPosition = (next) => {
onChange(
setImmutably2(
style,
["background", "backgroundPosition"],
coordsToBackgroundPosition(next)
)
);
};
const toggleIsRepeated = () => onChange(
setImmutably2(
style,
["background", "backgroundRepeat"],
repeatCheckedValue === true ? "no-repeat" : "repeat"
)
);
const toggleScrollWithPage = () => onChange(
setImmutably2(
style,
["background", "backgroundAttachment"],
attachmentValue === "fixed" ? "scroll" : "fixed"
)
);
const backgroundPositionValue = !positionValue && isUploadedImage && "contain" === sizeValue ? defaultValues?.backgroundPosition : positionValue;
return /* @__PURE__ */ (0, import_jsx_runtime432.jsxs)(import_components208.__experimentalVStack, { spacing: 3, className: "single-column", children: [
/* @__PURE__ */ (0, import_jsx_runtime432.jsx)(
import_components208.FocalPointPicker,
{
label: (0, import_i18n198.__)("Focal point"),
url: imageValue,
value: backgroundPositionToCoords(backgroundPositionValue),
onChange: updateBackgroundPosition
}
),
/* @__PURE__ */ (0, import_jsx_runtime432.jsx)(
import_components208.ToggleControl,
{
label: (0, import_i18n198.__)("Fixed background"),
checked: attachmentValue === "fixed",
onChange: toggleScrollWithPage
}
),
/* @__PURE__ */ (0, import_jsx_runtime432.jsxs)(
import_components208.__experimentalToggleGroupControl,
{
label: (0, import_i18n198.__)("Size"),
value: currentValueForToggle,
onChange: updateBackgroundSize,
isBlock: true,
help: backgroundSizeHelpText(
sizeValue || defaultValues?.backgroundSize
),
children: [
/* @__PURE__ */ (0, import_jsx_runtime432.jsx)(
import_components208.__experimentalToggleGroupControlOption,
{
value: "cover",
label: (0, import_i18n198._x)(
"Cover",
"Size option for background image control"
)
},
"cover"
),
/* @__PURE__ */ (0, import_jsx_runtime432.jsx)(
import_components208.__experimentalToggleGroupControlOption,
{
value: "contain",
label: (0, import_i18n198._x)(
"Contain",
"Size option for background image control"
)
},
"contain"
),
/* @__PURE__ */ (0, import_jsx_runtime432.jsx)(
import_components208.__experimentalToggleGroupControlOption,
{
value: "auto",
label: (0, import_i18n198._x)(
"Tile",
"Size option for background image control"
)
},
"tile"
)
]
}
),
/* @__PURE__ */ (0, import_jsx_runtime432.jsxs)(import_components208.__experimentalHStack, { justify: "flex-start", spacing: 2, as: "span", children: [
/* @__PURE__ */ (0, import_jsx_runtime432.jsx)(
import_components208.__experimentalUnitControl,
{
"aria-label": (0, import_i18n198.__)("Background image width"),
onChange: updateBackgroundSize,
value: sizeValue,
__unstableInputWidth: "100px",
min: 0,
placeholder: (0, import_i18n198.__)("Auto"),
disabled: currentValueForToggle !== "auto" || currentValueForToggle === void 0
}
),
/* @__PURE__ */ (0, import_jsx_runtime432.jsx)(
import_components208.ToggleControl,
{
label: (0, import_i18n198.__)("Repeat"),
checked: repeatCheckedValue,
onChange: toggleIsRepeated,
disabled: currentValueForToggle === "cover"
}
)
] })
] });
}
function BackgroundImagePanel({
value,
onChange,
inheritedValue = value,
settings: settings2,
defaultValues = {}
}) {
const { globalStyles, _links } = (0, import_data163.useSelect)((select3) => {
const { getSettings: getSettings7 } = select3(store);
const _settings = getSettings7();
return {
globalStyles: _settings[globalStylesDataKey],
_links: _settings[globalStylesLinksDataKey]
};
}, []);
const resolvedInheritedValue = (0, import_element255.useMemo)(() => {
const resolvedValues = {
background: {}
};
if (!inheritedValue?.background) {
return inheritedValue;
}
Object.entries(inheritedValue?.background).forEach(
([key, backgroundValue]) => {
resolvedValues.background[key] = getResolvedValue(
backgroundValue,
{
styles: globalStyles,
_links
}
);
}
);
return resolvedValues;
}, [globalStyles, _links, inheritedValue]);
const resetBackground = () => onChange(setImmutably2(value, ["background"], {}));
const { title, url } = value?.background?.backgroundImage || {
...resolvedInheritedValue?.background?.backgroundImage
};
const hasImageValue = hasBackgroundImageValue(value) || hasBackgroundImageValue(resolvedInheritedValue);
const imageValue = value?.background?.backgroundImage || inheritedValue?.background?.backgroundImage;
const shouldShowBackgroundImageControls = hasImageValue && "none" !== imageValue && (settings2?.background?.backgroundSize || settings2?.background?.backgroundPosition || settings2?.background?.backgroundRepeat);
const [isDropDownOpen, setIsDropDownOpen] = (0, import_element255.useState)(false);
const containerRef = (0, import_element255.useRef)();
return /* @__PURE__ */ (0, import_jsx_runtime432.jsx)(
"div",
{
ref: containerRef,
className: clsx_default(
"block-editor-global-styles-background-panel__inspector-media-replace-container",
{
"is-open": isDropDownOpen
}
),
children: shouldShowBackgroundImageControls ? /* @__PURE__ */ (0, import_jsx_runtime432.jsx)(
BackgroundControlsPanel,
{
label: title,
filename: title,
url,
onToggle: setIsDropDownOpen,
hasImageValue,
onReset: resetBackground,
containerRef,
children: /* @__PURE__ */ (0, import_jsx_runtime432.jsxs)(import_components208.__experimentalVStack, { spacing: 3, className: "single-column", children: [
/* @__PURE__ */ (0, import_jsx_runtime432.jsx)(
BackgroundImageControls,
{
onChange,
style: value,
inheritedValue: resolvedInheritedValue,
displayInPanel: true,
onResetImage: () => {
setIsDropDownOpen(false);
resetBackground();
},
onRemoveImage: () => setIsDropDownOpen(false),
defaultValues,
containerRef
}
),
/* @__PURE__ */ (0, import_jsx_runtime432.jsx)(
BackgroundSizeControls,
{
onChange,
style: value,
defaultValues,
inheritedValue: resolvedInheritedValue
}
)
] })
}
) : /* @__PURE__ */ (0, import_jsx_runtime432.jsx)(
BackgroundImageControls,
{
onChange,
style: value,
inheritedValue: resolvedInheritedValue,
defaultValues,
onResetImage: () => {
setIsDropDownOpen(false);
resetBackground();
},
onRemoveImage: () => setIsDropDownOpen(false),
containerRef
}
)
}
);
}
// packages/block-editor/build-module/components/global-styles/background-panel.mjs
var import_jsx_runtime433 = __toESM(require_jsx_runtime(), 1);
var DEFAULT_CONTROLS8 = {
backgroundImage: true,
backgroundColor: true,
gradient: true
};
function useHasBackgroundControl(settings2, feature) {
return settings2?.background?.[feature];
}
function useHasBackgroundPanel(settings2) {
const hasBackgroundColor = useHasBackgroundColorPanel(settings2);
const { backgroundImage, gradient } = settings2?.background || {};
return backgroundImage || gradient || hasBackgroundColor;
}
function hasBackgroundImageValue(style) {
return !!style?.background?.backgroundImage?.id || // Supports url() string values in theme.json.
"string" === typeof style?.background?.backgroundImage || !!style?.background?.backgroundImage?.url;
}
function hasBackgroundGradientValue(style) {
return "string" === typeof style?.background?.gradient && style?.background?.gradient !== "";
}
function hasBackgroundColorValue(style) {
return !!style?.color?.background;
}
function hasLegacyColorGradientValue(style) {
return !!style?.color?.gradient;
}
function BackgroundToolsPanel({
resetAllFilter,
onChange,
value,
panelId,
children,
headerLabel
}) {
const dropdownMenuProps = useToolsPanelDropdownMenuProps();
const resetAll = () => {
const updatedValue = resetAllFilter(value);
onChange(updatedValue);
};
return /* @__PURE__ */ (0, import_jsx_runtime433.jsx)(
import_components209.__experimentalToolsPanel,
{
label: headerLabel,
resetAll,
panelId,
hasInnerWrapper: true,
className: "background-block-support-panel",
__experimentalFirstVisibleItemClass: "first",
__experimentalLastVisibleItemClass: "last",
dropdownMenuProps,
children: /* @__PURE__ */ (0, import_jsx_runtime433.jsx)("div", { className: "background-block-support-panel__inner-wrapper", children })
}
);
}
function BackgroundImagePanel2({
as: Wrapper = BackgroundToolsPanel,
value,
onChange,
inheritedValue = value,
settings: settings2,
panelId,
defaultControls = DEFAULT_CONTROLS8,
defaultValues = {},
headerLabel = (0, import_i18n199.__)("Background"),
contrastWarning
}) {
const {
colors: colors2,
gradients,
allColors,
areCustomSolidsEnabled,
areCustomGradientsEnabled,
hasSolidColors,
hasGradientColors,
decodeValue,
encodeGradientValue
} = useColorGradientSettings(settings2);
const hasBackgroundGradientControl = useHasBackgroundControl(
settings2,
"gradient"
);
const hasColorPanelBackgroundSupport = useHasBackgroundColorPanel(settings2);
const showBackgroundColorControl = hasColorPanelBackgroundSupport && hasSolidColors;
const showBackgroundGradientControl = hasGradientColors && hasBackgroundGradientControl;
const showLegacyColorGradientControl = hasColorPanelBackgroundSupport && hasGradientColors && !hasBackgroundGradientControl;
const showBackgroundImageControl = useHasBackgroundControl(
settings2,
"backgroundImage"
);
const resetAllFilter = (0, import_element256.useCallback)(
(previousValue) => {
const clearsColorBackground = showBackgroundColorControl;
const clearsColorGradient = hasBackgroundGradientControl || showLegacyColorGradientControl;
if (!clearsColorBackground && !clearsColorGradient) {
return { ...previousValue, background: {} };
}
return {
...previousValue,
background: {},
color: {
...previousValue?.color,
...clearsColorBackground && { background: void 0 },
...clearsColorGradient && { gradient: void 0 }
}
};
},
[
hasBackgroundGradientControl,
showBackgroundColorControl,
showLegacyColorGradientControl
]
);
if (!showBackgroundImageControl && !showBackgroundColorControl && !showBackgroundGradientControl && !showLegacyColorGradientControl) {
return null;
}
const resetBackground = () => onChange(
setImmutably2(
value,
["background", "backgroundImage"],
void 0
)
);
const resetGradient = () => {
let newValue = setImmutably2(
value,
["background", "gradient"],
void 0
);
newValue = setImmutably2(newValue, ["color", "gradient"], void 0);
onChange(newValue);
};
const backgroundColor = decodeValue(inheritedValue?.color?.background);
const userBackgroundColor = decodeValue(value?.color?.background);
const setBackgroundColor = (newColor, newSlug) => {
const newValue = setImmutably2(
value,
["color", "background"],
encodeColorValueWithPalette(allColors, newColor, newSlug)
);
if (showLegacyColorGradientControl) {
newValue.color.gradient = void 0;
}
onChange(newValue);
};
const resetBackgroundColor = () => {
const newValue = setImmutably2(
value,
["color", "background"],
void 0
);
if (showLegacyColorGradientControl) {
newValue.color.gradient = void 0;
}
onChange(newValue);
};
const legacyColorGradient = decodeValue(inheritedValue?.color?.gradient);
const userLegacyColorGradient = decodeValue(value?.color?.gradient);
const setLegacyColorGradient = (newGradient) => {
const newValue = setImmutably2(
value,
["color", "gradient"],
encodeGradientValue(newGradient)
);
newValue.color.background = void 0;
onChange(newValue);
};
const resetLegacyColorGradient = () => onChange(setImmutably2(value, ["color", "gradient"], void 0));
const currentGradient = decodeValue(
value?.background?.gradient ?? value?.color?.gradient
);
const inheritedGradient = decodeValue(
inheritedValue?.background?.gradient ?? inheritedValue?.color?.gradient
);
const setGradient = (newGradient) => {
let newValue = setImmutably2(
value,
["background", "gradient"],
encodeGradientValue(newGradient)
);
newValue = setImmutably2(newValue, ["color", "gradient"], void 0);
onChange(newValue);
};
return /* @__PURE__ */ (0, import_jsx_runtime433.jsxs)(
Wrapper,
{
resetAllFilter,
value,
onChange,
panelId,
headerLabel,
children: [
showBackgroundImageControl && /* @__PURE__ */ (0, import_jsx_runtime433.jsx)(
import_components209.__experimentalToolsPanelItem,
{
className: "block-editor-color-gradient-item",
hasValue: () => hasBackgroundImageValue(value),
label: (0, import_i18n199.__)("Image"),
onDeselect: resetBackground,
isShownByDefault: defaultControls.backgroundImage,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime433.jsx)(
BackgroundImagePanel,
{
value,
onChange,
settings: settings2,
inheritedValue,
defaultControls,
defaultValues
}
)
}
),
showBackgroundColorControl && /* @__PURE__ */ (0, import_jsx_runtime433.jsx)(
ColorGradientDropdownItem,
{
label: (0, import_i18n199.__)("Color"),
hasValue: () => hasBackgroundColorValue(value),
resetValue: resetBackgroundColor,
isShownByDefault: defaultControls.backgroundColor,
indicators: [userBackgroundColor ?? backgroundColor],
contrastWarning,
tabs: [
{
key: "background",
label: (0, import_i18n199.__)("Color"),
inheritedValue: userBackgroundColor ?? backgroundColor,
// Resolve the slug from the same source as the
// displayed value (user value first, then the
// inherited fallback). For a block instance the
// selection lives in `value` while `inheritedValue`
// only holds the global styles fallback, so reading
// the slug from `inheritedValue` alone would miss it
// and two same-hex presets would both appear selected.
inheritedSlug: extractPresetSlug(
value?.color?.background,
"color"
) ?? extractPresetSlug(
inheritedValue?.color?.background,
"color"
),
setValue: setBackgroundColor,
userValue: userBackgroundColor
}
],
colorGradientControlSettings: {
colors: colors2,
disableCustomColors: !areCustomSolidsEnabled
},
panelId
}
),
showBackgroundGradientControl && /* @__PURE__ */ (0, import_jsx_runtime433.jsx)(
ColorGradientDropdownItem,
{
label: (0, import_i18n199.__)("Gradient"),
hasValue: () => hasBackgroundGradientValue(value),
resetValue: resetGradient,
isShownByDefault: defaultControls.gradient,
indicators: [currentGradient],
tabs: [
{
key: "gradient",
label: (0, import_i18n199.__)("Gradient"),
inheritedValue: currentGradient ?? inheritedGradient,
setValue: setGradient,
userValue: currentGradient,
isGradient: true
}
],
colorGradientControlSettings: {
gradients,
disableCustomGradients: !areCustomGradientsEnabled
},
panelId
}
),
showLegacyColorGradientControl && /* @__PURE__ */ (0, import_jsx_runtime433.jsx)(
ColorGradientDropdownItem,
{
label: (0, import_i18n199.__)("Gradient"),
hasValue: () => hasLegacyColorGradientValue(value),
resetValue: resetLegacyColorGradient,
isShownByDefault: defaultControls.gradient,
indicators: [
userLegacyColorGradient ?? legacyColorGradient
],
tabs: [
{
key: "gradient",
label: (0, import_i18n199.__)("Gradient"),
inheritedValue: userLegacyColorGradient ?? legacyColorGradient,
setValue: setLegacyColorGradient,
userValue: userLegacyColorGradient,
isGradient: true
}
],
colorGradientControlSettings: {
gradients,
disableCustomGradients: !areCustomGradientsEnabled
},
panelId
}
)
]
}
);
}
// packages/block-editor/build-module/components/global-styles/state-control.mjs
var import_i18n200 = __toESM(require_i18n(), 1);
var import_components210 = __toESM(require_components(), 1);
var import_jsx_runtime434 = __toESM(require_jsx_runtime(), 1);
function StateControl({
viewportStates = [],
pseudoStates = [],
viewportValue = "default",
pseudoStateValue = "default",
onChangeViewport,
onChangePseudoState,
showText = true,
popoverProps: popoverProps3 = {}
}) {
if (!viewportStates.length && !pseudoStates.length) {
return null;
}
const viewportOptions = [
{ label: (0, import_i18n200.__)("Default"), value: "default" },
...viewportStates.map((state) => ({
label: state.label,
value: state.value
}))
];
const pseudoStateOptions = [
{ label: (0, import_i18n200.__)("Default"), value: "default" },
...pseudoStates.map((state) => ({
label: state.label,
value: state.value
}))
];
const hasViewportOptions = viewportStates.length > 0;
const hasPseudoStateOptions = pseudoStates.length > 0;
const triggerLabel = (0, import_i18n200.__)("States");
const activeStates = [];
if (hasViewportOptions && viewportValue !== "default") {
const selectedViewport = viewportOptions.find(
(option) => option.value === viewportValue
);
if (selectedViewport) {
activeStates.push({
key: `viewport-${selectedViewport.value}`,
label: selectedViewport.label
});
}
}
if (hasPseudoStateOptions && pseudoStateValue !== "default") {
const selectedPseudoState = pseudoStateOptions.find(
(option) => option.value === pseudoStateValue
);
if (selectedPseudoState) {
activeStates.push({
key: `pseudo-${selectedPseudoState.value}`,
label: selectedPseudoState.label
});
}
}
const currentStateLabel = activeStates.length ? activeStates.map((state) => state.label).join(", ") : (0, import_i18n200.__)("Default");
const icon = showText ? chevron_down_default : more_vertical_default;
const toggleProps = showText ? { size: "compact", variant: "tertiary", iconPosition: "right" } : { size: "compact", variant: "tertiary" };
return /* @__PURE__ */ (0, import_jsx_runtime434.jsx)(
Stack,
{
direction: "column",
gap: "sm",
align: "flex-end",
className: "block-editor-global-styles-state-control",
children: /* @__PURE__ */ (0, import_jsx_runtime434.jsx)(
import_components210.DropdownMenu,
{
icon,
label: showText ? triggerLabel : (0, import_i18n200.sprintf)(
/* translators: %s: Current state (e.g. "Hover", "Focus") */
(0, import_i18n200.__)("State: %s"),
currentStateLabel
),
popoverProps: {
placement: "right-start",
...popoverProps3
},
text: showText ? triggerLabel : void 0,
toggleProps,
children: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime434.jsxs)(import_jsx_runtime434.Fragment, { children: [
hasViewportOptions && /* @__PURE__ */ (0, import_jsx_runtime434.jsx)(import_components210.MenuGroup, { label: (0, import_i18n200.__)("Viewport"), children: viewportOptions.map((option) => /* @__PURE__ */ (0, import_jsx_runtime434.jsx)(
import_components210.MenuItem,
{
onClick: () => {
onChangeViewport?.(option.value);
if (!hasPseudoStateOptions) {
onClose();
}
},
icon: viewportValue === option.value ? check_default : null,
children: option.label
},
`viewport-${option.value}`
)) }),
hasPseudoStateOptions && /* @__PURE__ */ (0, import_jsx_runtime434.jsx)(import_components210.MenuGroup, { label: (0, import_i18n200.__)("Pseudo state"), children: pseudoStateOptions.map((option) => /* @__PURE__ */ (0, import_jsx_runtime434.jsx)(
import_components210.MenuItem,
{
onClick: () => {
onChangePseudoState?.(
option.value
);
if (!hasViewportOptions) {
onClose();
}
},
icon: pseudoStateValue === option.value ? check_default : null,
children: option.label
},
`pseudo-${option.value}`
)) })
] })
}
)
}
);
}
// packages/block-editor/build-module/components/global-styles/state-control-badges.mjs
var import_components211 = __toESM(require_components(), 1);
var import_i18n201 = __toESM(require_i18n(), 1);
var import_jsx_runtime435 = __toESM(require_jsx_runtime(), 1);
var { Badge: WCBadge5 } = unlock(import_components211.privateApis);
function StateControlBadges({
viewportStates = [],
pseudoStates = [],
viewportValue = "default",
pseudoStateValue = "default",
className = "block-editor-global-styles-state-control__badges"
}) {
const activeStates = [];
const selectedViewport = viewportStates.find(
(state) => state.value === viewportValue
);
const selectedPseudoState = pseudoStates.find(
(state) => state.value === pseudoStateValue
);
if (selectedViewport) {
activeStates.push({
key: `viewport-${selectedViewport.value}`,
label: selectedViewport.label,
tooltipText: (0, import_i18n201.sprintf)(
/* translators: %s: viewport name, e.g. "Tablet". */
(0, import_i18n201.__)("Style changes apply to the %s viewport."),
selectedViewport.label
)
});
}
if (selectedPseudoState) {
activeStates.push({
key: `pseudo-${selectedPseudoState.value}`,
label: selectedPseudoState.label,
tooltipText: (0, import_i18n201.sprintf)(
/* translators: %s: pseudo state name, e.g. "Hover". */
(0, import_i18n201.__)("Style changes apply to the %s state."),
selectedPseudoState.label
)
});
}
return /* @__PURE__ */ (0, import_jsx_runtime435.jsx)(
Stack,
{
className,
direction: "row",
justify: "flex-start",
gap: "xs",
wrap: "wrap",
children: activeStates.map((state) => {
const badge = /* @__PURE__ */ (0, import_jsx_runtime435.jsxs)(
WCBadge5,
{
className: "block-editor-global-styles-state-control__badge",
intent: "info",
children: [
state.label,
!!state.tooltipText && /* @__PURE__ */ (0, import_jsx_runtime435.jsx)(VisuallyHidden, { render: /* @__PURE__ */ (0, import_jsx_runtime435.jsx)("span", {}), children: state.tooltipText })
]
},
state.key
);
if (!state.tooltipText) {
return badge;
}
return /* @__PURE__ */ (0, import_jsx_runtime435.jsxs)(tooltip_exports.Root, { children: [
/* @__PURE__ */ (0, import_jsx_runtime435.jsx)(
tooltip_exports.Trigger,
{
render: /* @__PURE__ */ (0, import_jsx_runtime435.jsx)("span", { className: "block-editor-global-styles-state-control__badge-tooltip-trigger", children: badge })
}
),
/* @__PURE__ */ (0, import_jsx_runtime435.jsx)(tooltip_exports.Popup, { children: state.tooltipText })
] }, state.key);
})
}
);
}
// packages/block-editor/build-module/hooks/border.mjs
var import_jsx_runtime436 = __toESM(require_jsx_runtime(), 1);
var BORDER_SUPPORT_KEY2 = "__experimentalBorder";
var SHADOW_SUPPORT_KEY = "shadow";
var getColorByProperty = (colors2, property, value) => {
let matchedColor;
colors2.some(
(origin) => origin.colors.some((color) => {
if (color[property] === value) {
matchedColor = color;
return true;
}
return false;
})
);
return matchedColor;
};
var getMultiOriginColor = ({ colors: colors2, namedColor, customColor }) => {
if (namedColor) {
const colorObject2 = getColorByProperty(colors2, "slug", namedColor);
if (colorObject2) {
return colorObject2;
}
}
if (!customColor) {
return { color: void 0 };
}
const colorObject = getColorByProperty(colors2, "color", customColor);
return colorObject ? colorObject : { color: customColor };
};
function getColorSlugFromVariable(value) {
const namedColor = /var:preset\|color\|(.+)/.exec(value);
if (namedColor && namedColor[1]) {
return namedColor[1];
}
return null;
}
function styleToAttributes(style) {
if ((0, import_components212.__experimentalHasSplitBorders)(style?.border)) {
return {
style,
borderColor: void 0
};
}
const borderColorValue = style?.border?.color;
const borderColorSlug = borderColorValue?.startsWith("var:preset|color|") ? borderColorValue.substring("var:preset|color|".length) : void 0;
const updatedStyle = { ...style };
updatedStyle.border = {
...updatedStyle.border,
color: borderColorSlug ? void 0 : borderColorValue
};
return {
style: cleanEmptyObject(updatedStyle),
borderColor: borderColorSlug
};
}
function attributesToStyle(attributes) {
if ((0, import_components212.__experimentalHasSplitBorders)(attributes.style?.border)) {
return attributes.style;
}
return {
...attributes.style,
border: {
...attributes.style?.border,
color: attributes.borderColor ? "var:preset|color|" + attributes.borderColor : attributes.style?.border?.color
}
};
}
function BordersInspectorControl({ label, children, resetAllFilter }) {
const attributesResetAllFilter = (0, import_element257.useCallback)(
(attributes) => {
const existingStyle = attributesToStyle(attributes);
const updatedStyle = resetAllFilter(existingStyle);
return {
...attributes,
...styleToAttributes(updatedStyle)
};
},
[resetAllFilter]
);
return /* @__PURE__ */ (0, import_jsx_runtime436.jsx)(
inspector_controls_default,
{
group: "border",
resetAllFilter: attributesResetAllFilter,
label,
children
}
);
}
function BorderPanel2({ clientId, name, setAttributes, settings: settings2 }) {
const selectedState = useBlockStyleState();
const isEnabled = useHasBorderPanel(settings2);
const { style, borderColor } = (0, import_data164.useSelect)(
(select3) => {
if (!isEnabled) {
return {};
}
const { style: _style, borderColor: _borderColor } = select3(store).getBlockAttributes(clientId) || {};
return { style: _style, borderColor: _borderColor };
},
[clientId, isEnabled]
);
const isStateSelected = !isDefaultBlockStyleState(selectedState);
const value = (0, import_element257.useMemo)(() => {
if (isStateSelected) {
return getStyleForState(style, selectedState);
}
return attributesToStyle({ style, borderColor });
}, [isStateSelected, selectedState, style, borderColor]);
const onChange = isStateSelected ? (newStyle) => {
setAttributes({
style: setStyleForState(style, selectedState, newStyle)
});
} : (newStyle) => {
setAttributes(styleToAttributes(newStyle));
};
if (!isEnabled) {
return null;
}
const defaultControls = {
...(0, import_blocks91.getBlockSupport)(name, [
BORDER_SUPPORT_KEY2,
"__experimentalDefaultControls"
]),
...(0, import_blocks91.getBlockSupport)(name, [
SHADOW_SUPPORT_KEY,
"__experimentalDefaultControls"
])
};
return /* @__PURE__ */ (0, import_jsx_runtime436.jsx)(
BorderPanel,
{
as: BordersInspectorControl,
panelId: clientId,
settings: settings2,
value,
onChange,
defaultControls
}
);
}
function hasBorderSupport2(blockName, feature = "any") {
const support = (0, import_blocks91.getBlockSupport)(blockName, BORDER_SUPPORT_KEY2);
if (support === true) {
return true;
}
if (feature === "any") {
return !!(support?.color || support?.radius || support?.width || support?.style);
}
return !!support?.[feature];
}
function useBorderPanelLabel({
blockName,
hasBorderControl,
hasShadowControl
} = {}) {
const settings2 = useBlockSettings(blockName);
const controls = useHasBorderPanelControls(settings2);
if (!hasBorderControl && !hasShadowControl && blockName) {
hasBorderControl = controls?.hasBorderColor || controls?.hasBorderStyle || controls?.hasBorderWidth || controls?.hasBorderRadius;
hasShadowControl = controls?.hasShadow;
}
if (hasBorderControl && hasShadowControl) {
return (0, import_i18n202.__)("Border & Shadow");
}
if (hasShadowControl) {
return (0, import_i18n202.__)("Shadow");
}
return (0, import_i18n202.__)("Border");
}
function addAttributes(settings2) {
if (!hasBorderSupport2(settings2, "color")) {
return settings2;
}
if (settings2.attributes.borderColor) {
return settings2;
}
return {
...settings2,
attributes: {
...settings2.attributes,
borderColor: {
type: "string"
}
}
};
}
function addSaveProps(props, blockNameOrType, attributes) {
if (!hasBorderSupport2(blockNameOrType, "color") || shouldSkipSerialization(blockNameOrType, BORDER_SUPPORT_KEY2, "color")) {
return props;
}
const borderClasses = getBorderClasses(attributes);
const newClassName = clsx_default(props.className, borderClasses);
props.className = newClassName ? newClassName : void 0;
return props;
}
function getBorderClasses(attributes) {
const { borderColor, style } = attributes;
const borderColorClass = getColorClassName("border-color", borderColor);
return clsx_default({
"has-border-color": borderColor || style?.border?.color,
[borderColorClass]: !!borderColorClass
});
}
function useBlockProps4({ name, borderColor, style }) {
const { colors: colors2 } = useMultipleOriginColorsAndGradients();
if (!hasBorderSupport2(name, "color") || shouldSkipSerialization(name, BORDER_SUPPORT_KEY2, "color")) {
return {};
}
const { color: borderColorValue } = getMultiOriginColor({
colors: colors2,
namedColor: borderColor
});
const { color: borderTopColor } = getMultiOriginColor({
colors: colors2,
namedColor: getColorSlugFromVariable(style?.border?.top?.color)
});
const { color: borderRightColor } = getMultiOriginColor({
colors: colors2,
namedColor: getColorSlugFromVariable(style?.border?.right?.color)
});
const { color: borderBottomColor } = getMultiOriginColor({
colors: colors2,
namedColor: getColorSlugFromVariable(style?.border?.bottom?.color)
});
const { color: borderLeftColor } = getMultiOriginColor({
colors: colors2,
namedColor: getColorSlugFromVariable(style?.border?.left?.color)
});
const extraStyles = {
borderTopColor: borderTopColor || borderColorValue,
borderRightColor: borderRightColor || borderColorValue,
borderBottomColor: borderBottomColor || borderColorValue,
borderLeftColor: borderLeftColor || borderColorValue
};
return addSaveProps(
{ style: cleanEmptyObject(extraStyles) || {} },
name,
{ borderColor, style }
);
}
var border_default = {
useBlockProps: useBlockProps4,
addSaveProps,
attributeKeys: ["borderColor", "style"],
hasSupport(name) {
return hasBorderSupport2(name, "color");
}
};
(0, import_hooks13.addFilter)(
"blocks.registerBlockType",
"core/border/addAttributes",
addAttributes
);
// packages/block-editor/build-module/hooks/elements.mjs
var import_blocks95 = __toESM(require_blocks(), 1);
var import_element260 = __toESM(require_element(), 1);
var import_data167 = __toESM(require_data(), 1);
var import_i18n204 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/hooks/color.mjs
var import_hooks14 = __toESM(require_hooks(), 1);
var import_blocks94 = __toESM(require_blocks(), 1);
var import_element259 = __toESM(require_element(), 1);
// packages/block-editor/build-module/hooks/background.mjs
var import_blocks93 = __toESM(require_blocks(), 1);
var import_data166 = __toESM(require_data(), 1);
var import_i18n203 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/hooks/contrast-checker.mjs
var import_element258 = __toESM(require_element(), 1);
var import_data165 = __toESM(require_data(), 1);
var import_blocks92 = __toESM(require_blocks(), 1);
var import_a11y19 = __toESM(require_a11y(), 1);
function getComputedValue(node, property) {
return node.ownerDocument.defaultView.getComputedStyle(node).getPropertyValue(property);
}
function getBlockElementColors(blockEl, blockType) {
if (!blockEl || !blockType) {
return {};
}
const textSelector = getBlockSelector(blockType, "color.text", {
fallback: true
});
const backgroundSelector = getBlockSelector(
blockType,
"color.background",
{ fallback: true }
);
const textElement = blockEl.querySelector(textSelector) || blockEl;
const backgroundElement = blockEl.querySelector(backgroundSelector) || blockEl;
const linkElement = blockEl.querySelector("a");
const textColor = getComputedValue(textElement, "color");
const linkColor = linkElement && linkElement.textContent ? getComputedValue(linkElement, "color") : void 0;
let backgroundColorNode = backgroundElement;
let backgroundColor = getComputedValue(
backgroundColorNode,
"background-color"
);
while (backgroundColor === "rgba(0, 0, 0, 0)" && backgroundColorNode.parentNode && backgroundColorNode.parentNode.nodeType === backgroundColorNode.parentNode.ELEMENT_NODE) {
backgroundColorNode = backgroundColorNode.parentNode;
backgroundColor = getComputedValue(
backgroundColorNode,
"background-color"
);
}
return {
textColor,
backgroundColor,
linkColor
};
}
function reducer2(prevColors, newColors) {
const hasChanged = Object.keys(newColors).some(
(key) => prevColors[key] !== newColors[key]
);
return hasChanged ? newColors : prevColors;
}
function useBlockColorContrastWarning({
clientId,
name,
enabled = true,
checkTextColor = true,
checkLinkColor = true,
messageOverride
}) {
const blockEl = useBlockElement(clientId);
const [colors2, setColors] = (0, import_element258.useReducer)(reducer2, {});
const blockType = (0, import_data165.useSelect)(
(select3) => {
return name && enabled ? select3(import_blocks92.store).getBlockType(name) : void 0;
},
[name, enabled]
);
(0, import_element258.useLayoutEffect)(() => {
if (!enabled || !blockEl || !blockType) {
return;
}
window.requestAnimationFrame(
() => window.requestAnimationFrame(
() => setColors(getBlockElementColors(blockEl, blockType))
)
);
});
(0, import_element258.useLayoutEffect)(() => {
if (!enabled || !blockEl || !blockType) {
return;
}
const observer = new window.MutationObserver(() => {
setColors(getBlockElementColors(blockEl, blockType));
});
observer.observe(blockEl, {
attributes: true,
attributeFilter: ["class", "style"],
subtree: true
});
return () => {
observer.disconnect();
};
}, [enabled, blockEl, blockType]);
const warning6 = enabled ? getContrastWarning({
backgroundColor: colors2.backgroundColor,
textColor: checkTextColor ? colors2.textColor : void 0,
linkColor: checkLinkColor ? colors2.linkColor : void 0,
messageOverride,
enableAlphaChecker: true
}) : null;
const speakMessage = warning6?.speakMessage;
(0, import_element258.useEffect)(() => {
if (speakMessage) {
(0, import_a11y19.speak)(speakMessage);
}
}, [speakMessage]);
return warning6?.message;
}
// packages/block-editor/build-module/hooks/background.mjs
var import_jsx_runtime437 = __toESM(require_jsx_runtime(), 1);
var BACKGROUND_SUPPORT_KEY = "background";
var BACKGROUND_BLOCK_DEFAULT_VALUES2 = {
backgroundSize: "cover",
backgroundPosition: "50% 50%"
// used only when backgroundSize is 'contain'.
};
function hasBackgroundSupport(blockName, feature = "any") {
const support = (0, import_blocks93.getBlockSupport)(blockName, BACKGROUND_SUPPORT_KEY);
if (support === true) {
return true;
}
if (feature === "any") {
return !!support?.backgroundImage || !!support?.backgroundSize || !!support?.backgroundRepeat || !!support?.gradient;
}
return !!support?.[feature];
}
function setBackgroundStyleDefaults2(backgroundStyle) {
if (!backgroundStyle || !backgroundStyle?.backgroundImage?.url) {
return;
}
let backgroundStylesWithDefaults;
if (!backgroundStyle?.backgroundSize) {
backgroundStylesWithDefaults = {
backgroundSize: BACKGROUND_BLOCK_DEFAULT_VALUES2.backgroundSize
};
}
if ("contain" === backgroundStyle?.backgroundSize && !backgroundStyle?.backgroundPosition) {
backgroundStylesWithDefaults = {
backgroundPosition: BACKGROUND_BLOCK_DEFAULT_VALUES2.backgroundPosition
};
}
return backgroundStylesWithDefaults;
}
function useBlockProps5({ name, style }) {
if (!hasBackgroundSupport(name) || !style?.background?.backgroundImage) {
return;
}
const backgroundStyles = setBackgroundStyleDefaults2(style?.background);
if (!backgroundStyles) {
return;
}
return {
style: {
...backgroundStyles
}
};
}
function getBackgroundImageClasses(style) {
return hasBackgroundImageValue(style) || hasBackgroundGradientValue(style) ? "has-background" : "";
}
function backgroundResetAllFilter(attributes) {
const updatedClassName = attributes.className?.includes("has-background") ? attributes.className.split(" ").filter((c6) => c6 !== "has-background").join(" ") || void 0 : attributes.className;
return {
...attributes,
className: updatedClassName,
backgroundColor: void 0,
gradient: void 0,
style: cleanEmptyObject({
...attributes.style,
background: void 0,
color: {
...attributes.style?.color,
background: void 0,
gradient: void 0
}
})
};
}
function BackgroundInspectorControl({ children }) {
return /* @__PURE__ */ (0, import_jsx_runtime437.jsx)(
inspector_controls_default,
{
group: "background",
resetAllFilter: backgroundResetAllFilter,
children
}
);
}
function BackgroundImagePanel3({
clientId,
name,
setAttributes,
settings: settings2,
// Allows rendering outside the `background` inspector group (e.g. section
// blocks direct-render this panel because their support fills are gated
// off by editing mode). Defaults to the slot-based wrapper.
asWrapper
}) {
const selectedState = useBlockStyleState();
const { style, className, backgroundColor, gradient, inheritedValue } = (0, import_data166.useSelect)(
(select3) => {
const { getBlockAttributes: getBlockAttributes3, getSettings: getSettings7 } = select3(store);
const _settings = getSettings7();
const blockAttributes = getBlockAttributes3(clientId);
return {
style: blockAttributes?.style,
className: blockAttributes?.className,
backgroundColor: blockAttributes?.backgroundColor,
gradient: blockAttributes?.gradient,
inheritedValue: _settings[globalStylesDataKey]?.blocks?.[name]
};
},
[clientId, name]
);
const backgroundGradientSupported = hasBackgroundSupport(
name,
"gradient"
);
const colorSupport = (0, import_blocks93.getBlockSupport)(name, "color");
const hasColorBackgroundSupport = colorSupport && colorSupport.background !== false;
const hasColorGradientSupport = !!colorSupport?.gradients;
const isStateSelected = !isDefaultBlockStyleState(selectedState);
const styleValue = {
...style,
color: {
...style?.color,
background: backgroundColor ? "var:preset|color|" + backgroundColor : style?.color?.background,
gradient: !backgroundGradientSupported && gradient ? "var:preset|gradient|" + gradient : style?.color?.gradient
},
...backgroundGradientSupported && {
background: {
...style?.background,
gradient: gradient ? "var:preset|gradient|" + gradient : style?.background?.gradient ?? style?.color?.gradient
}
}
};
const value = isStateSelected ? getStyleForState(style, selectedState) : styleValue;
const enableContrastChecking = !value?.color?.gradient && !value?.background?.gradient && !!value?.color?.background && (settings2?.color?.text || settings2?.color?.link) && false !== (0, import_blocks93.getBlockSupport)(name, ["color", "enableContrastChecker"]);
const contrastWarning = useBlockColorContrastWarning({
clientId,
name,
enabled: !!enableContrastChecking,
messageOverride: (0, import_i18n203.__)(
"This color combination has poor contrast. Consider increasing contrast between background and foreground."
)
});
if (!useHasBackgroundPanel(settings2) || !hasBackgroundSupport(name) && !hasColorBackgroundSupport && !hasColorGradientSupport) {
return null;
}
const onChange = (newStyle) => {
if (isStateSelected) {
setAttributes({
style: setStyleForState(style, selectedState, newStyle)
});
return;
}
const newBackgroundColorValue = newStyle?.color?.background;
const newBackgroundColorSlug = extractPresetSlug(
newBackgroundColorValue,
"color"
);
const newGradientValue = backgroundGradientSupported ? newStyle?.background?.gradient : newStyle?.color?.gradient;
const newGradientSlug = extractPresetSlug(
newGradientValue,
"gradient"
);
const cleanedColorGradient = newGradientSlug ? void 0 : newStyle?.color?.gradient;
const cleanedStyle = {
...newStyle,
color: {
...newStyle?.color,
background: newBackgroundColorSlug ? void 0 : newBackgroundColorValue,
gradient: backgroundGradientSupported ? void 0 : cleanedColorGradient
}
};
if (backgroundGradientSupported) {
cleanedStyle.background = {
...cleanedStyle.background,
gradient: newStyle?.background?.gradient
};
}
const isMigrating = backgroundGradientSupported && !!style?.color?.gradient;
const newAttributes = {
style: cleanEmptyObject(cleanedStyle),
backgroundColor: newBackgroundColorSlug,
// The legacy `gradient` attribute is only used when the block does
// not support `background.gradient`; otherwise the gradient is
// stored in `style.background.gradient` above.
gradient: backgroundGradientSupported ? void 0 : newGradientSlug
};
const hasNewGradient = !!newGradientSlug || !!newGradientValue;
if (isMigrating && hasNewGradient) {
newAttributes.className = clsx_default(className, "has-background");
} else if (!hasNewGradient && className?.includes("has-background")) {
newAttributes.className = className.split(" ").filter((c6) => c6 !== "has-background").join(" ") || void 0;
}
setAttributes(newAttributes);
};
const updatedSettings = {
...settings2,
background: {
...settings2.background,
backgroundSize: settings2?.background?.backgroundSize && hasBackgroundSupport(name, "backgroundSize")
}
};
const backgroundDefaultControls = (0, import_blocks93.getBlockSupport)(name, [
BACKGROUND_SUPPORT_KEY,
"__experimentalDefaultControls"
]);
const colorDefaultControls = (0, import_blocks93.getBlockSupport)(name, [
"color",
"__experimentalDefaultControls"
]);
const defaultControls = {
...backgroundDefaultControls,
backgroundColor: colorDefaultControls?.background,
// Mirror the old combined control: show the gradient item by default
// when background color was shown by default.
gradient: backgroundDefaultControls?.gradient ?? colorDefaultControls?.background
};
const Wrapper = asWrapper || BackgroundInspectorControl;
return /* @__PURE__ */ (0, import_jsx_runtime437.jsx)(
BackgroundImagePanel2,
{
inheritedValue,
as: Wrapper,
panelId: clientId,
defaultValues: BACKGROUND_BLOCK_DEFAULT_VALUES2,
settings: updatedSettings,
onChange,
defaultControls,
value,
contrastWarning
}
);
}
var background_default = {
useBlockProps: useBlockProps5,
attributeKeys: ["style"],
hasSupport: hasBackgroundSupport
};
// packages/block-editor/build-module/hooks/color.mjs
var COLOR_SUPPORT_KEY2 = "color";
var hasColorSupport = (blockNameOrType) => {
const colorSupport = (0, import_blocks94.getBlockSupport)(blockNameOrType, COLOR_SUPPORT_KEY2);
return colorSupport && (colorSupport.link === true || colorSupport.gradient === true || colorSupport.background !== false || colorSupport.text !== false);
};
var hasLinkColorSupport = (blockType) => {
const colorSupport = (0, import_blocks94.getBlockSupport)(blockType, COLOR_SUPPORT_KEY2);
return colorSupport !== null && typeof colorSupport === "object" && !!colorSupport.link;
};
var hasGradientSupport2 = (blockNameOrType) => {
const colorSupport = (0, import_blocks94.getBlockSupport)(blockNameOrType, COLOR_SUPPORT_KEY2);
return colorSupport !== null && typeof colorSupport === "object" && !!colorSupport.gradients;
};
var hasBackgroundColorSupport2 = (blockType) => {
const colorSupport = (0, import_blocks94.getBlockSupport)(blockType, COLOR_SUPPORT_KEY2);
return colorSupport && colorSupport.background !== false;
};
var hasTextColorSupport2 = (blockType) => {
const colorSupport = (0, import_blocks94.getBlockSupport)(blockType, COLOR_SUPPORT_KEY2);
return colorSupport && colorSupport.text !== false;
};
function addAttributes2(settings2) {
if (!hasColorSupport(settings2)) {
return settings2;
}
if (!settings2.attributes.backgroundColor) {
Object.assign(settings2.attributes, {
backgroundColor: {
type: "string"
}
});
}
if (!settings2.attributes.textColor) {
Object.assign(settings2.attributes, {
textColor: {
type: "string"
}
});
}
if (hasGradientSupport2(settings2) && !settings2.attributes.gradient) {
Object.assign(settings2.attributes, {
gradient: {
type: "string"
}
});
}
return settings2;
}
function addSaveProps2(props, blockNameOrType, attributes) {
if (!hasColorSupport(blockNameOrType) || shouldSkipSerialization(blockNameOrType, COLOR_SUPPORT_KEY2)) {
return props;
}
const hasGradient = hasGradientSupport2(blockNameOrType);
const { backgroundColor, textColor, gradient, style } = attributes;
const shouldSerialize = (feature) => !shouldSkipSerialization(
blockNameOrType,
COLOR_SUPPORT_KEY2,
feature
);
const textClass = shouldSerialize("text") ? getColorClassName("color", textColor) : void 0;
const gradientClass = shouldSerialize("gradients") ? __experimentalGetGradientClass(gradient) : void 0;
const backgroundClass = shouldSerialize("background") ? getColorClassName("background-color", backgroundColor) : void 0;
const serializeHasBackground = shouldSerialize("background") || shouldSerialize("gradients");
const hasBackground = backgroundColor || style?.color?.background || hasGradient && (gradient || style?.color?.gradient);
const newClassName = clsx_default(props.className, textClass, gradientClass, {
// Don't apply the background class if there's a custom gradient.
[backgroundClass]: (!hasGradient || !style?.color?.gradient) && !!backgroundClass,
"has-text-color": shouldSerialize("text") && (textColor || style?.color?.text),
"has-background": serializeHasBackground && hasBackground,
"has-link-color": shouldSerialize("link") && style?.elements?.link?.color
});
props.className = newClassName ? newClassName : void 0;
return props;
}
function useBlockProps6({
name,
backgroundColor,
textColor,
gradient,
style
}) {
const [userPalette, themePalette, defaultPalette] = useSettings(
"color.palette.custom",
"color.palette.theme",
"color.palette.default"
);
const colors2 = (0, import_element259.useMemo)(
() => [
...userPalette || [],
...themePalette || [],
...defaultPalette || []
],
[userPalette, themePalette, defaultPalette]
);
if (!hasColorSupport(name) || shouldSkipSerialization(name, COLOR_SUPPORT_KEY2)) {
return {};
}
const extraStyles = {};
if (textColor && !shouldSkipSerialization(name, COLOR_SUPPORT_KEY2, "text")) {
extraStyles.color = getColorObjectByAttributeValues(
colors2,
textColor
)?.color;
}
if (backgroundColor && !shouldSkipSerialization(name, COLOR_SUPPORT_KEY2, "background")) {
extraStyles.backgroundColor = getColorObjectByAttributeValues(
colors2,
backgroundColor
)?.color;
}
const saveProps = addSaveProps2({ style: extraStyles }, name, {
textColor,
backgroundColor,
gradient,
style
});
const hasBackgroundValue = backgroundColor || style?.color?.background || gradient || style?.color?.gradient;
return {
...saveProps,
className: clsx_default(
saveProps.className,
// Add background image classes in the editor, if not already handled by background color values.
!hasBackgroundValue && getBackgroundImageClasses(style)
)
};
}
var color_default = {
useBlockProps: useBlockProps6,
addSaveProps: addSaveProps2,
attributeKeys: ["backgroundColor", "textColor", "gradient", "style"],
hasSupport: hasColorSupport
};
var MIGRATION_PATHS = {
linkColor: [["style", "elements", "link", "color", "text"]],
textColor: [["textColor"], ["style", "color", "text"]],
backgroundColor: [
["backgroundColor"],
["style", "color", "background"]
],
gradient: [["gradient"], ["style", "color", "gradient"]]
};
function addTransforms(result, source, index2, results) {
const destinationBlockType = result.name;
const activeSupports = {
linkColor: hasLinkColorSupport(destinationBlockType),
textColor: hasTextColorSupport2(destinationBlockType),
backgroundColor: hasBackgroundColorSupport2(destinationBlockType),
gradient: hasGradientSupport2(destinationBlockType)
};
return transformStyles2(
activeSupports,
MIGRATION_PATHS,
result,
source,
index2,
results
);
}
(0, import_hooks14.addFilter)(
"blocks.registerBlockType",
"core/color/addAttribute",
addAttributes2
);
(0, import_hooks14.addFilter)(
"blocks.switchToBlockType.transformedBlock",
"core/color/addTransforms",
addTransforms
);
// packages/block-editor/build-module/hooks/elements.mjs
var import_jsx_runtime438 = __toESM(require_jsx_runtime(), 1);
function ElementsInspectorControl({ children, resetAllFilter }) {
const attributesResetAllFilter = (0, import_element260.useCallback)(
(attributes) => {
const updatedStyle = resetAllFilter(attributes.style);
return {
...attributes,
style: cleanEmptyObject(updatedStyle)
};
},
[resetAllFilter]
);
return /* @__PURE__ */ (0, import_jsx_runtime438.jsx)(
inspector_controls_default,
{
group: "elements",
resetAllFilter: attributesResetAllFilter,
children
}
);
}
function ElementsEdit({
clientId,
name,
setAttributes,
settings: settings2,
asWrapper,
label,
defaultControls
}) {
const selectedState = useBlockStyleState();
const isEnabled = useHasColorPanel(settings2);
const style = (0, import_data167.useSelect)(
(select3) => {
if (!isEnabled) {
return void 0;
}
const attributes = select3(store).getBlockAttributes(clientId);
return attributes?.style;
},
[clientId, isEnabled]
);
const isStateSelected = !isDefaultBlockStyleState(selectedState);
const value = (0, import_element260.useMemo)(() => {
if (isStateSelected) {
return getStyleForState(style, selectedState);
}
return style;
}, [isStateSelected, selectedState, style]);
const onChange = isStateSelected ? (newStyle) => {
setAttributes({
style: setStyleForState(style, selectedState, newStyle)
});
} : (newStyle) => {
setAttributes({ style: cleanEmptyObject(newStyle) });
};
const enableContrastChecking = !!value?.elements?.link?.color?.text && settings2?.color?.link && false !== (0, import_blocks95.getBlockSupport)(name, [
COLOR_SUPPORT_KEY2,
"enableContrastChecker"
]);
const contrastWarning = useBlockColorContrastWarning({
clientId,
name,
enabled: !!enableContrastChecking,
checkTextColor: false,
messageOverride: (0, import_i18n204.__)(
"This link color has poor contrast against the background. Consider increasing contrast."
)
});
if (!isEnabled) {
return null;
}
defaultControls = defaultControls ? defaultControls : (0, import_blocks95.getBlockSupport)(name, [
COLOR_SUPPORT_KEY2,
"__experimentalDefaultControls"
]);
const Wrapper = asWrapper || ElementsInspectorControl;
return /* @__PURE__ */ (0, import_jsx_runtime438.jsx)(
ColorPanel,
{
as: Wrapper,
panelId: clientId,
settings: settings2,
value,
onChange,
defaultControls,
label,
contrastWarning
}
);
}
// packages/block-editor/build-module/hooks/typography.mjs
var import_blocks101 = __toESM(require_blocks(), 1);
var import_element264 = __toESM(require_element(), 1);
var import_data171 = __toESM(require_data(), 1);
var import_i18n208 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/hooks/line-height.mjs
var import_blocks96 = __toESM(require_blocks(), 1);
var import_jsx_runtime439 = __toESM(require_jsx_runtime(), 1);
var LINE_HEIGHT_SUPPORT_KEY2 = "typography.lineHeight";
// packages/block-editor/build-module/hooks/font-family.mjs
var import_hooks15 = __toESM(require_hooks(), 1);
var import_blocks97 = __toESM(require_blocks(), 1);
var import_token_list2 = __toESM(require_token_list(), 1);
var import_components213 = __toESM(require_components(), 1);
var FONT_FAMILY_SUPPORT_KEY2 = "typography.__experimentalFontFamily";
var { kebabCase: kebabCase5 } = unlock(import_components213.privateApis);
function addAttributes3(settings2) {
if (!(0, import_blocks97.hasBlockSupport)(settings2, FONT_FAMILY_SUPPORT_KEY2)) {
return settings2;
}
if (!settings2.attributes.fontFamily) {
Object.assign(settings2.attributes, {
fontFamily: {
type: "string"
}
});
}
return settings2;
}
function addSaveProps3(props, blockType, attributes) {
if (!(0, import_blocks97.hasBlockSupport)(blockType, FONT_FAMILY_SUPPORT_KEY2)) {
return props;
}
if (shouldSkipSerialization(
blockType,
TYPOGRAPHY_SUPPORT_KEY,
"fontFamily"
)) {
return props;
}
if (!attributes?.fontFamily) {
return props;
}
const classes = new import_token_list2.default(props.className);
classes.add(`has-${kebabCase5(attributes?.fontFamily)}-font-family`);
const newClassName = classes.value;
props.className = newClassName ? newClassName : void 0;
return props;
}
function useBlockProps7({ name, fontFamily }) {
return addSaveProps3({}, name, { fontFamily });
}
var font_family_default = {
useBlockProps: useBlockProps7,
addSaveProps: addSaveProps3,
attributeKeys: ["fontFamily"],
hasSupport(name) {
return (0, import_blocks97.hasBlockSupport)(name, FONT_FAMILY_SUPPORT_KEY2);
}
};
(0, import_hooks15.addFilter)(
"blocks.registerBlockType",
"core/fontFamily/addAttribute",
addAttributes3
);
// packages/block-editor/build-module/hooks/font-size.mjs
var import_hooks16 = __toESM(require_hooks(), 1);
var import_blocks98 = __toESM(require_blocks(), 1);
var import_token_list3 = __toESM(require_token_list(), 1);
var import_jsx_runtime440 = __toESM(require_jsx_runtime(), 1);
var FONT_SIZE_SUPPORT_KEY2 = "typography.fontSize";
function addAttributes4(settings2) {
if (!(0, import_blocks98.hasBlockSupport)(settings2, FONT_SIZE_SUPPORT_KEY2)) {
return settings2;
}
if (!settings2.attributes.fontSize) {
Object.assign(settings2.attributes, {
fontSize: {
type: "string"
}
});
}
return settings2;
}
function addSaveProps4(props, blockNameOrType, attributes) {
if (!(0, import_blocks98.hasBlockSupport)(blockNameOrType, FONT_SIZE_SUPPORT_KEY2)) {
return props;
}
if (shouldSkipSerialization(
blockNameOrType,
TYPOGRAPHY_SUPPORT_KEY,
"fontSize"
)) {
return props;
}
const classes = new import_token_list3.default(props.className);
classes.add(getFontSizeClass(attributes.fontSize));
const newClassName = classes.value;
props.className = newClassName ? newClassName : void 0;
return props;
}
function useBlockProps8({ name, fontSize, style }) {
const [fontSizes, fluidTypographySettings, layoutSettings] = useSettings(
"typography.fontSizes",
"typography.fluid",
"layout"
);
if (!(0, import_blocks98.hasBlockSupport)(name, FONT_SIZE_SUPPORT_KEY2) || shouldSkipSerialization(name, TYPOGRAPHY_SUPPORT_KEY, "fontSize") || !fontSize && !style?.typography?.fontSize) {
return;
}
let props;
if (style?.typography?.fontSize) {
props = {
style: {
fontSize: getTypographyFontSizeValue(
{ size: style.typography.fontSize },
{
typography: {
fluid: fluidTypographySettings
},
layout: layoutSettings
}
)
}
};
}
if (fontSize) {
props = {
style: {
fontSize: getFontSize(
fontSizes,
fontSize,
style?.typography?.fontSize
).size
}
};
}
if (!props) {
return;
}
return addSaveProps4(props, name, { fontSize });
}
var font_size_default = {
useBlockProps: useBlockProps8,
addSaveProps: addSaveProps4,
attributeKeys: ["fontSize", "style"],
hasSupport(name) {
return (0, import_blocks98.hasBlockSupport)(name, FONT_SIZE_SUPPORT_KEY2);
}
};
var MIGRATION_PATHS2 = {
fontSize: [["fontSize"], ["style", "typography", "fontSize"]]
};
function addTransforms2(result, source, index2, results) {
const destinationBlockType = result.name;
const activeSupports = {
fontSize: (0, import_blocks98.hasBlockSupport)(
destinationBlockType,
FONT_SIZE_SUPPORT_KEY2
)
};
return transformStyles2(
activeSupports,
MIGRATION_PATHS2,
result,
source,
index2,
results
);
}
(0, import_hooks16.addFilter)(
"blocks.registerBlockType",
"core/font/addAttribute",
addAttributes4
);
(0, import_hooks16.addFilter)(
"blocks.switchToBlockType.transformedBlock",
"core/font-size/addTransforms",
addTransforms2
);
// packages/block-editor/build-module/hooks/text-align.mjs
var import_i18n205 = __toESM(require_i18n(), 1);
var import_blocks99 = __toESM(require_blocks(), 1);
var import_data169 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/block-editing-mode/index.mjs
var import_data168 = __toESM(require_data(), 1);
var import_element261 = __toESM(require_element(), 1);
function useBlockEditingMode(mode2) {
const context = useBlockEditContext();
const { clientId = "" } = context;
const registry = (0, import_data168.useRegistry)();
const globalBlockEditingMode = (0, import_data168.useSelect)(
(select3) => (
// Avoid adding the subscription if not needed!
clientId ? null : select3(store).getBlockEditingMode()
),
[clientId]
);
(0, import_element261.useEffect)(() => {
if (!mode2) {
return;
}
const {
setBlockEditingMode: setBlockEditingMode2,
unsetBlockEditingMode: unsetBlockEditingMode2,
__unstableMarkNextChangeAsNotPersistent: __unstableMarkNextChangeAsNotPersistent2
} = registry.dispatch(store);
__unstableMarkNextChangeAsNotPersistent2();
setBlockEditingMode2(clientId, mode2);
return () => {
__unstableMarkNextChangeAsNotPersistent2();
unsetBlockEditingMode2(clientId);
};
}, [registry, clientId, mode2]);
return clientId ? context[blockEditingModeKey] : globalBlockEditingMode;
}
// packages/block-editor/build-module/hooks/text-align.mjs
var import_jsx_runtime441 = __toESM(require_jsx_runtime(), 1);
var TEXT_ALIGN_SUPPORT_KEY2 = "typography.textAlign";
var TEXT_ALIGNMENT_OPTIONS2 = [
{
icon: align_left_default,
title: (0, import_i18n205.__)("Align text left"),
align: "left"
},
{
icon: align_center_default,
title: (0, import_i18n205.__)("Align text center"),
align: "center"
},
{
icon: align_right_default,
title: (0, import_i18n205.__)("Align text right"),
align: "right"
}
];
var VALID_TEXT_ALIGNMENTS = ["left", "center", "right"];
var NO_TEXT_ALIGNMENTS = [];
function getValidTextAlignments(blockTextAlign) {
if (Array.isArray(blockTextAlign)) {
return VALID_TEXT_ALIGNMENTS.filter(
(textAlign) => blockTextAlign.includes(textAlign)
);
}
return blockTextAlign === true ? VALID_TEXT_ALIGNMENTS : NO_TEXT_ALIGNMENTS;
}
function getTextAlignControlGroup(isResponsiveEditing3, selectedState) {
return isResponsiveEditing3 && hasViewportBlockStyleState(selectedState) ? "style-state" : "block";
}
function BlockEditTextAlignmentToolbarControlsPure({
clientId,
style,
name: blockName,
setAttributes
}) {
const settings2 = useBlockSettings(blockName);
const hasTextAlignControl = settings2?.typography?.textAlign;
const blockEditingMode = useBlockEditingMode();
const { selectedState, isResponsiveEditing: isResponsiveEditing3 } = (0, import_data169.useSelect)(
(select3) => {
const {
getSelectedBlockStyleState: getSelectedBlockStyleState2,
isResponsiveEditing: getIsResponsiveEditing
} = unlock(select3(store));
return {
selectedState: getSelectedBlockStyleState2(clientId),
isResponsiveEditing: getIsResponsiveEditing()
};
},
[clientId]
);
if (!hasTextAlignControl || blockEditingMode !== "default") {
return null;
}
const validTextAlignments = getValidTextAlignments(
(0, import_blocks99.getBlockSupport)(blockName, TEXT_ALIGN_SUPPORT_KEY2)
);
if (!validTextAlignments.length) {
return null;
}
const textAlignmentControls = TEXT_ALIGNMENT_OPTIONS2.filter(
(control) => validTextAlignments.includes(control.align)
);
const stateStyle = getStyleForState(style, selectedState);
const controlsGroup = getTextAlignControlGroup(
isResponsiveEditing3,
selectedState
);
const onChange = (newTextAlignValue) => {
const newStateStyle = {
...stateStyle,
typography: {
...stateStyle?.typography,
textAlign: newTextAlignValue
}
};
setAttributes({
style: setStyleForState(style, selectedState, newStateStyle)
});
};
return /* @__PURE__ */ (0, import_jsx_runtime441.jsx)(block_controls_default, { group: controlsGroup, children: /* @__PURE__ */ (0, import_jsx_runtime441.jsx)(
AlignmentControl,
{
value: stateStyle?.typography?.textAlign,
onChange,
alignmentControls: textAlignmentControls
}
) });
}
var text_align_default = {
edit: BlockEditTextAlignmentToolbarControlsPure,
useBlockProps: useBlockProps9,
addSaveProps: addAssignedTextAlign,
attributeKeys: ["style"],
hasSupport(name) {
return (0, import_blocks99.hasBlockSupport)(name, TEXT_ALIGN_SUPPORT_KEY2, false);
}
};
function useBlockProps9({ name, style }) {
if (!style?.typography?.textAlign) {
return null;
}
const validTextAlignments = getValidTextAlignments(
(0, import_blocks99.getBlockSupport)(name, TEXT_ALIGN_SUPPORT_KEY2)
);
if (!validTextAlignments.length) {
return null;
}
if (shouldSkipSerialization(name, TYPOGRAPHY_SUPPORT_KEY, "textAlign")) {
return null;
}
const textAlign = style.typography.textAlign;
const className = clsx_default({
[`has-text-align-${textAlign}`]: textAlign
});
return { className };
}
function addAssignedTextAlign(props, blockType, attributes) {
if (!attributes?.style?.typography?.textAlign) {
return props;
}
const { textAlign } = attributes.style.typography;
const blockTextAlign = (0, import_blocks99.getBlockSupport)(blockType, TEXT_ALIGN_SUPPORT_KEY2);
const isTextAlignValid = getValidTextAlignments(blockTextAlign).includes(textAlign);
if (isTextAlignValid && !shouldSkipSerialization(
blockType,
TYPOGRAPHY_SUPPORT_KEY,
"textAlign"
)) {
props.className = clsx_default(
`has-text-align-${textAlign}`,
props.className
);
}
return props;
}
// packages/block-editor/build-module/hooks/fit-text.mjs
var import_hooks17 = __toESM(require_hooks(), 1);
var import_blocks100 = __toESM(require_blocks(), 1);
var import_element263 = __toESM(require_element(), 1);
var import_data170 = __toESM(require_data(), 1);
var import_i18n207 = __toESM(require_i18n(), 1);
var import_components216 = __toESM(require_components(), 1);
var import_compose94 = __toESM(require_compose(), 1);
// packages/block-editor/build-module/utils/fit-text-utils.mjs
function findOptimalFontSize(textElement, applyFontSize) {
const alreadyHasScrollableHeight = textElement.scrollHeight > textElement.clientHeight;
let minSize = 0;
let maxSize = 2400;
let bestSize = minSize;
const computedStyle = window.getComputedStyle(textElement);
let paddingLeft = parseFloat(computedStyle.paddingLeft) || 0;
let paddingRight = parseFloat(computedStyle.paddingRight) || 0;
const range2 = document.createRange();
range2.selectNodeContents(textElement);
let referenceElement = textElement;
const parentElement = textElement.parentElement;
if (parentElement) {
const parentElementComputedStyle = window.getComputedStyle(parentElement);
if (parentElementComputedStyle?.display === "flex") {
referenceElement = parentElement;
paddingLeft += parseFloat(parentElementComputedStyle.paddingLeft) || 0;
paddingRight += parseFloat(parentElementComputedStyle.paddingRight) || 0;
}
}
let maxclientHeight = referenceElement.clientHeight;
while (minSize <= maxSize) {
const midSize = Math.floor((minSize + maxSize) / 2);
applyFontSize(midSize);
const rect = range2.getBoundingClientRect();
const textWidth = rect.width;
const fitsWidth = textElement.scrollWidth <= referenceElement.clientWidth && textWidth <= referenceElement.clientWidth - paddingLeft - paddingRight;
const fitsHeight = alreadyHasScrollableHeight || textElement.scrollHeight <= referenceElement.clientHeight || textElement.scrollHeight <= maxclientHeight;
if (referenceElement.clientHeight > maxclientHeight) {
maxclientHeight = referenceElement.clientHeight;
}
if (fitsWidth && fitsHeight) {
bestSize = midSize;
minSize = midSize + 1;
} else {
maxSize = midSize - 1;
}
}
range2.detach();
return bestSize;
}
function optimizeFitText(textElement, applyFontSize) {
if (!textElement) {
return;
}
applyFontSize(0);
const optimalSize = findOptimalFontSize(textElement, applyFontSize);
applyFontSize(optimalSize);
return optimalSize;
}
// packages/block-editor/build-module/components/fit-text-size-warning/index.mjs
var import_element262 = __toESM(require_element(), 1);
var import_i18n206 = __toESM(require_i18n(), 1);
var import_components215 = __toESM(require_components(), 1);
var import_a11y20 = __toESM(require_a11y(), 1);
var import_jsx_runtime442 = __toESM(require_jsx_runtime(), 1);
function FitTextSizeWarning() {
const message2 = (0, import_i18n206.__)(
"The text may be too small to read. Consider using a larger container or less text."
);
(0, import_element262.useEffect)(() => {
(0, import_a11y20.speak)(message2);
}, [message2]);
return /* @__PURE__ */ (0, import_jsx_runtime442.jsx)("div", { className: "block-editor-fit-text-size-warning", children: /* @__PURE__ */ (0, import_jsx_runtime442.jsx)(
import_components215.Notice,
{
spokenMessage: null,
status: "warning",
isDismissible: false,
children: message2
}
) });
}
// packages/block-editor/build-module/hooks/fit-text.mjs
var import_jsx_runtime443 = __toESM(require_jsx_runtime(), 1);
var EMPTY_OBJECT4 = {};
var MIN_FONT_SIZE_FOR_WARNING = 12;
var FIT_TEXT_SUPPORT_KEY = "typography.fitText";
function addAttributes5(settings2) {
if (!(0, import_blocks100.hasBlockSupport)(settings2, FIT_TEXT_SUPPORT_KEY)) {
return settings2;
}
if (settings2.attributes?.fitText) {
return settings2;
}
return {
...settings2,
attributes: {
...settings2.attributes,
fitText: {
type: "boolean"
}
}
};
}
function useFitText({ fitText, name, clientId }) {
const [fontSize, setFontSize] = (0, import_element263.useState)(null);
const hasFitTextSupport2 = (0, import_blocks100.hasBlockSupport)(name, FIT_TEXT_SUPPORT_KEY);
const blockElement = useBlockElement(clientId);
const { blockAttributes, parentId, blockMode } = (0, import_data170.useSelect)(
(select3) => {
if (!clientId || !hasFitTextSupport2 || !fitText) {
return EMPTY_OBJECT4;
}
const _blockMode = select3(store).getBlockMode(clientId);
if (_blockMode === "html") {
return { blockMode: _blockMode };
}
return {
blockAttributes: select3(store).getBlockAttributes(clientId),
parentId: select3(store).getBlockRootClientId(clientId),
blockMode: _blockMode
};
},
[clientId, hasFitTextSupport2, fitText]
);
const applyFitText = (0, import_element263.useCallback)(() => {
if (!blockElement || !hasFitTextSupport2 || !fitText) {
return;
}
const styleId = `fit-text-${clientId}`;
let styleElement = blockElement.ownerDocument.getElementById(styleId);
if (!styleElement) {
styleElement = blockElement.ownerDocument.createElement("style");
styleElement.id = styleId;
blockElement.ownerDocument.head.appendChild(styleElement);
}
const blockSelector = `#block-${clientId}`;
const applyFontSizeStyle = (size4) => {
if (size4 === 0) {
styleElement.textContent = "";
} else {
styleElement.textContent = `${blockSelector} { font-size: ${size4}px !important; }`;
}
};
const optimalSize = optimizeFitText(blockElement, applyFontSizeStyle);
setFontSize(optimalSize);
}, [blockElement, clientId, hasFitTextSupport2, fitText]);
(0, import_element263.useEffect)(() => {
if (!fitText || !blockElement || !clientId || !hasFitTextSupport2 || blockMode === "html") {
return;
}
const currentElement = blockElement;
const previousVisibility = currentElement.style.visibility;
let hideFrameId = null;
let calculateFrameId = null;
let showTimeoutId = null;
hideFrameId = window.requestAnimationFrame(() => {
currentElement.style.visibility = "hidden";
calculateFrameId = window.requestAnimationFrame(() => {
applyFitText();
showTimeoutId = setTimeout(() => {
currentElement.style.visibility = previousVisibility;
}, 10);
});
});
let resizeObserver;
if (window.ResizeObserver && currentElement.parentElement) {
resizeObserver = new window.ResizeObserver(applyFitText);
resizeObserver.observe(currentElement.parentElement);
resizeObserver.observe(currentElement);
}
return () => {
if (hideFrameId !== null) {
window.cancelAnimationFrame(hideFrameId);
}
if (calculateFrameId !== null) {
window.cancelAnimationFrame(calculateFrameId);
}
if (showTimeoutId !== null) {
clearTimeout(showTimeoutId);
}
if (resizeObserver) {
resizeObserver.disconnect();
}
const styleId = `fit-text-${clientId}`;
const styleElement = currentElement.ownerDocument.getElementById(styleId);
if (styleElement) {
styleElement.remove();
}
};
}, [
fitText,
clientId,
parentId,
applyFitText,
blockElement,
hasFitTextSupport2,
blockMode
]);
(0, import_element263.useEffect)(() => {
if (fitText && blockElement && hasFitTextSupport2 && blockMode !== "html") {
const frameId = window.requestAnimationFrame(() => {
if (blockElement) {
applyFitText();
}
});
return () => window.cancelAnimationFrame(frameId);
}
}, [
blockAttributes,
fitText,
applyFitText,
blockElement,
hasFitTextSupport2,
blockMode
]);
return { fontSize };
}
function FitTextControl({
clientId,
fitText = false,
setAttributes,
name,
fontSize,
style
}) {
const hasSelectedStyleState2 = (0, import_data170.useSelect)(
(select3) => {
const { hasSelectedStyleState: hasSelectedBlockStyleState } = unlock(select3(store));
return hasSelectedBlockStyleState(clientId);
},
[clientId]
);
if (!(0, import_blocks100.hasBlockSupport)(name, FIT_TEXT_SUPPORT_KEY)) {
return null;
}
if (hasSelectedStyleState2) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime443.jsx)(
import_components216.__experimentalToolsPanelItem,
{
hasValue: () => fitText,
label: (0, import_i18n207.__)("Fit text"),
onDeselect: () => setAttributes({ fitText: void 0 }),
resetAllFilter: () => ({ fitText: void 0 }),
panelId: clientId,
children: /* @__PURE__ */ (0, import_jsx_runtime443.jsx)(
import_components216.ToggleControl,
{
label: (0, import_i18n207.__)("Fit text"),
checked: fitText,
onChange: () => {
const newFitText = !fitText || void 0;
const updates = { fitText: newFitText };
if (newFitText) {
if (fontSize) {
updates.fontSize = void 0;
}
if (style?.typography?.fontSize) {
updates.style = {
...style,
typography: {
...style?.typography,
fontSize: void 0
}
};
}
}
setAttributes(updates);
},
help: fitText ? (0, import_i18n207.__)("Text will resize to fit its container.") : (0, import_i18n207.__)(
"The text will resize to fit its container, resetting other font size settings."
)
}
)
}
);
}
function addSaveProps5(props, blockType, attributes) {
if (!(0, import_blocks100.hasBlockSupport)(blockType, FIT_TEXT_SUPPORT_KEY)) {
return props;
}
const { fitText } = attributes;
if (!fitText) {
return props;
}
const className = props.className ? `${props.className} has-fit-text` : "has-fit-text";
return {
...props,
className
};
}
function useBlockProps10({ name, fitText }) {
if (fitText && (0, import_blocks100.hasBlockSupport)(name, FIT_TEXT_SUPPORT_KEY)) {
return {
className: "has-fit-text"
};
}
return {};
}
(0, import_hooks17.addFilter)(
"blocks.registerBlockType",
"core/fit-text/addAttribute",
addAttributes5
);
var hasFitTextSupport = (blockNameOrType) => {
return (0, import_blocks100.hasBlockSupport)(blockNameOrType, FIT_TEXT_SUPPORT_KEY);
};
function FitTextFontSize({ fitText, name, clientId, isSelected }) {
const { fontSize } = useFitText({ fitText, name, clientId });
if (isSelected && fontSize && fontSize < MIN_FONT_SIZE_FOR_WARNING) {
return /* @__PURE__ */ (0, import_jsx_runtime443.jsx)(inspector_controls_default, { group: "typography", children: /* @__PURE__ */ (0, import_jsx_runtime443.jsx)(FitTextSizeWarning, {}) });
}
return null;
}
var addFitTextControl = (0, import_compose94.createHigherOrderComponent)((BlockEdit2) => {
return function AddFitTextControl(props) {
const { name, attributes, clientId, isSelected, setAttributes } = props;
const { fitText } = attributes;
const supportsFitText = (0, import_blocks100.hasBlockSupport)(name, FIT_TEXT_SUPPORT_KEY);
if (!supportsFitText) {
return /* @__PURE__ */ (0, import_jsx_runtime443.jsx)(BlockEdit2, { ...props });
}
return /* @__PURE__ */ (0, import_jsx_runtime443.jsxs)(import_jsx_runtime443.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime443.jsx)(BlockEdit2, { ...props }),
/* @__PURE__ */ (0, import_jsx_runtime443.jsx)(inspector_controls_default, { group: "typography", children: /* @__PURE__ */ (0, import_jsx_runtime443.jsx)(
FitTextControl,
{
clientId,
fitText,
setAttributes,
name,
fontSize: attributes.fontSize,
style: attributes.style
}
) }),
fitText && /* @__PURE__ */ (0, import_jsx_runtime443.jsx)(
FitTextFontSize,
{
fitText,
name,
clientId,
isSelected
}
)
] });
};
}, "addFitTextControl");
(0, import_hooks17.addFilter)(
"editor.BlockEdit",
"core/fit-text/add-fit-text-control",
addFitTextControl
);
var fit_text_default = {
useBlockProps: useBlockProps10,
addSaveProps: addSaveProps5,
attributeKeys: ["fitText", "fontSize", "style"],
hasSupport: hasFitTextSupport,
edit: () => null
};
// packages/block-editor/build-module/hooks/typography.mjs
var import_jsx_runtime444 = __toESM(require_jsx_runtime(), 1);
function omit(object, keys) {
return Object.fromEntries(
Object.entries(object).filter(([key]) => !keys.includes(key))
);
}
var LETTER_SPACING_SUPPORT_KEY2 = "typography.__experimentalLetterSpacing";
var TEXT_TRANSFORM_SUPPORT_KEY2 = "typography.__experimentalTextTransform";
var TEXT_DECORATION_SUPPORT_KEY2 = "typography.__experimentalTextDecoration";
var TEXT_INDENT_SUPPORT_KEY = "typography.textIndent";
var TEXT_COLUMNS_SUPPORT_KEY2 = "typography.textColumns";
var FONT_STYLE_SUPPORT_KEY2 = "typography.__experimentalFontStyle";
var FONT_WEIGHT_SUPPORT_KEY2 = "typography.__experimentalFontWeight";
var WRITING_MODE_SUPPORT_KEY2 = "typography.__experimentalWritingMode";
var TYPOGRAPHY_SUPPORT_KEY = "typography";
var TYPOGRAPHY_SUPPORT_KEYS2 = [
LINE_HEIGHT_SUPPORT_KEY2,
FONT_SIZE_SUPPORT_KEY2,
FONT_STYLE_SUPPORT_KEY2,
FONT_WEIGHT_SUPPORT_KEY2,
FONT_FAMILY_SUPPORT_KEY2,
TEXT_ALIGN_SUPPORT_KEY2,
TEXT_COLUMNS_SUPPORT_KEY2,
TEXT_DECORATION_SUPPORT_KEY2,
TEXT_INDENT_SUPPORT_KEY,
WRITING_MODE_SUPPORT_KEY2,
TEXT_TRANSFORM_SUPPORT_KEY2,
LETTER_SPACING_SUPPORT_KEY2,
FIT_TEXT_SUPPORT_KEY
];
function styleToAttributes2(style) {
const updatedStyle = { ...omit(style, ["fontFamily"]) };
const fontSizeValue = style?.typography?.fontSize;
const fontFamilyValue = style?.typography?.fontFamily;
const textColorValue = style?.color?.text;
const fontSizeSlug = typeof fontSizeValue === "string" && fontSizeValue?.startsWith("var:preset|font-size|") ? fontSizeValue.substring("var:preset|font-size|".length) : void 0;
const fontFamilySlug = fontFamilyValue?.startsWith(
"var:preset|font-family|"
) ? fontFamilyValue.substring("var:preset|font-family|".length) : void 0;
const textColorSlug = extractPresetSlug(textColorValue, "color");
updatedStyle.typography = {
...omit(updatedStyle.typography, ["fontFamily"]),
fontSize: fontSizeSlug ? void 0 : fontSizeValue
};
updatedStyle.color = {
...updatedStyle.color,
text: textColorSlug ? void 0 : textColorValue
};
return {
style: cleanEmptyObject(updatedStyle),
fontFamily: fontFamilySlug,
fontSize: fontSizeSlug,
textColor: textColorSlug
};
}
function attributesToStyle2(attributes) {
return {
...attributes.style,
typography: {
...attributes.style?.typography,
fontFamily: attributes.fontFamily ? "var:preset|font-family|" + attributes.fontFamily : void 0,
fontSize: attributes.fontSize ? "var:preset|font-size|" + attributes.fontSize : attributes.style?.typography?.fontSize
},
color: {
...attributes.style?.color,
text: attributes.textColor ? "var:preset|color|" + attributes.textColor : attributes.style?.color?.text
}
};
}
function TypographyInspectorControl({ children, resetAllFilter }) {
const attributesResetAllFilter = (0, import_element264.useCallback)(
(attributes) => {
const existingStyle = attributesToStyle2(attributes);
const updatedStyle = resetAllFilter(existingStyle);
return {
...attributes,
...styleToAttributes2(updatedStyle)
};
},
[resetAllFilter]
);
return /* @__PURE__ */ (0, import_jsx_runtime444.jsx)(
inspector_controls_default,
{
group: "typography",
resetAllFilter: attributesResetAllFilter,
children
}
);
}
function TypographyPanel2({
clientId,
name,
setAttributes,
settings: settings2,
// Allows rendering outside the `typography` inspector group (e.g. section
// blocks direct-render this panel because their support fills are gated
// off by editing mode). Defaults to the slot-based wrapper.
asWrapper
}) {
const selectedState = useBlockStyleState();
const isEnabled = useHasTypographyPanel(settings2);
const { style, fontFamily, fontSize, fitText, textColor } = (0, import_data171.useSelect)(
(select3) => {
if (!isEnabled) {
return {};
}
const {
style: _style,
fontFamily: _fontFamily,
fontSize: _fontSize,
fitText: _fitText,
textColor: _textColor
} = select3(store).getBlockAttributes(clientId) || {};
return {
style: _style,
fontFamily: _fontFamily,
fontSize: _fontSize,
fitText: _fitText,
textColor: _textColor
};
},
[clientId, isEnabled]
);
const isStateSelected = !isDefaultBlockStyleState(selectedState);
const value = (0, import_element264.useMemo)(() => {
if (isStateSelected) {
return getStyleForState(style, selectedState);
}
return attributesToStyle2({ style, fontFamily, fontSize, textColor });
}, [
isStateSelected,
selectedState,
style,
fontSize,
fontFamily,
textColor
]);
const onChange = isStateSelected ? (newStyle) => {
setAttributes({
style: setStyleForState(style, selectedState, newStyle)
});
} : (newStyle) => {
const newAttributes = styleToAttributes2(newStyle);
const hasFontSize = newAttributes.fontSize || newAttributes.style?.typography?.fontSize;
if (hasFontSize && fitText) {
newAttributes.fitText = void 0;
}
setAttributes(newAttributes);
};
const enableContrastChecking = !value?.color?.gradient && !!value?.color?.text && settings2?.color?.text && false !== (0, import_blocks101.getBlockSupport)(name, ["color", "enableContrastChecker"]);
const contrastWarning = useBlockColorContrastWarning({
clientId,
name,
enabled: !!enableContrastChecking,
checkLinkColor: false,
messageOverride: (0, import_i18n208.__)(
"This color has poor contrast against the background. Consider increasing contrast."
)
});
if (!isEnabled) {
return null;
}
const typographyDefaultControls = (0, import_blocks101.getBlockSupport)(name, [
TYPOGRAPHY_SUPPORT_KEY,
"__experimentalDefaultControls"
]);
const colorDefaultControls = (0, import_blocks101.getBlockSupport)(name, [
"color",
"__experimentalDefaultControls"
]);
const defaultControls = {
...typographyDefaultControls,
textColor: colorDefaultControls?.text
};
const Wrapper = asWrapper || TypographyInspectorControl;
return /* @__PURE__ */ (0, import_jsx_runtime444.jsx)(
TypographyPanel,
{
as: Wrapper,
panelId: clientId,
settings: settings2,
value,
onChange,
defaultControls,
contrastWarning
}
);
}
// packages/block-editor/build-module/components/inspector-controls-tabs/styles-tab.mjs
var import_jsx_runtime445 = __toESM(require_jsx_runtime(), 1);
function SectionStyleControls({
blockName,
clientId,
contentClientIds
}) {
const settings2 = useBlockSettings(blockName);
const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data172.useDispatch)(store);
const { hasButtons, hasHeading } = (0, import_data172.useSelect)(
(select3) => {
const blockNames = select3(store).getBlockNamesByClientId(
contentClientIds
);
return {
hasButtons: blockNames.includes("core/buttons"),
hasHeading: blockNames.includes("core/heading")
};
},
[contentClientIds]
);
const setAttributes = (newAttributes) => {
updateBlockAttributes2(clientId, newAttributes);
};
const typographySettings = (0, import_element265.useMemo)(
() => ({ ...settings2, typography: {} }),
[settings2]
);
const backgroundSettings = (0, import_element265.useMemo)(
() => ({
...settings2,
background: {
...settings2.background,
backgroundImage: false,
backgroundSize: false
}
}),
[settings2]
);
return /* @__PURE__ */ (0, import_jsx_runtime445.jsxs)(import_jsx_runtime445.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime445.jsx)(
TypographyPanel2,
{
clientId,
name: blockName,
settings: typographySettings,
setAttributes,
asWrapper: TypographyToolsPanel
}
),
/* @__PURE__ */ (0, import_jsx_runtime445.jsx)(
BackgroundImagePanel3,
{
clientId,
name: blockName,
settings: backgroundSettings,
setAttributes,
asWrapper: BackgroundToolsPanel
}
),
/* @__PURE__ */ (0, import_jsx_runtime445.jsx)(
ElementsEdit,
{
clientId,
name: blockName,
settings: settings2,
setAttributes,
asWrapper: ColorToolsPanel,
label: (0, import_i18n209.__)("Elements"),
defaultControls: {
button: hasButtons,
heading: hasHeading
}
}
)
] });
}
var StylesTab = ({
blockName,
clientId,
hasBlockStyles,
isSectionBlock: isSectionBlock2,
contentClientIds
}) => {
const borderPanelLabel = useBorderPanelLabel({ blockName });
return /* @__PURE__ */ (0, import_jsx_runtime445.jsxs)(import_jsx_runtime445.Fragment, { children: [
hasBlockStyles && /* @__PURE__ */ (0, import_jsx_runtime445.jsx)(block_styles_default, { clientId }),
isSectionBlock2 && blockName !== "core/template-part" && /* @__PURE__ */ (0, import_jsx_runtime445.jsx)(
SectionStyleControls,
{
blockName,
clientId,
contentClientIds
}
),
(!isSectionBlock2 || blockName === "core/template-part") && /* @__PURE__ */ (0, import_jsx_runtime445.jsxs)(import_jsx_runtime445.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime445.jsx)(
inspector_controls_default.Slot,
{
group: "typography",
label: (0, import_i18n209.__)("Typography")
}
),
/* @__PURE__ */ (0, import_jsx_runtime445.jsx)(
inspector_controls_default.Slot,
{
group: "color",
label: (0, import_i18n209.__)("Color"),
className: "color-block-support-panel__inner-wrapper"
}
),
/* @__PURE__ */ (0, import_jsx_runtime445.jsx)(
inspector_controls_default.Slot,
{
group: "background",
label: (0, import_i18n209.__)("Background"),
className: "background-block-support-panel__inner-wrapper"
}
),
/* @__PURE__ */ (0, import_jsx_runtime445.jsx)(inspector_controls_default.Slot, { group: "filter" }),
/* @__PURE__ */ (0, import_jsx_runtime445.jsx)(
inspector_controls_default.Slot,
{
group: "layout",
label: (0, import_i18n209.__)("Layout")
}
),
/* @__PURE__ */ (0, import_jsx_runtime445.jsx)(
inspector_controls_default.Slot,
{
group: "dimensions",
label: (0, import_i18n209.__)("Dimensions")
}
),
/* @__PURE__ */ (0, import_jsx_runtime445.jsx)(
inspector_controls_default.Slot,
{
group: "border",
label: borderPanelLabel
}
),
/* @__PURE__ */ (0, import_jsx_runtime445.jsx)(
inspector_controls_default.Slot,
{
group: "elements",
label: (0, import_i18n209.__)("Elements"),
className: "elements-block-support-panel__inner-wrapper"
}
),
/* @__PURE__ */ (0, import_jsx_runtime445.jsx)(position_controls_panel_default, {}),
/* @__PURE__ */ (0, import_jsx_runtime445.jsx)(inspector_controls_default.Slot, { group: "styles" })
] })
] });
};
var styles_tab_default = StylesTab;
// packages/block-editor/build-module/components/inspector-controls-tabs/content-tab.mjs
var import_components218 = __toESM(require_components(), 1);
var import_i18n210 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/block-quick-navigation/index.mjs
var import_blocks102 = __toESM(require_blocks(), 1);
var import_data173 = __toESM(require_data(), 1);
var import_components217 = __toESM(require_components(), 1);
var import_jsx_runtime446 = __toESM(require_jsx_runtime(), 1);
function BlockQuickNavigation({
clientIds,
onSelect,
onSwitchToListView,
hasListViewTab
}) {
if (!clientIds.length) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime446.jsx)(import_components217.__experimentalVStack, { spacing: 1, children: clientIds.map((clientId) => /* @__PURE__ */ (0, import_jsx_runtime446.jsx)(
BlockQuickNavigationItem,
{
onSelect,
onSwitchToListView,
hasListViewTab,
clientId
},
clientId
)) });
}
function BlockQuickNavigationItem({
clientId,
onSelect,
onSwitchToListView,
hasListViewTab
}) {
const blockInformation = useBlockDisplayInformation(clientId);
const { isSelected, childBlocks, shouldRenderListView, blockName } = (0, import_data173.useSelect)(
(select3) => {
const {
isBlockSelected: isBlockSelected2,
hasSelectedInnerBlock: hasSelectedInnerBlock2,
getBlockOrder: getBlockOrder2,
getBlockName: getBlockName2,
shouldRenderBlockListView: shouldRenderBlockListView2
} = unlock(select3(store));
const _blockName = getBlockName2(clientId);
return {
isSelected: isBlockSelected2(clientId) || hasSelectedInnerBlock2(
clientId,
/* deep: */
true
),
childBlocks: getBlockOrder2(clientId),
shouldRenderListView: shouldRenderBlockListView2(clientId),
blockName: _blockName
};
},
[clientId]
);
const blockType = (0, import_blocks102.getBlockType)(blockName);
const displayTitle = useBlockDisplayTitle({
clientId,
context: "list-view"
});
const blockTitle = displayTitle || blockType?.title || blockName;
const { selectBlock: selectBlock2 } = (0, import_data173.useDispatch)(store);
const hasChildren = childBlocks && childBlocks.length > 0;
const canNavigateToListView = hasChildren && hasListViewTab && shouldRenderListView;
return /* @__PURE__ */ (0, import_jsx_runtime446.jsx)(
import_components217.Button,
{
__next40pxDefaultSize: true,
className: "block-editor-block-quick-navigation__item",
isPressed: isSelected,
onClick: async () => {
await selectBlock2(clientId);
if (canNavigateToListView && onSwitchToListView) {
onSwitchToListView(clientId);
}
if (onSelect) {
onSelect(clientId);
}
},
children: /* @__PURE__ */ (0, import_jsx_runtime446.jsxs)(import_components217.Flex, { children: [
/* @__PURE__ */ (0, import_jsx_runtime446.jsx)(import_components217.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime446.jsx)(block_icon_default, { icon: blockInformation?.icon }) }),
/* @__PURE__ */ (0, import_jsx_runtime446.jsx)(import_components217.FlexBlock, { style: { textAlign: "left" }, children: /* @__PURE__ */ (0, import_jsx_runtime446.jsx)(import_components217.__experimentalTruncate, { children: blockTitle }) }),
canNavigateToListView && /* @__PURE__ */ (0, import_jsx_runtime446.jsx)(import_components217.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime446.jsx)(icon_default, { icon: chevron_right_default, size: 24 }) })
] })
}
);
}
// packages/block-editor/build-module/components/inspector-controls-tabs/content-tab.mjs
var import_jsx_runtime447 = __toESM(require_jsx_runtime(), 1);
var ContentTab = ({
contentClientIds,
onSwitchToListView,
hasListViewTab
}) => {
if (!contentClientIds || contentClientIds.length === 0) {
return null;
}
const shouldShowBlockFields = window?.__experimentalContentOnlyInspectorFields;
return /* @__PURE__ */ (0, import_jsx_runtime447.jsx)(import_jsx_runtime447.Fragment, { children: !shouldShowBlockFields && /* @__PURE__ */ (0, import_jsx_runtime447.jsx)(import_components218.PanelBody, { title: (0, import_i18n210.__)("Content"), children: /* @__PURE__ */ (0, import_jsx_runtime447.jsx)(
BlockQuickNavigation,
{
clientIds: contentClientIds,
onSwitchToListView,
hasListViewTab
}
) }) });
};
var content_tab_default = ContentTab;
// packages/block-editor/build-module/components/inspector-controls-tabs/index.mjs
var import_jsx_runtime448 = __toESM(require_jsx_runtime(), 1);
var { Tabs: Tabs5 } = unlock(import_components219.privateApis);
function InspectorControlsTabs({
blockName,
clientId,
hasBlockStyles,
tabs,
isSectionBlock: isSectionBlock2,
contentClientIds
}) {
const listViewRef = (0, import_element266.useRef)(null);
const showIconLabels = (0, import_data174.useSelect)((select3) => {
return select3(import_preferences5.store).get("core", "showIconLabels");
}, []);
const { requestedTab } = (0, import_data174.useSelect)((select3) => ({
requestedTab: unlock(
select3(store)
).getRequestedInspectorTab()
}));
const [selectedTabId, setSelectedTabId] = (0, import_element266.useState)(
() => requestedTab?.tabName ?? tabs[0]?.name
);
const hasUserSelectionRef = (0, import_element266.useRef)(false);
const isProgrammaticSwitchRef = (0, import_element266.useRef)(false);
const {
__unstableSetOpenListViewPanel: setOpenListViewPanel,
__unstableIncrementListViewExpandRevision: incrementListViewExpandRevision,
__unstableSetAllListViewPanelsOpen: setAllListViewPanelsOpen
} = (0, import_data174.useDispatch)(store);
const { clearRequestedInspectorTab: clearRequestedInspectorTab2 } = unlock(
(0, import_data174.useDispatch)(store)
);
(0, import_element266.useEffect)(() => {
hasUserSelectionRef.current = false;
}, [clientId]);
(0, import_element266.useEffect)(() => {
if (!requestedTab) {
return;
}
setSelectedTabId(requestedTab.tabName);
if (requestedTab.tabName === TAB_LIST_VIEW.name && requestedTab.options?.openPanel) {
setOpenListViewPanel(requestedTab.options.openPanel);
incrementListViewExpandRevision();
}
isProgrammaticSwitchRef.current = true;
hasUserSelectionRef.current = true;
clearRequestedInspectorTab2();
}, [
requestedTab,
setOpenListViewPanel,
incrementListViewExpandRevision,
clearRequestedInspectorTab2
]);
(0, import_element266.useEffect)(() => {
if (selectedTabId === TAB_LIST_VIEW.name && !hasUserSelectionRef.current) {
setAllListViewPanelsOpen();
incrementListViewExpandRevision();
}
}, [
clientId,
selectedTabId,
setAllListViewPanelsOpen,
incrementListViewExpandRevision
]);
(0, import_element266.useEffect)(() => {
if (!tabs?.length || hasUserSelectionRef.current && tabs.some((tab) => tab.name === selectedTabId)) {
return;
}
const firstTabName = tabs[0]?.name;
if (selectedTabId !== firstTabName) {
setSelectedTabId(firstTabName);
}
}, [tabs, selectedTabId]);
const handleTabSelect = (tabId) => {
setSelectedTabId(tabId);
hasUserSelectionRef.current = true;
if (tabId === TAB_LIST_VIEW.name && !isProgrammaticSwitchRef.current) {
setAllListViewPanelsOpen();
incrementListViewExpandRevision();
}
isProgrammaticSwitchRef.current = false;
};
const hasListViewTab = tabs.some(
(tab) => tab.name === TAB_LIST_VIEW.name
);
const switchToListView = (targetClientId) => {
if (hasListViewTab) {
setOpenListViewPanel(targetClientId);
incrementListViewExpandRevision();
isProgrammaticSwitchRef.current = true;
handleTabSelect(TAB_LIST_VIEW.name);
}
};
return /* @__PURE__ */ (0, import_jsx_runtime448.jsx)("div", { className: "block-editor-block-inspector__tabs", children: /* @__PURE__ */ (0, import_jsx_runtime448.jsxs)(
Tabs5,
{
selectedTabId,
onSelect: handleTabSelect,
children: [
/* @__PURE__ */ (0, import_jsx_runtime448.jsx)(Tabs5.TabList, { children: tabs.map(
(tab) => showIconLabels ? /* @__PURE__ */ (0, import_jsx_runtime448.jsx)(Tabs5.Tab, { tabId: tab.name, children: tab.title }, tab.name) : /* @__PURE__ */ (0, import_jsx_runtime448.jsxs)(tooltip_exports.Root, { children: [
/* @__PURE__ */ (0, import_jsx_runtime448.jsx)(
Tabs5.Tab,
{
tabId: tab.name,
"aria-label": tab.title,
render: /* @__PURE__ */ (0, import_jsx_runtime448.jsx)(tooltip_exports.Trigger, {}),
children: /* @__PURE__ */ (0, import_jsx_runtime448.jsx)(import_components219.Icon, { icon: tab.icon })
}
),
/* @__PURE__ */ (0, import_jsx_runtime448.jsx)(tooltip_exports.Popup, { children: tab.title })
] }, tab.name)
) }),
/* @__PURE__ */ (0, import_jsx_runtime448.jsxs)(Tabs5.TabPanel, { tabId: TAB_CONTENT.name, focusable: false, children: [
/* @__PURE__ */ (0, import_jsx_runtime448.jsx)(
content_tab_default,
{
contentClientIds,
onSwitchToListView: switchToListView,
hasListViewTab
}
),
/* @__PURE__ */ (0, import_jsx_runtime448.jsx)(inspector_controls_default.Slot, { group: "content" })
] }),
/* @__PURE__ */ (0, import_jsx_runtime448.jsxs)(Tabs5.TabPanel, { tabId: TAB_LIST_VIEW.name, focusable: false, children: [
/* @__PURE__ */ (0, import_jsx_runtime448.jsx)(inspector_controls_default.Slot, { group: "list", ref: listViewRef }),
/* @__PURE__ */ (0, import_jsx_runtime448.jsx)(ListViewContentPopover, { listViewRef })
] }),
/* @__PURE__ */ (0, import_jsx_runtime448.jsx)(Tabs5.TabPanel, { tabId: TAB_SETTINGS.name, focusable: false, children: /* @__PURE__ */ (0, import_jsx_runtime448.jsx)(settings_tab_default, { showAdvancedControls: !!blockName }) }),
/* @__PURE__ */ (0, import_jsx_runtime448.jsx)(Tabs5.TabPanel, { tabId: TAB_STYLES.name, focusable: false, children: /* @__PURE__ */ (0, import_jsx_runtime448.jsx)(
styles_tab_default,
{
blockName,
clientId,
hasBlockStyles,
isSectionBlock: isSectionBlock2,
contentClientIds
}
) })
]
},
clientId
) });
}
// packages/block-editor/build-module/components/inspector-controls-tabs/use-inspector-controls-tabs.mjs
var import_components220 = __toESM(require_components(), 1);
var import_data175 = __toESM(require_data(), 1);
var EMPTY_ARRAY15 = [];
function getShowTabs(blockName, tabSettings = {}) {
if (tabSettings[blockName] !== void 0) {
return tabSettings[blockName];
}
if (tabSettings.default !== void 0) {
return tabSettings.default;
}
return true;
}
function useInspectorControlsTabs(blockName, contentClientIds, isSectionBlock2, hasBlockStyles) {
const tabs = [];
const {
bindings: bindingsGroup,
border: borderGroup,
color: colorGroup,
content: contentGroup,
default: defaultGroup,
layout: layoutGroup,
dimensions: dimensionsGroup,
list: listGroup,
position: positionGroup,
styles: stylesGroup,
typography: typographyGroup,
effects: effectsGroup
} = groups_default;
const listFills = (0, import_components220.__experimentalUseSlotFills)(listGroup.name);
const hasListFills = !!listFills && listFills.length;
const contentFills = (0, import_components220.__experimentalUseSlotFills)(contentGroup.name);
const hasContentFills = !!contentFills && contentFills.length;
const styleFills = [
...(0, import_components220.__experimentalUseSlotFills)(borderGroup.name) || [],
...(0, import_components220.__experimentalUseSlotFills)(colorGroup.name) || [],
...(0, import_components220.__experimentalUseSlotFills)(layoutGroup.name) || [],
...(0, import_components220.__experimentalUseSlotFills)(positionGroup.name) || [],
...(0, import_components220.__experimentalUseSlotFills)(dimensionsGroup.name) || [],
...(0, import_components220.__experimentalUseSlotFills)(stylesGroup.name) || [],
...(0, import_components220.__experimentalUseSlotFills)(typographyGroup.name) || [],
...(0, import_components220.__experimentalUseSlotFills)(effectsGroup.name) || []
];
const hasStyleFills = styleFills.length;
const advancedFills = [
...(0, import_components220.__experimentalUseSlotFills)(InspectorAdvancedControls.slotName) || [],
...(0, import_components220.__experimentalUseSlotFills)(bindingsGroup.name) || []
];
const settingsFills = [
...(0, import_components220.__experimentalUseSlotFills)(defaultGroup.name) || [],
...hasListFills && hasStyleFills > 1 ? advancedFills : []
];
const shouldShowBlockFields = window?.__experimentalContentOnlyInspectorFields;
const hasContentTab = hasContentFills || !shouldShowBlockFields && contentClientIds?.length;
if (hasContentTab) {
tabs.push(TAB_CONTENT);
}
if (hasListFills) {
tabs.push(TAB_LIST_VIEW);
}
if (settingsFills.length || // Advanced fills show up in settings tab if available or they blend into the default tab, if there's only one tab.
advancedFills.length && (hasContentTab || hasListFills)) {
tabs.push(TAB_SETTINGS);
}
const { tabSettings, isPreviewMode } = (0, import_data175.useSelect)((select3) => {
const settings2 = select3(store).getSettings();
return {
tabSettings: settings2.blockInspectorTabs,
isPreviewMode: settings2.isPreviewMode
};
}, []);
if (!isPreviewMode && (hasBlockStyles || hasStyleFills)) {
tabs.push(TAB_STYLES);
}
const showTabs = getShowTabs(blockName, tabSettings);
return showTabs ? tabs : EMPTY_ARRAY15;
}
// packages/block-editor/build-module/components/inspector-controls/last-item.mjs
var import_components221 = __toESM(require_components(), 1);
var import_jsx_runtime449 = __toESM(require_jsx_runtime(), 1);
var { Fill: Fill4, Slot: Slot9 } = (0, import_components221.createSlotFill)(/* @__PURE__ */ Symbol("InspectorControlsLastItem"));
var InspectorControlsLastItem = (props) => {
const context = useBlockEditContext();
if (!context[mayDisplayControlsKey]) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime449.jsx)(Fill4, { ...props });
};
InspectorControlsLastItem.Slot = function InspectorControlsLastItemSlot(props) {
return /* @__PURE__ */ (0, import_jsx_runtime449.jsx)(Slot9, { ...props });
};
var last_item_default = InspectorControlsLastItem;
// packages/block-editor/build-module/components/block-inspector/useBlockInspectorAnimationSettings.mjs
var import_data176 = __toESM(require_data(), 1);
function useBlockInspectorAnimationSettings(blockType) {
return (0, import_data176.useSelect)(
(select3) => {
if (blockType) {
const globalBlockInspectorAnimationSettings = select3(store).getSettings().blockInspectorAnimation;
const animationParent = globalBlockInspectorAnimationSettings?.animationParent;
const { getSelectedBlockClientId: getSelectedBlockClientId2, getBlockParentsByBlockName: getBlockParentsByBlockName2 } = select3(store);
const _selectedBlockClientId = getSelectedBlockClientId2();
const animationParentBlockClientId = getBlockParentsByBlockName2(
_selectedBlockClientId,
animationParent,
true
)[0];
if (!animationParentBlockClientId && blockType.name !== animationParent) {
return null;
}
return globalBlockInspectorAnimationSettings?.[blockType.name];
}
return null;
},
[blockType]
);
}
// packages/block-editor/build-module/hooks/states.mjs
var import_element267 = __toESM(require_element(), 1);
var import_i18n211 = __toESM(require_i18n(), 1);
var import_jsx_runtime450 = __toESM(require_jsx_runtime(), 1);
var { getViewportBreakpoints: getViewportBreakpoints5 } = unlock(privateApis);
var PSEUDO_STATE_LABELS = {
":hover": (0, import_i18n211.__)("Hover"),
":focus": (0, import_i18n211.__)("Focus"),
":focus-visible": (0, import_i18n211.__)("Focus-visible"),
":active": (0, import_i18n211.__)("Active")
};
var RESPONSIVE_STATE_LABELS = {
"@tablet": (0, import_i18n211.__)("Tablet"),
"@mobile": (0, import_i18n211.__)("Mobile")
};
function getDeviceStateOptions(viewportSettings) {
const breakpoints = getViewportBreakpoints5(viewportSettings);
return Object.entries(RESPONSIVE_STATE_LABELS).filter(
([value]) => (value !== "@tablet" || breakpoints.tablet !== void 0) && (value !== "@mobile" || breakpoints.mobile !== void 0)
).map(([value, label]) => ({
value,
label
}));
}
var VALID_BLOCK_PSEUDO_STATES = {
"core/button": [":hover", ":focus", ":focus-visible", ":active"],
"core/navigation-link": [":hover", ":focus", ":focus-visible", ":active"]
};
function getPseudoStateOptions(name) {
const validStates = VALID_BLOCK_PSEUDO_STATES[name] ?? [];
return validStates.filter((state) => PSEUDO_STATE_LABELS[state]).map((state) => ({
value: state,
label: PSEUDO_STATE_LABELS[state]
}));
}
var DEFAULT_STATE_VALUE2 = "default";
var EMPTY_STATE_OPTIONS = [];
function BlockStatesControl({ name, value, onChange }) {
const pseudoStateOptions = (0, import_element267.useMemo)(
() => getPseudoStateOptions(name),
[name]
);
const dropdownMenuProps = useToolsPanelDropdownMenuProps();
if (!pseudoStateOptions.length) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime450.jsx)(
StateControl,
{
pseudoStates: pseudoStateOptions,
pseudoStateValue: value?.pseudo ?? DEFAULT_STATE_VALUE2,
onChangePseudoState: (pseudo) => onChange({ pseudo }),
popoverProps: dropdownMenuProps.popoverProps,
showText: false
}
);
}
function BlockStateBadges({ name, value, isResponsiveEditing: isResponsiveEditing3 }) {
const pseudoStateOptions = (0, import_element267.useMemo)(
() => getPseudoStateOptions(name),
[name]
);
const [viewportSettings] = useSettings("viewport");
const deviceStateOptions = (0, import_element267.useMemo)(
() => getDeviceStateOptions(viewportSettings),
[viewportSettings]
);
if (!pseudoStateOptions.length && !isResponsiveEditing3) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime450.jsx)(
StateControlBadges,
{
viewportStates: isResponsiveEditing3 ? deviceStateOptions : EMPTY_STATE_OPTIONS,
pseudoStates: pseudoStateOptions,
viewportValue: value?.viewport ?? DEFAULT_STATE_VALUE2,
pseudoStateValue: value?.pseudo ?? DEFAULT_STATE_VALUE2
}
);
}
// packages/block-editor/build-module/components/block-inspector/index.mjs
var import_jsx_runtime451 = __toESM(require_jsx_runtime(), 1);
function StyleInspectorSlots({
blockName,
showAdvancedControls = true,
showPositionControls = true,
showBindingsControls = true
}) {
const borderPanelLabel = useBorderPanelLabel({ blockName });
return /* @__PURE__ */ (0, import_jsx_runtime451.jsxs)(import_jsx_runtime451.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(inspector_controls_default.Slot, {}),
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
inspector_controls_default.Slot,
{
group: "typography",
label: (0, import_i18n212.__)("Typography")
}
),
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
inspector_controls_default.Slot,
{
group: "color",
label: (0, import_i18n212.__)("Color"),
className: "color-block-support-panel__inner-wrapper"
}
),
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
inspector_controls_default.Slot,
{
group: "background",
label: (0, import_i18n212.__)("Background"),
className: "background-block-support-panel__inner-wrapper"
}
),
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(inspector_controls_default.Slot, { group: "layout", label: (0, import_i18n212.__)("Layout") }),
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
inspector_controls_default.Slot,
{
group: "dimensions",
label: (0, import_i18n212.__)("Dimensions")
}
),
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(inspector_controls_default.Slot, { group: "border", label: borderPanelLabel }),
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
inspector_controls_default.Slot,
{
group: "elements",
label: (0, import_i18n212.__)("Elements"),
className: "elements-block-support-panel__inner-wrapper"
}
),
showPositionControls && /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(position_controls_panel_default, {}),
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(inspector_controls_default.Slot, { group: "styles" }),
showBindingsControls && /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(inspector_controls_default.Slot, { group: "bindings" }),
showAdvancedControls && /* @__PURE__ */ (0, import_jsx_runtime451.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(advanced_controls_panel_default, {}) })
] });
}
function StyleStateInspectorSlots({
blockName,
clientId,
contentClientIds,
isSectionBlock: isSectionBlock2,
selectedBlockStyleState: selectedBlockStyleState2
}) {
const borderPanelLabel = useBorderPanelLabel({ blockName });
const showLayoutControls = hasViewportBlockStyleState(selectedBlockStyleState2) && !hasPseudoBlockStyleState(selectedBlockStyleState2);
const showSectionStyleControls = isSectionBlock2 && blockName !== "core/template-part";
return /* @__PURE__ */ (0, import_jsx_runtime451.jsxs)(import_jsx_runtime451.Fragment, { children: [
showSectionStyleControls && /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(BlockStyleStateProvider, { value: selectedBlockStyleState2, children: /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
SectionStyleControls,
{
blockName,
clientId,
contentClientIds
}
) }),
!showSectionStyleControls && /* @__PURE__ */ (0, import_jsx_runtime451.jsxs)(import_jsx_runtime451.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
inspector_controls_default.Slot,
{
group: "typography",
label: (0, import_i18n212.__)("Typography")
}
),
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
inspector_controls_default.Slot,
{
group: "color",
label: (0, import_i18n212.__)("Color"),
className: "color-block-support-panel__inner-wrapper"
}
),
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
inspector_controls_default.Slot,
{
group: "background",
label: (0, import_i18n212.__)("Background"),
className: "background-block-support-panel__inner-wrapper"
}
),
showLayoutControls && /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
inspector_controls_default.Slot,
{
group: "layout",
label: (0, import_i18n212.__)("Layout")
}
),
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
inspector_controls_default.Slot,
{
group: "dimensions",
label: (0, import_i18n212.__)("Dimensions")
}
),
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
inspector_controls_default.Slot,
{
group: "border",
label: borderPanelLabel
}
),
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
inspector_controls_default.Slot,
{
group: "elements",
label: (0, import_i18n212.__)("Elements"),
className: "elements-block-support-panel__inner-wrapper"
}
)
] })
] });
}
function BlockInspector() {
const {
selectedBlockCount,
renderedBlockName,
renderedBlockClientId,
blockType,
isSectionBlock: isSectionBlock2,
isSectionBlockInSelection,
hasBlockStyles,
editedContentOnlySection: editedContentOnlySection2,
blockEditingMode,
selectedBlockStyleState: selectedBlockStyleState2,
showStateOnCanvas,
isResponsiveEditing: isResponsiveEditing3
} = (0, import_data177.useSelect)((select3) => {
const {
getSelectedBlockClientId: getSelectedBlockClientId2,
getSelectedBlockClientIds: getSelectedBlockClientIds2,
getSelectedBlockCount: getSelectedBlockCount2,
getBlockName: getBlockName2,
getParentSectionBlock: getParentSectionBlock2,
isSectionBlock: _isSectionBlock,
getEditedContentOnlySection: getEditedContentOnlySection2,
isWithinEditedContentOnlySection: isWithinEditedContentOnlySection2,
getBlockEditingMode: getBlockEditingMode2,
getSelectedBlockStyleState: getSelectedBlockStyleState2,
isSelectedBlockStyleStateShownOnCanvas: isSelectedBlockStyleStateShownOnCanvas2,
isResponsiveEditing: _isResponsiveEditing
} = unlock(select3(store));
const { getBlockStyles: getBlockStyles2 } = select3(import_blocks103.store);
const _selectedBlockClientId = getSelectedBlockClientId2();
const isWithinEditedSection = isWithinEditedContentOnlySection2(
_selectedBlockClientId
);
const _renderedBlockClientId = isWithinEditedSection ? _selectedBlockClientId : getParentSectionBlock2(_selectedBlockClientId) || _selectedBlockClientId;
const _renderedBlockName = _renderedBlockClientId && getBlockName2(_renderedBlockClientId);
const _blockType = _renderedBlockName && (0, import_blocks103.getBlockType)(_renderedBlockName);
const selectedBlockClientIds = getSelectedBlockClientIds2();
const _isSectionBlockInSelection = selectedBlockClientIds.some(
(id) => _isSectionBlock(id)
);
const blockStyles = _renderedBlockName && getBlockStyles2(_renderedBlockName);
const _hasBlockStyles = blockStyles && blockStyles.length > 0;
return {
selectedBlockCount: getSelectedBlockCount2(),
renderedBlockClientId: _renderedBlockClientId,
renderedBlockName: _renderedBlockName,
blockType: _blockType,
isSectionBlockInSelection: _isSectionBlockInSelection,
isSectionBlock: _isSectionBlock(_renderedBlockClientId),
hasBlockStyles: _hasBlockStyles,
editedContentOnlySection: getEditedContentOnlySection2(),
blockEditingMode: getBlockEditingMode2(_renderedBlockClientId),
selectedBlockStyleState: getSelectedBlockStyleState2(
_renderedBlockClientId
),
showStateOnCanvas: isSelectedBlockStyleStateShownOnCanvas2(
_renderedBlockClientId
),
isResponsiveEditing: _isResponsiveEditing()
};
}, []);
const contentClientIds = (0, import_data177.useSelect)(
(select3) => {
if (!isSectionBlock2 || !renderedBlockClientId) {
return [];
}
const {
getClientIdsOfDescendants: getClientIdsOfDescendants2,
getBlockEditingMode: getBlockEditingMode2,
shouldRenderBlockListView: shouldRenderBlockListView2
} = unlock(select3(store));
const descendants = getClientIdsOfDescendants2(
renderedBlockClientId
);
const listViewDescendants = /* @__PURE__ */ new Set();
descendants.forEach((clientId) => {
if (shouldRenderBlockListView2(clientId)) {
const listViewChildren = getClientIdsOfDescendants2(clientId);
listViewChildren.forEach(
(childId) => listViewDescendants.add(childId)
);
}
});
return descendants.filter((current) => {
return !listViewDescendants.has(current) && getBlockEditingMode2(current) === "contentOnly";
});
},
[isSectionBlock2, renderedBlockClientId]
);
const availableTabs = useInspectorControlsTabs(
blockType?.name,
contentClientIds,
isSectionBlock2,
hasBlockStyles
);
const hasMultipleTabs = availableTabs?.length > 1;
const blockInspectorAnimationSettings = useBlockInspectorAnimationSettings(blockType);
const hasSelectedBlocks = selectedBlockCount > 1;
const isBlockStyleStateSelected = !isDefaultBlockStyleState(
selectedBlockStyleState2
);
if (hasSelectedBlocks && !isSectionBlockInSelection) {
return /* @__PURE__ */ (0, import_jsx_runtime451.jsxs)("div", { className: "block-editor-block-inspector", children: [
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(MultiSelectionInspector, {}),
hasMultipleTabs ? /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(InspectorControlsTabs, { tabs: availableTabs }) : /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
StyleInspectorSlots,
{
blockName: renderedBlockName,
showAdvancedControls: false,
showPositionControls: false,
showBindingsControls: false
}
)
] });
}
if (hasSelectedBlocks && isSectionBlockInSelection) {
return /* @__PURE__ */ (0, import_jsx_runtime451.jsx)("div", { className: "block-editor-block-inspector", children: /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(MultiSelectionInspector, {}) });
}
const isRenderedBlockUnregistered = renderedBlockName === (0, import_blocks103.getUnregisteredTypeHandlerName)();
const shouldShowWarning = !blockType || !renderedBlockClientId || isRenderedBlockUnregistered;
if (shouldShowWarning) {
return /* @__PURE__ */ (0, import_jsx_runtime451.jsx)("span", { className: "block-editor-block-inspector__no-blocks", children: (0, import_i18n212.__)("No block selected.") });
}
return /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
BlockInspectorSingleBlockWrapper,
{
animate: blockInspectorAnimationSettings,
wrapper: (children) => /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
AnimatedContainer,
{
blockInspectorAnimationSettings,
renderedBlockClientId,
children
}
),
children: /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
BlockInspectorSingleBlock,
{
renderedBlockClientId,
blockName: blockType.name,
isSectionBlock: isSectionBlock2,
availableTabs,
contentClientIds,
hasBlockStyles,
editedContentOnlySection: editedContentOnlySection2,
blockEditingMode,
selectedBlockStyleState: selectedBlockStyleState2,
showStateOnCanvas,
isResponsiveEditing: isResponsiveEditing3,
isBlockStyleStateSelected
}
)
}
);
}
var BlockInspectorSingleBlockWrapper = ({ animate, wrapper, children }) => {
return animate ? wrapper(children) : children;
};
var AnimatedContainer = ({
blockInspectorAnimationSettings,
renderedBlockClientId,
children
}) => {
const animationOrigin = blockInspectorAnimationSettings && blockInspectorAnimationSettings.enterDirection === "leftToRight" ? -50 : 50;
return /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
import_components222.__unstableMotion.div,
{
animate: {
x: 0,
opacity: 1,
transition: {
ease: "easeInOut",
duration: 0.14
}
},
initial: {
x: animationOrigin,
opacity: 0
},
children
},
renderedBlockClientId
);
};
var BlockInspectorSingleBlock = ({
// The block that is displayed in the inspector. This is the block whose
// controls and information are shown to the user.
renderedBlockClientId,
blockName,
isSectionBlock: isSectionBlock2,
availableTabs,
contentClientIds,
hasBlockStyles,
editedContentOnlySection: editedContentOnlySection2,
blockEditingMode,
selectedBlockStyleState: selectedBlockStyleState2,
showStateOnCanvas,
isResponsiveEditing: isResponsiveEditing3
}) => {
const listViewRef = (0, import_element268.useRef)(null);
const hasMultipleTabs = availableTabs?.length > 1;
const hasPseudoState = hasPseudoBlockStyleState(selectedBlockStyleState2);
const isEditingStyleState = hasViewportBlockStyleState(selectedBlockStyleState2) && isResponsiveEditing3 || hasPseudoBlockStyleState(selectedBlockStyleState2);
const hasParentChildBlockCards = editedContentOnlySection2 && editedContentOnlySection2 !== renderedBlockClientId;
const parentBlockInformation = useBlockDisplayInformation(
editedContentOnlySection2
);
const blockInformation = useBlockDisplayInformation(
renderedBlockClientId
);
const isBlockSynced = blockInformation.isSynced;
const {
setSelectedBlockStyleState: setSelectedBlockStyleState2,
setSelectedBlockStyleStateCanvasPreview: setSelectedBlockStyleStateCanvasPreview2
} = unlock((0, import_data177.useDispatch)(store));
const onBlockStyleStateChange = (value) => {
setSelectedBlockStyleState2(renderedBlockClientId, value);
};
const onShowStateOnCanvasChange = (value) => {
setSelectedBlockStyleStateCanvasPreview2(renderedBlockClientId, value);
};
return /* @__PURE__ */ (0, import_jsx_runtime451.jsxs)("div", { className: "block-editor-block-inspector", children: [
hasParentChildBlockCards && /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
block_card_default,
{
...parentBlockInformation,
className: parentBlockInformation?.isSynced && "is-synced",
parentClientId: editedContentOnlySection2
}
),
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
block_card_default,
{
...blockInformation,
allowParentNavigation: true,
className: isBlockSynced && "is-synced",
isChild: hasParentChildBlockCards,
clientId: renderedBlockClientId,
controls: blockEditingMode === "default" && /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
BlockStatesControl,
{
name: blockName,
value: selectedBlockStyleState2,
onChange: onBlockStyleStateChange
}
)
}
),
blockEditingMode === "default" && isEditingStyleState && /* @__PURE__ */ (0, import_jsx_runtime451.jsxs)(import_components222.__experimentalSpacer, { paddingX: 4, paddingY: 2, children: [
hasPseudoState && /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
import_components222.ToggleControl,
{
label: (0, import_i18n212.__)("Show state on canvas"),
checked: showStateOnCanvas,
onChange: onShowStateOnCanvasChange
}
),
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
BlockStateBadges,
{
name: blockName,
value: selectedBlockStyleState2,
isResponsiveEditing: isResponsiveEditing3
}
)
] }),
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(ViewportVisibilityInfo, { clientId: renderedBlockClientId }),
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(EditContents, { clientId: renderedBlockClientId }),
!isEditingStyleState && /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
block_variation_transforms_default,
{
blockClientId: renderedBlockClientId
}
),
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(BlockInspectorPreTabsSlot, {}),
isEditingStyleState && /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
StyleStateInspectorSlots,
{
blockName,
clientId: renderedBlockClientId,
contentClientIds,
isSectionBlock: isSectionBlock2,
selectedBlockStyleState: selectedBlockStyleState2
}
),
!isEditingStyleState && hasMultipleTabs && /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(import_jsx_runtime451.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
InspectorControlsTabs,
{
hasBlockStyles,
clientId: renderedBlockClientId,
blockName,
tabs: availableTabs,
isSectionBlock: isSectionBlock2,
contentClientIds
}
) }),
!isEditingStyleState && !hasMultipleTabs && /* @__PURE__ */ (0, import_jsx_runtime451.jsxs)(import_jsx_runtime451.Fragment, { children: [
hasBlockStyles && /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(block_styles_default, { clientId: renderedBlockClientId }),
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(content_tab_default, { contentClientIds }),
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(inspector_controls_default.Slot, { group: "content" }),
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(inspector_controls_default.Slot, { group: "list", ref: listViewRef }),
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(ListViewContentPopover, { listViewRef }),
!isSectionBlock2 && /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(StyleInspectorSlots, { blockName })
] }),
!isEditingStyleState && /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(last_item_default.Slot, {}),
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(SkipToSelectedBlock, {}, "back")
] });
};
var block_inspector_default = BlockInspector;
// packages/block-editor/build-module/components/copy-handler/index.mjs
var import_deprecated30 = __toESM(require_deprecated(), 1);
var import_jsx_runtime452 = __toESM(require_jsx_runtime(), 1);
var __unstableUseClipboardHandler = () => {
(0, import_deprecated30.default)("__unstableUseClipboardHandler", {
alternative: "BlockCanvas or WritingFlow",
since: "6.4",
version: "6.7"
});
return useClipboardHandler();
};
function CopyHandler(props) {
(0, import_deprecated30.default)("CopyHandler", {
alternative: "BlockCanvas or WritingFlow",
since: "6.4",
version: "6.7"
});
return /* @__PURE__ */ (0, import_jsx_runtime452.jsx)("div", { ...props, ref: useClipboardHandler() });
}
// packages/block-editor/build-module/components/inserter/library.mjs
var import_data178 = __toESM(require_data(), 1);
var import_element269 = __toESM(require_element(), 1);
var import_jsx_runtime453 = __toESM(require_jsx_runtime(), 1);
var noop22 = () => {
};
function InserterLibrary({
rootClientId,
clientId,
isAppender,
showInserterHelpPanel,
showMostUsedBlocks = false,
__experimentalInsertionIndex,
__experimentalInitialTab,
__experimentalInitialCategory,
__experimentalFilterValue,
onPatternCategorySelection,
onSelect = noop22,
shouldFocusBlock = false,
onClose
}, ref) {
const { destinationRootClientId } = (0, import_data178.useSelect)(
(select3) => {
const { getBlockRootClientId: getBlockRootClientId2 } = select3(store);
const _rootClientId = rootClientId || getBlockRootClientId2(clientId) || void 0;
return {
destinationRootClientId: _rootClientId
};
},
[clientId, rootClientId]
);
return /* @__PURE__ */ (0, import_jsx_runtime453.jsx)(
PrivateInserterMenu,
{
onSelect,
rootClientId: destinationRootClientId,
clientId,
isAppender,
showInserterHelpPanel,
showMostUsedBlocks,
__experimentalInsertionIndex,
__experimentalFilterValue,
onPatternCategorySelection,
__experimentalInitialTab,
__experimentalInitialCategory,
shouldFocusBlock,
ref,
onClose
}
);
}
var PrivateInserterLibrary = (0, import_element269.forwardRef)(InserterLibrary);
function PublicInserterLibrary(props, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime453.jsx)(
PrivateInserterLibrary,
{
...props,
onPatternCategorySelection: void 0,
ref
}
);
}
var library_default = (0, import_element269.forwardRef)(PublicInserterLibrary);
// packages/block-editor/build-module/components/selection-scroll-into-view/index.mjs
var import_deprecated31 = __toESM(require_deprecated(), 1);
function MultiSelectScrollIntoView() {
(0, import_deprecated31.default)("wp.blockEditor.MultiSelectScrollIntoView", {
hint: "This behaviour is now built-in.",
since: "5.8"
});
return null;
}
// packages/block-editor/build-module/components/typewriter/index.mjs
var import_compose95 = __toESM(require_compose(), 1);
var import_dom71 = __toESM(require_dom(), 1);
var import_keycodes28 = __toESM(require_keycodes(), 1);
var import_jsx_runtime454 = __toESM(require_jsx_runtime(), 1);
var isIE = window.navigator.userAgent.indexOf("Trident") !== -1;
var arrowKeyCodes = /* @__PURE__ */ new Set([import_keycodes28.UP, import_keycodes28.DOWN, import_keycodes28.LEFT, import_keycodes28.RIGHT]);
var initialTriggerPercentage = 0.75;
function useTypewriter() {
return (0, import_compose95.useRefEffect)((node) => {
const { ownerDocument: ownerDocument2 } = node;
const { defaultView } = ownerDocument2;
let scrollResizeRafId;
let onKeyDownRafId;
let caretRect;
function onScrollResize() {
if (scrollResizeRafId) {
return;
}
scrollResizeRafId = defaultView.requestAnimationFrame(() => {
computeCaretRectangle();
scrollResizeRafId = null;
});
}
function onKeyDown(event) {
if (onKeyDownRafId) {
defaultView.cancelAnimationFrame(onKeyDownRafId);
}
onKeyDownRafId = defaultView.requestAnimationFrame(() => {
maintainCaretPosition(event);
onKeyDownRafId = null;
});
}
function maintainCaretPosition({ keyCode }) {
if (!isSelectionEligibleForScroll()) {
return;
}
const currentCaretRect = (0, import_dom71.computeCaretRect)(defaultView);
if (!currentCaretRect) {
return;
}
if (!caretRect) {
caretRect = currentCaretRect;
return;
}
if (arrowKeyCodes.has(keyCode)) {
caretRect = currentCaretRect;
return;
}
const diff = currentCaretRect.top - caretRect.top;
if (diff === 0) {
return;
}
const scrollContainer = (0, import_dom71.getScrollContainer)(node);
if (!scrollContainer) {
return;
}
const windowScroll = scrollContainer === ownerDocument2.body || scrollContainer === ownerDocument2.documentElement;
const scrollY = windowScroll ? defaultView.scrollY : scrollContainer.scrollTop;
const scrollContainerY = windowScroll ? 0 : scrollContainer.getBoundingClientRect().top;
const relativeScrollPosition = windowScroll ? caretRect.top / defaultView.innerHeight : (caretRect.top - scrollContainerY) / (defaultView.innerHeight - scrollContainerY);
if (scrollY === 0 && relativeScrollPosition < initialTriggerPercentage && isLastEditableNode()) {
caretRect = currentCaretRect;
return;
}
const scrollContainerHeight = windowScroll ? defaultView.innerHeight : scrollContainer.clientHeight;
if (
// The caret is under the lower fold.
caretRect.top + caretRect.height > scrollContainerY + scrollContainerHeight || // The caret is above the upper fold.
caretRect.top < scrollContainerY
) {
caretRect = currentCaretRect;
return;
}
if (windowScroll) {
defaultView.scrollBy(0, diff);
} else {
scrollContainer.scrollTop += diff;
}
}
function addSelectionChangeListener() {
ownerDocument2.addEventListener(
"selectionchange",
computeCaretRectOnSelectionChange
);
}
function computeCaretRectOnSelectionChange() {
ownerDocument2.removeEventListener(
"selectionchange",
computeCaretRectOnSelectionChange
);
computeCaretRectangle();
}
function computeCaretRectangle() {
if (isSelectionEligibleForScroll()) {
caretRect = (0, import_dom71.computeCaretRect)(defaultView);
}
}
function getActiveEditableElement() {
const { activeElement: activeElement2 } = ownerDocument2;
if (!activeElement2) {
return null;
}
if (!activeElement2.isContentEditable || !activeElement2.contains(node)) {
return activeElement2;
}
const { anchorNode } = defaultView.getSelection();
if (!anchorNode) {
return null;
}
const element = anchorNode.nodeType === anchorNode.ELEMENT_NODE ? anchorNode : anchorNode.parentElement;
return element?.closest('[contenteditable="true"]') ?? null;
}
function isSelectionEligibleForScroll() {
const activeEditableElement = getActiveEditableElement();
return !!activeEditableElement && node.contains(activeEditableElement) && activeEditableElement.isContentEditable;
}
function isLastEditableNode() {
const editableNodes = node.querySelectorAll(
'[contenteditable="true"]'
);
const lastEditableNode = editableNodes[editableNodes.length - 1];
return lastEditableNode === getActiveEditableElement();
}
defaultView.addEventListener("scroll", onScrollResize, true);
defaultView.addEventListener("resize", onScrollResize, true);
node.addEventListener("keydown", onKeyDown);
node.addEventListener("keyup", maintainCaretPosition);
node.addEventListener("mousedown", addSelectionChangeListener);
node.addEventListener("touchstart", addSelectionChangeListener);
return () => {
defaultView.removeEventListener("scroll", onScrollResize, true);
defaultView.removeEventListener("resize", onScrollResize, true);
node.removeEventListener("keydown", onKeyDown);
node.removeEventListener("keyup", maintainCaretPosition);
node.removeEventListener("mousedown", addSelectionChangeListener);
node.removeEventListener(
"touchstart",
addSelectionChangeListener
);
ownerDocument2.removeEventListener(
"selectionchange",
computeCaretRectOnSelectionChange
);
defaultView.cancelAnimationFrame(scrollResizeRafId);
defaultView.cancelAnimationFrame(onKeyDownRafId);
};
}, []);
}
function Typewriter({ children }) {
return /* @__PURE__ */ (0, import_jsx_runtime454.jsx)("div", { ref: useTypewriter(), className: "block-editor__typewriter", children });
}
var TypewriterOrIEBypass = isIE ? (props) => props.children : Typewriter;
var typewriter_default = TypewriterOrIEBypass;
// packages/block-editor/build-module/components/recursion-provider/index.mjs
var import_element270 = __toESM(require_element(), 1);
var import_deprecated32 = __toESM(require_deprecated(), 1);
var import_jsx_runtime455 = __toESM(require_jsx_runtime(), 1);
var RenderedRefsContext = (0, import_element270.createContext)({});
RenderedRefsContext.displayName = "RenderedRefsContext";
function addToBlockType(renderedBlocks, blockName, uniqueId2) {
const result = {
...renderedBlocks,
[blockName]: renderedBlocks[blockName] ? new Set(renderedBlocks[blockName]) : /* @__PURE__ */ new Set()
};
result[blockName].add(uniqueId2);
return result;
}
function RecursionProvider({ children, uniqueId: uniqueId2, blockName = "" }) {
const previouslyRenderedBlocks = (0, import_element270.useContext)(RenderedRefsContext);
const { name } = useBlockEditContext();
blockName = blockName || name;
const newRenderedBlocks = (0, import_element270.useMemo)(
() => addToBlockType(previouslyRenderedBlocks, blockName, uniqueId2),
[previouslyRenderedBlocks, blockName, uniqueId2]
);
return /* @__PURE__ */ (0, import_jsx_runtime455.jsx)(RenderedRefsContext.Provider, { value: newRenderedBlocks, children });
}
function useHasRecursion(uniqueId2, blockName = "") {
const previouslyRenderedBlocks = (0, import_element270.useContext)(RenderedRefsContext);
const { name } = useBlockEditContext();
blockName = blockName || name;
return Boolean(previouslyRenderedBlocks[blockName]?.has(uniqueId2));
}
var DeprecatedExperimentalRecursionProvider = (props) => {
(0, import_deprecated32.default)("wp.blockEditor.__experimentalRecursionProvider", {
since: "6.5",
alternative: "wp.blockEditor.RecursionProvider"
});
return /* @__PURE__ */ (0, import_jsx_runtime455.jsx)(RecursionProvider, { ...props });
};
var DeprecatedExperimentalUseHasRecursion = (...args) => {
(0, import_deprecated32.default)("wp.blockEditor.__experimentalUseHasRecursion", {
since: "6.5",
alternative: "wp.blockEditor.useHasRecursion"
});
return useHasRecursion(...args);
};
// packages/block-editor/build-module/components/publish-date-time-picker/index.mjs
var import_components224 = __toESM(require_components(), 1);
var import_i18n214 = __toESM(require_i18n(), 1);
var import_element271 = __toESM(require_element(), 1);
var import_date2 = __toESM(require_date(), 1);
// packages/block-editor/build-module/components/inspector-popover-header/index.mjs
var import_components223 = __toESM(require_components(), 1);
var import_i18n213 = __toESM(require_i18n(), 1);
var import_jsx_runtime456 = __toESM(require_jsx_runtime(), 1);
function InspectorPopoverHeader({
title,
help,
actions = [],
onClose
}) {
return /* @__PURE__ */ (0, import_jsx_runtime456.jsxs)(import_components223.__experimentalVStack, { className: "block-editor-inspector-popover-header", spacing: 4, children: [
/* @__PURE__ */ (0, import_jsx_runtime456.jsxs)(import_components223.__experimentalHStack, { alignment: "center", children: [
/* @__PURE__ */ (0, import_jsx_runtime456.jsx)(
import_components223.__experimentalHeading,
{
className: "block-editor-inspector-popover-header__heading",
level: 2,
size: 13,
children: title
}
),
/* @__PURE__ */ (0, import_jsx_runtime456.jsx)(import_components223.__experimentalSpacer, {}),
actions.map(({ label, icon, onClick }) => /* @__PURE__ */ (0, import_jsx_runtime456.jsx)(
import_components223.Button,
{
size: "small",
className: "block-editor-inspector-popover-header__action",
label,
icon,
variant: !icon && "tertiary",
onClick,
children: !icon && label
},
label
)),
onClose && /* @__PURE__ */ (0, import_jsx_runtime456.jsx)(
import_components223.Button,
{
size: "small",
className: "block-editor-inspector-popover-header__action",
label: (0, import_i18n213.__)("Close"),
icon: close_small_default,
onClick: onClose
}
)
] }),
help && /* @__PURE__ */ (0, import_jsx_runtime456.jsx)(import_components223.__experimentalText, { children: help })
] });
}
// packages/block-editor/build-module/components/publish-date-time-picker/index.mjs
var import_jsx_runtime457 = __toESM(require_jsx_runtime(), 1);
function PublishDateTimePicker({
onClose,
onChange,
showPopoverHeaderActions,
isCompact,
currentDate,
title,
...additionalProps
}, ref) {
const datePickerProps = {
startOfWeek: (0, import_date2.getSettings)().l10n.startOfWeek,
onChange,
currentDate: isCompact ? void 0 : currentDate,
currentTime: isCompact ? currentDate : void 0,
...additionalProps
};
const DatePickerComponent = isCompact ? import_components224.TimePicker : import_components224.DateTimePicker;
return /* @__PURE__ */ (0, import_jsx_runtime457.jsxs)("div", { ref, className: "block-editor-publish-date-time-picker", children: [
/* @__PURE__ */ (0, import_jsx_runtime457.jsx)(
InspectorPopoverHeader,
{
title: title || (0, import_i18n214.__)("Publish"),
actions: showPopoverHeaderActions ? [
{
label: (0, import_i18n214.__)("Now"),
onClick: () => onChange?.(null)
}
] : void 0,
onClose
}
),
/* @__PURE__ */ (0, import_jsx_runtime457.jsx)(DatePickerComponent, { ...datePickerProps })
] });
}
var PrivatePublishDateTimePicker = (0, import_element271.forwardRef)(PublishDateTimePicker);
function PublicPublishDateTimePicker(props, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime457.jsx)(
PrivatePublishDateTimePicker,
{
...props,
showPopoverHeaderActions: true,
isCompact: false,
ref
}
);
}
var publish_date_time_picker_default = (0, import_element271.forwardRef)(PublicPublishDateTimePicker);
// packages/block-editor/build-module/components/tool-selector/index.mjs
var import_deprecated33 = __toESM(require_deprecated(), 1);
var import_element272 = __toESM(require_element(), 1);
function ToolSelector() {
(0, import_deprecated33.default)("wp.blockEditor.ToolSelector", {
since: "6.9",
hint: "The ToolSelector component no longer renders anything."
});
return null;
}
var tool_selector_default = (0, import_element272.forwardRef)(ToolSelector);
// packages/block-editor/build-module/hooks/utils.mjs
var import_jsx_runtime458 = __toESM(require_jsx_runtime(), 1);
var cleanEmptyObject = (object) => {
if (object === null || typeof object !== "object" || Array.isArray(object)) {
return object;
}
const cleanedNestedObjects = Object.entries(object).map(([key, value]) => [key, cleanEmptyObject(value)]).filter(([, value]) => value !== void 0);
return !cleanedNestedObjects.length ? void 0 : Object.fromEntries(cleanedNestedObjects);
};
function transformStyles2(activeSupports, migrationPaths, result, source, index2, results) {
if (Object.values(activeSupports ?? {}).every(
(isActive) => !isActive
)) {
return result;
}
if (results.length === 1 && result.innerBlocks.length === source.length) {
return result;
}
let referenceBlockAttributes = source[0]?.attributes;
if (results.length > 1 && source.length > 1) {
if (source[index2]) {
referenceBlockAttributes = source[index2]?.attributes;
} else {
return result;
}
}
let returnBlock = result;
Object.entries(activeSupports).forEach(([support, isActive]) => {
if (isActive) {
migrationPaths[support].forEach((path) => {
const styleValue = getValueFromObjectPath2(
referenceBlockAttributes,
path
);
if (styleValue) {
returnBlock = {
...returnBlock,
attributes: setImmutably2(
returnBlock.attributes,
path,
styleValue
)
};
}
});
}
});
return returnBlock;
}
function shouldSkipSerialization(blockNameOrType, featureSet, feature) {
const support = (0, import_blocks104.getBlockSupport)(blockNameOrType, featureSet);
const skipSerialization = support?.__experimentalSkipSerialization;
if (Array.isArray(skipSerialization)) {
return skipSerialization.includes(feature);
}
return skipSerialization;
}
var pendingStyleOverrides = /* @__PURE__ */ new WeakMap();
function useStyleOverride({ id, css }) {
return usePrivateStyleOverride({ id, css });
}
function usePrivateStyleOverride({
id,
css,
assets,
__unstableType,
variation,
clientId
} = {}) {
const { setStyleOverride: setStyleOverride2, deleteStyleOverride: deleteStyleOverride2 } = unlock(
(0, import_data179.useDispatch)(store)
);
const registry = (0, import_data179.useRegistry)();
const fallbackId = (0, import_element273.useId)();
(0, import_element273.useEffect)(() => {
if (!css && !assets) {
return;
}
const _id = id || fallbackId;
const override = {
id,
css,
assets,
__unstableType,
variation,
clientId
};
if (!pendingStyleOverrides.get(registry)) {
pendingStyleOverrides.set(registry, []);
}
pendingStyleOverrides.get(registry).push([_id, override]);
window.queueMicrotask(() => {
if (pendingStyleOverrides.get(registry)?.length) {
registry.batch(() => {
pendingStyleOverrides.get(registry).forEach((args) => {
setStyleOverride2(...args);
});
pendingStyleOverrides.set(registry, []);
});
}
});
return () => {
const isPending = pendingStyleOverrides.get(registry)?.find(([currentId]) => currentId === _id);
if (isPending) {
pendingStyleOverrides.set(
registry,
pendingStyleOverrides.get(registry).filter(([currentId]) => currentId !== _id)
);
} else {
deleteStyleOverride2(_id);
}
};
}, [
id,
css,
clientId,
assets,
__unstableType,
fallbackId,
setStyleOverride2,
deleteStyleOverride2,
registry,
variation
]);
}
function useBlockSettings(name, parentLayout) {
const [
backgroundImage,
backgroundSize,
gradient,
customFontFamilies,
defaultFontFamilies,
themeFontFamilies,
defaultFontSizesEnabled,
customFontSizes,
defaultFontSizes,
themeFontSizes,
customFontSize,
fontStyle,
fontWeight,
lineHeight,
textAlign,
textColumns,
textDecoration,
textIndent,
writingMode,
textTransform,
letterSpacing,
padding,
margin,
blockGap,
defaultSpacingSizesEnabled,
customSpacingSize,
userSpacingSizes,
defaultSpacingSizes,
themeSpacingSizes,
units2,
aspectRatio,
height,
minHeight,
minWidth,
width,
dimensionSizes,
layout,
borderColor,
borderRadius,
borderStyle,
borderWidth,
borderRadiusSizes,
customColorsEnabled,
customColors,
customDuotone,
themeColors,
defaultColors,
defaultPalette,
defaultDuotone,
userDuotonePalette,
themeDuotonePalette,
defaultDuotonePalette,
userGradientPalette,
themeGradientPalette,
defaultGradientPalette,
defaultGradients,
areCustomGradientsEnabled,
isBackgroundEnabled,
isLinkEnabled,
isTextEnabled,
isHeadingEnabled,
isButtonEnabled,
shadow
] = useSettings(
"background.backgroundImage",
"background.backgroundSize",
"background.gradient",
"typography.fontFamilies.custom",
"typography.fontFamilies.default",
"typography.fontFamilies.theme",
"typography.defaultFontSizes",
"typography.fontSizes.custom",
"typography.fontSizes.default",
"typography.fontSizes.theme",
"typography.customFontSize",
"typography.fontStyle",
"typography.fontWeight",
"typography.lineHeight",
"typography.textAlign",
"typography.textColumns",
"typography.textDecoration",
"typography.textIndent",
"typography.writingMode",
"typography.textTransform",
"typography.letterSpacing",
"spacing.padding",
"spacing.margin",
"spacing.blockGap",
"spacing.defaultSpacingSizes",
"spacing.customSpacingSize",
"spacing.spacingSizes.custom",
"spacing.spacingSizes.default",
"spacing.spacingSizes.theme",
"spacing.units",
"dimensions.aspectRatio",
"dimensions.height",
"dimensions.minHeight",
"dimensions.minWidth",
"dimensions.width",
"dimensions.dimensionSizes",
"layout",
"border.color",
"border.radius",
"border.style",
"border.width",
"border.radiusSizes",
"color.custom",
"color.palette.custom",
"color.customDuotone",
"color.palette.theme",
"color.palette.default",
"color.defaultPalette",
"color.defaultDuotone",
"color.duotone.custom",
"color.duotone.theme",
"color.duotone.default",
"color.gradients.custom",
"color.gradients.theme",
"color.gradients.default",
"color.defaultGradients",
"color.customGradient",
"color.background",
"color.link",
"color.text",
"color.heading",
"color.button",
"shadow"
);
const rawSettings = (0, import_element273.useMemo)(() => {
return {
background: {
backgroundImage,
backgroundSize,
gradient
},
color: {
palette: {
custom: customColors,
theme: themeColors,
default: defaultColors
},
gradients: {
custom: userGradientPalette,
theme: themeGradientPalette,
default: defaultGradientPalette
},
duotone: {
custom: userDuotonePalette,
theme: themeDuotonePalette,
default: defaultDuotonePalette
},
defaultGradients,
defaultPalette,
defaultDuotone,
custom: customColorsEnabled,
customGradient: areCustomGradientsEnabled,
customDuotone,
background: isBackgroundEnabled,
link: isLinkEnabled,
heading: isHeadingEnabled,
button: isButtonEnabled,
text: isTextEnabled
},
typography: {
fontFamilies: {
custom: customFontFamilies,
default: defaultFontFamilies,
theme: themeFontFamilies
},
fontSizes: {
custom: customFontSizes,
default: defaultFontSizes,
theme: themeFontSizes
},
customFontSize,
defaultFontSizes: defaultFontSizesEnabled,
fontStyle,
fontWeight,
lineHeight,
textAlign,
textColumns,
textDecoration,
textIndent,
textTransform,
letterSpacing,
writingMode
},
spacing: {
spacingSizes: {
custom: userSpacingSizes,
default: defaultSpacingSizes,
theme: themeSpacingSizes
},
customSpacingSize,
defaultSpacingSizes: defaultSpacingSizesEnabled,
padding,
margin,
blockGap,
units: units2
},
border: {
color: borderColor,
radius: borderRadius,
style: borderStyle,
width: borderWidth,
radiusSizes: borderRadiusSizes
},
dimensions: {
aspectRatio,
height,
minHeight,
minWidth,
width,
dimensionSizes
},
layout,
parentLayout,
shadow
};
}, [
backgroundImage,
backgroundSize,
gradient,
customFontFamilies,
defaultFontFamilies,
themeFontFamilies,
defaultFontSizesEnabled,
customFontSizes,
defaultFontSizes,
themeFontSizes,
customFontSize,
fontStyle,
fontWeight,
lineHeight,
textAlign,
textColumns,
textDecoration,
textIndent,
textTransform,
letterSpacing,
writingMode,
padding,
margin,
blockGap,
defaultSpacingSizesEnabled,
customSpacingSize,
userSpacingSizes,
defaultSpacingSizes,
themeSpacingSizes,
units2,
aspectRatio,
height,
minHeight,
minWidth,
width,
dimensionSizes,
layout,
parentLayout,
borderColor,
borderRadius,
borderStyle,
borderWidth,
borderRadiusSizes,
customColorsEnabled,
customColors,
customDuotone,
themeColors,
defaultColors,
defaultPalette,
defaultDuotone,
userDuotonePalette,
themeDuotonePalette,
defaultDuotonePalette,
userGradientPalette,
themeGradientPalette,
defaultGradientPalette,
defaultGradients,
areCustomGradientsEnabled,
isBackgroundEnabled,
isLinkEnabled,
isTextEnabled,
isHeadingEnabled,
isButtonEnabled,
shadow
]);
return useSettingsForBlockElement(rawSettings, name);
}
function createBlockEditFilter(features) {
features = features.map((settings2) => {
return { ...settings2, Edit: (0, import_element273.memo)(settings2.edit) };
});
const withBlockEditHooks = (0, import_compose96.createHigherOrderComponent)(
(OriginalBlockEdit) => function WithBlockEditHooks(props) {
const context = useBlockEditContext();
return [
...features.map((feature, i2) => {
const {
Edit: Edit5,
hasSupport,
attributeKeys = [],
shareWithChildBlocks,
supportsPatternEditing
} = feature;
const shouldDisplayControls = supportsPatternEditing && context[mayDisplayPatternEditingControlsKey] || context[mayDisplayControlsKey] || context[mayDisplayParentControlsKey] && shareWithChildBlocks;
if (!shouldDisplayControls || !hasSupport(props.name)) {
return null;
}
const neededProps = {};
for (const key of attributeKeys) {
if (props.attributes[key]) {
neededProps[key] = props.attributes[key];
}
}
return /* @__PURE__ */ (0, import_jsx_runtime458.jsx)(
Edit5,
{
name: props.name,
isSelected: props.isSelected,
clientId: props.clientId,
setAttributes: props.setAttributes,
__unstableParentLayout: props.__unstableParentLayout,
...neededProps
},
i2
);
}),
/* @__PURE__ */ (0, import_jsx_runtime458.jsx)(OriginalBlockEdit, { ...props }, "edit")
];
},
"withBlockEditHooks"
);
(0, import_hooks18.addFilter)("editor.BlockEdit", "core/editor/hooks", withBlockEditHooks);
}
function BlockProps({
index: index2,
useBlockProps: hook,
setAllWrapperProps,
...props
}) {
const wrapperProps = hook(props);
const setWrapperProps = (next) => setAllWrapperProps((prev) => {
const nextAll = [...prev];
nextAll[index2] = next;
return nextAll;
});
(0, import_element273.useEffect)(() => {
setWrapperProps(wrapperProps);
return () => {
setWrapperProps(void 0);
};
});
return null;
}
var BlockPropsPure = (0, import_element273.memo)(BlockProps);
function createBlockListBlockFilter(features) {
const withBlockListBlockHooks = (0, import_compose96.createHigherOrderComponent)(
(BlockListBlock2) => function WithBlockListBlockHooks(props) {
const [allWrapperProps, setAllWrapperProps] = (0, import_element273.useState)(
Array(features.length).fill(void 0)
);
return [
...features.map((feature, i2) => {
const {
hasSupport,
attributeKeys = [],
useBlockProps: useBlockProps16,
isMatch
} = feature;
const neededProps = {};
for (const key of attributeKeys) {
if (props.attributes[key]) {
neededProps[key] = props.attributes[key];
}
}
if (
// Skip rendering if none of the needed attributes are
// set.
!Object.keys(neededProps).length || !hasSupport(props.name) || isMatch && !isMatch(neededProps)
) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime458.jsx)(
BlockPropsPure,
{
index: i2,
useBlockProps: useBlockProps16,
setAllWrapperProps,
name: props.name,
clientId: props.clientId,
...neededProps
},
i2
);
}),
/* @__PURE__ */ (0, import_jsx_runtime458.jsx)(
BlockListBlock2,
{
...props,
wrapperProps: allWrapperProps.filter(Boolean).reduce((acc, wrapperProps) => {
return {
...acc,
...wrapperProps,
className: clsx_default(
acc.className,
wrapperProps.className
),
style: {
...acc.style,
...wrapperProps.style
}
};
}, props.wrapperProps || {})
},
"edit"
)
];
},
"withBlockListBlockHooks"
);
(0, import_hooks18.addFilter)(
"editor.BlockListBlock",
"core/editor/hooks",
withBlockListBlockHooks
);
}
function createBlockSaveFilter(features) {
function extraPropsFromHooks(props, name, attributes) {
return features.reduce((accu, feature) => {
const { hasSupport, attributeKeys = [], addSaveProps: addSaveProps11 } = feature;
const neededAttributes = {};
for (const key of attributeKeys) {
if (attributes[key]) {
neededAttributes[key] = attributes[key];
}
}
if (
// Skip rendering if none of the needed attributes are
// set.
!Object.keys(neededAttributes).length || !hasSupport(name)
) {
return accu;
}
return addSaveProps11(accu, name, neededAttributes);
}, props);
}
(0, import_hooks18.addFilter)(
"blocks.getSaveContent.extraProps",
"core/editor/hooks",
extraPropsFromHooks,
0
);
(0, import_hooks18.addFilter)(
"blocks.getSaveContent.extraProps",
"core/editor/hooks",
(props) => {
if (props.hasOwnProperty("className") && !props.className) {
delete props.className;
}
return props;
}
);
}
// packages/block-editor/build-module/hooks/compat.mjs
var import_blocks105 = __toESM(require_blocks(), 1);
var import_hooks20 = __toESM(require_hooks(), 1);
function migrateLightBlockWrapper(settings2) {
const { apiVersion = 1 } = settings2;
if (apiVersion < 2 && (0, import_blocks105.hasBlockSupport)(settings2, "lightBlockWrapper", false)) {
settings2.apiVersion = 2;
}
return settings2;
}
(0, import_hooks20.addFilter)(
"blocks.registerBlockType",
"core/compat/migrateLightBlockWrapper",
migrateLightBlockWrapper
);
// packages/block-editor/build-module/hooks/cross-origin-isolation.mjs
function addCrossOriginAttribute(el) {
if (!el.hasAttribute("crossorigin")) {
el.setAttribute("crossorigin", "anonymous");
}
}
if (window.crossOriginIsolated) {
let startObservingBody = function() {
if (document.body) {
observer.observe(document.body, {
childList: true,
attributes: true,
subtree: true
});
} else if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", () => {
if (document.body) {
observer.observe(document.body, {
childList: true,
attributes: true,
subtree: true
});
}
});
}
};
startObservingBody2 = startObservingBody;
const observer = new window.MutationObserver((mutations) => {
mutations.forEach((mutation) => {
[mutation.addedNodes, mutation.target].forEach((value) => {
const nodes = value instanceof window.NodeList ? value : [value];
nodes.forEach((node) => {
const el = node;
if (!el.querySelectorAll) {
return;
}
el.querySelectorAll("source,script,video,link").forEach(
(v2) => {
addCrossOriginAttribute(v2);
}
);
if (["SOURCE", "SCRIPT", "VIDEO", "LINK"].includes(
el.nodeName
)) {
addCrossOriginAttribute(el);
}
});
});
});
});
startObservingBody();
}
var startObservingBody2;
// packages/block-editor/build-module/hooks/align.mjs
var import_hooks21 = __toESM(require_hooks(), 1);
var import_blocks106 = __toESM(require_blocks(), 1);
var import_jsx_runtime459 = __toESM(require_jsx_runtime(), 1);
var ALL_ALIGNMENTS = ["left", "center", "right", "wide", "full"];
var WIDE_ALIGNMENTS = ["wide", "full"];
function getValidAlignments(blockAlign, hasWideBlockSupport = true, hasWideEnabled = true) {
let validAlignments;
if (Array.isArray(blockAlign)) {
validAlignments = ALL_ALIGNMENTS.filter(
(value) => blockAlign.includes(value)
);
} else if (blockAlign === true) {
validAlignments = [...ALL_ALIGNMENTS];
} else {
validAlignments = [];
}
if (!hasWideEnabled || blockAlign === true && !hasWideBlockSupport) {
return validAlignments.filter(
(alignment) => !WIDE_ALIGNMENTS.includes(alignment)
);
}
return validAlignments;
}
function addAttribute(settings2) {
if ("type" in (settings2.attributes?.align ?? {})) {
return settings2;
}
if ((0, import_blocks106.hasBlockSupport)(settings2, "align")) {
settings2.attributes = {
...settings2.attributes,
align: {
type: "string",
// Allow for '' since it is used by the `updateAlignment` function
// in toolbar controls for special cases with defined default values.
enum: [...ALL_ALIGNMENTS, ""]
}
};
}
return settings2;
}
function BlockEditAlignmentToolbarControlsPure({
name: blockName,
align,
setAttributes
}) {
const blockAllowedAlignments = getValidAlignments(
(0, import_blocks106.getBlockSupport)(blockName, "align"),
(0, import_blocks106.hasBlockSupport)(blockName, "alignWide", true)
);
const validAlignments = useAvailableAlignments(
blockAllowedAlignments
).map(({ name }) => name);
const blockEditingMode = useBlockEditingMode();
if (!validAlignments.length || blockEditingMode !== "default") {
return null;
}
const updateAlignment = (nextAlign) => {
if (!nextAlign) {
const blockType = (0, import_blocks106.getBlockType)(blockName);
const blockDefaultAlign = blockType?.attributes?.align?.default;
if (blockDefaultAlign) {
nextAlign = "";
}
}
setAttributes({ align: nextAlign });
};
return /* @__PURE__ */ (0, import_jsx_runtime459.jsx)(block_controls_default, { group: "block", __experimentalShareWithChildBlocks: true, children: /* @__PURE__ */ (0, import_jsx_runtime459.jsx)(
BlockAlignmentControl,
{
value: align,
onChange: updateAlignment,
controls: validAlignments
}
) });
}
var align_default = {
shareWithChildBlocks: true,
edit: BlockEditAlignmentToolbarControlsPure,
useBlockProps: useBlockProps11,
addSaveProps: addAssignedAlign,
attributeKeys: ["align"],
hasSupport(name) {
return (0, import_blocks106.hasBlockSupport)(name, "align", false);
}
};
function useBlockProps11({ name, align }) {
const blockAllowedAlignments = getValidAlignments(
(0, import_blocks106.getBlockSupport)(name, "align"),
(0, import_blocks106.hasBlockSupport)(name, "alignWide", true)
);
const validAlignments = useAvailableAlignments(blockAllowedAlignments);
if (validAlignments.some((alignment) => alignment.name === align)) {
return { "data-align": align };
}
return {};
}
function addAssignedAlign(props, blockType, attributes) {
const { align } = attributes;
const blockAlign = (0, import_blocks106.getBlockSupport)(blockType, "align");
const hasWideBlockSupport = (0, import_blocks106.hasBlockSupport)(blockType, "alignWide", true);
const isAlignValid = getValidAlignments(
blockAlign,
hasWideBlockSupport
).includes(align);
if (isAlignValid) {
props.className = clsx_default(`align${align}`, props.className);
}
return props;
}
(0, import_hooks21.addFilter)(
"blocks.registerBlockType",
"core/editor/align/addAttribute",
addAttribute
);
// packages/block-editor/build-module/hooks/lock.mjs
var import_hooks22 = __toESM(require_hooks(), 1);
function addAttribute2(settings2) {
if ("type" in (settings2.attributes?.lock ?? {})) {
return settings2;
}
settings2.attributes = {
...settings2.attributes,
lock: {
type: "object"
}
};
return settings2;
}
(0, import_hooks22.addFilter)("blocks.registerBlockType", "core/lock/addAttribute", addAttribute2);
// packages/block-editor/build-module/hooks/allowed-blocks.mjs
var import_hooks23 = __toESM(require_hooks(), 1);
var import_blocks109 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/components/block-allowed-blocks/allowed-blocks-control.mjs
var import_components231 = __toESM(require_components(), 1);
var import_i18n217 = __toESM(require_i18n(), 1);
var import_element277 = __toESM(require_element(), 1);
var import_data182 = __toESM(require_data(), 1);
var import_blocks108 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/components/block-allowed-blocks/modal.mjs
var import_components230 = __toESM(require_components(), 1);
var import_element276 = __toESM(require_element(), 1);
var import_i18n216 = __toESM(require_i18n(), 1);
var import_data181 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/block-manager/index.mjs
var import_blocks107 = __toESM(require_blocks(), 1);
var import_data180 = __toESM(require_data(), 1);
var import_components229 = __toESM(require_components(), 1);
var import_i18n215 = __toESM(require_i18n(), 1);
var import_element275 = __toESM(require_element(), 1);
var import_compose98 = __toESM(require_compose(), 1);
var import_a11y21 = __toESM(require_a11y(), 1);
// packages/block-editor/build-module/components/block-manager/category.mjs
var import_element274 = __toESM(require_element(), 1);
var import_compose97 = __toESM(require_compose(), 1);
var import_components228 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/block-manager/checklist.mjs
var import_components227 = __toESM(require_components(), 1);
var import_jsx_runtime460 = __toESM(require_jsx_runtime(), 1);
function BlockTypesChecklist({ blockTypes, value, onItemChange }) {
return /* @__PURE__ */ (0, import_jsx_runtime460.jsx)("ul", { className: "block-editor-block-manager__checklist", children: blockTypes.map((blockType) => /* @__PURE__ */ (0, import_jsx_runtime460.jsxs)(
"li",
{
className: "block-editor-block-manager__checklist-item",
children: [
/* @__PURE__ */ (0, import_jsx_runtime460.jsx)(
import_components227.CheckboxControl,
{
label: blockType.title,
checked: value.includes(blockType.name),
onChange: (...args) => onItemChange(blockType, ...args)
}
),
/* @__PURE__ */ (0, import_jsx_runtime460.jsx)(block_icon_default, { icon: blockType.icon })
]
},
blockType.name
)) });
}
var checklist_default = BlockTypesChecklist;
// packages/block-editor/build-module/components/block-manager/category.mjs
var import_jsx_runtime461 = __toESM(require_jsx_runtime(), 1);
function BlockManagerCategory({
title,
blockTypes,
selectedBlockTypes,
onChange
}) {
const instanceId = (0, import_compose97.useInstanceId)(BlockManagerCategory);
const toggleVisible = (0, import_element274.useCallback)(
(blockType, nextIsChecked) => {
if (nextIsChecked) {
onChange([...selectedBlockTypes, blockType]);
} else {
onChange(
selectedBlockTypes.filter(
({ name }) => name !== blockType.name
)
);
}
},
[selectedBlockTypes, onChange]
);
const toggleAllVisible = (0, import_element274.useCallback)(
(nextIsChecked) => {
if (nextIsChecked) {
onChange([
...selectedBlockTypes,
...blockTypes.filter(
(blockType) => !selectedBlockTypes.find(
({ name }) => name === blockType.name
)
)
]);
} else {
onChange(
selectedBlockTypes.filter(
(selectedBlockType) => !blockTypes.find(
({ name }) => name === selectedBlockType.name
)
)
);
}
},
[blockTypes, selectedBlockTypes, onChange]
);
if (!blockTypes.length) {
return null;
}
const checkedBlockNames = blockTypes.map(({ name }) => name).filter(
(type) => (selectedBlockTypes ?? []).some(
(selectedBlockType) => selectedBlockType.name === type
)
);
const titleId = "block-editor-block-manager__category-title-" + instanceId;
const isAllChecked = checkedBlockNames.length === blockTypes.length;
const isIndeterminate = !isAllChecked && checkedBlockNames.length > 0;
return /* @__PURE__ */ (0, import_jsx_runtime461.jsxs)(
"div",
{
role: "group",
"aria-labelledby": titleId,
className: "block-editor-block-manager__category",
children: [
/* @__PURE__ */ (0, import_jsx_runtime461.jsx)(
import_components228.CheckboxControl,
{
checked: isAllChecked,
onChange: toggleAllVisible,
className: "block-editor-block-manager__category-title",
indeterminate: isIndeterminate,
label: /* @__PURE__ */ (0, import_jsx_runtime461.jsx)("span", { id: titleId, children: title })
}
),
/* @__PURE__ */ (0, import_jsx_runtime461.jsx)(
checklist_default,
{
blockTypes,
value: checkedBlockNames,
onItemChange: toggleVisible
}
)
]
}
);
}
var category_default2 = BlockManagerCategory;
// packages/block-editor/build-module/components/block-manager/index.mjs
var import_jsx_runtime462 = __toESM(require_jsx_runtime(), 1);
function BlockManager({
blockTypes,
selectedBlockTypes,
onChange,
showSelectAll = true
}) {
const debouncedSpeak = (0, import_compose98.useDebounce)(import_a11y21.speak, 500);
const [search, setSearch] = (0, import_element275.useState)("");
const { categories, isMatchingSearchTerm } = (0, import_data180.useSelect)((select3) => {
return {
categories: select3(import_blocks107.store).getCategories(),
isMatchingSearchTerm: select3(import_blocks107.store).isMatchingSearchTerm
};
}, []);
const filteredBlockTypes = blockTypes.filter((blockType) => {
return !search || isMatchingSearchTerm(blockType, search);
});
const isIndeterminate = selectedBlockTypes.length > 0 && selectedBlockTypes.length !== blockTypes.length;
const isAllChecked = blockTypes.length > 0 && selectedBlockTypes.length === blockTypes.length;
(0, import_element275.useEffect)(() => {
if (!search) {
return;
}
const count = filteredBlockTypes.length;
const resultsFoundMessage = (0, import_i18n215.sprintf)(
/* translators: %d: number of results. */
(0, import_i18n215._n)("%d result found.", "%d results found.", count),
count
);
debouncedSpeak(resultsFoundMessage);
}, [filteredBlockTypes?.length, search, debouncedSpeak]);
return /* @__PURE__ */ (0, import_jsx_runtime462.jsxs)(import_components229.__experimentalVStack, { className: "block-editor-block-manager__content", spacing: 4, children: [
/* @__PURE__ */ (0, import_jsx_runtime462.jsx)(
import_components229.SearchControl,
{
label: (0, import_i18n215.__)("Search for a block"),
placeholder: (0, import_i18n215.__)("Search for a block"),
value: search,
onChange: (nextSearch) => setSearch(nextSearch),
className: "block-editor-block-manager__search"
}
),
showSelectAll && /* @__PURE__ */ (0, import_jsx_runtime462.jsx)(
import_components229.CheckboxControl,
{
className: "block-editor-block-manager__select-all",
label: (0, import_i18n215.__)("Select all"),
checked: isAllChecked,
onChange: () => {
if (isAllChecked) {
onChange([]);
} else {
onChange(blockTypes);
}
},
indeterminate: isIndeterminate
}
),
/* @__PURE__ */ (0, import_jsx_runtime462.jsxs)(
"div",
{
tabIndex: "0",
role: "region",
"aria-label": (0, import_i18n215.__)("Available block types"),
className: "block-editor-block-manager__results",
children: [
filteredBlockTypes.length === 0 && /* @__PURE__ */ (0, import_jsx_runtime462.jsx)("p", { className: "block-editor-block-manager__no-results", children: (0, import_i18n215.__)("No blocks found.") }),
categories.map((category) => /* @__PURE__ */ (0, import_jsx_runtime462.jsx)(
category_default2,
{
title: category.title,
blockTypes: filteredBlockTypes.filter(
(blockType) => blockType.category === category.slug
),
selectedBlockTypes,
onChange
},
category.slug
)),
/* @__PURE__ */ (0, import_jsx_runtime462.jsx)(
category_default2,
{
title: (0, import_i18n215.__)("Uncategorized"),
blockTypes: filteredBlockTypes.filter(
({ category }) => !category
),
selectedBlockTypes,
onChange
}
)
]
}
)
] });
}
// packages/block-editor/build-module/components/block-allowed-blocks/modal.mjs
var import_jsx_runtime463 = __toESM(require_jsx_runtime(), 1);
function BlockAllowedBlocksModal({
clientId,
blockTypes,
selectedBlockTypes,
onClose
}) {
const [currentSelectedBlockTypes, setCurrentSelectedBlockTypes] = (0, import_element276.useState)(selectedBlockTypes);
const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data181.useDispatch)(store);
const handleSubmit = () => {
const isFullySelected = currentSelectedBlockTypes.length === blockTypes.length;
const newBlockNames = currentSelectedBlockTypes.map(
({ name }) => name
);
updateBlockAttributes2(clientId, {
allowedBlocks: isFullySelected ? void 0 : newBlockNames
});
onClose();
};
return /* @__PURE__ */ (0, import_jsx_runtime463.jsx)(
import_components230.Modal,
{
title: (0, import_i18n216._x)("Manage allowed blocks", "modal title"),
onRequestClose: onClose,
overlayClassName: "block-editor-block-allowed-blocks-modal",
focusOnMount: "firstContentElement",
size: "medium",
children: /* @__PURE__ */ (0, import_jsx_runtime463.jsxs)(
import_components230.__experimentalVStack,
{
as: "form",
onSubmit: (e2) => {
e2.preventDefault();
handleSubmit();
},
spacing: "4",
children: [
/* @__PURE__ */ (0, import_jsx_runtime463.jsx)(import_components230.__experimentalText, { children: (0, import_i18n216.__)(
"Select which blocks can be added inside this container."
) }),
/* @__PURE__ */ (0, import_jsx_runtime463.jsx)(
BlockManager,
{
blockTypes,
selectedBlockTypes: currentSelectedBlockTypes,
onChange: (newSelectedBlockTypes) => {
setCurrentSelectedBlockTypes(newSelectedBlockTypes);
}
}
),
/* @__PURE__ */ (0, import_jsx_runtime463.jsxs)(
import_components230.Flex,
{
className: "block-editor-block-allowed-blocks-modal__actions",
justify: "flex-end",
expanded: false,
children: [
/* @__PURE__ */ (0, import_jsx_runtime463.jsx)(import_components230.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime463.jsx)(
import_components230.Button,
{
variant: "tertiary",
onClick: onClose,
__next40pxDefaultSize: true,
children: (0, import_i18n216.__)("Cancel")
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime463.jsx)(import_components230.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime463.jsx)(
import_components230.Button,
{
variant: "primary",
type: "submit",
__next40pxDefaultSize: true,
children: (0, import_i18n216.__)("Apply")
}
) })
]
}
)
]
}
)
}
);
}
// packages/block-editor/build-module/components/block-allowed-blocks/allowed-blocks-control.mjs
var import_jsx_runtime464 = __toESM(require_jsx_runtime(), 1);
function BlockAllowedBlocksControl({ clientId }) {
const [isBlockControlOpened, setIsBlockControlOpened] = (0, import_element277.useState)(false);
const { blockTypes, selectedBlockNames } = (0, import_data182.useSelect)(
(select3) => {
const { getBlockAttributes: getBlockAttributes3 } = select3(store);
return {
blockTypes: select3(import_blocks108.store).getBlockTypes(),
selectedBlockNames: getBlockAttributes3(clientId)?.allowedBlocks
};
},
[clientId]
);
const filteredBlockTypes = blockTypes.filter(
(blockType) => (0, import_blocks108.hasBlockSupport)(blockType, "inserter", true) && (!blockType.parent || blockType.parent.includes("core/post-content"))
);
if (!filteredBlockTypes) {
return null;
}
const selectedBlockTypes = selectedBlockNames === void 0 ? filteredBlockTypes : filteredBlockTypes.filter(
(blockType) => selectedBlockNames.includes(blockType.name)
);
return /* @__PURE__ */ (0, import_jsx_runtime464.jsxs)("div", { className: "block-editor-block-allowed-blocks-control", children: [
/* @__PURE__ */ (0, import_jsx_runtime464.jsxs)(
import_components231.BaseControl,
{
help: (0, import_i18n217.__)(
"Specify which blocks are allowed inside this container."
),
children: [
/* @__PURE__ */ (0, import_jsx_runtime464.jsx)(import_components231.BaseControl.VisualLabel, { children: (0, import_i18n217.__)("Allowed Blocks") }),
/* @__PURE__ */ (0, import_jsx_runtime464.jsx)(
import_components231.Button,
{
__next40pxDefaultSize: true,
variant: "secondary",
onClick: () => {
setIsBlockControlOpened(true);
},
className: "block-editor-block-allowed-blocks-control__button",
children: (0, import_i18n217.__)("Manage allowed blocks")
}
)
]
}
),
isBlockControlOpened && /* @__PURE__ */ (0, import_jsx_runtime464.jsx)(
BlockAllowedBlocksModal,
{
clientId,
blockTypes: filteredBlockTypes,
selectedBlockTypes,
onClose: () => setIsBlockControlOpened(false)
}
)
] });
}
// packages/block-editor/build-module/hooks/allowed-blocks.mjs
var import_jsx_runtime465 = __toESM(require_jsx_runtime(), 1);
function BlockEditAllowedBlocksControlPure({ clientId }) {
const blockEditingMode = useBlockEditingMode();
const isContentOnly = blockEditingMode === "contentOnly";
if (isContentOnly) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime465.jsx)(PrivateInspectorControlsAllowedBlocks.Fill, { children: /* @__PURE__ */ (0, import_jsx_runtime465.jsx)(BlockAllowedBlocksControl, { clientId }) });
}
var allowed_blocks_default = {
edit: BlockEditAllowedBlocksControlPure,
attributeKeys: ["allowedBlocks"],
hasSupport(name) {
return (0, import_blocks109.hasBlockSupport)(name, "allowedBlocks");
}
};
function addAttribute3(settings2) {
if (settings2?.attributes?.allowedBlocks?.type) {
return settings2;
}
if ((0, import_blocks109.hasBlockSupport)(settings2, "allowedBlocks")) {
settings2.attributes = {
...settings2.attributes,
allowedBlocks: {
type: "array"
}
};
}
return settings2;
}
(0, import_hooks23.addFilter)(
"blocks.registerBlockType",
"core/allowedBlocks/attribute",
addAttribute3
);
function addTransforms3(result, source, index2, results) {
if (!(0, import_blocks109.hasBlockSupport)(result.name, "allowedBlocks")) {
return result;
}
if (source.length !== 1 && results.length === 1 && result.innerBlocks.length === source.length) {
return result;
}
if (results.length === 1 && source.length > 1 || results.length > 1 && source.length === 1) {
return result;
}
if (results.length > 1 && source.length > 1 && results.length !== source.length) {
return result;
}
if (result.attributes.allowedBlocks) {
return result;
}
const sourceAllowedBlocks = source[index2]?.attributes?.allowedBlocks;
if (!sourceAllowedBlocks) {
return result;
}
const blockType = (0, import_blocks109.getBlockType)(result.name);
const destinationAllowedBlocks = blockType?.allowedBlocks || [];
if (!destinationAllowedBlocks.length) {
return {
...result,
attributes: {
...result.attributes,
allowedBlocks: sourceAllowedBlocks
}
};
}
const filteredSourceAllowedBlocks = sourceAllowedBlocks.filter(
(block) => destinationAllowedBlocks.includes(block)
);
return {
...result,
attributes: {
...result.attributes,
allowedBlocks: filteredSourceAllowedBlocks
}
};
}
(0, import_hooks23.addFilter)(
"blocks.switchToBlockType.transformedBlock",
"core/allowedBlocks/addTransforms",
addTransforms3
);
// packages/block-editor/build-module/hooks/anchor.mjs
var import_hooks24 = __toESM(require_hooks(), 1);
var import_components232 = __toESM(require_components(), 1);
var import_i18n218 = __toESM(require_i18n(), 1);
var import_blocks110 = __toESM(require_blocks(), 1);
var import_jsx_runtime466 = __toESM(require_jsx_runtime(), 1);
var ANCHOR_REGEX = /[\s#]/g;
function addAttribute4(settings2) {
if ("type" in (settings2.attributes?.anchor ?? {})) {
return settings2;
}
if ((0, import_blocks110.hasBlockSupport)(settings2, "anchor")) {
settings2.attributes = {
...settings2.attributes,
anchor: {
type: "string"
}
};
}
return settings2;
}
function BlockEditAnchorControlPure({ anchor, setAttributes }) {
const blockEditingMode = useBlockEditingMode();
if (blockEditingMode !== "default") {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime466.jsx)(inspector_controls_default, { group: "advanced", children: /* @__PURE__ */ (0, import_jsx_runtime466.jsx)(
import_components232.TextControl,
{
className: "html-anchor-control",
label: (0, import_i18n218.__)("HTML anchor"),
help: /* @__PURE__ */ (0, import_jsx_runtime466.jsxs)(import_jsx_runtime466.Fragment, { children: [
(0, import_i18n218.__)(
"Enter a word or two\u2014without spaces\u2014to make a unique web address just for this block, called an \u201Canchor\u201D. Then, you\u2019ll be able to link directly to this section of your page."
),
" ",
/* @__PURE__ */ (0, import_jsx_runtime466.jsx)(
import_components232.ExternalLink,
{
href: (0, import_i18n218.__)(
"https://wordpress.org/documentation/article/page-jumps/"
),
children: (0, import_i18n218.__)("Learn more about anchors")
}
)
] }),
value: anchor || "",
placeholder: null,
onChange: (nextValue) => {
nextValue = nextValue.replace(ANCHOR_REGEX, "-");
setAttributes({
anchor: nextValue !== "" ? nextValue : void 0
});
},
autoCapitalize: "none",
autoComplete: "off"
}
) });
}
var anchor_default = {
addSaveProps: addSaveProps6,
edit: BlockEditAnchorControlPure,
attributeKeys: ["anchor"],
hasSupport(name) {
return (0, import_blocks110.hasBlockSupport)(name, "anchor");
}
};
function addSaveProps6(extraProps, blockType, attributes) {
if ((0, import_blocks110.hasBlockSupport)(blockType, "anchor")) {
extraProps.id = attributes.anchor === "" ? null : attributes.anchor;
}
return extraProps;
}
(0, import_hooks24.addFilter)("blocks.registerBlockType", "core/anchor/attribute", addAttribute4);
// packages/block-editor/build-module/hooks/aria-label.mjs
var import_hooks25 = __toESM(require_hooks(), 1);
var import_blocks111 = __toESM(require_blocks(), 1);
function addAttribute5(settings2) {
if (settings2?.attributes?.ariaLabel?.type) {
return settings2;
}
if ((0, import_blocks111.hasBlockSupport)(settings2, "ariaLabel")) {
settings2.attributes = {
...settings2.attributes,
ariaLabel: {
type: "string"
}
};
}
return settings2;
}
function addSaveProps7(extraProps, blockType, attributes) {
if ((0, import_blocks111.hasBlockSupport)(blockType, "ariaLabel") && !shouldSkipSerialization(blockType, "ariaLabel", "ariaLabel")) {
extraProps["aria-label"] = attributes.ariaLabel === "" ? null : attributes.ariaLabel;
}
return extraProps;
}
var aria_label_default = {
addSaveProps: addSaveProps7,
attributeKeys: ["ariaLabel"],
hasSupport(name) {
return (0, import_blocks111.hasBlockSupport)(name, "ariaLabel");
}
};
(0, import_hooks25.addFilter)(
"blocks.registerBlockType",
"core/ariaLabel/attribute",
addAttribute5
);
// packages/block-editor/build-module/hooks/block-fields/index.mjs
var import_blocks112 = __toESM(require_blocks(), 1);
var import_compose105 = __toESM(require_compose(), 1);
var import_components263 = __toESM(require_components(), 1);
var import_data185 = __toESM(require_data(), 1);
// packages/dataviews/build-module/constants.mjs
var import_i18n219 = __toESM(require_i18n(), 1);
var OPERATOR_IS_ANY = "isAny";
var OPERATOR_IS_NONE = "isNone";
var OPERATOR_IS_ALL = "isAll";
var OPERATOR_IS_NOT_ALL = "isNotAll";
var OPERATOR_BETWEEN = "between";
var OPERATOR_IN_THE_PAST = "inThePast";
var OPERATOR_OVER = "over";
var OPERATOR_IS = "is";
var OPERATOR_IS_NOT = "isNot";
var OPERATOR_LESS_THAN = "lessThan";
var OPERATOR_GREATER_THAN = "greaterThan";
var OPERATOR_LESS_THAN_OR_EQUAL = "lessThanOrEqual";
var OPERATOR_GREATER_THAN_OR_EQUAL = "greaterThanOrEqual";
var OPERATOR_BEFORE = "before";
var OPERATOR_AFTER = "after";
var OPERATOR_BEFORE_INC = "beforeInc";
var OPERATOR_AFTER_INC = "afterInc";
var OPERATOR_CONTAINS = "contains";
var OPERATOR_NOT_CONTAINS = "notContains";
var OPERATOR_STARTS_WITH = "startsWith";
var OPERATOR_ON = "on";
var OPERATOR_NOT_ON = "notOn";
var sortLabels = {
asc: (0, import_i18n219.__)("Sort ascending"),
desc: (0, import_i18n219.__)("Sort descending")
};
// packages/dataviews/build-module/lock-unlock.mjs
var import_private_apis5 = __toESM(require_private_apis(), 1);
var { lock: lock4, unlock: unlock4 } = (0, import_private_apis5.__dangerousOptInToUnstableAPIsOnlyForCoreModules)(
"I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.",
"@wordpress/dataviews"
);
// packages/dataviews/build-module/hooks/use-elements.mjs
var import_element278 = __toESM(require_element(), 1);
var EMPTY_ARRAY16 = [];
function useElements({
elements,
getElements
}) {
const staticElements = Array.isArray(elements) && elements.length > 0 ? elements : EMPTY_ARRAY16;
const [records, setRecords] = (0, import_element278.useState)(staticElements);
const [isLoading, setIsLoading] = (0, import_element278.useState)(false);
(0, import_element278.useEffect)(() => {
if (!getElements) {
setRecords(staticElements);
return;
}
let cancelled = false;
setIsLoading(true);
getElements().then((fetchedElements) => {
if (!cancelled) {
const dynamicElements = Array.isArray(fetchedElements) && fetchedElements.length > 0 ? fetchedElements : staticElements;
setRecords(dynamicElements);
}
}).catch(() => {
if (!cancelled) {
setRecords(staticElements);
}
}).finally(() => {
if (!cancelled) {
setIsLoading(false);
}
});
return () => {
cancelled = true;
};
}, [getElements, staticElements]);
return {
elements: records,
isLoading
};
}
// node_modules/date-fns/constants.js
var daysInYear = 365.2425;
var maxTime = Math.pow(10, 8) * 24 * 60 * 60 * 1e3;
var minTime = -maxTime;
var millisecondsInWeek = 6048e5;
var millisecondsInDay = 864e5;
var secondsInHour = 3600;
var secondsInDay = secondsInHour * 24;
var secondsInWeek = secondsInDay * 7;
var secondsInYear = secondsInDay * daysInYear;
var secondsInMonth = secondsInYear / 12;
var secondsInQuarter = secondsInMonth * 3;
var constructFromSymbol = /* @__PURE__ */ Symbol.for("constructDateFrom");
// node_modules/date-fns/constructFrom.js
function constructFrom(date, value) {
if (typeof date === "function") return date(value);
if (date && typeof date === "object" && constructFromSymbol in date)
return date[constructFromSymbol](value);
if (date instanceof Date) return new date.constructor(value);
return new Date(value);
}
// node_modules/date-fns/toDate.js
function toDate(argument, context) {
return constructFrom(context || argument, argument);
}
// node_modules/date-fns/addDays.js
function addDays(date, amount, options) {
const _date = toDate(date, options?.in);
if (isNaN(amount)) return constructFrom(options?.in || date, NaN);
if (!amount) return _date;
_date.setDate(_date.getDate() + amount);
return _date;
}
// node_modules/date-fns/addMonths.js
function addMonths(date, amount, options) {
const _date = toDate(date, options?.in);
if (isNaN(amount)) return constructFrom(options?.in || date, NaN);
if (!amount) {
return _date;
}
const dayOfMonth = _date.getDate();
const endOfDesiredMonth = constructFrom(options?.in || date, _date.getTime());
endOfDesiredMonth.setMonth(_date.getMonth() + amount + 1, 0);
const daysInMonth = endOfDesiredMonth.getDate();
if (dayOfMonth >= daysInMonth) {
return endOfDesiredMonth;
} else {
_date.setFullYear(
endOfDesiredMonth.getFullYear(),
endOfDesiredMonth.getMonth(),
dayOfMonth
);
return _date;
}
}
// node_modules/date-fns/_lib/defaultOptions.js
var defaultOptions = {};
function getDefaultOptions() {
return defaultOptions;
}
// node_modules/date-fns/startOfWeek.js
function startOfWeek(date, options) {
const defaultOptions2 = getDefaultOptions();
const weekStartsOn = options?.weekStartsOn ?? options?.locale?.options?.weekStartsOn ?? defaultOptions2.weekStartsOn ?? defaultOptions2.locale?.options?.weekStartsOn ?? 0;
const _date = toDate(date, options?.in);
const day = _date.getDay();
const diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
_date.setDate(_date.getDate() - diff);
_date.setHours(0, 0, 0, 0);
return _date;
}
// node_modules/date-fns/startOfISOWeek.js
function startOfISOWeek(date, options) {
return startOfWeek(date, { ...options, weekStartsOn: 1 });
}
// node_modules/date-fns/getISOWeekYear.js
function getISOWeekYear(date, options) {
const _date = toDate(date, options?.in);
const year = _date.getFullYear();
const fourthOfJanuaryOfNextYear = constructFrom(_date, 0);
fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4);
fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0);
const startOfNextYear = startOfISOWeek(fourthOfJanuaryOfNextYear);
const fourthOfJanuaryOfThisYear = constructFrom(_date, 0);
fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4);
fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0);
const startOfThisYear = startOfISOWeek(fourthOfJanuaryOfThisYear);
if (_date.getTime() >= startOfNextYear.getTime()) {
return year + 1;
} else if (_date.getTime() >= startOfThisYear.getTime()) {
return year;
} else {
return year - 1;
}
}
// node_modules/date-fns/_lib/getTimezoneOffsetInMilliseconds.js
function getTimezoneOffsetInMilliseconds(date) {
const _date = toDate(date);
const utcDate = new Date(
Date.UTC(
_date.getFullYear(),
_date.getMonth(),
_date.getDate(),
_date.getHours(),
_date.getMinutes(),
_date.getSeconds(),
_date.getMilliseconds()
)
);
utcDate.setUTCFullYear(_date.getFullYear());
return +date - +utcDate;
}
// node_modules/date-fns/_lib/normalizeDates.js
function normalizeDates(context, ...dates) {
const normalize = constructFrom.bind(
null,
context || dates.find((date) => typeof date === "object")
);
return dates.map(normalize);
}
// node_modules/date-fns/startOfDay.js
function startOfDay(date, options) {
const _date = toDate(date, options?.in);
_date.setHours(0, 0, 0, 0);
return _date;
}
// node_modules/date-fns/differenceInCalendarDays.js
function differenceInCalendarDays(laterDate, earlierDate, options) {
const [laterDate_, earlierDate_] = normalizeDates(
options?.in,
laterDate,
earlierDate
);
const laterStartOfDay = startOfDay(laterDate_);
const earlierStartOfDay = startOfDay(earlierDate_);
const laterTimestamp = +laterStartOfDay - getTimezoneOffsetInMilliseconds(laterStartOfDay);
const earlierTimestamp = +earlierStartOfDay - getTimezoneOffsetInMilliseconds(earlierStartOfDay);
return Math.round((laterTimestamp - earlierTimestamp) / millisecondsInDay);
}
// node_modules/date-fns/startOfISOWeekYear.js
function startOfISOWeekYear(date, options) {
const year = getISOWeekYear(date, options);
const fourthOfJanuary = constructFrom(options?.in || date, 0);
fourthOfJanuary.setFullYear(year, 0, 4);
fourthOfJanuary.setHours(0, 0, 0, 0);
return startOfISOWeek(fourthOfJanuary);
}
// node_modules/date-fns/addWeeks.js
function addWeeks(date, amount, options) {
return addDays(date, amount * 7, options);
}
// node_modules/date-fns/addYears.js
function addYears(date, amount, options) {
return addMonths(date, amount * 12, options);
}
// node_modules/date-fns/isDate.js
function isDate(value) {
return value instanceof Date || typeof value === "object" && Object.prototype.toString.call(value) === "[object Date]";
}
// node_modules/date-fns/isValid.js
function isValid(date) {
return !(!isDate(date) && typeof date !== "number" || isNaN(+toDate(date)));
}
// node_modules/date-fns/startOfMonth.js
function startOfMonth(date, options) {
const _date = toDate(date, options?.in);
_date.setDate(1);
_date.setHours(0, 0, 0, 0);
return _date;
}
// node_modules/date-fns/startOfYear.js
function startOfYear(date, options) {
const date_ = toDate(date, options?.in);
date_.setFullYear(date_.getFullYear(), 0, 1);
date_.setHours(0, 0, 0, 0);
return date_;
}
// node_modules/date-fns/locale/en-US/_lib/formatDistance.js
var formatDistanceLocale = {
lessThanXSeconds: {
one: "less than a second",
other: "less than {{count}} seconds"
},
xSeconds: {
one: "1 second",
other: "{{count}} seconds"
},
halfAMinute: "half a minute",
lessThanXMinutes: {
one: "less than a minute",
other: "less than {{count}} minutes"
},
xMinutes: {
one: "1 minute",
other: "{{count}} minutes"
},
aboutXHours: {
one: "about 1 hour",
other: "about {{count}} hours"
},
xHours: {
one: "1 hour",
other: "{{count}} hours"
},
xDays: {
one: "1 day",
other: "{{count}} days"
},
aboutXWeeks: {
one: "about 1 week",
other: "about {{count}} weeks"
},
xWeeks: {
one: "1 week",
other: "{{count}} weeks"
},
aboutXMonths: {
one: "about 1 month",
other: "about {{count}} months"
},
xMonths: {
one: "1 month",
other: "{{count}} months"
},
aboutXYears: {
one: "about 1 year",
other: "about {{count}} years"
},
xYears: {
one: "1 year",
other: "{{count}} years"
},
overXYears: {
one: "over 1 year",
other: "over {{count}} years"
},
almostXYears: {
one: "almost 1 year",
other: "almost {{count}} years"
}
};
var formatDistance = (token, count, options) => {
let result;
const tokenValue = formatDistanceLocale[token];
if (typeof tokenValue === "string") {
result = tokenValue;
} else if (count === 1) {
result = tokenValue.one;
} else {
result = tokenValue.other.replace("{{count}}", count.toString());
}
if (options?.addSuffix) {
if (options.comparison && options.comparison > 0) {
return "in " + result;
} else {
return result + " ago";
}
}
return result;
};
// node_modules/date-fns/locale/_lib/buildFormatLongFn.js
function buildFormatLongFn(args) {
return (options = {}) => {
const width = options.width ? String(options.width) : args.defaultWidth;
const format6 = args.formats[width] || args.formats[args.defaultWidth];
return format6;
};
}
// node_modules/date-fns/locale/en-US/_lib/formatLong.js
var dateFormats = {
full: "EEEE, MMMM do, y",
long: "MMMM do, y",
medium: "MMM d, y",
short: "MM/dd/yyyy"
};
var timeFormats = {
full: "h:mm:ss a zzzz",
long: "h:mm:ss a z",
medium: "h:mm:ss a",
short: "h:mm a"
};
var dateTimeFormats = {
full: "{{date}} 'at' {{time}}",
long: "{{date}} 'at' {{time}}",
medium: "{{date}}, {{time}}",
short: "{{date}}, {{time}}"
};
var formatLong = {
date: buildFormatLongFn({
formats: dateFormats,
defaultWidth: "full"
}),
time: buildFormatLongFn({
formats: timeFormats,
defaultWidth: "full"
}),
dateTime: buildFormatLongFn({
formats: dateTimeFormats,
defaultWidth: "full"
})
};
// node_modules/date-fns/locale/en-US/_lib/formatRelative.js
var formatRelativeLocale = {
lastWeek: "'last' eeee 'at' p",
yesterday: "'yesterday at' p",
today: "'today at' p",
tomorrow: "'tomorrow at' p",
nextWeek: "eeee 'at' p",
other: "P"
};
var formatRelative = (token, _date, _baseDate, _options) => formatRelativeLocale[token];
// node_modules/date-fns/locale/_lib/buildLocalizeFn.js
function buildLocalizeFn(args) {
return (value, options) => {
const context = options?.context ? String(options.context) : "standalone";
let valuesArray;
if (context === "formatting" && args.formattingValues) {
const defaultWidth = args.defaultFormattingWidth || args.defaultWidth;
const width = options?.width ? String(options.width) : defaultWidth;
valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth];
} else {
const defaultWidth = args.defaultWidth;
const width = options?.width ? String(options.width) : args.defaultWidth;
valuesArray = args.values[width] || args.values[defaultWidth];
}
const index2 = args.argumentCallback ? args.argumentCallback(value) : value;
return valuesArray[index2];
};
}
// node_modules/date-fns/locale/en-US/_lib/localize.js
var eraValues = {
narrow: ["B", "A"],
abbreviated: ["BC", "AD"],
wide: ["Before Christ", "Anno Domini"]
};
var quarterValues = {
narrow: ["1", "2", "3", "4"],
abbreviated: ["Q1", "Q2", "Q3", "Q4"],
wide: ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"]
};
var monthValues = {
narrow: ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"],
abbreviated: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
wide: [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
]
};
var dayValues = {
narrow: ["S", "M", "T", "W", "T", "F", "S"],
short: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
abbreviated: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
wide: [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
]
};
var dayPeriodValues = {
narrow: {
am: "a",
pm: "p",
midnight: "mi",
noon: "n",
morning: "morning",
afternoon: "afternoon",
evening: "evening",
night: "night"
},
abbreviated: {
am: "AM",
pm: "PM",
midnight: "midnight",
noon: "noon",
morning: "morning",
afternoon: "afternoon",
evening: "evening",
night: "night"
},
wide: {
am: "a.m.",
pm: "p.m.",
midnight: "midnight",
noon: "noon",
morning: "morning",
afternoon: "afternoon",
evening: "evening",
night: "night"
}
};
var formattingDayPeriodValues = {
narrow: {
am: "a",
pm: "p",
midnight: "mi",
noon: "n",
morning: "in the morning",
afternoon: "in the afternoon",
evening: "in the evening",
night: "at night"
},
abbreviated: {
am: "AM",
pm: "PM",
midnight: "midnight",
noon: "noon",
morning: "in the morning",
afternoon: "in the afternoon",
evening: "in the evening",
night: "at night"
},
wide: {
am: "a.m.",
pm: "p.m.",
midnight: "midnight",
noon: "noon",
morning: "in the morning",
afternoon: "in the afternoon",
evening: "in the evening",
night: "at night"
}
};
var ordinalNumber = (dirtyNumber, _options) => {
const number = Number(dirtyNumber);
const rem100 = number % 100;
if (rem100 > 20 || rem100 < 10) {
switch (rem100 % 10) {
case 1:
return number + "st";
case 2:
return number + "nd";
case 3:
return number + "rd";
}
}
return number + "th";
};
var localize = {
ordinalNumber,
era: buildLocalizeFn({
values: eraValues,
defaultWidth: "wide"
}),
quarter: buildLocalizeFn({
values: quarterValues,
defaultWidth: "wide",
argumentCallback: (quarter) => quarter - 1
}),
month: buildLocalizeFn({
values: monthValues,
defaultWidth: "wide"
}),
day: buildLocalizeFn({
values: dayValues,
defaultWidth: "wide"
}),
dayPeriod: buildLocalizeFn({
values: dayPeriodValues,
defaultWidth: "wide",
formattingValues: formattingDayPeriodValues,
defaultFormattingWidth: "wide"
})
};
// node_modules/date-fns/locale/_lib/buildMatchFn.js
function buildMatchFn(args) {
return (string, options = {}) => {
const width = options.width;
const matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth];
const matchResult = string.match(matchPattern);
if (!matchResult) {
return null;
}
const matchedString = matchResult[0];
const parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth];
const key = Array.isArray(parsePatterns) ? findIndex2(parsePatterns, (pattern) => pattern.test(matchedString)) : (
// [TODO] -- I challenge you to fix the type
findKey(parsePatterns, (pattern) => pattern.test(matchedString))
);
let value;
value = args.valueCallback ? args.valueCallback(key) : key;
value = options.valueCallback ? (
// [TODO] -- I challenge you to fix the type
options.valueCallback(value)
) : value;
const rest = string.slice(matchedString.length);
return { value, rest };
};
}
function findKey(object, predicate) {
for (const key in object) {
if (Object.prototype.hasOwnProperty.call(object, key) && predicate(object[key])) {
return key;
}
}
return void 0;
}
function findIndex2(array, predicate) {
for (let key = 0; key < array.length; key++) {
if (predicate(array[key])) {
return key;
}
}
return void 0;
}
// node_modules/date-fns/locale/_lib/buildMatchPatternFn.js
function buildMatchPatternFn(args) {
return (string, options = {}) => {
const matchResult = string.match(args.matchPattern);
if (!matchResult) return null;
const matchedString = matchResult[0];
const parseResult = string.match(args.parsePattern);
if (!parseResult) return null;
let value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0];
value = options.valueCallback ? options.valueCallback(value) : value;
const rest = string.slice(matchedString.length);
return { value, rest };
};
}
// node_modules/date-fns/locale/en-US/_lib/match.js
var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i;
var parseOrdinalNumberPattern = /\d+/i;
var matchEraPatterns = {
narrow: /^(b|a)/i,
abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,
wide: /^(before christ|before common era|anno domini|common era)/i
};
var parseEraPatterns = {
any: [/^b/i, /^(a|c)/i]
};
var matchQuarterPatterns = {
narrow: /^[1234]/i,
abbreviated: /^q[1234]/i,
wide: /^[1234](th|st|nd|rd)? quarter/i
};
var parseQuarterPatterns = {
any: [/1/i, /2/i, /3/i, /4/i]
};
var matchMonthPatterns = {
narrow: /^[jfmasond]/i,
abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,
wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i
};
var parseMonthPatterns = {
narrow: [
/^j/i,
/^f/i,
/^m/i,
/^a/i,
/^m/i,
/^j/i,
/^j/i,
/^a/i,
/^s/i,
/^o/i,
/^n/i,
/^d/i
],
any: [
/^ja/i,
/^f/i,
/^mar/i,
/^ap/i,
/^may/i,
/^jun/i,
/^jul/i,
/^au/i,
/^s/i,
/^o/i,
/^n/i,
/^d/i
]
};
var matchDayPatterns = {
narrow: /^[smtwf]/i,
short: /^(su|mo|tu|we|th|fr|sa)/i,
abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,
wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i
};
var parseDayPatterns = {
narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],
any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i]
};
var matchDayPeriodPatterns = {
narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,
any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i
};
var parseDayPeriodPatterns = {
any: {
am: /^a/i,
pm: /^p/i,
midnight: /^mi/i,
noon: /^no/i,
morning: /morning/i,
afternoon: /afternoon/i,
evening: /evening/i,
night: /night/i
}
};
var match = {
ordinalNumber: buildMatchPatternFn({
matchPattern: matchOrdinalNumberPattern,
parsePattern: parseOrdinalNumberPattern,
valueCallback: (value) => parseInt(value, 10)
}),
era: buildMatchFn({
matchPatterns: matchEraPatterns,
defaultMatchWidth: "wide",
parsePatterns: parseEraPatterns,
defaultParseWidth: "any"
}),
quarter: buildMatchFn({
matchPatterns: matchQuarterPatterns,
defaultMatchWidth: "wide",
parsePatterns: parseQuarterPatterns,
defaultParseWidth: "any",
valueCallback: (index2) => index2 + 1
}),
month: buildMatchFn({
matchPatterns: matchMonthPatterns,
defaultMatchWidth: "wide",
parsePatterns: parseMonthPatterns,
defaultParseWidth: "any"
}),
day: buildMatchFn({
matchPatterns: matchDayPatterns,
defaultMatchWidth: "wide",
parsePatterns: parseDayPatterns,
defaultParseWidth: "any"
}),
dayPeriod: buildMatchFn({
matchPatterns: matchDayPeriodPatterns,
defaultMatchWidth: "any",
parsePatterns: parseDayPeriodPatterns,
defaultParseWidth: "any"
})
};
// node_modules/date-fns/locale/en-US.js
var enUS = {
code: "en-US",
formatDistance,
formatLong,
formatRelative,
localize,
match,
options: {
weekStartsOn: 0,
firstWeekContainsDate: 1
}
};
// node_modules/date-fns/getDayOfYear.js
function getDayOfYear(date, options) {
const _date = toDate(date, options?.in);
const diff = differenceInCalendarDays(_date, startOfYear(_date));
const dayOfYear = diff + 1;
return dayOfYear;
}
// node_modules/date-fns/getISOWeek.js
function getISOWeek(date, options) {
const _date = toDate(date, options?.in);
const diff = +startOfISOWeek(_date) - +startOfISOWeekYear(_date);
return Math.round(diff / millisecondsInWeek) + 1;
}
// node_modules/date-fns/getWeekYear.js
function getWeekYear(date, options) {
const _date = toDate(date, options?.in);
const year = _date.getFullYear();
const defaultOptions2 = getDefaultOptions();
const firstWeekContainsDate = options?.firstWeekContainsDate ?? options?.locale?.options?.firstWeekContainsDate ?? defaultOptions2.firstWeekContainsDate ?? defaultOptions2.locale?.options?.firstWeekContainsDate ?? 1;
const firstWeekOfNextYear = constructFrom(options?.in || date, 0);
firstWeekOfNextYear.setFullYear(year + 1, 0, firstWeekContainsDate);
firstWeekOfNextYear.setHours(0, 0, 0, 0);
const startOfNextYear = startOfWeek(firstWeekOfNextYear, options);
const firstWeekOfThisYear = constructFrom(options?.in || date, 0);
firstWeekOfThisYear.setFullYear(year, 0, firstWeekContainsDate);
firstWeekOfThisYear.setHours(0, 0, 0, 0);
const startOfThisYear = startOfWeek(firstWeekOfThisYear, options);
if (+_date >= +startOfNextYear) {
return year + 1;
} else if (+_date >= +startOfThisYear) {
return year;
} else {
return year - 1;
}
}
// node_modules/date-fns/startOfWeekYear.js
function startOfWeekYear(date, options) {
const defaultOptions2 = getDefaultOptions();
const firstWeekContainsDate = options?.firstWeekContainsDate ?? options?.locale?.options?.firstWeekContainsDate ?? defaultOptions2.firstWeekContainsDate ?? defaultOptions2.locale?.options?.firstWeekContainsDate ?? 1;
const year = getWeekYear(date, options);
const firstWeek = constructFrom(options?.in || date, 0);
firstWeek.setFullYear(year, 0, firstWeekContainsDate);
firstWeek.setHours(0, 0, 0, 0);
const _date = startOfWeek(firstWeek, options);
return _date;
}
// node_modules/date-fns/getWeek.js
function getWeek(date, options) {
const _date = toDate(date, options?.in);
const diff = +startOfWeek(_date, options) - +startOfWeekYear(_date, options);
return Math.round(diff / millisecondsInWeek) + 1;
}
// node_modules/date-fns/_lib/addLeadingZeros.js
function addLeadingZeros(number, targetLength) {
const sign = number < 0 ? "-" : "";
const output = Math.abs(number).toString().padStart(targetLength, "0");
return sign + output;
}
// node_modules/date-fns/_lib/format/lightFormatters.js
var lightFormatters = {
// Year
y(date, token) {
const signedYear = date.getFullYear();
const year = signedYear > 0 ? signedYear : 1 - signedYear;
return addLeadingZeros(token === "yy" ? year % 100 : year, token.length);
},
// Month
M(date, token) {
const month = date.getMonth();
return token === "M" ? String(month + 1) : addLeadingZeros(month + 1, 2);
},
// Day of the month
d(date, token) {
return addLeadingZeros(date.getDate(), token.length);
},
// AM or PM
a(date, token) {
const dayPeriodEnumValue = date.getHours() / 12 >= 1 ? "pm" : "am";
switch (token) {
case "a":
case "aa":
return dayPeriodEnumValue.toUpperCase();
case "aaa":
return dayPeriodEnumValue;
case "aaaaa":
return dayPeriodEnumValue[0];
case "aaaa":
default:
return dayPeriodEnumValue === "am" ? "a.m." : "p.m.";
}
},
// Hour [1-12]
h(date, token) {
return addLeadingZeros(date.getHours() % 12 || 12, token.length);
},
// Hour [0-23]
H(date, token) {
return addLeadingZeros(date.getHours(), token.length);
},
// Minute
m(date, token) {
return addLeadingZeros(date.getMinutes(), token.length);
},
// Second
s(date, token) {
return addLeadingZeros(date.getSeconds(), token.length);
},
// Fraction of second
S(date, token) {
const numberOfDigits = token.length;
const milliseconds = date.getMilliseconds();
const fractionalSeconds = Math.trunc(
milliseconds * Math.pow(10, numberOfDigits - 3)
);
return addLeadingZeros(fractionalSeconds, token.length);
}
};
// node_modules/date-fns/_lib/format/formatters.js
var dayPeriodEnum = {
am: "am",
pm: "pm",
midnight: "midnight",
noon: "noon",
morning: "morning",
afternoon: "afternoon",
evening: "evening",
night: "night"
};
var formatters = {
// Era
G: function(date, token, localize2) {
const era = date.getFullYear() > 0 ? 1 : 0;
switch (token) {
// AD, BC
case "G":
case "GG":
case "GGG":
return localize2.era(era, { width: "abbreviated" });
// A, B
case "GGGGG":
return localize2.era(era, { width: "narrow" });
// Anno Domini, Before Christ
case "GGGG":
default:
return localize2.era(era, { width: "wide" });
}
},
// Year
y: function(date, token, localize2) {
if (token === "yo") {
const signedYear = date.getFullYear();
const year = signedYear > 0 ? signedYear : 1 - signedYear;
return localize2.ordinalNumber(year, { unit: "year" });
}
return lightFormatters.y(date, token);
},
// Local week-numbering year
Y: function(date, token, localize2, options) {
const signedWeekYear = getWeekYear(date, options);
const weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear;
if (token === "YY") {
const twoDigitYear = weekYear % 100;
return addLeadingZeros(twoDigitYear, 2);
}
if (token === "Yo") {
return localize2.ordinalNumber(weekYear, { unit: "year" });
}
return addLeadingZeros(weekYear, token.length);
},
// ISO week-numbering year
R: function(date, token) {
const isoWeekYear = getISOWeekYear(date);
return addLeadingZeros(isoWeekYear, token.length);
},
// Extended year. This is a single number designating the year of this calendar system.
// The main difference between `y` and `u` localizers are B.C. years:
// | Year | `y` | `u` |
// |------|-----|-----|
// | AC 1 | 1 | 1 |
// | BC 1 | 1 | 0 |
// | BC 2 | 2 | -1 |
// Also `yy` always returns the last two digits of a year,
// while `uu` pads single digit years to 2 characters and returns other years unchanged.
u: function(date, token) {
const year = date.getFullYear();
return addLeadingZeros(year, token.length);
},
// Quarter
Q: function(date, token, localize2) {
const quarter = Math.ceil((date.getMonth() + 1) / 3);
switch (token) {
// 1, 2, 3, 4
case "Q":
return String(quarter);
// 01, 02, 03, 04
case "QQ":
return addLeadingZeros(quarter, 2);
// 1st, 2nd, 3rd, 4th
case "Qo":
return localize2.ordinalNumber(quarter, { unit: "quarter" });
// Q1, Q2, Q3, Q4
case "QQQ":
return localize2.quarter(quarter, {
width: "abbreviated",
context: "formatting"
});
// 1, 2, 3, 4 (narrow quarter; could be not numerical)
case "QQQQQ":
return localize2.quarter(quarter, {
width: "narrow",
context: "formatting"
});
// 1st quarter, 2nd quarter, ...
case "QQQQ":
default:
return localize2.quarter(quarter, {
width: "wide",
context: "formatting"
});
}
},
// Stand-alone quarter
q: function(date, token, localize2) {
const quarter = Math.ceil((date.getMonth() + 1) / 3);
switch (token) {
// 1, 2, 3, 4
case "q":
return String(quarter);
// 01, 02, 03, 04
case "qq":
return addLeadingZeros(quarter, 2);
// 1st, 2nd, 3rd, 4th
case "qo":
return localize2.ordinalNumber(quarter, { unit: "quarter" });
// Q1, Q2, Q3, Q4
case "qqq":
return localize2.quarter(quarter, {
width: "abbreviated",
context: "standalone"
});
// 1, 2, 3, 4 (narrow quarter; could be not numerical)
case "qqqqq":
return localize2.quarter(quarter, {
width: "narrow",
context: "standalone"
});
// 1st quarter, 2nd quarter, ...
case "qqqq":
default:
return localize2.quarter(quarter, {
width: "wide",
context: "standalone"
});
}
},
// Month
M: function(date, token, localize2) {
const month = date.getMonth();
switch (token) {
case "M":
case "MM":
return lightFormatters.M(date, token);
// 1st, 2nd, ..., 12th
case "Mo":
return localize2.ordinalNumber(month + 1, { unit: "month" });
// Jan, Feb, ..., Dec
case "MMM":
return localize2.month(month, {
width: "abbreviated",
context: "formatting"
});
// J, F, ..., D
case "MMMMM":
return localize2.month(month, {
width: "narrow",
context: "formatting"
});
// January, February, ..., December
case "MMMM":
default:
return localize2.month(month, { width: "wide", context: "formatting" });
}
},
// Stand-alone month
L: function(date, token, localize2) {
const month = date.getMonth();
switch (token) {
// 1, 2, ..., 12
case "L":
return String(month + 1);
// 01, 02, ..., 12
case "LL":
return addLeadingZeros(month + 1, 2);
// 1st, 2nd, ..., 12th
case "Lo":
return localize2.ordinalNumber(month + 1, { unit: "month" });
// Jan, Feb, ..., Dec
case "LLL":
return localize2.month(month, {
width: "abbreviated",
context: "standalone"
});
// J, F, ..., D
case "LLLLL":
return localize2.month(month, {
width: "narrow",
context: "standalone"
});
// January, February, ..., December
case "LLLL":
default:
return localize2.month(month, { width: "wide", context: "standalone" });
}
},
// Local week of year
w: function(date, token, localize2, options) {
const week = getWeek(date, options);
if (token === "wo") {
return localize2.ordinalNumber(week, { unit: "week" });
}
return addLeadingZeros(week, token.length);
},
// ISO week of year
I: function(date, token, localize2) {
const isoWeek = getISOWeek(date);
if (token === "Io") {
return localize2.ordinalNumber(isoWeek, { unit: "week" });
}
return addLeadingZeros(isoWeek, token.length);
},
// Day of the month
d: function(date, token, localize2) {
if (token === "do") {
return localize2.ordinalNumber(date.getDate(), { unit: "date" });
}
return lightFormatters.d(date, token);
},
// Day of year
D: function(date, token, localize2) {
const dayOfYear = getDayOfYear(date);
if (token === "Do") {
return localize2.ordinalNumber(dayOfYear, { unit: "dayOfYear" });
}
return addLeadingZeros(dayOfYear, token.length);
},
// Day of week
E: function(date, token, localize2) {
const dayOfWeek = date.getDay();
switch (token) {
// Tue
case "E":
case "EE":
case "EEE":
return localize2.day(dayOfWeek, {
width: "abbreviated",
context: "formatting"
});
// T
case "EEEEE":
return localize2.day(dayOfWeek, {
width: "narrow",
context: "formatting"
});
// Tu
case "EEEEEE":
return localize2.day(dayOfWeek, {
width: "short",
context: "formatting"
});
// Tuesday
case "EEEE":
default:
return localize2.day(dayOfWeek, {
width: "wide",
context: "formatting"
});
}
},
// Local day of week
e: function(date, token, localize2, options) {
const dayOfWeek = date.getDay();
const localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
switch (token) {
// Numerical value (Nth day of week with current locale or weekStartsOn)
case "e":
return String(localDayOfWeek);
// Padded numerical value
case "ee":
return addLeadingZeros(localDayOfWeek, 2);
// 1st, 2nd, ..., 7th
case "eo":
return localize2.ordinalNumber(localDayOfWeek, { unit: "day" });
case "eee":
return localize2.day(dayOfWeek, {
width: "abbreviated",
context: "formatting"
});
// T
case "eeeee":
return localize2.day(dayOfWeek, {
width: "narrow",
context: "formatting"
});
// Tu
case "eeeeee":
return localize2.day(dayOfWeek, {
width: "short",
context: "formatting"
});
// Tuesday
case "eeee":
default:
return localize2.day(dayOfWeek, {
width: "wide",
context: "formatting"
});
}
},
// Stand-alone local day of week
c: function(date, token, localize2, options) {
const dayOfWeek = date.getDay();
const localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
switch (token) {
// Numerical value (same as in `e`)
case "c":
return String(localDayOfWeek);
// Padded numerical value
case "cc":
return addLeadingZeros(localDayOfWeek, token.length);
// 1st, 2nd, ..., 7th
case "co":
return localize2.ordinalNumber(localDayOfWeek, { unit: "day" });
case "ccc":
return localize2.day(dayOfWeek, {
width: "abbreviated",
context: "standalone"
});
// T
case "ccccc":
return localize2.day(dayOfWeek, {
width: "narrow",
context: "standalone"
});
// Tu
case "cccccc":
return localize2.day(dayOfWeek, {
width: "short",
context: "standalone"
});
// Tuesday
case "cccc":
default:
return localize2.day(dayOfWeek, {
width: "wide",
context: "standalone"
});
}
},
// ISO day of week
i: function(date, token, localize2) {
const dayOfWeek = date.getDay();
const isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek;
switch (token) {
// 2
case "i":
return String(isoDayOfWeek);
// 02
case "ii":
return addLeadingZeros(isoDayOfWeek, token.length);
// 2nd
case "io":
return localize2.ordinalNumber(isoDayOfWeek, { unit: "day" });
// Tue
case "iii":
return localize2.day(dayOfWeek, {
width: "abbreviated",
context: "formatting"
});
// T
case "iiiii":
return localize2.day(dayOfWeek, {
width: "narrow",
context: "formatting"
});
// Tu
case "iiiiii":
return localize2.day(dayOfWeek, {
width: "short",
context: "formatting"
});
// Tuesday
case "iiii":
default:
return localize2.day(dayOfWeek, {
width: "wide",
context: "formatting"
});
}
},
// AM or PM
a: function(date, token, localize2) {
const hours = date.getHours();
const dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am";
switch (token) {
case "a":
case "aa":
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "abbreviated",
context: "formatting"
});
case "aaa":
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "abbreviated",
context: "formatting"
}).toLowerCase();
case "aaaaa":
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "narrow",
context: "formatting"
});
case "aaaa":
default:
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "wide",
context: "formatting"
});
}
},
// AM, PM, midnight, noon
b: function(date, token, localize2) {
const hours = date.getHours();
let dayPeriodEnumValue;
if (hours === 12) {
dayPeriodEnumValue = dayPeriodEnum.noon;
} else if (hours === 0) {
dayPeriodEnumValue = dayPeriodEnum.midnight;
} else {
dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am";
}
switch (token) {
case "b":
case "bb":
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "abbreviated",
context: "formatting"
});
case "bbb":
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "abbreviated",
context: "formatting"
}).toLowerCase();
case "bbbbb":
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "narrow",
context: "formatting"
});
case "bbbb":
default:
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "wide",
context: "formatting"
});
}
},
// in the morning, in the afternoon, in the evening, at night
B: function(date, token, localize2) {
const hours = date.getHours();
let dayPeriodEnumValue;
if (hours >= 17) {
dayPeriodEnumValue = dayPeriodEnum.evening;
} else if (hours >= 12) {
dayPeriodEnumValue = dayPeriodEnum.afternoon;
} else if (hours >= 4) {
dayPeriodEnumValue = dayPeriodEnum.morning;
} else {
dayPeriodEnumValue = dayPeriodEnum.night;
}
switch (token) {
case "B":
case "BB":
case "BBB":
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "abbreviated",
context: "formatting"
});
case "BBBBB":
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "narrow",
context: "formatting"
});
case "BBBB":
default:
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "wide",
context: "formatting"
});
}
},
// Hour [1-12]
h: function(date, token, localize2) {
if (token === "ho") {
let hours = date.getHours() % 12;
if (hours === 0) hours = 12;
return localize2.ordinalNumber(hours, { unit: "hour" });
}
return lightFormatters.h(date, token);
},
// Hour [0-23]
H: function(date, token, localize2) {
if (token === "Ho") {
return localize2.ordinalNumber(date.getHours(), { unit: "hour" });
}
return lightFormatters.H(date, token);
},
// Hour [0-11]
K: function(date, token, localize2) {
const hours = date.getHours() % 12;
if (token === "Ko") {
return localize2.ordinalNumber(hours, { unit: "hour" });
}
return addLeadingZeros(hours, token.length);
},
// Hour [1-24]
k: function(date, token, localize2) {
let hours = date.getHours();
if (hours === 0) hours = 24;
if (token === "ko") {
return localize2.ordinalNumber(hours, { unit: "hour" });
}
return addLeadingZeros(hours, token.length);
},
// Minute
m: function(date, token, localize2) {
if (token === "mo") {
return localize2.ordinalNumber(date.getMinutes(), { unit: "minute" });
}
return lightFormatters.m(date, token);
},
// Second
s: function(date, token, localize2) {
if (token === "so") {
return localize2.ordinalNumber(date.getSeconds(), { unit: "second" });
}
return lightFormatters.s(date, token);
},
// Fraction of second
S: function(date, token) {
return lightFormatters.S(date, token);
},
// Timezone (ISO-8601. If offset is 0, output is always `'Z'`)
X: function(date, token, _localize) {
const timezoneOffset = date.getTimezoneOffset();
if (timezoneOffset === 0) {
return "Z";
}
switch (token) {
// Hours and optional minutes
case "X":
return formatTimezoneWithOptionalMinutes(timezoneOffset);
// Hours, minutes and optional seconds without `:` delimiter
// Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
// so this token always has the same output as `XX`
case "XXXX":
case "XX":
return formatTimezone(timezoneOffset);
// Hours, minutes and optional seconds with `:` delimiter
// Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
// so this token always has the same output as `XXX`
case "XXXXX":
case "XXX":
// Hours and minutes with `:` delimiter
default:
return formatTimezone(timezoneOffset, ":");
}
},
// Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent)
x: function(date, token, _localize) {
const timezoneOffset = date.getTimezoneOffset();
switch (token) {
// Hours and optional minutes
case "x":
return formatTimezoneWithOptionalMinutes(timezoneOffset);
// Hours, minutes and optional seconds without `:` delimiter
// Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
// so this token always has the same output as `xx`
case "xxxx":
case "xx":
return formatTimezone(timezoneOffset);
// Hours, minutes and optional seconds with `:` delimiter
// Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
// so this token always has the same output as `xxx`
case "xxxxx":
case "xxx":
// Hours and minutes with `:` delimiter
default:
return formatTimezone(timezoneOffset, ":");
}
},
// Timezone (GMT)
O: function(date, token, _localize) {
const timezoneOffset = date.getTimezoneOffset();
switch (token) {
// Short
case "O":
case "OO":
case "OOO":
return "GMT" + formatTimezoneShort(timezoneOffset, ":");
// Long
case "OOOO":
default:
return "GMT" + formatTimezone(timezoneOffset, ":");
}
},
// Timezone (specific non-location)
z: function(date, token, _localize) {
const timezoneOffset = date.getTimezoneOffset();
switch (token) {
// Short
case "z":
case "zz":
case "zzz":
return "GMT" + formatTimezoneShort(timezoneOffset, ":");
// Long
case "zzzz":
default:
return "GMT" + formatTimezone(timezoneOffset, ":");
}
},
// Seconds timestamp
t: function(date, token, _localize) {
const timestamp = Math.trunc(+date / 1e3);
return addLeadingZeros(timestamp, token.length);
},
// Milliseconds timestamp
T: function(date, token, _localize) {
return addLeadingZeros(+date, token.length);
}
};
function formatTimezoneShort(offset4, delimiter = "") {
const sign = offset4 > 0 ? "-" : "+";
const absOffset = Math.abs(offset4);
const hours = Math.trunc(absOffset / 60);
const minutes = absOffset % 60;
if (minutes === 0) {
return sign + String(hours);
}
return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2);
}
function formatTimezoneWithOptionalMinutes(offset4, delimiter) {
if (offset4 % 60 === 0) {
const sign = offset4 > 0 ? "-" : "+";
return sign + addLeadingZeros(Math.abs(offset4) / 60, 2);
}
return formatTimezone(offset4, delimiter);
}
function formatTimezone(offset4, delimiter = "") {
const sign = offset4 > 0 ? "-" : "+";
const absOffset = Math.abs(offset4);
const hours = addLeadingZeros(Math.trunc(absOffset / 60), 2);
const minutes = addLeadingZeros(absOffset % 60, 2);
return sign + hours + delimiter + minutes;
}
// node_modules/date-fns/_lib/format/longFormatters.js
var dateLongFormatter = (pattern, formatLong2) => {
switch (pattern) {
case "P":
return formatLong2.date({ width: "short" });
case "PP":
return formatLong2.date({ width: "medium" });
case "PPP":
return formatLong2.date({ width: "long" });
case "PPPP":
default:
return formatLong2.date({ width: "full" });
}
};
var timeLongFormatter = (pattern, formatLong2) => {
switch (pattern) {
case "p":
return formatLong2.time({ width: "short" });
case "pp":
return formatLong2.time({ width: "medium" });
case "ppp":
return formatLong2.time({ width: "long" });
case "pppp":
default:
return formatLong2.time({ width: "full" });
}
};
var dateTimeLongFormatter = (pattern, formatLong2) => {
const matchResult = pattern.match(/(P+)(p+)?/) || [];
const datePattern = matchResult[1];
const timePattern = matchResult[2];
if (!timePattern) {
return dateLongFormatter(pattern, formatLong2);
}
let dateTimeFormat;
switch (datePattern) {
case "P":
dateTimeFormat = formatLong2.dateTime({ width: "short" });
break;
case "PP":
dateTimeFormat = formatLong2.dateTime({ width: "medium" });
break;
case "PPP":
dateTimeFormat = formatLong2.dateTime({ width: "long" });
break;
case "PPPP":
default:
dateTimeFormat = formatLong2.dateTime({ width: "full" });
break;
}
return dateTimeFormat.replace("{{date}}", dateLongFormatter(datePattern, formatLong2)).replace("{{time}}", timeLongFormatter(timePattern, formatLong2));
};
var longFormatters = {
p: timeLongFormatter,
P: dateTimeLongFormatter
};
// node_modules/date-fns/_lib/protectedTokens.js
var dayOfYearTokenRE = /^D+$/;
var weekYearTokenRE = /^Y+$/;
var throwTokens = ["D", "DD", "YY", "YYYY"];
function isProtectedDayOfYearToken(token) {
return dayOfYearTokenRE.test(token);
}
function isProtectedWeekYearToken(token) {
return weekYearTokenRE.test(token);
}
function warnOrThrowProtectedError(token, format6, input) {
const _message = message(token, format6, input);
console.warn(_message);
if (throwTokens.includes(token)) throw new RangeError(_message);
}
function message(token, format6, input) {
const subject = token[0] === "Y" ? "years" : "days of the month";
return `Use \`${token.toLowerCase()}\` instead of \`${token}\` (in \`${format6}\`) for formatting ${subject} to the input \`${input}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`;
}
// node_modules/date-fns/format.js
var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g;
var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
var escapedStringRegExp = /^'([^]*?)'?$/;
var doubleQuoteRegExp = /''/g;
var unescapedLatinCharacterRegExp = /[a-zA-Z]/;
function format(date, formatStr, options) {
const defaultOptions2 = getDefaultOptions();
const locale = options?.locale ?? defaultOptions2.locale ?? enUS;
const firstWeekContainsDate = options?.firstWeekContainsDate ?? options?.locale?.options?.firstWeekContainsDate ?? defaultOptions2.firstWeekContainsDate ?? defaultOptions2.locale?.options?.firstWeekContainsDate ?? 1;
const weekStartsOn = options?.weekStartsOn ?? options?.locale?.options?.weekStartsOn ?? defaultOptions2.weekStartsOn ?? defaultOptions2.locale?.options?.weekStartsOn ?? 0;
const originalDate = toDate(date, options?.in);
if (!isValid(originalDate)) {
throw new RangeError("Invalid time value");
}
let parts = formatStr.match(longFormattingTokensRegExp).map((substring) => {
const firstCharacter = substring[0];
if (firstCharacter === "p" || firstCharacter === "P") {
const longFormatter = longFormatters[firstCharacter];
return longFormatter(substring, locale.formatLong);
}
return substring;
}).join("").match(formattingTokensRegExp).map((substring) => {
if (substring === "''") {
return { isToken: false, value: "'" };
}
const firstCharacter = substring[0];
if (firstCharacter === "'") {
return { isToken: false, value: cleanEscapedString(substring) };
}
if (formatters[firstCharacter]) {
return { isToken: true, value: substring };
}
if (firstCharacter.match(unescapedLatinCharacterRegExp)) {
throw new RangeError(
"Format string contains an unescaped latin alphabet character `" + firstCharacter + "`"
);
}
return { isToken: false, value: substring };
});
if (locale.localize.preprocessor) {
parts = locale.localize.preprocessor(originalDate, parts);
}
const formatterOptions = {
firstWeekContainsDate,
weekStartsOn,
locale
};
return parts.map((part) => {
if (!part.isToken) return part.value;
const token = part.value;
if (!options?.useAdditionalWeekYearTokens && isProtectedWeekYearToken(token) || !options?.useAdditionalDayOfYearTokens && isProtectedDayOfYearToken(token)) {
warnOrThrowProtectedError(token, formatStr, String(date));
}
const formatter = formatters[token[0]];
return formatter(originalDate, token, locale.localize, formatterOptions);
}).join("");
}
function cleanEscapedString(input) {
const matched = input.match(escapedStringRegExp);
if (!matched) {
return input;
}
return matched[1].replace(doubleQuoteRegExp, "'");
}
// node_modules/date-fns/subDays.js
function subDays(date, amount, options) {
return addDays(date, -amount, options);
}
// node_modules/date-fns/subMonths.js
function subMonths(date, amount, options) {
return addMonths(date, -amount, options);
}
// node_modules/date-fns/subWeeks.js
function subWeeks(date, amount, options) {
return addWeeks(date, -amount, options);
}
// node_modules/date-fns/subYears.js
function subYears(date, amount, options) {
return addYears(date, -amount, options);
}
// packages/dataviews/build-module/utils/operators.mjs
var import_i18n220 = __toESM(require_i18n(), 1);
var import_element279 = __toESM(require_element(), 1);
var import_date3 = __toESM(require_date(), 1);
var import_jsx_runtime467 = __toESM(require_jsx_runtime(), 1);
var filterTextWrappers = {
Name: /* @__PURE__ */ (0, import_jsx_runtime467.jsx)("span", { className: "dataviews-filters__summary-filter-text-name" }),
Value: /* @__PURE__ */ (0, import_jsx_runtime467.jsx)("span", { className: "dataviews-filters__summary-filter-text-value" })
};
function getRelativeDate(value, unit) {
switch (unit) {
case "days":
return subDays(/* @__PURE__ */ new Date(), value);
case "weeks":
return subWeeks(/* @__PURE__ */ new Date(), value);
case "months":
return subMonths(/* @__PURE__ */ new Date(), value);
case "years":
return subYears(/* @__PURE__ */ new Date(), value);
default:
return /* @__PURE__ */ new Date();
}
}
var isNoneOperatorDefinition = {
/* translators: DataViews operator name */
label: (0, import_i18n220.__)("Is none of"),
filterText: (filter, activeElements) => (0, import_element279.createInterpolateElement)(
(0, import_i18n220.sprintf)(
/* translators: 1: Filter name (e.g. "Author"). 2: Filter value (e.g. "Admin"): "Author is none of: Admin, Editor". */
(0, import_i18n220.__)("<Name>%1$s is none of: </Name><Value>%2$s</Value>"),
filter.name,
activeElements.map((element) => element.label).join(", ")
),
filterTextWrappers
),
filter: ((item, field, filterValue) => {
if (!filterValue?.length) {
return true;
}
const fieldValue = field.getValue({ item });
if (Array.isArray(fieldValue)) {
return !filterValue.some(
(fv) => fieldValue.includes(fv)
);
} else if (typeof fieldValue === "string") {
return !filterValue.includes(fieldValue);
}
return false;
}),
selection: "multi"
};
var OPERATORS = [
{
name: OPERATOR_IS_ANY,
/* translators: DataViews operator name */
label: (0, import_i18n220.__)("Includes"),
filterText: (filter, activeElements) => (0, import_element279.createInterpolateElement)(
(0, import_i18n220.sprintf)(
/* translators: 1: Filter name (e.g. "Author"). 2: Filter value (e.g. "Admin"): "Author is any: Admin, Editor". */
(0, import_i18n220.__)("<Name>%1$s includes: </Name><Value>%2$s</Value>"),
filter.name,
activeElements.map((element) => element.label).join(", ")
),
filterTextWrappers
),
filter(item, field, filterValue) {
if (!filterValue?.length) {
return true;
}
const fieldValue = field.getValue({ item });
if (Array.isArray(fieldValue)) {
return filterValue.some(
(fv) => fieldValue.includes(fv)
);
} else if (typeof fieldValue === "string") {
return filterValue.includes(fieldValue);
}
return false;
},
selection: "multi"
},
{
name: OPERATOR_IS_NONE,
...isNoneOperatorDefinition
},
{
name: OPERATOR_IS_ALL,
/* translators: DataViews operator name */
label: (0, import_i18n220.__)("Includes all"),
filterText: (filter, activeElements) => (0, import_element279.createInterpolateElement)(
(0, import_i18n220.sprintf)(
/* translators: 1: Filter name (e.g. "Author"). 2: Filter value (e.g. "Admin"): "Author includes all: Admin, Editor". */
(0, import_i18n220.__)("<Name>%1$s includes all: </Name><Value>%2$s</Value>"),
filter.name,
activeElements.map((element) => element.label).join(", ")
),
filterTextWrappers
),
filter(item, field, filterValue) {
if (!filterValue?.length) {
return true;
}
return filterValue.every((value) => {
return field.getValue({ item })?.includes(value);
});
},
selection: "multi"
},
{
name: OPERATOR_IS_NOT_ALL,
...isNoneOperatorDefinition
},
{
name: OPERATOR_BETWEEN,
/* translators: DataViews operator name */
label: (0, import_i18n220.__)("Between (inc)"),
filterText: (filter, activeElements) => (0, import_element279.createInterpolateElement)(
(0, import_i18n220.sprintf)(
/* translators: 1: Filter name (e.g. "Item count"). 2: Filter value min. 3: Filter value max. e.g.: "Item count between (inc): 10 and 180". */
(0, import_i18n220.__)(
"<Name>%1$s between (inc): </Name><Value>%2$s and %3$s</Value>"
),
filter.name,
activeElements[0].label[0],
activeElements[0].label[1]
),
filterTextWrappers
),
filter(item, field, filterValue) {
if (!Array.isArray(filterValue) || filterValue.length !== 2 || filterValue[0] === void 0 || filterValue[1] === void 0) {
return true;
}
const fieldValue = field.getValue({ item });
if (typeof fieldValue === "number" || fieldValue instanceof Date || typeof fieldValue === "string") {
return fieldValue >= filterValue[0] && fieldValue <= filterValue[1];
}
return false;
},
selection: "custom"
},
{
name: OPERATOR_IN_THE_PAST,
/* translators: DataViews operator name */
label: (0, import_i18n220.__)("In the past"),
filterText: (filter, activeElements) => (0, import_element279.createInterpolateElement)(
(0, import_i18n220.sprintf)(
/* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "7 days"): "Date is in the past: 7 days". */
(0, import_i18n220.__)(
"<Name>%1$s is in the past: </Name><Value>%2$s</Value>"
),
filter.name,
`${activeElements[0].value.value} ${activeElements[0].value.unit}`
),
filterTextWrappers
),
filter(item, field, filterValue) {
if (filterValue?.value === void 0 || filterValue?.unit === void 0) {
return true;
}
const targetDate = getRelativeDate(
filterValue.value,
filterValue.unit
);
const fieldValue = (0, import_date3.getDate)(field.getValue({ item }));
return fieldValue >= targetDate && fieldValue <= /* @__PURE__ */ new Date();
},
selection: "custom"
},
{
name: OPERATOR_OVER,
/* translators: DataViews operator name */
label: (0, import_i18n220.__)("Over"),
filterText: (filter, activeElements) => (0, import_element279.createInterpolateElement)(
(0, import_i18n220.sprintf)(
/* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "7 days"): "Date is over: 7 days". */
(0, import_i18n220.__)("<Name>%1$s is over: </Name><Value>%2$s</Value>"),
filter.name,
`${activeElements[0].value.value} ${activeElements[0].value.unit}`
),
filterTextWrappers
),
filter(item, field, filterValue) {
if (filterValue?.value === void 0 || filterValue?.unit === void 0) {
return true;
}
const targetDate = getRelativeDate(
filterValue.value,
filterValue.unit
);
const fieldValue = (0, import_date3.getDate)(field.getValue({ item }));
return fieldValue < targetDate;
},
selection: "custom"
},
{
name: OPERATOR_IS,
/* translators: DataViews operator name */
label: (0, import_i18n220.__)("Is"),
filterText: (filter, activeElements) => (0, import_element279.createInterpolateElement)(
(0, import_i18n220.sprintf)(
/* translators: 1: Filter name (e.g. "Author"). 2: Filter value (e.g. "Admin"): "Author is: Admin". */
(0, import_i18n220.__)("<Name>%1$s is: </Name><Value>%2$s</Value>"),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
filter(item, field, filterValue) {
return filterValue === field.getValue({ item }) || filterValue === void 0;
},
selection: "single"
},
{
name: OPERATOR_IS_NOT,
/* translators: DataViews operator name */
label: (0, import_i18n220.__)("Is not"),
filterText: (filter, activeElements) => (0, import_element279.createInterpolateElement)(
(0, import_i18n220.sprintf)(
/* translators: 1: Filter name (e.g. "Author"). 2: Filter value (e.g. "Admin"): "Author is not: Admin". */
(0, import_i18n220.__)("<Name>%1$s is not: </Name><Value>%2$s</Value>"),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
filter(item, field, filterValue) {
return filterValue !== field.getValue({ item });
},
selection: "single"
},
{
name: OPERATOR_LESS_THAN,
/* translators: DataViews operator name */
label: (0, import_i18n220.__)("Less than"),
filterText: (filter, activeElements) => (0, import_element279.createInterpolateElement)(
(0, import_i18n220.sprintf)(
/* translators: 1: Filter name (e.g. "Count"). 2: Filter value (e.g. "10"): "Count is less than: 10". */
(0, import_i18n220.__)("<Name>%1$s is less than: </Name><Value>%2$s</Value>"),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
filter(item, field, filterValue) {
if (filterValue === void 0) {
return true;
}
const fieldValue = field.getValue({ item });
return fieldValue < filterValue;
},
selection: "single"
},
{
name: OPERATOR_GREATER_THAN,
/* translators: DataViews operator name */
label: (0, import_i18n220.__)("Greater than"),
filterText: (filter, activeElements) => (0, import_element279.createInterpolateElement)(
(0, import_i18n220.sprintf)(
/* translators: 1: Filter name (e.g. "Count"). 2: Filter value (e.g. "10"): "Count is greater than: 10". */
(0, import_i18n220.__)(
"<Name>%1$s is greater than: </Name><Value>%2$s</Value>"
),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
filter(item, field, filterValue) {
if (filterValue === void 0) {
return true;
}
const fieldValue = field.getValue({ item });
return fieldValue > filterValue;
},
selection: "single"
},
{
name: OPERATOR_LESS_THAN_OR_EQUAL,
/* translators: DataViews operator name */
label: (0, import_i18n220.__)("Less than or equal"),
filterText: (filter, activeElements) => (0, import_element279.createInterpolateElement)(
(0, import_i18n220.sprintf)(
/* translators: 1: Filter name (e.g. "Count"). 2: Filter value (e.g. "10"): "Count is less than or equal to: 10". */
(0, import_i18n220.__)(
"<Name>%1$s is less than or equal to: </Name><Value>%2$s</Value>"
),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
filter(item, field, filterValue) {
if (filterValue === void 0) {
return true;
}
const fieldValue = field.getValue({ item });
return fieldValue <= filterValue;
},
selection: "single"
},
{
name: OPERATOR_GREATER_THAN_OR_EQUAL,
/* translators: DataViews operator name */
label: (0, import_i18n220.__)("Greater than or equal"),
filterText: (filter, activeElements) => (0, import_element279.createInterpolateElement)(
(0, import_i18n220.sprintf)(
/* translators: 1: Filter name (e.g. "Count"). 2: Filter value (e.g. "10"): "Count is greater than or equal to: 10". */
(0, import_i18n220.__)(
"<Name>%1$s is greater than or equal to: </Name><Value>%2$s</Value>"
),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
filter(item, field, filterValue) {
if (filterValue === void 0) {
return true;
}
const fieldValue = field.getValue({ item });
return fieldValue >= filterValue;
},
selection: "single"
},
{
name: OPERATOR_BEFORE,
/* translators: DataViews operator name */
label: (0, import_i18n220.__)("Before"),
filterText: (filter, activeElements) => (0, import_element279.createInterpolateElement)(
(0, import_i18n220.sprintf)(
/* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "2024-01-01"): "Date is before: 2024-01-01". */
(0, import_i18n220.__)("<Name>%1$s is before: </Name><Value>%2$s</Value>"),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
filter(item, field, filterValue) {
if (filterValue === void 0) {
return true;
}
const filterDate = (0, import_date3.getDate)(filterValue);
const fieldDate = (0, import_date3.getDate)(field.getValue({ item }));
return fieldDate < filterDate;
},
selection: "single"
},
{
name: OPERATOR_AFTER,
/* translators: DataViews operator name */
label: (0, import_i18n220.__)("After"),
filterText: (filter, activeElements) => (0, import_element279.createInterpolateElement)(
(0, import_i18n220.sprintf)(
/* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "2024-01-01"): "Date is after: 2024-01-01". */
(0, import_i18n220.__)("<Name>%1$s is after: </Name><Value>%2$s</Value>"),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
filter(item, field, filterValue) {
if (filterValue === void 0) {
return true;
}
const filterDate = (0, import_date3.getDate)(filterValue);
const fieldDate = (0, import_date3.getDate)(field.getValue({ item }));
return fieldDate > filterDate;
},
selection: "single"
},
{
name: OPERATOR_BEFORE_INC,
/* translators: DataViews operator name */
label: (0, import_i18n220.__)("Before (inc)"),
filterText: (filter, activeElements) => (0, import_element279.createInterpolateElement)(
(0, import_i18n220.sprintf)(
/* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "2024-01-01"): "Date is on or before: 2024-01-01". */
(0, import_i18n220.__)(
"<Name>%1$s is on or before: </Name><Value>%2$s</Value>"
),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
filter(item, field, filterValue) {
if (filterValue === void 0) {
return true;
}
const filterDate = (0, import_date3.getDate)(filterValue);
const fieldDate = (0, import_date3.getDate)(field.getValue({ item }));
return fieldDate <= filterDate;
},
selection: "single"
},
{
name: OPERATOR_AFTER_INC,
/* translators: DataViews operator name */
label: (0, import_i18n220.__)("After (inc)"),
filterText: (filter, activeElements) => (0, import_element279.createInterpolateElement)(
(0, import_i18n220.sprintf)(
/* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "2024-01-01"): "Date is on or after: 2024-01-01". */
(0, import_i18n220.__)(
"<Name>%1$s is on or after: </Name><Value>%2$s</Value>"
),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
filter(item, field, filterValue) {
if (filterValue === void 0) {
return true;
}
const filterDate = (0, import_date3.getDate)(filterValue);
const fieldDate = (0, import_date3.getDate)(field.getValue({ item }));
return fieldDate >= filterDate;
},
selection: "single"
},
{
name: OPERATOR_CONTAINS,
/* translators: DataViews operator name */
label: (0, import_i18n220.__)("Contains"),
filterText: (filter, activeElements) => (0, import_element279.createInterpolateElement)(
(0, import_i18n220.sprintf)(
/* translators: 1: Filter name (e.g. "Title"). 2: Filter value (e.g. "Hello"): "Title contains: Hello". */
(0, import_i18n220.__)("<Name>%1$s contains: </Name><Value>%2$s</Value>"),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
filter(item, field, filterValue) {
if (filterValue === void 0) {
return true;
}
const fieldValue = field.getValue({ item });
return typeof fieldValue === "string" && filterValue && fieldValue.toLowerCase().includes(String(filterValue).toLowerCase());
},
selection: "single"
},
{
name: OPERATOR_NOT_CONTAINS,
/* translators: DataViews operator name */
label: (0, import_i18n220.__)("Doesn't contain"),
filterText: (filter, activeElements) => (0, import_element279.createInterpolateElement)(
(0, import_i18n220.sprintf)(
/* translators: 1: Filter name (e.g. "Title"). 2: Filter value (e.g. "Hello"): "Title doesn't contain: Hello". */
(0, import_i18n220.__)(
"<Name>%1$s doesn't contain: </Name><Value>%2$s</Value>"
),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
filter(item, field, filterValue) {
if (filterValue === void 0) {
return true;
}
const fieldValue = field.getValue({ item });
return typeof fieldValue === "string" && filterValue && !fieldValue.toLowerCase().includes(String(filterValue).toLowerCase());
},
selection: "single"
},
{
name: OPERATOR_STARTS_WITH,
/* translators: DataViews operator name */
label: (0, import_i18n220.__)("Starts with"),
filterText: (filter, activeElements) => (0, import_element279.createInterpolateElement)(
(0, import_i18n220.sprintf)(
/* translators: 1: Filter name (e.g. "Title"). 2: Filter value (e.g. "Hello"): "Title starts with: Hello". */
(0, import_i18n220.__)("<Name>%1$s starts with: </Name><Value>%2$s</Value>"),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
filter(item, field, filterValue) {
if (filterValue === void 0) {
return true;
}
const fieldValue = field.getValue({ item });
return typeof fieldValue === "string" && filterValue && fieldValue.toLowerCase().startsWith(String(filterValue).toLowerCase());
},
selection: "single"
},
{
name: OPERATOR_ON,
/* translators: DataViews operator name */
label: (0, import_i18n220.__)("On"),
filterText: (filter, activeElements) => (0, import_element279.createInterpolateElement)(
(0, import_i18n220.sprintf)(
/* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "2024-01-01"): "Date is: 2024-01-01". */
(0, import_i18n220.__)("<Name>%1$s is: </Name><Value>%2$s</Value>"),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
filter(item, field, filterValue) {
if (filterValue === void 0) {
return true;
}
const filterDate = (0, import_date3.getDate)(filterValue);
const fieldDate = (0, import_date3.getDate)(field.getValue({ item }));
return filterDate.getTime() === fieldDate.getTime();
},
selection: "single"
},
{
name: OPERATOR_NOT_ON,
/* translators: DataViews operator name */
label: (0, import_i18n220.__)("Not on"),
filterText: (filter, activeElements) => (0, import_element279.createInterpolateElement)(
(0, import_i18n220.sprintf)(
/* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "2024-01-01"): "Date is not: 2024-01-01". */
(0, import_i18n220.__)("<Name>%1$s is not: </Name><Value>%2$s</Value>"),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
filter(item, field, filterValue) {
if (filterValue === void 0) {
return true;
}
const filterDate = (0, import_date3.getDate)(filterValue);
const fieldDate = (0, import_date3.getDate)(field.getValue({ item }));
return filterDate.getTime() !== fieldDate.getTime();
},
selection: "single"
}
];
var getOperatorByName = (name) => OPERATORS.find((op) => op.name === name);
var getAllOperatorNames = () => OPERATORS.map((op) => op.name);
// packages/dataviews/build-module/components/dataform-controls/checkbox.mjs
var import_components234 = __toESM(require_components(), 1);
var import_element280 = __toESM(require_element(), 1);
// packages/dataviews/build-module/components/dataform-controls/utils/get-custom-validity.mjs
function getCustomValidity(isValid2, validity) {
let customValidity;
if (isValid2?.required && validity?.required) {
customValidity = validity?.required?.message ? validity.required : void 0;
} else if (isValid2?.pattern && validity?.pattern) {
customValidity = validity.pattern;
} else if (isValid2?.min && validity?.min) {
customValidity = validity.min;
} else if (isValid2?.max && validity?.max) {
customValidity = validity.max;
} else if (isValid2?.minLength && validity?.minLength) {
customValidity = validity.minLength;
} else if (isValid2?.maxLength && validity?.maxLength) {
customValidity = validity.maxLength;
} else if (isValid2?.elements && validity?.elements) {
customValidity = validity.elements;
} else if (validity?.custom) {
customValidity = validity.custom;
}
return customValidity;
}
// packages/dataviews/build-module/components/dataform-controls/checkbox.mjs
var import_jsx_runtime468 = __toESM(require_jsx_runtime(), 1);
var { ValidatedCheckboxControl } = unlock4(import_components234.privateApis);
function Checkbox({
field,
onChange,
data,
hideLabelFromVision,
markWhenOptional,
validity
}) {
const { getValue, setValue, label, description, isValid: isValid2 } = field;
const disabled2 = field.isDisabled({ item: data, field });
const onChangeControl = (0, import_element280.useCallback)(() => {
onChange(
setValue({ item: data, value: !getValue({ item: data }) })
);
}, [data, getValue, onChange, setValue]);
return /* @__PURE__ */ (0, import_jsx_runtime468.jsx)(
ValidatedCheckboxControl,
{
required: !!field.isValid?.required,
markWhenOptional,
customValidity: getCustomValidity(isValid2, validity),
hidden: hideLabelFromVision,
label,
help: description,
checked: getValue({ item: data }),
onChange: onChangeControl,
disabled: disabled2
}
);
}
// packages/dataviews/build-module/components/dataform-controls/combobox.mjs
var import_components235 = __toESM(require_components(), 1);
var import_element281 = __toESM(require_element(), 1);
var import_jsx_runtime469 = __toESM(require_jsx_runtime(), 1);
var { ValidatedComboboxControl } = unlock4(import_components235.privateApis);
function Combobox({
data,
field,
onChange,
hideLabelFromVision,
validity
}) {
const { label, description, placeholder, getValue, setValue, isValid: isValid2 } = field;
const value = getValue({ item: data }) ?? "";
const onChangeControl = (0, import_element281.useCallback)(
(newValue) => onChange(setValue({ item: data, value: newValue ?? "" })),
[data, onChange, setValue]
);
const { elements, isLoading } = useElements({
elements: field.elements,
getElements: field.getElements
});
if (isLoading) {
return /* @__PURE__ */ (0, import_jsx_runtime469.jsx)(import_components235.Spinner, {});
}
return /* @__PURE__ */ (0, import_jsx_runtime469.jsx)(
ValidatedComboboxControl,
{
required: !!field.isValid?.required,
customValidity: getCustomValidity(isValid2, validity),
label,
value,
help: description,
placeholder,
options: elements,
onChange: onChangeControl,
hideLabelFromVision,
allowReset: true,
expandOnFocus: true
}
);
}
// packages/dataviews/build-module/components/dataform-controls/datetime.mjs
var import_components237 = __toESM(require_components(), 1);
var import_element284 = __toESM(require_element(), 1);
var import_i18n222 = __toESM(require_i18n(), 1);
var import_date5 = __toESM(require_date(), 1);
// packages/dataviews/build-module/components/dataform-controls/utils/relative-date-control.mjs
var import_components236 = __toESM(require_components(), 1);
var import_element282 = __toESM(require_element(), 1);
var import_i18n221 = __toESM(require_i18n(), 1);
var import_jsx_runtime470 = __toESM(require_jsx_runtime(), 1);
var TIME_UNITS_OPTIONS = {
[OPERATOR_IN_THE_PAST]: [
{ value: "days", label: (0, import_i18n221.__)("Days") },
{ value: "weeks", label: (0, import_i18n221.__)("Weeks") },
{ value: "months", label: (0, import_i18n221.__)("Months") },
{ value: "years", label: (0, import_i18n221.__)("Years") }
],
[OPERATOR_OVER]: [
{ value: "days", label: (0, import_i18n221.__)("Days ago") },
{ value: "weeks", label: (0, import_i18n221.__)("Weeks ago") },
{ value: "months", label: (0, import_i18n221.__)("Months ago") },
{ value: "years", label: (0, import_i18n221.__)("Years ago") }
]
};
function RelativeDateControl({
className,
data,
field,
onChange,
hideLabelFromVision,
operator
}) {
const options = TIME_UNITS_OPTIONS[operator === OPERATOR_IN_THE_PAST ? "inThePast" : "over"];
const { id, label, description, getValue, setValue } = field;
const disabled2 = field.isDisabled({ item: data, field });
const fieldValue = getValue({ item: data });
const { value: relValue = "", unit = options[0].value } = fieldValue && typeof fieldValue === "object" ? fieldValue : {};
const onChangeValue = (0, import_element282.useCallback)(
(newValue) => onChange(
setValue({
item: data,
value: { value: Number(newValue), unit }
})
),
[onChange, setValue, data, unit]
);
const onChangeUnit = (0, import_element282.useCallback)(
(newUnit) => onChange(
setValue({
item: data,
value: { value: relValue, unit: newUnit }
})
),
[onChange, setValue, data, relValue]
);
return /* @__PURE__ */ (0, import_jsx_runtime470.jsx)(
import_components236.BaseControl,
{
id,
className: clsx_default(className, "dataviews-controls__relative-date"),
label,
hideLabelFromVision,
help: description,
children: /* @__PURE__ */ (0, import_jsx_runtime470.jsxs)(Stack, { direction: "row", gap: "sm", children: [
/* @__PURE__ */ (0, import_jsx_runtime470.jsx)(
import_components236.__experimentalNumberControl,
{
className: "dataviews-controls__relative-date-number",
spinControls: "none",
min: 1,
step: 1,
value: relValue,
onChange: onChangeValue,
disabled: disabled2
}
),
/* @__PURE__ */ (0, import_jsx_runtime470.jsx)(
import_components236.SelectControl,
{
className: "dataviews-controls__relative-date-unit",
label: (0, import_i18n221.__)("Unit"),
value: unit,
options,
onChange: onChangeUnit,
hideLabelFromVision: true,
disabled: disabled2
}
)
] })
}
);
}
// packages/dataviews/build-module/components/dataform-controls/utils/use-disabled-date-matchers.mjs
var import_element283 = __toESM(require_element(), 1);
function useDisabledDateMatchers(isValid2, parseDateFn) {
const minConstraint = typeof isValid2.min?.constraint === "string" ? isValid2.min.constraint : void 0;
const maxConstraint = typeof isValid2.max?.constraint === "string" ? isValid2.max.constraint : void 0;
const disabledMatchers = (0, import_element283.useMemo)(() => {
const matchers = [];
if (minConstraint) {
const minDate = parseDateFn(minConstraint);
if (minDate) {
matchers.push({ before: minDate });
}
}
if (maxConstraint) {
const maxDate = parseDateFn(maxConstraint);
if (maxDate) {
matchers.push({ after: maxDate });
}
}
return matchers.length > 0 ? matchers : void 0;
}, [minConstraint, maxConstraint, parseDateFn]);
return { minConstraint, maxConstraint, disabledMatchers };
}
// packages/dataviews/build-module/field-types/utils/parse-date-time.mjs
var import_date4 = __toESM(require_date(), 1);
function parseDateTime(dateTimeString) {
if (!dateTimeString) {
return null;
}
const parsed = (0, import_date4.getDate)(dateTimeString);
return parsed && isValid(parsed) ? parsed : null;
}
// packages/dataviews/build-module/components/dataform-controls/datetime.mjs
var import_jsx_runtime471 = __toESM(require_jsx_runtime(), 1);
var { DateCalendar, ValidatedInputControl: ValidatedInputControl2 } = unlock4(import_components237.privateApis);
var formatDateTime = (value) => {
if (!value) {
return "";
}
return (0, import_date5.dateI18n)("Y-m-d\\TH:i", (0, import_date5.getDate)(value));
};
function CalendarDateTimeControl({
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
validity,
config: config2
}) {
const { compact } = config2 || {};
const { id, label, description, setValue, getValue, isValid: isValid2 } = field;
const disabled2 = field.isDisabled({ item: data, field });
const fieldValue = getValue({ item: data });
const value = typeof fieldValue === "string" ? fieldValue : void 0;
const [calendarMonth, setCalendarMonth] = (0, import_element284.useState)(() => {
const parsedDate = parseDateTime(value);
return parsedDate || /* @__PURE__ */ new Date();
});
const inputControlRef = (0, import_element284.useRef)(null);
const validationTimeoutRef = (0, import_element284.useRef)(void 0);
const previousFocusRef = (0, import_element284.useRef)(null);
const { minConstraint, maxConstraint, disabledMatchers } = useDisabledDateMatchers(isValid2, parseDateTime);
const onChangeCallback = (0, import_element284.useCallback)(
(newValue) => onChange(setValue({ item: data, value: newValue })),
[data, onChange, setValue]
);
(0, import_element284.useEffect)(() => {
return () => {
if (validationTimeoutRef.current) {
clearTimeout(validationTimeoutRef.current);
}
};
}, []);
const onSelectDate = (0, import_element284.useCallback)(
(newDate) => {
let dateTimeValue;
if (newDate) {
const wpDate = (0, import_date5.dateI18n)("Y-m-d", newDate);
let wpTime;
if (value) {
wpTime = (0, import_date5.dateI18n)("H:i", (0, import_date5.getDate)(value));
} else {
wpTime = (0, import_date5.dateI18n)("H:i", newDate);
}
const finalDateTime = (0, import_date5.getDate)(`${wpDate}T${wpTime}`);
dateTimeValue = finalDateTime.toISOString();
onChangeCallback(dateTimeValue);
if (validationTimeoutRef.current) {
clearTimeout(validationTimeoutRef.current);
}
} else {
onChangeCallback(void 0);
}
previousFocusRef.current = inputControlRef.current && inputControlRef.current.ownerDocument.activeElement;
validationTimeoutRef.current = setTimeout(() => {
if (inputControlRef.current) {
inputControlRef.current.focus();
inputControlRef.current.blur();
onChangeCallback(dateTimeValue);
if (previousFocusRef.current && previousFocusRef.current instanceof HTMLElement) {
previousFocusRef.current.focus();
}
}
}, 0);
},
[onChangeCallback, value]
);
const handleManualDateTimeChange = (0, import_element284.useCallback)(
(newValue) => {
if (newValue) {
const dateTime = (0, import_date5.getDate)(newValue);
onChangeCallback(dateTime.toISOString());
const parsedDate = parseDateTime(dateTime.toISOString());
if (parsedDate) {
setCalendarMonth(parsedDate);
}
} else {
onChangeCallback(void 0);
}
},
[onChangeCallback]
);
const { format: fieldFormat } = field;
const weekStartsOn = fieldFormat.weekStartsOn ?? (0, import_date5.getSettings)().l10n.startOfWeek;
const {
timezone: { string: timezoneString }
} = (0, import_date5.getSettings)();
let displayLabel = label;
if (isValid2?.required && !markWhenOptional && !hideLabelFromVision) {
displayLabel = `${label} (${(0, import_i18n222.__)("Required")})`;
} else if (!isValid2?.required && markWhenOptional && !hideLabelFromVision) {
displayLabel = `${label} (${(0, import_i18n222.__)("Optional")})`;
}
return /* @__PURE__ */ (0, import_jsx_runtime471.jsx)(
import_components237.BaseControl,
{
id,
label: displayLabel,
help: description,
hideLabelFromVision,
children: /* @__PURE__ */ (0, import_jsx_runtime471.jsxs)(Stack, { direction: "column", gap: "lg", children: [
/* @__PURE__ */ (0, import_jsx_runtime471.jsx)(
ValidatedInputControl2,
{
ref: inputControlRef,
required: !!isValid2?.required,
customValidity: getCustomValidity(isValid2, validity),
type: "datetime-local",
label: (0, import_i18n222.__)("Date time"),
hideLabelFromVision: true,
value: formatDateTime(value),
onChange: handleManualDateTimeChange,
disabled: disabled2,
min: minConstraint ? formatDateTime(minConstraint) : void 0,
max: maxConstraint ? formatDateTime(maxConstraint) : void 0
}
),
!compact && /* @__PURE__ */ (0, import_jsx_runtime471.jsx)(
DateCalendar,
{
style: { width: "100%" },
selected: value ? parseDateTime(value) || void 0 : void 0,
onSelect: onSelectDate,
month: calendarMonth,
onMonthChange: setCalendarMonth,
timeZone: timezoneString || void 0,
weekStartsOn,
disabled: disabled2 || disabledMatchers
}
)
] })
}
);
}
function DateTime({
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
operator,
validity,
config: config2
}) {
if (operator === OPERATOR_IN_THE_PAST || operator === OPERATOR_OVER) {
return /* @__PURE__ */ (0, import_jsx_runtime471.jsx)(
RelativeDateControl,
{
className: "dataviews-controls__datetime",
data,
field,
onChange,
hideLabelFromVision,
operator
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime471.jsx)(
CalendarDateTimeControl,
{
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
validity,
config: config2
}
);
}
// packages/dataviews/build-module/components/dataform-controls/date.mjs
var import_components238 = __toESM(require_components(), 1);
var import_a11y22 = __toESM(require_a11y(), 1);
var import_element285 = __toESM(require_element(), 1);
var import_i18n223 = __toESM(require_i18n(), 1);
var import_date6 = __toESM(require_date(), 1);
var import_jsx_runtime472 = __toESM(require_jsx_runtime(), 1);
var { DateCalendar: DateCalendar2, DateRangeCalendar } = unlock4(import_components238.privateApis);
var DATE_PRESETS = [
{
id: "today",
label: (0, import_i18n223.__)("Today"),
getValue: () => (0, import_date6.getDate)(null)
},
{
id: "yesterday",
label: (0, import_i18n223.__)("Yesterday"),
getValue: () => {
const today = (0, import_date6.getDate)(null);
return subDays(today, 1);
}
},
{
id: "past-week",
label: (0, import_i18n223.__)("Past week"),
getValue: () => {
const today = (0, import_date6.getDate)(null);
return subDays(today, 7);
}
},
{
id: "past-month",
label: (0, import_i18n223.__)("Past month"),
getValue: () => {
const today = (0, import_date6.getDate)(null);
return subMonths(today, 1);
}
}
];
var DATE_RANGE_PRESETS = [
{
id: "last-7-days",
label: (0, import_i18n223.__)("Last 7 days"),
getValue: () => {
const today = (0, import_date6.getDate)(null);
return [subDays(today, 7), today];
}
},
{
id: "last-30-days",
label: (0, import_i18n223.__)("Last 30 days"),
getValue: () => {
const today = (0, import_date6.getDate)(null);
return [subDays(today, 30), today];
}
},
{
id: "month-to-date",
label: (0, import_i18n223.__)("Month to date"),
getValue: () => {
const today = (0, import_date6.getDate)(null);
return [startOfMonth(today), today];
}
},
{
id: "last-year",
label: (0, import_i18n223.__)("Last year"),
getValue: () => {
const today = (0, import_date6.getDate)(null);
return [subYears(today, 1), today];
}
},
{
id: "year-to-date",
label: (0, import_i18n223.__)("Year to date"),
getValue: () => {
const today = (0, import_date6.getDate)(null);
return [startOfYear(today), today];
}
}
];
var parseDate = (dateString) => {
if (!dateString) {
return null;
}
const parsed = (0, import_date6.getDate)(dateString);
return parsed && isValid(parsed) ? parsed : null;
};
var formatDate = (date) => {
if (!date) {
return "";
}
return typeof date === "string" ? date : format(date, "yyyy-MM-dd");
};
function ValidatedDateControl({
field,
validity,
inputRefs,
isTouched,
setIsTouched,
children
}) {
const { isValid: isValid2 } = field;
const [customValidity, setCustomValidity] = (0, import_element285.useState)(void 0);
const validateRefs = (0, import_element285.useCallback)(() => {
const refs = Array.isArray(inputRefs) ? inputRefs : [inputRefs];
for (const ref of refs) {
const input = ref.current;
if (input && !input.validity.valid) {
setCustomValidity({
type: "invalid",
message: input.validationMessage
});
return;
}
}
setCustomValidity(void 0);
}, [inputRefs]);
(0, import_element285.useEffect)(() => {
const refs = Array.isArray(inputRefs) ? inputRefs : [inputRefs];
const result = validity ? getCustomValidity(isValid2, validity) : void 0;
for (const ref of refs) {
const input = ref.current;
if (input) {
input.setCustomValidity(
result?.type === "invalid" && result.message ? result.message : ""
);
}
}
}, [inputRefs, isValid2, validity]);
(0, import_element285.useEffect)(() => {
const refs = Array.isArray(inputRefs) ? inputRefs : [inputRefs];
const handleInvalid = (event) => {
event.preventDefault();
setIsTouched(true);
};
for (const ref of refs) {
ref.current?.addEventListener("invalid", handleInvalid);
}
return () => {
for (const ref of refs) {
ref.current?.removeEventListener("invalid", handleInvalid);
}
};
}, [inputRefs, setIsTouched]);
(0, import_element285.useEffect)(() => {
if (!isTouched) {
return;
}
const result = validity ? getCustomValidity(isValid2, validity) : void 0;
if (result) {
setCustomValidity(result);
} else {
validateRefs();
}
}, [isTouched, isValid2, validity, validateRefs]);
(0, import_element285.useEffect)(() => {
if (isTouched && customValidity?.message) {
(0, import_a11y22.speak)(customValidity.message);
}
}, [isTouched, customValidity?.message]);
const onBlur = (event) => {
if (isTouched) {
return;
}
if (!event.relatedTarget || !event.currentTarget.contains(event.relatedTarget)) {
setIsTouched(true);
}
};
return /* @__PURE__ */ (0, import_jsx_runtime472.jsxs)("div", { onBlur, children: [
children,
customValidity && /* @__PURE__ */ (0, import_jsx_runtime472.jsxs)(
"p",
{
className: clsx_default(
"components-validated-control__indicator",
customValidity.type === "invalid" ? "is-invalid" : void 0
),
children: [
/* @__PURE__ */ (0, import_jsx_runtime472.jsx)(
import_components238.Icon,
{
className: "components-validated-control__indicator-icon",
icon: error_default,
size: 16,
fill: "currentColor"
}
),
customValidity.message
]
}
)
] });
}
function CalendarDateControl({
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
validity
}) {
const {
id,
label,
description,
setValue,
getValue,
isValid: isValid2,
format: fieldFormat
} = field;
const disabled2 = field.isDisabled({ item: data, field });
const [selectedPresetId, setSelectedPresetId] = (0, import_element285.useState)(
null
);
const weekStartsOn = fieldFormat.weekStartsOn ?? (0, import_date6.getSettings)().l10n.startOfWeek;
const fieldValue = getValue({ item: data });
const value = typeof fieldValue === "string" ? fieldValue : void 0;
const [calendarMonth, setCalendarMonth] = (0, import_element285.useState)(() => {
const parsedDate = parseDate(value);
return parsedDate || /* @__PURE__ */ new Date();
});
const [isTouched, setIsTouched] = (0, import_element285.useState)(false);
const validityTargetRef = (0, import_element285.useRef)(null);
const { minConstraint, maxConstraint, disabledMatchers } = useDisabledDateMatchers(isValid2, parseDate);
const onChangeCallback = (0, import_element285.useCallback)(
(newValue) => onChange(setValue({ item: data, value: newValue })),
[data, onChange, setValue]
);
const onSelectDate = (0, import_element285.useCallback)(
(newDate) => {
const dateValue = newDate ? format(newDate, "yyyy-MM-dd") : void 0;
onChangeCallback(dateValue);
setSelectedPresetId(null);
setIsTouched(true);
},
[onChangeCallback]
);
const handlePresetClick = (0, import_element285.useCallback)(
(preset) => {
const presetDate = preset.getValue();
const dateValue = formatDate(presetDate);
setCalendarMonth(presetDate);
onChangeCallback(dateValue);
setSelectedPresetId(preset.id);
setIsTouched(true);
},
[onChangeCallback]
);
const handleManualDateChange = (0, import_element285.useCallback)(
(newValue) => {
onChangeCallback(newValue);
if (newValue) {
const parsedDate = parseDate(newValue);
if (parsedDate) {
setCalendarMonth(parsedDate);
}
}
setSelectedPresetId(null);
setIsTouched(true);
},
[onChangeCallback]
);
const {
timezone: { string: timezoneString }
} = (0, import_date6.getSettings)();
let displayLabel = label;
if (isValid2?.required && !markWhenOptional) {
displayLabel = `${label} (${(0, import_i18n223.__)("Required")})`;
} else if (!isValid2?.required && markWhenOptional) {
displayLabel = `${label} (${(0, import_i18n223.__)("Optional")})`;
}
return /* @__PURE__ */ (0, import_jsx_runtime472.jsx)(
ValidatedDateControl,
{
field,
validity,
inputRefs: validityTargetRef,
isTouched,
setIsTouched,
children: /* @__PURE__ */ (0, import_jsx_runtime472.jsx)(
import_components238.BaseControl,
{
id,
className: "dataviews-controls__date",
label: displayLabel,
help: description,
hideLabelFromVision,
children: /* @__PURE__ */ (0, import_jsx_runtime472.jsxs)(Stack, { direction: "column", gap: "lg", children: [
/* @__PURE__ */ (0, import_jsx_runtime472.jsxs)(
Stack,
{
direction: "row",
gap: "sm",
wrap: "wrap",
justify: "flex-start",
children: [
DATE_PRESETS.map((preset) => {
const isSelected = selectedPresetId === preset.id;
return /* @__PURE__ */ (0, import_jsx_runtime472.jsx)(
import_components238.Button,
{
className: "dataviews-controls__date-preset",
variant: "tertiary",
isPressed: isSelected,
size: "small",
disabled: disabled2,
accessibleWhenDisabled: true,
onClick: () => handlePresetClick(preset),
children: preset.label
},
preset.id
);
}),
/* @__PURE__ */ (0, import_jsx_runtime472.jsx)(
import_components238.Button,
{
className: "dataviews-controls__date-preset",
variant: "tertiary",
isPressed: !selectedPresetId,
size: "small",
disabled: !!selectedPresetId || disabled2,
accessibleWhenDisabled: true,
children: (0, import_i18n223.__)("Custom")
}
)
]
}
),
/* @__PURE__ */ (0, import_jsx_runtime472.jsx)(
import_components238.__experimentalInputControl,
{
ref: validityTargetRef,
type: "date",
label: (0, import_i18n223.__)("Date"),
hideLabelFromVision: true,
value,
onChange: handleManualDateChange,
required: !!field.isValid?.required,
disabled: disabled2,
min: minConstraint,
max: maxConstraint
}
),
/* @__PURE__ */ (0, import_jsx_runtime472.jsx)(
DateCalendar2,
{
style: { width: "100%" },
selected: value ? parseDate(value) || void 0 : void 0,
onSelect: onSelectDate,
month: calendarMonth,
onMonthChange: setCalendarMonth,
timeZone: timezoneString || void 0,
weekStartsOn,
disabled: disabled2 || disabledMatchers,
disableNavigation: disabled2
}
)
] })
}
)
}
);
}
function CalendarDateRangeControl({
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
validity
}) {
const {
id,
label,
description,
getValue,
setValue,
isValid: isValid2,
format: fieldFormat
} = field;
const disabled2 = field.isDisabled({ item: data, field });
let value;
const fieldValue = getValue({ item: data });
if (Array.isArray(fieldValue) && fieldValue.length === 2 && fieldValue.every((date) => typeof date === "string")) {
value = fieldValue;
}
const weekStartsOn = fieldFormat.weekStartsOn ?? (0, import_date6.getSettings)().l10n.startOfWeek;
const { minConstraint, maxConstraint, disabledMatchers } = useDisabledDateMatchers(isValid2, parseDate);
const onChangeCallback = (0, import_element285.useCallback)(
(newValue) => {
onChange(
setValue({
item: data,
value: newValue
})
);
},
[data, onChange, setValue]
);
const [selectedPresetId, setSelectedPresetId] = (0, import_element285.useState)(
null
);
const selectedRange = (0, import_element285.useMemo)(() => {
if (!value) {
return { from: void 0, to: void 0 };
}
const [from, to2] = value;
return {
from: parseDate(from) || void 0,
to: parseDate(to2) || void 0
};
}, [value]);
const [calendarMonth, setCalendarMonth] = (0, import_element285.useState)(() => {
return selectedRange.from || /* @__PURE__ */ new Date();
});
const [isTouched, setIsTouched] = (0, import_element285.useState)(false);
const fromInputRef = (0, import_element285.useRef)(null);
const toInputRef = (0, import_element285.useRef)(null);
const updateDateRange = (0, import_element285.useCallback)(
(fromDate, toDate2) => {
if (fromDate && toDate2) {
onChangeCallback([
formatDate(fromDate),
formatDate(toDate2)
]);
} else if (!fromDate && !toDate2) {
onChangeCallback(void 0);
}
},
[onChangeCallback]
);
const onSelectCalendarRange = (0, import_element285.useCallback)(
(newRange) => {
updateDateRange(newRange?.from, newRange?.to);
setSelectedPresetId(null);
setIsTouched(true);
},
[updateDateRange]
);
const handlePresetClick = (0, import_element285.useCallback)(
(preset) => {
const [startDate, endDate] = preset.getValue();
setCalendarMonth(startDate);
updateDateRange(startDate, endDate);
setSelectedPresetId(preset.id);
setIsTouched(true);
},
[updateDateRange]
);
const handleManualDateChange = (0, import_element285.useCallback)(
(fromOrTo, newValue) => {
const [currentFrom, currentTo] = value || [
void 0,
void 0
];
const updatedFrom = fromOrTo === "from" ? newValue : currentFrom;
const updatedTo = fromOrTo === "to" ? newValue : currentTo;
updateDateRange(updatedFrom, updatedTo);
if (newValue) {
const parsedDate = parseDate(newValue);
if (parsedDate) {
setCalendarMonth(parsedDate);
}
}
setSelectedPresetId(null);
setIsTouched(true);
},
[value, updateDateRange]
);
const { timezone } = (0, import_date6.getSettings)();
let displayLabel = label;
if (field.isValid?.required && !markWhenOptional) {
displayLabel = `${label} (${(0, import_i18n223.__)("Required")})`;
} else if (!field.isValid?.required && markWhenOptional) {
displayLabel = `${label} (${(0, import_i18n223.__)("Optional")})`;
}
return /* @__PURE__ */ (0, import_jsx_runtime472.jsx)(
ValidatedDateControl,
{
field,
validity,
inputRefs: [fromInputRef, toInputRef],
isTouched,
setIsTouched,
children: /* @__PURE__ */ (0, import_jsx_runtime472.jsx)(
import_components238.BaseControl,
{
id,
className: "dataviews-controls__date",
label: displayLabel,
help: description,
hideLabelFromVision,
children: /* @__PURE__ */ (0, import_jsx_runtime472.jsxs)(Stack, { direction: "column", gap: "lg", children: [
/* @__PURE__ */ (0, import_jsx_runtime472.jsxs)(
Stack,
{
direction: "row",
gap: "sm",
wrap: "wrap",
justify: "flex-start",
children: [
DATE_RANGE_PRESETS.map((preset) => {
const isSelected = selectedPresetId === preset.id;
return /* @__PURE__ */ (0, import_jsx_runtime472.jsx)(
import_components238.Button,
{
className: "dataviews-controls__date-preset",
variant: "tertiary",
isPressed: isSelected,
size: "small",
disabled: disabled2,
accessibleWhenDisabled: true,
onClick: () => handlePresetClick(preset),
children: preset.label
},
preset.id
);
}),
/* @__PURE__ */ (0, import_jsx_runtime472.jsx)(
import_components238.Button,
{
className: "dataviews-controls__date-preset",
variant: "tertiary",
isPressed: !selectedPresetId,
size: "small",
accessibleWhenDisabled: true,
disabled: !!selectedPresetId || disabled2,
children: (0, import_i18n223.__)("Custom")
}
)
]
}
),
/* @__PURE__ */ (0, import_jsx_runtime472.jsxs)(
Stack,
{
direction: "row",
gap: "sm",
justify: "space-between",
className: "dataviews-controls__date-range-inputs",
children: [
/* @__PURE__ */ (0, import_jsx_runtime472.jsx)(
import_components238.__experimentalInputControl,
{
ref: fromInputRef,
type: "date",
label: (0, import_i18n223.__)("From"),
hideLabelFromVision: true,
value: value?.[0],
onChange: (newValue) => handleManualDateChange("from", newValue),
required: !!field.isValid?.required,
disabled: disabled2,
min: minConstraint,
max: maxConstraint
}
),
/* @__PURE__ */ (0, import_jsx_runtime472.jsx)(
import_components238.__experimentalInputControl,
{
ref: toInputRef,
type: "date",
label: (0, import_i18n223.__)("To"),
hideLabelFromVision: true,
value: value?.[1],
onChange: (newValue) => handleManualDateChange("to", newValue),
required: !!field.isValid?.required,
disabled: disabled2,
min: minConstraint,
max: maxConstraint
}
)
]
}
),
/* @__PURE__ */ (0, import_jsx_runtime472.jsx)(
DateRangeCalendar,
{
style: { width: "100%" },
selected: selectedRange,
onSelect: onSelectCalendarRange,
month: calendarMonth,
onMonthChange: setCalendarMonth,
timeZone: timezone.string || void 0,
weekStartsOn,
disabled: disabled2 || disabledMatchers
}
)
] })
}
)
}
);
}
function DateControl({
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
operator,
validity
}) {
if (operator === OPERATOR_IN_THE_PAST || operator === OPERATOR_OVER) {
return /* @__PURE__ */ (0, import_jsx_runtime472.jsx)(
RelativeDateControl,
{
className: "dataviews-controls__date",
data,
field,
onChange,
hideLabelFromVision,
operator
}
);
}
if (operator === OPERATOR_BETWEEN) {
return /* @__PURE__ */ (0, import_jsx_runtime472.jsx)(
CalendarDateRangeControl,
{
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
validity
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime472.jsx)(
CalendarDateControl,
{
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
validity
}
);
}
// packages/dataviews/build-module/components/dataform-controls/select.mjs
var import_components239 = __toESM(require_components(), 1);
var import_element286 = __toESM(require_element(), 1);
var import_jsx_runtime473 = __toESM(require_jsx_runtime(), 1);
var { ValidatedSelectControl } = unlock4(import_components239.privateApis);
function Select({
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
validity
}) {
const { type, label, description, getValue, setValue, isValid: isValid2 } = field;
const disabled2 = field.isDisabled({ item: data, field });
const isMultiple = type === "array";
const value = getValue({ item: data }) ?? (isMultiple ? [] : "");
const onChangeControl = (0, import_element286.useCallback)(
(newValue) => onChange(setValue({ item: data, value: newValue })),
[data, onChange, setValue]
);
const { elements, isLoading } = useElements({
elements: field.elements,
getElements: field.getElements
});
if (isLoading) {
return /* @__PURE__ */ (0, import_jsx_runtime473.jsx)(import_components239.Spinner, {});
}
return /* @__PURE__ */ (0, import_jsx_runtime473.jsx)(
ValidatedSelectControl,
{
required: !!field.isValid?.required,
markWhenOptional,
customValidity: getCustomValidity(isValid2, validity),
label,
value,
help: description,
options: elements,
onChange: onChangeControl,
hideLabelFromVision,
multiple: isMultiple,
disabled: disabled2
}
);
}
// packages/dataviews/build-module/components/dataform-controls/adaptive-select.mjs
var import_jsx_runtime474 = __toESM(require_jsx_runtime(), 1);
var ELEMENTS_THRESHOLD = 10;
function AdaptiveSelect(props) {
const { field } = props;
const { elements } = useElements({
elements: field.elements,
getElements: field.getElements
});
if (elements.length >= ELEMENTS_THRESHOLD) {
return /* @__PURE__ */ (0, import_jsx_runtime474.jsx)(Combobox, { ...props });
}
return /* @__PURE__ */ (0, import_jsx_runtime474.jsx)(Select, { ...props });
}
// packages/dataviews/build-module/components/dataform-controls/email.mjs
var import_components241 = __toESM(require_components(), 1);
// packages/dataviews/build-module/components/dataform-controls/utils/validated-input.mjs
var import_components240 = __toESM(require_components(), 1);
var import_element287 = __toESM(require_element(), 1);
var import_jsx_runtime475 = __toESM(require_jsx_runtime(), 1);
var { ValidatedInputControl: ValidatedInputControl3 } = unlock4(import_components240.privateApis);
function ValidatedText({
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
type,
prefix: prefix2,
suffix,
validity
}) {
const { label, placeholder, description, getValue, setValue, isValid: isValid2 } = field;
const value = getValue({ item: data });
const disabled2 = field.isDisabled({ item: data, field });
const onChangeControl = (0, import_element287.useCallback)(
(newValue) => onChange(
setValue({
item: data,
value: newValue
})
),
[data, setValue, onChange]
);
return /* @__PURE__ */ (0, import_jsx_runtime475.jsx)(
ValidatedInputControl3,
{
required: !!isValid2.required,
markWhenOptional,
customValidity: getCustomValidity(isValid2, validity),
label,
placeholder,
value: value ?? "",
help: description,
onChange: onChangeControl,
hideLabelFromVision,
type,
prefix: prefix2,
suffix,
disabled: disabled2,
pattern: isValid2.pattern ? isValid2.pattern.constraint : void 0,
minLength: isValid2.minLength ? isValid2.minLength.constraint : void 0,
maxLength: isValid2.maxLength ? isValid2.maxLength.constraint : void 0
}
);
}
// packages/dataviews/build-module/components/dataform-controls/email.mjs
var import_jsx_runtime476 = __toESM(require_jsx_runtime(), 1);
function Email({
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
validity
}) {
return /* @__PURE__ */ (0, import_jsx_runtime476.jsx)(
ValidatedText,
{
...{
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
validity,
type: "email",
prefix: /* @__PURE__ */ (0, import_jsx_runtime476.jsx)(import_components241.__experimentalInputControlPrefixWrapper, { variant: "icon", children: /* @__PURE__ */ (0, import_jsx_runtime476.jsx)(import_components241.Icon, { icon: envelope_default }) })
}
}
);
}
// packages/dataviews/build-module/components/dataform-controls/telephone.mjs
var import_components242 = __toESM(require_components(), 1);
var import_jsx_runtime477 = __toESM(require_jsx_runtime(), 1);
function Telephone({
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
validity
}) {
return /* @__PURE__ */ (0, import_jsx_runtime477.jsx)(
ValidatedText,
{
...{
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
validity,
type: "tel",
prefix: /* @__PURE__ */ (0, import_jsx_runtime477.jsx)(import_components242.__experimentalInputControlPrefixWrapper, { variant: "icon", children: /* @__PURE__ */ (0, import_jsx_runtime477.jsx)(import_components242.Icon, { icon: mobile_default }) })
}
}
);
}
// packages/dataviews/build-module/components/dataform-controls/url.mjs
var import_components243 = __toESM(require_components(), 1);
var import_jsx_runtime478 = __toESM(require_jsx_runtime(), 1);
function Url({
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
validity
}) {
return /* @__PURE__ */ (0, import_jsx_runtime478.jsx)(
ValidatedText,
{
...{
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
validity,
type: "url",
prefix: /* @__PURE__ */ (0, import_jsx_runtime478.jsx)(import_components243.__experimentalInputControlPrefixWrapper, { variant: "icon", children: /* @__PURE__ */ (0, import_jsx_runtime478.jsx)(import_components243.Icon, { icon: link_default }) })
}
}
);
}
// packages/dataviews/build-module/components/dataform-controls/utils/validated-number.mjs
var import_components244 = __toESM(require_components(), 1);
var import_element288 = __toESM(require_element(), 1);
var import_i18n224 = __toESM(require_i18n(), 1);
var import_jsx_runtime479 = __toESM(require_jsx_runtime(), 1);
var { ValidatedNumberControl } = unlock4(import_components244.privateApis);
function toNumberOrEmpty(value) {
if (value === "" || value === void 0) {
return "";
}
const number = Number(value);
return Number.isFinite(number) ? number : "";
}
function BetweenControls({
value,
onChange,
hideLabelFromVision,
step
}) {
const [min2 = "", max2 = ""] = value;
const onChangeMin = (0, import_element288.useCallback)(
(newValue) => onChange([toNumberOrEmpty(newValue), max2]),
[onChange, max2]
);
const onChangeMax = (0, import_element288.useCallback)(
(newValue) => onChange([min2, toNumberOrEmpty(newValue)]),
[onChange, min2]
);
return /* @__PURE__ */ (0, import_jsx_runtime479.jsx)(
import_components244.BaseControl,
{
help: (0, import_i18n224.__)("The max. value must be greater than the min. value."),
children: /* @__PURE__ */ (0, import_jsx_runtime479.jsxs)(import_components244.Flex, { direction: "row", gap: 4, children: [
/* @__PURE__ */ (0, import_jsx_runtime479.jsx)(
import_components244.__experimentalNumberControl,
{
label: (0, import_i18n224.__)("Min."),
value: min2,
max: max2 ? Number(max2) - step : void 0,
onChange: onChangeMin,
hideLabelFromVision,
step
}
),
/* @__PURE__ */ (0, import_jsx_runtime479.jsx)(
import_components244.__experimentalNumberControl,
{
label: (0, import_i18n224.__)("Max."),
value: max2,
min: min2 ? Number(min2) + step : void 0,
onChange: onChangeMax,
hideLabelFromVision,
step
}
)
] })
}
);
}
function ValidatedNumber({
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
operator,
validity
}) {
const decimals = field.format?.decimals ?? 0;
const step = Math.pow(10, Math.abs(decimals) * -1);
const { label, description, getValue, setValue, isValid: isValid2 } = field;
const value = getValue({ item: data }) ?? "";
const disabled2 = field.isDisabled({ item: data, field });
const onChangeControl = (0, import_element288.useCallback)(
(newValue) => {
onChange(
setValue({
item: data,
// Do not convert an empty string or undefined to a number,
// otherwise there's a mismatch between the UI control (empty)
// and the data relied by onChange (0).
value: ["", void 0].includes(newValue) ? void 0 : Number(newValue)
})
);
},
[data, onChange, setValue]
);
const onChangeBetweenControls = (0, import_element288.useCallback)(
(newValue) => {
onChange(
setValue({
item: data,
value: newValue
})
);
},
[data, onChange, setValue]
);
if (operator === OPERATOR_BETWEEN) {
let valueBetween = ["", ""];
if (Array.isArray(value) && value.length === 2 && value.every(
(element) => typeof element === "number" || element === ""
)) {
valueBetween = value;
}
return /* @__PURE__ */ (0, import_jsx_runtime479.jsx)(
BetweenControls,
{
value: valueBetween,
onChange: onChangeBetweenControls,
hideLabelFromVision,
step
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime479.jsx)(
ValidatedNumberControl,
{
required: !!isValid2.required,
markWhenOptional,
customValidity: getCustomValidity(isValid2, validity),
label,
help: description,
value,
onChange: onChangeControl,
hideLabelFromVision,
step,
min: isValid2.min ? isValid2.min.constraint : void 0,
max: isValid2.max ? isValid2.max.constraint : void 0,
disabled: disabled2
}
);
}
// packages/dataviews/build-module/components/dataform-controls/integer.mjs
var import_jsx_runtime480 = __toESM(require_jsx_runtime(), 1);
function Integer(props) {
return /* @__PURE__ */ (0, import_jsx_runtime480.jsx)(ValidatedNumber, { ...props });
}
// packages/dataviews/build-module/components/dataform-controls/number.mjs
var import_jsx_runtime481 = __toESM(require_jsx_runtime(), 1);
function Number2(props) {
return /* @__PURE__ */ (0, import_jsx_runtime481.jsx)(ValidatedNumber, { ...props });
}
// packages/dataviews/build-module/components/dataform-controls/radio.mjs
var import_components245 = __toESM(require_components(), 1);
var import_element289 = __toESM(require_element(), 1);
var import_jsx_runtime482 = __toESM(require_jsx_runtime(), 1);
var { ValidatedRadioControl } = unlock4(import_components245.privateApis);
function Radio({
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
validity
}) {
const { label, description, getValue, setValue, isValid: isValid2 } = field;
const disabled2 = field.isDisabled({ item: data, field });
const { elements, isLoading } = useElements({
elements: field.elements,
getElements: field.getElements
});
const value = getValue({ item: data });
const onChangeControl = (0, import_element289.useCallback)(
(newValue) => onChange(setValue({ item: data, value: newValue })),
[data, onChange, setValue]
);
if (isLoading) {
return /* @__PURE__ */ (0, import_jsx_runtime482.jsx)(import_components245.Spinner, {});
}
return /* @__PURE__ */ (0, import_jsx_runtime482.jsx)(
ValidatedRadioControl,
{
required: !!field.isValid?.required,
markWhenOptional,
customValidity: getCustomValidity(isValid2, validity),
label,
help: description,
onChange: onChangeControl,
options: elements,
selected: value,
hideLabelFromVision,
disabled: disabled2
}
);
}
// packages/dataviews/build-module/components/dataform-controls/text.mjs
var import_element290 = __toESM(require_element(), 1);
var import_jsx_runtime483 = __toESM(require_jsx_runtime(), 1);
function Text3({
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
config: config2,
validity
}) {
const { prefix: prefix2, suffix } = config2 || {};
return /* @__PURE__ */ (0, import_jsx_runtime483.jsx)(
ValidatedText,
{
...{
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
validity,
prefix: prefix2 ? (0, import_element290.createElement)(prefix2) : void 0,
suffix: suffix ? (0, import_element290.createElement)(suffix) : void 0
}
}
);
}
// packages/dataviews/build-module/components/dataform-controls/toggle.mjs
var import_components246 = __toESM(require_components(), 1);
var import_element291 = __toESM(require_element(), 1);
var import_jsx_runtime484 = __toESM(require_jsx_runtime(), 1);
var { ValidatedToggleControl } = unlock4(import_components246.privateApis);
function Toggle({
field,
onChange,
data,
hideLabelFromVision,
markWhenOptional,
validity
}) {
const { label, description, getValue, setValue, isValid: isValid2 } = field;
const disabled2 = field.isDisabled({ item: data, field });
const onChangeControl = (0, import_element291.useCallback)(() => {
onChange(
setValue({ item: data, value: !getValue({ item: data }) })
);
}, [onChange, setValue, data, getValue]);
return /* @__PURE__ */ (0, import_jsx_runtime484.jsx)(
ValidatedToggleControl,
{
required: !!isValid2.required,
markWhenOptional,
customValidity: getCustomValidity(isValid2, validity),
hidden: hideLabelFromVision,
label,
help: description,
checked: getValue({ item: data }),
onChange: onChangeControl,
disabled: disabled2
}
);
}
// packages/dataviews/build-module/components/dataform-controls/textarea.mjs
var import_components247 = __toESM(require_components(), 1);
var import_element292 = __toESM(require_element(), 1);
var import_jsx_runtime485 = __toESM(require_jsx_runtime(), 1);
var { ValidatedTextareaControl } = unlock4(import_components247.privateApis);
function Textarea({
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
config: config2,
validity
}) {
const { rows = 4 } = config2 || {};
const disabled2 = field.isDisabled({ item: data, field });
const { label, placeholder, description, setValue, isValid: isValid2 } = field;
const value = field.getValue({ item: data });
const onChangeControl = (0, import_element292.useCallback)(
(newValue) => onChange(setValue({ item: data, value: newValue })),
[data, onChange, setValue]
);
return /* @__PURE__ */ (0, import_jsx_runtime485.jsx)(
ValidatedTextareaControl,
{
required: !!isValid2.required,
markWhenOptional,
customValidity: getCustomValidity(isValid2, validity),
label,
placeholder,
value: value ?? "",
help: description,
onChange: onChangeControl,
rows,
disabled: disabled2,
minLength: isValid2.minLength ? isValid2.minLength.constraint : void 0,
maxLength: isValid2.maxLength ? isValid2.maxLength.constraint : void 0,
__next40pxDefaultSize: true,
hideLabelFromVision
}
);
}
// packages/dataviews/build-module/components/dataform-controls/richtext/index.mjs
var import_element294 = __toESM(require_element(), 1);
// packages/dataviews/build-module/components/dataform-controls/richtext/control.mjs
var import_components248 = __toESM(require_components(), 1);
var import_compose99 = __toESM(require_compose(), 1);
var import_element293 = __toESM(require_element(), 1);
var import_rich_text23 = __toESM(require_rich_text(), 1);
// packages/dataviews/build-module/components/dataform-controls/richtext/utils.mjs
var EMPTY_ARRAY17 = [];
function getAllowedFormats2({
allowedFormats,
disableFormats
}) {
if (disableFormats) {
return EMPTY_ARRAY17;
}
return allowedFormats;
}
// packages/dataviews/build-module/components/dataform-controls/richtext/format-edit.mjs
var import_rich_text22 = __toESM(require_rich_text(), 1);
var import_jsx_runtime486 = __toESM(require_jsx_runtime(), 1);
var import_react17 = __toESM(require_react(), 1);
var EMPTY_CONTEXT2 = {};
function Edit4({
onChange,
onFocus,
value,
forwardedRef,
settings: settings2,
isVisible
}) {
const { name, edit: EditFunction } = settings2;
if (!EditFunction) {
return null;
}
const activeFormat = (0, import_rich_text22.getActiveFormat)(value, name);
const isActive = activeFormat !== void 0;
const activeObject = (0, import_rich_text22.getActiveObject)(value);
const isObjectActive = activeObject !== void 0 && activeObject.type === name;
return /* @__PURE__ */ (0, import_jsx_runtime486.jsx)(
EditFunction,
{
isActive,
isVisible,
activeAttributes: isActive ? activeFormat.attributes || {} : {},
isObjectActive,
activeObjectAttributes: isObjectActive ? activeObject.attributes || {} : {},
value,
onChange,
onFocus,
contentRef: forwardedRef,
context: EMPTY_CONTEXT2
},
name
);
}
function FormatEdit2({
formatTypes,
...props
}) {
return formatTypes.map((settings2) => /* @__PURE__ */ (0, import_react17.createElement)(Edit4, { settings: settings2, ...props, key: settings2.name }));
}
// packages/dataviews/build-module/components/dataform-controls/richtext/control.mjs
var import_jsx_runtime487 = __toESM(require_jsx_runtime(), 1);
var {
ValidatedContentEditableControl: RichTextControlShell,
withIgnoreIMEEvents
} = unlock4(import_components248.privateApis);
var {
useRichText: useRichText2,
KeyboardShortcutContext: KeyboardShortcutContext2,
InputEventContext: InputEventContext2,
shortcutsListener,
inputEventsListener
} = unlock4(import_rich_text23.privateApis);
var EMPTY_COMPLETERS = [];
function RichTextControl({
label,
value: attrValue,
onChange,
placeholder,
id,
clientId,
className,
hideLabelFromVision,
help,
disabled: disabled2,
required,
markWhenOptional,
customValidity,
allowedFormats,
disableFormats,
withoutInteractiveFormatting,
preserveWhiteSpace,
disableLineBreaks,
focusOnMount,
completers = EMPTY_COMPLETERS
}) {
const [selection2, setSelection] = (0, import_element293.useState)({
start: void 0,
end: void 0
});
const [isSelected, setIsSelected] = (0, import_element293.useState)(false);
const anchorRef = (0, import_element293.useRef)(void 0);
const inputEvents = (0, import_element293.useRef)(/* @__PURE__ */ new Set());
const keyboardShortcuts = (0, import_element293.useRef)(
/* @__PURE__ */ new Set()
);
const popoverSlotRef = (0, import_element293.useRef)(null);
const [popoverContainer, setPopoverContainer] = (0, import_element293.useState)(null);
const popoverContainerRef = (0, import_compose99.useRefEffect)((element) => {
setPopoverContainer(element.ownerDocument.body);
}, []);
const blurDeselectTimeoutRef = (0, import_element293.useRef)();
const stopPopoverFocusTrackingRef = (0, import_element293.useRef)(
void 0
);
(0, import_element293.useEffect)(
() => () => {
clearTimeout(blurDeselectTimeoutRef.current);
stopPopoverFocusTrackingRef.current?.();
},
[]
);
function isFocusInField(ownerDocument2) {
const active = ownerDocument2.activeElement;
return !!(active && (anchorRef.current?.contains(active) || popoverSlotRef.current?.contains(active)));
}
function trackPopoverFocusOut(ownerDocument2) {
stopPopoverFocusTrackingRef.current?.();
function onDocumentFocusOut() {
clearTimeout(blurDeselectTimeoutRef.current);
blurDeselectTimeoutRef.current = setTimeout(() => {
if (isFocusInField(ownerDocument2)) {
return;
}
stopPopoverFocusTrackingRef.current?.();
setIsSelected(false);
}, 0);
}
ownerDocument2.addEventListener("focusout", onDocumentFocusOut);
stopPopoverFocusTrackingRef.current = () => {
ownerDocument2.removeEventListener("focusout", onDocumentFocusOut);
stopPopoverFocusTrackingRef.current = void 0;
};
}
function onEditableFocus() {
clearTimeout(blurDeselectTimeoutRef.current);
stopPopoverFocusTrackingRef.current?.();
setIsSelected(true);
}
function onEditableBlur(event) {
clearTimeout(blurDeselectTimeoutRef.current);
const { ownerDocument: ownerDocument2 } = event.currentTarget;
blurDeselectTimeoutRef.current = setTimeout(() => {
if (isFocusInField(ownerDocument2)) {
trackPopoverFocusOut(ownerDocument2);
return;
}
setIsSelected(false);
}, 0);
}
const adjustedAllowedFormats = getAllowedFormats2({
allowedFormats,
disableFormats
});
const {
value,
onChange: onRichTextChange,
ref: richTextRef,
formatTypes,
getValue
} = useRichText2({
value: attrValue,
onChange,
selectionStart: selection2.start,
selectionEnd: selection2.end,
onSelectionChange: (start2, end) => setSelection({ start: start2, end }),
__unstableIsSelected: isSelected,
preserveWhiteSpace: !!preserveWhiteSpace,
placeholder,
__unstableDisableFormats: disableFormats,
allowedFormats: adjustedAllowedFormats,
withoutInteractiveFormatting,
__unstableFormatTypeHandlerContext: (0, import_element293.useMemo)(
() => ({
richTextIdentifier: id,
blockClientId: clientId
}),
[id, clientId]
)
});
function onFocus() {
anchorRef.current?.focus();
}
const eventListenersPropsRef = (0, import_element293.useRef)({
keyboardShortcuts,
inputEvents
});
const inputRulePropsRef = (0, import_element293.useRef)({
formatTypes,
getValue,
onChange: onRichTextChange
});
(0, import_element293.useInsertionEffect)(() => {
inputRulePropsRef.current = {
formatTypes,
getValue,
onChange: onRichTextChange
};
});
const enterRef = (0, import_compose99.useRefEffect)(
(element) => {
if (disabled2) {
return;
}
const onKeyDown = withIgnoreIMEEvents((event) => {
if (event.key !== "Enter" || event.defaultPrevented || event.metaKey || event.ctrlKey) {
return;
}
event.preventDefault();
if (disableLineBreaks) {
return;
}
const { getValue: getCurrentValue, onChange: handleChange } = inputRulePropsRef.current;
const current = getCurrentValue();
handleChange(
(0, import_rich_text23.insert)(
current,
"\n",
current.start ?? current.text.length,
current.end ?? current.text.length
)
);
});
element.addEventListener("keydown", onKeyDown);
return () => element.removeEventListener("keydown", onKeyDown);
},
[disableLineBreaks, disabled2]
);
const eventListenersRef = (0, import_compose99.useRefEffect)(
(element) => {
if (!isSelected) {
return;
}
const cleanupShortcuts = shortcutsListener(
eventListenersPropsRef
)(element);
const cleanupInputEvents = inputEventsListener(
eventListenersPropsRef
)(element);
function onFormatInput(event) {
if (event.inputType !== "insertText" && event.type !== "compositionend") {
return;
}
const {
formatTypes: types,
getValue: getCurrentValue,
onChange: handleChange
} = inputRulePropsRef.current;
const current = getCurrentValue();
const transformed = types.reduce(
(accumulator, {
__unstableInputRule
}) => __unstableInputRule ? __unstableInputRule(accumulator) : accumulator,
current
);
if (transformed !== current) {
handleChange({
...transformed,
activeFormats: current.activeFormats
});
}
}
element.addEventListener("input", onFormatInput);
element.addEventListener("compositionend", onFormatInput);
return () => {
cleanupShortcuts();
cleanupInputEvents();
element.removeEventListener("input", onFormatInput);
element.removeEventListener("compositionend", onFormatInput);
};
},
[isSelected]
);
const unusedContentRef = (0, import_element293.useRef)(null);
const {
ref: autocompleteRef,
"aria-activedescendant": autocompleteActiveDescendant,
"aria-autocomplete": autocompleteAriaAutocomplete,
...autocompleteRest
} = (0, import_components248.__unstableUseAutocompleteProps)({
completers,
record: value,
onChange: onRichTextChange,
// This control's completers insert their completion into the value;
// none replace the whole value, so the required `onReplace` is a
// no-op here.
onReplace: () => {
},
contentRef: unusedContentRef
});
const autocompleteProps = {
...autocompleteRest,
"aria-activedescendant": autocompleteActiveDescendant ?? void 0,
"aria-autocomplete": autocompleteAriaAutocomplete
};
const focusOnMountRef = (0, import_compose99.useRefEffect)(
(element) => {
if (focusOnMount && !disabled2) {
element.focus();
}
},
[focusOnMount, disabled2]
);
const editableRef = (0, import_compose99.useMergeRefs)([
richTextRef,
anchorRef,
eventListenersRef,
enterRef,
focusOnMountRef,
popoverContainerRef,
autocompleteRef
]);
return (
/*
* The provider scopes every slot/fill rendered by this field — most
* importantly the format popovers, which land in the `Popover.Slot`
* below. That containment is what the blur handling above checks to
* decide whether focus is still within the field's own UI. A format
* popover using a custom `__unstableSlotName` would portal to the
* body-level fallback container instead and deselect the field;
* `core/link` (and every other core format) uses the default slot.
*/
/* @__PURE__ */ (0, import_jsx_runtime487.jsxs)(import_components248.SlotFillProvider, { children: [
/* @__PURE__ */ (0, import_jsx_runtime487.jsx)(
RichTextControlShell,
{
label,
id,
className: clsx_default("dataviews-controls__richtext", className),
placeholder,
hideLabelFromVision,
help,
disabled: disabled2,
required,
markWhenOptional,
customValidity,
value: value.text,
"aria-multiline": !disableLineBreaks,
...autocompleteProps,
ref: editableRef,
onFocus: onEditableFocus,
onBlur: onEditableBlur
}
),
isSelected && !disabled2 && /* @__PURE__ */ (0, import_jsx_runtime487.jsx)(KeyboardShortcutContext2.Provider, { value: keyboardShortcuts, children: /* @__PURE__ */ (0, import_jsx_runtime487.jsx)(InputEventContext2.Provider, { value: inputEvents, children: /* @__PURE__ */ (0, import_jsx_runtime487.jsx)(
FormatEdit2,
{
value,
onChange: onRichTextChange,
onFocus,
formatTypes,
forwardedRef: anchorRef,
isVisible: true
}
) }) }),
popoverContainer && (0, import_element293.createPortal)(
/* @__PURE__ */ (0, import_jsx_runtime487.jsx)(import_components248.Popover.Slot, { ref: popoverSlotRef }),
popoverContainer
)
] })
);
}
// packages/dataviews/build-module/components/dataform-controls/richtext/index.mjs
var import_jsx_runtime488 = __toESM(require_jsx_runtime(), 1);
function RichText({
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
config: config2,
validity
}) {
const {
className,
clientId,
allowedFormats,
disableFormats,
withoutInteractiveFormatting,
preserveWhiteSpace,
disableLineBreaks
} = config2 || {};
const disabled2 = field.isDisabled({ item: data, field });
const { label, placeholder, description, id, setValue, isValid: isValid2 } = field;
const value = field.getValue({ item: data }) ?? "";
const onChangeControl = (0, import_element294.useCallback)(
(newValue) => onChange(setValue({ item: data, value: newValue })),
[data, onChange, setValue]
);
return /* @__PURE__ */ (0, import_jsx_runtime488.jsx)(
RichTextControl,
{
label,
value,
onChange: onChangeControl,
placeholder,
id,
hideLabelFromVision,
help: description,
disabled: disabled2,
required: !!isValid2.required,
markWhenOptional,
customValidity: getCustomValidity(isValid2, validity),
className,
clientId,
allowedFormats,
disableFormats,
withoutInteractiveFormatting,
preserveWhiteSpace,
disableLineBreaks
}
);
}
// packages/dataviews/build-module/components/dataform-controls/toggle-group.mjs
var import_components249 = __toESM(require_components(), 1);
var import_element295 = __toESM(require_element(), 1);
var import_jsx_runtime489 = __toESM(require_jsx_runtime(), 1);
var { ValidatedToggleGroupControl } = unlock4(import_components249.privateApis);
function ToggleGroup({
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
validity
}) {
const { getValue, setValue, isValid: isValid2 } = field;
const disabled2 = field.isDisabled({ item: data, field });
const value = getValue({ item: data });
const onChangeControl = (0, import_element295.useCallback)(
(newValue) => onChange(setValue({ item: data, value: newValue })),
[data, onChange, setValue]
);
const { elements, isLoading } = useElements({
elements: field.elements,
getElements: field.getElements
});
if (isLoading) {
return /* @__PURE__ */ (0, import_jsx_runtime489.jsx)(import_components249.Spinner, {});
}
if (elements.length === 0) {
return null;
}
const selectedOption = elements.find((el) => el.value === value);
return /* @__PURE__ */ (0, import_jsx_runtime489.jsx)(
ValidatedToggleGroupControl,
{
required: !!field.isValid?.required,
markWhenOptional,
customValidity: getCustomValidity(isValid2, validity),
isBlock: true,
label: field.label,
help: selectedOption?.description || field.description,
onChange: onChangeControl,
value,
hideLabelFromVision,
children: elements.map((el) => /* @__PURE__ */ (0, import_jsx_runtime489.jsx)(
import_components249.__experimentalToggleGroupControlOption,
{
label: el.label,
value: el.value,
disabled: disabled2
},
el.value
))
}
);
}
// packages/dataviews/build-module/components/dataform-controls/array.mjs
var import_components250 = __toESM(require_components(), 1);
var import_element296 = __toESM(require_element(), 1);
var import_jsx_runtime490 = __toESM(require_jsx_runtime(), 1);
var { ValidatedFormTokenField } = unlock4(import_components250.privateApis);
function ArrayControl({
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
validity
}) {
const { label, placeholder, description, getValue, setValue, isValid: isValid2 } = field;
const value = getValue({ item: data });
const disabled2 = field.isDisabled({ item: data, field });
const { elements, isLoading } = useElements({
elements: field.elements,
getElements: field.getElements
});
const arrayValueAsElements = (0, import_element296.useMemo)(
() => Array.isArray(value) ? value.map((token) => {
const element = elements?.find(
(suggestion) => suggestion.value === token
);
return element || { value: token, label: token };
}) : [],
[value, elements]
);
const onChangeControl = (0, import_element296.useCallback)(
(tokens) => {
const valueTokens = tokens.map((token) => {
if (typeof token === "object" && "value" in token) {
return token.value;
}
return token;
});
onChange(setValue({ item: data, value: valueTokens }));
},
[onChange, setValue, data]
);
if (isLoading) {
return /* @__PURE__ */ (0, import_jsx_runtime490.jsx)(import_components250.Spinner, {});
}
return /* @__PURE__ */ (0, import_jsx_runtime490.jsx)(
ValidatedFormTokenField,
{
required: !!isValid2?.required,
markWhenOptional,
customValidity: getCustomValidity(isValid2, validity),
label: hideLabelFromVision ? void 0 : label,
value: arrayValueAsElements,
onChange: onChangeControl,
placeholder,
suggestions: elements?.map((element) => element.value),
disabled: disabled2,
__experimentalValidateInput: (token) => {
if (field.isValid?.elements && elements) {
return elements.some(
(element) => element.value === token || element.label === token
);
}
return true;
},
__experimentalExpandOnFocus: elements && elements.length > 0,
help: description ?? (field.isValid?.elements ? "" : void 0),
displayTransform: (token) => {
if (typeof token === "object" && "label" in token) {
return token.label;
}
if (typeof token === "string" && elements) {
const element = elements.find(
(el) => el.value === token
);
return element?.label || token;
}
return token;
},
__experimentalRenderItem: ({ item }) => {
if (typeof item === "string" && elements) {
const element = elements.find(
(el) => el.value === item
);
return /* @__PURE__ */ (0, import_jsx_runtime490.jsx)("span", { children: element?.label || item });
}
return /* @__PURE__ */ (0, import_jsx_runtime490.jsx)("span", { children: item });
}
}
);
}
// packages/dataviews/build-module/components/dataform-controls/color.mjs
var import_components251 = __toESM(require_components(), 1);
var import_element297 = __toESM(require_element(), 1);
var import_i18n225 = __toESM(require_i18n(), 1);
var import_jsx_runtime491 = __toESM(require_jsx_runtime(), 1);
var { ValidatedInputControl: ValidatedInputControl4 } = unlock4(import_components251.privateApis);
var ColorPickerDropdown = ({
color,
onColorChange,
disabled: disabled2
}) => {
const validColor = color && w(color).isValid() ? color : "#ffffff";
return /* @__PURE__ */ (0, import_jsx_runtime491.jsx)(
import_components251.Dropdown,
{
className: "dataviews-controls__color-picker-dropdown",
popoverProps: { resize: false },
renderToggle: ({ onToggle }) => /* @__PURE__ */ (0, import_jsx_runtime491.jsx)(
import_components251.Button,
{
onClick: onToggle,
"aria-label": (0, import_i18n225.__)("Open color picker"),
size: "small",
disabled: disabled2,
accessibleWhenDisabled: true,
icon: () => /* @__PURE__ */ (0, import_jsx_runtime491.jsx)(import_components251.ColorIndicator, { colorValue: validColor })
}
),
renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime491.jsx)(import_components251.__experimentalDropdownContentWrapper, { paddingSize: "none", children: /* @__PURE__ */ (0, import_jsx_runtime491.jsx)(
import_components251.ColorPicker,
{
color: validColor,
onChange: onColorChange,
enableAlpha: true
}
) })
}
);
};
function Color({
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
validity
}) {
const { label, placeholder, description, setValue, isValid: isValid2 } = field;
const disabled2 = field.isDisabled({ item: data, field });
const value = field.getValue({ item: data }) || "";
const handleColorChange = (0, import_element297.useCallback)(
(newColor) => {
onChange(setValue({ item: data, value: newColor }));
},
[data, onChange, setValue]
);
const handleInputChange = (0, import_element297.useCallback)(
(newValue) => {
onChange(setValue({ item: data, value: newValue || "" }));
},
[data, onChange, setValue]
);
return /* @__PURE__ */ (0, import_jsx_runtime491.jsx)(
ValidatedInputControl4,
{
required: !!field.isValid?.required,
markWhenOptional,
customValidity: getCustomValidity(isValid2, validity),
label,
placeholder,
value,
help: description,
onChange: handleInputChange,
hideLabelFromVision,
type: "text",
disabled: disabled2,
prefix: /* @__PURE__ */ (0, import_jsx_runtime491.jsx)(import_components251.__experimentalInputControlPrefixWrapper, { variant: "control", children: /* @__PURE__ */ (0, import_jsx_runtime491.jsx)(
ColorPickerDropdown,
{
color: value,
onColorChange: handleColorChange,
disabled: disabled2
}
) })
}
);
}
// packages/dataviews/build-module/components/dataform-controls/password.mjs
var import_components252 = __toESM(require_components(), 1);
var import_element298 = __toESM(require_element(), 1);
var import_i18n226 = __toESM(require_i18n(), 1);
var import_jsx_runtime492 = __toESM(require_jsx_runtime(), 1);
function Password({
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
validity
}) {
const [isVisible, setIsVisible] = (0, import_element298.useState)(false);
const disabled2 = field.isDisabled({ item: data, field });
const toggleVisibility = (0, import_element298.useCallback)(() => {
setIsVisible((prev) => !prev);
}, []);
return /* @__PURE__ */ (0, import_jsx_runtime492.jsx)(
ValidatedText,
{
...{
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
validity,
type: isVisible ? "text" : "password",
suffix: /* @__PURE__ */ (0, import_jsx_runtime492.jsx)(import_components252.__experimentalInputControlSuffixWrapper, { variant: "control", children: /* @__PURE__ */ (0, import_jsx_runtime492.jsx)(
import_components252.Button,
{
icon: isVisible ? unseen_default : seen_default,
onClick: toggleVisibility,
size: "small",
label: isVisible ? (0, import_i18n226.__)("Hide password") : (0, import_i18n226.__)("Show password"),
disabled: disabled2,
accessibleWhenDisabled: true
}
) })
}
}
);
}
// packages/dataviews/build-module/field-types/utils/has-elements.mjs
function hasElements(field) {
return Array.isArray(field.elements) && field.elements.length > 0 || typeof field.getElements === "function";
}
// packages/dataviews/build-module/components/dataform-controls/index.mjs
var import_jsx_runtime493 = __toESM(require_jsx_runtime(), 1);
var FORM_CONTROLS = {
adaptiveSelect: AdaptiveSelect,
array: ArrayControl,
checkbox: Checkbox,
color: Color,
combobox: Combobox,
datetime: DateTime,
date: DateControl,
email: Email,
telephone: Telephone,
url: Url,
integer: Integer,
number: Number2,
password: Password,
radio: Radio,
select: Select,
text: Text3,
toggle: Toggle,
textarea: Textarea,
richtext: RichText,
toggleGroup: ToggleGroup
};
function isEditConfig(value) {
return value && typeof value === "object" && typeof value.control === "string";
}
function createConfiguredControl(config2) {
const { control, ...controlConfig } = config2;
const BaseControlType = getControlByType(control);
if (BaseControlType === null) {
return null;
}
return function ConfiguredControl(props) {
return /* @__PURE__ */ (0, import_jsx_runtime493.jsx)(BaseControlType, { ...props, config: controlConfig });
};
}
function getControl(field, fallback) {
if (typeof field.Edit === "function") {
return field.Edit;
}
if (typeof field.Edit === "string") {
return getControlByType(field.Edit);
}
if (isEditConfig(field.Edit)) {
return createConfiguredControl(field.Edit);
}
if (hasElements(field) && field.type !== "array") {
return getControlByType("adaptiveSelect");
}
if (fallback === null) {
return null;
}
return getControlByType(fallback);
}
function getControlByType(type) {
if (Object.keys(FORM_CONTROLS).includes(type)) {
return FORM_CONTROLS[type];
}
return null;
}
// packages/dataviews/build-module/field-types/utils/get-filter-by.mjs
function getFilterBy(field, defaultOperators, validOperators) {
if (field.filterBy === false) {
return false;
}
const operators = field.filterBy?.operators?.filter(
(op) => validOperators.includes(op)
) ?? defaultOperators;
if (operators.length === 0) {
return false;
}
return {
isPrimary: !!field.filterBy?.isPrimary,
operators
};
}
var get_filter_by_default = getFilterBy;
// packages/dataviews/build-module/field-types/utils/get-value-from-id.mjs
var getValueFromId = (id) => ({ item }) => {
const path = id.split(".");
let value = item;
for (const segment of path) {
if (value.hasOwnProperty(segment)) {
value = value[segment];
} else {
value = void 0;
}
}
return value;
};
var get_value_from_id_default = getValueFromId;
// packages/dataviews/build-module/field-types/utils/set-value-from-id.mjs
var setValueFromId = (id) => ({ value }) => {
const path = id.split(".");
const result = {};
let current = result;
for (const segment of path.slice(0, -1)) {
current[segment] = {};
current = current[segment];
}
current[path.at(-1)] = value;
return result;
};
var set_value_from_id_default = setValueFromId;
// packages/dataviews/build-module/field-types/email.mjs
var import_i18n227 = __toESM(require_i18n(), 1);
// packages/dataviews/build-module/field-types/utils/render-from-elements.mjs
function RenderFromElements({
item,
field
}) {
const { elements, isLoading } = useElements({
elements: field.elements,
getElements: field.getElements
});
const value = field.getValue({ item });
if (isLoading) {
return value;
}
if (elements.length === 0) {
return value;
}
return elements?.find((element) => element.value === value)?.label || field.getValue({ item });
}
// packages/dataviews/build-module/field-types/utils/render-default.mjs
var import_jsx_runtime494 = __toESM(require_jsx_runtime(), 1);
function render({
item,
field
}) {
if (field.hasElements) {
return /* @__PURE__ */ (0, import_jsx_runtime494.jsx)(RenderFromElements, { item, field });
}
return field.getValueFormatted({ item, field });
}
// packages/dataviews/build-module/field-types/utils/sort-text.mjs
var sort_text_default = (a2, b2, direction) => {
return direction === "asc" ? a2.localeCompare(b2) : b2.localeCompare(a2);
};
// packages/dataviews/build-module/field-types/utils/is-valid-required.mjs
function isValidRequired(item, field) {
const value = field.getValue({ item });
return ![void 0, "", null].includes(value);
}
// packages/dataviews/build-module/field-types/utils/is-valid-min-length.mjs
function isValidMinLength(item, field) {
if (typeof field.isValid.minLength?.constraint !== "number") {
return false;
}
const value = field.getValue({ item });
if ([void 0, "", null].includes(value)) {
return true;
}
return String(value).length >= field.isValid.minLength.constraint;
}
// packages/dataviews/build-module/field-types/utils/is-valid-max-length.mjs
function isValidMaxLength(item, field) {
if (typeof field.isValid.maxLength?.constraint !== "number") {
return false;
}
const value = field.getValue({ item });
if ([void 0, "", null].includes(value)) {
return true;
}
return String(value).length <= field.isValid.maxLength.constraint;
}
// packages/dataviews/build-module/field-types/utils/is-valid-pattern.mjs
function isValidPattern(item, field) {
if (field.isValid.pattern?.constraint === void 0) {
return true;
}
try {
const regexp = new RegExp(field.isValid.pattern.constraint);
const value = field.getValue({ item });
if ([void 0, "", null].includes(value)) {
return true;
}
return regexp.test(String(value));
} catch {
return false;
}
}
// packages/dataviews/build-module/field-types/utils/is-valid-elements.mjs
function isValidElements(item, field) {
const elements = field.elements ?? [];
const validValues = elements.map((el) => el.value);
if (validValues.length === 0) {
return true;
}
const value = field.getValue({ item });
return [].concat(value).every((v2) => validValues.includes(v2));
}
// packages/dataviews/build-module/field-types/utils/get-value-formatted-default.mjs
function getValueFormatted({
item,
field
}) {
return field.getValue({ item });
}
var get_value_formatted_default_default = getValueFormatted;
// packages/dataviews/build-module/field-types/email.mjs
var emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
function isValidCustom(item, field) {
const value = field.getValue({ item });
if (![void 0, "", null].includes(value) && !emailRegex.test(value)) {
return (0, import_i18n227.__)("Value must be a valid email address.");
}
return null;
}
var email_default = {
type: "email",
render,
Edit: "email",
sort: sort_text_default,
enableSorting: true,
enableGlobalSearch: false,
defaultOperators: [OPERATOR_IS_ANY, OPERATOR_IS_NONE],
validOperators: [
OPERATOR_IS,
OPERATOR_IS_NOT,
OPERATOR_CONTAINS,
OPERATOR_NOT_CONTAINS,
OPERATOR_STARTS_WITH,
// Multiple selection
OPERATOR_IS_ANY,
OPERATOR_IS_NONE,
OPERATOR_IS_ALL,
OPERATOR_IS_NOT_ALL
],
format: {},
getValueFormatted: get_value_formatted_default_default,
validate: {
required: isValidRequired,
pattern: isValidPattern,
minLength: isValidMinLength,
maxLength: isValidMaxLength,
elements: isValidElements,
custom: isValidCustom
}
};
// packages/dataviews/build-module/field-types/integer.mjs
var import_i18n228 = __toESM(require_i18n(), 1);
// packages/dataviews/build-module/field-types/utils/sort-number.mjs
var sort_number_default = (a2, b2, direction) => {
return direction === "asc" ? a2 - b2 : b2 - a2;
};
// packages/dataviews/build-module/field-types/utils/is-valid-min.mjs
function isValidMin(item, field) {
if (typeof field.isValid.min?.constraint !== "number") {
return false;
}
const value = field.getValue({ item });
if ([void 0, "", null].includes(value)) {
return true;
}
return Number(value) >= field.isValid.min.constraint;
}
// packages/dataviews/build-module/field-types/utils/is-valid-max.mjs
function isValidMax(item, field) {
if (typeof field.isValid.max?.constraint !== "number") {
return false;
}
const value = field.getValue({ item });
if ([void 0, "", null].includes(value)) {
return true;
}
return Number(value) <= field.isValid.max.constraint;
}
// packages/dataviews/build-module/field-types/integer.mjs
var format2 = {
separatorThousand: ","
};
function getValueFormatted2({
item,
field
}) {
let value = field.getValue({ item });
if (value === null || value === void 0) {
return "";
}
value = Number(value);
if (!Number.isFinite(value)) {
return String(value);
}
let formatInteger;
if (field.type !== "integer") {
formatInteger = format2;
} else {
formatInteger = field.format;
}
const { separatorThousand } = formatInteger;
const integerValue = Math.trunc(value);
if (!separatorThousand) {
return String(integerValue);
}
return String(integerValue).replace(
/\B(?=(\d{3})+(?!\d))/g,
separatorThousand
);
}
function isValidCustom2(item, field) {
const value = field.getValue({ item });
if (![void 0, "", null].includes(value) && !Number.isInteger(value)) {
return (0, import_i18n228.__)("Value must be an integer.");
}
return null;
}
var integer_default = {
type: "integer",
render,
Edit: "integer",
sort: sort_number_default,
enableSorting: true,
enableGlobalSearch: false,
defaultOperators: [
OPERATOR_IS,
OPERATOR_IS_NOT,
OPERATOR_LESS_THAN,
OPERATOR_GREATER_THAN,
OPERATOR_LESS_THAN_OR_EQUAL,
OPERATOR_GREATER_THAN_OR_EQUAL,
OPERATOR_BETWEEN
],
validOperators: [
// Single-selection
OPERATOR_IS,
OPERATOR_IS_NOT,
OPERATOR_LESS_THAN,
OPERATOR_GREATER_THAN,
OPERATOR_LESS_THAN_OR_EQUAL,
OPERATOR_GREATER_THAN_OR_EQUAL,
OPERATOR_BETWEEN,
// Multiple-selection
OPERATOR_IS_ANY,
OPERATOR_IS_NONE,
OPERATOR_IS_ALL,
OPERATOR_IS_NOT_ALL
],
format: format2,
getValueFormatted: getValueFormatted2,
validate: {
required: isValidRequired,
min: isValidMin,
max: isValidMax,
elements: isValidElements,
custom: isValidCustom2
}
};
// packages/dataviews/build-module/field-types/number.mjs
var import_i18n229 = __toESM(require_i18n(), 1);
var format3 = {
separatorThousand: ",",
separatorDecimal: ".",
decimals: 2
};
function getValueFormatted3({
item,
field
}) {
let value = field.getValue({ item });
if (value === null || value === void 0) {
return "";
}
value = Number(value);
if (!Number.isFinite(value)) {
return String(value);
}
let formatNumber;
if (field.type !== "number") {
formatNumber = format3;
} else {
formatNumber = field.format;
}
const { separatorThousand, separatorDecimal, decimals } = formatNumber;
const fixedValue = value.toFixed(decimals);
const [integerPart, decimalPart] = fixedValue.split(".");
const formattedInteger = separatorThousand ? integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, separatorThousand) : integerPart;
return decimals === 0 ? formattedInteger : formattedInteger + separatorDecimal + decimalPart;
}
function isEmpty3(value) {
return value === "" || value === void 0 || value === null;
}
function isValidCustom3(item, field) {
const value = field.getValue({ item });
if (!isEmpty3(value) && !Number.isFinite(value)) {
return (0, import_i18n229.__)("Value must be a number.");
}
return null;
}
var number_default = {
type: "number",
render,
Edit: "number",
sort: sort_number_default,
enableSorting: true,
enableGlobalSearch: false,
defaultOperators: [
OPERATOR_IS,
OPERATOR_IS_NOT,
OPERATOR_LESS_THAN,
OPERATOR_GREATER_THAN,
OPERATOR_LESS_THAN_OR_EQUAL,
OPERATOR_GREATER_THAN_OR_EQUAL,
OPERATOR_BETWEEN
],
validOperators: [
// Single-selection
OPERATOR_IS,
OPERATOR_IS_NOT,
OPERATOR_LESS_THAN,
OPERATOR_GREATER_THAN,
OPERATOR_LESS_THAN_OR_EQUAL,
OPERATOR_GREATER_THAN_OR_EQUAL,
OPERATOR_BETWEEN,
// Multiple-selection
OPERATOR_IS_ANY,
OPERATOR_IS_NONE,
OPERATOR_IS_ALL,
OPERATOR_IS_NOT_ALL
],
format: format3,
getValueFormatted: getValueFormatted3,
validate: {
required: isValidRequired,
min: isValidMin,
max: isValidMax,
elements: isValidElements,
custom: isValidCustom3
}
};
// packages/dataviews/build-module/field-types/text.mjs
var text_default = {
type: "text",
render,
Edit: "text",
sort: sort_text_default,
enableSorting: true,
enableGlobalSearch: false,
defaultOperators: [OPERATOR_IS_ANY, OPERATOR_IS_NONE],
validOperators: [
// Single selection
OPERATOR_IS,
OPERATOR_IS_NOT,
OPERATOR_CONTAINS,
OPERATOR_NOT_CONTAINS,
OPERATOR_STARTS_WITH,
// Multiple selection
OPERATOR_IS_ANY,
OPERATOR_IS_NONE,
OPERATOR_IS_ALL,
OPERATOR_IS_NOT_ALL
],
format: {},
getValueFormatted: get_value_formatted_default_default,
validate: {
required: isValidRequired,
pattern: isValidPattern,
minLength: isValidMinLength,
maxLength: isValidMaxLength,
elements: isValidElements
}
};
// packages/dataviews/build-module/field-types/datetime.mjs
var import_date9 = __toESM(require_date(), 1);
// packages/dataviews/build-module/field-types/utils/is-valid-date-boundary.mjs
var import_date8 = __toESM(require_date(), 1);
function parseDateLike(value) {
if (!value) {
return null;
}
if (!isValid(new Date(value))) {
return null;
}
const parsed = (0, import_date8.getDate)(value);
return parsed && isValid(parsed) ? parsed : null;
}
function validateDateLikeBoundary(item, field, boundary) {
const constraint = field.isValid[boundary]?.constraint;
if (typeof constraint !== "string") {
return false;
}
const value = field.getValue({ item });
const boundaryValue = Array.isArray(value) ? value[boundary === "min" ? 0 : value.length - 1] : value;
if (boundaryValue === void 0 || boundaryValue === null || boundaryValue === "") {
return true;
}
const parsedConstraint = parseDateLike(constraint);
const parsedValue = parseDateLike(String(boundaryValue));
return !!parsedConstraint && !!parsedValue && (boundary === "min" ? parsedValue.getTime() >= parsedConstraint.getTime() : parsedValue.getTime() <= parsedConstraint.getTime());
}
function isValidMinDate(item, field) {
return validateDateLikeBoundary(item, field, "min");
}
function isValidMaxDate(item, field) {
return validateDateLikeBoundary(item, field, "max");
}
// packages/dataviews/build-module/field-types/datetime.mjs
var format4 = {
datetime: (0, import_date9.getSettings)().formats.datetime,
weekStartsOn: (0, import_date9.getSettings)().l10n.startOfWeek
};
function getValueFormatted4({
item,
field
}) {
const value = field.getValue({ item });
if (["", void 0, null].includes(value)) {
return "";
}
let formatDatetime;
if (field.type !== "datetime") {
formatDatetime = format4;
} else {
formatDatetime = field.format;
}
return (0, import_date9.dateI18n)(formatDatetime.datetime, (0, import_date9.getDate)(value));
}
var sort = (a2, b2, direction) => {
const timeA = new Date(a2).getTime();
const timeB = new Date(b2).getTime();
return direction === "asc" ? timeA - timeB : timeB - timeA;
};
var datetime_default = {
type: "datetime",
render,
Edit: "datetime",
sort,
enableSorting: true,
enableGlobalSearch: false,
defaultOperators: [
OPERATOR_ON,
OPERATOR_NOT_ON,
OPERATOR_BEFORE,
OPERATOR_AFTER,
OPERATOR_BEFORE_INC,
OPERATOR_AFTER_INC,
OPERATOR_IN_THE_PAST,
OPERATOR_OVER
],
validOperators: [
OPERATOR_ON,
OPERATOR_NOT_ON,
OPERATOR_BEFORE,
OPERATOR_AFTER,
OPERATOR_BEFORE_INC,
OPERATOR_AFTER_INC,
OPERATOR_IN_THE_PAST,
OPERATOR_OVER
],
format: format4,
getValueFormatted: getValueFormatted4,
validate: {
required: isValidRequired,
elements: isValidElements,
min: isValidMinDate,
max: isValidMaxDate
}
};
// packages/dataviews/build-module/field-types/date.mjs
var import_date10 = __toESM(require_date(), 1);
var format5 = {
date: (0, import_date10.getSettings)().formats.date,
weekStartsOn: (0, import_date10.getSettings)().l10n.startOfWeek
};
function getValueFormatted5({
item,
field
}) {
const value = field.getValue({ item });
if (["", void 0, null].includes(value)) {
return "";
}
let formatDate2;
if (field.type !== "date") {
formatDate2 = format5;
} else {
formatDate2 = field.format;
}
return (0, import_date10.dateI18n)(formatDate2.date, (0, import_date10.getDate)(value));
}
var sort2 = (a2, b2, direction) => {
const timeA = new Date(a2).getTime();
const timeB = new Date(b2).getTime();
return direction === "asc" ? timeA - timeB : timeB - timeA;
};
var date_default = {
type: "date",
render,
Edit: "date",
sort: sort2,
enableSorting: true,
enableGlobalSearch: false,
defaultOperators: [
OPERATOR_ON,
OPERATOR_NOT_ON,
OPERATOR_BEFORE,
OPERATOR_AFTER,
OPERATOR_BEFORE_INC,
OPERATOR_AFTER_INC,
OPERATOR_IN_THE_PAST,
OPERATOR_OVER,
OPERATOR_BETWEEN
],
validOperators: [
OPERATOR_ON,
OPERATOR_NOT_ON,
OPERATOR_BEFORE,
OPERATOR_AFTER,
OPERATOR_BEFORE_INC,
OPERATOR_AFTER_INC,
OPERATOR_IN_THE_PAST,
OPERATOR_OVER,
OPERATOR_BETWEEN
],
format: format5,
getValueFormatted: getValueFormatted5,
validate: {
required: isValidRequired,
elements: isValidElements,
min: isValidMinDate,
max: isValidMaxDate
}
};
// packages/dataviews/build-module/field-types/boolean.mjs
var import_i18n230 = __toESM(require_i18n(), 1);
// packages/dataviews/build-module/field-types/utils/is-valid-required-for-bool.mjs
function isValidRequiredForBool(item, field) {
const value = field.getValue({ item });
return value === true;
}
// packages/dataviews/build-module/field-types/boolean.mjs
function getValueFormatted6({
item,
field
}) {
const value = field.getValue({ item });
if (value === true) {
return (0, import_i18n230.__)("True");
}
if (value === false) {
return (0, import_i18n230.__)("False");
}
return "";
}
function isValidCustom4(item, field) {
const value = field.getValue({ item });
if (![void 0, "", null].includes(value) && ![true, false].includes(value)) {
return (0, import_i18n230.__)("Value must be true, false, or undefined");
}
return null;
}
var sort3 = (a2, b2, direction) => {
const boolA = Boolean(a2);
const boolB = Boolean(b2);
if (boolA === boolB) {
return 0;
}
if (direction === "asc") {
return boolA ? 1 : -1;
}
return boolA ? -1 : 1;
};
var boolean_default = {
type: "boolean",
render,
Edit: "checkbox",
sort: sort3,
validate: {
required: isValidRequiredForBool,
elements: isValidElements,
custom: isValidCustom4
},
enableSorting: true,
enableGlobalSearch: false,
defaultOperators: [OPERATOR_IS, OPERATOR_IS_NOT],
validOperators: [OPERATOR_IS, OPERATOR_IS_NOT],
format: {},
getValueFormatted: getValueFormatted6
};
// packages/dataviews/build-module/field-types/media.mjs
var media_default2 = {
type: "media",
render: () => null,
Edit: null,
sort: () => 0,
enableSorting: false,
enableGlobalSearch: false,
defaultOperators: [],
validOperators: [],
format: {},
getValueFormatted: get_value_formatted_default_default,
// cannot validate any constraint, so
// the only available validation for the field author
// would be providing a custom validator.
validate: {}
};
// packages/dataviews/build-module/field-types/array.mjs
var import_i18n231 = __toESM(require_i18n(), 1);
// packages/dataviews/build-module/field-types/utils/is-valid-required-for-array.mjs
function isValidRequiredForArray(item, field) {
const value = field.getValue({ item });
return Array.isArray(value) && value.length > 0 && value.every(
(element) => ![void 0, "", null].includes(element)
);
}
// packages/dataviews/build-module/field-types/array.mjs
function getValueFormatted7({
item,
field
}) {
const value = field.getValue({ item });
const arr = Array.isArray(value) ? value : [];
return arr.join(", ");
}
function render2({ item, field }) {
return getValueFormatted7({ item, field });
}
function isValidCustom5(item, field) {
const value = field.getValue({ item });
if (![void 0, "", null].includes(value) && !Array.isArray(value)) {
return (0, import_i18n231.__)("Value must be an array.");
}
if (!value.every((v2) => typeof v2 === "string")) {
return (0, import_i18n231.__)("Every value must be a string.");
}
return null;
}
var sort4 = (a2, b2, direction) => {
const arrA = Array.isArray(a2) ? a2 : [];
const arrB = Array.isArray(b2) ? b2 : [];
if (arrA.length !== arrB.length) {
return direction === "asc" ? arrA.length - arrB.length : arrB.length - arrA.length;
}
const joinedA = arrA.join(",");
const joinedB = arrB.join(",");
return direction === "asc" ? joinedA.localeCompare(joinedB) : joinedB.localeCompare(joinedA);
};
var array_default = {
type: "array",
render: render2,
Edit: "array",
sort: sort4,
enableSorting: true,
enableGlobalSearch: false,
defaultOperators: [OPERATOR_IS_ANY, OPERATOR_IS_NONE],
validOperators: [
OPERATOR_IS_ANY,
OPERATOR_IS_NONE,
OPERATOR_IS_ALL,
OPERATOR_IS_NOT_ALL
],
format: {},
getValueFormatted: getValueFormatted7,
validate: {
required: isValidRequiredForArray,
elements: isValidElements,
custom: isValidCustom5
}
};
// packages/dataviews/build-module/field-types/password.mjs
function getValueFormatted8({
item,
field
}) {
return field.getValue({ item }) ? "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022" : "";
}
var password_default = {
type: "password",
render,
Edit: "password",
sort: () => 0,
// Passwords should not be sortable for security reasons
enableSorting: false,
enableGlobalSearch: false,
defaultOperators: [],
validOperators: [],
format: {},
getValueFormatted: getValueFormatted8,
validate: {
required: isValidRequired,
pattern: isValidPattern,
minLength: isValidMinLength,
maxLength: isValidMaxLength,
elements: isValidElements
}
};
// packages/dataviews/build-module/field-types/telephone.mjs
var telephone_default = {
type: "telephone",
render,
Edit: "telephone",
sort: sort_text_default,
enableSorting: true,
enableGlobalSearch: false,
defaultOperators: [OPERATOR_IS_ANY, OPERATOR_IS_NONE],
validOperators: [
OPERATOR_IS,
OPERATOR_IS_NOT,
OPERATOR_CONTAINS,
OPERATOR_NOT_CONTAINS,
OPERATOR_STARTS_WITH,
// Multiple selection
OPERATOR_IS_ANY,
OPERATOR_IS_NONE,
OPERATOR_IS_ALL,
OPERATOR_IS_NOT_ALL
],
format: {},
getValueFormatted: get_value_formatted_default_default,
validate: {
required: isValidRequired,
pattern: isValidPattern,
minLength: isValidMinLength,
maxLength: isValidMaxLength,
elements: isValidElements
}
};
// packages/dataviews/build-module/field-types/color.mjs
var import_i18n232 = __toESM(require_i18n(), 1);
var import_jsx_runtime495 = __toESM(require_jsx_runtime(), 1);
function render3({ item, field }) {
if (field.hasElements) {
return /* @__PURE__ */ (0, import_jsx_runtime495.jsx)(RenderFromElements, { item, field });
}
const value = get_value_formatted_default_default({ item, field });
if (!value || !w(value).isValid()) {
return value;
}
return /* @__PURE__ */ (0, import_jsx_runtime495.jsxs)("div", { style: { display: "flex", alignItems: "center", gap: "8px" }, children: [
/* @__PURE__ */ (0, import_jsx_runtime495.jsx)(
"div",
{
style: {
width: "16px",
height: "16px",
borderRadius: "50%",
backgroundColor: value,
border: "1px solid #ddd",
flexShrink: 0
}
}
),
/* @__PURE__ */ (0, import_jsx_runtime495.jsx)("span", { children: value })
] });
}
function isValidCustom6(item, field) {
const value = field.getValue({ item });
if (![void 0, "", null].includes(value) && !w(value).isValid()) {
return (0, import_i18n232.__)("Value must be a valid color.");
}
return null;
}
var sort5 = (a2, b2, direction) => {
const colorA = w(a2);
const colorB = w(b2);
if (!colorA.isValid() && !colorB.isValid()) {
return 0;
}
if (!colorA.isValid()) {
return direction === "asc" ? 1 : -1;
}
if (!colorB.isValid()) {
return direction === "asc" ? -1 : 1;
}
const hslA = colorA.toHsl();
const hslB = colorB.toHsl();
if (hslA.h !== hslB.h) {
return direction === "asc" ? hslA.h - hslB.h : hslB.h - hslA.h;
}
if (hslA.s !== hslB.s) {
return direction === "asc" ? hslA.s - hslB.s : hslB.s - hslA.s;
}
return direction === "asc" ? hslA.l - hslB.l : hslB.l - hslA.l;
};
var color_default2 = {
type: "color",
render: render3,
Edit: "color",
sort: sort5,
enableSorting: true,
enableGlobalSearch: false,
defaultOperators: [OPERATOR_IS_ANY, OPERATOR_IS_NONE],
validOperators: [
OPERATOR_IS,
OPERATOR_IS_NOT,
OPERATOR_IS_ANY,
OPERATOR_IS_NONE
],
format: {},
getValueFormatted: get_value_formatted_default_default,
validate: {
required: isValidRequired,
elements: isValidElements,
custom: isValidCustom6
}
};
// packages/dataviews/build-module/field-types/url.mjs
var url_default = {
type: "url",
render,
Edit: "url",
sort: sort_text_default,
enableSorting: true,
enableGlobalSearch: false,
defaultOperators: [OPERATOR_IS_ANY, OPERATOR_IS_NONE],
validOperators: [
OPERATOR_IS,
OPERATOR_IS_NOT,
OPERATOR_CONTAINS,
OPERATOR_NOT_CONTAINS,
OPERATOR_STARTS_WITH,
// Multiple selection
OPERATOR_IS_ANY,
OPERATOR_IS_NONE,
OPERATOR_IS_ALL,
OPERATOR_IS_NOT_ALL
],
format: {},
getValueFormatted: get_value_formatted_default_default,
validate: {
required: isValidRequired,
pattern: isValidPattern,
minLength: isValidMinLength,
maxLength: isValidMaxLength,
elements: isValidElements
}
};
// packages/dataviews/build-module/field-types/no-type.mjs
var sort6 = (a2, b2, direction) => {
if (typeof a2 === "number" && typeof b2 === "number") {
return sort_number_default(a2, b2, direction);
}
return sort_text_default(a2, b2, direction);
};
var no_type_default = {
// type: no type for this one
render,
Edit: null,
sort: sort6,
enableSorting: true,
enableGlobalSearch: false,
defaultOperators: [OPERATOR_IS, OPERATOR_IS_NOT],
validOperators: getAllOperatorNames(),
format: {},
getValueFormatted: get_value_formatted_default_default,
validate: {
required: isValidRequired,
elements: isValidElements
}
};
// packages/dataviews/build-module/field-types/utils/get-is-valid.mjs
function supportsNumericRangeConstraint(type) {
return type === "integer" || type === "number";
}
function supportsDateRangeConstraint(type) {
return type === "date" || type === "datetime";
}
function normalizeRangeRule(value, fieldType, key) {
const validator = fieldType.validate[key];
if (validator && (typeof value === "number" && supportsNumericRangeConstraint(fieldType.type) || typeof value === "string" && supportsDateRangeConstraint(fieldType.type))) {
return { constraint: value, validate: validator };
}
return void 0;
}
function getIsValid(field, fieldType) {
const rules = field.isValid;
let required;
if (rules?.required === true && fieldType.validate.required !== void 0) {
required = {
constraint: true,
validate: fieldType.validate.required
};
}
let elements;
if ((rules?.elements === true || // elements is enabled unless the field opts-out
rules?.elements === void 0 && (!!field.elements || !!field.getElements)) && fieldType.validate.elements !== void 0) {
elements = {
constraint: true,
validate: fieldType.validate.elements
};
}
const min2 = normalizeRangeRule(rules?.min, fieldType, "min");
const max2 = normalizeRangeRule(rules?.max, fieldType, "max");
const minLengthValue = rules?.minLength;
let minLength;
if (typeof minLengthValue === "number" && fieldType.validate.minLength !== void 0) {
minLength = {
constraint: minLengthValue,
validate: fieldType.validate.minLength
};
}
const maxLengthValue = rules?.maxLength;
let maxLength;
if (typeof maxLengthValue === "number" && fieldType.validate.maxLength !== void 0) {
maxLength = {
constraint: maxLengthValue,
validate: fieldType.validate.maxLength
};
}
const patternValue = rules?.pattern;
let pattern;
if (patternValue !== void 0 && fieldType.validate.pattern !== void 0) {
pattern = {
constraint: patternValue,
validate: fieldType.validate.pattern
};
}
const custom = rules?.custom ?? fieldType.validate.custom;
return {
required,
elements,
min: min2,
max: max2,
minLength,
maxLength,
pattern,
custom
};
}
// packages/dataviews/build-module/field-types/utils/get-filter.mjs
function getFilter(fieldType) {
return fieldType.validOperators.reduce((accumulator, operator) => {
const operatorObj = getOperatorByName(operator);
if (operatorObj?.filter) {
accumulator[operator] = operatorObj.filter;
}
return accumulator;
}, {});
}
// packages/dataviews/build-module/field-types/utils/get-format.mjs
function getFormat(field, fieldType) {
return {
...fieldType.format,
...field.format
};
}
var get_format_default = getFormat;
// packages/dataviews/build-module/field-types/index.mjs
function getFieldTypeByName(type) {
const found = [
email_default,
integer_default,
number_default,
text_default,
datetime_default,
date_default,
boolean_default,
media_default2,
array_default,
password_default,
telephone_default,
color_default2,
url_default
].find((fieldType) => fieldType?.type === type);
if (!!found) {
return found;
}
return no_type_default;
}
function normalizeFields(fields) {
return fields.map((field) => {
const fieldType = getFieldTypeByName(field.type);
const getValue = field.getValue || get_value_from_id_default(field.id);
const sort7 = function(a2, b2, direction) {
const aValue = getValue({ item: a2 });
const bValue = getValue({ item: b2 });
return field.sort ? field.sort(aValue, bValue, direction) : fieldType.sort(aValue, bValue, direction);
};
return {
id: field.id,
label: field.label || field.id,
header: field.header || field.label || field.id,
description: field.description,
placeholder: field.placeholder,
getValue,
setValue: field.setValue || set_value_from_id_default(field.id),
elements: field.elements,
getElements: field.getElements,
hasElements: hasElements(field),
isVisible: field.isVisible,
isDisabled: typeof field.isDisabled === "function" ? field.isDisabled : () => !!field.isDisabled,
enableHiding: field.enableHiding ?? true,
readOnly: field.readOnly ?? false,
// The type provides defaults for the following props
type: fieldType.type,
render: field.render ?? fieldType.render,
Edit: getControl(field, fieldType.Edit),
sort: sort7,
enableSorting: field.enableSorting ?? fieldType.enableSorting,
enableGlobalSearch: field.enableGlobalSearch ?? fieldType.enableGlobalSearch,
isValid: getIsValid(field, fieldType),
filterBy: get_filter_by_default(
field,
fieldType.defaultOperators,
fieldType.validOperators
),
filter: getFilter(fieldType),
format: get_format_default(field, fieldType),
getValueFormatted: field.getValueFormatted ?? fieldType.getValueFormatted
};
});
}
// packages/dataviews/build-module/dataform/index.mjs
var import_element310 = __toESM(require_element(), 1);
// packages/dataviews/build-module/components/dataform-context/index.mjs
var import_element299 = __toESM(require_element(), 1);
var import_jsx_runtime496 = __toESM(require_jsx_runtime(), 1);
var DataFormContext = (0, import_element299.createContext)({
fields: []
});
DataFormContext.displayName = "DataFormContext";
function DataFormProvider({
fields,
children
}) {
return /* @__PURE__ */ (0, import_jsx_runtime496.jsx)(DataFormContext.Provider, { value: { fields }, children });
}
var dataform_context_default = DataFormContext;
// packages/dataviews/build-module/components/dataform-layouts/data-form-layout.mjs
var import_element309 = __toESM(require_element(), 1);
// packages/dataviews/build-module/components/dataform-layouts/regular/index.mjs
var import_element300 = __toESM(require_element(), 1);
var import_components253 = __toESM(require_components(), 1);
// packages/dataviews/build-module/components/dataform-layouts/normalize-form.mjs
var import_i18n233 = __toESM(require_i18n(), 1);
var DEFAULT_LAYOUT = {
type: "regular",
labelPosition: "top"
};
var normalizeCardSummaryField = (sum) => {
if (typeof sum === "string") {
return [{ id: sum, visibility: "when-collapsed" }];
}
return sum.map((item) => {
if (typeof item === "string") {
return { id: item, visibility: "when-collapsed" };
}
return { id: item.id, visibility: item.visibility };
});
};
function normalizeLayout(layout) {
let normalizedLayout = DEFAULT_LAYOUT;
if (layout?.type === "regular") {
normalizedLayout = {
type: "regular",
labelPosition: layout?.labelPosition ?? "top"
};
} else if (layout?.type === "panel") {
const summary = layout.summary ?? [];
const normalizedSummary = Array.isArray(summary) ? summary : [summary];
const openAs = layout?.openAs;
let normalizedOpenAs;
if (typeof openAs === "object" && openAs.type === "modal") {
normalizedOpenAs = {
type: "modal",
applyLabel: openAs.applyLabel?.trim() || (0, import_i18n233.__)("Apply"),
cancelLabel: openAs.cancelLabel?.trim() || (0, import_i18n233.__)("Cancel")
};
} else if (openAs === "modal") {
normalizedOpenAs = {
type: "modal",
applyLabel: (0, import_i18n233.__)("Apply"),
cancelLabel: (0, import_i18n233.__)("Cancel")
};
} else {
normalizedOpenAs = { type: "dropdown" };
}
normalizedLayout = {
type: "panel",
labelPosition: layout?.labelPosition ?? "side",
openAs: normalizedOpenAs,
summary: normalizedSummary,
editVisibility: layout?.editVisibility ?? "on-hover"
};
} else if (layout?.type === "card") {
if (layout.withHeader === false) {
normalizedLayout = {
type: "card",
withHeader: false,
isOpened: true,
summary: [],
isCollapsible: false
};
} else {
const summary = layout.summary ?? [];
normalizedLayout = {
type: "card",
withHeader: true,
isOpened: typeof layout.isOpened === "boolean" ? layout.isOpened : true,
summary: normalizeCardSummaryField(summary),
isCollapsible: layout.isCollapsible === void 0 ? true : layout.isCollapsible
};
}
} else if (layout?.type === "row") {
normalizedLayout = {
type: "row",
alignment: layout?.alignment ?? "center",
styles: layout?.styles ?? {}
};
} else if (layout?.type === "details") {
normalizedLayout = {
type: "details",
summary: layout?.summary ?? ""
};
}
return normalizedLayout;
}
function normalizeForm(form) {
const normalizedFormLayout = normalizeLayout(form?.layout);
const normalizedFields = (form.fields ?? []).map(
(field) => {
if (typeof field === "string") {
return {
id: field,
layout: normalizedFormLayout
};
}
const fieldLayout = field.layout ? normalizeLayout(field.layout) : normalizedFormLayout;
return {
id: field.id,
layout: fieldLayout,
...!!field.label && { label: field.label },
...!!field.description && {
description: field.description
},
..."children" in field && Array.isArray(field.children) && {
children: normalizeForm({
fields: field.children,
layout: DEFAULT_LAYOUT
}).fields
}
};
}
);
return {
layout: normalizedFormLayout,
fields: normalizedFields
};
}
var normalize_form_default = normalizeForm;
// packages/dataviews/build-module/components/dataform-layouts/regular/index.mjs
var import_jsx_runtime497 = __toESM(require_jsx_runtime(), 1);
function Header3({ title }) {
return /* @__PURE__ */ (0, import_jsx_runtime497.jsx)(
Stack,
{
direction: "column",
className: "dataforms-layouts-regular__header",
gap: "lg",
children: /* @__PURE__ */ (0, import_jsx_runtime497.jsx)(Stack, { direction: "row", align: "center", children: /* @__PURE__ */ (0, import_jsx_runtime497.jsx)(import_components253.__experimentalHeading, { level: 2, size: 13, children: title }) })
}
);
}
function FormRegularField({
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
validity
}) {
const { fields } = (0, import_element300.useContext)(dataform_context_default);
const layout = field.layout;
const form = (0, import_element300.useMemo)(
() => ({
layout: DEFAULT_LAYOUT,
fields: !!field.children ? field.children : []
}),
[field]
);
if (!!field.children) {
return /* @__PURE__ */ (0, import_jsx_runtime497.jsxs)(import_jsx_runtime497.Fragment, { children: [
!hideLabelFromVision && field.label && /* @__PURE__ */ (0, import_jsx_runtime497.jsx)(Header3, { title: field.label }),
/* @__PURE__ */ (0, import_jsx_runtime497.jsx)(
DataFormLayout,
{
data,
form,
onChange,
validity: validity?.children
}
)
] });
}
const labelPosition = layout.labelPosition;
const fieldDefinition = fields.find(
(fieldDef) => fieldDef.id === field.id
);
if (!fieldDefinition || !fieldDefinition.Edit) {
return null;
}
if (labelPosition === "side") {
return /* @__PURE__ */ (0, import_jsx_runtime497.jsxs)(
Stack,
{
direction: "row",
className: "dataforms-layouts-regular__field",
gap: "sm",
children: [
/* @__PURE__ */ (0, import_jsx_runtime497.jsx)(
"div",
{
className: clsx_default(
"dataforms-layouts-regular__field-label",
`dataforms-layouts-regular__field-label--label-position-${labelPosition}`
),
children: /* @__PURE__ */ (0, import_jsx_runtime497.jsx)(import_components253.BaseControl.VisualLabel, { children: fieldDefinition.label })
}
),
/* @__PURE__ */ (0, import_jsx_runtime497.jsx)("div", { className: "dataforms-layouts-regular__field-control", children: fieldDefinition.readOnly === true ? /* @__PURE__ */ (0, import_jsx_runtime497.jsx)(
fieldDefinition.render,
{
item: data,
field: fieldDefinition
}
) : /* @__PURE__ */ (0, import_jsx_runtime497.jsx)(
fieldDefinition.Edit,
{
data,
field: fieldDefinition,
onChange,
hideLabelFromVision: true,
markWhenOptional,
validity
},
fieldDefinition.id
) })
]
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime497.jsx)("div", { className: "dataforms-layouts-regular__field", children: fieldDefinition.readOnly === true ? /* @__PURE__ */ (0, import_jsx_runtime497.jsx)(import_jsx_runtime497.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime497.jsxs)(import_jsx_runtime497.Fragment, { children: [
!hideLabelFromVision && labelPosition !== "none" && /* @__PURE__ */ (0, import_jsx_runtime497.jsx)(import_components253.BaseControl.VisualLabel, { children: fieldDefinition.label }),
/* @__PURE__ */ (0, import_jsx_runtime497.jsx)(
fieldDefinition.render,
{
item: data,
field: fieldDefinition
}
)
] }) }) : /* @__PURE__ */ (0, import_jsx_runtime497.jsx)(
fieldDefinition.Edit,
{
data,
field: fieldDefinition,
onChange,
hideLabelFromVision: labelPosition === "none" ? true : hideLabelFromVision,
markWhenOptional,
validity
}
) });
}
// packages/dataviews/build-module/components/dataform-layouts/panel/modal.mjs
var import_deepmerge3 = __toESM(require_cjs(), 1);
var import_components256 = __toESM(require_components(), 1);
var import_element305 = __toESM(require_element(), 1);
var import_compose101 = __toESM(require_compose(), 1);
// packages/dataviews/build-module/components/dataform-layouts/panel/summary-button.mjs
var import_components255 = __toESM(require_components(), 1);
var import_i18n234 = __toESM(require_i18n(), 1);
var import_compose100 = __toESM(require_compose(), 1);
var import_element301 = __toESM(require_element(), 1);
// packages/dataviews/build-module/components/dataform-layouts/panel/utils/get-label-classname.mjs
function getLabelClassName(labelPosition, showError) {
return clsx_default(
"dataforms-layouts-panel__field-label",
`dataforms-layouts-panel__field-label--label-position-${labelPosition}`,
{ "has-error": showError }
);
}
var get_label_classname_default = getLabelClassName;
// packages/dataviews/build-module/components/dataform-layouts/panel/utils/get-label-content.mjs
var import_components254 = __toESM(require_components(), 1);
var import_jsx_runtime498 = __toESM(require_jsx_runtime(), 1);
function getLabelContent(showError, errorMessage, fieldLabel) {
return showError ? /* @__PURE__ */ (0, import_jsx_runtime498.jsxs)(tooltip_exports.Root, { children: [
/* @__PURE__ */ (0, import_jsx_runtime498.jsx)(
tooltip_exports.Trigger,
{
render: /* @__PURE__ */ (0, import_jsx_runtime498.jsxs)("span", { className: "dataforms-layouts-panel__field-label-error-content", children: [
/* @__PURE__ */ (0, import_jsx_runtime498.jsx)(import_components254.Icon, { icon: error_default, size: 16 }),
/* @__PURE__ */ (0, import_jsx_runtime498.jsxs)(VisuallyHidden, { children: [
errorMessage,
": "
] }),
fieldLabel
] })
}
),
/* @__PURE__ */ (0, import_jsx_runtime498.jsx)(tooltip_exports.Popup, { children: errorMessage })
] }) : fieldLabel;
}
var get_label_content_default = getLabelContent;
// packages/dataviews/build-module/components/dataform-layouts/panel/utils/get-first-validation-error.mjs
function getFirstValidationError(validity) {
if (!validity) {
return void 0;
}
const validityRules = Object.keys(validity).filter(
(key) => key !== "children"
);
for (const key of validityRules) {
const rule = validity[key];
if (rule === void 0) {
continue;
}
if (rule.type === "invalid") {
if (rule.message) {
return rule.message;
}
if (key === "required") {
return "A required field is empty";
}
return "Unidentified validation error";
}
}
if (validity.children) {
for (const childValidity of Object.values(validity.children)) {
const childError = getFirstValidationError(childValidity);
if (childError) {
return childError;
}
}
}
return void 0;
}
var get_first_validation_error_default = getFirstValidationError;
// packages/dataviews/build-module/components/dataform-layouts/panel/summary-button.mjs
var import_jsx_runtime499 = __toESM(require_jsx_runtime(), 1);
function SummaryButton({
data,
field,
fieldLabel,
summaryFields,
validity,
touched,
disabled: disabled2,
isOpen,
onClick
}) {
const { labelPosition, editVisibility } = field.layout;
const errorMessage = get_first_validation_error_default(validity);
const showError = touched && !!errorMessage;
const labelClassName = get_label_classname_default(labelPosition, showError);
const labelContent = get_label_content_default(showError, errorMessage, fieldLabel);
const className = clsx_default(
"dataforms-layouts-panel__field-trigger",
`dataforms-layouts-panel__field-trigger--label-${labelPosition}`,
{
"is-disabled": disabled2,
"dataforms-layouts-panel__field-trigger--edit-always": editVisibility === "always"
}
);
const controlId = (0, import_compose100.useInstanceId)(
SummaryButton,
"dataforms-layouts-panel__field-control"
);
const ariaLabel = showError ? (0, import_i18n234.sprintf)(
// translators: %s: Field name.
(0, import_i18n234._x)("Edit %s (has errors)", "field"),
fieldLabel || ""
) : (0, import_i18n234.sprintf)(
// translators: %s: Field name.
(0, import_i18n234._x)("Edit %s", "field"),
fieldLabel || ""
);
const rowRef = (0, import_element301.useRef)(null);
const editButtonRef = (0, import_element301.useRef)(null);
const handleRowClick = (event) => {
if (!isOpen && event.detail < 2 && !editButtonRef.current?.contains(event.target) && rowRef.current?.ownerDocument.defaultView?.getSelection()?.toString()) {
return;
}
onClick();
};
const handleKeyDown = (event) => {
if (event.target === event.currentTarget && (event.key === "Enter" || event.key === " ")) {
event.preventDefault();
onClick();
}
};
return /* @__PURE__ */ (0, import_jsx_runtime499.jsxs)(
"div",
{
ref: rowRef,
className,
onClick: !disabled2 ? handleRowClick : void 0,
onKeyDown: !disabled2 ? handleKeyDown : void 0,
children: [
labelPosition !== "none" && /* @__PURE__ */ (0, import_jsx_runtime499.jsx)("span", { className: labelClassName, children: labelContent }),
labelPosition === "none" && showError && /* @__PURE__ */ (0, import_jsx_runtime499.jsxs)(tooltip_exports.Root, { children: [
/* @__PURE__ */ (0, import_jsx_runtime499.jsx)(
tooltip_exports.Trigger,
{
render: /* @__PURE__ */ (0, import_jsx_runtime499.jsx)(
"span",
{
className: "dataforms-layouts-panel__field-label-error-content",
role: "img",
"aria-label": errorMessage,
children: /* @__PURE__ */ (0, import_jsx_runtime499.jsx)(import_components255.Icon, { icon: error_default, size: 16 })
}
)
}
),
/* @__PURE__ */ (0, import_jsx_runtime499.jsx)(tooltip_exports.Popup, { children: errorMessage })
] }),
/* @__PURE__ */ (0, import_jsx_runtime499.jsx)(
"span",
{
id: `${controlId}`,
className: "dataforms-layouts-panel__field-control",
children: summaryFields.length > 1 ? /* @__PURE__ */ (0, import_jsx_runtime499.jsx)(
"span",
{
style: {
display: "flex",
flexDirection: "column",
alignItems: "flex-start",
width: "100%",
gap: "2px"
},
children: summaryFields.map((summaryField) => /* @__PURE__ */ (0, import_jsx_runtime499.jsx)(
"span",
{
style: { width: "100%" },
children: /* @__PURE__ */ (0, import_jsx_runtime499.jsx)(
summaryField.render,
{
item: data,
field: summaryField
}
)
},
summaryField.id
))
}
) : summaryFields.map((summaryField) => /* @__PURE__ */ (0, import_jsx_runtime499.jsx)(
summaryField.render,
{
item: data,
field: summaryField
},
summaryField.id
))
}
),
!disabled2 && /* @__PURE__ */ (0, import_jsx_runtime499.jsx)(
import_components255.Button,
{
ref: editButtonRef,
className: "dataforms-layouts-panel__field-trigger-icon",
label: ariaLabel,
icon: pencil_default,
size: "small",
"aria-expanded": isOpen,
"aria-haspopup": "dialog",
"aria-describedby": `${controlId}`
}
)
]
}
);
}
// packages/dataviews/build-module/hooks/use-form-validity.mjs
var import_deepmerge2 = __toESM(require_cjs(), 1);
var import_es66 = __toESM(require_es6(), 1);
var import_element302 = __toESM(require_element(), 1);
var import_i18n235 = __toESM(require_i18n(), 1);
function isFormValid(formValidity) {
if (!formValidity) {
return true;
}
return Object.values(formValidity).every((fieldValidation) => {
return Object.entries(fieldValidation).every(
([key, validation]) => {
if (key === "children" && validation && typeof validation === "object") {
return isFormValid(validation);
}
return validation.type !== "invalid" && validation.type !== "validating";
}
);
});
}
function getFormFieldsToValidate(form, fields) {
const normalizedForm = normalize_form_default(form);
if (normalizedForm.fields.length === 0) {
return [];
}
const fieldsMap = /* @__PURE__ */ new Map();
fields.forEach((field) => {
fieldsMap.set(field.id, field);
});
function processFormField(formField) {
if ("children" in formField && Array.isArray(formField.children)) {
const processedChildren = formField.children.map(processFormField).filter((child) => child !== null);
if (processedChildren.length === 0) {
return null;
}
const fieldDef2 = fieldsMap.get(formField.id);
if (fieldDef2) {
const [normalizedField2] = normalizeFields([
fieldDef2
]);
return {
id: formField.id,
children: processedChildren,
field: normalizedField2
};
}
return {
id: formField.id,
children: processedChildren
};
}
const fieldDef = fieldsMap.get(formField.id);
if (!fieldDef) {
return null;
}
const [normalizedField] = normalizeFields([fieldDef]);
return {
id: formField.id,
children: [],
field: normalizedField
};
}
const toValidate = normalizedForm.fields.map(processFormField).filter((field) => field !== null);
return toValidate;
}
function setValidityAtPath(formValidity, fieldValidity, path) {
if (!formValidity) {
formValidity = {};
}
if (path.length === 0) {
return formValidity;
}
const result = { ...formValidity };
let current = result;
for (let i2 = 0; i2 < path.length - 1; i2++) {
const segment = path[i2];
if (!current[segment]) {
current[segment] = {};
}
current[segment] = { ...current[segment] };
current = current[segment];
}
const finalKey = path[path.length - 1];
current[finalKey] = {
...current[finalKey] || {},
...fieldValidity
};
return result;
}
function removeValidationProperty(formValidity, path, property) {
if (!formValidity || path.length === 0) {
return formValidity;
}
const result = { ...formValidity };
let current = result;
for (let i2 = 0; i2 < path.length - 1; i2++) {
const segment = path[i2];
if (!current[segment]) {
return formValidity;
}
current[segment] = { ...current[segment] };
current = current[segment];
}
const finalKey = path[path.length - 1];
if (!current[finalKey]) {
return formValidity;
}
const fieldValidity = { ...current[finalKey] };
delete fieldValidity[property];
if (Object.keys(fieldValidity).length === 0) {
delete current[finalKey];
} else {
current[finalKey] = fieldValidity;
}
if (Object.keys(result).length === 0) {
return void 0;
}
return result;
}
function handleElementsValidationAsync(promise, formField, promiseHandler) {
const { elementsCounterRef, setFormValidity, path, item } = promiseHandler;
const currentToken = (elementsCounterRef.current[formField.id] || 0) + 1;
elementsCounterRef.current[formField.id] = currentToken;
promise.then((result) => {
if (currentToken !== elementsCounterRef.current[formField.id]) {
return;
}
if (!Array.isArray(result)) {
setFormValidity((prev) => {
const newFormValidity = setValidityAtPath(
prev,
{
elements: {
type: "invalid",
message: (0, import_i18n235.__)("Could not validate elements.")
}
},
[...path, formField.id]
);
return newFormValidity;
});
return;
}
if (formField.field?.isValid.elements && !formField.field.isValid.elements.validate(item, {
...formField.field,
elements: result
})) {
setFormValidity((prev) => {
const newFormValidity = setValidityAtPath(
prev,
{
elements: {
type: "invalid",
message: (0, import_i18n235.__)(
"Value must be one of the elements."
)
}
},
[...path, formField.id]
);
return newFormValidity;
});
} else {
setFormValidity((prev) => {
return removeValidationProperty(
prev,
[...path, formField.id],
"elements"
);
});
}
}).catch((error2) => {
if (currentToken !== elementsCounterRef.current[formField.id]) {
return;
}
let errorMessage;
if (error2 instanceof Error) {
errorMessage = error2.message;
} else {
errorMessage = String(error2) || (0, import_i18n235.__)(
"Unknown error when running elements validation asynchronously."
);
}
setFormValidity((prev) => {
const newFormValidity = setValidityAtPath(
prev,
{
elements: {
type: "invalid",
message: errorMessage
}
},
[...path, formField.id]
);
return newFormValidity;
});
});
}
function handleCustomValidationAsync(promise, formField, promiseHandler) {
const { customCounterRef, setFormValidity, path } = promiseHandler;
const currentToken = (customCounterRef.current[formField.id] || 0) + 1;
customCounterRef.current[formField.id] = currentToken;
promise.then((result) => {
if (currentToken !== customCounterRef.current[formField.id]) {
return;
}
if (result === null) {
setFormValidity((prev) => {
return removeValidationProperty(
prev,
[...path, formField.id],
"custom"
);
});
return;
}
if (typeof result === "string") {
setFormValidity((prev) => {
const newFormValidity = setValidityAtPath(
prev,
{
custom: {
type: "invalid",
message: result
}
},
[...path, formField.id]
);
return newFormValidity;
});
return;
}
setFormValidity((prev) => {
const newFormValidity = setValidityAtPath(
prev,
{
custom: {
type: "invalid",
message: (0, import_i18n235.__)("Validation could not be processed.")
}
},
[...path, formField.id]
);
return newFormValidity;
});
}).catch((error2) => {
if (currentToken !== customCounterRef.current[formField.id]) {
return;
}
let errorMessage;
if (error2 instanceof Error) {
errorMessage = error2.message;
} else {
errorMessage = String(error2) || (0, import_i18n235.__)(
"Unknown error when running custom validation asynchronously."
);
}
setFormValidity((prev) => {
const newFormValidity = setValidityAtPath(
prev,
{
custom: {
type: "invalid",
message: errorMessage
}
},
[...path, formField.id]
);
return newFormValidity;
});
});
}
function validateFormField(item, formField, promiseHandler) {
if (formField.field?.isValid.required && !formField.field.isValid.required.validate(item, formField.field)) {
return {
required: { type: "invalid" }
};
}
if (formField.field?.isValid.pattern && !formField.field.isValid.pattern.validate(item, formField.field)) {
return {
pattern: {
type: "invalid",
message: (0, import_i18n235.__)("Value does not match the required pattern.")
}
};
}
if (formField.field?.isValid.min && !formField.field.isValid.min.validate(item, formField.field)) {
return {
min: {
type: "invalid",
message: (0, import_i18n235.__)("Value is below the minimum.")
}
};
}
if (formField.field?.isValid.max && !formField.field.isValid.max.validate(item, formField.field)) {
return {
max: {
type: "invalid",
message: (0, import_i18n235.__)("Value is above the maximum.")
}
};
}
if (formField.field?.isValid.minLength && !formField.field.isValid.minLength.validate(item, formField.field)) {
return {
minLength: {
type: "invalid",
message: (0, import_i18n235.__)("Value is too short.")
}
};
}
if (formField.field?.isValid.maxLength && !formField.field.isValid.maxLength.validate(item, formField.field)) {
return {
maxLength: {
type: "invalid",
message: (0, import_i18n235.__)("Value is too long.")
}
};
}
if (formField.field?.isValid.elements && formField.field.hasElements && !formField.field.getElements && Array.isArray(formField.field.elements) && !formField.field.isValid.elements.validate(item, formField.field)) {
return {
elements: {
type: "invalid",
message: (0, import_i18n235.__)("Value must be one of the elements.")
}
};
}
let customError;
if (!!formField.field && formField.field.isValid.custom) {
try {
const value = formField.field.getValue({ item });
customError = formField.field.isValid.custom(
(0, import_deepmerge2.default)(
item,
formField.field.setValue({
item,
value
})
),
formField.field
);
} catch (error2) {
let errorMessage;
if (error2 instanceof Error) {
errorMessage = error2.message;
} else {
errorMessage = String(error2) || (0, import_i18n235.__)("Unknown error when running custom validation.");
}
return {
custom: {
type: "invalid",
message: errorMessage
}
};
}
}
if (typeof customError === "string") {
return {
custom: {
type: "invalid",
message: customError
}
};
}
const fieldValidity = {};
if (!!formField.field && formField.field.isValid.elements && formField.field.hasElements && typeof formField.field.getElements === "function") {
handleElementsValidationAsync(
formField.field.getElements(),
formField,
promiseHandler
);
fieldValidity.elements = {
type: "validating",
message: (0, import_i18n235.__)("Validating\u2026")
};
}
if (customError instanceof Promise) {
handleCustomValidationAsync(customError, formField, promiseHandler);
fieldValidity.custom = {
type: "validating",
message: (0, import_i18n235.__)("Validating\u2026")
};
}
if (Object.keys(fieldValidity).length > 0) {
return fieldValidity;
}
if (formField.children.length > 0) {
const result = {};
formField.children.forEach((child) => {
result[child.id] = validateFormField(item, child, {
...promiseHandler,
path: [...promiseHandler.path, formField.id, "children"]
});
});
const filteredResult = {};
Object.entries(result).forEach(([key, value]) => {
if (value !== void 0) {
filteredResult[key] = value;
}
});
if (Object.keys(filteredResult).length === 0) {
return void 0;
}
return {
children: filteredResult
};
}
return void 0;
}
function getFormFieldValue(formField, item) {
const fieldValue = formField?.field?.getValue({ item });
if (formField.children.length === 0) {
return fieldValue;
}
const childrenValues = formField.children.map(
(child) => getFormFieldValue(child, item)
);
if (!childrenValues) {
return fieldValue;
}
return {
value: fieldValue,
children: childrenValues
};
}
function useFormValidity(item, fields, form) {
const [formValidity, setFormValidity] = (0, import_element302.useState)();
const customCounterRef = (0, import_element302.useRef)({});
const elementsCounterRef = (0, import_element302.useRef)({});
const previousValuesRef = (0, import_element302.useRef)({});
const validate = (0, import_element302.useCallback)(() => {
const promiseHandler = {
customCounterRef,
elementsCounterRef,
setFormValidity,
path: [],
item
};
const formFieldsToValidate = getFormFieldsToValidate(form, fields);
if (formFieldsToValidate.length === 0) {
setFormValidity(void 0);
return;
}
const newFormValidity = {};
const untouchedFields = [];
formFieldsToValidate.forEach((formField) => {
const value = getFormFieldValue(formField, item);
if (previousValuesRef.current.hasOwnProperty(formField.id) && (0, import_es66.default)(
previousValuesRef.current[formField.id],
value
)) {
untouchedFields.push(formField.id);
return;
}
previousValuesRef.current[formField.id] = value;
const fieldValidity = validateFormField(
item,
formField,
promiseHandler
);
if (fieldValidity !== void 0) {
newFormValidity[formField.id] = fieldValidity;
}
});
setFormValidity((existingFormValidity) => {
let validity = {
...existingFormValidity,
...newFormValidity
};
const fieldsToKeep = [
...untouchedFields,
...Object.keys(newFormValidity)
];
Object.keys(validity).forEach((key) => {
if (validity && !fieldsToKeep.includes(key)) {
delete validity[key];
}
});
if (Object.keys(validity).length === 0) {
validity = void 0;
}
const areEqual = (0, import_es66.default)(existingFormValidity, validity);
if (areEqual) {
return existingFormValidity;
}
return validity;
});
}, [item, fields, form]);
(0, import_element302.useEffect)(() => {
validate();
}, [validate]);
return {
validity: formValidity,
isValid: isFormValid(formValidity)
};
}
var use_form_validity_default = useFormValidity;
// packages/dataviews/build-module/hooks/use-report-validity.mjs
var import_element303 = __toESM(require_element(), 1);
function useReportValidity(ref, shouldReport) {
(0, import_element303.useEffect)(() => {
if (shouldReport && ref.current) {
const inputs = ref.current.querySelectorAll(
"input, textarea, select"
);
inputs.forEach((input) => {
input.reportValidity();
});
}
}, [shouldReport, ref]);
}
// packages/dataviews/build-module/components/dataform-layouts/panel/utils/use-field-from-form-field.mjs
var import_element304 = __toESM(require_element(), 1);
// packages/dataviews/build-module/components/dataform-layouts/get-summary-fields.mjs
function extractSummaryIds(summary) {
if (Array.isArray(summary)) {
return summary.map(
(item) => typeof item === "string" ? item : item.id
);
}
return [];
}
var getSummaryFields = (summaryField, fields) => {
if (Array.isArray(summaryField) && summaryField.length > 0) {
const summaryIds = extractSummaryIds(summaryField);
return summaryIds.map(
(summaryId) => fields.find((_field) => _field.id === summaryId)
).filter((_field) => _field !== void 0);
}
return [];
};
// packages/dataviews/build-module/components/dataform-layouts/panel/utils/use-field-from-form-field.mjs
var getFieldDefinition = (field, fields) => {
const fieldDefinition = fields.find((_field) => _field.id === field.id);
if (!fieldDefinition) {
return fields.find((_field) => {
if (!!field.children) {
const simpleChildren = field.children.filter(
(child) => !child.children
);
if (simpleChildren.length === 0) {
return false;
}
return _field.id === simpleChildren[0].id;
}
return _field.id === field.id;
});
}
return fieldDefinition;
};
function useFieldFromFormField(field) {
const { fields } = (0, import_element304.useContext)(dataform_context_default);
const layout = field.layout;
const summaryFields = getSummaryFields(layout.summary, fields);
const fieldDefinition = getFieldDefinition(field, fields);
const fieldLabel = !!field.children ? field.label : fieldDefinition?.label;
if (summaryFields.length === 0) {
return {
summaryFields: fieldDefinition ? [fieldDefinition] : [],
fieldDefinition,
fieldLabel
};
}
return {
summaryFields,
fieldDefinition,
fieldLabel
};
}
var use_field_from_form_field_default = useFieldFromFormField;
// packages/dataviews/build-module/components/dataform-layouts/panel/modal.mjs
var import_jsx_runtime500 = __toESM(require_jsx_runtime(), 1);
function ModalContent({
data,
field,
onChange,
fieldLabel,
onClose,
touched
}) {
const { openAs } = field.layout;
const { applyLabel, cancelLabel } = openAs;
const { fields } = (0, import_element305.useContext)(dataform_context_default);
const [changes, setChanges] = (0, import_element305.useState)({});
const modalData = (0, import_element305.useMemo)(() => {
return (0, import_deepmerge3.default)(data, changes, {
arrayMerge: (target, source) => source
});
}, [data, changes]);
const form = (0, import_element305.useMemo)(
() => ({
layout: DEFAULT_LAYOUT,
fields: !!field.children ? field.children : (
// If not explicit children return the field id itself.
[{ id: field.id, layout: DEFAULT_LAYOUT }]
)
}),
[field]
);
const fieldsAsFieldType = fields.map((f2) => ({
...f2,
Edit: f2.Edit === null ? void 0 : f2.Edit,
isValid: {
required: f2.isValid.required?.constraint,
elements: f2.isValid.elements?.constraint,
min: f2.isValid.min?.constraint,
max: f2.isValid.max?.constraint,
pattern: f2.isValid.pattern?.constraint,
minLength: f2.isValid.minLength?.constraint,
maxLength: f2.isValid.maxLength?.constraint
}
}));
const { validity } = use_form_validity_default(modalData, fieldsAsFieldType, form);
const onApply = () => {
onChange(changes);
onClose();
};
const handleOnChange = (newValue) => {
setChanges(
(prev) => (0, import_deepmerge3.default)(prev, newValue, {
arrayMerge: (target, source) => source
})
);
};
const focusOnMountRef = (0, import_compose101.useFocusOnMount)("firstInputElement");
const contentRef = (0, import_element305.useRef)(null);
const mergedRef = (0, import_compose101.useMergeRefs)([focusOnMountRef, contentRef]);
useReportValidity(contentRef, touched);
return /* @__PURE__ */ (0, import_jsx_runtime500.jsxs)(
import_components256.Modal,
{
className: "dataforms-layouts-panel__modal",
onRequestClose: onClose,
isFullScreen: false,
title: fieldLabel,
size: "medium",
children: [
/* @__PURE__ */ (0, import_jsx_runtime500.jsx)("div", { ref: mergedRef, children: /* @__PURE__ */ (0, import_jsx_runtime500.jsx)(
DataFormLayout,
{
data: modalData,
form,
onChange: handleOnChange,
validity,
children: (FieldLayout, childField, childFieldValidity, markWhenOptional) => /* @__PURE__ */ (0, import_jsx_runtime500.jsx)(
FieldLayout,
{
data: modalData,
field: childField,
onChange: handleOnChange,
hideLabelFromVision: form.fields.length < 2,
markWhenOptional,
validity: childFieldValidity
},
childField.id
)
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime500.jsxs)(
Stack,
{
direction: "row",
className: "dataforms-layouts-panel__modal-footer",
gap: "md",
children: [
/* @__PURE__ */ (0, import_jsx_runtime500.jsx)(import_components256.__experimentalSpacer, { style: { flex: 1 } }),
/* @__PURE__ */ (0, import_jsx_runtime500.jsx)(
import_components256.Button,
{
variant: "tertiary",
onClick: onClose,
__next40pxDefaultSize: true,
children: cancelLabel
}
),
/* @__PURE__ */ (0, import_jsx_runtime500.jsx)(
import_components256.Button,
{
variant: "primary",
onClick: onApply,
__next40pxDefaultSize: true,
children: applyLabel
}
)
]
}
)
]
}
);
}
function PanelModal({
data,
field,
onChange,
validity
}) {
const [touched, setTouched] = (0, import_element305.useState)(false);
const [isOpen, setIsOpen] = (0, import_element305.useState)(false);
const { fieldDefinition, fieldLabel, summaryFields } = use_field_from_form_field_default(field);
if (!fieldDefinition) {
return null;
}
const handleClose = () => {
setIsOpen(false);
setTouched(true);
};
return /* @__PURE__ */ (0, import_jsx_runtime500.jsxs)(import_jsx_runtime500.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime500.jsx)(
SummaryButton,
{
data,
field,
fieldLabel,
summaryFields,
validity,
touched,
disabled: fieldDefinition.readOnly === true,
onClick: () => setIsOpen(true),
isOpen
}
),
isOpen && /* @__PURE__ */ (0, import_jsx_runtime500.jsx)(
ModalContent,
{
data,
field,
onChange,
fieldLabel: fieldLabel ?? "",
onClose: handleClose,
touched
}
)
] });
}
var modal_default = PanelModal;
// packages/dataviews/build-module/components/dataform-layouts/panel/dropdown.mjs
var import_components257 = __toESM(require_components(), 1);
var import_i18n236 = __toESM(require_i18n(), 1);
var import_element306 = __toESM(require_element(), 1);
var import_compose102 = __toESM(require_compose(), 1);
var import_jsx_runtime501 = __toESM(require_jsx_runtime(), 1);
function DropdownHeader({
title,
onClose
}) {
return /* @__PURE__ */ (0, import_jsx_runtime501.jsx)(
Stack,
{
direction: "column",
className: "dataforms-layouts-panel__dropdown-header",
gap: "lg",
children: /* @__PURE__ */ (0, import_jsx_runtime501.jsxs)(Stack, { direction: "row", gap: "sm", align: "center", children: [
title && /* @__PURE__ */ (0, import_jsx_runtime501.jsx)(import_components257.__experimentalHeading, { level: 2, size: 13, children: title }),
/* @__PURE__ */ (0, import_jsx_runtime501.jsx)(import_components257.__experimentalSpacer, { style: { flex: 1 } }),
onClose && /* @__PURE__ */ (0, import_jsx_runtime501.jsx)(
import_components257.Button,
{
label: (0, import_i18n236.__)("Close"),
icon: close_small_default,
onClick: onClose,
size: "small"
}
)
] })
}
);
}
function DropdownContentWithValidation({
touched,
children
}) {
const ref = (0, import_element306.useRef)(null);
useReportValidity(ref, touched);
return /* @__PURE__ */ (0, import_jsx_runtime501.jsx)("div", { ref, children });
}
function PanelDropdown({
data,
field,
onChange,
validity
}) {
const [touched, setTouched] = (0, import_element306.useState)(false);
const [popoverAnchor, setPopoverAnchor] = (0, import_element306.useState)(
null
);
const popoverProps3 = (0, import_element306.useMemo)(
() => ({
// Anchor the popover to the middle of the entire row so that it doesn't
// move around when the label changes.
anchor: popoverAnchor,
placement: "left-start",
offset: 36,
shift: true
}),
[popoverAnchor]
);
const [dialogRef, dialogProps] = (0, import_compose102.__experimentalUseDialog)({
focusOnMount: "firstInputElement"
});
const form = (0, import_element306.useMemo)(
() => ({
layout: DEFAULT_LAYOUT,
fields: !!field.children ? field.children : (
// If not explicit children return the field id itself.
[{ id: field.id, layout: DEFAULT_LAYOUT }]
)
}),
[field]
);
const formValidity = (0, import_element306.useMemo)(() => {
if (validity === void 0) {
return void 0;
}
if (!!field.children) {
return validity?.children;
}
return { [field.id]: validity };
}, [validity, field]);
const { fieldDefinition, fieldLabel, summaryFields } = use_field_from_form_field_default(field);
if (!fieldDefinition) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime501.jsx)(
"div",
{
ref: setPopoverAnchor,
className: "dataforms-layouts-panel__field-dropdown-anchor",
children: /* @__PURE__ */ (0, import_jsx_runtime501.jsx)(
import_components257.Dropdown,
{
contentClassName: "dataforms-layouts-panel__field-dropdown",
popoverProps: popoverProps3,
focusOnMount: false,
onToggle: (willOpen) => {
if (!willOpen) {
setTouched(true);
}
},
renderToggle: ({ isOpen, onToggle }) => /* @__PURE__ */ (0, import_jsx_runtime501.jsx)(
SummaryButton,
{
data,
field,
fieldLabel,
summaryFields,
validity,
touched,
disabled: fieldDefinition.readOnly === true,
isOpen,
onClick: onToggle
}
),
renderContent: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime501.jsx)(DropdownContentWithValidation, { touched, children: /* @__PURE__ */ (0, import_jsx_runtime501.jsxs)("div", { ref: dialogRef, ...dialogProps, children: [
/* @__PURE__ */ (0, import_jsx_runtime501.jsx)(
DropdownHeader,
{
title: fieldLabel,
onClose
}
),
/* @__PURE__ */ (0, import_jsx_runtime501.jsx)(
DataFormLayout,
{
data,
form,
onChange,
validity: formValidity,
children: (FieldLayout, childField, childFieldValidity, markWhenOptional) => /* @__PURE__ */ (0, import_jsx_runtime501.jsx)(
FieldLayout,
{
data,
field: childField,
onChange,
hideLabelFromVision: (form?.fields ?? []).length < 2,
markWhenOptional,
validity: childFieldValidity
},
childField.id
)
}
)
] }) })
}
)
}
);
}
var dropdown_default2 = PanelDropdown;
// packages/dataviews/build-module/components/dataform-layouts/panel/index.mjs
var import_jsx_runtime502 = __toESM(require_jsx_runtime(), 1);
function FormPanelField({
data,
field,
onChange,
validity
}) {
const layout = field.layout;
if (layout.openAs.type === "modal") {
return /* @__PURE__ */ (0, import_jsx_runtime502.jsx)(
modal_default,
{
data,
field,
onChange,
validity
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime502.jsx)(
dropdown_default2,
{
data,
field,
onChange,
validity
}
);
}
// packages/dataviews/build-module/components/dataform-layouts/card/index.mjs
var import_element307 = __toESM(require_element(), 1);
// packages/dataviews/build-module/components/dataform-layouts/validation-badge.mjs
var import_i18n237 = __toESM(require_i18n(), 1);
var import_jsx_runtime503 = __toESM(require_jsx_runtime(), 1);
function countInvalidFields(validity) {
if (!validity) {
return 0;
}
let count = 0;
const validityRules = Object.keys(validity).filter(
(key) => key !== "children"
);
for (const key of validityRules) {
const rule = validity[key];
if (rule?.type === "invalid") {
count++;
}
}
if (validity.children) {
for (const childValidity of Object.values(validity.children)) {
count += countInvalidFields(childValidity);
}
}
return count;
}
function ValidationBadge({
validity
}) {
const invalidCount = countInvalidFields(validity);
if (invalidCount === 0) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime503.jsx)(Badge, { intent: "high", children: (0, import_i18n237.sprintf)(
/* translators: %d: Number of fields that need attention */
(0, import_i18n237._n)(
"%d field needs attention",
"%d fields need attention",
invalidCount
),
invalidCount
) });
}
// packages/dataviews/build-module/components/dataform-layouts/card/index.mjs
var import_jsx_runtime504 = __toESM(require_jsx_runtime(), 1);
function isSummaryFieldVisible(summaryField, summaryConfig, isOpen) {
if (!summaryConfig || Array.isArray(summaryConfig) && summaryConfig.length === 0) {
return false;
}
const summaryConfigArray = Array.isArray(summaryConfig) ? summaryConfig : [summaryConfig];
const fieldConfig = summaryConfigArray.find((config2) => {
if (typeof config2 === "string") {
return config2 === summaryField.id;
}
if (typeof config2 === "object" && "id" in config2) {
return config2.id === summaryField.id;
}
return false;
});
if (!fieldConfig) {
return false;
}
if (typeof fieldConfig === "string") {
return true;
}
if (typeof fieldConfig === "object" && "visibility" in fieldConfig) {
return fieldConfig.visibility === "always" || fieldConfig.visibility === "when-collapsed" && !isOpen;
}
return true;
}
function HeaderContent({
data,
fields,
label,
layout,
isOpen,
touched,
validity
}) {
const summaryFields = getSummaryFields(layout.summary, fields);
const visibleSummaryFields = summaryFields.filter(
(summaryField) => isSummaryFieldVisible(summaryField, layout.summary, isOpen)
);
const hasBadge = touched && layout.isCollapsible;
const hasSummary = visibleSummaryFields.length > 0 && layout.withHeader;
return /* @__PURE__ */ (0, import_jsx_runtime504.jsxs)(
Stack,
{
align: "center",
justify: "space-between",
className: "dataforms-layouts-card__field-header-content",
children: [
/* @__PURE__ */ (0, import_jsx_runtime504.jsx)(card_exports.Title, { children: label }),
(hasBadge || hasSummary) && /* @__PURE__ */ (0, import_jsx_runtime504.jsxs)(collapsible_card_exports.HeaderDescription, { className: "dataforms-layouts-card__field-header-content-description", children: [
hasBadge && /* @__PURE__ */ (0, import_jsx_runtime504.jsx)(ValidationBadge, { validity }),
hasSummary && /* @__PURE__ */ (0, import_jsx_runtime504.jsx)("div", { className: "dataforms-layouts-card__field-summary", children: visibleSummaryFields.map((summaryField) => /* @__PURE__ */ (0, import_jsx_runtime504.jsx)(
summaryField.render,
{
item: data,
field: summaryField
},
summaryField.id
)) })
] })
]
}
);
}
function BodyContent({
data,
field,
form,
onChange,
hideLabelFromVision,
markWhenOptional,
validity,
withHeader
}) {
if (field.children) {
return /* @__PURE__ */ (0, import_jsx_runtime504.jsxs)(import_jsx_runtime504.Fragment, { children: [
field.description && /* @__PURE__ */ (0, import_jsx_runtime504.jsx)("div", { className: "dataforms-layouts-card__field-description", children: field.description }),
/* @__PURE__ */ (0, import_jsx_runtime504.jsx)(
DataFormLayout,
{
data,
form,
onChange,
validity: validity?.children
}
)
] });
}
const SingleFieldLayout = getFormFieldLayout("regular")?.component;
if (!SingleFieldLayout) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime504.jsx)(
SingleFieldLayout,
{
data,
field,
onChange,
hideLabelFromVision: hideLabelFromVision || withHeader,
markWhenOptional,
validity
}
);
}
function FormCardField({
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
validity
}) {
const { fields } = (0, import_element307.useContext)(dataform_context_default);
const layout = field.layout;
const contentRef = (0, import_element307.useRef)(null);
const form = (0, import_element307.useMemo)(
() => ({
layout: DEFAULT_LAYOUT,
fields: field.children ?? []
}),
[field]
);
const { isOpened, isCollapsible } = layout;
const [isOpen, setIsOpen] = (0, import_element307.useState)(isOpened);
const [touched, setTouched] = (0, import_element307.useState)(false);
(0, import_element307.useEffect)(() => {
setIsOpen(isOpened);
}, [isOpened]);
const handleOpenChange = (0, import_element307.useCallback)((open) => {
if (!open) {
setTouched(true);
}
setIsOpen(open);
}, []);
const handleBlur = (0, import_element307.useCallback)(() => {
setTouched(true);
}, []);
useReportValidity(
contentRef,
(isCollapsible ? isOpen : true) && touched
);
let label = field.label;
let withHeader;
if (field.children) {
withHeader = !!label && layout.withHeader;
} else {
const fieldDefinition = fields.find(
(fieldDef) => fieldDef.id === field.id
);
if (!fieldDefinition || !fieldDefinition.Edit) {
return null;
}
label = fieldDefinition.label;
withHeader = !!label && layout.withHeader;
}
const bodyContent = /* @__PURE__ */ (0, import_jsx_runtime504.jsx)(
BodyContent,
{
data,
field,
form,
onChange,
hideLabelFromVision,
markWhenOptional,
validity,
withHeader
}
);
const headerContent = /* @__PURE__ */ (0, import_jsx_runtime504.jsx)(
HeaderContent,
{
data,
fields,
label,
layout,
isOpen: isCollapsible ? !!isOpen : true,
touched,
validity
}
);
if (withHeader && isCollapsible) {
return /* @__PURE__ */ (0, import_jsx_runtime504.jsxs)(
collapsible_card_exports.Root,
{
className: "dataforms-layouts-card__field",
open: isOpen,
onOpenChange: handleOpenChange,
children: [
/* @__PURE__ */ (0, import_jsx_runtime504.jsx)(collapsible_card_exports.Header, { children: headerContent }),
/* @__PURE__ */ (0, import_jsx_runtime504.jsx)(
collapsible_card_exports.Content,
{
ref: contentRef,
onBlur: handleBlur,
children: bodyContent
}
)
]
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime504.jsxs)(card_exports.Root, { className: "dataforms-layouts-card__field", children: [
withHeader && /* @__PURE__ */ (0, import_jsx_runtime504.jsx)(card_exports.Header, { children: headerContent }),
/* @__PURE__ */ (0, import_jsx_runtime504.jsx)(card_exports.Content, { ref: contentRef, onBlur: handleBlur, children: bodyContent })
] });
}
// packages/dataviews/build-module/components/dataform-layouts/row/index.mjs
var import_components258 = __toESM(require_components(), 1);
var import_jsx_runtime505 = __toESM(require_jsx_runtime(), 1);
function Header4({ title }) {
return /* @__PURE__ */ (0, import_jsx_runtime505.jsx)(
Stack,
{
direction: "column",
className: "dataforms-layouts-row__header",
gap: "lg",
children: /* @__PURE__ */ (0, import_jsx_runtime505.jsx)(Stack, { direction: "row", align: "center", children: /* @__PURE__ */ (0, import_jsx_runtime505.jsx)(import_components258.__experimentalHeading, { level: 2, size: 13, children: title }) })
}
);
}
var EMPTY_WRAPPER = ({ children }) => /* @__PURE__ */ (0, import_jsx_runtime505.jsx)(import_jsx_runtime505.Fragment, { children });
function FormRowField({
data,
field,
onChange,
hideLabelFromVision,
markWhenOptional,
validity
}) {
const layout = field.layout;
if (!!field.children) {
const form = {
layout: DEFAULT_LAYOUT,
fields: field.children
};
return /* @__PURE__ */ (0, import_jsx_runtime505.jsxs)("div", { className: "dataforms-layouts-row__field", children: [
!hideLabelFromVision && field.label && /* @__PURE__ */ (0, import_jsx_runtime505.jsx)(Header4, { title: field.label }),
/* @__PURE__ */ (0, import_jsx_runtime505.jsx)(Stack, { direction: "row", align: layout.alignment, gap: "lg", children: /* @__PURE__ */ (0, import_jsx_runtime505.jsx)(
DataFormLayout,
{
data,
form,
onChange,
validity: validity?.children,
as: EMPTY_WRAPPER,
children: (FieldLayout, childField, childFieldValidity) => /* @__PURE__ */ (0, import_jsx_runtime505.jsx)(
"div",
{
className: "dataforms-layouts-row__field-control",
style: layout.styles[childField.id],
children: /* @__PURE__ */ (0, import_jsx_runtime505.jsx)(
FieldLayout,
{
data,
field: childField,
onChange,
hideLabelFromVision,
markWhenOptional,
validity: childFieldValidity
}
)
},
childField.id
)
}
) })
] });
}
const RegularLayout = getFormFieldLayout("regular")?.component;
if (!RegularLayout) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime505.jsx)(import_jsx_runtime505.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime505.jsx)("div", { className: "dataforms-layouts-row__field-control", children: /* @__PURE__ */ (0, import_jsx_runtime505.jsx)(
RegularLayout,
{
data,
field,
onChange,
markWhenOptional,
validity
}
) }) });
}
// packages/dataviews/build-module/components/dataform-layouts/details/index.mjs
var import_element308 = __toESM(require_element(), 1);
var import_i18n238 = __toESM(require_i18n(), 1);
var import_jsx_runtime506 = __toESM(require_jsx_runtime(), 1);
function FormDetailsField({
data,
field,
onChange,
validity
}) {
const { fields } = (0, import_element308.useContext)(dataform_context_default);
const detailsRef = (0, import_element308.useRef)(null);
const contentRef = (0, import_element308.useRef)(null);
const [touched, setTouched] = (0, import_element308.useState)(false);
const [isOpen, setIsOpen] = (0, import_element308.useState)(false);
const form = (0, import_element308.useMemo)(
() => ({
layout: DEFAULT_LAYOUT,
fields: field.children ?? []
}),
[field]
);
(0, import_element308.useEffect)(() => {
const details = detailsRef.current;
if (!details) {
return;
}
const handleToggle = () => {
const nowOpen = details.open;
if (!nowOpen) {
setTouched(true);
}
setIsOpen(nowOpen);
};
details.addEventListener("toggle", handleToggle);
return () => {
details.removeEventListener("toggle", handleToggle);
};
}, []);
useReportValidity(contentRef, isOpen && touched);
const handleBlur = (0, import_element308.useCallback)(() => {
setTouched(true);
}, []);
if (!field.children) {
return null;
}
const summaryFieldId = field.layout.summary ?? "";
const summaryField = summaryFieldId ? fields.find((fieldDef) => fieldDef.id === summaryFieldId) : void 0;
let summaryContent;
if (summaryField && summaryField.render) {
summaryContent = /* @__PURE__ */ (0, import_jsx_runtime506.jsx)(summaryField.render, { item: data, field: summaryField });
} else {
summaryContent = field.label || (0, import_i18n238.__)("More details");
}
return /* @__PURE__ */ (0, import_jsx_runtime506.jsxs)(
"details",
{
ref: detailsRef,
className: "dataforms-layouts-details__details",
children: [
/* @__PURE__ */ (0, import_jsx_runtime506.jsx)("summary", { className: "dataforms-layouts-details__summary", children: /* @__PURE__ */ (0, import_jsx_runtime506.jsxs)(
Stack,
{
direction: "row",
align: "center",
gap: "md",
className: "dataforms-layouts-details__summary-content",
children: [
summaryContent,
touched && /* @__PURE__ */ (0, import_jsx_runtime506.jsx)(ValidationBadge, { validity })
]
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime506.jsx)(
"div",
{
ref: contentRef,
className: "dataforms-layouts-details__content",
onBlur: handleBlur,
children: /* @__PURE__ */ (0, import_jsx_runtime506.jsx)(
DataFormLayout,
{
data,
form,
onChange,
validity: validity?.children
}
)
}
)
]
}
);
}
// packages/dataviews/build-module/components/dataform-layouts/index.mjs
var import_jsx_runtime507 = __toESM(require_jsx_runtime(), 1);
var FORM_FIELD_LAYOUTS = [
{
type: "regular",
component: FormRegularField,
wrapper: ({ children }) => /* @__PURE__ */ (0, import_jsx_runtime507.jsx)(
Stack,
{
direction: "column",
className: "dataforms-layouts__wrapper",
gap: "lg",
children
}
)
},
{
type: "panel",
component: FormPanelField,
wrapper: ({ children }) => /* @__PURE__ */ (0, import_jsx_runtime507.jsx)(
Stack,
{
direction: "column",
className: "dataforms-layouts__wrapper",
gap: "md",
children
}
)
},
{
type: "card",
component: FormCardField,
wrapper: ({ children }) => /* @__PURE__ */ (0, import_jsx_runtime507.jsx)(
Stack,
{
direction: "column",
className: "dataforms-layouts__wrapper",
gap: "xl",
children
}
)
},
{
type: "row",
component: FormRowField,
wrapper: ({
children,
layout
}) => /* @__PURE__ */ (0, import_jsx_runtime507.jsx)(
Stack,
{
direction: "column",
className: "dataforms-layouts__wrapper",
gap: "lg",
children: /* @__PURE__ */ (0, import_jsx_runtime507.jsx)("div", { className: "dataforms-layouts-row__field", children: /* @__PURE__ */ (0, import_jsx_runtime507.jsx)(
Stack,
{
direction: "row",
gap: "lg",
align: layout.alignment,
children
}
) })
}
)
},
{
type: "details",
component: FormDetailsField
}
];
function getFormFieldLayout(type) {
return FORM_FIELD_LAYOUTS.find((layout) => layout.type === type);
}
// packages/dataviews/build-module/components/dataform-layouts/data-form-layout.mjs
var import_jsx_runtime508 = __toESM(require_jsx_runtime(), 1);
var DEFAULT_WRAPPER = ({ children }) => /* @__PURE__ */ (0, import_jsx_runtime508.jsx)(Stack, { direction: "column", className: "dataforms-layouts__wrapper", gap: "lg", children });
function DataFormLayout({
data,
form,
onChange,
validity,
children,
as
}) {
const { fields: fieldDefinitions } = (0, import_element309.useContext)(dataform_context_default);
const markWhenOptional = (0, import_element309.useMemo)(() => {
const requiredCount = fieldDefinitions.filter(
(f2) => !!f2.isValid?.required
).length;
const optionalCount = fieldDefinitions.length - requiredCount;
return requiredCount > optionalCount;
}, [fieldDefinitions]);
function getFieldDefinition2(field) {
return fieldDefinitions.find(
(fieldDefinition) => fieldDefinition.id === field.id
);
}
const Wrapper = as ?? getFormFieldLayout(form.layout.type)?.wrapper ?? DEFAULT_WRAPPER;
return /* @__PURE__ */ (0, import_jsx_runtime508.jsx)(Wrapper, { layout: form.layout, children: form.fields.map((formField) => {
const FieldLayout = getFormFieldLayout(formField.layout.type)?.component;
if (!FieldLayout) {
return null;
}
const fieldDefinition = !formField.children ? getFieldDefinition2(formField) : void 0;
if (fieldDefinition && fieldDefinition.isVisible && !fieldDefinition.isVisible(data)) {
return null;
}
if (children) {
return children(
FieldLayout,
formField,
validity?.[formField.id],
markWhenOptional
);
}
return /* @__PURE__ */ (0, import_jsx_runtime508.jsx)(
FieldLayout,
{
data,
field: formField,
onChange,
markWhenOptional,
validity: validity?.[formField.id]
},
formField.id
);
}) });
}
// packages/dataviews/build-module/dataform/index.mjs
var import_jsx_runtime509 = __toESM(require_jsx_runtime(), 1);
function DataForm({
data,
form,
fields,
onChange,
validity
}) {
const normalizedForm = (0, import_element310.useMemo)(() => normalize_form_default(form), [form]);
const normalizedFields = (0, import_element310.useMemo)(
() => normalizeFields(fields),
[fields]
);
if (!form.fields) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime509.jsx)(DataFormProvider, { fields: normalizedFields, children: /* @__PURE__ */ (0, import_jsx_runtime509.jsx)(
DataFormLayout,
{
data,
form: normalizedForm,
onChange,
validity
}
) });
}
// packages/block-editor/build-module/hooks/block-fields/index.mjs
var import_element314 = __toESM(require_element(), 1);
var import_i18n242 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/hooks/block-fields/fields-dropdown-menu.mjs
var import_components259 = __toESM(require_components(), 1);
var import_i18n239 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/hooks/block-fields/use-inspector-popover-placement.mjs
var import_compose103 = __toESM(require_compose(), 1);
function useInspectorPopoverPlacement2({ isControl } = { isControl: false }) {
const isMobile = (0, import_compose103.useViewportMatch)("medium", "<");
return !isMobile ? {
popoverProps: {
placement: "left-start",
// For non-mobile, inner sidebar width (248px) - button width (24px) - border (1px) + padding (16px) + spacing (20px)
offset: isControl ? 35 : 259
}
} : {};
}
// packages/block-editor/build-module/hooks/block-fields/fields-dropdown-menu.mjs
var import_jsx_runtime510 = __toESM(require_jsx_runtime(), 1);
function FieldsDropdownMenu({
fields,
visibleFields,
onToggleField
}) {
const { popoverProps: popoverProps3 } = useInspectorPopoverPlacement2();
if (!fields || fields.length === 0) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime510.jsx)(
import_components259.DropdownMenu,
{
icon: more_vertical_default,
label: (0, import_i18n239.__)("Options"),
popoverProps: popoverProps3,
toggleProps: { size: "small" },
children: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime510.jsx)(import_components259.MenuGroup, { label: (0, import_i18n239.__)("Show / Hide"), children: fields.map((field) => {
const isVisible = visibleFields.includes(field.id);
return /* @__PURE__ */ (0, import_jsx_runtime510.jsx)(
import_components259.MenuItem,
{
isSelected: isVisible,
onClick: () => {
onToggleField(field.id);
onClose();
},
role: "menuitemcheckbox",
icon: isVisible ? check_default : null,
children: field.label
},
field.id
);
}) })
}
);
}
// packages/block-editor/build-module/hooks/block-fields/rich-text/index.mjs
var import_components260 = __toESM(require_components(), 1);
var import_compose104 = __toESM(require_compose(), 1);
var import_data183 = __toESM(require_data(), 1);
var import_element311 = __toESM(require_element(), 1);
var import_rich_text24 = __toESM(require_rich_text(), 1);
var import_jsx_runtime511 = __toESM(require_jsx_runtime(), 1);
var { useRichText: useRichText3, KeyboardShortcutContext: KeyboardShortcutContext3, InputEventContext: InputEventContext3 } = unlock(import_rich_text24.privateApis);
function RichTextControl2({
data,
field,
hideLabelFromVision,
onChange,
config: config2 = {}
}) {
const registry = (0, import_data183.useRegistry)();
const attrValue = field.getValue({ item: data });
const fieldConfig = field.config || {};
const { clientId } = config2;
const [selection2, setSelection] = (0, import_element311.useState)({
start: void 0,
end: void 0
});
const [isSelected, setIsSelected] = (0, import_element311.useState)(false);
const anchorRef = (0, import_element311.useRef)();
const inputEvents = (0, import_element311.useRef)(/* @__PURE__ */ new Set());
const keyboardShortcuts = (0, import_element311.useRef)(/* @__PURE__ */ new Set());
const adjustedAllowedFormats = getAllowedFormats({
allowedFormats: fieldConfig?.allowedFormats,
disableFormats: fieldConfig?.disableFormats
});
function onFocus() {
anchorRef.current?.focus();
}
const {
value,
getValue,
onChange: onRichTextChange,
ref: richTextRef,
formatTypes
} = useRichText3({
value: attrValue,
onChange(html) {
onChange(field.setValue({ item: data, value: html }));
},
selectionStart: selection2.start,
selectionEnd: selection2.end,
onSelectionChange: (start2, end) => setSelection({ start: start2, end }),
__unstableIsSelected: isSelected,
preserveWhiteSpace: !!fieldConfig?.preserveWhiteSpace,
placeholder: fieldConfig?.placeholder,
__unstableDisableFormats: fieldConfig?.disableFormats,
allowedFormats: adjustedAllowedFormats,
withoutInteractiveFormatting: fieldConfig?.withoutInteractiveFormatting,
__unstableFormatTypeHandlerContext: (0, import_element311.useMemo)(
() => ({ richTextIdentifier: field.id, blockClientId: clientId }),
[field.id, clientId]
)
});
const { baseControlProps, controlProps } = (0, import_components260.useBaseControlProps)({
hideLabelFromVision: hideLabelFromVision ?? field.hideLabelFromVision,
label: field.label
});
return /* @__PURE__ */ (0, import_jsx_runtime511.jsxs)(import_jsx_runtime511.Fragment, { children: [
isSelected && /* @__PURE__ */ (0, import_jsx_runtime511.jsx)(KeyboardShortcutContext3.Provider, { value: keyboardShortcuts, children: /* @__PURE__ */ (0, import_jsx_runtime511.jsx)(InputEventContext3.Provider, { value: inputEvents, children: /* @__PURE__ */ (0, import_jsx_runtime511.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime511.jsx)(
FormatEdit,
{
value,
onChange: onRichTextChange,
onFocus,
formatTypes,
forwardedRef: anchorRef,
isVisible: false
}
) }) }) }),
/* @__PURE__ */ (0, import_jsx_runtime511.jsx)(import_components260.BaseControl, { ...baseControlProps, children: /* @__PURE__ */ (0, import_jsx_runtime511.jsx)(
"div",
{
className: "block-editor-content-only-controls__rich-text",
role: "textbox",
"aria-multiline": !fieldConfig?.disableLineBreaks,
ref: (0, import_compose104.useMergeRefs)([
richTextRef,
useEventListeners({
registry,
getValue,
onChange: onRichTextChange,
formatTypes,
selectionChange: setSelection,
isSelected,
disableFormats: fieldConfig?.disableFormats,
value,
tagName: "div",
disableLineBreaks: fieldConfig?.disableLineBreaks,
keyboardShortcuts,
inputEvents
}),
anchorRef
]),
onFocus: () => setIsSelected(true),
onBlur: () => setIsSelected(false),
contentEditable: true,
...controlProps
}
) })
] });
}
// packages/block-editor/build-module/hooks/block-fields/media/index.mjs
var import_components261 = __toESM(require_components(), 1);
var import_data184 = __toESM(require_data(), 1);
var import_dom72 = __toESM(require_dom(), 1);
var import_element312 = __toESM(require_element(), 1);
var import_i18n240 = __toESM(require_i18n(), 1);
var import_jsx_runtime512 = __toESM(require_jsx_runtime(), 1);
var focusToggleButton2 = (containerRef) => {
window.requestAnimationFrame(() => {
const [toggleButton] = import_dom72.focus.tabbable.find(containerRef?.current);
if (!toggleButton) {
return;
}
toggleButton.focus();
});
};
function MediaThumbnail({ data, field, attachment, config: config2 }) {
const { allowedTypes = [], multiple = false } = config2 || {};
if (multiple) {
return "todo multiple";
}
if (attachment?.media_type === "image" || attachment?.poster) {
return /* @__PURE__ */ (0, import_jsx_runtime512.jsx)("div", { className: "block-editor-content-only-controls__media-thumbnail", children: /* @__PURE__ */ (0, import_jsx_runtime512.jsx)(
"img",
{
alt: "",
width: 20,
height: 20,
src: attachment.media_type === "image" ? attachment.source_url : attachment.poster
}
) });
}
if (allowedTypes.length === 1) {
const value = field.getValue({ item: data });
const url = value?.url;
if (allowedTypes[0] === "image" && url) {
return /* @__PURE__ */ (0, import_jsx_runtime512.jsx)("div", { className: "block-editor-content-only-controls__media-thumbnail", children: /* @__PURE__ */ (0, import_jsx_runtime512.jsx)("img", { alt: "", width: 20, height: 20, src: url }) });
}
let icon;
if (allowedTypes[0] === "image") {
icon = image_default;
} else if (allowedTypes[0] === "video") {
icon = video_default;
} else if (allowedTypes[0] === "audio") {
icon = audio_default;
} else {
icon = media_default;
}
if (icon) {
return /* @__PURE__ */ (0, import_jsx_runtime512.jsx)(import_components261.Icon, { icon, size: 20 });
}
}
return /* @__PURE__ */ (0, import_jsx_runtime512.jsx)(import_components261.Icon, { icon: media_default, size: 20 });
}
function Media({ data, field, onChange, config: config2 = {} }) {
const { popoverProps: popoverProps3 } = useInspectorPopoverPlacement2({
isControl: true
});
const value = field.getValue({ item: data });
const {
allowedTypes = [],
multiple = false,
useFeaturedImage = false
} = config2;
const id = value?.id;
const url = value?.url;
const attachment = (0, import_data184.useSelect)(
(select3) => {
if (!id) {
return;
}
const settings2 = select3(store).getSettings();
const getMedia = settings2[getMediaSelectKey];
if (!getMedia) {
return;
}
return getMedia(select3, id);
},
[id]
);
let chooseItemLabel;
if (allowedTypes.length === 1) {
const allowedType = allowedTypes[0];
if (allowedType === "image") {
chooseItemLabel = (0, import_i18n240.__)("Image");
} else if (allowedType === "video") {
chooseItemLabel = (0, import_i18n240.__)("Video");
} else if (allowedType === "application") {
chooseItemLabel = (0, import_i18n240.__)("File");
} else {
chooseItemLabel = (0, import_i18n240.__)("Media");
}
} else {
chooseItemLabel = (0, import_i18n240.__)("Media");
}
const containerRef = (0, import_element312.useRef)();
return /* @__PURE__ */ (0, import_jsx_runtime512.jsx)(check_default2, { children: /* @__PURE__ */ (0, import_jsx_runtime512.jsxs)(
"div",
{
ref: containerRef,
className: "block-editor-content-only-controls",
children: [
/* @__PURE__ */ (0, import_jsx_runtime512.jsx)(
media_replace_flow_default,
{
className: "block-editor-content-only-controls__media-replace-flow",
allowedTypes,
mediaId: id,
mediaURL: url,
multiple,
popoverProps: popoverProps3,
onReset: () => {
onChange(
field.setValue({
item: data,
value: {}
})
);
},
...useFeaturedImage && {
useFeaturedImage: !!value?.featuredImage,
onToggleFeaturedImage: () => {
onChange(
field.setValue({
item: data,
value: {
featuredImage: !value?.featuredImage
}
})
);
}
},
onSelect: (selectedMedia) => {
if (selectedMedia.id && selectedMedia.url) {
const newValue = {
...selectedMedia,
mediaType: selectedMedia.media_type
};
if (useFeaturedImage) {
newValue.featuredImage = false;
}
onChange(
field.setValue({
item: data,
value: newValue
})
);
}
},
renderToggle: (buttonProps) => /* @__PURE__ */ (0, import_jsx_runtime512.jsx)(
import_components261.Button,
{
__next40pxDefaultSize: true,
className: "block-editor-content-only-controls__media",
...buttonProps,
children: /* @__PURE__ */ (0, import_jsx_runtime512.jsxs)(
import_components261.__experimentalGrid,
{
rowGap: 0,
columnGap: 8,
templateColumns: "20px 1fr",
className: "block-editor-content-only-controls__media-row",
children: [
url && /* @__PURE__ */ (0, import_jsx_runtime512.jsxs)(import_jsx_runtime512.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime512.jsx)(
MediaThumbnail,
{
attachment,
field,
data,
config: config2
}
),
/* @__PURE__ */ (0, import_jsx_runtime512.jsx)("span", {
className: "block-editor-content-only-controls__media-title",
// TODO - truncate long titles or url smartly (e.g. show filename).
children: attachment?.title?.raw && attachment?.title?.raw !== "" ? attachment?.title?.raw : url
})
] }),
!url && /* @__PURE__ */ (0, import_jsx_runtime512.jsxs)(import_jsx_runtime512.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime512.jsx)(
"span",
{
className: "block-editor-content-only-controls__media-placeholder",
style: {
width: "20px",
height: "20px"
}
}
),
/* @__PURE__ */ (0, import_jsx_runtime512.jsx)("span", { className: "block-editor-content-only-controls__media-title", children: chooseItemLabel })
] })
]
}
)
}
)
}
),
url && /* @__PURE__ */ (0, import_jsx_runtime512.jsx)(
import_components261.Button,
{
label: (0, import_i18n240.__)("Reset"),
className: "block-editor-content-only-controls__media-reset",
size: "small",
icon: reset_default,
onClick: () => {
onChange(
field.setValue({
item: data,
value: {}
})
);
focusToggleButton2(containerRef);
}
}
)
]
}
) });
}
// packages/block-editor/build-module/hooks/block-fields/link/index.mjs
var import_components262 = __toESM(require_components(), 1);
var import_element313 = __toESM(require_element(), 1);
var import_i18n241 = __toESM(require_i18n(), 1);
var import_url14 = __toESM(require_url(), 1);
var import_jsx_runtime513 = __toESM(require_jsx_runtime(), 1);
var NEW_TAB_REL2 = "noopener";
var NEW_TAB_TARGET = "_blank";
var NOFOLLOW_REL = "nofollow";
function getUpdatedLinkAttributes({
rel = "",
url = "",
opensInNewTab,
nofollow
}) {
let newLinkTarget;
let updatedRel = rel;
if (opensInNewTab) {
newLinkTarget = NEW_TAB_TARGET;
updatedRel = updatedRel?.includes(NEW_TAB_REL2) ? updatedRel : updatedRel + ` ${NEW_TAB_REL2}`;
} else {
const relRegex = new RegExp(`\\b${NEW_TAB_REL2}\\s*`, "g");
updatedRel = updatedRel?.replace(relRegex, "").trim();
}
if (nofollow) {
updatedRel = updatedRel?.includes(NOFOLLOW_REL) ? updatedRel : (updatedRel + ` ${NOFOLLOW_REL}`).trim();
} else {
const relRegex = new RegExp(`\\b${NOFOLLOW_REL}\\s*`, "g");
updatedRel = updatedRel?.replace(relRegex, "").trim();
}
return {
url: (0, import_url14.prependHTTP)(url),
linkTarget: newLinkTarget,
rel: updatedRel || void 0
};
}
function Link({ data, field, onChange }) {
const [isLinkControlOpen, setIsLinkControlOpen] = (0, import_element313.useState)(false);
const { popoverProps: popoverProps3 } = useInspectorPopoverPlacement2({
isControl: true
});
const value = field.getValue({ item: data });
const url = value?.url;
const rel = value?.rel || "";
const target = value?.linkTarget;
const opensInNewTab = target === NEW_TAB_TARGET;
const nofollow = rel === NOFOLLOW_REL;
const linkValue = (0, import_element313.useMemo)(
() => ({ url, opensInNewTab, nofollow }),
[url, opensInNewTab, nofollow]
);
return /* @__PURE__ */ (0, import_jsx_runtime513.jsxs)(import_jsx_runtime513.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime513.jsx)(
import_components262.Button,
{
__next40pxDefaultSize: true,
className: "block-editor-content-only-controls__link",
onClick: () => {
setIsLinkControlOpen(true);
},
children: /* @__PURE__ */ (0, import_jsx_runtime513.jsxs)(
import_components262.__experimentalGrid,
{
rowGap: 0,
columnGap: 8,
templateColumns: "24px 1fr",
className: "block-editor-content-only-controls__link-row",
children: [
url && /* @__PURE__ */ (0, import_jsx_runtime513.jsxs)(import_jsx_runtime513.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime513.jsx)(import_components262.Icon, { icon: link_default, size: 24 }),
/* @__PURE__ */ (0, import_jsx_runtime513.jsx)("span", { className: "block-editor-content-only-controls__link-title", children: url })
] }),
!url && /* @__PURE__ */ (0, import_jsx_runtime513.jsxs)(import_jsx_runtime513.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime513.jsx)(
import_components262.Icon,
{
icon: link_default,
size: 24,
style: { opacity: 0.3 }
}
),
/* @__PURE__ */ (0, import_jsx_runtime513.jsx)("span", { className: "block-editor-content-only-controls__link-title", children: (0, import_i18n241.__)("Link") })
] })
]
}
)
}
),
isLinkControlOpen && /* @__PURE__ */ (0, import_jsx_runtime513.jsx)(
import_components262.Popover,
{
onClose: () => {
setIsLinkControlOpen(false);
},
...popoverProps3 ?? {},
children: /* @__PURE__ */ (0, import_jsx_runtime513.jsx)(
link_control_default,
{
value: linkValue,
onChange: (newValues) => {
const updatedAttrs = getUpdatedLinkAttributes({
rel,
...newValues
});
onChange(
field.setValue({
item: data,
value: updatedAttrs
})
);
},
onRemove: () => {
onChange(
field.setValue({
item: data,
value: {}
})
);
}
}
)
}
)
] });
}
// packages/block-editor/build-module/hooks/block-fields/index.mjs
var import_jsx_runtime514 = __toESM(require_jsx_runtime(), 1);
var { fieldsKey, formKey } = unlock(import_blocks112.privateApis);
function createConfiguredControl2(ControlComponent, config2 = {}) {
return function ConfiguredControl(props) {
return /* @__PURE__ */ (0, import_jsx_runtime514.jsx)(ControlComponent, { ...props, config: config2 });
};
}
function BlockFields({
clientId,
blockType,
setAttributes,
isMultiBlock = false
}) {
const blockTitle = useBlockDisplayTitle({
clientId,
context: "list-view"
});
const blockInformation = useBlockDisplayInformation(clientId);
const blockTypeFields = blockType?.[fieldsKey];
const blockContext = (0, import_element314.useContext)(block_context_default);
const attributes = (0, import_data185.useSelect)(
(select3) => {
const _attributes = select3(store).getBlockAttributes(clientId);
if (!_attributes?.metadata?.bindings) {
return _attributes;
}
const { __experimentalBlockBindingsSupportedAttributes } = select3(store).getSettings();
const bindableAttributes = __experimentalBlockBindingsSupportedAttributes?.[blockType?.name];
const bindings = bindableAttributes ? replacePatternOverridesDefaultBinding(
_attributes.metadata.bindings,
bindableAttributes
) : _attributes.metadata.bindings;
const { getBlockBindingsSource: getBlockBindingsSource4 } = unlock(select3(import_blocks112.store));
return Object.entries(bindings).reduce(
(acc, [attribute, binding]) => {
if (attribute === "__default") {
return acc;
}
const source = getBlockBindingsSource4(binding.source);
if (!source) {
return acc;
}
const values = source.getValues({
select: select3,
clientId,
context: blockContext,
bindings: { [attribute]: binding }
});
return { ...acc, ...values };
},
_attributes
);
},
[blockContext, clientId, blockType?.name]
);
const { selectBlock: selectBlock2, toggleBlockHighlight: toggleBlockHighlight2 } = (0, import_data185.useDispatch)(store);
const debouncedToggleBlockHighlight = (0, import_compose105.useDebounce)(
toggleBlockHighlight2,
50
);
const computedForm = (0, import_element314.useMemo)(() => {
if (!isMultiBlock) {
return blockType?.[formKey];
}
return {
...blockType?.[formKey],
fields: [blockType?.[formKey]?.fields?.[0]]
};
}, [blockType, isMultiBlock]);
const [form, setForm] = (0, import_element314.useState)(computedForm);
const dataFormFields = (0, import_element314.useMemo)(() => {
if (!blockTypeFields?.length) {
return [];
}
return blockTypeFields.map((fieldDef) => {
const field = {
...fieldDef
};
if ("string" === typeof fieldDef.Edit && fieldDef.Edit === "rich-text") {
field.Edit = createConfiguredControl2(RichTextControl2, {
clientId
});
} else if ("string" === typeof fieldDef.Edit && fieldDef.Edit === "link") {
field.Edit = createConfiguredControl2(Link);
} else if ("object" === typeof fieldDef.Edit && fieldDef.Edit.control === "media") {
field.Edit = createConfiguredControl2(Media, {
...fieldDef.Edit
});
}
return field;
});
}, [blockTypeFields, clientId]);
if (!blockTypeFields?.length) {
return null;
}
const handleToggleField = (fieldId) => {
setForm((prev) => {
if (prev.fields?.includes(fieldId)) {
return {
...prev,
fields: prev.fields.filter((id) => id !== fieldId)
};
}
return {
...prev,
fields: [...prev.fields || [], fieldId]
};
});
};
return /* @__PURE__ */ (0, import_jsx_runtime514.jsxs)(
"div",
{
className: "block-editor-block-fields__container",
onMouseEnter: isMultiBlock ? () => debouncedToggleBlockHighlight(clientId, true) : void 0,
onMouseLeave: () => isMultiBlock ? debouncedToggleBlockHighlight(clientId, false) : void 0,
onFocus: isMultiBlock ? () => {
selectBlock2(
clientId,
null
/* null to avoid focus on the block in the canvas */
);
} : void 0,
children: [
/* @__PURE__ */ (0, import_jsx_runtime514.jsx)("div", { className: "block-editor-block-fields__header", children: /* @__PURE__ */ (0, import_jsx_runtime514.jsxs)(import_components263.__experimentalHStack, { spacing: 1, children: [
isMultiBlock && /* @__PURE__ */ (0, import_jsx_runtime514.jsxs)(import_jsx_runtime514.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime514.jsx)(
block_icon_default,
{
className: "block-editor-block-fields__header-icon",
icon: blockInformation?.icon
}
),
/* @__PURE__ */ (0, import_jsx_runtime514.jsx)("h2", { className: "block-editor-block-fields__header-title", children: /* @__PURE__ */ (0, import_jsx_runtime514.jsx)(import_components263.__experimentalTruncate, { numberOfLines: 1, children: blockTitle }) }),
/* @__PURE__ */ (0, import_jsx_runtime514.jsx)(
FieldsDropdownMenu,
{
fields: dataFormFields,
visibleFields: form.fields,
onToggleField: handleToggleField
}
)
] }),
!isMultiBlock && /* @__PURE__ */ (0, import_jsx_runtime514.jsx)("h2", { className: "block-editor-block-fields__header-title", children: (0, import_i18n242.__)("Content") })
] }) }),
/* @__PURE__ */ (0, import_jsx_runtime514.jsx)(
DataForm,
{
data: attributes,
fields: dataFormFields,
form,
onChange: setAttributes
}
)
]
}
);
}
function hasBlockFieldsSupport(blockName) {
return !!(window?.__experimentalContentOnlyInspectorFields && (0, import_blocks112.getBlockType)(blockName)?.[fieldsKey]);
}
function BlockFieldsPanel(props) {
const { blockType, isSelectionWithinCurrentSection } = (0, import_element314.useContext)(PrivateBlockContext);
return /* @__PURE__ */ (0, import_jsx_runtime514.jsx)(InspectorControlsFill, { group: "content", children: /* @__PURE__ */ (0, import_jsx_runtime514.jsx)(
BlockFields,
{
...props,
blockType,
isMultiBlock: isSelectionWithinCurrentSection
}
) });
}
var block_fields_default = {
edit: BlockFieldsPanel,
hasSupport: hasBlockFieldsSupport,
attributeKeys: [],
supportsPatternEditing: true
};
// packages/block-editor/build-module/hooks/custom-class-name.mjs
var import_hooks26 = __toESM(require_hooks(), 1);
var import_components264 = __toESM(require_components(), 1);
var import_i18n243 = __toESM(require_i18n(), 1);
var import_blocks113 = __toESM(require_blocks(), 1);
var import_jsx_runtime515 = __toESM(require_jsx_runtime(), 1);
function addAttribute6(settings2) {
if ((0, import_blocks113.hasBlockSupport)(settings2, "customClassName", true)) {
settings2.attributes = {
...settings2.attributes,
className: {
type: "string"
}
};
}
return settings2;
}
function CustomClassNameControlsPure({ className, setAttributes }) {
const blockEditingMode = useBlockEditingMode();
if (blockEditingMode !== "default") {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime515.jsx)(inspector_controls_default, { group: "advanced", children: /* @__PURE__ */ (0, import_jsx_runtime515.jsx)(
import_components264.TextControl,
{
autoComplete: "off",
label: (0, import_i18n243.__)("Additional CSS class(es)"),
value: className || "",
onChange: (nextValue) => {
setAttributes({
className: nextValue !== "" ? nextValue : void 0
});
},
help: (0, import_i18n243.__)("Separate multiple classes with spaces.")
}
) });
}
var custom_class_name_default = {
edit: CustomClassNameControlsPure,
addSaveProps: addSaveProps8,
attributeKeys: ["className"],
hasSupport(name) {
return (0, import_blocks113.hasBlockSupport)(name, "customClassName", true);
}
};
function addSaveProps8(extraProps, blockType, attributes) {
if ((0, import_blocks113.hasBlockSupport)(blockType, "customClassName", true) && attributes.className) {
extraProps.className = clsx_default(
extraProps.className,
attributes.className
);
}
return extraProps;
}
function addTransforms4(result, source, index2, results) {
if (!(0, import_blocks113.hasBlockSupport)(result.name, "customClassName", true)) {
return result;
}
if (results.length === 1 && result.innerBlocks.length === source.length) {
return result;
}
if (results.length === 1 && source.length > 1 || results.length > 1 && source.length === 1) {
return result;
}
if (source[index2]) {
const originClassName = source[index2]?.attributes.className;
if (originClassName && result.attributes.className === void 0) {
return {
...result,
attributes: {
...result.attributes,
className: originClassName
}
};
}
}
return result;
}
(0, import_hooks26.addFilter)(
"blocks.registerBlockType",
"core/editor/custom-class-name/attribute",
addAttribute6
);
(0, import_hooks26.addFilter)(
"blocks.switchToBlockType.transformedBlock",
"core/customClassName/addTransforms",
addTransforms4
);
// packages/block-editor/build-module/hooks/generated-class-name.mjs
var import_hooks27 = __toESM(require_hooks(), 1);
var import_blocks114 = __toESM(require_blocks(), 1);
function addGeneratedClassName(extraProps, blockType) {
if ((0, import_blocks114.hasBlockSupport)(blockType, "className", true)) {
if (typeof extraProps.className === "string") {
extraProps.className = [
.../* @__PURE__ */ new Set([
(0, import_blocks114.getBlockDefaultClassName)(blockType.name),
...extraProps.className.split(" ")
])
].join(" ").trim();
} else {
extraProps.className = (0, import_blocks114.getBlockDefaultClassName)(blockType.name);
}
}
return extraProps;
}
(0, import_hooks27.addFilter)(
"blocks.getSaveContent.extraProps",
"core/generated-class-name/save-props",
addGeneratedClassName
);
// packages/block-editor/build-module/hooks/style.mjs
var import_element317 = __toESM(require_element(), 1);
var import_hooks28 = __toESM(require_hooks(), 1);
var import_data187 = __toESM(require_data(), 1);
var import_blocks117 = __toESM(require_blocks(), 1);
var import_compose106 = __toESM(require_compose(), 1);
var import_style_engine4 = __toESM(require_style_engine(), 1);
// packages/block-editor/build-module/hooks/dimensions.mjs
var import_element316 = __toESM(require_element(), 1);
var import_data186 = __toESM(require_data(), 1);
var import_blocks115 = __toESM(require_blocks(), 1);
var import_deprecated34 = __toESM(require_deprecated(), 1);
// packages/block-editor/build-module/hooks/spacing-visualizer.mjs
var import_element315 = __toESM(require_element(), 1);
var import_is_shallow_equal4 = __toESM(require_is_shallow_equal(), 1);
var import_jsx_runtime516 = __toESM(require_jsx_runtime(), 1);
function SpacingVisualizer({ clientId, value, computeStyle, forceShow }) {
const blockElement = useBlockElement(clientId);
const [style, updateStyle] = (0, import_element315.useReducer)(
() => computeStyle(blockElement)
);
(0, import_element315.useEffect)(() => {
if (blockElement && forceShow) {
updateStyle();
}
}, [blockElement, forceShow]);
(0, import_element315.useEffect)(() => {
if (!blockElement) {
return;
}
const observer = new window.MutationObserver(updateStyle);
observer.observe(blockElement, {
attributes: true,
attributeFilter: ["style", "class"]
});
return () => {
observer.disconnect();
};
}, [blockElement]);
const previousValueRef = (0, import_element315.useRef)(value);
const [isActive, setIsActive] = (0, import_element315.useState)(false);
(0, import_element315.useEffect)(() => {
if ((0, import_is_shallow_equal4.isShallowEqual)(value, previousValueRef.current) || forceShow) {
return;
}
setIsActive(true);
previousValueRef.current = value;
const timeout = setTimeout(() => {
setIsActive(false);
}, 400);
return () => {
setIsActive(false);
clearTimeout(timeout);
};
}, [value, forceShow]);
if (!isActive && !forceShow) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime516.jsx)(
cover_default,
{
clientId,
__unstablePopoverSlot: "block-toolbar",
children: /* @__PURE__ */ (0, import_jsx_runtime516.jsx)("div", { className: "block-editor__spacing-visualizer", style })
}
);
}
function getComputedCSS(element, property) {
return element.ownerDocument.defaultView.getComputedStyle(element).getPropertyValue(property);
}
function MarginVisualizer({ clientId, value, forceShow }) {
return /* @__PURE__ */ (0, import_jsx_runtime516.jsx)(
SpacingVisualizer,
{
clientId,
value: value?.spacing?.margin,
computeStyle: (blockElement) => {
const top = getComputedCSS(blockElement, "margin-top");
const right = getComputedCSS(blockElement, "margin-right");
const bottom = getComputedCSS(blockElement, "margin-bottom");
const left = getComputedCSS(blockElement, "margin-left");
return {
borderTopWidth: top,
borderRightWidth: right,
borderBottomWidth: bottom,
borderLeftWidth: left,
top: top ? `-${top}` : 0,
right: right ? `-${right}` : 0,
bottom: bottom ? `-${bottom}` : 0,
left: left ? `-${left}` : 0
};
},
forceShow
}
);
}
function PaddingVisualizer({ clientId, value, forceShow }) {
return /* @__PURE__ */ (0, import_jsx_runtime516.jsx)(
SpacingVisualizer,
{
clientId,
value: value?.spacing?.padding,
computeStyle: (blockElement) => ({
borderTopWidth: getComputedCSS(blockElement, "padding-top"),
borderRightWidth: getComputedCSS(
blockElement,
"padding-right"
),
borderBottomWidth: getComputedCSS(
blockElement,
"padding-bottom"
),
borderLeftWidth: getComputedCSS(blockElement, "padding-left")
}),
forceShow
}
);
}
// packages/block-editor/build-module/hooks/dimensions.mjs
var import_jsx_runtime517 = __toESM(require_jsx_runtime(), 1);
var DIMENSIONS_SUPPORT_KEY = "dimensions";
var SPACING_SUPPORT_KEY2 = "spacing";
function useVisualizer() {
const [property, setProperty] = (0, import_element316.useState)(false);
const { hideBlockInterface: hideBlockInterface2, showBlockInterface: showBlockInterface2 } = unlock(
(0, import_data186.useDispatch)(store)
);
(0, import_element316.useEffect)(() => {
if (!property) {
showBlockInterface2();
} else {
hideBlockInterface2();
}
}, [property, showBlockInterface2, hideBlockInterface2]);
return [property, setProperty];
}
function DimensionsInspectorControl({ children, resetAllFilter }) {
const attributesResetAllFilter = (0, import_element316.useCallback)(
(attributes) => {
const existingStyle = attributes.style;
const updatedStyle = resetAllFilter(existingStyle);
return {
...attributes,
style: updatedStyle
};
},
[resetAllFilter]
);
return /* @__PURE__ */ (0, import_jsx_runtime517.jsx)(
inspector_controls_default,
{
group: "dimensions",
resetAllFilter: attributesResetAllFilter,
children
}
);
}
function DimensionsPanel2({ clientId, name, setAttributes, settings: settings2 }) {
const selectedState = useBlockStyleState();
const isStateSelected = !isDefaultBlockStyleState(selectedState);
const isEnabled = useHasDimensionsPanel(settings2, selectedState);
const style = (0, import_data186.useSelect)(
(select3) => {
if (!isEnabled) {
return void 0;
}
return select3(store).getBlockAttributes(clientId)?.style;
},
[clientId, isEnabled]
);
const [visualizedProperty, setVisualizedProperty] = useVisualizer();
const value = isStateSelected ? getStyleForState(style, selectedState) : style;
const onChange = isStateSelected ? (newStyle) => {
setAttributes({
style: setStyleForState(style, selectedState, newStyle)
});
} : (newStyle) => {
setAttributes({
style: cleanEmptyObject(newStyle)
});
};
if (!isEnabled) {
return null;
}
const defaultDimensionsControls = (0, import_blocks115.getBlockSupport)(name, [
DIMENSIONS_SUPPORT_KEY,
"__experimentalDefaultControls"
]);
const defaultSpacingControls = (0, import_blocks115.getBlockSupport)(name, [
SPACING_SUPPORT_KEY2,
"__experimentalDefaultControls"
]);
const defaultControls = {
// In the block inspector, minHeight and minWidth should not
// be shown by default unless the block explicitly opts in.
minHeight: false,
minWidth: false,
...defaultDimensionsControls,
...defaultSpacingControls
};
return /* @__PURE__ */ (0, import_jsx_runtime517.jsxs)(import_jsx_runtime517.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime517.jsx)(
DimensionsPanel,
{
as: DimensionsInspectorControl,
panelId: clientId,
settings: settings2,
value,
onChange,
defaultControls,
styleState: selectedState,
onVisualize: isStateSelected ? void 0 : setVisualizedProperty
}
),
!isStateSelected && !!settings2?.spacing?.padding && visualizedProperty === "padding" && /* @__PURE__ */ (0, import_jsx_runtime517.jsx)(
PaddingVisualizer,
{
forceShow: visualizedProperty === "padding",
clientId,
value
}
),
!isStateSelected && !!settings2?.spacing?.margin && visualizedProperty === "margin" && /* @__PURE__ */ (0, import_jsx_runtime517.jsx)(
MarginVisualizer,
{
forceShow: visualizedProperty === "margin",
clientId,
value
}
)
] });
}
function hasDimensionsSupport(blockName, feature = "any") {
const support = (0, import_blocks115.getBlockSupport)(blockName, DIMENSIONS_SUPPORT_KEY);
if (support === true) {
return true;
}
if (feature === "any") {
return !!(support?.aspectRatio || !!support?.height || !!support?.minHeight || !!support?.width || !!support?.minWidth);
}
return !!support?.[feature];
}
function isExplicitAspectRatio(aspectRatio) {
if (!aspectRatio) {
return false;
}
return `${aspectRatio}`.trim().toLowerCase() !== "auto";
}
var dimensions_default = {
useBlockProps: useBlockProps12,
attributeKeys: ["height", "minHeight", "width", "style"],
hasSupport(name) {
return hasDimensionsSupport(name);
}
};
function useBlockProps12({ name, height, minHeight, style }) {
if (!hasDimensionsSupport(name, "aspectRatio") || shouldSkipSerialization(name, DIMENSIONS_SUPPORT_KEY, "aspectRatio")) {
return {};
}
const hasExplicitAspectRatio = isExplicitAspectRatio(
style?.dimensions?.aspectRatio
);
const className = clsx_default({
"has-aspect-ratio": hasExplicitAspectRatio
});
const inlineStyleOverrides = {};
if (hasExplicitAspectRatio) {
inlineStyleOverrides.minHeight = "unset";
inlineStyleOverrides.height = "unset";
} else if (minHeight || style?.dimensions?.minHeight || height || style?.dimensions?.height) {
inlineStyleOverrides.aspectRatio = "unset";
}
return { className, style: inlineStyleOverrides };
}
function useCustomSides() {
(0, import_deprecated34.default)("wp.blockEditor.__experimentalUseCustomSides", {
since: "6.3",
version: "6.4"
});
}
// packages/block-editor/build-module/hooks/state-utils.mjs
var import_blocks116 = __toESM(require_blocks(), 1);
function buildScopedBlockSelector(baseSelector, blockSelector, suffix = "") {
if (typeof blockSelector !== "string" || !blockSelector) {
return splitSelectorList(baseSelector).map((selector3) => `${selector3.trim()}${suffix}`).join(", ");
}
const baseSelectors = splitSelectorList(baseSelector).filter(
(selector3) => selector3.trim()
);
const selectors4 = splitSelectorList(blockSelector).filter(
(selector3) => selector3.trim()
);
if (!selectors4.length) {
return baseSelectors.map((selector3) => `${selector3.trim()}${suffix}`).join(", ");
}
return selectors4.map((selector3) => {
selector3 = selector3.trim();
const match2 = selector3.match(/^([.#]?[-_a-zA-Z0-9]+|\[[^\]]+\])/);
if (match2) {
return baseSelectors.map(
(base) => `${base.trim()}${selector3.slice(
match2[0].length
)}${suffix}`
).join(", ");
}
return baseSelectors.map((base) => `${base.trim()}${suffix}`).join(", ");
}).join(", ");
}
// packages/block-editor/build-module/hooks/style.mjs
var import_jsx_runtime518 = __toESM(require_jsx_runtime(), 1);
var { getResponsiveMediaQueries: getResponsiveMediaQueries2 } = unlock(privateApis);
var BORDER_SIDES = ["Top", "Right", "Bottom", "Left"];
var styleSupportKeys2 = [
...TYPOGRAPHY_SUPPORT_KEYS2,
BORDER_SUPPORT_KEY2,
COLOR_SUPPORT_KEY2,
DIMENSIONS_SUPPORT_KEY,
BACKGROUND_SUPPORT_KEY,
SPACING_SUPPORT_KEY2,
SHADOW_SUPPORT_KEY
];
var hasStyleSupport2 = (nameOrType) => styleSupportKeys2.some((key) => (0, import_blocks117.hasBlockSupport)(nameOrType, key));
function getInlineStyles(styles = {}) {
const output = {};
(0, import_style_engine4.getCSSRules)(styles).forEach((rule) => {
output[rule.key] = rule.value;
});
return output;
}
function getStateFallbackBorderStyles(stateStyles) {
const border = stateStyles?.border;
if (!border) {
return void 0;
}
const hasBorderStyle = !!border.style;
const hasBorderColor = !!border.color;
const hasBorderWidth = !!border.width;
const fallbackBorder = {};
if (!hasBorderStyle && (hasBorderColor || hasBorderWidth)) {
fallbackBorder.style = "solid";
}
BORDER_SIDES.forEach((side) => {
const sideKey = side.toLowerCase();
const sideBorder = border[sideKey];
const hasSideStyle = !!sideBorder?.style;
const hasSideColor = !!sideBorder?.color;
const hasSideWidth = !!sideBorder?.width;
if (!hasBorderStyle && !hasSideStyle && (hasSideColor || hasSideWidth)) {
fallbackBorder[sideKey] = { style: "solid" };
}
});
return cleanEmptyObject({ border: cleanEmptyObject(fallbackBorder) });
}
function getStateBackgroundResetCSS(stateStyles, selector3) {
const hasSolidBackground = !!stateStyles?.color?.background;
if (!hasSolidBackground) {
return void 0;
}
const hasColorGradient = !!stateStyles?.color?.gradient;
const hasBackgroundGradient = !!stateStyles?.background?.gradient || !!stateStyles?.background?.backgroundImage;
if (hasColorGradient || hasBackgroundGradient) {
return void 0;
}
const declaration = "background-image: unset !important";
return selector3 ? `${selector3} { ${declaration}; }` : `${declaration};`;
}
function getStateFallbackDimensionStyles(stateStyles) {
const dimensions = stateStyles?.dimensions;
if (!dimensions) {
return void 0;
}
if (isExplicitAspectRatio(dimensions.aspectRatio)) {
return {
dimensions: {
minHeight: "unset",
height: "unset"
}
};
}
if (dimensions.minHeight || dimensions.height) {
return {
dimensions: {
aspectRatio: "unset"
}
};
}
}
function getStateTextAlignCSS(stateStyles, selector3) {
const textAlign = stateStyles?.typography?.textAlign;
if (typeof textAlign !== "string" || !textAlign) {
return void 0;
}
const declaration = `text-align: ${(0, import_style_engine4.getCSSValueFromRawStyle)(
textAlign
)} !important`;
return selector3 ? `${selector3} { ${declaration}; }` : `${declaration};`;
}
function getStateStylesCSS(stateStyles, selector3) {
const fallbackDimensionStyles = getStateFallbackDimensionStyles(stateStyles);
const stylesWithDimensionFallbacks = fallbackDimensionStyles ? mergeStyleObjects(stateStyles, fallbackDimensionStyles) : stateStyles;
const css = (0, import_style_engine4.compileCSS)(stylesWithDimensionFallbacks, { selector: selector3 });
const importantCSS = css ? css.replace(/;/g, " !important;") : void 0;
const fallbackBorderStyles = getStateFallbackBorderStyles(stateStyles);
const fallbackCSS = fallbackBorderStyles ? (0, import_style_engine4.compileCSS)(fallbackBorderStyles, { selector: selector3 }) : void 0;
const textAlignCSS = getStateTextAlignCSS(stateStyles, selector3);
const backgroundResetCSS = getStateBackgroundResetCSS(
stateStyles,
selector3
);
return [importantCSS, textAlignCSS, fallbackCSS, backgroundResetCSS].filter(Boolean).join("\n");
}
function isPlainObject2(value) {
return !!value && typeof value === "object" && !Array.isArray(value);
}
function mergeStyleObjects(target = {}, source = {}) {
const merged = { ...target };
Object.entries(source).forEach(([key, value]) => {
merged[key] = isPlainObject2(value) && isPlainObject2(merged[key]) ? mergeStyleObjects(merged[key], value) : value;
});
return merged;
}
function addStyleGroup(groups3, selector3, style) {
const key = selector3 || "";
const existing = groups3.get(key) || { selector: selector3, style: {} };
groups3.set(key, {
selector: selector3,
style: mergeStyleObjects(existing.style, style)
});
}
function getStateStyleGroups(stateStyles, name) {
const blockSelectors = (0, import_blocks117.getBlockType)(name)?.selectors || {};
const groups3 = /* @__PURE__ */ new Map();
Object.entries(stateStyles || {}).forEach(
([feature, featureStyles]) => {
const featureSelectors = blockSelectors[feature];
if (typeof featureSelectors === "string") {
addStyleGroup(groups3, featureSelectors, {
[feature]: featureStyles
});
return;
}
if (isPlainObject2(featureSelectors) && isPlainObject2(featureStyles)) {
const remainingStyles = { ...featureStyles };
Object.entries(featureSelectors).forEach(
([subfeature, subfeatureSelector]) => {
if (subfeature === "root" || typeof subfeatureSelector !== "string" || !Object.hasOwn(featureStyles, subfeature)) {
return;
}
addStyleGroup(groups3, subfeatureSelector, {
[feature]: {
[subfeature]: featureStyles[subfeature]
}
});
delete remainingStyles[subfeature];
}
);
if (Object.keys(remainingStyles).length) {
addStyleGroup(
groups3,
featureSelectors.root || blockSelectors.root,
{
[feature]: remainingStyles
}
);
}
return;
}
addStyleGroup(groups3, blockSelectors.root, {
[feature]: featureStyles
});
}
);
return Array.from(groups3.values());
}
function getBlockStateStylesCSS(stateStyles, options) {
const { name, baseSelector, state = "" } = options;
const rules = getStateStyleGroups(stateStyles, name).map(
({ selector: blockSelector, style }) => getStateStylesCSS(
style,
buildScopedBlockSelector(baseSelector, blockSelector, state)
)
).filter(Boolean);
return rules.length ? rules.join("\n") : void 0;
}
function getRootStateStyles(stateStyles, nestedKeys) {
if (!stateStyles) {
return stateStyles;
}
const rootStyles = { ...stateStyles };
nestedKeys.forEach((key) => {
delete rootStyles[key];
});
return rootStyles;
}
function getPseudoStateCSSRules(style, name, baseSelector) {
const validPseudoStates = VALID_BLOCK_PSEUDO_STATES[name];
if (!validPseudoStates) {
return [];
}
const cssRules = [];
validPseudoStates.forEach((pseudoState) => {
const stateStyles = style?.[pseudoState];
if (stateStyles) {
const css = getBlockStateStylesCSS(stateStyles, {
name,
baseSelector,
state: pseudoState
});
if (css) {
cssRules.push(css);
}
}
});
return cssRules;
}
function getResponsiveStateCSSRules(style, name, baseSelector, viewportSettings) {
const cssRules = [];
const validPseudoStates = VALID_BLOCK_PSEUDO_STATES[name] ?? [];
const nestedStateKeys = ["elements", ...validPseudoStates];
const responsiveMediaQueries = getResponsiveMediaQueries2(viewportSettings);
Object.entries(responsiveMediaQueries).forEach(
([viewport, mediaQuery]) => {
const viewportStyles = getStyleForState(style, {
viewport,
pseudo: DEFAULT_BLOCK_STYLE_STATE2.pseudo
});
if (!viewportStyles) {
return;
}
const viewportCSSRules = [];
const rootCSS = getBlockStateStylesCSS(
getRootStateStyles(viewportStyles, nestedStateKeys),
{
name,
baseSelector
}
);
if (rootCSS) {
viewportCSSRules.push(rootCSS);
}
const elementCSS = getElementCSSRules(
viewportStyles.elements,
name,
baseSelector
);
if (elementCSS) {
viewportCSSRules.push(elementCSS);
}
viewportCSSRules.push(
...getPseudoStateCSSRules(viewportStyles, name, baseSelector)
);
if (viewportCSSRules.length) {
cssRules.push(
`${mediaQuery}{${viewportCSSRules.join("")}}`
);
}
}
);
return cssRules;
}
function getCanvasStateStyleValue(style, selectedState) {
const stateValue = getStyleForState(style, selectedState);
if (!hasViewportBlockStyleState(selectedState)) {
return stateValue;
}
const defaultViewportState = {
...selectedState,
viewport: DEFAULT_BLOCK_STYLE_STATE2.viewport
};
const defaultViewportStateValue = getStyleForState(
style,
defaultViewportState
);
if (defaultViewportStateValue && stateValue) {
return mergeGlobalStyles(defaultViewportStateValue, stateValue);
}
return stateValue || defaultViewportStateValue;
}
function addAttribute7(settings2) {
if (!hasStyleSupport2(settings2) && !(0, import_blocks117.hasBlockSupport)(settings2, "customCSS", true)) {
return settings2;
}
if (!settings2.attributes.style) {
Object.assign(settings2.attributes, {
style: {
type: "object"
}
});
}
return settings2;
}
var skipSerializationPathsEdit = {
[`${BORDER_SUPPORT_KEY2}.__experimentalSkipSerialization`]: ["border"],
[`${COLOR_SUPPORT_KEY2}.__experimentalSkipSerialization`]: [
COLOR_SUPPORT_KEY2
],
[`${TYPOGRAPHY_SUPPORT_KEY}.__experimentalSkipSerialization`]: [
TYPOGRAPHY_SUPPORT_KEY
],
[`${DIMENSIONS_SUPPORT_KEY}.__experimentalSkipSerialization`]: [
DIMENSIONS_SUPPORT_KEY
],
[`${SPACING_SUPPORT_KEY2}.__experimentalSkipSerialization`]: [
SPACING_SUPPORT_KEY2
],
[`${SHADOW_SUPPORT_KEY}.__experimentalSkipSerialization`]: [
SHADOW_SUPPORT_KEY
]
};
var skipSerializationPathsSave = {
...skipSerializationPathsEdit,
[`${DIMENSIONS_SUPPORT_KEY}.aspectRatio`]: [
`${DIMENSIONS_SUPPORT_KEY}.aspectRatio`
],
// Skip serialization of aspect ratio in save mode.
[`${BACKGROUND_SUPPORT_KEY}`]: [BACKGROUND_SUPPORT_KEY]
// Skip serialization of background support in save mode.
};
var skipSerializationPathsSaveChecks = {
[`${DIMENSIONS_SUPPORT_KEY}.aspectRatio`]: true,
[`${BACKGROUND_SUPPORT_KEY}`]: true
};
var renamedFeatures = { gradients: "gradient" };
function omitStyle(style, paths, preserveReference = false) {
if (!style) {
return style;
}
let newStyle = style;
if (!preserveReference) {
newStyle = JSON.parse(JSON.stringify(style));
}
if (!Array.isArray(paths)) {
paths = [paths];
}
paths.forEach((path) => {
if (!Array.isArray(path)) {
path = path.split(".");
}
if (path.length > 1) {
const [firstSubpath, ...restPath] = path;
omitStyle(newStyle[firstSubpath], [restPath], true);
} else if (path.length === 1) {
delete newStyle[path[0]];
}
});
return newStyle;
}
function addSaveProps9(props, blockNameOrType, attributes, skipPaths = skipSerializationPathsSave) {
if (!hasStyleSupport2(blockNameOrType)) {
return props;
}
let { style } = attributes;
Object.entries(skipPaths).forEach(([indicator, path]) => {
const skipSerialization = skipSerializationPathsSaveChecks[indicator] || (0, import_blocks117.getBlockSupport)(blockNameOrType, indicator);
if (skipSerialization === true) {
style = omitStyle(style, path);
}
if (Array.isArray(skipSerialization)) {
skipSerialization.forEach((featureName) => {
const feature = renamedFeatures[featureName] || featureName;
style = omitStyle(style, [[...path, feature]]);
});
}
});
props.style = {
...getInlineStyles(style),
...props.style
};
return props;
}
function BlockStyleControls({
clientId,
name,
setAttributes,
style,
__unstableParentLayout
}) {
const settings2 = useBlockSettings(name, __unstableParentLayout);
const blockEditingMode = useBlockEditingMode();
const { globalBlockStyles, selectedState, showStateOnCanvas } = (0, import_data187.useSelect)(
(select3) => {
const blockEditorSelect = select3(store);
const {
getSelectedBlockStyleState: getSelectedBlockStyleState2,
isSelectedBlockStyleStateShownOnCanvas: isSelectedBlockStyleStateShownOnCanvas2
} = unlock(blockEditorSelect);
const editorSettings = blockEditorSelect.getSettings();
return {
globalBlockStyles: editorSettings?.[globalStylesDataKey]?.blocks?.[name],
selectedState: getSelectedBlockStyleState2(clientId),
showStateOnCanvas: isSelectedBlockStyleStateShownOnCanvas2(clientId)
};
},
[clientId, name]
);
const isPseudoSelectorState = hasPseudoBlockStyleState(selectedState);
const canvasStateCSS = (0, import_element317.useMemo)(() => {
if (!showStateOnCanvas || !isPseudoSelectorState) {
return void 0;
}
const globalStateValue = getCanvasStateStyleValue(
globalBlockStyles,
selectedState
);
const instanceStateValue = getCanvasStateStyleValue(
style,
selectedState
);
let stateValue;
if (globalStateValue && instanceStateValue) {
stateValue = mergeGlobalStyles(
globalStateValue,
instanceStateValue
);
} else if (instanceStateValue) {
stateValue = instanceStateValue;
} else if (globalStateValue) {
stateValue = globalStateValue;
} else {
return void 0;
}
return getBlockStateStylesCSS(stateValue, {
name,
baseSelector: `[data-block="${clientId}"]`
});
}, [
showStateOnCanvas,
isPseudoSelectorState,
globalBlockStyles,
style,
selectedState,
clientId,
name
]);
useStyleOverride({ css: canvasStateCSS });
if (blockEditingMode !== "default") {
return null;
}
const panelSettings = {
...settings2,
typography: {
...settings2.typography,
// The text alignment UI for individual blocks is rendered in
// the block toolbar, so disable it here.
textAlign: false
}
};
const passedProps = {
clientId,
name,
setAttributes,
settings: panelSettings
};
return /* @__PURE__ */ (0, import_jsx_runtime518.jsxs)(BlockStyleStateProvider, { value: selectedState, children: [
/* @__PURE__ */ (0, import_jsx_runtime518.jsx)(ElementsEdit, { ...passedProps }),
/* @__PURE__ */ (0, import_jsx_runtime518.jsx)(BackgroundImagePanel3, { ...passedProps }),
/* @__PURE__ */ (0, import_jsx_runtime518.jsx)(TypographyPanel2, { ...passedProps }),
/* @__PURE__ */ (0, import_jsx_runtime518.jsx)(BorderPanel2, { ...passedProps }),
/* @__PURE__ */ (0, import_jsx_runtime518.jsx)(DimensionsPanel2, { ...passedProps })
] });
}
var style_default16 = {
edit: BlockStyleControls,
hasSupport: hasStyleSupport2,
addSaveProps: addSaveProps9,
attributeKeys: ["style"],
useBlockProps: useBlockProps13
};
var elementTypes = [
{ elementType: "button" },
{ elementType: "link", pseudo: [":hover"] },
{
elementType: "heading",
elements: ["h1", "h2", "h3", "h4", "h5", "h6"]
}
];
var STYLE_BLOCK_PROPS_REFERENCE = {};
function getElementCSSRules(blockElementStyles, blockName, baseSelector) {
if (!blockElementStyles) {
return;
}
const rules = [];
elementTypes.forEach(({ elementType, pseudo, elements }) => {
const skipSerialization = shouldSkipSerialization(
blockName,
COLOR_SUPPORT_KEY2,
elementType
);
if (skipSerialization) {
return;
}
const elementStyles = blockElementStyles?.[elementType];
if (elementStyles) {
const selector3 = scopeSelector2(
baseSelector,
import_blocks117.__EXPERIMENTAL_ELEMENTS[elementType]
);
rules.push((0, import_style_engine4.compileCSS)(elementStyles, { selector: selector3 }));
if (pseudo) {
pseudo.forEach((pseudoSelector) => {
if (elementStyles[pseudoSelector]) {
rules.push(
(0, import_style_engine4.compileCSS)(elementStyles[pseudoSelector], {
selector: scopeSelector2(
baseSelector,
`${import_blocks117.__EXPERIMENTAL_ELEMENTS[elementType]}${pseudoSelector}`
)
})
);
}
});
}
}
if (elements) {
elements.forEach((element) => {
if (blockElementStyles[element]) {
rules.push(
(0, import_style_engine4.compileCSS)(blockElementStyles[element], {
selector: scopeSelector2(
baseSelector,
import_blocks117.__EXPERIMENTAL_ELEMENTS[element]
)
})
);
}
});
}
});
return rules.length > 0 ? rules.join("") : void 0;
}
function useBlockProps13({ name, style }) {
const blockElementsContainerIdentifier = (0, import_compose106.useInstanceId)(
STYLE_BLOCK_PROPS_REFERENCE,
"wp-elements"
);
const baseElementSelector = `.${blockElementsContainerIdentifier}`;
const blockElementStyles = style?.elements;
const [viewportSettings] = useSettings("viewport");
const styles = (0, import_element317.useMemo)(() => {
const cssRules = [];
const elementCSS = getElementCSSRules(
blockElementStyles,
name,
baseElementSelector
);
if (elementCSS) {
cssRules.push(elementCSS);
}
cssRules.push(
...getPseudoStateCSSRules(style, name, baseElementSelector)
);
cssRules.push(
...getResponsiveStateCSSRules(
style,
name,
baseElementSelector,
viewportSettings
)
);
return cssRules.length > 0 ? cssRules.join("") : void 0;
}, [
baseElementSelector,
blockElementStyles,
name,
style,
viewportSettings
]);
useStyleOverride({ css: styles });
return addSaveProps9(
{ className: blockElementsContainerIdentifier },
name,
{ style },
skipSerializationPathsEdit
);
}
(0, import_hooks28.addFilter)(
"blocks.registerBlockType",
"core/style/addAttribute",
addAttribute7
);
// packages/block-editor/build-module/hooks/settings.mjs
var import_hooks29 = __toESM(require_hooks(), 1);
var import_blocks118 = __toESM(require_blocks(), 1);
var hasSettingsSupport = (blockType) => (0, import_blocks118.hasBlockSupport)(blockType, "__experimentalSettings", false);
function addAttribute8(settings2) {
if (!hasSettingsSupport(settings2)) {
return settings2;
}
if (!settings2?.attributes?.settings) {
settings2.attributes = {
...settings2.attributes,
settings: {
type: "object"
}
};
}
return settings2;
}
(0, import_hooks29.addFilter)(
"blocks.registerBlockType",
"core/settings/addAttribute",
addAttribute8
);
// packages/block-editor/build-module/hooks/duotone.mjs
var import_blocks119 = __toESM(require_blocks(), 1);
var import_compose107 = __toESM(require_compose(), 1);
var import_hooks30 = __toESM(require_hooks(), 1);
var import_element318 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/duotone/utils.mjs
function getValuesFromColors(colors2 = []) {
const values = { r: [], g: [], b: [], a: [] };
colors2.forEach((color) => {
const rgbColor = w(color).toRgb();
values.r.push(rgbColor.r / 255);
values.g.push(rgbColor.g / 255);
values.b.push(rgbColor.b / 255);
values.a.push(rgbColor.a);
});
return values;
}
function getDuotoneUnsetStylesheet(selector3) {
return `${selector3}{filter:none}`;
}
function getDuotoneStylesheet(selector3, id) {
return `${selector3}{filter:url(#${id})}`;
}
function getDuotoneFilter(id, colors2) {
const values = getValuesFromColors(colors2);
return `
<svg
xmlns:xlink="http://www.w3.org/1999/xlink"
viewBox="0 0 0 0"
width="0"
height="0"
focusable="false"
role="none"
aria-hidden="true"
style="visibility: hidden; position: absolute; left: -9999px; overflow: hidden;"
>
<defs>
<filter id="${id}">
<!--
Use sRGB instead of linearRGB so transparency looks correct.
Use perceptual brightness to convert to grayscale.
-->
<feColorMatrix color-interpolation-filters="sRGB" type="matrix" values=" .299 .587 .114 0 0 .299 .587 .114 0 0 .299 .587 .114 0 0 .299 .587 .114 0 0 "></feColorMatrix>
<!-- Use sRGB instead of linearRGB to be consistent with how CSS gradients work. -->
<feComponentTransfer color-interpolation-filters="sRGB">
<feFuncR type="table" tableValues="${values.r.join(" ")}"></feFuncR>
<feFuncG type="table" tableValues="${values.g.join(" ")}"></feFuncG>
<feFuncB type="table" tableValues="${values.b.join(" ")}"></feFuncB>
<feFuncA type="table" tableValues="${values.a.join(" ")}"></feFuncA>
</feComponentTransfer>
<!-- Re-mask the image with the original transparency since the feColorMatrix above loses that information. -->
<feComposite in2="SourceGraphic" operator="in"></feComposite>
</filter>
</defs>
</svg>`;
}
// packages/block-editor/build-module/hooks/duotone.mjs
var import_jsx_runtime519 = __toESM(require_jsx_runtime(), 1);
var EMPTY_ARRAY18 = [];
var isSafari = window?.navigator.userAgent && window.navigator.userAgent.includes("Safari") && !window.navigator.userAgent.includes("Chrome") && !window.navigator.userAgent.includes("Chromium");
k([names_default]);
function useMultiOriginPresets({ presetSetting, defaultSetting }) {
const [enableDefault, userPresets, themePresets, defaultPresets] = useSettings(
defaultSetting,
`${presetSetting}.custom`,
`${presetSetting}.theme`,
`${presetSetting}.default`
);
return (0, import_element318.useMemo)(
() => [
...userPresets || EMPTY_ARRAY18,
...themePresets || EMPTY_ARRAY18,
...enableDefault && defaultPresets || EMPTY_ARRAY18
],
[enableDefault, userPresets, themePresets, defaultPresets]
);
}
function getColorsFromDuotonePreset(duotone, duotonePalette) {
if (!duotone) {
return;
}
const preset = duotonePalette?.find(({ slug }) => {
return duotone === `var:preset|duotone|${slug}`;
});
return preset ? preset.colors : void 0;
}
function getDuotonePresetFromColors(colors2, duotonePalette) {
if (!colors2 || !Array.isArray(colors2)) {
return;
}
const preset = duotonePalette?.find((duotonePreset) => {
return duotonePreset?.colors?.every(
(val, index2) => val === colors2[index2]
);
});
return preset ? `var:preset|duotone|${preset.slug}` : void 0;
}
function DuotonePanelPure({ style, setAttributes, name }) {
const duotoneStyle = style?.color?.duotone;
const settings2 = useBlockSettings(name);
const blockEditingMode = useBlockEditingMode();
const duotonePalette = useMultiOriginPresets({
presetSetting: "color.duotone",
defaultSetting: "color.defaultDuotone"
});
const colorPalette = useMultiOriginPresets({
presetSetting: "color.palette",
defaultSetting: "color.defaultPalette"
});
const [enableCustomColors, enableCustomDuotone] = useSettings(
"color.custom",
"color.customDuotone"
);
const disableCustomColors = !enableCustomColors;
const disableCustomDuotone = !enableCustomDuotone || colorPalette?.length === 0 && disableCustomColors;
if (duotonePalette?.length === 0 && disableCustomDuotone) {
return null;
}
if (blockEditingMode !== "default") {
return null;
}
const duotonePresetOrColors = duotoneStyle === "unset" || Array.isArray(duotoneStyle) ? duotoneStyle : getColorsFromDuotonePreset(duotoneStyle, duotonePalette);
return /* @__PURE__ */ (0, import_jsx_runtime519.jsxs)(import_jsx_runtime519.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime519.jsx)(inspector_controls_default, { group: "filter", children: /* @__PURE__ */ (0, import_jsx_runtime519.jsx)(
FiltersPanel,
{
value: { filter: { duotone: duotonePresetOrColors } },
onChange: (newDuotone) => {
const newStyle = {
...style,
color: {
...newDuotone?.filter
}
};
setAttributes({
style: cleanEmptyObject(newStyle)
});
},
settings: settings2
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime519.jsx)(block_controls_default, { group: "block", __experimentalShareWithChildBlocks: true, children: /* @__PURE__ */ (0, import_jsx_runtime519.jsx)(
duotone_control_default,
{
duotonePalette,
colorPalette,
disableCustomDuotone,
disableCustomColors,
value: duotonePresetOrColors,
onChange: (newDuotone) => {
const maybePreset = getDuotonePresetFromColors(
newDuotone,
duotonePalette
);
const newStyle = {
...style,
color: {
...style?.color,
duotone: maybePreset ?? newDuotone
// use preset or fallback to custom colors.
}
};
setAttributes({
style: cleanEmptyObject(newStyle)
});
},
settings: settings2
}
) })
] });
}
var duotone_default = {
shareWithChildBlocks: true,
edit: DuotonePanelPure,
useBlockProps: useBlockProps14,
attributeKeys: ["style"],
hasSupport(name) {
return (0, import_blocks119.hasBlockSupport)(name, "filter.duotone");
}
};
function addDuotoneAttributes(settings2) {
if (!(0, import_blocks119.hasBlockSupport)(settings2, "filter.duotone")) {
return settings2;
}
if (!settings2.attributes.style) {
Object.assign(settings2.attributes, {
style: {
type: "object"
}
});
}
return settings2;
}
function useDuotoneStyles({
clientId,
id: filterId,
selector: duotoneSelector,
attribute: duotoneAttr
}) {
const duotonePalette = useMultiOriginPresets({
presetSetting: "color.duotone",
defaultSetting: "color.defaultDuotone"
});
const isCustom = Array.isArray(duotoneAttr);
const duotonePreset = isCustom ? void 0 : getColorsFromDuotonePreset(duotoneAttr, duotonePalette);
const isPreset = typeof duotoneAttr === "string" && duotonePreset;
const isCSS = typeof duotoneAttr === "string" && !isPreset;
let colors2 = null;
if (isPreset) {
colors2 = duotonePreset;
} else if (isCSS) {
colors2 = duotoneAttr;
} else if (isCustom) {
colors2 = duotoneAttr;
}
const selectors4 = duotoneSelector.split(",");
const selectorsScoped = selectors4.map((selectorPart) => {
return `.${filterId}${selectorPart.trim()}`;
});
const selector3 = selectorsScoped.join(", ");
const isValidFilter = Array.isArray(colors2) || colors2 === "unset";
usePrivateStyleOverride(
isValidFilter ? {
css: colors2 !== "unset" ? getDuotoneStylesheet(selector3, filterId) : getDuotoneUnsetStylesheet(selector3),
__unstableType: "presets"
} : void 0
);
usePrivateStyleOverride(
isValidFilter ? {
assets: colors2 !== "unset" ? getDuotoneFilter(filterId, colors2) : "",
__unstableType: "svgs"
} : void 0
);
const blockElement = useBlockElement(clientId);
(0, import_element318.useEffect)(() => {
if (!isValidFilter) {
return;
}
if (blockElement && isSafari) {
const display = blockElement.style.display;
blockElement.style.setProperty("display", "inline-block");
blockElement.offsetHeight;
blockElement.style.setProperty("display", display);
}
}, [isValidFilter, blockElement, colors2]);
}
var DUOTONE_BLOCK_PROPS_REFERENCE = {};
function useBlockProps14({ clientId, name, style }) {
const id = (0, import_compose107.useInstanceId)(DUOTONE_BLOCK_PROPS_REFERENCE);
const selector3 = (0, import_element318.useMemo)(() => {
const blockType = (0, import_blocks119.getBlockType)(name);
if (blockType) {
const duotoneSupport = (0, import_blocks119.getBlockSupport)(
blockType,
"filter.duotone",
false
);
if (!duotoneSupport) {
return null;
}
const experimentalDuotone = (0, import_blocks119.getBlockSupport)(
blockType,
"color.__experimentalDuotone",
false
);
if (experimentalDuotone) {
const rootSelector = getBlockSelector(blockType);
return typeof experimentalDuotone === "string" ? scopeSelector2(rootSelector, experimentalDuotone) : rootSelector;
}
return getBlockSelector(blockType, "filter.duotone", {
fallback: true
});
}
}, [name]);
const attribute = style?.color?.duotone;
const filterClass = `wp-duotone-${id}`;
const shouldRender = selector3 && attribute;
useDuotoneStyles({
clientId,
id: filterClass,
selector: selector3,
attribute
});
return {
className: shouldRender ? filterClass : ""
};
}
(0, import_hooks30.addFilter)(
"blocks.registerBlockType",
"core/editor/duotone/add-attributes",
addDuotoneAttributes
);
// packages/block-editor/build-module/hooks/custom-css.mjs
var import_element319 = __toESM(require_element(), 1);
var import_data188 = __toESM(require_data(), 1);
var import_compose108 = __toESM(require_compose(), 1);
var import_blocks120 = __toESM(require_blocks(), 1);
var import_i18n244 = __toESM(require_i18n(), 1);
var import_notices13 = __toESM(require_notices(), 1);
var import_jsx_runtime520 = __toESM(require_jsx_runtime(), 1);
var CUSTOM_CSS_INSTANCE_REFERENCE = {};
var EMPTY_STYLE = {};
function CustomCSSControl({ blockName, setAttributes, style }) {
const blockEditingMode = useBlockEditingMode();
if (blockEditingMode !== "default") {
return null;
}
const blockType = (0, import_blocks120.getBlockType)(blockName);
function onChange(newStyle) {
const css = newStyle?.css?.trim() ? newStyle.css : void 0;
setAttributes({
style: cleanEmptyObject({ ...newStyle, css })
});
}
const cssHelpText = (0, import_i18n244.sprintf)(
// translators: %s: is the name of a block e.g., 'Image' or 'Quote'.
(0, import_i18n244.__)(
"Add your own CSS to customize the appearance of the %s block. You do not need to include a CSS selector, just add the property and value, e.g. color: red;."
),
blockType?.title
);
return /* @__PURE__ */ (0, import_jsx_runtime520.jsx)(inspector_controls_default, { group: "advanced", children: /* @__PURE__ */ (0, import_jsx_runtime520.jsx)(
AdvancedPanel,
{
value: style,
onChange,
inheritedValue: style,
help: cssHelpText
}
) });
}
var CUSTOM_CSS_WARNING_NOTICE_ID = "custom-css-edit-warning";
function CustomCSSEdit({ clientId, name, setAttributes }) {
const { style, canEditCSS } = (0, import_data188.useSelect)(
(select3) => {
const { getBlockAttributes: getBlockAttributes3, getSettings: getSettings7 } = select3(store);
return {
style: getBlockAttributes3(clientId)?.style || EMPTY_STYLE,
canEditCSS: getSettings7().canEditCSS
};
},
[clientId]
);
if (!canEditCSS) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime520.jsx)(
CustomCSSControl,
{
blockName: name,
setAttributes,
style
}
);
}
function useBlockProps15({ style }) {
const customCSS = style?.css;
const isValidCSS = typeof customCSS === "string" && customCSS.trim().length > 0 && validateCSS(customCSS);
const canEditCSS = (0, import_data188.useSelect)(
(select3) => select3(store).getSettings().canEditCSS,
[]
);
const { createWarningNotice } = (0, import_data188.useDispatch)(import_notices13.store);
const hasCustomCSS = !!customCSS?.trim();
(0, import_element319.useEffect)(() => {
if (!canEditCSS && hasCustomCSS) {
createWarningNotice(
(0, import_i18n244.__)(
"This post contains blocks with custom CSS. You do not have permission to edit CSS. If you save this post, the custom CSS will be removed."
),
{
id: CUSTOM_CSS_WARNING_NOTICE_ID,
isDismissible: true
}
);
}
}, [canEditCSS, hasCustomCSS, createWarningNotice]);
const customCSSIdentifier = (0, import_compose108.useInstanceId)(
CUSTOM_CSS_INSTANCE_REFERENCE,
"wp-custom-css"
);
const customCSSSelector = `.${customCSSIdentifier}`;
const transformedCSS = (0, import_element319.useMemo)(() => {
if (!isValidCSS) {
return void 0;
}
return processCSSNesting(customCSS, customCSSSelector);
}, [customCSS, customCSSSelector, isValidCSS]);
useStyleOverride({ css: transformedCSS });
if (!isValidCSS) {
return {};
}
return {
className: `has-custom-css ${customCSSIdentifier}`
};
}
function addSaveProps10(props, blockType, attributes) {
if (!(0, import_blocks120.hasBlockSupport)(blockType, "customCSS", true)) {
return props;
}
if (!attributes?.style?.css?.trim()) {
return props;
}
const className = props.className ? `${props.className} has-custom-css` : "has-custom-css";
return {
...props,
className
};
}
var custom_css_default = {
edit: CustomCSSEdit,
useBlockProps: useBlockProps15,
addSaveProps: addSaveProps10,
attributeKeys: ["style"],
hasSupport(name) {
return (0, import_blocks120.hasBlockSupport)(name, "customCSS", true);
}
};
// packages/block-editor/build-module/hooks/layout.mjs
var import_compose109 = __toESM(require_compose(), 1);
var import_hooks31 = __toESM(require_hooks(), 1);
var import_element320 = __toESM(require_element(), 1);
var import_blocks121 = __toESM(require_blocks(), 1);
var import_data189 = __toESM(require_data(), 1);
var import_components267 = __toESM(require_components(), 1);
var import_i18n245 = __toESM(require_i18n(), 1);
var import_jsx_runtime521 = __toESM(require_jsx_runtime(), 1);
var VARIATION_PREFIX2 = "is-style-";
var layoutBlockSupportKey = "layout";
var CHILD_LAYOUT_KEYS = [
"selfStretch",
"flexSize",
"columnStart",
"columnSpan",
"rowStart",
"rowSpan"
];
var { kebabCase: kebabCase6 } = unlock(import_components267.privateApis);
var { getResponsiveMediaQueries: getResponsiveMediaQueries3 } = unlock(privateApis);
function getDefaultLayout(layoutBlockSupport = {}, blockVariation) {
const defaultBlockLayout = layoutBlockSupport?.default;
return blockVariation?.attributes?.layout ?? defaultBlockLayout;
}
function getResetLayout(layoutBlockSupport = {}, blockVariation) {
return cleanEmptyObject({
...getDefaultLayout(layoutBlockSupport, blockVariation)
});
}
function getLayoutStateOverrides(layout = {}, baseLayout = {}, existingLayout = {}) {
const overrides = {};
const childLayoutValues = Object.fromEntries(
CHILD_LAYOUT_KEYS.filter(
(key) => Object.hasOwn(existingLayout || {}, key)
).map((key) => [key, existingLayout[key]])
);
Object.entries(layout || {}).forEach(([key, value]) => {
const baseHasValue = Object.hasOwn(baseLayout || {}, key);
if (!CHILD_LAYOUT_KEYS.includes(key) && value !== baseLayout?.[key]) {
overrides[key] = value === void 0 && baseHasValue ? null : value;
}
});
return cleanEmptyObject({
...childLayoutValues,
...overrides
});
}
function getLayoutContainerValues(layout = {}) {
return Object.fromEntries(
Object.entries(layout || {}).filter(
([key]) => !CHILD_LAYOUT_KEYS.includes(key)
)
);
}
function hasLayoutBlockSupport(blockName) {
return (0, import_blocks121.hasBlockSupport)(blockName, "layout") || (0, import_blocks121.hasBlockSupport)(blockName, "__experimentalLayout");
}
function useLayoutClasses(blockAttributes = {}, blockName = "") {
const { layout } = blockAttributes;
const { default: defaultBlockLayout } = (0, import_blocks121.getBlockSupport)(blockName, layoutBlockSupportKey) || {};
const usedLayout = layout?.inherit || layout?.contentSize || layout?.wideSize ? { ...layout, type: "constrained" } : layout || defaultBlockLayout || {};
const layoutClassnames = [];
if (LAYOUT_DEFINITIONS2[usedLayout?.type || "default"]?.className) {
const baseClassName = LAYOUT_DEFINITIONS2[usedLayout?.type || "default"]?.className;
const splitBlockName = blockName.split("/");
const fullBlockName = splitBlockName[0] === "core" ? splitBlockName.pop() : splitBlockName.join("-");
const compoundClassName = `wp-block-${fullBlockName}-${baseClassName}`;
layoutClassnames.push(baseClassName, compoundClassName);
}
const hasGlobalPadding = (0, import_data189.useSelect)(
(select3) => {
if (!usedLayout?.inherit && !usedLayout?.contentSize && usedLayout?.type !== "constrained") {
return false;
}
return select3(store).getSettings().__experimentalFeatures?.useRootPaddingAwareAlignments;
},
[usedLayout?.contentSize, usedLayout?.inherit, usedLayout?.type]
);
if (hasGlobalPadding) {
layoutClassnames.push("has-global-padding");
}
if (usedLayout?.orientation) {
layoutClassnames.push(`is-${kebabCase6(usedLayout.orientation)}`);
}
if (usedLayout?.justifyContent) {
layoutClassnames.push(
`is-content-justification-${kebabCase6(
usedLayout.justifyContent
)}`
);
}
if (usedLayout?.flexWrap && usedLayout.flexWrap === "nowrap") {
layoutClassnames.push("is-nowrap");
}
return layoutClassnames;
}
function useLayoutStyles(blockAttributes = {}, blockName, selector3) {
const { layout = {}, style = {} } = blockAttributes;
const usedLayout = layout?.inherit || layout?.contentSize || layout?.wideSize ? { ...layout, type: "constrained" } : layout || {};
const fullLayoutType = getLayoutType(usedLayout?.type || "default");
const [blockGapSupport] = useSettings("spacing.blockGap");
const hasBlockGapSupport = blockGapSupport !== null;
return fullLayoutType?.getLayoutStyle?.({
blockName,
selector: selector3,
layout,
style,
hasBlockGapSupport
});
}
function getResponsiveLayoutStyles({
attributes = {},
blockName,
selector: selector3,
layout = {},
hasBlockGapSupport,
globalBlockGapValue,
viewportSettings
}) {
return Object.entries(getResponsiveMediaQueries3(viewportSettings)).map(([viewport, mediaQuery]) => {
const viewportStyle = getStyleForState(attributes?.style, {
viewport,
pseudo: DEFAULT_BLOCK_STYLE_STATE2.pseudo
});
const viewportLayout = getLayoutContainerValues(
viewportStyle?.layout
);
const hasViewportLayout = Object.keys(viewportLayout).length > 0;
const hasViewportBlockGap = viewportStyle?.spacing && Object.hasOwn(viewportStyle.spacing, "blockGap");
const hasViewportPadding = viewportStyle?.spacing && Object.hasOwn(viewportStyle.spacing, "padding");
if (!hasViewportLayout && !hasViewportBlockGap && !hasViewportPadding) {
return "";
}
const layoutType = getLayoutType(layout?.type || "default");
const viewportCSS = layoutType?.getLayoutStyle?.({
blockName,
selector: selector3,
layout,
viewportOverrides: viewportLayout,
style: viewportStyle,
hasBlockGapSupport,
globalBlockGapValue
});
return viewportCSS ? `${mediaQuery}{${viewportCSS}}` : "";
}).filter(Boolean).join("");
}
function LayoutPanelPure({
layout,
style,
setAttributes,
name: blockName,
clientId
}) {
const settings2 = useBlockSettings(blockName);
const { layout: layoutSettings } = settings2;
const {
themeSupportsLayout,
activeBlockVariation,
selectedState,
isResponsiveEditing: isResponsiveEditing3
} = (0, import_data189.useSelect)(
(select3) => {
const {
getBlockAttributes: getBlockAttributes3,
getSettings: getSettings7,
getSelectedBlockStyleState: getSelectedBlockStyleState2,
isResponsiveEditing: getIsResponsiveEditing
} = unlock(select3(store));
return {
activeBlockVariation: select3(
import_blocks121.store
).getActiveBlockVariation(
blockName,
getBlockAttributes3(clientId) || {},
"block"
),
themeSupportsLayout: getSettings7().supportsLayout,
selectedState: getSelectedBlockStyleState2(clientId),
isResponsiveEditing: getIsResponsiveEditing()
};
},
[blockName, clientId]
);
const blockEditingMode = useBlockEditingMode();
const isViewportLayoutState = hasViewportBlockStyleState(selectedState) && !hasPseudoBlockStyleState(selectedState);
const resetLayoutFilter = (0, import_element320.useCallback)(
(...resetArgs) => {
const attributes = resetArgs[0] || {};
const context = resetArgs[1] || {};
if (isViewportLayoutState) {
const existingStateStyle = getStyleForState(
attributes.style ?? style,
selectedState
) || {};
const nextStateStyle = cleanEmptyObject({
...existingStateStyle,
layout: void 0
});
return {
style: setStyleForState(
attributes.style ?? style,
selectedState,
nextStateStyle
)
};
}
const resetBlockName = context.name || blockName;
const resetLayoutBlockSupport = (0, import_blocks121.getBlockSupport)(
resetBlockName,
layoutBlockSupportKey,
{}
);
return {
layout: getResetLayout(
resetLayoutBlockSupport,
activeBlockVariation
)
};
},
[
blockName,
activeBlockVariation,
isViewportLayoutState,
selectedState,
style
]
);
if (blockEditingMode !== "default") {
return null;
}
const layoutBlockSupport = (0, import_blocks121.getBlockSupport)(
blockName,
layoutBlockSupportKey,
{}
);
const blockSupportAndThemeSettings = {
...layoutSettings,
...layoutBlockSupport
};
const {
allowSwitching,
allowEditing = true,
allowInheriting = true,
default: defaultBlockLayout
} = blockSupportAndThemeSettings;
if (!allowEditing) {
return null;
}
const baseLayout = layout || defaultBlockLayout || {};
const stateStyle = isViewportLayoutState ? getStyleForState(style, selectedState) : void 0;
const stateLayout = stateStyle?.layout;
const usedLayout = isViewportLayoutState ? cleanEmptyObject({
...baseLayout,
...stateLayout
}) || {} : baseLayout;
const resetLayoutDefaults = isViewportLayoutState ? baseLayout : getResetLayout(layoutBlockSupport, activeBlockVariation);
const blockSupportAndLayout = {
...layoutBlockSupport,
...usedLayout
};
const { type, default: { type: defaultType = "default" } = {} } = blockSupportAndLayout;
const blockLayoutType = type || defaultType;
const showInheritToggle = !!(allowInheriting && (!blockLayoutType || blockLayoutType === "default" || blockLayoutType === "constrained" || blockSupportAndLayout.inherit));
const { inherit = false, contentSize = null } = usedLayout;
if ((blockLayoutType === "default" || blockLayoutType === "constrained") && !themeSupportsLayout) {
return null;
}
const layoutType = getLayoutType(blockLayoutType);
const constrainedType = getLayoutType("constrained");
const displayControlsForLegacyLayouts = !usedLayout.type && (contentSize || inherit);
const hasContentSizeOrLegacySettings = !!inherit || !!contentSize;
const showLayoutTypeSwitcher = isDefaultBlockStyleState(selectedState) && !inherit && allowSwitching;
const onChangeLayout = (newLayout) => {
if (isViewportLayoutState) {
const nextStateStyle = cleanEmptyObject({
...stateStyle,
layout: getLayoutStateOverrides(
newLayout,
baseLayout,
stateStyle?.layout
)
});
setAttributes({
style: setStyleForState(style, selectedState, nextStateStyle)
});
return;
}
setAttributes({ layout: cleanEmptyObject(newLayout) });
};
const onChangeType = (newType) => onChangeLayout({ type: newType });
const resetLayout = () => onChangeLayout(resetLayoutDefaults);
const resetInheritToggle = () => onChangeLayout({ type: "default" });
const isUsingContentWidth = () => layoutType?.name === "constrained" || hasContentSizeOrLegacySettings;
const hasInheritToggleValue = () => isViewportLayoutState ? (usedLayout?.type ?? "default") !== (resetLayoutDefaults?.type ?? "default") : layout?.type === "constrained";
const hasLayoutTypeValue = () => (usedLayout?.type ?? "default") !== (resetLayoutDefaults?.type ?? "default");
return /* @__PURE__ */ (0, import_jsx_runtime521.jsxs)(import_jsx_runtime521.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime521.jsxs)(
inspector_controls_default,
{
group: "layout",
resetAllFilter: resetLayoutFilter,
children: [
showInheritToggle && /* @__PURE__ */ (0, import_jsx_runtime521.jsx)(
import_components267.__experimentalToolsPanelItem,
{
label: (0, import_i18n245.__)("Use content width"),
hasValue: hasInheritToggleValue,
onDeselect: resetInheritToggle,
isShownByDefault: true,
panelId: clientId,
children: /* @__PURE__ */ (0, import_jsx_runtime521.jsx)(
import_components267.ToggleControl,
{
label: (0, import_i18n245.__)("Inner blocks use content width"),
checked: isUsingContentWidth(),
onChange: () => onChangeLayout({
type: isUsingContentWidth() ? "default" : "constrained"
}),
help: isUsingContentWidth() ? (0, import_i18n245.__)(
"Nested blocks use content width with options for full and wide widths."
) : (0, import_i18n245.__)(
"Nested blocks will fill the width of this container."
)
}
)
}
),
showLayoutTypeSwitcher && /* @__PURE__ */ (0, import_jsx_runtime521.jsx)(
import_components267.__experimentalToolsPanelItem,
{
label: (0, import_i18n245.__)("Layout type"),
hasValue: hasLayoutTypeValue,
onDeselect: resetLayout,
isShownByDefault: true,
panelId: clientId,
children: /* @__PURE__ */ (0, import_jsx_runtime521.jsx)(
LayoutTypeSwitcher,
{
type: blockLayoutType,
onChange: onChangeType
}
)
}
),
layoutType && layoutType.name !== "default" && /* @__PURE__ */ (0, import_jsx_runtime521.jsx)(
layoutType.inspectorControls,
{
layout: usedLayout,
value: layout,
onChange: onChangeLayout,
layoutBlockSupport: blockSupportAndThemeSettings,
resetLayout: resetLayoutDefaults,
name: blockName,
clientId
}
),
constrainedType && displayControlsForLegacyLayouts && /* @__PURE__ */ (0, import_jsx_runtime521.jsx)(
constrainedType.inspectorControls,
{
layout: usedLayout,
value: layout,
onChange: onChangeLayout,
layoutBlockSupport: blockSupportAndThemeSettings,
resetLayout: resetLayoutDefaults,
name: blockName,
clientId
}
)
]
}
),
!inherit && layoutType && /* @__PURE__ */ (0, import_jsx_runtime521.jsx)(
layoutType.toolBarControls,
{
layout: usedLayout,
onChange: onChangeLayout,
layoutBlockSupport,
controlsGroup: isResponsiveEditing3 && hasViewportBlockStyleState(selectedState) && !hasPseudoBlockStyleState(selectedState) ? "style-state" : "block",
name: blockName,
clientId
}
)
] });
}
var layout_default2 = {
shareWithChildBlocks: true,
edit: LayoutPanelPure,
attributeKeys: ["layout", "style"],
hasSupport(name) {
return hasLayoutBlockSupport(name);
}
};
function LayoutTypeSwitcher({ type, onChange }) {
return /* @__PURE__ */ (0, import_jsx_runtime521.jsx)(
import_components267.__experimentalToggleGroupControl,
{
isBlock: true,
label: (0, import_i18n245.__)("Layout type"),
hideLabelFromVision: true,
isAdaptiveWidth: true,
value: type,
onChange,
children: getLayoutTypes().map(({ name, label }) => {
return /* @__PURE__ */ (0, import_jsx_runtime521.jsx)(
import_components267.__experimentalToggleGroupControlOption,
{
value: name,
label
},
name
);
})
}
);
}
function addAttribute9(settings2) {
if ("type" in (settings2.attributes?.layout ?? {})) {
return settings2;
}
if (hasLayoutBlockSupport(settings2)) {
settings2.attributes = {
...settings2.attributes,
layout: {
type: "object"
}
};
}
return settings2;
}
function BlockWithLayoutStyles({
block: BlockListBlock2,
props,
blockGapSupport,
globalBlockGapValue,
viewportSettings,
layoutClasses
}) {
const { name, attributes } = props;
const id = (0, import_compose109.useInstanceId)(BlockListBlock2);
const { layout } = attributes;
const { default: defaultBlockLayout } = (0, import_blocks121.getBlockSupport)(name, layoutBlockSupportKey) || {};
const usedLayout = layout?.inherit || layout?.contentSize || layout?.wideSize ? { ...layout, type: "constrained" } : layout || defaultBlockLayout || {};
const selectorPrefix = `wp-container-${kebabCase6(name)}-is-layout-`;
const selector3 = `.${selectorPrefix}${id}`;
const hasBlockGapSupport = blockGapSupport !== null;
const fullLayoutType = getLayoutType(usedLayout?.type || "default");
const baseLayoutCSS = fullLayoutType?.getLayoutStyle?.({
blockName: name,
selector: selector3,
layout: usedLayout,
style: attributes?.style,
hasBlockGapSupport,
globalBlockGapValue
});
const responsiveLayoutCSS = getResponsiveLayoutStyles({
attributes,
blockName: name,
selector: selector3,
layout: usedLayout,
hasBlockGapSupport,
globalBlockGapValue,
viewportSettings
});
const css = [baseLayoutCSS, responsiveLayoutCSS].filter(Boolean).join("");
const layoutClassNames = clsx_default(
{
[`${selectorPrefix}${id}`]: !!css
// Only attach a container class if there is generated CSS to be attached.
},
layoutClasses
);
useStyleOverride({ css });
return /* @__PURE__ */ (0, import_jsx_runtime521.jsx)(
BlockListBlock2,
{
...props,
__unstableLayoutClassNames: layoutClassNames
}
);
}
var withLayoutStyles = (0, import_compose109.createHigherOrderComponent)(
(BlockListBlock2) => function WithLayoutStyles(props) {
const { clientId, name, attributes } = props;
const blockSupportsLayout = hasLayoutBlockSupport(name);
const layoutClasses = useLayoutClasses(attributes, name);
const extraProps = (0, import_data189.useSelect)(
(select3) => {
if (!blockSupportsLayout) {
return;
}
const { getSettings: getSettings7, getBlockSettings: getBlockSettings2 } = unlock(
select3(store)
);
const settings2 = getSettings7();
const { disableLayoutStyles } = settings2;
if (disableLayoutStyles) {
return;
}
const [blockGapSupport] = getBlockSettings2(
clientId,
"spacing.blockGap"
);
const globalStyles = settings2[globalStylesDataKey];
let variationBlockGapValue;
const className = attributes?.className;
if (className?.includes(VARIATION_PREFIX2)) {
const { getBlockStyles: getBlockStyles2 } = select3(import_blocks121.store);
const registeredStyles = getBlockStyles2(name);
const variationName = getVariationNameFromClass(
className,
registeredStyles
);
variationBlockGapValue = variationName ? globalStyles?.blocks?.[name]?.variations?.[variationName]?.spacing?.blockGap : void 0;
}
const globalBlockGapValue = variationBlockGapValue ?? globalStyles?.blocks?.[name]?.spacing?.blockGap ?? globalStyles?.spacing?.blockGap;
return {
blockGapSupport,
globalBlockGapValue,
viewportSettings: settings2?.__experimentalFeatures?.viewport
};
},
[blockSupportsLayout, clientId, attributes?.className, name]
);
if (!extraProps) {
return /* @__PURE__ */ (0, import_jsx_runtime521.jsx)(
BlockListBlock2,
{
...props,
__unstableLayoutClassNames: blockSupportsLayout ? layoutClasses : void 0
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime521.jsx)(
BlockWithLayoutStyles,
{
block: BlockListBlock2,
props,
layoutClasses,
...extraProps
}
);
},
"withLayoutStyles"
);
(0, import_hooks31.addFilter)(
"blocks.registerBlockType",
"core/layout/addAttribute",
addAttribute9
);
(0, import_hooks31.addFilter)(
"editor.BlockListBlock",
"core/editor/layout/with-layout-styles",
withLayoutStyles
);
// packages/block-editor/build-module/hooks/layout-child.mjs
var import_compose113 = __toESM(require_compose(), 1);
var import_data193 = __toESM(require_data(), 1);
var import_element324 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/grid/grid-visualizer.mjs
var import_element321 = __toESM(require_element(), 1);
var import_data190 = __toESM(require_data(), 1);
var import_compose110 = __toESM(require_compose(), 1);
// packages/block-editor/build-module/components/grid/utils.mjs
function range(start2, length) {
return Array.from({ length }, (_, i2) => start2 + i2);
}
var GridRect = class {
constructor({
columnStart,
rowStart,
columnEnd,
rowEnd,
columnSpan,
rowSpan
} = {}) {
this.columnStart = columnStart ?? 1;
this.rowStart = rowStart ?? 1;
if (columnSpan !== void 0) {
this.columnEnd = this.columnStart + columnSpan - 1;
} else {
this.columnEnd = columnEnd ?? this.columnStart;
}
if (rowSpan !== void 0) {
this.rowEnd = this.rowStart + rowSpan - 1;
} else {
this.rowEnd = rowEnd ?? this.rowStart;
}
}
get columnSpan() {
return this.columnEnd - this.columnStart + 1;
}
get rowSpan() {
return this.rowEnd - this.rowStart + 1;
}
contains(column, row) {
return column >= this.columnStart && column <= this.columnEnd && row >= this.rowStart && row <= this.rowEnd;
}
containsRect(rect) {
return this.contains(rect.columnStart, rect.rowStart) && this.contains(rect.columnEnd, rect.rowEnd);
}
intersectsRect(rect) {
return this.columnStart <= rect.columnEnd && this.columnEnd >= rect.columnStart && this.rowStart <= rect.rowEnd && this.rowEnd >= rect.rowStart;
}
};
function getComputedCSS2(element, property) {
return element.ownerDocument.defaultView.getComputedStyle(element).getPropertyValue(property);
}
function getGridTracks(template2, gap) {
const tracks = [];
for (const size4 of template2.split(" ")) {
const previousTrack = tracks[tracks.length - 1];
const start2 = previousTrack ? previousTrack.end + gap : 0;
const end = start2 + parseFloat(size4);
tracks.push({ start: start2, end });
}
return tracks;
}
function getClosestTrack(tracks, position, edge = "start") {
return tracks.reduce(
(closest, track, index2) => Math.abs(track[edge] - position) < Math.abs(tracks[closest][edge] - position) ? index2 : closest,
0
);
}
function getGridRect(gridElement, rect) {
const columnGap = parseFloat(getComputedCSS2(gridElement, "column-gap"));
const rowGap = parseFloat(getComputedCSS2(gridElement, "row-gap"));
const gridColumnTracks = getGridTracks(
getComputedCSS2(gridElement, "grid-template-columns"),
columnGap
);
const gridRowTracks = getGridTracks(
getComputedCSS2(gridElement, "grid-template-rows"),
rowGap
);
const columnStart = getClosestTrack(gridColumnTracks, rect.left) + 1;
const rowStart = getClosestTrack(gridRowTracks, rect.top) + 1;
const columnEnd = getClosestTrack(gridColumnTracks, rect.right, "end") + 1;
const rowEnd = getClosestTrack(gridRowTracks, rect.bottom, "end") + 1;
return new GridRect({
columnStart,
columnEnd,
rowStart,
rowEnd
});
}
function getGridItemRect(gridItemElement) {
return getGridRect(
gridItemElement.parentElement,
new window.DOMRect(
gridItemElement.offsetLeft,
gridItemElement.offsetTop,
gridItemElement.offsetWidth,
gridItemElement.offsetHeight
)
);
}
function getGridInfo(gridElement) {
const gridTemplateColumns = getComputedCSS2(
gridElement,
"grid-template-columns"
);
const gridTemplateRows = getComputedCSS2(
gridElement,
"grid-template-rows"
);
const borderTopWidth = getComputedCSS2(gridElement, "border-top-width");
const borderRightWidth = getComputedCSS2(
gridElement,
"border-right-width"
);
const borderBottomWidth = getComputedCSS2(
gridElement,
"border-bottom-width"
);
const borderLeftWidth = getComputedCSS2(gridElement, "border-left-width");
const paddingTop = getComputedCSS2(gridElement, "padding-top");
const paddingRight = getComputedCSS2(gridElement, "padding-right");
const paddingBottom = getComputedCSS2(gridElement, "padding-bottom");
const paddingLeft = getComputedCSS2(gridElement, "padding-left");
const numColumns = gridTemplateColumns.split(" ").length;
const numRows = gridTemplateRows.split(" ").length;
const numItems = numColumns * numRows;
return {
numColumns,
numRows,
numItems,
currentColor: getComputedCSS2(gridElement, "color"),
style: {
gridTemplateColumns,
gridTemplateRows,
gap: getComputedCSS2(gridElement, "gap"),
inset: `
calc(${paddingTop} + ${borderTopWidth})
calc(${paddingRight} + ${borderRightWidth})
calc(${paddingBottom} + ${borderBottomWidth})
calc(${paddingLeft} + ${borderLeftWidth})
`
}
};
}
// packages/block-editor/build-module/components/grid/grid-visualizer.mjs
var import_jsx_runtime522 = __toESM(require_jsx_runtime(), 1);
function GridVisualizer({
clientId,
contentRef,
parentLayout,
childGridClientId
}) {
const isDistractionFree = (0, import_data190.useSelect)(
(select3) => select3(store).getSettings().isDistractionFree,
[]
);
const gridElement = useBlockElement(clientId);
if (isDistractionFree || !gridElement) {
return null;
}
const isManualGrid = parentLayout?.isManualPlacement && window.__experimentalEnableGridInteractivity;
return /* @__PURE__ */ (0, import_jsx_runtime522.jsx)(
GridVisualizerGrid,
{
gridClientId: clientId,
gridElement,
isManualGrid,
ref: contentRef,
childGridClientId
}
);
}
var GridVisualizerGrid = (0, import_element321.forwardRef)(
({ gridClientId, gridElement, isManualGrid, childGridClientId }, ref) => {
const [gridInfo, setGridInfo] = (0, import_element321.useState)(
() => getGridInfo(gridElement)
);
const [isDroppingAllowed, setIsDroppingAllowed] = (0, import_element321.useState)(false);
const childGridElement = useBlockElement(childGridClientId);
const childGridRect = (0, import_element321.useMemo)(() => {
if (!childGridElement) {
return null;
}
return getGridItemRect(childGridElement);
}, [childGridElement]);
(0, import_element321.useEffect)(() => {
const resizeCallback = () => setGridInfo(getGridInfo(gridElement));
const borderBoxSpy = new window.ResizeObserver(resizeCallback);
borderBoxSpy.observe(gridElement, { box: "border-box" });
const contentBoxSpy = new window.ResizeObserver(resizeCallback);
contentBoxSpy.observe(gridElement);
for (const element of gridElement.children) {
contentBoxSpy.observe(element);
}
return () => {
borderBoxSpy.disconnect();
contentBoxSpy.disconnect();
};
}, [gridElement]);
(0, import_element321.useEffect)(() => {
function onGlobalDrag() {
setIsDroppingAllowed(true);
}
function onGlobalDragEnd() {
setIsDroppingAllowed(false);
}
document.addEventListener("drag", onGlobalDrag);
document.addEventListener("dragend", onGlobalDragEnd);
return () => {
document.removeEventListener("drag", onGlobalDrag);
document.removeEventListener("dragend", onGlobalDragEnd);
};
}, []);
return /* @__PURE__ */ (0, import_jsx_runtime522.jsx)(
cover_default,
{
className: clsx_default("block-editor-grid-visualizer", {
"is-dropping-allowed": isDroppingAllowed
}),
clientId: gridClientId,
__unstablePopoverSlot: "__unstable-block-tools-after",
children: /* @__PURE__ */ (0, import_jsx_runtime522.jsx)(
"div",
{
ref,
className: "block-editor-grid-visualizer__grid",
style: gridInfo.style,
children: isManualGrid ? /* @__PURE__ */ (0, import_jsx_runtime522.jsx)(
ManualGridVisualizer,
{
gridClientId,
gridInfo,
childGridRect
}
) : /* @__PURE__ */ (0, import_jsx_runtime522.jsx)(
AutoGridVisualizer,
{
gridInfo,
childGridRect
}
)
}
)
}
);
}
);
function AutoGridVisualizer({ gridInfo, childGridRect }) {
return range(1, gridInfo.numRows).map(
(row) => range(1, gridInfo.numColumns).map((column) => {
let color = gridInfo.currentColor;
if (childGridRect?.contains(column, row)) {
color = "transparent";
}
return /* @__PURE__ */ (0, import_jsx_runtime522.jsx)(
GridVisualizerCell,
{
color
},
`${row}-${column}`
);
})
);
}
function ManualGridVisualizer({ gridClientId, gridInfo, childGridRect }) {
const [highlightedRect, setHighlightedRect] = (0, import_element321.useState)(null);
const gridItemStyles = (0, import_data190.useSelect)(
(select3) => {
const { getBlockOrder: getBlockOrder2, getBlockStyles: getBlockStyles2 } = unlock(
select3(store)
);
const blockOrder = getBlockOrder2(gridClientId);
return getBlockStyles2(blockOrder);
},
[gridClientId]
);
const occupiedRects = (0, import_element321.useMemo)(() => {
const rects = [];
for (const style of Object.values(gridItemStyles)) {
const {
columnStart,
rowStart,
columnSpan = 1,
rowSpan = 1
} = style?.layout ?? {};
if (!columnStart || !rowStart) {
continue;
}
rects.push(
new GridRect({
columnStart,
rowStart,
columnSpan,
rowSpan
})
);
}
return rects;
}, [gridItemStyles]);
return range(1, gridInfo.numRows).map(
(row) => range(1, gridInfo.numColumns).map((column) => {
const isChildGridCell = childGridRect?.contains(column, row);
let color = gridInfo.currentColor;
if (isChildGridCell) {
color = "transparent";
}
const isCellOccupied = occupiedRects.some(
(rect) => rect.contains(column, row)
);
const isHighlighted = highlightedRect?.contains(column, row) ?? false;
return /* @__PURE__ */ (0, import_jsx_runtime522.jsx)(
GridVisualizerCell,
{
color,
className: isHighlighted && "is-highlighted",
children: isCellOccupied && !isChildGridCell ? /* @__PURE__ */ (0, import_jsx_runtime522.jsx)(
GridVisualizerDropZone,
{
column,
row,
gridClientId,
gridInfo,
setHighlightedRect
}
) : /* @__PURE__ */ (0, import_jsx_runtime522.jsx)(
GridVisualizerAppender,
{
column,
row,
gridClientId,
gridInfo,
setHighlightedRect
}
)
},
`${row}-${column}`
);
})
);
}
function GridVisualizerCell({ color, children, className }) {
return /* @__PURE__ */ (0, import_jsx_runtime522.jsx)(
"div",
{
className: clsx_default(
"block-editor-grid-visualizer__cell",
className
),
style: {
boxShadow: `inset 0 0 0 1px color-mix(in srgb, ${color} 20%, #0000)`,
color
},
children
}
);
}
function useGridVisualizerDropZone(column, row, gridClientId, gridInfo, setHighlightedRect) {
const {
getBlockAttributes: getBlockAttributes3,
getBlockRootClientId: getBlockRootClientId2,
canInsertBlockType: canInsertBlockType2,
getBlockName: getBlockName2
} = (0, import_data190.useSelect)(store);
const {
updateBlockAttributes: updateBlockAttributes2,
moveBlocksToPosition: moveBlocksToPosition2,
__unstableMarkNextChangeAsNotPersistent: __unstableMarkNextChangeAsNotPersistent2
} = (0, import_data190.useDispatch)(store);
const getNumberOfBlocksBeforeCell = useGetNumberOfBlocksBeforeCell(
gridClientId,
gridInfo.numColumns
);
return useDropZoneWithValidation({
validateDrag(srcClientId) {
const blockName = getBlockName2(srcClientId);
if (!canInsertBlockType2(blockName, gridClientId)) {
return false;
}
const attributes = getBlockAttributes3(srcClientId);
const rect = new GridRect({
columnStart: column,
rowStart: row,
columnSpan: attributes.style?.layout?.columnSpan,
rowSpan: attributes.style?.layout?.rowSpan
});
const isInBounds = new GridRect({
columnSpan: gridInfo.numColumns,
rowSpan: gridInfo.numRows
}).containsRect(rect);
return isInBounds;
},
onDragEnter(srcClientId) {
const attributes = getBlockAttributes3(srcClientId);
setHighlightedRect(
new GridRect({
columnStart: column,
rowStart: row,
columnSpan: attributes.style?.layout?.columnSpan,
rowSpan: attributes.style?.layout?.rowSpan
})
);
},
onDragLeave() {
setHighlightedRect(
(prevHighlightedRect) => prevHighlightedRect?.columnStart === column && prevHighlightedRect?.rowStart === row ? null : prevHighlightedRect
);
},
onDrop(srcClientId) {
setHighlightedRect(null);
const attributes = getBlockAttributes3(srcClientId);
updateBlockAttributes2(srcClientId, {
style: {
...attributes.style,
layout: {
...attributes.style?.layout,
columnStart: column,
rowStart: row
}
}
});
__unstableMarkNextChangeAsNotPersistent2();
moveBlocksToPosition2(
[srcClientId],
getBlockRootClientId2(srcClientId),
gridClientId,
getNumberOfBlocksBeforeCell(column, row)
);
}
});
}
function GridVisualizerDropZone({
column,
row,
gridClientId,
gridInfo,
setHighlightedRect
}) {
return /* @__PURE__ */ (0, import_jsx_runtime522.jsx)(
"div",
{
className: "block-editor-grid-visualizer__drop-zone",
ref: useGridVisualizerDropZone(
column,
row,
gridClientId,
gridInfo,
setHighlightedRect
)
}
);
}
function GridVisualizerAppender({
column,
row,
gridClientId,
gridInfo,
setHighlightedRect
}) {
const {
updateBlockAttributes: updateBlockAttributes2,
moveBlocksToPosition: moveBlocksToPosition2,
__unstableMarkNextChangeAsNotPersistent: __unstableMarkNextChangeAsNotPersistent2
} = (0, import_data190.useDispatch)(store);
const getNumberOfBlocksBeforeCell = useGetNumberOfBlocksBeforeCell(
gridClientId,
gridInfo.numColumns
);
return /* @__PURE__ */ (0, import_jsx_runtime522.jsx)(
button_block_appender_default,
{
rootClientId: gridClientId,
className: "block-editor-grid-visualizer__appender",
ref: useGridVisualizerDropZone(
column,
row,
gridClientId,
gridInfo,
setHighlightedRect
),
style: {
color: gridInfo.currentColor
},
onSelect: (block) => {
if (!block) {
return;
}
updateBlockAttributes2(block.clientId, {
style: {
layout: {
columnStart: column,
rowStart: row
}
}
});
__unstableMarkNextChangeAsNotPersistent2();
moveBlocksToPosition2(
[block.clientId],
gridClientId,
gridClientId,
getNumberOfBlocksBeforeCell(column, row)
);
}
}
);
}
function useDropZoneWithValidation({
validateDrag,
onDragEnter,
onDragLeave,
onDrop
}) {
const { getDraggedBlockClientIds: getDraggedBlockClientIds2 } = (0, import_data190.useSelect)(store);
return (0, import_compose110.__experimentalUseDropZone)({
onDragEnter() {
const [srcClientId] = getDraggedBlockClientIds2();
if (srcClientId && validateDrag(srcClientId)) {
onDragEnter(srcClientId);
}
},
onDragLeave() {
onDragLeave();
},
onDrop() {
const [srcClientId] = getDraggedBlockClientIds2();
if (srcClientId && validateDrag(srcClientId)) {
onDrop(srcClientId);
}
}
});
}
// packages/block-editor/build-module/components/grid/grid-item-resizer.mjs
var import_components269 = __toESM(require_components(), 1);
var import_element322 = __toESM(require_element(), 1);
var import_jsx_runtime523 = __toESM(require_jsx_runtime(), 1);
function GridItemResizer({
clientId,
bounds,
onChange,
parentLayout
}) {
const blockElement = useBlockElement(clientId);
const rootBlockElement = blockElement?.parentElement;
const { isManualPlacement } = parentLayout;
if (!blockElement || !rootBlockElement) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime523.jsx)(
GridItemResizerInner,
{
clientId,
bounds,
blockElement,
rootBlockElement,
onChange,
isManualGrid: isManualPlacement && window.__experimentalEnableGridInteractivity
}
);
}
function GridItemResizerInner({
clientId,
bounds,
blockElement,
rootBlockElement,
onChange,
isManualGrid
}) {
const [resizeDirection, setResizeDirection] = (0, import_element322.useState)(null);
const [enableSide, setEnableSide] = (0, import_element322.useState)({
top: false,
bottom: false,
left: false,
right: false
});
(0, import_element322.useEffect)(() => {
const observer = new window.ResizeObserver(() => {
const blockClientRect = blockElement.getBoundingClientRect();
const rootBlockClientRect = rootBlockElement.getBoundingClientRect();
const topAvailable = blockClientRect.top > rootBlockClientRect.top;
const bottomAvailable = blockClientRect.bottom < rootBlockClientRect.bottom;
const leftAvailable = blockClientRect.left > rootBlockClientRect.left;
const rightAvailable = blockClientRect.right < rootBlockClientRect.right;
setEnableSide({
top: !!isManualGrid ? topAvailable : !bottomAvailable && topAvailable,
bottom: bottomAvailable,
left: !!isManualGrid ? leftAvailable : !rightAvailable && leftAvailable,
right: rightAvailable
});
});
observer.observe(blockElement);
return () => observer.disconnect();
}, [blockElement, rootBlockElement, isManualGrid]);
const justification = {
right: "left",
left: "right"
};
const alignment = {
top: "flex-end",
bottom: "flex-start"
};
const styles = {
display: "flex",
justifyContent: "center",
alignItems: "center",
...justification[resizeDirection] && {
justifyContent: justification[resizeDirection]
},
...alignment[resizeDirection] && {
alignItems: alignment[resizeDirection]
}
};
return /* @__PURE__ */ (0, import_jsx_runtime523.jsx)(
cover_default,
{
className: "block-editor-grid-item-resizer",
clientId,
__unstablePopoverSlot: "__unstable-block-tools-after",
additionalStyles: styles,
children: /* @__PURE__ */ (0, import_jsx_runtime523.jsx)(
import_components269.ResizableBox,
{
className: "block-editor-grid-item-resizer__box",
size: {
width: "100%",
height: "100%"
},
enable: {
bottom: enableSide.bottom,
bottomLeft: false,
bottomRight: false,
left: enableSide.left,
right: enableSide.right,
top: enableSide.top,
topLeft: false,
topRight: false
},
bounds,
boundsByDirection: true,
onPointerDown: ({ target, pointerId }) => {
target.setPointerCapture(pointerId);
},
onResizeStart: (event, direction) => {
setResizeDirection(direction);
},
onResizeStop: (event, direction, boxElement) => {
const columnGap = parseFloat(
getComputedCSS2(rootBlockElement, "column-gap")
);
const rowGap = parseFloat(
getComputedCSS2(rootBlockElement, "row-gap")
);
const gridColumnTracks = getGridTracks(
getComputedCSS2(
rootBlockElement,
"grid-template-columns"
),
columnGap
);
const gridRowTracks = getGridTracks(
getComputedCSS2(
rootBlockElement,
"grid-template-rows"
),
rowGap
);
const rect = new window.DOMRect(
blockElement.offsetLeft + boxElement.offsetLeft,
blockElement.offsetTop + boxElement.offsetTop,
boxElement.offsetWidth,
boxElement.offsetHeight
);
const columnStart = getClosestTrack(gridColumnTracks, rect.left) + 1;
const rowStart = getClosestTrack(gridRowTracks, rect.top) + 1;
const columnEnd = getClosestTrack(gridColumnTracks, rect.right, "end") + 1;
const rowEnd = getClosestTrack(gridRowTracks, rect.bottom, "end") + 1;
onChange({
columnSpan: columnEnd - columnStart + 1,
rowSpan: rowEnd - rowStart + 1,
columnStart: isManualGrid ? columnStart : void 0,
rowStart: isManualGrid ? rowStart : void 0
});
}
}
)
}
);
}
// packages/block-editor/build-module/components/grid/grid-item-movers.mjs
var import_i18n246 = __toESM(require_i18n(), 1);
var import_components270 = __toESM(require_components(), 1);
var import_data191 = __toESM(require_data(), 1);
var import_compose111 = __toESM(require_compose(), 1);
var import_jsx_runtime524 = __toESM(require_jsx_runtime(), 1);
function GridItemMovers({
layout,
parentLayout,
onChange,
gridClientId,
blockClientId
}) {
const { moveBlocksToPosition: moveBlocksToPosition2, __unstableMarkNextChangeAsNotPersistent: __unstableMarkNextChangeAsNotPersistent2 } = (0, import_data191.useDispatch)(store);
const columnStart = layout?.columnStart ?? 1;
const rowStart = layout?.rowStart ?? 1;
const columnSpan = layout?.columnSpan ?? 1;
const rowSpan = layout?.rowSpan ?? 1;
const columnEnd = columnStart + columnSpan - 1;
const rowEnd = rowStart + rowSpan - 1;
const columnCount = parentLayout?.columnCount;
const rowCount = parentLayout?.rowCount;
const getNumberOfBlocksBeforeCell = useGetNumberOfBlocksBeforeCell(
gridClientId,
columnCount
);
return /* @__PURE__ */ (0, import_jsx_runtime524.jsx)(block_controls_default, { group: "parent", children: /* @__PURE__ */ (0, import_jsx_runtime524.jsxs)(import_components270.ToolbarGroup, { className: "block-editor-grid-item-mover__move-button-container", children: [
/* @__PURE__ */ (0, import_jsx_runtime524.jsx)("div", { className: "block-editor-grid-item-mover__move-horizontal-button-container is-left", children: /* @__PURE__ */ (0, import_jsx_runtime524.jsx)(
GridItemMover,
{
icon: (0, import_i18n246.isRTL)() ? chevron_right_default : chevron_left_default,
label: (0, import_i18n246.__)("Move left"),
description: (0, import_i18n246.__)("Move left"),
isDisabled: columnStart <= 1,
onClick: () => {
onChange({
columnStart: columnStart - 1
});
__unstableMarkNextChangeAsNotPersistent2();
moveBlocksToPosition2(
[blockClientId],
gridClientId,
gridClientId,
getNumberOfBlocksBeforeCell(
columnStart - 1,
rowStart
)
);
}
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime524.jsxs)("div", { className: "block-editor-grid-item-mover__move-vertical-button-container", children: [
/* @__PURE__ */ (0, import_jsx_runtime524.jsx)(
GridItemMover,
{
className: "is-up-button",
icon: chevron_up_default,
label: (0, import_i18n246.__)("Move up"),
description: (0, import_i18n246.__)("Move up"),
isDisabled: rowStart <= 1,
onClick: () => {
onChange({
rowStart: rowStart - 1
});
__unstableMarkNextChangeAsNotPersistent2();
moveBlocksToPosition2(
[blockClientId],
gridClientId,
gridClientId,
getNumberOfBlocksBeforeCell(
columnStart,
rowStart - 1
)
);
}
}
),
/* @__PURE__ */ (0, import_jsx_runtime524.jsx)(
GridItemMover,
{
className: "is-down-button",
icon: chevron_down_default,
label: (0, import_i18n246.__)("Move down"),
description: (0, import_i18n246.__)("Move down"),
isDisabled: rowCount && rowEnd >= rowCount,
onClick: () => {
onChange({
rowStart: rowStart + 1
});
__unstableMarkNextChangeAsNotPersistent2();
moveBlocksToPosition2(
[blockClientId],
gridClientId,
gridClientId,
getNumberOfBlocksBeforeCell(
columnStart,
rowStart + 1
)
);
}
}
)
] }),
/* @__PURE__ */ (0, import_jsx_runtime524.jsx)("div", { className: "block-editor-grid-item-mover__move-horizontal-button-container is-right", children: /* @__PURE__ */ (0, import_jsx_runtime524.jsx)(
GridItemMover,
{
icon: (0, import_i18n246.isRTL)() ? chevron_left_default : chevron_right_default,
label: (0, import_i18n246.__)("Move right"),
description: (0, import_i18n246.__)("Move right"),
isDisabled: columnCount && columnEnd >= columnCount,
onClick: () => {
onChange({
columnStart: columnStart + 1
});
__unstableMarkNextChangeAsNotPersistent2();
moveBlocksToPosition2(
[blockClientId],
gridClientId,
gridClientId,
getNumberOfBlocksBeforeCell(
columnStart + 1,
rowStart
)
);
}
}
) })
] }) });
}
function GridItemMover({
className,
icon,
label,
isDisabled,
onClick,
description
}) {
const instanceId = (0, import_compose111.useInstanceId)(GridItemMover);
const descriptionId = `block-editor-grid-item-mover-button__description-${instanceId}`;
return /* @__PURE__ */ (0, import_jsx_runtime524.jsxs)(import_jsx_runtime524.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime524.jsx)(
import_components270.ToolbarButton,
{
className: clsx_default(
"block-editor-grid-item-mover-button",
className
),
icon,
label,
"aria-describedby": descriptionId,
onClick: isDisabled ? null : onClick,
disabled: isDisabled,
accessibleWhenDisabled: true
}
),
/* @__PURE__ */ (0, import_jsx_runtime524.jsx)(VisuallyHidden, { id: descriptionId, children: description })
] });
}
// packages/block-editor/build-module/components/grid/use-grid-layout-sync.mjs
var import_data192 = __toESM(require_data(), 1);
var import_element323 = __toESM(require_element(), 1);
var import_compose112 = __toESM(require_compose(), 1);
function useGridLayoutSync({ clientId: gridClientId }) {
const { gridLayout, blockOrder, selectedBlockLayout } = (0, import_data192.useSelect)(
(select3) => {
const { getBlockAttributes: getBlockAttributes22, getBlockOrder: getBlockOrder2 } = select3(store);
const selectedBlock = select3(store).getSelectedBlock();
return {
gridLayout: getBlockAttributes22(gridClientId).layout ?? {},
blockOrder: getBlockOrder2(gridClientId),
selectedBlockLayout: selectedBlock?.attributes.style?.layout
};
},
[gridClientId]
);
const { getBlockAttributes: getBlockAttributes3, getBlockRootClientId: getBlockRootClientId2 } = (0, import_data192.useSelect)(store);
const { updateBlockAttributes: updateBlockAttributes2, __unstableMarkNextChangeAsNotPersistent: __unstableMarkNextChangeAsNotPersistent2 } = (0, import_data192.useDispatch)(store);
const selectedBlockRect = (0, import_element323.useMemo)(
() => selectedBlockLayout ? new GridRect(selectedBlockLayout) : null,
[selectedBlockLayout]
);
const previouslySelectedBlockRect = (0, import_compose112.usePrevious)(selectedBlockRect);
const previousIsManualPlacement = (0, import_compose112.usePrevious)(
gridLayout.isManualPlacement
);
const previousBlockOrder = (0, import_compose112.usePrevious)(blockOrder);
(0, import_element323.useEffect)(() => {
const updates = {};
if (gridLayout.isManualPlacement) {
const occupiedRects = [];
for (const clientId of blockOrder) {
const {
columnStart,
rowStart,
columnSpan = 1,
rowSpan = 1
} = getBlockAttributes3(clientId).style?.layout ?? {};
if (!columnStart || !rowStart) {
continue;
}
occupiedRects.push(
new GridRect({
columnStart,
rowStart,
columnSpan,
rowSpan
})
);
}
for (const clientId of blockOrder) {
const attributes = getBlockAttributes3(clientId);
const {
columnStart,
rowStart,
columnSpan = 1,
rowSpan = 1
} = attributes.style?.layout ?? {};
if (columnStart && rowStart) {
continue;
}
const [newColumnStart, newRowStart] = placeBlock(
occupiedRects,
gridLayout.columnCount,
columnSpan,
rowSpan,
previouslySelectedBlockRect?.columnEnd,
previouslySelectedBlockRect?.rowEnd
);
occupiedRects.push(
new GridRect({
columnStart: newColumnStart,
rowStart: newRowStart,
columnSpan,
rowSpan
})
);
updates[clientId] = {
style: {
...attributes.style,
layout: {
...attributes.style?.layout,
columnStart: newColumnStart,
rowStart: newRowStart
}
}
};
}
const bottomMostRow = Math.max(
...occupiedRects.map((r3) => r3.rowEnd)
);
if (!gridLayout.rowCount || gridLayout.rowCount < bottomMostRow) {
updates[gridClientId] = {
layout: {
...gridLayout,
rowCount: bottomMostRow
}
};
}
for (const clientId of previousBlockOrder ?? []) {
if (!blockOrder.includes(clientId)) {
const rootClientId = getBlockRootClientId2(clientId);
if (rootClientId === null) {
continue;
}
const rootAttributes = getBlockAttributes3(rootClientId);
if (rootAttributes?.layout?.type === "grid") {
continue;
}
const attributes = getBlockAttributes3(clientId);
const {
columnStart,
rowStart,
columnSpan,
rowSpan,
...layout
} = attributes.style?.layout ?? {};
if (columnStart || rowStart || columnSpan || rowSpan) {
const hasEmptyLayoutAttribute = Object.keys(layout).length === 0;
updates[clientId] = setImmutably2(
attributes,
["style", "layout"],
hasEmptyLayoutAttribute ? void 0 : layout
);
}
}
}
} else {
if (previousIsManualPlacement === true) {
for (const clientId of blockOrder) {
const attributes = getBlockAttributes3(clientId);
const { columnStart, rowStart, ...layout } = attributes.style?.layout ?? {};
if (columnStart || rowStart) {
const hasEmptyLayoutAttribute = Object.keys(layout).length === 0;
updates[clientId] = setImmutably2(
attributes,
["style", "layout"],
hasEmptyLayoutAttribute ? void 0 : layout
);
}
}
}
if (gridLayout.rowCount) {
updates[gridClientId] = {
layout: {
...gridLayout,
rowCount: void 0
}
};
}
}
if (Object.keys(updates).length) {
__unstableMarkNextChangeAsNotPersistent2();
updateBlockAttributes2(
Object.keys(updates),
updates,
/* uniqueByBlock: */
true
);
}
}, [
// Actual deps to sync:
gridClientId,
gridLayout,
previousBlockOrder,
blockOrder,
previouslySelectedBlockRect,
previousIsManualPlacement,
// These won't change, but the linter thinks they might:
__unstableMarkNextChangeAsNotPersistent2,
getBlockAttributes3,
getBlockRootClientId2,
updateBlockAttributes2
]);
}
function placeBlock(occupiedRects, gridColumnCount, blockColumnSpan, blockRowSpan, startColumn = 1, startRow = 1) {
for (let row = startRow; ; row++) {
for (let column = row === startRow ? startColumn : 1; column <= gridColumnCount; column++) {
const candidateRect = new GridRect({
columnStart: column,
rowStart: row,
columnSpan: blockColumnSpan,
rowSpan: blockRowSpan
});
if (!occupiedRects.some(
(r3) => r3.intersectsRect(candidateRect)
)) {
return [column, row];
}
}
}
}
// packages/block-editor/build-module/hooks/layout-child.mjs
var import_jsx_runtime525 = __toESM(require_jsx_runtime(), 1);
var { getResponsiveMediaQueries: getResponsiveMediaQueries4 } = unlock(privateApis);
var LAYOUT_CHILD_BLOCK_PROPS_REFERENCE = {};
var FLEX_CHILD_LAYOUT_VALUES2 = {
fit: "fit",
grow: "fill",
max: "fixed",
fixed: "fixedNoShrink"
};
var FLEX_SIZE_VALUES2 = [
FLEX_CHILD_LAYOUT_VALUES2.max,
FLEX_CHILD_LAYOUT_VALUES2.fixed
];
function isFlexSizeValue2(value) {
return FLEX_SIZE_VALUES2.includes(value);
}
function serializeRule({ selector: selector3, declarations }) {
return `${selector3} {
${Object.entries(declarations).map(([property, value]) => `${property}: ${value}`).join("; ")};
}`;
}
function getChildLayoutStyleRules({
selector: selector3,
layout = {},
viewportOverrides,
parentLayout = {},
includeContainerQuery = true
}) {
const hasViewportOverrides = viewportOverrides !== void 0;
const effectiveLayout = hasViewportOverrides ? {
...layout,
...viewportOverrides
} : layout;
const hasViewportOverride = (key) => Object.hasOwn(viewportOverrides || {}, key);
const {
selfStretch,
flexSize,
columnStart,
rowStart,
columnSpan,
rowSpan
} = effectiveLayout;
const baseSelfStretch = layout.selfStretch;
const { columnCount, minimumColumnWidth } = parentLayout;
const rules = [];
const declarations = {};
if (!hasViewportOverrides || hasViewportOverride("selfStretch") || hasViewportOverride("flexSize")) {
if (hasViewportOverrides && (selfStretch === FLEX_CHILD_LAYOUT_VALUES2.fit || selfStretch === FLEX_CHILD_LAYOUT_VALUES2.grow) && isFlexSizeValue2(baseSelfStretch) && layout.flexSize) {
declarations["flex-basis"] = "unset";
if (baseSelfStretch === FLEX_CHILD_LAYOUT_VALUES2.fixed) {
declarations["flex-shrink"] = "unset";
}
}
if (isFlexSizeValue2(selfStretch) && flexSize) {
declarations["flex-basis"] = flexSize;
if (selfStretch === FLEX_CHILD_LAYOUT_VALUES2.fixed) {
declarations["flex-shrink"] = "0";
} else if (hasViewportOverrides && baseSelfStretch === FLEX_CHILD_LAYOUT_VALUES2.fixed) {
declarations["flex-shrink"] = "unset";
}
declarations["box-sizing"] = "border-box";
} else if (selfStretch === FLEX_CHILD_LAYOUT_VALUES2.grow) {
declarations["flex-grow"] = "1";
}
}
if (!hasViewportOverrides || hasViewportOverride("columnStart") || hasViewportOverride("columnSpan")) {
if (columnStart && columnSpan) {
declarations["grid-column"] = `${columnStart} / span ${columnSpan}`;
} else if (columnStart) {
declarations["grid-column"] = `${columnStart}`;
} else if (columnSpan) {
declarations["grid-column"] = `span ${columnSpan}`;
}
}
if (!hasViewportOverrides || hasViewportOverride("rowStart") || hasViewportOverride("rowSpan")) {
if (rowStart && rowSpan) {
declarations["grid-row"] = `${rowStart} / span ${rowSpan}`;
} else if (rowStart) {
declarations["grid-row"] = `${rowStart}`;
} else if (rowSpan) {
declarations["grid-row"] = `span ${rowSpan}`;
}
}
if (Object.keys(declarations).length) {
rules.push({ selector: selector3, declarations });
}
if (includeContainerQuery && !hasViewportOverrides) {
if ((columnSpan || columnStart) && (minimumColumnWidth || !columnCount)) {
let parentColumnValue = parseFloat(minimumColumnWidth);
if (isNaN(parentColumnValue)) {
parentColumnValue = 12;
}
let parentColumnUnit = minimumColumnWidth?.replace(
parentColumnValue,
""
);
if (!["px", "rem", "em"].includes(parentColumnUnit)) {
parentColumnUnit = "rem";
}
let numColsToBreakAt = 2;
if (columnSpan && columnStart) {
numColsToBreakAt = columnSpan + columnStart - 1;
} else if (columnSpan) {
numColsToBreakAt = columnSpan;
} else {
numColsToBreakAt = columnStart;
}
const defaultGapValue = parentColumnUnit === "px" ? 24 : 1.5;
const containerQueryValue = numColsToBreakAt * parentColumnValue + (numColsToBreakAt - 1) * defaultGapValue;
const minimumContainerQueryValue = parentColumnValue * 2 + defaultGapValue - 1;
const gridColumnValue = columnSpan && columnSpan > 1 ? "1/-1" : "auto";
rules.push({
rulesGroup: `@container (max-width: ${Math.max(
containerQueryValue,
minimumContainerQueryValue
)}${parentColumnUnit})`,
selector: selector3,
declarations: {
"grid-column": gridColumnValue,
"grid-row": "auto"
}
});
}
}
return rules;
}
function getChildLayoutStyles({
selector: selector3,
layout = {},
parentLayout = {},
includeContainerQuery = true
}) {
return getChildLayoutStyleRules({
selector: selector3,
layout,
parentLayout,
includeContainerQuery
}).map((rule) => {
const serializedRule = serializeRule(rule);
return rule.rulesGroup ? `${rule.rulesGroup} {
${serializedRule}
}` : serializedRule;
}).join("");
}
function getResponsiveChildLayoutStyles({
style = {},
selector: selector3,
parentLayout = {},
viewportSettings
}) {
const baseLayout = style?.layout ?? {};
return Object.entries(getResponsiveMediaQueries4(viewportSettings)).map(([viewport, mediaQuery]) => {
const viewportLayout = getStyleForState(style, {
viewport,
pseudo: DEFAULT_BLOCK_STYLE_STATE2.pseudo
})?.layout;
if (!viewportLayout || !Object.keys(viewportLayout).length) {
return "";
}
const viewportRules = getChildLayoutStyleRules({
selector: selector3,
layout: baseLayout,
viewportOverrides: viewportLayout,
parentLayout,
includeContainerQuery: false
});
const css = viewportRules.map(serializeRule).join("");
return css ? `${mediaQuery}{${css}}` : "";
}).filter(Boolean).join("");
}
function useBlockPropsChildLayoutStyles({ style }) {
const { shouldRenderChildLayoutStyles, viewportSettings } = (0, import_data193.useSelect)(
(select3) => {
const settings2 = select3(store).getSettings();
return {
shouldRenderChildLayoutStyles: !settings2.disableLayoutStyles,
viewportSettings: settings2?.__experimentalFeatures?.viewport
};
}
);
const layout = style?.layout ?? {};
const { columnStart, rowStart, columnSpan, rowSpan } = layout;
const parentLayout = useLayout() || {};
const id = (0, import_compose113.useInstanceId)(LAYOUT_CHILD_BLOCK_PROPS_REFERENCE);
const selector3 = `.wp-container-content-${id}`;
if (true) {
if (columnStart && typeof columnStart !== "number") {
throw new Error("columnStart must be a number");
}
if (rowStart && typeof rowStart !== "number") {
throw new Error("rowStart must be a number");
}
if (columnSpan && typeof columnSpan !== "number") {
throw new Error("columnSpan must be a number");
}
if (rowSpan && typeof rowSpan !== "number") {
throw new Error("rowSpan must be a number");
}
}
let css = "";
if (shouldRenderChildLayoutStyles) {
css = [
getChildLayoutStyles({
selector: selector3,
layout,
parentLayout
}),
getResponsiveChildLayoutStyles({
style,
selector: selector3,
parentLayout,
viewportSettings
})
].join("");
}
useStyleOverride({ css });
if (!css) {
return;
}
return { className: `wp-container-content-${id}` };
}
function ChildLayoutControlsPure({ clientId, style, setAttributes }) {
const parentLayout = useLayout() || {};
const {
type: parentLayoutType = "default",
allowSizingOnChildren = false,
isManualPlacement
} = parentLayout;
if (parentLayoutType !== "grid") {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime525.jsx)(
GridTools,
{
clientId,
style,
setAttributes,
allowSizingOnChildren,
isManualPlacement,
parentLayout
}
);
}
function GridTools({
clientId,
style,
setAttributes,
allowSizingOnChildren,
isManualPlacement,
parentLayout
}) {
const {
rootClientId,
isVisible,
parentBlockVisibility,
blockBlockVisibility,
deviceType,
viewportSettings,
isChildBlockAGrid
} = (0, import_data193.useSelect)(
(select3) => {
const {
getBlockRootClientId: getBlockRootClientId2,
getBlockEditingMode: getBlockEditingMode2,
getTemplateLock: getTemplateLock2,
getBlockAttributes: getBlockAttributes3,
getSettings: getSettings7
} = select3(store);
const _rootClientId = getBlockRootClientId2(clientId);
if (getTemplateLock2(_rootClientId) || getBlockEditingMode2(_rootClientId) !== "default") {
return {
rootClientId: _rootClientId,
isVisible: false
};
}
const parentAttributes = getBlockAttributes3(_rootClientId);
const blockAttributes = getBlockAttributes3(clientId);
const settings2 = getSettings7();
const currentDeviceType = settings2?.[deviceTypeKey]?.toLowerCase() || BLOCK_VISIBILITY_VIEWPORTS.desktop.key;
return {
rootClientId: _rootClientId,
isVisible: true,
parentBlockVisibility: parentAttributes?.metadata?.blockVisibility,
blockBlockVisibility: blockAttributes?.metadata?.blockVisibility,
deviceType: currentDeviceType,
viewportSettings: settings2?.__experimentalFeatures?.viewport,
// Check if the selected child block is itself a grid.
isChildBlockAGrid: blockAttributes?.layout?.type === "grid"
};
},
[clientId]
);
const blockElement = useBlockElement(clientId);
const rawCanvasView = blockElement?.ownerDocument?.defaultView;
const canvasView = rawCanvasView === null ? void 0 : rawCanvasView;
const {
isBlockCurrentlyHidden: isParentBlockCurrentlyHidden,
currentViewport
} = useBlockVisibility({
blockVisibility: parentBlockVisibility,
deviceType,
view: canvasView,
viewportSettings
});
const isAnyAncestorHidden = (0, import_data193.useSelect)(
(select3) => {
if (!rootClientId) {
return false;
}
const { isBlockParentHiddenAtViewport: isBlockParentHiddenAtViewport2 } = unlock(
select3(store)
);
return isBlockParentHiddenAtViewport2(
rootClientId,
currentViewport
);
},
[rootClientId, currentViewport]
);
const { isBlockCurrentlyHidden: isBlockItselfCurrentlyHidden } = useBlockVisibility({
blockVisibility: blockBlockVisibility,
deviceType,
view: canvasView,
viewportSettings
});
const [resizerBounds, setResizerBounds] = (0, import_element324.useState)();
const childGridClientId = isChildBlockAGrid ? clientId : void 0;
if (!isVisible || isParentBlockCurrentlyHidden || isAnyAncestorHidden) {
return null;
}
const showResizer = allowSizingOnChildren && !isBlockItselfCurrentlyHidden;
function updateLayout(layout) {
setAttributes({
style: {
...style,
layout: {
...style?.layout,
...layout
}
}
});
}
return /* @__PURE__ */ (0, import_jsx_runtime525.jsxs)(import_jsx_runtime525.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime525.jsx)(
GridVisualizer,
{
clientId: rootClientId,
contentRef: setResizerBounds,
parentLayout,
childGridClientId
}
),
showResizer && /* @__PURE__ */ (0, import_jsx_runtime525.jsx)(
GridItemResizer,
{
clientId,
bounds: resizerBounds,
onChange: updateLayout,
parentLayout
}
),
isManualPlacement && window.__experimentalEnableGridInteractivity && /* @__PURE__ */ (0, import_jsx_runtime525.jsx)(
GridItemMovers,
{
layout: style?.layout,
parentLayout,
onChange: updateLayout,
gridClientId: rootClientId,
blockClientId: clientId
}
)
] });
}
var layout_child_default = {
useBlockProps: useBlockPropsChildLayoutStyles,
edit: ChildLayoutControlsPure,
attributeKeys: ["style"],
hasSupport() {
return true;
}
};
// packages/block-editor/build-module/hooks/metadata.mjs
var import_hooks32 = __toESM(require_hooks(), 1);
var import_blocks122 = __toESM(require_blocks(), 1);
var META_ATTRIBUTE_NAME = "metadata";
function addMetaAttribute(blockTypeSettings) {
if (blockTypeSettings?.attributes?.[META_ATTRIBUTE_NAME]?.type) {
return blockTypeSettings;
}
blockTypeSettings.attributes = {
...blockTypeSettings.attributes,
[META_ATTRIBUTE_NAME]: {
type: "object"
}
};
return blockTypeSettings;
}
function addTransforms5(result, source, index2, results) {
if (results.length === 1 && result.innerBlocks.length === source.length) {
return result;
}
if (results.length === 1 && source.length > 1 || results.length > 1 && source.length === 1) {
return result;
}
if (results.length > 1 && source.length > 1 && results.length !== source.length) {
return result;
}
const sourceMetadata = source[index2]?.attributes?.metadata;
if (!sourceMetadata) {
return result;
}
const preservedMetadata = {};
if (sourceMetadata.noteId && !result.attributes?.metadata?.noteId) {
preservedMetadata.noteId = sourceMetadata.noteId;
}
if (sourceMetadata.name && !result.attributes?.metadata?.name && (0, import_blocks122.hasBlockSupport)(result.name, "renaming", true)) {
preservedMetadata.name = sourceMetadata.name;
}
if (sourceMetadata.blockVisibility !== void 0 && !result.attributes?.metadata?.blockVisibility && (0, import_blocks122.hasBlockSupport)(result.name, "visibility", true)) {
preservedMetadata.blockVisibility = sourceMetadata.blockVisibility;
}
if (Object.keys(preservedMetadata).length > 0) {
return {
...result,
attributes: {
...result.attributes,
metadata: {
...result.attributes.metadata,
...preservedMetadata
}
}
};
}
return result;
}
(0, import_hooks32.addFilter)(
"blocks.registerBlockType",
"core/metadata/addMetaAttribute",
addMetaAttribute
);
(0, import_hooks32.addFilter)(
"blocks.switchToBlockType.transformedBlock",
"core/metadata/addTransforms",
addTransforms5
);
// packages/block-editor/build-module/hooks/block-hooks.mjs
var import_i18n247 = __toESM(require_i18n(), 1);
var import_element325 = __toESM(require_element(), 1);
var import_components271 = __toESM(require_components(), 1);
var import_blocks123 = __toESM(require_blocks(), 1);
var import_data194 = __toESM(require_data(), 1);
var import_jsx_runtime526 = __toESM(require_jsx_runtime(), 1);
var EMPTY_OBJECT5 = {};
function BlockHooksControlPure({
name,
clientId,
metadata: { ignoredHookedBlocks = [] } = {}
}) {
const blockTypes = (0, import_data194.useSelect)(
(select3) => select3(import_blocks123.store).getBlockTypes(),
[]
);
const hookedBlocksForCurrentBlock = (0, import_element325.useMemo)(
() => blockTypes?.filter(
({ name: blockName, blockHooks }) => blockHooks && name in blockHooks || ignoredHookedBlocks.includes(blockName)
),
[blockTypes, name, ignoredHookedBlocks]
);
const hookedBlockClientIds = (0, import_data194.useSelect)(
(select3) => {
const { getBlocks: getBlocks2, getBlockRootClientId: getBlockRootClientId22, getGlobalBlockCount: getGlobalBlockCount2 } = select3(store);
const rootClientId = getBlockRootClientId22(clientId);
const _hookedBlockClientIds = hookedBlocksForCurrentBlock.reduce(
(clientIds, block) => {
if (getGlobalBlockCount2(block.name) === 0) {
return clientIds;
}
const relativePosition = block?.blockHooks?.[name];
let candidates;
switch (relativePosition) {
case "before":
case "after":
candidates = getBlocks2(rootClientId);
break;
case "first_child":
case "last_child":
candidates = getBlocks2(clientId);
break;
case void 0:
candidates = [
...getBlocks2(rootClientId),
...getBlocks2(clientId)
];
break;
}
const hookedBlock = candidates?.find(
(candidate) => candidate.name === block.name
);
if (hookedBlock) {
return {
...clientIds,
[block.name]: hookedBlock.clientId
};
}
return clientIds;
},
{}
);
if (Object.values(_hookedBlockClientIds).length > 0) {
return _hookedBlockClientIds;
}
return EMPTY_OBJECT5;
},
[hookedBlocksForCurrentBlock, name, clientId]
);
const { getBlockIndex: getBlockIndex2, getBlockCount: getBlockCount2, getBlockRootClientId: getBlockRootClientId2 } = (0, import_data194.useSelect)(store);
const { insertBlock: insertBlock2, removeBlock: removeBlock2 } = (0, import_data194.useDispatch)(store);
if (!hookedBlocksForCurrentBlock.length) {
return null;
}
const groupedHookedBlocks = hookedBlocksForCurrentBlock.reduce(
(groups3, block) => {
const [namespace] = block.name.split("/");
if (!groups3[namespace]) {
groups3[namespace] = [];
}
groups3[namespace].push(block);
return groups3;
},
{}
);
const insertBlockIntoDesignatedLocation = (block, relativePosition) => {
const blockIndex = getBlockIndex2(clientId);
const innerBlocksLength = getBlockCount2(clientId);
const rootClientId = getBlockRootClientId2(clientId);
switch (relativePosition) {
case "before":
case "after":
insertBlock2(
block,
relativePosition === "after" ? blockIndex + 1 : blockIndex,
rootClientId,
// Insert as a child of the current block's parent
false
);
break;
case "first_child":
case "last_child":
insertBlock2(
block,
// TODO: It'd be great if insertBlock() would accept negative indices for insertion.
relativePosition === "first_child" ? 0 : innerBlocksLength,
clientId,
// Insert as a child of the current block.
false
);
break;
case void 0:
insertBlock2(
block,
blockIndex + 1,
rootClientId,
// Insert as a child of the current block's parent
false
);
break;
}
};
return /* @__PURE__ */ (0, import_jsx_runtime526.jsx)(inspector_controls_default, { children: /* @__PURE__ */ (0, import_jsx_runtime526.jsxs)(
import_components271.PanelBody,
{
className: "block-editor-hooks__block-hooks",
title: (0, import_i18n247.__)("Plugins"),
initialOpen: true,
children: [
/* @__PURE__ */ (0, import_jsx_runtime526.jsx)("p", { className: "block-editor-hooks__block-hooks-helptext", children: (0, import_i18n247.__)(
"Manage the inclusion of blocks added automatically by plugins."
) }),
Object.keys(groupedHookedBlocks).map((vendor) => {
return /* @__PURE__ */ (0, import_jsx_runtime526.jsxs)(import_element325.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime526.jsx)("h3", { children: vendor }),
groupedHookedBlocks[vendor].map((block) => {
const checked = block.name in hookedBlockClientIds;
return /* @__PURE__ */ (0, import_jsx_runtime526.jsx)(
import_components271.ToggleControl,
{
checked,
label: block.title,
onChange: () => {
if (!checked) {
const relativePosition = block.blockHooks[name];
insertBlockIntoDesignatedLocation(
(0, import_blocks123.createBlock)(block.name),
relativePosition
);
return;
}
removeBlock2(
hookedBlockClientIds[block.name],
false
);
}
},
block.title
);
})
] }, vendor);
})
]
}
) });
}
var block_hooks_default = {
edit: BlockHooksControlPure,
attributeKeys: ["metadata"],
hasSupport() {
return true;
}
};
// packages/block-editor/build-module/hooks/block-bindings.mjs
var import_i18n248 = __toESM(require_i18n(), 1);
var import_blocks124 = __toESM(require_blocks(), 1);
var import_components273 = __toESM(require_components(), 1);
var import_data195 = __toESM(require_data(), 1);
var import_element326 = __toESM(require_element(), 1);
var import_compose114 = __toESM(require_compose(), 1);
var import_jsx_runtime527 = __toESM(require_jsx_runtime(), 1);
var useToolsPanelDropdownMenuProps2 = () => {
const isMobile = (0, import_compose114.useViewportMatch)("medium", "<");
return !isMobile ? {
popoverProps: {
placement: "left-start",
// For non-mobile, inner sidebar width (248px) - button width (24px) - border (1px) + padding (16px) + spacing (20px)
offset: 259
}
} : {};
};
var BlockBindingsPanel = ({ name: blockName, metadata }) => {
const blockContext = (0, import_element326.useContext)(block_context_default);
const { removeAllBlockBindings } = useBlockBindingsUtils();
const dropdownMenuProps = useToolsPanelDropdownMenuProps2();
const { bindableAttributes, hasCompatibleFields } = (0, import_data195.useSelect)(
(select3) => {
const { __experimentalBlockBindingsSupportedAttributes } = select3(store).getSettings();
const {
getAllBlockBindingsSources,
getBlockBindingsSourceFieldsList
} = unlock(select3(import_blocks124.store));
return {
bindableAttributes: __experimentalBlockBindingsSupportedAttributes?.[blockName],
hasCompatibleFields: Object.values(
getAllBlockBindingsSources()
).some(
(source) => getBlockBindingsSourceFieldsList(source, blockContext)?.length > 0
)
};
},
[blockName, blockContext]
);
if (!bindableAttributes || bindableAttributes.length === 0) {
return null;
}
const { bindings } = metadata || {};
if (bindings === void 0 && !hasCompatibleFields) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime527.jsx)(inspector_controls_default, { group: "bindings", children: /* @__PURE__ */ (0, import_jsx_runtime527.jsxs)(
import_components273.__experimentalToolsPanel,
{
label: (0, import_i18n248.__)("Attributes"),
resetAll: () => {
removeAllBlockBindings();
},
dropdownMenuProps,
className: "block-editor-bindings__panel",
children: [
/* @__PURE__ */ (0, import_jsx_runtime527.jsx)(import_components273.__experimentalItemGroup, { isBordered: true, isSeparated: true, children: bindableAttributes.map((attribute) => /* @__PURE__ */ (0, import_jsx_runtime527.jsx)(
BlockBindingsAttributeControl,
{
attribute,
blockName,
binding: bindings?.[attribute]
},
attribute
)) }),
/* @__PURE__ */ (0, import_jsx_runtime527.jsx)(import_components273.__experimentalText, { as: "div", variant: "muted", children: /* @__PURE__ */ (0, import_jsx_runtime527.jsx)("p", { children: (0, import_i18n248.__)(
"Attributes connected to custom fields or other dynamic data."
) }) })
]
}
) });
};
var block_bindings_default = {
edit: BlockBindingsPanel,
attributeKeys: ["metadata"],
hasSupport(name) {
return ![
"core/post-date",
"core/navigation-link",
"core/navigation-submenu"
].includes(name);
}
};
// packages/block-editor/build-module/hooks/list-view.mjs
var import_i18n249 = __toESM(require_i18n(), 1);
var import_components274 = __toESM(require_components(), 1);
var import_data197 = __toESM(require_data(), 1);
var import_blocks125 = __toESM(require_blocks(), 1);
var import_element327 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/use-list-view-panel-state/index.mjs
var import_data196 = __toESM(require_data(), 1);
function useListViewPanelState(clientId) {
const { isOpened, expandRevision } = (0, import_data196.useSelect)(
(select3) => {
const { isListViewPanelOpened: isListViewPanelOpened2, getListViewExpandRevision: getListViewExpandRevision2 } = unlock(
select3(store)
);
return {
isOpened: isListViewPanelOpened2(clientId),
expandRevision: getListViewExpandRevision2()
};
},
[clientId]
);
const { __unstableToggleListViewPanel: toggleListViewPanel } = (0, import_data196.useDispatch)(store);
const handleToggle = (opened) => {
toggleListViewPanel(clientId, opened);
};
return {
isOpened,
expandRevision,
handleToggle
};
}
// packages/block-editor/build-module/hooks/list-view.mjs
var import_jsx_runtime528 = __toESM(require_jsx_runtime(), 1);
var LIST_VIEW_SUPPORT_KEY = "listView";
function hasListViewSupport(nameOrType) {
return (0, import_blocks125.hasBlockSupport)(nameOrType, LIST_VIEW_SUPPORT_KEY);
}
function ListViewPanel({ clientId, name }) {
const { isSelectionWithinCurrentSection } = (0, import_element327.useContext)(PrivateBlockContext);
const { isOpened, expandRevision, handleToggle } = useListViewPanelState(clientId);
const { openListViewContentPanel: openListViewContentPanel2 } = unlock(
(0, import_data197.useDispatch)(store)
);
const { isEnabled, hasChildren, isNestedListView } = (0, import_data197.useSelect)(
(select3) => {
const {
getBlockCount: getBlockCount2,
getBlockParents: getBlockParents2,
shouldRenderBlockListView: shouldRenderBlockListView2
} = unlock(select3(store));
const parents = getBlockParents2(clientId, false);
const _isNestedListView = parents.find(
(parentId) => shouldRenderBlockListView2(parentId)
);
return {
isEnabled: shouldRenderBlockListView2(clientId),
hasChildren: !!getBlockCount2(clientId),
isNestedListView: _isNestedListView
};
},
[clientId]
);
const blockType = (0, import_blocks125.getBlockType)(name);
const title = blockType?.title || name;
if (!isEnabled || isNestedListView) {
return null;
}
const showBlockTitle = isSelectionWithinCurrentSection;
return /* @__PURE__ */ (0, import_jsx_runtime528.jsx)(InspectorControlsFill, { group: "list", children: /* @__PURE__ */ (0, import_jsx_runtime528.jsxs)(
import_components274.PanelBody,
{
title: showBlockTitle ? title : void 0,
opened: isOpened,
onToggle: handleToggle,
children: [
!hasChildren && /* @__PURE__ */ (0, import_jsx_runtime528.jsx)("p", { className: "block-editor-block-inspector__no-blocks", children: (0, import_i18n249.__)("No items yet.") }),
/* @__PURE__ */ (0, import_jsx_runtime528.jsx)(
PrivateListView,
{
rootClientId: clientId,
isExpanded: true,
description: title,
showAppender: true,
onSelect: openListViewContentPanel2
},
`${clientId}-${expandRevision}`
)
]
}
) });
}
var list_view_default3 = {
edit: ListViewPanel,
hasSupport: hasListViewSupport,
attributeKeys: [],
supportsPatternEditing: true
};
// packages/block-editor/build-module/hooks/block-renaming.mjs
var import_hooks33 = __toESM(require_hooks(), 1);
var import_blocks126 = __toESM(require_blocks(), 1);
function addLabelCallback(settings2) {
if (settings2.__experimentalLabel) {
return settings2;
}
const supportsBlockNaming = (0, import_blocks126.hasBlockSupport)(
settings2,
"renaming",
true
// default value
);
if (supportsBlockNaming) {
settings2.__experimentalLabel = (attributes, { context }) => {
const { metadata } = attributes;
if ((context === "list-view" || context === "breadcrumb") && metadata?.name) {
return metadata.name;
}
};
}
return settings2;
}
(0, import_hooks33.addFilter)(
"blocks.registerBlockType",
"core/metadata/addLabelCallback",
addLabelCallback
);
// packages/block-editor/build-module/hooks/grid-visualizer.mjs
var import_compose115 = __toESM(require_compose(), 1);
var import_hooks34 = __toESM(require_hooks(), 1);
var import_data198 = __toESM(require_data(), 1);
var import_jsx_runtime529 = __toESM(require_jsx_runtime(), 1);
function GridLayoutSync(props) {
useGridLayoutSync(props);
}
function GridTools2({ clientId, layout }) {
const { isVisible, blockVisibility: blockVisibility2, deviceType, viewportSettings } = (0, import_data198.useSelect)(
(select3) => {
const {
isBlockSelected: isBlockSelected2,
hasSelectedInnerBlock: hasSelectedInnerBlock2,
isDraggingBlocks: isDraggingBlocks2,
getTemplateLock: getTemplateLock2,
getBlockEditingMode: getBlockEditingMode2,
getBlockAttributes: getBlockAttributes3,
getSettings: getSettings7
} = select3(store);
if (!isDraggingBlocks2() && !isBlockSelected2(clientId) || getTemplateLock2(clientId) || getBlockEditingMode2(clientId) !== "default" || hasSelectedInnerBlock2(clientId)) {
return { isVisible: false };
}
const attributes = getBlockAttributes3(clientId);
const settings2 = getSettings7();
const currentDeviceType = settings2?.[deviceTypeKey]?.toLowerCase() || BLOCK_VISIBILITY_VIEWPORTS.desktop.key;
return {
isVisible: true,
blockVisibility: attributes?.metadata?.blockVisibility,
deviceType: currentDeviceType,
viewportSettings: settings2?.__experimentalFeatures?.viewport
};
},
[clientId]
);
const blockElement = useBlockElement(clientId);
const rawCanvasView = blockElement?.ownerDocument?.defaultView;
const canvasView = rawCanvasView === null ? void 0 : rawCanvasView;
const { isBlockCurrentlyHidden, currentViewport } = useBlockVisibility({
blockVisibility: blockVisibility2,
deviceType,
view: canvasView,
viewportSettings
});
const isAnyAncestorHidden = (0, import_data198.useSelect)(
(select3) => {
if (!isVisible) {
return false;
}
const { isBlockParentHiddenAtViewport: isBlockParentHiddenAtViewport2 } = unlock(
select3(store)
);
return isBlockParentHiddenAtViewport2(clientId, currentViewport);
},
[clientId, currentViewport, isVisible]
);
return /* @__PURE__ */ (0, import_jsx_runtime529.jsxs)(import_jsx_runtime529.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime529.jsx)(GridLayoutSync, { clientId }),
isVisible && !isBlockCurrentlyHidden && !isAnyAncestorHidden && /* @__PURE__ */ (0, import_jsx_runtime529.jsx)(
GridVisualizer,
{
clientId,
parentLayout: layout
}
)
] });
}
var addGridVisualizerToBlockEdit = (0, import_compose115.createHigherOrderComponent)(
(BlockEdit2) => function AddGridVisualizerToBlockEdit(props) {
if (props.attributes.layout?.type !== "grid") {
return /* @__PURE__ */ (0, import_jsx_runtime529.jsx)(BlockEdit2, { ...props }, "edit");
}
return /* @__PURE__ */ (0, import_jsx_runtime529.jsxs)(import_jsx_runtime529.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime529.jsx)(
GridTools2,
{
clientId: props.clientId,
layout: props.attributes.layout
}
),
/* @__PURE__ */ (0, import_jsx_runtime529.jsx)(BlockEdit2, { ...props }, "edit")
] });
},
"addGridVisualizerToBlockEdit"
);
(0, import_hooks34.addFilter)(
"editor.BlockEdit",
"core/editor/grid-visualizer",
addGridVisualizerToBlockEdit
);
// packages/block-editor/build-module/hooks/auto-inspector-controls.mjs
var import_blocks127 = __toESM(require_blocks(), 1);
var import_components275 = __toESM(require_components(), 1);
var import_data199 = __toESM(require_data(), 1);
var import_element328 = __toESM(require_element(), 1);
var import_i18n250 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/hooks/generate-fields-from-attributes.mjs
function generateFieldsFromAttributes(attributes) {
const fields = [];
const fieldIds = [];
Object.entries(attributes).forEach(([name, def]) => {
if (!def.autoGenerateControl) {
return;
}
const field = createFieldFromAttribute(name, def);
if (field) {
fields.push(field);
fieldIds.push(name);
}
});
return {
fields,
form: { fields: fieldIds }
};
}
function createFieldFromAttribute(name, def) {
const type = def.type;
const field = {
id: name,
label: def.label || name,
// Only 'string' needs mapping to 'text'; others are 1:1 with DataForm types.
// This mapping will be unnecessary once #74105 lands.
type: type === "string" ? "text" : type
};
if (def.enum && Array.isArray(def.enum)) {
field.elements = def.enum.map((value) => ({
value,
label: String(value)
}));
}
return field;
}
// packages/block-editor/build-module/hooks/auto-inspector-controls.mjs
var import_jsx_runtime530 = __toESM(require_jsx_runtime(), 1);
function hasAutoGenerateControl(blockTypeAttributes) {
if (!blockTypeAttributes) {
return false;
}
return Object.values(blockTypeAttributes).some(
(attr2) => attr2?.autoGenerateControl
);
}
function AutoRegisterControls({ name, clientId, setAttributes }) {
const blockEditingMode = useBlockEditingMode();
const blockContext = (0, import_element328.useContext)(block_context_default);
const attributes = (0, import_data199.useSelect)(
(select3) => {
const _attributes = select3(store).getBlockAttributes(clientId);
if (!_attributes?.metadata?.bindings) {
return _attributes;
}
const { getBlockBindingsSource: getBlockBindingsSource4 } = unlock(select3(import_blocks127.store));
return Object.entries(_attributes.metadata.bindings).reduce(
(acc, [attribute, binding]) => {
const source = getBlockBindingsSource4(binding.source);
if (!source) {
return acc;
}
const values = source.getValues({
select: select3,
context: blockContext,
bindings: { [attribute]: binding }
});
return { ...acc, ...values };
},
_attributes
);
},
[blockContext, clientId]
);
const blockType = (0, import_blocks127.getBlockType)(name);
const { fields, form } = (0, import_element328.useMemo)(() => {
if (!blockType?.attributes) {
return { fields: [], form: { fields: [] } };
}
return generateFieldsFromAttributes(blockType.attributes);
}, [blockType?.attributes]);
if (blockEditingMode !== "default") {
return null;
}
if (!fields || fields.length === 0) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime530.jsx)(inspector_controls_default, { children: /* @__PURE__ */ (0, import_jsx_runtime530.jsx)(import_components275.PanelBody, { title: (0, import_i18n250.__)("Settings"), children: /* @__PURE__ */ (0, import_jsx_runtime530.jsx)(
DataForm,
{
data: attributes,
fields,
form,
onChange: setAttributes
}
) }) });
}
var auto_inspector_controls_default = {
edit: AutoRegisterControls,
attributeKeys: [],
hasSupport(name) {
const blockType = (0, import_blocks127.getBlockType)(name);
return hasAutoGenerateControl(blockType?.attributes);
}
};
// packages/block-editor/build-module/hooks/use-dimensions-props.mjs
function getDimensionsClassesAndStyles(attributes) {
const { style } = attributes;
const dimensionsStyles = style?.dimensions || {};
const styleProp = getInlineStyles({ dimensions: dimensionsStyles });
return {
className: dimensionsStyles.aspectRatio ? "has-aspect-ratio" : void 0,
style: styleProp
};
}
// packages/block-editor/build-module/hooks/use-border-props.mjs
function getBorderClassesAndStyles(attributes) {
const border = attributes.style?.border || {};
const className = getBorderClasses(attributes);
return {
className: className || void 0,
style: getInlineStyles({ border })
};
}
function useBorderProps(attributes) {
const { colors: colors2 } = useMultipleOriginColorsAndGradients();
const borderProps = getBorderClassesAndStyles(attributes);
const { borderColor } = attributes;
if (borderColor) {
const borderColorObject = getMultiOriginColor({
colors: colors2,
namedColor: borderColor
});
borderProps.style.borderColor = borderColorObject.color;
}
return borderProps;
}
// packages/block-editor/build-module/hooks/use-shadow-props.mjs
function getShadowClassesAndStyles(attributes) {
const shadow = attributes.style?.shadow || "";
return {
style: getInlineStyles({ shadow })
};
}
// packages/block-editor/build-module/hooks/use-color-props.mjs
var import_element329 = __toESM(require_element(), 1);
function getColorClassesAndStyles(attributes) {
const { backgroundColor, textColor, gradient, style } = attributes;
const backgroundClass = getColorClassName(
"background-color",
backgroundColor
);
const textClass = getColorClassName("color", textColor);
const gradientClass = __experimentalGetGradientClass(gradient);
const hasGradient = gradientClass || style?.color?.gradient;
const className = clsx_default(textClass, gradientClass, {
// Don't apply the background class if there's a gradient.
[backgroundClass]: !hasGradient && !!backgroundClass,
"has-text-color": textColor || style?.color?.text,
"has-background": backgroundColor || style?.color?.background || gradient || style?.color?.gradient,
"has-link-color": style?.elements?.link?.color
});
const colorStyles = style?.color || {};
const styleProp = getInlineStyles({ color: colorStyles });
return {
className: className || void 0,
style: styleProp
};
}
function useColorProps(attributes) {
const { backgroundColor, textColor, gradient } = attributes;
const [
userPalette,
themePalette,
defaultPalette,
userGradients,
themeGradients,
defaultGradients
] = useSettings(
"color.palette.custom",
"color.palette.theme",
"color.palette.default",
"color.gradients.custom",
"color.gradients.theme",
"color.gradients.default"
);
const colors2 = (0, import_element329.useMemo)(
() => [
...userPalette || [],
...themePalette || [],
...defaultPalette || []
],
[userPalette, themePalette, defaultPalette]
);
const gradients = (0, import_element329.useMemo)(
() => [
...userGradients || [],
...themeGradients || [],
...defaultGradients || []
],
[userGradients, themeGradients, defaultGradients]
);
const colorProps = getColorClassesAndStyles(attributes);
if (backgroundColor) {
const backgroundColorObject = getColorObjectByAttributeValues(
colors2,
backgroundColor
);
colorProps.style.backgroundColor = backgroundColorObject.color;
}
if (gradient) {
colorProps.style.background = getGradientValueBySlug(
gradients,
gradient
);
}
if (textColor) {
const textColorObject = getColorObjectByAttributeValues(
colors2,
textColor
);
colorProps.style.color = textColorObject.color;
}
return colorProps;
}
// packages/block-editor/build-module/hooks/use-spacing-props.mjs
function getSpacingClassesAndStyles(attributes) {
const { style } = attributes;
const spacingStyles = style?.spacing || {};
const styleProp = getInlineStyles({ spacing: spacingStyles });
return {
style: styleProp
};
}
// packages/block-editor/build-module/hooks/use-typography-props.mjs
var import_components276 = __toESM(require_components(), 1);
var { kebabCase: kebabCase7 } = unlock(import_components276.privateApis);
function getTypographyClassesAndStyles(attributes, settings2) {
let typographyStyles = attributes?.style?.typography || {};
typographyStyles = {
...typographyStyles,
fontSize: getTypographyFontSizeValue(
{ size: attributes?.style?.typography?.fontSize },
settings2
)
};
const style = getInlineStyles({ typography: typographyStyles });
const fontFamilyClassName = !!attributes?.fontFamily ? `has-${kebabCase7(attributes.fontFamily)}-font-family` : "";
const textAlignClassName = !!attributes?.style?.typography?.textAlign ? `has-text-align-${attributes?.style?.typography?.textAlign}` : "";
const className = clsx_default(
fontFamilyClassName,
textAlignClassName,
getFontSizeClass(attributes?.fontSize)
);
return {
className,
style
};
}
// packages/block-editor/build-module/hooks/use-cached-truthy.mjs
var import_element330 = __toESM(require_element(), 1);
function useCachedTruthy(value) {
const [cachedValue, setCachedValue] = (0, import_element330.useState)(value);
(0, import_element330.useEffect)(() => {
if (value) {
setCachedValue(value);
}
}, [value]);
return cachedValue;
}
// packages/block-editor/build-module/hooks/index.mjs
createBlockEditFilter(
[
align_default,
text_align_default,
anchor_default,
custom_class_name_default,
style_default16,
custom_css_default,
duotone_default,
fit_text_default,
position_default,
layout_default2,
block_hooks_default,
block_bindings_default,
layout_child_default,
allowed_blocks_default,
block_fields_default,
list_view_default3,
auto_inspector_controls_default
].filter(Boolean)
);
createBlockListBlockFilter([
align_default,
text_align_default,
background_default,
style_default16,
color_default,
dimensions_default,
duotone_default,
font_family_default,
font_size_default,
fit_text_default,
border_default,
custom_css_default,
position_default,
block_style_variation_default,
layout_child_default
]);
createBlockSaveFilter([
align_default,
text_align_default,
anchor_default,
aria_label_default,
custom_class_name_default,
border_default,
custom_css_default,
fit_text_default,
color_default,
style_default16,
font_family_default,
font_size_default
]);
// packages/block-editor/build-module/elements/index.mjs
var ELEMENT_CLASS_NAMES2 = {
button: "wp-element-button",
caption: "wp-element-caption"
};
var __experimentalGetElementClassName = (element) => {
return ELEMENT_CLASS_NAMES2[element] ? ELEMENT_CLASS_NAMES2[element] : "";
};
// packages/block-editor/build-module/utils/get-px-from-css-unit.mjs
var get_px_from_css_unit_default = () => "";
// packages/block-editor/build-module/components/rich-text/get-rich-text-values.mjs
var import_element331 = __toESM(require_element(), 1);
var import_blocks128 = __toESM(require_blocks(), 1);
var import_rich_text26 = __toESM(require_rich_text(), 1);
var import_jsx_runtime531 = __toESM(require_jsx_runtime(), 1);
function addValuesForElement(element, values, innerBlocks) {
if (null === element || void 0 === element || false === element) {
return;
}
if (Array.isArray(element)) {
return addValuesForElements(element, values, innerBlocks);
}
switch (typeof element) {
case "string":
case "number":
return;
}
const { type, props } = element;
switch (type) {
case import_element331.StrictMode:
case import_element331.Fragment:
return addValuesForElements(props.children, values, innerBlocks);
case import_element331.RawHTML:
return;
case inner_blocks_default.Content:
return addValuesForBlocks(values, innerBlocks);
case Content3:
values.push(props.value);
return;
}
switch (typeof type) {
case "string":
if (typeof props.children !== "undefined") {
return addValuesForElements(
props.children,
values,
innerBlocks
);
}
return;
case "function":
const el = type.prototype && typeof type.prototype.render === "function" ? new type(props).render() : type(props);
return addValuesForElement(el, values, innerBlocks);
}
}
function addValuesForElements(children, ...args) {
children = Array.isArray(children) ? children : [children];
for (let i2 = 0; i2 < children.length; i2++) {
addValuesForElement(children[i2], ...args);
}
}
function addValuesForBlocks(values, blocks2) {
for (let i2 = 0; i2 < blocks2.length; i2++) {
const { name, attributes, innerBlocks } = blocks2[i2];
const saveElement = (0, import_blocks128.getSaveElement)(
name,
attributes,
// Instead of letting save elements use `useInnerBlocksProps.save`,
// force them to use InnerBlocks.Content instead so we can intercept
// a single component.
/* @__PURE__ */ (0, import_jsx_runtime531.jsx)(inner_blocks_default.Content, {})
);
addValuesForElement(saveElement, values, innerBlocks);
}
}
function getRichTextValues(blocks2 = []) {
import_blocks128.__unstableGetBlockProps.skipFilters = true;
const values = [];
addValuesForBlocks(values, blocks2);
import_blocks128.__unstableGetBlockProps.skipFilters = false;
return values.map(
(value) => value instanceof import_rich_text26.RichTextData ? value : import_rich_text26.RichTextData.fromHTMLString(value)
);
}
// packages/block-editor/build-module/components/resizable-box-popover/index.mjs
var import_components277 = __toESM(require_components(), 1);
var import_jsx_runtime532 = __toESM(require_jsx_runtime(), 1);
function ResizableBoxPopover({
clientId,
resizableBoxProps,
...props
}) {
return /* @__PURE__ */ (0, import_jsx_runtime532.jsx)(
cover_default,
{
clientId,
__unstablePopoverSlot: "block-toolbar",
...props,
children: /* @__PURE__ */ (0, import_jsx_runtime532.jsx)(import_components277.ResizableBox, { ...resizableBoxProps })
}
);
}
// packages/block-editor/build-module/components/block-removal-warning-modal/index.mjs
var import_element332 = __toESM(require_element(), 1);
var import_data200 = __toESM(require_data(), 1);
var import_components278 = __toESM(require_components(), 1);
var import_i18n251 = __toESM(require_i18n(), 1);
var import_jsx_runtime533 = __toESM(require_jsx_runtime(), 1);
function BlockRemovalWarningModal({ rules }) {
const [confirmed, setConfirmed] = (0, import_element332.useState)(false);
const { clientIds, selectPrevious, message: message2 } = (0, import_data200.useSelect)(
(select3) => unlock(select3(store)).getRemovalPromptData()
);
const {
clearBlockRemovalPrompt: clearBlockRemovalPrompt2,
setBlockRemovalRules: setBlockRemovalRules2,
privateRemoveBlocks: privateRemoveBlocks2
} = unlock((0, import_data200.useDispatch)(store));
(0, import_element332.useEffect)(() => {
setBlockRemovalRules2(rules);
return () => {
setBlockRemovalRules2();
};
}, [rules, setBlockRemovalRules2]);
(0, import_element332.useEffect)(() => {
setConfirmed(false);
}, [clientIds]);
if (!message2) {
return;
}
const isStructured = typeof message2 === "object" && message2 !== null;
const description = isStructured ? message2.description : message2;
const requireConfirmation = isStructured && message2.requireConfirmation;
const isRemoveDisabled = requireConfirmation && !confirmed;
const onConfirmRemoval = () => {
privateRemoveBlocks2(
clientIds,
selectPrevious,
/* force */
true
);
clearBlockRemovalPrompt2();
};
return /* @__PURE__ */ (0, import_jsx_runtime533.jsx)(
import_components278.Modal,
{
title: (0, import_i18n251.__)("Confirm deletion"),
onRequestClose: clearBlockRemovalPrompt2,
size: "medium",
children: /* @__PURE__ */ (0, import_jsx_runtime533.jsxs)(import_components278.__experimentalVStack, { spacing: 4, children: [
/* @__PURE__ */ (0, import_jsx_runtime533.jsxs)("div", { children: [
/* @__PURE__ */ (0, import_jsx_runtime533.jsx)("p", { children: description }),
isStructured && (message2.warning || message2.subtext) && /* @__PURE__ */ (0, import_jsx_runtime533.jsxs)("p", { children: [
message2.warning && /* @__PURE__ */ (0, import_jsx_runtime533.jsx)("strong", { children: message2.warning }),
message2.warning && message2.subtext && " ",
message2.subtext
] })
] }),
requireConfirmation && /* @__PURE__ */ (0, import_jsx_runtime533.jsx)(
import_components278.CheckboxControl,
{
label: (0, import_i18n251.__)("I understand the consequences"),
checked: confirmed,
onChange: setConfirmed
}
),
/* @__PURE__ */ (0, import_jsx_runtime533.jsxs)(import_components278.__experimentalHStack, { justify: "right", children: [
/* @__PURE__ */ (0, import_jsx_runtime533.jsx)(
import_components278.Button,
{
variant: "tertiary",
onClick: clearBlockRemovalPrompt2,
__next40pxDefaultSize: true,
children: (0, import_i18n251.__)("Cancel")
}
),
/* @__PURE__ */ (0, import_jsx_runtime533.jsx)(
import_components278.Button,
{
variant: "primary",
onClick: onConfirmRemoval,
disabled: isRemoveDisabled,
accessibleWhenDisabled: true,
__next40pxDefaultSize: true,
children: (0, import_i18n251.__)("Delete")
}
)
] })
] })
}
);
}
// packages/block-editor/build-module/components/dimensions-tool/index.mjs
var import_element334 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/dimensions-tool/scale-tool.mjs
var import_components279 = __toESM(require_components(), 1);
var import_element333 = __toESM(require_element(), 1);
var import_i18n252 = __toESM(require_i18n(), 1);
var import_jsx_runtime534 = __toESM(require_jsx_runtime(), 1);
var DEFAULT_SCALE_OPTIONS = [
{
value: "fill",
label: (0, import_i18n252._x)("Fill", "Scale option for dimensions control"),
help: (0, import_i18n252.__)("Fill the space by stretching the content.")
},
{
value: "contain",
label: (0, import_i18n252._x)("Contain", "Scale option for dimensions control"),
help: (0, import_i18n252.__)("Fit the content to the space without clipping.")
},
{
value: "cover",
label: (0, import_i18n252._x)("Cover", "Scale option for dimensions control"),
help: (0, import_i18n252.__)("Fill the space by clipping what doesn't fit.")
},
{
value: "none",
label: (0, import_i18n252._x)("None", "Scale option for dimensions control"),
help: (0, import_i18n252.__)(
"Do not adjust the sizing of the content. Content that is too large will be clipped, and content that is too small will have additional padding."
)
},
{
value: "scale-down",
label: (0, import_i18n252._x)("Scale down", "Scale option for dimensions control"),
help: (0, import_i18n252.__)(
"Scale down the content to fit the space if it is too big. Content that is too small will have additional padding."
)
}
];
function ScaleTool({
panelId,
value,
onChange,
options = DEFAULT_SCALE_OPTIONS,
defaultValue = DEFAULT_SCALE_OPTIONS[0].value,
isShownByDefault = true
}) {
const displayValue = value ?? defaultValue;
const scaleHelp = (0, import_element333.useMemo)(() => {
return options.reduce((acc, option) => {
acc[option.value] = option.help;
return acc;
}, {});
}, [options]);
return /* @__PURE__ */ (0, import_jsx_runtime534.jsx)(
import_components279.__experimentalToolsPanelItem,
{
label: (0, import_i18n252._x)("Scale", "Image scaling options"),
isShownByDefault,
hasValue: () => displayValue !== defaultValue,
onDeselect: () => onChange(defaultValue),
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime534.jsx)(
import_components279.__experimentalToggleGroupControl,
{
label: (0, import_i18n252._x)("Scale", "Image scaling options"),
isBlock: true,
help: scaleHelp[displayValue],
value: displayValue,
onChange,
children: options.map((option) => /* @__PURE__ */ (0, import_jsx_runtime534.jsx)(
import_components279.__experimentalToggleGroupControlOption,
{
...option
},
option.value
))
}
)
}
);
}
// packages/block-editor/build-module/components/dimensions-tool/width-height-tool.mjs
var import_components280 = __toESM(require_components(), 1);
var import_i18n253 = __toESM(require_i18n(), 1);
var import_jsx_runtime535 = __toESM(require_jsx_runtime(), 1);
function WidthHeightTool({
panelId,
value = {},
onChange = () => {
},
units: units2,
isShownByDefault = true
}) {
const width = value.width === "auto" ? "" : value.width ?? "";
const height = value.height === "auto" ? "" : value.height ?? "";
const onDimensionChange = (dimension) => (nextDimension) => {
const nextValue = { ...value };
if (!nextDimension) {
delete nextValue[dimension];
} else {
nextValue[dimension] = nextDimension;
}
onChange(nextValue);
};
return /* @__PURE__ */ (0, import_jsx_runtime535.jsxs)(import_jsx_runtime535.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime535.jsx)(
import_components280.__experimentalToolsPanelItem,
{
style: { gridColumn: "span 1" },
label: (0, import_i18n253.__)("Width"),
isShownByDefault,
hasValue: () => width !== "",
onDeselect: onDimensionChange("width"),
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime535.jsx)(
import_components280.__experimentalUnitControl,
{
label: (0, import_i18n253.__)("Width"),
placeholder: (0, import_i18n253.__)("Auto"),
labelPosition: "top",
units: units2,
min: 0,
value: width,
onChange: onDimensionChange("width")
}
)
}
),
/* @__PURE__ */ (0, import_jsx_runtime535.jsx)(
import_components280.__experimentalToolsPanelItem,
{
style: { gridColumn: "span 1" },
label: (0, import_i18n253.__)("Height"),
isShownByDefault,
hasValue: () => height !== "",
onDeselect: onDimensionChange("height"),
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime535.jsx)(
import_components280.__experimentalUnitControl,
{
label: (0, import_i18n253.__)("Height"),
placeholder: (0, import_i18n253.__)("Auto"),
labelPosition: "top",
units: units2,
min: 0,
value: height,
onChange: onDimensionChange("height")
}
)
}
)
] });
}
// packages/block-editor/build-module/components/dimensions-tool/index.mjs
var import_jsx_runtime536 = __toESM(require_jsx_runtime(), 1);
function DimensionsTool({
panelId,
value = {},
onChange = () => {
},
aspectRatioOptions,
// Default options handled by AspectRatioTool.
defaultAspectRatio = "auto",
// Match CSS default value for aspect-ratio.
scaleOptions,
// Default options handled by ScaleTool.
defaultScale = "cover",
unitsOptions,
// Default options handled by UnitControl.
tools = ["aspectRatio", "widthHeight", "scale"]
}) {
const width = value.width === void 0 || value.width === "auto" ? null : value.width;
const height = value.height === void 0 || value.height === "auto" ? null : value.height;
const aspectRatio = value.aspectRatio === void 0 || value.aspectRatio === "auto" ? null : value.aspectRatio;
const scale = value.scale === void 0 ? null : value.scale;
const [lastScale, setLastScale] = (0, import_element334.useState)(scale);
const [lastAspectRatio, setLastAspectRatio] = (0, import_element334.useState)(aspectRatio);
const hasCustomAspectRatio = !!(width && height);
const aspectRatioValue = hasCustomAspectRatio ? "custom" : aspectRatio;
const showScaleControl = aspectRatio || width && height;
return /* @__PURE__ */ (0, import_jsx_runtime536.jsxs)(import_jsx_runtime536.Fragment, { children: [
tools.includes("aspectRatio") && /* @__PURE__ */ (0, import_jsx_runtime536.jsx)(
AspectRatioTool,
{
panelId,
options: aspectRatioOptions,
defaultValue: defaultAspectRatio,
value: aspectRatioValue,
onChange: (nextAspectRatio) => {
const nextValue = { ...value };
nextAspectRatio = nextAspectRatio === "auto" ? null : nextAspectRatio;
setLastAspectRatio(nextAspectRatio);
if (!nextAspectRatio) {
delete nextValue.aspectRatio;
} else {
nextValue.aspectRatio = nextAspectRatio;
}
if (!nextAspectRatio) {
delete nextValue.scale;
} else if (lastScale) {
nextValue.scale = lastScale;
} else {
nextValue.scale = defaultScale;
setLastScale(defaultScale);
}
if ("custom" !== nextAspectRatio && width && height) {
delete nextValue.height;
}
onChange(nextValue);
}
}
),
tools.includes("widthHeight") && /* @__PURE__ */ (0, import_jsx_runtime536.jsx)(
WidthHeightTool,
{
panelId,
units: unitsOptions,
value: { width, height },
onChange: ({ width: nextWidth, height: nextHeight }) => {
const nextValue = { ...value };
nextWidth = nextWidth === "auto" ? null : nextWidth;
nextHeight = nextHeight === "auto" ? null : nextHeight;
if (!nextWidth) {
delete nextValue.width;
} else {
nextValue.width = nextWidth;
}
if (!nextHeight) {
delete nextValue.height;
} else {
nextValue.height = nextHeight;
}
if (nextWidth && nextHeight) {
delete nextValue.aspectRatio;
} else if (lastAspectRatio) {
nextValue.aspectRatio = lastAspectRatio;
} else {
}
if (!lastAspectRatio && !!nextWidth !== !!nextHeight) {
delete nextValue.scale;
} else if (lastScale) {
nextValue.scale = lastScale;
} else {
nextValue.scale = defaultScale;
setLastScale(defaultScale);
}
onChange(nextValue);
}
}
),
tools.includes("scale") && showScaleControl && /* @__PURE__ */ (0, import_jsx_runtime536.jsx)(
ScaleTool,
{
panelId,
options: scaleOptions,
defaultValue: defaultScale,
value: lastScale,
onChange: (nextScale) => {
const nextValue = { ...value };
setLastScale(nextScale);
if (!nextScale) {
delete nextValue.scale;
} else {
nextValue.scale = nextScale;
}
onChange(nextValue);
}
}
)
] });
}
var dimensions_tool_default = DimensionsTool;
// packages/block-editor/build-module/components/resolution-tool/index.mjs
var import_components281 = __toESM(require_components(), 1);
var import_i18n254 = __toESM(require_i18n(), 1);
var import_jsx_runtime537 = __toESM(require_jsx_runtime(), 1);
var DEFAULT_SIZE_OPTIONS = [
{
label: (0, import_i18n254._x)("Thumbnail", "Image size option for resolution control"),
value: "thumbnail"
},
{
label: (0, import_i18n254._x)("Medium", "Image size option for resolution control"),
value: "medium"
},
{
label: (0, import_i18n254._x)("Large", "Image size option for resolution control"),
value: "large"
},
{
label: (0, import_i18n254._x)("Full Size", "Image size option for resolution control"),
value: "full"
}
];
function ResolutionTool({
panelId,
value,
onChange,
options = DEFAULT_SIZE_OPTIONS,
defaultValue = DEFAULT_SIZE_OPTIONS[0].value,
isShownByDefault = true,
resetAllFilter
}) {
const displayValue = value ?? defaultValue;
return /* @__PURE__ */ (0, import_jsx_runtime537.jsx)(
import_components281.__experimentalToolsPanelItem,
{
hasValue: () => displayValue !== defaultValue,
label: (0, import_i18n254.__)("Resolution"),
onDeselect: () => onChange(defaultValue),
isShownByDefault,
panelId,
resetAllFilter,
children: /* @__PURE__ */ (0, import_jsx_runtime537.jsx)(
import_components281.SelectControl,
{
label: (0, import_i18n254.__)("Resolution"),
value: displayValue,
options,
onChange,
help: (0, import_i18n254.__)("Select the size of the source image.")
}
)
}
);
}
// packages/block-editor/build-module/components/html-element-control/index.mjs
var import_i18n256 = __toESM(require_i18n(), 1);
var import_components282 = __toESM(require_components(), 1);
var import_data201 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/html-element-control/messages.mjs
var import_i18n255 = __toESM(require_i18n(), 1);
var htmlElementMessages = {
a: (0, import_i18n255.__)(
"The <a> element should be used for links that navigate to a different page or to a different section within the same page."
),
article: (0, import_i18n255.__)(
"The <article> element should represent a self-contained, syndicatable portion of the document."
),
aside: (0, import_i18n255.__)(
"The <aside> element should represent a portion of a document whose content is only indirectly related to the document's main content."
),
button: (0, import_i18n255.__)(
"The <button> element should be used for interactive controls that perform an action on the current page, such as opening a modal or toggling content visibility."
),
div: (0, import_i18n255.__)(
"The <div> element should only be used if the block is a design element with no semantic meaning."
),
footer: (0, import_i18n255.__)(
"The <footer> element should represent a footer for its nearest sectioning element (e.g.: <section>, <article>, <main> etc.)."
),
header: (0, import_i18n255.__)(
"The <header> element should represent introductory content, typically a group of introductory or navigational aids."
),
main: (0, import_i18n255.__)(
"The <main> element should be used for the primary content of your document only."
),
nav: (0, import_i18n255.__)(
"The <nav> element should be used to identify groups of links that are intended to be used for website or page content navigation."
),
section: (0, import_i18n255.__)(
"The <section> element should represent a standalone portion of the document that can't be better represented by another element."
)
};
// packages/block-editor/build-module/components/html-element-control/index.mjs
var import_jsx_runtime538 = __toESM(require_jsx_runtime(), 1);
function HTMLElementControl({
tagName,
onChange,
clientId,
options = [
{ label: (0, import_i18n256.__)("Default (<div>)"), value: "div" },
{ label: "<header>", value: "header" },
{ label: "<main>", value: "main" },
{ label: "<section>", value: "section" },
{ label: "<article>", value: "article" },
{ label: "<aside>", value: "aside" },
{ label: "<footer>", value: "footer" }
]
}) {
const checkForMainTag = !!clientId && options.some((option) => option.value === "main");
const hasMainElementElsewhere = (0, import_data201.useSelect)(
(select3) => {
if (!checkForMainTag) {
return false;
}
const { getClientIdsWithDescendants: getClientIdsWithDescendants2, getBlockAttributes: getBlockAttributes3 } = select3(store);
return getClientIdsWithDescendants2().some((id) => {
if (id === clientId) {
return false;
}
return getBlockAttributes3(id)?.tagName === "main";
});
},
[clientId, checkForMainTag]
);
const modifiedOptions = options.map((option) => {
if (option.value === "main" && hasMainElementElsewhere && tagName !== "main") {
return {
...option,
disabled: true,
label: (0, import_i18n256.sprintf)(
/* translators: %s: HTML element name */
(0, import_i18n256.__)("%s (Already in use)"),
option.label
)
};
}
return option;
});
return /* @__PURE__ */ (0, import_jsx_runtime538.jsxs)(import_components282.__experimentalVStack, { spacing: 2, className: "block-editor-html-element-control", children: [
/* @__PURE__ */ (0, import_jsx_runtime538.jsx)(
import_components282.SelectControl,
{
label: (0, import_i18n256.__)("HTML element"),
options: modifiedOptions,
value: tagName,
onChange,
help: htmlElementMessages[tagName]
}
),
tagName === "main" && hasMainElementElsewhere && /* @__PURE__ */ (0, import_jsx_runtime538.jsx)(import_components282.Notice, { status: "warning", isDismissible: false, children: (0, import_i18n256.__)(
"Multiple <main> elements detected. The duplicate may be in your content or template. This is not valid HTML and may cause accessibility issues. Please change this HTML element."
) })
] });
}
// packages/block-editor/build-module/components/link-picker/link-picker.mjs
var import_components284 = __toESM(require_components(), 1);
var import_element335 = __toESM(require_element(), 1);
var import_i18n257 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/link-picker/link-preview.mjs
var import_components283 = __toESM(require_components(), 1);
var import_dom73 = __toESM(require_dom(), 1);
var import_jsx_runtime539 = __toESM(require_jsx_runtime(), 1);
var { Badge: WCBadge6 } = unlock(import_components283.privateApis);
function LinkPreview2({ title, url, image, badges }) {
return /* @__PURE__ */ (0, import_jsx_runtime539.jsxs)(import_components283.__experimentalHStack, { justify: "space-between", alignment: "top", children: [
/* @__PURE__ */ (0, import_jsx_runtime539.jsx)(import_components283.FlexItem, { className: "link-preview-button__content", children: /* @__PURE__ */ (0, import_jsx_runtime539.jsxs)(import_components283.__experimentalHStack, { alignment: "top", children: [
image && /* @__PURE__ */ (0, import_jsx_runtime539.jsx)(import_components283.FlexItem, { className: "link-preview-button__image-container", children: /* @__PURE__ */ (0, import_jsx_runtime539.jsx)(
"img",
{
className: "link-preview-button__image",
src: image,
alt: ""
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime539.jsxs)(
import_components283.__experimentalVStack,
{
className: "link-preview-button__details",
alignment: "topLeft",
children: [
/* @__PURE__ */ (0, import_jsx_runtime539.jsx)(
import_components283.__experimentalTruncate,
{
numberOfLines: 1,
className: "link-preview-button__title",
children: (0, import_dom73.__unstableStripHTML)(title)
}
),
url && /* @__PURE__ */ (0, import_jsx_runtime539.jsx)(
import_components283.__experimentalTruncate,
{
numberOfLines: 1,
className: "link-preview-button__hint",
children: url
}
),
badges && badges.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime539.jsx)(
import_components283.__experimentalHStack,
{
className: "link-preview-button__badges",
alignment: "left",
children: badges.map((badge) => /* @__PURE__ */ (0, import_jsx_runtime539.jsx)(
WCBadge6,
{
intent: badge.intent,
children: badge.label
},
`${badge.label}|${badge.intent}`
))
}
)
]
}
)
] }) }),
/* @__PURE__ */ (0, import_jsx_runtime539.jsx)(icon_default, { icon: chevron_down_default, className: "link-preview-button__icon" })
] });
}
// packages/block-editor/build-module/components/link-picker/link-picker.mjs
var import_jsx_runtime540 = __toESM(require_jsx_runtime(), 1);
function LinkPicker({
preview,
onSelect,
suggestionsQuery,
label,
help
}) {
const [isOpen, setIsOpen] = (0, import_element335.useState)(false);
const instanceId = (0, import_element335.useId)();
const dialogTitleId = `link-picker-title-${instanceId}`;
const dialogDescriptionId = `link-picker-description-${instanceId}`;
const anchorRef = (0, import_element335.useRef)(null);
const { baseControlProps, controlProps } = (0, import_components284.useBaseControlProps)({
help
});
const handleChange = (newValue) => {
setIsOpen(false);
if (newValue) {
const suggestion = {
url: newValue.url,
kind: newValue.kind,
type: newValue.type,
id: newValue.id,
title: newValue.title
};
onSelect(suggestion);
}
};
return /* @__PURE__ */ (0, import_jsx_runtime540.jsxs)(import_components284.BaseControl, { ...baseControlProps, children: [
/* @__PURE__ */ (0, import_jsx_runtime540.jsx)(import_components284.BaseControl.VisualLabel, { children: label }),
/* @__PURE__ */ (0, import_jsx_runtime540.jsxs)(
import_components284.Button,
{
ref: anchorRef,
onClick: () => setIsOpen(!isOpen),
"aria-haspopup": "dialog",
"aria-expanded": isOpen,
"aria-describedby": controlProps["aria-describedby"],
variant: "secondary",
__next40pxDefaultSize: true,
className: "link-preview-button",
children: [
label && /* @__PURE__ */ (0, import_jsx_runtime540.jsxs)(VisuallyHidden, { children: [
label,
":"
] }),
/* @__PURE__ */ (0, import_jsx_runtime540.jsx)(
LinkPreview2,
{
title: preview.title || (0, import_i18n257.__)("Add link"),
url: preview.url,
image: preview.image,
badges: preview.badges
}
)
]
}
),
isOpen && /* @__PURE__ */ (0, import_jsx_runtime540.jsx)(
import_components284.Popover,
{
anchor: anchorRef.current,
onClose: () => setIsOpen(false),
placement: "left-start",
offset: 36,
shift: true,
children: /* @__PURE__ */ (0, import_jsx_runtime540.jsxs)(
"div",
{
role: "dialog",
"aria-labelledby": dialogTitleId,
"aria-describedby": dialogDescriptionId,
children: [
/* @__PURE__ */ (0, import_jsx_runtime540.jsxs)(VisuallyHidden, { children: [
/* @__PURE__ */ (0, import_jsx_runtime540.jsx)("h2", { id: dialogTitleId, children: (0, import_i18n257.__)("Select a link") }),
/* @__PURE__ */ (0, import_jsx_runtime540.jsx)("p", { id: dialogDescriptionId, children: (0, import_i18n257.__)(
"Search for and add a link to the navigation item."
) })
] }),
/* @__PURE__ */ (0, import_jsx_runtime540.jsx)(
link_control_default,
{
value: null,
onChange: handleChange,
suggestionsQuery,
showInitialSuggestions: true,
forceIsEditingLink: true,
settings: []
}
)
]
}
)
}
)
] });
}
// packages/block-editor/build-module/components/inner-content/index.mjs
var import_element336 = __toESM(require_element(), 1);
var import_data202 = __toESM(require_data(), 1);
var import_dom74 = __toESM(require_dom(), 1);
var import_jsx_runtime541 = __toESM(require_jsx_runtime(), 1);
var SLOT_TAG_NAME = "wp-inner-block-slot";
var LAYOUT = { type: "default", alignments: [] };
function InnerContent({ clientId }) {
const { innerContent, order, selectedClientIds } = (0, import_data202.useSelect)(
(select3) => {
const { getBlock: getBlock2, getBlockOrder: getBlockOrder2, getSelectedBlockClientIds: getSelectedBlockClientIds2 } = select3(store);
return {
innerContent: getBlock2(clientId)?.innerContent,
order: getBlockOrder2(clientId),
selectedClientIds: getSelectedBlockClientIds2()
};
},
[clientId]
);
const html = (0, import_element336.useMemo)(() => {
let slotIndex = 0;
return (innerContent ?? []).map(
(item) => item === null ? `<${SLOT_TAG_NAME} data-slot-index="${slotIndex++}" style="display: contents"></${SLOT_TAG_NAME}>` : item
).join("");
}, [innerContent]);
const containerRef = (0, import_element336.useRef)();
const [slots, setSlots] = (0, import_element336.useState)([]);
(0, import_element336.useLayoutEffect)(() => {
const container = containerRef.current;
container.innerHTML = (0, import_dom74.safeHTML)(html);
setSlots(
Array.from(container.querySelectorAll(SLOT_TAG_NAME)).sort(
(a2, b2) => Number(a2.dataset.slotIndex) - Number(b2.dataset.slotIndex)
)
);
}, [html]);
return /* @__PURE__ */ (0, import_jsx_runtime541.jsxs)(LayoutProvider, { value: LAYOUT, children: [
/* @__PURE__ */ (0, import_jsx_runtime541.jsx)(
"div",
{
ref: containerRef,
className: "block-editor-inner-content",
style: { display: "contents" }
}
),
order.map(
(childClientId, index2) => slots[index2] ? (0, import_element336.createPortal)(
// Render the selected block synchronously, as the block list does.
/* @__PURE__ */ (0, import_jsx_runtime541.jsx)(
import_data202.AsyncModeProvider,
{
value: !selectedClientIds.includes(
childClientId
),
children: /* @__PURE__ */ (0, import_jsx_runtime541.jsx)(
block_default2,
{
rootClientId: clientId,
clientId: childClientId
}
)
}
),
slots[index2],
childClientId
) : null
)
] });
}
// packages/block-editor/build-module/private-apis.mjs
var privateApis14 = {};
lock(privateApis14, {
...global_styles_exports,
ExperimentalBlockCanvas,
BlockCanvasCover,
ExperimentalBlockEditorProvider,
getDuotoneFilter,
getRichTextValues,
PrivateQuickInserter: QuickInserter,
extractWords,
getNormalizedSearchTerms,
normalizeString,
PrivateListView,
ResizableBoxPopover,
InspectorControlsLastItem: last_item_default,
useHasBlockToolbar,
cleanEmptyObject,
getStyleForState,
isDefaultBlockStyleState,
setStyleForState,
usePrivateStyleOverride,
BlockQuickNavigation,
LayoutStyle,
BlockManager,
BlockRemovalWarningModal,
useLayoutClasses,
useLayoutStyles,
DimensionsTool: dimensions_tool_default,
ResolutionTool,
TabbedSidebar: tabbed_sidebar_default,
TextAlignmentControl,
usesContextKey,
useFlashEditableBlocks,
HTMLElementControl,
useZoomOut,
globalStylesDataKey,
globalStylesLinksDataKey,
selectBlockPatternsKey,
requiresWrapperOnCopy,
PrivateRichText,
PrivateInserterLibrary,
reusableBlocksSelectKey,
userPatternCategoriesSelectKey,
PrivateBlockPopover,
PrivatePublishDateTimePicker,
useSpacingSizes,
useBlockDisplayTitle,
BlockStyleVariationOverridesWithConfig,
setBackgroundStyleDefaults: setBackgroundStyleDefaults2,
sectionRootClientIdKey,
NoteIconSlotFill: note_icon_slot_default,
NoteIconToolbarSlotFill: note_icon_toolbar_slot_default,
mediaEditKey,
getMediaSelectKey,
deviceTypeKey,
isIsolatedEditorKey,
isNavigationOverlayContextKey,
isNavigationPostEditorKey,
mediaUploadOnSuccessKey,
mediaSideloadFromUrlKey,
openMediaEditorModalKey,
useBlockElement,
useBlockElementRef,
LinkPicker,
useRemoteUrlData: use_rich_url_data_default,
PrivateBlockContext,
useListViewPanelState,
isHashLink,
isRelativePath,
InnerContent
});
return __toCommonJS(index_exports);
})();
/*! Bundled license information:
react-is/cjs/react-is.development.js:
(** @license React v16.13.1
* react-is.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
object-assign/index.js:
(*
object-assign
(c) Sindre Sorhus
@license MIT
*)
autosize/dist/autosize.js:
(*!
autosize 4.0.2
license: MIT
http://www.jacklmoore.com/autosize
*)
use-sync-external-store/cjs/use-sync-external-store-shim.development.js:
(**
* @license React
* use-sync-external-store-shim.development.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js:
(**
* @license React
* use-sync-external-store-shim/with-selector.development.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
normalize-wheel/src/isEventSupported.js:
(**
* Checks if an event is supported in the current execution environment.
*
* NOTE: This will not work correctly for non-generic events such as `change`,
* `reset`, `load`, `error`, and `select`.
*
* Borrows from Modernizr.
*
* @param {string} eventNameSuffix Event name, e.g. "click".
* @param {?boolean} capture Check if the capture phase is supported.
* @return {boolean} True if the event is supported.
* @internal
* @license Modernizr 3.0.0pre (Custom Build) | MIT
*)
is-plain-object/dist/is-plain-object.mjs:
(*!
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*)
*/