File: /www/wwwroot/www.waciwang.com/wp-content/plugins/gutenberg/build/scripts/block-editor/index.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/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/api-fetch
var require_api_fetch = __commonJS({
"package-external:@wordpress/api-fetch"(exports, module) {
module.exports = window.wp.apiFetch;
}
});
// package-external:@wordpress/html-entities
var require_html_entities = __commonJS({
"package-external:@wordpress/html-entities"(exports, module) {
module.exports = window.wp.htmlEntities;
}
});
// package-external:@wordpress/style-engine
var require_style_engine = __commonJS({
"package-external:@wordpress/style-engine"(exports, module) {
module.exports = window.wp.styleEngine;
}
});
// 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;
}
});
// node_modules/diff/lib/diff/base.js
var require_base = __commonJS({
"node_modules/diff/lib/diff/base.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = Diff;
function Diff() {
}
Diff.prototype = {
/*istanbul ignore start*/
/*istanbul ignore end*/
diff: function diff(oldString, newString) {
var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
var callback = options.callback;
if (typeof options === "function") {
callback = options;
options = {};
}
this.options = options;
var self = this;
function done(value) {
if (callback) {
setTimeout(function() {
callback(void 0, value);
}, 0);
return true;
} else {
return value;
}
}
oldString = this.castInput(oldString);
newString = this.castInput(newString);
oldString = this.removeEmpty(this.tokenize(oldString));
newString = this.removeEmpty(this.tokenize(newString));
var newLen = newString.length, oldLen = oldString.length;
var editLength = 1;
var maxEditLength = newLen + oldLen;
var bestPath = [{
newPos: -1,
components: []
}];
var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
return done([{
value: this.join(newString),
count: newString.length
}]);
}
function execEditLength() {
for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
var basePath = (
/*istanbul ignore start*/
void 0
);
var addPath = bestPath[diagonalPath - 1], removePath = bestPath[diagonalPath + 1], _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
if (addPath) {
bestPath[diagonalPath - 1] = void 0;
}
var canAdd = addPath && addPath.newPos + 1 < newLen, canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
if (!canAdd && !canRemove) {
bestPath[diagonalPath] = void 0;
continue;
}
if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
basePath = clonePath(removePath);
self.pushComponent(basePath.components, void 0, true);
} else {
basePath = addPath;
basePath.newPos++;
self.pushComponent(basePath.components, true, void 0);
}
_oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath);
if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
} else {
bestPath[diagonalPath] = basePath;
}
}
editLength++;
}
if (callback) {
(function exec() {
setTimeout(function() {
if (editLength > maxEditLength) {
return callback();
}
if (!execEditLength()) {
exec();
}
}, 0);
})();
} else {
while (editLength <= maxEditLength) {
var ret = execEditLength();
if (ret) {
return ret;
}
}
}
},
/*istanbul ignore start*/
/*istanbul ignore end*/
pushComponent: function pushComponent(components, added, removed) {
var last = components[components.length - 1];
if (last && last.added === added && last.removed === removed) {
components[components.length - 1] = {
count: last.count + 1,
added,
removed
};
} else {
components.push({
count: 1,
added,
removed
});
}
},
/*istanbul ignore start*/
/*istanbul ignore end*/
extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
var newLen = newString.length, oldLen = oldString.length, newPos = basePath.newPos, oldPos = newPos - diagonalPath, commonCount = 0;
while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
newPos++;
oldPos++;
commonCount++;
}
if (commonCount) {
basePath.components.push({
count: commonCount
});
}
basePath.newPos = newPos;
return oldPos;
},
/*istanbul ignore start*/
/*istanbul ignore end*/
equals: function equals(left, right) {
if (this.options.comparator) {
return this.options.comparator(left, right);
} else {
return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
}
},
/*istanbul ignore start*/
/*istanbul ignore end*/
removeEmpty: function removeEmpty(array) {
var ret = [];
for (var i2 = 0; i2 < array.length; i2++) {
if (array[i2]) {
ret.push(array[i2]);
}
}
return ret;
},
/*istanbul ignore start*/
/*istanbul ignore end*/
castInput: function castInput(value) {
return value;
},
/*istanbul ignore start*/
/*istanbul ignore end*/
tokenize: function tokenize2(value) {
return value.split("");
},
/*istanbul ignore start*/
/*istanbul ignore end*/
join: function join(chars) {
return chars.join("");
}
};
function buildValues(diff, components, newString, oldString, useLongestToken) {
var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0;
for (; componentPos < componentLen; componentPos++) {
var component = components[componentPos];
if (!component.removed) {
if (!component.added && useLongestToken) {
var value = newString.slice(newPos, newPos + component.count);
value = value.map(function(value2, i2) {
var oldValue = oldString[oldPos + i2];
return oldValue.length > value2.length ? oldValue : value2;
});
component.value = diff.join(value);
} else {
component.value = diff.join(newString.slice(newPos, newPos + component.count));
}
newPos += component.count;
if (!component.added) {
oldPos += component.count;
}
} else {
component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
oldPos += component.count;
if (componentPos && components[componentPos - 1].added) {
var tmp = components[componentPos - 1];
components[componentPos - 1] = components[componentPos];
components[componentPos] = tmp;
}
}
}
var lastComponent = components[componentLen - 1];
if (componentLen > 1 && typeof lastComponent.value === "string" && (lastComponent.added || lastComponent.removed) && diff.equals("", lastComponent.value)) {
components[componentLen - 2].value += lastComponent.value;
components.pop();
}
return components;
}
function clonePath(path) {
return {
newPos: path.newPos,
components: path.components.slice(0)
};
}
}
});
// node_modules/diff/lib/diff/character.js
var require_character = __commonJS({
"node_modules/diff/lib/diff/character.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.diffChars = diffChars2;
exports.characterDiff = void 0;
var _base = _interopRequireDefault(require_base());
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
var characterDiff = new /*istanbul ignore start*/
_base.default();
exports.characterDiff = characterDiff;
function diffChars2(oldStr, newStr, options) {
return characterDiff.diff(oldStr, newStr, options);
}
}
});
// 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_TYPE = 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_TYPE || 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_TYPE:
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 Fragment98 = REACT_FRAGMENT_TYPE;
var Lazy = REACT_LAZY_TYPE;
var Memo = REACT_MEMO_TYPE;
var Portal = 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 isElement(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_TYPE;
}
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 = Fragment98;
exports.Lazy = Lazy;
exports.Memo = Memo;
exports.Portal = Portal;
exports.Profiler = Profiler;
exports.StrictMode = StrictMode2;
exports.Suspense = Suspense;
exports.isAsyncMode = isAsyncMode;
exports.isConcurrentMode = isConcurrentMode;
exports.isContextConsumer = isContextConsumer;
exports.isContextProvider = isContextProvider;
exports.isElement = isElement;
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 error;
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;
}
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
} catch (ex) {
error = ex;
}
if (error && !(error 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 error + ". 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 (error instanceof Error && !(error.message in loggedTypeFailures)) {
loggedTypeFailures[error.message] = true;
var stack = getStack ? getStack() : "";
printWarning(
"Failed " + location + " type: " + error.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(isValidElement2, 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 error = typeChecker(propValue, i2, componentName, location, propFullName + "[" + i2 + "]", ReactPropTypesSecret);
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!isValidElement2(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 error = typeChecker(propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret);
if (error instanceof Error) {
return error;
}
}
}
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 (!isNode(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 error = checker(propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret);
if (error) {
return error;
}
}
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 error = checker(propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(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(isNode);
}
if (propValue === null || isValidElement2(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 (!isNode(step.value)) {
return false;
}
}
} else {
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
if (!isNode(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 set(key, value) {
if (keys.indexOf(key) === -1) {
keys.push(key);
values.push(value);
}
},
delete: function _delete(key) {
var index = keys.indexOf(key);
if (index > -1) {
keys.splice(index, 1);
values.splice(index, 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, getComputedStyle) {
getComputedStyle = window.getComputedStyle;
return (
// If we have getComputedStyle
(getComputedStyle ? (
// Query it
// TODO: From CSS-Query notes, we might need (node, null) for FF
getComputedStyle(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 __222() {
this.constructor = d2;
}
d2.prototype = b2 === null ? Object.create(b2) : (__222.prototype = b2.prototype, new __222());
};
})();
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 React8 = 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 React8.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;
})(React8.Component)
);
exports.TextareaAutosize = React8.forwardRef(function(props, ref) {
return React8.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/blob
var require_blob = __commonJS({
"package-external:@wordpress/blob"(exports, module) {
module.exports = window.wp.blob;
}
});
// (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):path
var require_path = __commonJS({
"(disabled):path"() {
}
});
// (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 (size = defaultSize) => {
let id = "";
let i2 = size | 0;
while (i2--) {
id += alphabet[Math.random() * alphabet.length | 0];
}
return id;
};
};
var nanoid = (size = 21) => {
let id = "";
let i2 = size | 0;
while (i2--) {
id += urlAlphabet[Math.random() * 64 | 0];
}
return id;
};
module.exports = { nanoid, customAlphabet };
}
});
// (disabled):node_modules/postcss/lib/terminal-highlight
var require_terminal_highlight = __commonJS({
"(disabled):node_modules/postcss/lib/terminal-highlight"() {
}
});
// 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;
}
});
// 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 css3 = this.source;
if (color == null) color = pico.isColorSupported;
if (terminalHighlight) {
if (color) css3 = terminalHighlight(css3);
}
let lines = css3.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;
let mark, aside;
if (color) {
let { bold, gray, red } = pico.createColors(true);
mark = (text) => bold(red(text));
aside = (text) => gray(text);
} else {
mark = aside = (str) => str;
}
return lines.slice(start2, end).map((line, index) => {
let number = start2 + 1 + index;
let gutter = " " + (" " + number).slice(-maxWidth) + " | ";
if (number === this.line) {
let spacing = aside(gutter.replace(/\d/g, " ")) + line.slice(0, this.column - 1).replace(/[^\t]/g, " ");
return mark(">") + aside(gutter) + line + "\n " + spacing + mark("^");
}
return " " + aside(gutter) + 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;
}
});
// (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 { SourceMapConsumer, SourceMapGenerator } = require_source_map();
var { existsSync, readFileSync } = require_fs();
var { dirname, join } = require_path();
function fromBase64(str) {
if (Buffer) {
return Buffer.from(str, "base64").toString();
} else {
return window.atob(str);
}
}
var PreviousMap = class {
constructor(css3, opts) {
if (opts.map === false) return;
this.loadAnnotation(css3);
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.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,/;
if (charsetUri.test(text) || uri.test(text)) {
return decodeURIComponent(text.substr(RegExp.lastMatch.length));
}
if (baseCharsetUri.test(text) || baseUri.test(text)) {
return fromBase64(text.substr(RegExp.lastMatch.length));
}
let encoding = text.match(/data:application\/json;([^,]+),/)[1];
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(css3) {
let comments = css3.match(/\/\*\s*# sourceMappingURL=/gm);
if (!comments) return;
let start2 = css3.lastIndexOf(comments.pop());
let end = css3.indexOf("*/", start2);
if (start2 > -1 && end > -1) {
this.annotation = this.getAnnotationURL(css3.substring(start2, end));
}
}
loadFile(path) {
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);
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);
return this.loadFile(map);
}
}
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 { SourceMapConsumer, SourceMapGenerator } = require_source_map();
var { fileURLToPath, pathToFileURL } = require_url2();
var { isAbsolute, resolve } = require_path();
var { nanoid } = require_non_secure();
var terminalHighlight = require_terminal_highlight();
var CssSyntaxError2 = require_css_syntax_error();
var PreviousMap = require_previous_map();
var fromOffsetCache = /* @__PURE__ */ Symbol("fromOffsetCache");
var sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator);
var pathAvailable = Boolean(resolve && isAbsolute);
var Input = class {
constructor(css3, opts = {}) {
if (css3 === null || typeof css3 === "undefined" || typeof css3 === "object" && !css3.toString) {
throw new Error(`PostCSS received ${css3} instead of CSS string`);
}
this.css = css3.toString();
if (this.css[0] === "\uFEFF" || this.css[0] === "\uFFFE") {
this.hasBOM = true;
this.css = this.css.slice(1);
} else {
this.hasBOM = false;
}
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 result, endLine, endColumn;
if (line && typeof line === "object") {
let start2 = line;
let end = column;
if (typeof start2.offset === "number") {
let pos = this.fromOffset(start2.offset);
line = pos.line;
column = pos.col;
} else {
line = start2.line;
column = start2.column;
}
if (typeof end.offset === "number") {
let pos = this.fromOffset(end.offset);
endLine = pos.line;
endColumn = pos.col;
} else {
endLine = end.line;
endColumn = end.column;
}
} else if (!column) {
let pos = this.fromOffset(line);
line = pos.line;
column = pos.col;
}
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, line, source: this.css };
if (this.file) {
if (pathToFileURL) {
result.input.url = pathToFileURL(this.file).toString();
}
result.input.file = this.file;
}
return result;
}
fromOffset(offset) {
let lastLine, lineToIndex;
if (!this[fromOffsetCache]) {
let lines = this.css.split("\n");
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;
}
this[fromOffsetCache] = lineToIndex;
} else {
lineToIndex = this[fromOffsetCache];
}
lastLine = lineToIndex[lineToIndex.length - 1];
let min = 0;
if (offset >= lastLine) {
min = lineToIndex.length - 1;
} else {
let max = lineToIndex.length - 2;
let mid;
while (min < max) {
mid = min + (max - min >> 1);
if (offset < lineToIndex[mid]) {
max = mid - 1;
} else if (offset >= lineToIndex[mid + 1]) {
min = mid + 1;
} else {
min = mid;
break;
}
}
}
return {
col: offset - lineToIndex[min] + 1,
line: min + 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, line });
if (!from.source) return false;
let to2;
if (typeof endLine === "number") {
to2 = consumer.originalPositionFor({ column: endColumn, 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,
endColumn: to2 && to2.column,
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;
}
get from() {
return this.file || this.id;
}
};
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 { SourceMapConsumer, SourceMapGenerator } = require_source_map();
var { dirname, relative, resolve, sep } = require_path();
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.indexOf("# sourceMappingURL=") === 0) {
this.root.removeChild(i2);
}
}
} else if (this.css) {
this.css = this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm, "");
}
}
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 lines, last;
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/stringifier.js
var require_stringifier = __commonJS({
"node_modules/postcss/lib/stringifier.js"(exports, module) {
"use strict";
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 name = "@" + node.name;
let params = node.params ? this.rawValue(node, "params") : "";
if (typeof node.raws.afterName !== "undefined") {
name += node.raws.afterName;
} else if (params) {
name += " ";
}
if (node.nodes) {
this.block(node, name + params);
} else {
let end = (node.raws.between || "") + (semicolon ? ";" : "");
this.builder(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(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(after);
this.builder("}", node, "end");
}
body(node) {
let last = node.nodes.length - 1;
while (last > 0) {
if (node.nodes[last].type !== "comment") break;
last -= 1;
}
let semicolon = this.raw(node, "semicolon");
for (let i2 = 0; i2 < node.nodes.length; i2++) {
let child = node.nodes[i2];
let before = this.raw(child, "before");
if (before) this.builder(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("/*" + left + node.text + right + "*/", node);
}
decl(node, semicolon) {
let between = this.raw(node, "between", "colon");
let string = node.prop + between + this.rawValue(node, "value");
if (node.important) {
string += node.raws.important || " !important";
}
if (semicolon) string += ";";
this.builder(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();
if (!root.rawCache) root.rawCache = {};
if (typeof root.rawCache[detect] !== "undefined") {
return root.rawCache[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];
root.rawCache[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) this.builder(node.raws.after);
}
rule(node) {
this.block(node, this.rawValue(node, "selector"));
if (node.raws.ownSemicolon) {
this.builder(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/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/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 { isClean, my } = require_symbols();
var CssSyntaxError2 = require_css_syntax_error();
var Stringifier = require_stringifier();
var stringify2 = require_stringify();
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;
}
var Node = class {
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") {
this.append(node.clone());
} else {
this.append(node);
}
}
} else {
this[name] = defaults2[name];
}
}
}
addToError(error) {
error.postcssNode = this;
if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
let s2 = this.source;
error.stack = error.stack.replace(
/\n\s{4}at /,
`$&${s2.input.from}:${s2.start.line}:${s2.start.column}$&`
);
}
return error;
}
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;
}
};
}
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 index = this.parent.index(this);
return this.parent.nodes[index + 1];
}
positionBy(opts, stringRepresentation) {
let pos = this.source.start;
if (opts.index) {
pos = this.positionInside(opts.index, stringRepresentation);
} else if (opts.word) {
stringRepresentation = this.toString();
let index = stringRepresentation.indexOf(opts.word);
if (index !== -1) pos = this.positionInside(index, stringRepresentation);
}
return pos;
}
positionInside(index, stringRepresentation) {
let string = stringRepresentation || this.toString();
let column = this.source.start.column;
let line = this.source.start.line;
for (let i2 = 0; i2 < index; i2++) {
if (string[i2] === "\n") {
column = 1;
line += 1;
} else {
column += 1;
}
}
return { column, line };
}
prev() {
if (!this.parent) return void 0;
let index = this.parent.index(this);
return this.parent.nodes[index - 1];
}
rangeBy(opts) {
let start2 = {
column: this.source.start.column,
line: this.source.start.line
};
let end = this.source.end ? {
column: this.source.end.column + 1,
line: this.source.end.line
} : {
column: start2.column + 1,
line: start2.line
};
if (opts.word) {
let stringRepresentation = this.toString();
let index = stringRepresentation.indexOf(opts.word);
if (index !== -1) {
start2 = this.positionInside(index, stringRepresentation);
end = this.positionInside(index + opts.word.length, stringRepresentation);
}
} else {
if (opts.start) {
start2 = {
column: opts.start.column,
line: opts.start.line
};
} else if (opts.index) {
start2 = this.positionInside(opts.index);
}
if (opts.end) {
end = {
column: opts.end.column,
line: opts.end.line
};
} else if (typeof opts.endIndex === "number") {
end = this.positionInside(opts.endIndex);
} else if (opts.index) {
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 };
}
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") {
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);
}
get proxyOf() {
return this;
}
};
module.exports = Node;
Node.default = Node;
}
});
// node_modules/postcss/lib/declaration.js
var require_declaration = __commonJS({
"node_modules/postcss/lib/declaration.js"(exports, module) {
"use strict";
var Node = require_node();
var Declaration = class extends Node {
constructor(defaults2) {
if (defaults2 && typeof defaults2.value !== "undefined" && typeof defaults2.value !== "string") {
defaults2 = { ...defaults2, value: String(defaults2.value) };
}
super(defaults2);
this.type = "decl";
}
get variable() {
return this.prop.startsWith("--") || this.prop[0] === "$";
}
};
module.exports = Declaration;
Declaration.default = Declaration;
}
});
// node_modules/postcss/lib/comment.js
var require_comment = __commonJS({
"node_modules/postcss/lib/comment.js"(exports, module) {
"use strict";
var Node = require_node();
var Comment = class extends Node {
constructor(defaults2) {
super(defaults2);
this.type = "comment";
}
};
module.exports = Comment;
Comment.default = Comment;
}
});
// node_modules/postcss/lib/container.js
var require_container = __commonJS({
"node_modules/postcss/lib/container.js"(exports, module) {
"use strict";
var { isClean, my } = require_symbols();
var Declaration = require_declaration();
var Comment = require_comment();
var Node = require_node();
var parse4;
var Rule;
var AtRule;
var Root2;
function cleanSource(nodes) {
return nodes.map((i2) => {
if (i2.nodes) i2.nodes = cleanSource(i2.nodes);
delete i2.source;
return i2;
});
}
function markDirtyUp(node) {
node[isClean] = false;
if (node.proxyOf.nodes) {
for (let i2 of node.proxyOf.nodes) {
markDirtyUp(i2);
}
}
}
var Container = class _Container extends Node {
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 index, result;
while (this.indexes[iterator] < this.proxyOf.nodes.length) {
index = this.indexes[iterator];
result = callback(this.proxyOf.nodes[index], index);
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, index) => i2(child.toProxy(), index);
} 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 index;
for (let id in this.indexes) {
index = this.indexes[id];
if (existIndex < index) {
this.indexes[id] = index + 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 index;
for (let id in this.indexes) {
index = this.indexes[id];
if (existIndex <= index) {
this.indexes[id] = index + 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 = [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]) markDirtyUp(i2);
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 index;
for (let id in this.indexes) {
index = this.indexes[id];
if (index >= child) {
this.indexes[id] = index - 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);
}
});
}
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];
}
};
Container.registerParse = (dependant) => {
parse4 = dependant;
};
Container.registerRule = (dependant) => {
Rule = dependant;
};
Container.registerAtRule = (dependant) => {
AtRule = dependant;
};
Container.registerRoot = (dependant) => {
Root2 = 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, Root2.prototype);
}
node[my] = true;
if (node.nodes) {
node.nodes.forEach((child) => {
Container.rebuild(child);
});
}
};
}
});
// 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 TAB4 = " ".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 css3 = input.css.valueOf();
let ignore = options.ignoreErrors;
let code, next, quote, content, escape;
let escaped, escapePos, prev, n2, currentToken;
let length = css3.length;
let pos = 0;
let buffer = [];
let returned = [];
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 = css3.charCodeAt(pos);
switch (code) {
case NEWLINE:
case SPACE3:
case TAB4:
case CR:
case FEED: {
next = pos;
do {
next += 1;
code = css3.charCodeAt(next);
} while (code === SPACE3 || code === NEWLINE || code === TAB4 || code === CR || code === FEED);
currentToken = ["space", css3.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 = css3.charCodeAt(pos + 1);
if (prev === "url" && n2 !== SINGLE_QUOTE && n2 !== DOUBLE_QUOTE && n2 !== SPACE3 && n2 !== NEWLINE && n2 !== TAB4 && n2 !== FEED && n2 !== CR) {
next = pos;
do {
escaped = false;
next = css3.indexOf(")", next + 1);
if (next === -1) {
if (ignore || ignoreUnclosed) {
next = pos;
break;
} else {
unclosed("bracket");
}
}
escapePos = next;
while (css3.charCodeAt(escapePos - 1) === BACKSLASH) {
escapePos -= 1;
escaped = !escaped;
}
} while (escaped);
currentToken = ["brackets", css3.slice(pos, next + 1), pos, next];
pos = next;
} else {
next = css3.indexOf(")", pos + 1);
content = css3.slice(pos, next + 1);
if (next === -1 || RE_BAD_BRACKET.test(content)) {
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 = css3.indexOf(quote, next + 1);
if (next === -1) {
if (ignore || ignoreUnclosed) {
next = pos + 1;
break;
} else {
unclosed("string");
}
}
escapePos = next;
while (css3.charCodeAt(escapePos - 1) === BACKSLASH) {
escapePos -= 1;
escaped = !escaped;
}
} while (escaped);
currentToken = ["string", css3.slice(pos, next + 1), pos, next];
pos = next;
break;
}
case AT: {
RE_AT_END.lastIndex = pos + 1;
RE_AT_END.test(css3);
if (RE_AT_END.lastIndex === 0) {
next = css3.length - 1;
} else {
next = RE_AT_END.lastIndex - 2;
}
currentToken = ["at-word", css3.slice(pos, next + 1), pos, next];
pos = next;
break;
}
case BACKSLASH: {
next = pos;
escape = true;
while (css3.charCodeAt(next + 1) === BACKSLASH) {
next += 1;
escape = !escape;
}
code = css3.charCodeAt(next + 1);
if (escape && code !== SLASH && code !== SPACE3 && code !== NEWLINE && code !== TAB4 && code !== CR && code !== FEED) {
next += 1;
if (RE_HEX_ESCAPE.test(css3.charAt(next))) {
while (RE_HEX_ESCAPE.test(css3.charAt(next + 1))) {
next += 1;
}
if (css3.charCodeAt(next + 1) === SPACE3) {
next += 1;
}
}
}
currentToken = ["word", css3.slice(pos, next + 1), pos, next];
pos = next;
break;
}
default: {
if (code === SLASH && css3.charCodeAt(pos + 1) === ASTERISK) {
next = css3.indexOf("*/", pos + 2) + 1;
if (next === 0) {
if (ignore || ignoreUnclosed) {
next = css3.length;
} else {
unclosed("comment");
}
}
currentToken = ["comment", css3.slice(pos, next + 1), pos, next];
pos = next;
} else {
RE_WORD_END.lastIndex = pos + 1;
RE_WORD_END.test(css3);
if (RE_WORD_END.lastIndex === 0) {
next = css3.length - 1;
} else {
next = RE_WORD_END.lastIndex - 2;
}
currentToken = ["word", css3.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/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 Root2 = 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 index = this.index(child);
if (!ignore && index === 0 && this.nodes.length > 1) {
this.nodes[1].raws.before = this.nodes[index].raws.before;
}
return super.removeChild(child);
}
toResult(opts = {}) {
let lazy = new LazyResult(new Processor2(), this, opts);
return lazy.stringify();
}
};
Root2.registerLazyResult = (dependant) => {
LazyResult = dependant;
};
Root2.registerProcessor = (dependant) => {
Processor2 = dependant;
};
module.exports = Root2;
Root2.default = Root2;
Container.registerRoot(Root2);
}
});
// 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 {
constructor(defaults2) {
super(defaults2);
this.type = "rule";
if (!this.nodes) this.nodes = [];
}
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);
}
};
module.exports = Rule;
Rule.default = Rule;
Container.registerRule(Rule);
}
});
// node_modules/postcss/lib/parser.js
var require_parser = __commonJS({
"node_modules/postcss/lib/parser.js"(exports, module) {
"use strict";
var Declaration = require_declaration();
var tokenizer = require_tokenize();
var Comment = require_comment();
var AtRule = require_at_rule();
var Root2 = require_root();
var Rule = require_rule();
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;
}
}
var Parser = class {
constructor(input) {
this.input = input;
this.root = new Root2();
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 shift;
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) {
shift = params.length - 1;
prev = params[shift];
while (prev && prev[0] === "space") {
prev = params[--shift];
}
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 token, type, prev;
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 (/^\s*$/.test(text)) {
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++;
while (tokens[0][0] !== "word") {
if (tokens.length === 1) this.unknownWord(tokens);
node.raws.before += tokens.shift()[1];
}
node.source.start = this.getPosition(tokens[0][2]);
node.prop = "";
while (tokens.length) {
let type = tokens[0][0];
if (type === ":" || type === "space" || type === "comment") {
break;
}
node.prop += tokens.shift()[1];
}
node.raws.between = "";
let token;
while (tokens.length) {
token = tokens.shift();
if (token[0] === ":") {
node.raws.between += token[1];
break;
} else {
if (token[0] === "word" && /\w/.test(token[1])) {
this.unknownWord([token]);
}
node.raws.between += token[1];
}
}
if (node.prop[0] === "_" || node.prop[0] === "*") {
node.raws.before += node.prop[0];
node.prop = node.prop.slice(1);
}
let firstSpaces = [];
let next;
while (tokens.length) {
next = tokens[0][0];
if (next !== "space" && next !== "comment") break;
firstSpaces.push(tokens.shift());
}
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().indexOf("!") === 0 && type !== "space") {
break;
}
str = cache.pop()[1] + str;
}
if (str.trim().indexOf("!") === 0) {
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 = "";
}
}
}
// Helpers
getPosition(offset) {
let pos = this.input.fromOffset(offset);
return {
column: pos.col,
line: pos.line,
offset
};
}
init(node, offset) {
this.current.push(node);
node.source = {
input: this.input,
start: this.getPosition(offset)
};
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",
{ 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 Parser = require_parser();
var Input = require_input();
function parse4(css3, opts) {
let input = new Input(css3, 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 {
constructor(processor, root, opts) {
this.processor = processor;
this.messages = [];
this.root = root;
this.opts = opts;
this.css = void 0;
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");
}
get content() {
return this.css;
}
};
module.exports = Result;
Result.default = Result;
}
});
// 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 stringify2 = require_stringify();
var warnOnce = require_warn_once();
var parse4 = require_parse();
var Result = require_result();
var NoWorkResult = class {
constructor(processor, css3, opts) {
css3 = css3.toString();
this.stringified = false;
this._processor = processor;
this._css = css3;
this._opts = opts;
this._map = void 0;
let root;
let str = stringify2;
this.result = new Result(this._processor, root, this._opts);
this.result.css = css3;
let self = this;
Object.defineProperty(this.result, "root", {
get() {
return self.root;
}
});
let map = new MapGenerator(str, root, this._opts, css3);
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 [];
}
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 (error) {
this.error = error;
}
if (this.error) {
throw this.error;
} else {
this._root = root;
return root;
}
}
get [Symbol.toStringTag]() {
return "NoWorkResult";
}
};
module.exports = NoWorkResult;
NoWorkResult.default = NoWorkResult;
}
});
// 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;
}
});
// node_modules/postcss/lib/lazy-result.js
var require_lazy_result = __commonJS({
"node_modules/postcss/lib/lazy-result.js"(exports, module) {
"use strict";
var { isClean, my } = require_symbols();
var MapGenerator = require_map_generator();
var stringify2 = require_stringify();
var Container = require_container();
var Document = require_document();
var warnOnce = require_warn_once();
var Result = require_result();
var parse4 = require_parse();
var Root2 = require_root();
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 {
constructor(processor, css3, opts) {
this.stringified = false;
this.processed = false;
let root;
if (typeof css3 === "object" && css3 !== null && (css3.type === "root" || css3.type === "document")) {
root = cleanMarks(css3);
} else if (css3 instanceof _LazyResult || css3 instanceof Result) {
root = cleanMarks(css3.root);
if (css3.map) {
if (typeof opts.map === "undefined") opts.map = {};
if (!opts.map.inline) opts.map.inline = false;
opts.map.prev = css3.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(css3, opts);
} catch (error) {
this.processed = true;
this.error = error;
}
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(error, node) {
let plugin = this.result.lastPlugin;
try {
if (node) node.addToError(error);
this.error = error;
if (error.name === "CssSyntaxError" && !error.plugin) {
error.plugin = plugin.postcssPlugin;
error.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 error;
}
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 (error) {
throw this.handleError(error);
}
}
}
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 (error) {
throw this.handleError(error);
}
}
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 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();
}
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";
}
};
LazyResult.registerPostcss = (dependant) => {
postcss = dependant;
};
module.exports = LazyResult;
LazyResult.default = LazyResult;
Root2.registerLazyResult(LazyResult);
Document.registerLazyResult(LazyResult);
}
});
// node_modules/postcss/lib/processor.js
var require_processor = __commonJS({
"node_modules/postcss/lib/processor.js"(exports, module) {
"use strict";
var NoWorkResult = require_no_work_result();
var LazyResult = require_lazy_result();
var Document = require_document();
var Root2 = require_root();
var Processor2 = class {
constructor(plugins = []) {
this.version = "8.4.38";
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(css3, opts = {}) {
if (!this.plugins.length && !opts.parser && !opts.stringifier && !opts.syntax) {
return new NoWorkResult(this, css3, opts);
} else {
return new LazyResult(this, css3, opts);
}
}
use(plugin) {
this.plugins = this.plugins.concat(this.normalize([plugin]));
return this;
}
};
module.exports = Processor2;
Processor2.default = Processor2;
Root2.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;
});
}
}
});
// packages/block-editor/node_modules/postcss-value-parser/lib/parse.js
var require_parse2 = __commonJS({
"packages/block-editor/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 max = value.length;
var stack = [{ nodes: tokens }];
var balanced = 0;
var parent;
var name = "";
var before = "";
var after = "";
while (pos < max) {
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 < max && !(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;
};
}
});
// packages/block-editor/node_modules/postcss-value-parser/lib/walk.js
var require_walk = __commonJS({
"packages/block-editor/node_modules/postcss-value-parser/lib/walk.js"(exports, module) {
module.exports = function walk(nodes, cb, bubble) {
var i2, max, node, result;
for (i2 = 0, max = nodes.length; i2 < max; 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);
}
}
};
}
});
// packages/block-editor/node_modules/postcss-value-parser/lib/stringify.js
var require_stringify2 = __commonJS({
"packages/block-editor/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;
}
});
// packages/block-editor/node_modules/postcss-value-parser/lib/unit.js
var require_unit = __commonJS({
"packages/block-editor/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)
};
};
}
});
// packages/block-editor/node_modules/postcss-value-parser/lib/index.js
var require_lib2 = __commonJS({
"packages/block-editor/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/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;
}
});
// 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) ? deepmerge(emptyTarget(value), value, options) : value;
}
function defaultArrayMerge(target, source, options) {
return target.concat(source).map(function(element) {
return cloneUnlessOtherwiseSpecified(element, options);
});
}
function getMergeFunction(key, options) {
if (!options.customMerge) {
return deepmerge;
}
var customMerge = options.customMerge(key);
return typeof customMerge === "function" ? customMerge : deepmerge;
}
function getEnumerableOwnPropertySymbols(target) {
return Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(target).filter(function(symbol) {
return Object.propertyIsEnumerable.call(target, symbol);
}) : [];
}
function getKeys(target) {
return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target));
}
function propertyIsOnObject(object, property) {
try {
return property in object;
} catch (_) {
return false;
}
}
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 deepmerge(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);
}
}
deepmerge.all = function deepmergeAll(array, options) {
if (!Array.isArray(array)) {
throw new Error("first argument should be an array");
}
return array.reduce(function(prev, next) {
return deepmerge(prev, next, options);
}, {});
};
var deepmerge_1 = deepmerge;
module.exports = deepmerge_1;
}
});
// 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_default2,
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,
__experimentalGetElementClassName: () => __experimentalGetElementClassName,
__experimentalGetGapCSSValue: () => getGapCSSValue,
__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: () => __experimentalUseGradient,
__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: () => __unstableRichTextInputEvent,
__unstableUseBlockSelectionClearer: () => useBlockSelectionClearer,
__unstableUseClipboardHandler: () => __unstableUseClipboardHandler,
__unstableUseMouseMoveTypingReset: () => useMouseMoveTypingReset,
__unstableUseTypewriter: () => useTypewriter,
__unstableUseTypingObserver: () => useTypingObserver,
createCustomColorsHOC: () => createCustomColorsHOC,
getColorClassName: () => getColorClassName,
getColorObjectByAttributeValues: () => getColorObjectByAttributeValues,
getColorObjectByColorValue: () => getColorObjectByColorValue,
getComputedFluidTypographyValue: () => getComputedFluidTypographyValue,
getCustomValueFromPreset: () => getCustomValueFromPreset,
getFontSize: () => getFontSize,
getFontSizeClass: () => getFontSizeClass,
getFontSizeObjectByValue: () => getFontSizeObjectByValue,
getGradientSlugByValue: () => getGradientSlugByValue,
getGradientValueBySlug: () => getGradientValueBySlug,
getPxFromCssUnit: () => get_px_from_css_unit_default,
getSpacingPresetCssVar: () => getSpacingPresetCssVar,
getTypographyClassesAndStyles: () => getTypographyClassesAndStyles,
isValueSpacingPreset: () => isValueSpacingPreset,
privateApis: () => privateApis12,
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_blocks95 = __toESM(require_blocks(), 1);
var import_element221 = __toESM(require_element(), 1);
var import_data177 = __toESM(require_data(), 1);
var import_compose91 = __toESM(require_compose(), 1);
var import_hooks13 = __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 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_element9 = __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_data7 = __toESM(require_data(), 1);
var import_deprecated5 = __toESM(require_deprecated(), 1);
// packages/block-editor/build-module/components/block-edit/index.mjs
var import_element8 = __toESM(require_element(), 1);
var import_blocks9 = __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 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.");
const isInternal = val?.startsWith("#") && (0, import_url.isValidFragment)(val);
return protocolIsValid || isWWW || isInternal || mayBeTLD;
}
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";
function hasPatternOverridesDefaultBinding(bindings) {
return bindings?.[DEFAULT_ATTRIBUTE]?.source === PATTERN_OVERRIDES_SOURCE;
}
function replacePatternOverridesDefaultBinding(bindings, supportedAttributes) {
if (hasPatternOverridesDefaultBinding(bindings)) {
const bindingsWithDefaults = {};
for (const attributeName of supportedAttributes) {
const bindingSource = bindings[attributeName] ? bindings[attributeName] : { source: PATTERN_OVERRIDES_SOURCE };
bindingsWithDefaults[attributeName] = bindingSource;
}
return bindingsWithDefaults;
}
return bindings;
}
// 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 DEFAULT_BLOCK_CONTEXT = {};
var Edit = (props) => {
const { name } = props;
const blockType = (0, import_blocks.getBlockType)(name);
if (!blockType) {
return null;
}
const Component7 = blockType.edit || blockType.save;
return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Component7, { ...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)(() => {
const computedContext = blockType?.usesContext ? Object.fromEntries(
Object.entries(blockContext).filter(
([key]) => blockType.usesContext.includes(key)
)
) : DEFAULT_BLOCK_CONTEXT;
if (attributes?.metadata?.bindings) {
Object.values(attributes?.metadata?.bindings || {}).forEach(
(binding) => {
registeredSources[binding?.source]?.usesContext?.forEach(
(key) => {
computedContext[key] = blockContext[key];
}
);
}
);
}
return {
blockBindings: replacePatternOverridesDefaultBinding(
attributes?.metadata?.bindings,
bindableAttributes
),
context: computedContext,
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((attr) => {
values[attr] = 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_blocks8 = __toESM(require_blocks(), 1);
var import_components4 = __toESM(require_components(), 1);
var import_data6 = __toESM(require_data(), 1);
var import_i18n7 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/store/index.mjs
var import_data5 = __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,
// 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, index) {
return [
...array.slice(0, index),
...Array.isArray(elements) ? elements : [elements],
...array.slice(index)
];
}
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 sectionRootClientIdKey = /* @__PURE__ */ Symbol("sectionRootClientIdKey");
var mediaEditKey = /* @__PURE__ */ Symbol("mediaEditKey");
var getMediaSelectKey = /* @__PURE__ */ Symbol("getMediaSelect");
var essentialFormatKey = /* @__PURE__ */ Symbol("essentialFormat");
var isIsolatedEditorKey = /* @__PURE__ */ Symbol("isIsolatedEditor");
var deviceTypeKey = /* @__PURE__ */ Symbol("deviceTypeKey");
// 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[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 = (reducer4) => (state = {}, action) => {
const newState = reducer4(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 "SYNC_DERIVED_BLOCK_ATTRIBUTES":
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;
}
case "SAVE_REUSABLE_BLOCK_SUCCESS": {
const updatedBlockUids = [];
newState.attributes.forEach((attributes, clientId) => {
if (newState.byClientId.get(clientId).name === "core/block" && attributes.ref === action.updatedId) {
updatedBlockUids.push(clientId);
}
});
newState.tree = new Map(newState.tree);
updatedBlockUids.forEach((clientId) => {
newState.tree.set(clientId, {
...newState.byClientId.get(clientId),
attributes: newState.attributes.get(clientId),
innerBlocks: newState.tree.get(clientId).innerBlocks
});
});
updateParentInnerBlocksInTree(
newState,
updatedBlockUids,
false
);
}
}
return newState;
};
function withPersistentBlockChange(reducer4) {
let lastAction;
let markNextChangeAsNotPersistent = false;
let explicitPersistent;
return (state, action) => {
let nextState = reducer4(state, action);
let nextIsPersistentChange;
if (action.type === "SET_EXPLICIT_PERSISTENT") {
explicitPersistent = action.isPersistentChange;
nextIsPersistentChange = state.isPersistentChange ?? true;
}
if (explicitPersistent !== void 0) {
nextIsPersistentChange = explicitPersistent;
return nextIsPersistentChange === nextState.isPersistentChange ? nextState : {
...nextState,
isPersistentChange: nextIsPersistentChange
};
}
const isExplicitPersistentChange = action.type === "MARK_LAST_CHANGE_AS_PERSISTENT" || markNextChangeAsNotPersistent;
if (state === nextState && !isExplicitPersistentChange) {
markNextChangeAsNotPersistent = action.type === "MARK_NEXT_CHANGE_AS_NOT_PERSISTENT";
nextIsPersistentChange = state?.isPersistentChange ?? true;
if (state.isPersistentChange === nextIsPersistentChange) {
return state;
}
return {
...nextState,
isPersistentChange: nextIsPersistentChange
};
}
nextState = {
...nextState,
isPersistentChange: isExplicitPersistentChange ? !markNextChangeAsNotPersistent : !isUpdatingSameBlockAttribute(action, lastAction)
};
lastAction = action;
markNextChangeAsNotPersistent = action.type === "MARK_NEXT_CHANGE_AS_NOT_PERSISTENT";
return nextState;
};
}
function withIgnoredBlockChange(reducer4) {
const IGNORED_ACTION_TYPES = /* @__PURE__ */ new Set(["RECEIVE_BLOCKS"]);
return (state, action) => {
const nextState = reducer4(state, action);
if (nextState !== state) {
nextState.isIgnoredChange = IGNORED_ACTION_TYPES.has(action.type);
}
return nextState;
};
}
var withInnerBlocksRemoveCascade = (reducer4) => (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 reducer4(state, action);
};
var withBlockReset = (reducer4) => (state, action) => {
if (action.type === "RESET_BLOCKS") {
const newState = {
...state,
byClientId: new Map(
getFlattenedBlocksWithoutAttributes(action.blocks)
),
attributes: new Map(getFlattenedBlockAttributes(action.blocks)),
order: mapBlockOrder(action.blocks),
parents: new Map(mapBlockParents(action.blocks)),
controlledInnerBlocks: {}
};
newState.tree = new Map(state?.tree);
updateBlockTreeForBlocks(newState, action.blocks);
newState.tree.set("", {
innerBlocks: action.blocks.map(
(subBlock) => newState.tree.get(subBlock.clientId)
)
});
return newState;
}
return reducer4(state, action);
};
var withReplaceInnerBlocks = (reducer4) => (state, action) => {
if (action.type !== "REPLACE_INNER_BLOCKS") {
return reducer4(state, action);
}
const nestedControllers = {};
if (Object.keys(state.controlledInnerBlocks).length) {
const stack = [...action.blocks];
while (stack.length) {
const { innerBlocks, ...block } = stack.shift();
stack.push(...innerBlocks);
if (!!state.controlledInnerBlocks[block.clientId]) {
nestedControllers[block.clientId] = true;
}
}
}
let stateAfterBlocksRemoval = state;
if (state.order.get(action.rootClientId)) {
stateAfterBlocksRemoval = reducer4(stateAfterBlocksRemoval, {
type: "REMOVE_BLOCKS",
keepControlledInnerBlocks: nestedControllers,
clientIds: state.order.get(action.rootClientId)
});
}
let stateAfterInsert = stateAfterBlocksRemoval;
if (action.blocks.length) {
stateAfterInsert = reducer4(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 withSaveReusableBlock = (reducer4) => (state, action) => {
if (state && action.type === "SAVE_REUSABLE_BLOCK_SUCCESS") {
const { id, updatedId } = action;
if (id === updatedId) {
return state;
}
state = { ...state };
state.attributes = new Map(state.attributes);
state.attributes.forEach((attributes, clientId) => {
const { name } = state.byClientId.get(clientId);
if (name === "core/block" && attributes.ref === id) {
state.attributes.set(clientId, {
...attributes,
ref: updatedId
});
}
});
}
return reducer4(state, action);
};
var withResetControlledBlocks = (reducer4) => (state, action) => {
if (action.type === "SET_HAS_CONTROLLED_INNER_BLOCKS") {
const tempState = reducer4(state, {
type: "REPLACE_INNER_BLOCKS",
rootClientId: action.clientId,
blocks: []
});
return reducer4(tempState, action);
}
return reducer4(state, action);
};
var blocks = (0, import_compose.pipe)(
import_data2.combineReducers,
withSaveReusableBlock,
// Needs to be before withBlockCache.
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 "SYNC_DERIVED_BLOCK_ATTRIBUTES":
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 = subState.length } = action;
const newState = new Map(state);
mappedBlocks.forEach((order, clientId) => {
newState.set(clientId, order);
});
newState.set(
rootClientId,
insertAt(
subState,
mappedBlocks.get(rootClientId),
index
)
);
return newState;
}
case "MOVE_BLOCKS_TO_POSITION": {
const {
fromRootClientId = "",
toRootClientId = "",
clientIds
} = action;
const { index = state.get(toRootClientId).length } = action;
if (fromRootClientId === toRootClientId) {
const subState = state.get(toRootClientId);
const fromIndex = subState.indexOf(clientIds[0]);
const newState2 = new Map(state);
newState2.set(
toRootClientId,
moveTo(
state.get(toRootClientId),
fromIndex,
index,
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, index)
);
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 = {}, { type, clientId, hasControlledInnerBlocks }) {
if (type === "SET_HAS_CONTROLLED_INNER_BLOCKS") {
return {
...state,
[clientId]: hasControlledInnerBlocks
};
}
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 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,
__unstableWithInserter,
operation,
nearestSide
} = action;
const nextState = {
rootClientId,
index,
__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 = {}, action) => {
switch (action.type) {
// Even if the replaced blocks have the same client ID, our logic
// should correct the state.
case "REPLACE_BLOCKS":
case "REMOVE_BLOCKS": {
return Object.fromEntries(
Object.entries(state).filter(
([id]) => !action.clientIds.includes(id)
)
);
}
case "UPDATE_BLOCK_LIST_SETTINGS": {
const updates = typeof action.clientId === "string" ? { [action.clientId]: action.settings } : action.clientId;
for (const clientId in updates) {
if (!updates[clientId]) {
if (!state[clientId]) {
delete updates[clientId];
}
} else if ((0, import_es6.default)(state[clientId], updates[clientId])) {
delete updates[clientId];
}
}
if (Object.keys(updates).length === 0) {
return state;
}
const merged = { ...state, ...updates };
for (const clientId in updates) {
if (!updates[clientId]) {
delete merged[clientId];
}
}
return merged;
}
}
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;
}
return state;
}
function 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;
}
case "RESET_BLOCKS": {
return state.has("") ? (/* @__PURE__ */ new Map()).set("", state.get("")) : state;
}
}
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;
}
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,
blockEditingModes,
styleOverrides,
removalPromptData,
blockRemovalRules,
registeredInserterMediaCategories,
zoomLevel,
hasBlockSpotlight
});
function getBlockTreeBlock(state, clientId) {
if (clientId === "") {
const rootBlock = state.blocks.tree.get(clientId);
if (!rootBlock) {
return;
}
return {
clientId: "",
...rootBlock
};
}
if (!state.blocks.controlledInnerBlocks[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.blockEditingModes).some(
([, mode2]) => mode2 === "disabled"
);
const templatePartClientIds = [];
const syncedPatternClientIds = [];
Object.keys(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 = Object.keys(
state.blockListSettings
).filter(
(clientId) => state.blockListSettings[clientId]?.templateLock === "contentOnly"
);
const isIsolatedEditor = state.settings?.[isIsolatedEditorKey];
const unsyncedPatternClientIds = !!window?.__experimentalContentOnlyPatternInsertion && !isIsolatedEditor ? Array.from(state.blocks.attributes.keys()).filter(
(clientId) => state.blocks.attributes.get(clientId)?.metadata?.patternName
) : [];
const contentOnlyParents = [
...contentOnlyTemplateLockedClientIds,
...unsyncedPatternClientIds,
...window?.__experimentalContentOnlyPatternInsertion && !isIsolatedEditor ? templatePartClientIds : []
];
traverseBlockTree(state, treeClientId, (block) => {
const { clientId, name: blockName } = block;
if (state.editedContentOnlySection) {
if (state.editedContentOnlySection === clientId) {
derivedBlockEditingModes.set(clientId, "default");
return;
}
const parentTempEditedClientId = findParentInClientIdsList(
state,
clientId,
[state.editedContentOnlySection]
);
if (parentTempEditedClientId) {
derivedBlockEditingModes.set(clientId, "default");
return;
}
if (window?.__experimentalContentOnlyPatternInsertion) {
derivedBlockEditingModes.set(clientId, "disabled");
return;
}
}
if (state.blockEditingModes.has(clientId)) {
return;
}
if (hasDisabledBlocks) {
let ancestorBlockEditingMode;
let parent = state.blocks.parents.get(clientId);
while (parent !== void 0) {
if (state.blockEditingModes.has(parent)) {
ancestorBlockEditingMode = state.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 parentPatternClientId = findParentInClientIdsList(
state,
clientId,
syncedPatternClientIds
);
if (parentPatternClientId) {
if (findParentInClientIdsList(
state,
parentPatternClientId,
syncedPatternClientIds
)) {
derivedBlockEditingModes.set(clientId, "disabled");
return;
}
if (hasBindings(block)) {
derivedBlockEditingModes.set(clientId, "contentOnly");
return;
}
derivedBlockEditingModes.set(clientId, "disabled");
}
}
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(reducer4) {
return (state, action) => {
const nextState = reducer4(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 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[clientId]?.templateLock !== "contentOnly" && nextState.blockListSettings[clientId]?.templateLock === "contentOnly";
const wasContentOnlyBlock = state.blockListSettings[clientId]?.templateLock === "contentOnly" && nextState.blockListSettings[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]) {
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(reducer4) {
return (state, action) => {
const nextState = reducer4(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,
__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_blocks6 = __toESM(require_blocks(), 1);
var import_element6 = __toESM(require_element(), 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 = 24, ...props }, ref) => {
return (0, import_element5.cloneElement)(icon, {
width: size,
height: size,
...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", 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", 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", 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", 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", 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", 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", 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", 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", 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, { viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", 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", 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, { viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
import_primitives12.Path,
{
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",
fillRule: "evenodd",
clipRule: "evenodd"
}
) });
// packages/icons/build-module/library/check.mjs
var import_primitives13 = __toESM(require_primitives(), 1);
var import_jsx_runtime15 = __toESM(require_jsx_runtime(), 1);
var check_default = /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(import_primitives13.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(import_primitives13.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_primitives14 = __toESM(require_primitives(), 1);
var import_jsx_runtime16 = __toESM(require_jsx_runtime(), 1);
var chevron_down_default = /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(import_primitives14.SVG, { viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(import_primitives14.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_primitives15 = __toESM(require_primitives(), 1);
var import_jsx_runtime17 = __toESM(require_jsx_runtime(), 1);
var chevron_left_small_default = /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(import_primitives15.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(import_primitives15.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_primitives16 = __toESM(require_primitives(), 1);
var import_jsx_runtime18 = __toESM(require_jsx_runtime(), 1);
var chevron_left_default = /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(import_primitives16.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(import_primitives16.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_primitives17 = __toESM(require_primitives(), 1);
var import_jsx_runtime19 = __toESM(require_jsx_runtime(), 1);
var chevron_right_small_default = /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(import_primitives17.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(import_primitives17.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_primitives18 = __toESM(require_primitives(), 1);
var import_jsx_runtime20 = __toESM(require_jsx_runtime(), 1);
var chevron_right_default = /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(import_primitives18.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(import_primitives18.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_primitives19 = __toESM(require_primitives(), 1);
var import_jsx_runtime21 = __toESM(require_jsx_runtime(), 1);
var chevron_up_default = /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(import_primitives19.SVG, { viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(import_primitives19.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_primitives20 = __toESM(require_primitives(), 1);
var import_jsx_runtime22 = __toESM(require_jsx_runtime(), 1);
var close_small_default = /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(import_primitives20.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(import_primitives20.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_primitives21 = __toESM(require_primitives(), 1);
var import_jsx_runtime23 = __toESM(require_jsx_runtime(), 1);
var cog_default = /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(import_primitives21.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(
import_primitives21.Path,
{
fillRule: "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",
clipRule: "evenodd"
}
) });
// packages/icons/build-module/library/copy-small.mjs
var import_primitives22 = __toESM(require_primitives(), 1);
var import_jsx_runtime24 = __toESM(require_jsx_runtime(), 1);
var copy_small_default = /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(import_primitives22.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
import_primitives22.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_primitives23 = __toESM(require_primitives(), 1);
var import_jsx_runtime25 = __toESM(require_jsx_runtime(), 1);
var copy_default = /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(import_primitives23.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(
import_primitives23.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_primitives24 = __toESM(require_primitives(), 1);
var import_jsx_runtime26 = __toESM(require_jsx_runtime(), 1);
var corner_all_default = /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(import_primitives24.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
import_primitives24.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_primitives25 = __toESM(require_primitives(), 1);
var import_jsx_runtime27 = __toESM(require_jsx_runtime(), 1);
var corner_bottom_left_default = /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(import_primitives25.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: [
/* @__PURE__ */ (0, import_jsx_runtime27.jsx)(import_primitives25.G, { opacity: ".25", children: /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(import_primitives25.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_runtime27.jsx)(
import_primitives25.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_primitives26 = __toESM(require_primitives(), 1);
var import_jsx_runtime28 = __toESM(require_jsx_runtime(), 1);
var corner_bottom_right_default = /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(import_primitives26.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", 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: "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_primitives27 = __toESM(require_primitives(), 1);
var import_jsx_runtime29 = __toESM(require_jsx_runtime(), 1);
var corner_top_left_default = /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(import_primitives27.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", 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: "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_primitives28 = __toESM(require_primitives(), 1);
var import_jsx_runtime30 = __toESM(require_jsx_runtime(), 1);
var corner_top_right_default = /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(import_primitives28.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", 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: "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_primitives29 = __toESM(require_primitives(), 1);
var import_jsx_runtime31 = __toESM(require_jsx_runtime(), 1);
var desktop_default = /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(import_primitives29.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(import_primitives29.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_primitives30 = __toESM(require_primitives(), 1);
var import_jsx_runtime32 = __toESM(require_jsx_runtime(), 1);
var drag_handle_default = /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(import_primitives30.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(import_primitives30.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_primitives31 = __toESM(require_primitives(), 1);
var import_jsx_runtime33 = __toESM(require_jsx_runtime(), 1);
var envelope_default = /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(import_primitives31.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
import_primitives31.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_primitives32 = __toESM(require_primitives(), 1);
var import_jsx_runtime34 = __toESM(require_jsx_runtime(), 1);
var error_default = /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(import_primitives32.SVG, { viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(
import_primitives32.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_primitives33 = __toESM(require_primitives(), 1);
var import_jsx_runtime35 = __toESM(require_jsx_runtime(), 1);
var external_default = /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(import_primitives33.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(import_primitives33.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_primitives34 = __toESM(require_primitives(), 1);
var import_jsx_runtime36 = __toESM(require_jsx_runtime(), 1);
var file_default = /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(import_primitives34.SVG, { viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
import_primitives34.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_primitives35 = __toESM(require_primitives(), 1);
var import_jsx_runtime37 = __toESM(require_jsx_runtime(), 1);
var filter_default = /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(import_primitives35.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(import_primitives35.Path, { d: "M12 4 4 19h16L12 4zm0 3.2 5.5 10.3H12V7.2z" }) });
// packages/icons/build-module/library/format-capitalize.mjs
var import_primitives36 = __toESM(require_primitives(), 1);
var import_jsx_runtime38 = __toESM(require_jsx_runtime(), 1);
var format_capitalize_default = /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(import_primitives36.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(import_primitives36.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_primitives37 = __toESM(require_primitives(), 1);
var import_jsx_runtime39 = __toESM(require_jsx_runtime(), 1);
var format_lowercase_default = /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(import_primitives37.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(import_primitives37.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_primitives38 = __toESM(require_primitives(), 1);
var import_jsx_runtime40 = __toESM(require_jsx_runtime(), 1);
var format_strikethrough_default = /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(import_primitives38.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(import_primitives38.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_primitives39 = __toESM(require_primitives(), 1);
var import_jsx_runtime41 = __toESM(require_jsx_runtime(), 1);
var format_underline_default = /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(import_primitives39.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(import_primitives39.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_primitives40 = __toESM(require_primitives(), 1);
var import_jsx_runtime42 = __toESM(require_jsx_runtime(), 1);
var format_uppercase_default = /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(import_primitives40.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(import_primitives40.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/fullscreen.mjs
var import_primitives41 = __toESM(require_primitives(), 1);
var import_jsx_runtime43 = __toESM(require_jsx_runtime(), 1);
var fullscreen_default = /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(import_primitives41.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(import_primitives41.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_primitives42 = __toESM(require_primitives(), 1);
var import_jsx_runtime44 = __toESM(require_jsx_runtime(), 1);
var globe_default = /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(import_primitives42.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(import_primitives42.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_primitives43 = __toESM(require_primitives(), 1);
var import_jsx_runtime45 = __toESM(require_jsx_runtime(), 1);
var grid_default = /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(import_primitives43.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(
import_primitives43.Path,
{
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",
fillRule: "evenodd",
clipRule: "evenodd"
}
) });
// packages/icons/build-module/library/group.mjs
var import_primitives44 = __toESM(require_primitives(), 1);
var import_jsx_runtime46 = __toESM(require_jsx_runtime(), 1);
var group_default = /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_primitives44.SVG, { viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_primitives44.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_primitives45 = __toESM(require_primitives(), 1);
var import_jsx_runtime47 = __toESM(require_jsx_runtime(), 1);
var heading_level_1_default = /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(import_primitives45.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(import_primitives45.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_primitives46 = __toESM(require_primitives(), 1);
var import_jsx_runtime48 = __toESM(require_jsx_runtime(), 1);
var heading_level_2_default = /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(import_primitives46.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(import_primitives46.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_primitives47 = __toESM(require_primitives(), 1);
var import_jsx_runtime49 = __toESM(require_jsx_runtime(), 1);
var heading_level_3_default = /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(import_primitives47.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(import_primitives47.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_primitives48 = __toESM(require_primitives(), 1);
var import_jsx_runtime50 = __toESM(require_jsx_runtime(), 1);
var heading_level_4_default = /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(import_primitives48.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(import_primitives48.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_primitives49 = __toESM(require_primitives(), 1);
var import_jsx_runtime51 = __toESM(require_jsx_runtime(), 1);
var heading_level_5_default = /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(import_primitives49.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(import_primitives49.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_primitives50 = __toESM(require_primitives(), 1);
var import_jsx_runtime52 = __toESM(require_jsx_runtime(), 1);
var heading_level_6_default = /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(import_primitives50.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(import_primitives50.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_primitives51 = __toESM(require_primitives(), 1);
var import_jsx_runtime53 = __toESM(require_jsx_runtime(), 1);
var home_default = /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(import_primitives51.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(import_primitives51.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_primitives52 = __toESM(require_primitives(), 1);
var import_jsx_runtime54 = __toESM(require_jsx_runtime(), 1);
var image_default = /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(import_primitives52.SVG, { viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(import_primitives52.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_primitives53 = __toESM(require_primitives(), 1);
var import_jsx_runtime55 = __toESM(require_jsx_runtime(), 1);
var info_default = /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(import_primitives53.SVG, { viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(
import_primitives53.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_primitives54 = __toESM(require_primitives(), 1);
var import_jsx_runtime56 = __toESM(require_jsx_runtime(), 1);
var justify_bottom_default = /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(import_primitives54.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(import_primitives54.Path, { d: "M15 4H9v11h6V4zM4 18.5V20h16v-1.5H4z" }) });
// packages/icons/build-module/library/justify-center-vertical.mjs
var import_primitives55 = __toESM(require_primitives(), 1);
var import_jsx_runtime57 = __toESM(require_jsx_runtime(), 1);
var justify_center_vertical_default = /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(import_primitives55.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(import_primitives55.Path, { d: "M20 11h-5V4H9v7H4v1.5h5V20h6v-7.5h5z" }) });
// packages/icons/build-module/library/justify-center.mjs
var import_primitives56 = __toESM(require_primitives(), 1);
var import_jsx_runtime58 = __toESM(require_jsx_runtime(), 1);
var justify_center_default = /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(import_primitives56.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(import_primitives56.Path, { d: "M12.5 15v5H11v-5H4V9h7V4h1.5v5h7v6h-7Z" }) });
// packages/icons/build-module/library/justify-left.mjs
var import_primitives57 = __toESM(require_primitives(), 1);
var import_jsx_runtime59 = __toESM(require_jsx_runtime(), 1);
var justify_left_default = /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(import_primitives57.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(import_primitives57.Path, { d: "M9 9v6h11V9H9zM4 20h1.5V4H4v16z" }) });
// packages/icons/build-module/library/justify-right.mjs
var import_primitives58 = __toESM(require_primitives(), 1);
var import_jsx_runtime60 = __toESM(require_jsx_runtime(), 1);
var justify_right_default = /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(import_primitives58.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(import_primitives58.Path, { d: "M4 15h11V9H4v6zM18.5 4v16H20V4h-1.5z" }) });
// packages/icons/build-module/library/justify-space-between-vertical.mjs
var import_primitives59 = __toESM(require_primitives(), 1);
var import_jsx_runtime61 = __toESM(require_jsx_runtime(), 1);
var justify_space_between_vertical_default = /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(import_primitives59.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(import_primitives59.Path, { d: "M7 4H17V8L7 8V4ZM7 16L17 16V20L7 20V16ZM20 11.25H4V12.75H20V11.25Z" }) });
// packages/icons/build-module/library/justify-space-between.mjs
var import_primitives60 = __toESM(require_primitives(), 1);
var import_jsx_runtime62 = __toESM(require_jsx_runtime(), 1);
var justify_space_between_default = /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(import_primitives60.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(import_primitives60.Path, { d: "M9 15h6V9H9v6zm-5 5h1.5V4H4v16zM18.5 4v16H20V4h-1.5z" }) });
// packages/icons/build-module/library/justify-stretch-vertical.mjs
var import_primitives61 = __toESM(require_primitives(), 1);
var import_jsx_runtime63 = __toESM(require_jsx_runtime(), 1);
var justify_stretch_vertical_default = /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(import_primitives61.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(import_primitives61.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_primitives62 = __toESM(require_primitives(), 1);
var import_jsx_runtime64 = __toESM(require_jsx_runtime(), 1);
var justify_stretch_default = /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(import_primitives62.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(import_primitives62.Path, { d: "M4 4H5.5V20H4V4ZM7 10L17 10V14L7 14V10ZM20 4H18.5V20H20V4Z" }) });
// packages/icons/build-module/library/justify-top.mjs
var import_primitives63 = __toESM(require_primitives(), 1);
var import_jsx_runtime65 = __toESM(require_jsx_runtime(), 1);
var justify_top_default = /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(import_primitives63.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(import_primitives63.Path, { d: "M9 20h6V9H9v11zM4 4v1.5h16V4H4z" }) });
// packages/icons/build-module/library/keyboard-return.mjs
var import_primitives64 = __toESM(require_primitives(), 1);
var import_jsx_runtime66 = __toESM(require_jsx_runtime(), 1);
var keyboard_return_default = /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(import_primitives64.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(import_primitives64.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_primitives65 = __toESM(require_primitives(), 1);
var import_jsx_runtime67 = __toESM(require_jsx_runtime(), 1);
var layout_default = /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(import_primitives65.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(import_primitives65.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_primitives66 = __toESM(require_primitives(), 1);
var import_jsx_runtime68 = __toESM(require_jsx_runtime(), 1);
var link_off_default = /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(import_primitives66.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(import_primitives66.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_primitives67 = __toESM(require_primitives(), 1);
var import_jsx_runtime69 = __toESM(require_jsx_runtime(), 1);
var link_default = /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(import_primitives67.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(import_primitives67.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_primitives68 = __toESM(require_primitives(), 1);
var import_jsx_runtime70 = __toESM(require_jsx_runtime(), 1);
var list_view_default = /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(import_primitives68.SVG, { viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(import_primitives68.Path, { d: "M3 6h11v1.5H3V6Zm3.5 5.5h11V13h-11v-1.5ZM21 17H10v1.5h11V17Z" }) });
// packages/icons/build-module/library/lock-outline.mjs
var import_primitives69 = __toESM(require_primitives(), 1);
var import_jsx_runtime71 = __toESM(require_jsx_runtime(), 1);
var lock_outline_default = /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(import_primitives69.SVG, { viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(import_primitives69.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_primitives70 = __toESM(require_primitives(), 1);
var import_jsx_runtime72 = __toESM(require_jsx_runtime(), 1);
var lock_small_default = /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(import_primitives70.SVG, { viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(
import_primitives70.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_primitives71 = __toESM(require_primitives(), 1);
var import_jsx_runtime73 = __toESM(require_jsx_runtime(), 1);
var lock_default = /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(import_primitives71.SVG, { viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", 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-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_primitives72 = __toESM(require_primitives(), 1);
var import_jsx_runtime74 = __toESM(require_jsx_runtime(), 1);
var media_default = /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(import_primitives72.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: [
/* @__PURE__ */ (0, import_jsx_runtime74.jsx)(import_primitives72.Path, { d: "m7 6.5 4 2.5-4 2.5z" }),
/* @__PURE__ */ (0, import_jsx_runtime74.jsx)(
import_primitives72.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_primitives73 = __toESM(require_primitives(), 1);
var import_jsx_runtime75 = __toESM(require_jsx_runtime(), 1);
var mobile_default = /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(import_primitives73.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(import_primitives73.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_primitives74 = __toESM(require_primitives(), 1);
var import_jsx_runtime76 = __toESM(require_jsx_runtime(), 1);
var more_vertical_default = /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(import_primitives74.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(import_primitives74.Path, { d: "M13 19h-2v-2h2v2zm0-6h-2v-2h2v2zm0-6h-2V5h2v2z" }) });
// packages/icons/build-module/library/page.mjs
var import_primitives75 = __toESM(require_primitives(), 1);
var import_jsx_runtime77 = __toESM(require_jsx_runtime(), 1);
var page_default = /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)(import_primitives75.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: [
/* @__PURE__ */ (0, import_jsx_runtime77.jsx)(import_primitives75.Path, { d: "M15.5 7.5h-7V9h7V7.5Zm-7 3.5h7v1.5h-7V11Zm7 3.5h-7V16h7v-1.5Z" }),
/* @__PURE__ */ (0, import_jsx_runtime77.jsx)(import_primitives75.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_primitives76 = __toESM(require_primitives(), 1);
var import_jsx_runtime78 = __toESM(require_jsx_runtime(), 1);
var paragraph_default = /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(import_primitives76.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(import_primitives76.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_primitives77 = __toESM(require_primitives(), 1);
var import_jsx_runtime79 = __toESM(require_jsx_runtime(), 1);
var pencil_default = /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(import_primitives77.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(import_primitives77.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_primitives78 = __toESM(require_primitives(), 1);
var import_jsx_runtime80 = __toESM(require_jsx_runtime(), 1);
var pin_small_default = /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(import_primitives78.SVG, { viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(import_primitives78.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_primitives79 = __toESM(require_primitives(), 1);
var import_jsx_runtime81 = __toESM(require_jsx_runtime(), 1);
var plus_default = /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(import_primitives79.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(import_primitives79.Path, { d: "M11 12.5V17.5H12.5V12.5H17.5V11H12.5V6H11V11H6V12.5H11Z" }) });
// packages/icons/build-module/library/position-center.mjs
var import_primitives80 = __toESM(require_primitives(), 1);
var import_jsx_runtime82 = __toESM(require_jsx_runtime(), 1);
var position_center_default = /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(import_primitives80.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(import_primitives80.Path, { d: "M19 5.5H5V4h14v1.5ZM19 20H5v-1.5h14V20ZM7 9h10v6H7V9Z" }) });
// packages/icons/build-module/library/position-left.mjs
var import_primitives81 = __toESM(require_primitives(), 1);
var import_jsx_runtime83 = __toESM(require_jsx_runtime(), 1);
var position_left_default = /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(import_primitives81.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(import_primitives81.Path, { d: "M5 5.5h8V4H5v1.5ZM5 20h8v-1.5H5V20ZM19 9H5v6h14V9Z" }) });
// packages/icons/build-module/library/position-right.mjs
var import_primitives82 = __toESM(require_primitives(), 1);
var import_jsx_runtime84 = __toESM(require_jsx_runtime(), 1);
var position_right_default = /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(import_primitives82.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(import_primitives82.Path, { d: "M19 5.5h-8V4h8v1.5ZM19 20h-8v-1.5h8V20ZM5 9h14v6H5V9Z" }) });
// packages/icons/build-module/library/post-featured-image.mjs
var import_primitives83 = __toESM(require_primitives(), 1);
var import_jsx_runtime85 = __toESM(require_jsx_runtime(), 1);
var post_featured_image_default = /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(import_primitives83.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(import_primitives83.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_primitives84 = __toESM(require_primitives(), 1);
var import_jsx_runtime86 = __toESM(require_jsx_runtime(), 1);
var post_list_default = /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(import_primitives84.SVG, { viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(import_primitives84.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/post.mjs
var import_primitives85 = __toESM(require_primitives(), 1);
var import_jsx_runtime87 = __toESM(require_jsx_runtime(), 1);
var post_default = /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(import_primitives85.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(import_primitives85.Path, { d: "m7.3 9.7 1.4 1.4c.2-.2.3-.3.4-.5 0 0 0-.1.1-.1.3-.5.4-1.1.3-1.6L12 7 9 4 7.2 6.5c-.6-.1-1.1 0-1.6.3 0 0-.1 0-.1.1-.3.1-.4.2-.6.4l1.4 1.4L4 11v1h1l2.3-2.3zM4 20h9v-1.5H4V20zm0-5.5V16h16v-1.5H4z" }) });
// packages/icons/build-module/library/reset.mjs
var import_primitives86 = __toESM(require_primitives(), 1);
var import_jsx_runtime88 = __toESM(require_jsx_runtime(), 1);
var reset_default = /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(import_primitives86.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(import_primitives86.Path, { d: "M7 11.5h10V13H7z" }) });
// packages/icons/build-module/library/rotate-right.mjs
var import_primitives87 = __toESM(require_primitives(), 1);
var import_jsx_runtime89 = __toESM(require_jsx_runtime(), 1);
var rotate_right_default = /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(import_primitives87.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(import_primitives87.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_primitives88 = __toESM(require_primitives(), 1);
var import_jsx_runtime90 = __toESM(require_jsx_runtime(), 1);
var row_default = /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(import_primitives88.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(import_primitives88.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_primitives89 = __toESM(require_primitives(), 1);
var import_jsx_runtime91 = __toESM(require_jsx_runtime(), 1);
var search_default = /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(import_primitives89.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(import_primitives89.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_primitives90 = __toESM(require_primitives(), 1);
var import_jsx_runtime92 = __toESM(require_jsx_runtime(), 1);
var seen_default = /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(import_primitives90.SVG, { viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(import_primitives90.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_primitives91 = __toESM(require_primitives(), 1);
var import_jsx_runtime93 = __toESM(require_jsx_runtime(), 1);
var settings_default = /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(import_primitives91.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: [
/* @__PURE__ */ (0, import_jsx_runtime93.jsx)(import_primitives91.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_runtime93.jsx)(import_primitives91.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_primitives92 = __toESM(require_primitives(), 1);
var import_jsx_runtime94 = __toESM(require_jsx_runtime(), 1);
var shadow_default = /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(import_primitives92.SVG, { viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(import_primitives92.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_primitives93 = __toESM(require_primitives(), 1);
var import_jsx_runtime95 = __toESM(require_jsx_runtime(), 1);
var sides_all_default = /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(import_primitives93.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(import_primitives93.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_primitives94 = __toESM(require_primitives(), 1);
var import_jsx_runtime96 = __toESM(require_jsx_runtime(), 1);
var sides_bottom_default = /* @__PURE__ */ (0, import_jsx_runtime96.jsxs)(import_primitives94.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", 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",
style: { opacity: 0.25 }
}
),
/* @__PURE__ */ (0, import_jsx_runtime96.jsx)(import_primitives94.Path, { d: "m16.5 19.5h-9v-1.5h9z" })
] });
// packages/icons/build-module/library/sides-horizontal.mjs
var import_primitives95 = __toESM(require_primitives(), 1);
var import_jsx_runtime97 = __toESM(require_jsx_runtime(), 1);
var sides_horizontal_default = /* @__PURE__ */ (0, import_jsx_runtime97.jsxs)(import_primitives95.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", 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: "m4.5 7.5v9h1.5v-9z" }),
/* @__PURE__ */ (0, import_jsx_runtime97.jsx)(import_primitives95.Path, { d: "m18 7.5v9h1.5v-9z" })
] });
// packages/icons/build-module/library/sides-left.mjs
var import_primitives96 = __toESM(require_primitives(), 1);
var import_jsx_runtime98 = __toESM(require_jsx_runtime(), 1);
var sides_left_default = /* @__PURE__ */ (0, import_jsx_runtime98.jsxs)(import_primitives96.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", 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 16.5v-9h1.5v9z" })
] });
// packages/icons/build-module/library/sides-right.mjs
var import_primitives97 = __toESM(require_primitives(), 1);
var import_jsx_runtime99 = __toESM(require_jsx_runtime(), 1);
var sides_right_default = /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)(import_primitives97.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", 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: "m18 16.5v-9h1.5v9z" })
] });
// packages/icons/build-module/library/sides-top.mjs
var import_primitives98 = __toESM(require_primitives(), 1);
var import_jsx_runtime100 = __toESM(require_jsx_runtime(), 1);
var sides_top_default = /* @__PURE__ */ (0, import_jsx_runtime100.jsxs)(import_primitives98.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", 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: "m16.5 6h-9v-1.5h9z" })
] });
// packages/icons/build-module/library/sides-vertical.mjs
var import_primitives99 = __toESM(require_primitives(), 1);
var import_jsx_runtime101 = __toESM(require_jsx_runtime(), 1);
var sides_vertical_default = /* @__PURE__ */ (0, import_jsx_runtime101.jsxs)(import_primitives99.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", 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: "m7.5 6h9v-1.5h-9z" }),
/* @__PURE__ */ (0, import_jsx_runtime101.jsx)(import_primitives99.Path, { d: "m7.5 19.5h9v-1.5h-9z" })
] });
// packages/icons/build-module/library/stack.mjs
var import_primitives100 = __toESM(require_primitives(), 1);
var import_jsx_runtime102 = __toESM(require_jsx_runtime(), 1);
var stack_default = /* @__PURE__ */ (0, import_jsx_runtime102.jsx)(import_primitives100.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime102.jsx)(import_primitives100.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_primitives101 = __toESM(require_primitives(), 1);
var import_jsx_runtime103 = __toESM(require_jsx_runtime(), 1);
var stretch_full_width_default = /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(import_primitives101.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(import_primitives101.Path, { d: "M5 4h14v11H5V4Zm11 16H8v-1.5h8V20Z" }) });
// packages/icons/build-module/library/stretch-wide.mjs
var import_primitives102 = __toESM(require_primitives(), 1);
var import_jsx_runtime104 = __toESM(require_jsx_runtime(), 1);
var stretch_wide_default = /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(import_primitives102.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(import_primitives102.Path, { d: "M16 5.5H8V4h8v1.5ZM16 20H8v-1.5h8V20ZM5 9h14v6H5V9Z" }) });
// packages/icons/build-module/library/styles.mjs
var import_primitives103 = __toESM(require_primitives(), 1);
var import_jsx_runtime105 = __toESM(require_jsx_runtime(), 1);
var styles_default = /* @__PURE__ */ (0, import_jsx_runtime105.jsx)(import_primitives103.SVG, { viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ (0, import_jsx_runtime105.jsx)(
import_primitives103.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_primitives104 = __toESM(require_primitives(), 1);
var import_jsx_runtime106 = __toESM(require_jsx_runtime(), 1);
var symbol_default = /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(import_primitives104.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(import_primitives104.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_primitives105 = __toESM(require_primitives(), 1);
var import_jsx_runtime107 = __toESM(require_jsx_runtime(), 1);
var tablet_default = /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(import_primitives105.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(import_primitives105.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_primitives106 = __toESM(require_primitives(), 1);
var import_jsx_runtime108 = __toESM(require_jsx_runtime(), 1);
var tag_default = /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(import_primitives106.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(import_primitives106.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_primitives107 = __toESM(require_primitives(), 1);
var import_jsx_runtime109 = __toESM(require_jsx_runtime(), 1);
var text_horizontal_default = /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(import_primitives107.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(import_primitives107.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_primitives108 = __toESM(require_primitives(), 1);
var import_jsx_runtime110 = __toESM(require_jsx_runtime(), 1);
var text_vertical_default = /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(import_primitives108.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(import_primitives108.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_primitives109 = __toESM(require_primitives(), 1);
var import_jsx_runtime111 = __toESM(require_jsx_runtime(), 1);
var trash_default = /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(import_primitives109.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(
import_primitives109.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_primitives110 = __toESM(require_primitives(), 1);
var import_jsx_runtime112 = __toESM(require_jsx_runtime(), 1);
var ungroup_default = /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(import_primitives110.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(import_primitives110.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_primitives111 = __toESM(require_primitives(), 1);
var import_jsx_runtime113 = __toESM(require_jsx_runtime(), 1);
var unlock_default = /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(import_primitives111.SVG, { viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(import_primitives111.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_primitives112 = __toESM(require_primitives(), 1);
var import_jsx_runtime114 = __toESM(require_jsx_runtime(), 1);
var unseen_default = /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(import_primitives112.SVG, { viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(import_primitives112.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_primitives113 = __toESM(require_primitives(), 1);
var import_jsx_runtime115 = __toESM(require_jsx_runtime(), 1);
var upload_default = /* @__PURE__ */ (0, import_jsx_runtime115.jsx)(import_primitives113.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime115.jsx)(import_primitives113.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_primitives114 = __toESM(require_primitives(), 1);
var import_jsx_runtime116 = __toESM(require_jsx_runtime(), 1);
var verse_default = /* @__PURE__ */ (0, import_jsx_runtime116.jsx)(import_primitives114.SVG, { viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ (0, import_jsx_runtime116.jsx)(import_primitives114.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_primitives115 = __toESM(require_primitives(), 1);
var import_jsx_runtime117 = __toESM(require_jsx_runtime(), 1);
var video_default = /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(import_primitives115.SVG, { viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(import_primitives115.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_data4 = __toESM(require_data(), 1);
// packages/block-editor/build-module/store/utils.mjs
var import_blocks5 = __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, {
areBlocksHidden: () => areBlocksHidden,
areBlocksHiddenAnywhere: () => areBlocksHiddenAnywhere,
getAllPatterns: () => getAllPatterns,
getBlockRemovalRules: () => getBlockRemovalRules,
getBlockSettings: () => getBlockSettings,
getBlockStyles: () => getBlockStyles,
getBlockWithoutAttributes: () => getBlockWithoutAttributes,
getClosestAllowedInsertionPoint: () => getClosestAllowedInsertionPoint,
getClosestAllowedInsertionPointForPattern: () => getClosestAllowedInsertionPointForPattern,
getContentLockingParent: () => getContentLockingParent,
getEditedContentOnlySection: () => getEditedContentOnlySection,
getEnabledBlockParents: () => getEnabledBlockParents,
getEnabledClientIdsTree: () => getEnabledClientIdsTree,
getExpandedBlock: () => getExpandedBlock,
getInserterMediaCategories: () => getInserterMediaCategories,
getInsertionPoint: () => getInsertionPoint,
getLastFocus: () => getLastFocus,
getLastInsertedBlocksClientIds: () => getLastInsertedBlocksClientIds,
getParentSectionBlock: () => getParentSectionBlock,
getPatternBySlug: () => getPatternBySlug,
getRegisteredInserterMediaCategories: () => getRegisteredInserterMediaCategories,
getRemovalPromptData: () => getRemovalPromptData,
getReusableBlocks: () => getReusableBlocks,
getSectionRootClientId: () => getSectionRootClientId,
getStyleOverrides: () => getStyleOverrides,
getZoomLevel: () => getZoomLevel,
hasAllowedPatterns: () => hasAllowedPatterns,
hasBlockSpotlight: () => hasBlockSpotlight2,
isBlockHidden: () => isBlockHidden,
isBlockInterfaceHidden: () => isBlockInterfaceHidden2,
isBlockSubtreeDisabled: () => isBlockSubtreeDisabled,
isContainerInsertableToInContentOnlyMode: () => isContainerInsertableToInContentOnlyMode,
isDragging: () => isDragging2,
isEditLockedBlock: () => isEditLockedBlock,
isLockedBlock: () => isLockedBlock,
isMoveLockedBlock: () => isMoveLockedBlock,
isRemoveLockedBlock: () => isRemoveLockedBlock,
isSectionBlock: () => isSectionBlock,
isWithinEditedContentOnlySection: () => isWithinEditedContentOnlySection,
isZoomOut: () => isZoomOut
});
var import_data3 = __toESM(require_data(), 1);
var import_blocks4 = __toESM(require_blocks(), 1);
// 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_blocks3 = __toESM(require_blocks(), 1);
var import_hooks = __toESM(require_hooks(), 1);
// packages/block-editor/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/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_blocks3.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 = getValueFromObjectPath(
candidateAtts.settings?.blocks?.[blockName],
normalizedPath
) ?? getValueFromObjectPath(
candidateAtts.settings,
normalizedPath
);
if (result !== void 0) {
break;
}
}
const settings2 = getSettings(state);
if (result === void 0 && blockName) {
result = getValueFromObjectPath(
settings2.__experimentalFeatures?.blocks?.[blockName],
normalizedPath
);
}
if (result === void 0) {
result = getValueFromObjectPath(
settings2.__experimentalFeatures,
normalizedPath
);
}
if (result !== void 0) {
if (import_blocks3.__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_blocks4.privateApis);
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 getEnabledClientIdsTreeUnmemoized(state, rootClientId) {
const blockOrder = getBlockOrder(state, rootClientId);
const result = [];
for (const clientId of blockOrder) {
const innerBlocks = getEnabledClientIdsTreeUnmemoized(
state,
clientId
);
if (getBlockEditingMode(state, clientId) !== "disabled") {
result.push({ clientId, innerBlocks });
} else {
result.push(...innerBlocks);
}
}
return result;
}
var getEnabledClientIdsTree = (0, import_data3.createRegistrySelector)(
() => (0, import_data3.createSelector)(getEnabledClientIdsTreeUnmemoized, (state) => [
state.blocks.order,
state.derivedBlockEditingModes,
state.blockEditingModes
])
);
var getEnabledBlockParents = (0, import_data3.createSelector)(
(state, clientId, ascending = false) => {
return getBlockParents(state, clientId, ascending).filter(
(parent) => getBlockEditingMode(state, parent) !== "disabled"
);
},
(state) => [
state.blocks.parents,
state.blockEditingModes,
state.settings.templateLock,
state.blockListSettings
]
);
function getRemovalPromptData(state) {
return state.removalPromptData;
}
function getBlockRemovalRules(state) {
return state.blockRemovalRules;
}
var getStyleOverrides = (0, import_data3.createSelector)(
(state) => {
const clientIds = getClientIdsWithDescendants(state);
const clientIdMap = clientIds.reduce((acc, clientId, index) => {
acc[clientId] = index;
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_data3.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_data3.createRegistrySelector)(
(select3) => (0, import_data3.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_data3.createRegistrySelector)(
(select3) => (0, import_data3.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.__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_data3.createRegistrySelector)(
(select3) => (0, import_data3.createSelector)((state) => {
return [
...unlock(select3(STORE_NAME)).getReusableBlocks().map(
(userPattern) => mapUserPattern(
userPattern,
state.settings.__experimentalUserPatternCategories
)
),
// This setting is left for back compat.
...state.settings.__experimentalBlockPatterns ?? [],
...state.settings[selectBlockPatternsKey]?.(select3) ?? []
].filter(
(x2, index, arr) => index === arr.findIndex((y2) => x2.name === y2.name)
);
}, getAllPatternsDependants(select3))
);
var EMPTY_ARRAY = [];
var getReusableBlocks = (0, import_data3.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;
};
var getParentSectionBlock = (state, clientId) => {
let current = clientId;
let result;
while (current = state.blocks.parents.get(current)) {
if (isSectionBlock(state, current)) {
result = current;
}
}
return result;
};
function isSectionBlock(state, clientId) {
if (clientId === state.editedContentOnlySection) {
return false;
}
const blockName = getBlockName(state, clientId);
if (blockName === "core/block") {
return true;
}
const attributes = getBlockAttributes(state, clientId);
const isTemplatePart8 = blockName === "core/template-part";
const isIsolatedEditor = state.settings?.[isIsolatedEditorKey];
if ((attributes?.metadata?.patternName || isTemplatePart8) && !!window?.__experimentalContentOnlyPatternInsertion && !isIsolatedEditor) {
return true;
}
const hasContentOnlyTempateLock = getTemplateLock(state, clientId) === "contentOnly";
const rootClientId = getBlockRootClientId(state, clientId);
const hasRootContentOnlyTemplateLock = getTemplateLock(state, rootClientId) === "contentOnly";
if (hasContentOnlyTempateLock && !hasRootContentOnlyTemplateLock) {
return true;
}
return false;
}
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_data3.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 isBlockHidden = (state, clientId) => {
const blockName = getBlockName(state, clientId);
if (!(0, import_blocks4.hasBlockSupport)(blockName, "visibility", true)) {
return false;
}
const attributes = state.blocks.attributes.get(clientId);
const blockVisibility2 = attributes?.metadata?.blockVisibility;
if (blockVisibility2 === false) {
return true;
}
if (!window.__experimentalHideBlocksBasedOnScreenSize) {
return false;
}
if (typeof blockVisibility2 === "object" && blockVisibility2 !== null) {
const settings2 = getSettings(state);
const viewportType = settings2[deviceTypeKey] ?? BLOCK_VISIBILITY_VIEWPORTS.desktop.key;
const viewportKey = viewportType.toLowerCase();
return blockVisibility2?.[viewportKey] === false;
}
return false;
};
var areBlocksHidden = (state, clientIds) => {
if (!clientIds || clientIds.length === 0) {
return false;
}
return clientIds.some((clientId) => isBlockHidden(state, clientId));
};
var areBlocksHiddenAnywhere = (state, clientIds) => {
if (!clientIds?.length) {
return false;
}
return clientIds.some((clientId) => {
if (!clientId) {
return false;
}
const attributes = state.blocks.attributes.get(clientId);
const blockVisibility2 = attributes?.metadata?.blockVisibility;
if (typeof blockVisibility2 === "boolean") {
return blockVisibility2 === false;
}
if ("object" !== typeof blockVisibility2) {
return false;
}
return BLOCK_VISIBILITY_VIEWPORT_ENTRIES.some(
([, { key }]) => blockVisibility2?.[key] === false
);
});
};
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);
}
// 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_blocks5.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.__experimentalUserPatternCategories,
state.settings.__experimentalReusableBlocks,
state.settings[selectBlockPatternsKey]?.(select3),
state.blockPatterns,
unlock(select3(STORE_NAME)).getReusableBlocks()
];
};
var getInsertBlockTypeDependants = () => (state, rootClientId) => {
return [
state.blockListSettings[rootClientId],
state.blocks.byClientId.get(rootClientId),
state.settings.allowedBlockTypes,
state.settings.templateLock,
getBlockEditingMode(state, rootClientId),
getSectionRootClientId(state),
isSectionBlock(state, rootClientId)
];
};
// packages/block-editor/build-module/utils/sorting.mjs
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 (cmpA > cmpB) {
return order === "asc" ? 1 : -1;
} else if (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_blocks6.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);
const socialLinkName = "core/social-link";
if (import_element6.Platform.OS !== "web" && block?.name === socialLinkName) {
const attributes = state.blocks.attributes.get(clientId);
const { service } = attributes ?? {};
return service ? `${socialLinkName}-${service}` : socialLinkName;
}
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_data4.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;
}
var __unstableGetClientIdWithClientIdsTree = (0, import_data4.createSelector)(
(state, clientId) => {
(0, import_deprecated2.default)(
"wp.data.select( 'core/block-editor' ).__unstableGetClientIdWithClientIdsTree",
{
since: "6.3",
version: "6.5"
}
);
return {
clientId,
innerBlocks: __unstableGetClientIdsTree(state, clientId)
};
},
(state) => [state.blocks.order]
);
var __unstableGetClientIdsTree = (0, import_data4.createSelector)(
(state, rootClientId = "") => {
(0, import_deprecated2.default)(
"wp.data.select( 'core/block-editor' ).__unstableGetClientIdsTree",
{
since: "6.3",
version: "6.5"
}
);
return getBlockOrder(state, rootClientId).map(
(clientId) => __unstableGetClientIdWithClientIdsTree(state, clientId)
);
},
(state) => [state.blocks.order]
);
var getClientIdsOfDescendants = (0, import_data4.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 index = 0;
while (index < ids.length) {
const id = ids[index];
const order = state.blocks.order.get(id);
if (order) {
ids.splice(index + 1, 0, ...order);
}
index++;
}
return ids;
},
(state) => [state.blocks.order]
);
var getClientIdsWithDescendants = (state) => getClientIdsOfDescendants(state, "");
var getGlobalBlockCount = (0, import_data4.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_data4.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_data4.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_data4.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_data4.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_data4.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 index = 0; index < maxDepth; index++) {
if (clientParents[index] === selectedParents[index]) {
lowestCommonAncestor = clientParents[index];
} 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 index = orderSet.indexOf(startClientId);
const nextIndex = index + 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_data4.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_data4.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_data4.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_blocks6.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_blocks6.getBlockType)(targetBlockName);
if (!targetBlockType.merge) {
return false;
}
const blockToMerge = getBlock(state, blockToMergeClientId);
if (blockToMerge.name === targetBlockName) {
return true;
}
const blocksToMerge = (0, import_blocks6.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 index = clientIds.indexOf(clientId);
return index > -1 && index < 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_data4.createSelector)(
(state) => {
let rootClientId, index;
const {
insertionCue: insertionCue2,
selection: { selectionEnd }
} = state;
if (insertionCue2 !== null) {
return insertionCue2;
}
const { clientId } = selectionEnd;
if (clientId) {
rootClientId = getBlockRootClientId(state, clientId) || void 0;
index = getBlockIndex(state, selectionEnd.clientId) + 1;
} else {
index = getBlockOrder(state).length;
}
return { rootClientId, index };
},
(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_blocks6.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 (!isBlockVisibleInTheInserter(state, blockName, rootClientId)) {
return false;
}
let blockType;
if (blockName && "object" === typeof blockName) {
blockType = blockName;
blockName = blockType.name;
} else {
blockType = (0, import_blocks6.getBlockType)(blockName);
}
const rootTemplateLock = getTemplateLock(state, rootClientId);
if (rootTemplateLock && rootTemplateLock !== "contentOnly") {
return false;
}
const blockEditingMode = getBlockEditingMode(state, rootClientId ?? "");
if (blockEditingMode === "disabled") {
return false;
}
const parentBlockListSettings = getBlockListSettings(state, rootClientId);
if (rootClientId && parentBlockListSettings === void 0) {
return false;
}
const isContentRoleBlock = isContentBlock3(blockName);
const isParentSectionBlock = !!isSectionBlock(state, rootClientId);
const isBlockWithinSection = !!getParentSectionBlock(
state,
rootClientId
);
if ((isParentSectionBlock || isBlockWithinSection) && !isContentRoleBlock) {
return false;
}
if ((isParentSectionBlock || blockEditingMode === "contentOnly") && !isContainerInsertableToInContentOnlyMode(
state,
blockName,
rootClientId
)) {
return false;
}
const parentName = getBlockName(state, rootClientId);
const parentBlockType = (0, import_blocks6.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_data4.createRegistrySelector)(
(select3) => (0, import_data4.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 canRemoveBlock(state, clientId) {
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 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 ((isParentSectionBlock || rootBlockEditingMode === "contentOnly") && !isContainerInsertableToInContentOnlyMode(
state,
getBlockName(state, clientId),
rootClientId
)) {
return false;
}
return rootBlockEditingMode !== "disabled";
}
function canRemoveBlocks(state, clientIds) {
return clientIds.every((clientId) => canRemoveBlock(state, clientId));
}
function canMoveBlock(state, clientId) {
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 ((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) {
const attributes = getBlockAttributes(state, clientId);
if (attributes === null) {
return true;
}
const { lock: lock4 } = attributes;
return !lock4?.edit;
}
function canLockBlockType(state, nameOrType) {
if (!(0, import_blocks6.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_blocks6.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,
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_blocks6.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_blocks6.getBlockVariations)(
blockType.name,
"inserter"
);
const blockVariations = (0, import_blocks6.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 getInserterItems = (0, import_data4.createRegistrySelector)(
(select3) => (0, import_data4.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_blocks6.getBlockTypes)().filter(
(blockType) => (0, import_blocks6.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_blocks6.getBlockTypes)(),
unlock(select3(STORE_NAME)).getReusableBlocks(),
state.blocks.order,
state.preferences.insertUsage,
...getInsertBlockTypeDependants(select3)(state, rootClientId)
]
)
);
var getBlockTransformItems = (0, import_data4.createRegistrySelector)(
(select3) => (0, import_data4.createSelector)(
(state, blocks2, rootClientId = null) => {
const normalizedBlocks = Array.isArray(blocks2) ? blocks2 : [blocks2];
const buildBlockTypeTransformItem = buildBlockTypeItem(state, {
buildScope: "transform"
});
const blockTypeTransformItems = (0, import_blocks6.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_blocks6.getPossibleBlockTransformations)(
normalizedBlocks
).reduce((accumulator, block) => {
if (itemsByName[block?.name]) {
accumulator.push(itemsByName[block.name]);
}
return accumulator;
}, []);
return orderBy(
possibleTransforms,
(block) => itemsByName[block.name].frecency,
"desc"
);
},
(state, blocks2, rootClientId) => [
(0, import_blocks6.getBlockTypes)(),
state.preferences.insertUsage,
...getInsertBlockTypeDependants(select3)(state, rootClientId)
]
)
);
var hasInserterItems = (state, rootClientId = null) => {
const hasBlockType = (0, import_blocks6.getBlockTypes)().some(
(blockType) => canIncludeBlockTypeInInserter(state, blockType, rootClientId)
);
if (hasBlockType) {
return true;
}
const hasReusableBlock = canInsertBlockTypeUnmemoized(
state,
"core/block",
rootClientId
);
return hasReusableBlock;
};
var getAllowedBlocks = (0, import_data4.createRegistrySelector)(
(select3) => (0, import_data4.createSelector)(
(state, rootClientId = null) => {
if (!rootClientId) {
return;
}
const blockTypes = (0, import_blocks6.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_blocks6.getBlockTypes)(),
...getInsertBlockTypeDependants(select3)(state, rootClientId)
]
)
);
var __experimentalGetAllowedBlocks = (0, import_data4.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[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_data4.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_data4.createRegistrySelector)(
(select3) => {
return (0, import_data4.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_data4.createRegistrySelector)(
(select3) => (0, import_data4.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_data4.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_data4.createRegistrySelector)(
(select3) => (0, import_data4.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[clientId];
}
function getSettings(state) {
return state.settings;
}
function isLastBlockChangePersistent(state) {
return state.blocks.isPersistentChange;
}
var __experimentalGetBlockListSettingsForBlocks = (0, import_data4.createSelector)(
(state, clientIds = []) => {
return clientIds.reduce((blockListSettingsForBlocks, clientId) => {
if (!state.blockListSettings[clientId]) {
return blockListSettingsForBlocks;
}
return {
...blockListSettingsForBlocks,
[clientId]: state.blockListSettings[clientId]
};
}, {});
},
(state) => [state.blockListSettings]
);
var __experimentalGetReusableBlockTitle = (0, import_data4.createRegistrySelector)(
(select3) => (0, import_data4.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[clientId];
}
var __experimentalGetActiveBlockIdByBlockNames = (0, import_data4.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_data4.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_blocks6.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.blockEditingModes.has(clientId)) {
return state.blockEditingModes.get(clientId);
}
return "default";
}
var isUngroupable = (0, import_data4.createRegistrySelector)(
(select3) => (state, clientId = "") => {
const _clientId = clientId || getSelectedBlockClientId(state);
if (!_clientId) {
return false;
}
if (isSectionBlock(state, _clientId)) {
return false;
}
const { getGroupingBlockName } = select3(import_blocks6.store);
const block = getBlock(state, _clientId);
const groupingBlockName = getGroupingBlockName();
const _isUngroupable = block && (block.name === groupingBlockName || (0, import_blocks6.getBlockType)(block.name)?.transforms?.ungroup) && !!block.innerBlocks.length;
return _isUngroupable && canRemoveBlock(state, _clientId);
}
);
var isGroupable = (0, import_data4.createRegistrySelector)(
(select3) => (state, clientIds = EMPTY_ARRAY2) => {
const { getGroupingBlockName } = select3(import_blocks6.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,
deleteStyleOverride: () => deleteStyleOverride,
editContentOnlySection: () => editContentOnlySection,
ensureDefaultBlock: () => ensureDefaultBlock,
expandBlock: () => expandBlock,
hideBlockInterface: () => hideBlockInterface,
privateRemoveBlocks: () => privateRemoveBlocks,
resetZoomLevel: () => resetZoomLevel,
setBlockRemovalRules: () => setBlockRemovalRules,
setInsertionPoint: () => setInsertionPoint,
setLastFocus: () => setLastFocus,
setStyleOverride: () => setStyleOverride,
setZoomLevel: () => setZoomLevel,
showBlockInterface: () => showBlockInterface,
startDragging: () => startDragging,
stopDragging: () => stopDragging,
stopEditingContentOnlySection: () => stopEditingContentOnlySection,
toggleBlockSpotlight: () => toggleBlockSpotlight
});
var import_element7 = __toESM(require_element(), 1);
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 && import_element7.Platform.OS === "web") {
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
};
}
// packages/block-editor/build-module/store/actions.mjs
var actions_exports = {};
__export(actions_exports, {
__unstableDeleteSelection: () => __unstableDeleteSelection,
__unstableExpandSelection: () => __unstableExpandSelection,
__unstableMarkAutomaticChange: () => __unstableMarkAutomaticChange,
__unstableMarkLastChangeAsPersistent: () => __unstableMarkLastChangeAsPersistent,
__unstableMarkNextChangeAsNotPersistent: () => __unstableMarkNextChangeAsNotPersistent,
__unstableSaveReusableBlock: () => __unstableSaveReusableBlock,
__unstableSetEditorMode: () => __unstableSetEditorMode,
__unstableSetTemporarilyEditingAsBlocks: () => __unstableSetTemporarilyEditingAsBlocks,
__unstableSplitSelection: () => __unstableSplitSelection,
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_blocks7 = __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;
}
}
}
// 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_blocks7.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);
}
}
};
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 index = 0; index < blocks2.length; index++) {
const block = blocks2[index];
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 = "", index) => ({ 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
});
};
function moveBlockToPosition(clientId, fromRootClientId = "", toRootClientId = "", index) {
return moveBlocksToPosition(
[clientId],
fromRootClientId,
toRootClientId,
index
);
}
function insertBlock(block, index, rootClientId, updateSelection, meta) {
return insertBlocks(
[block],
index,
rootClientId,
updateSelection,
0,
meta
);
}
var insertBlocks = (blocks2, index, 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,
rootClientId,
time: Date.now(),
updateSelection,
initialPosition: updateSelection ? initialPosition2 : null,
meta
});
}
};
function showInsertionPoint(rootClientId, index, __unstableOptions = {}) {
const { __unstableWithInserter, operation, nearestSide } = __unstableOptions;
return {
type: "SHOW_INSERTION_POINT",
rootClientId,
index,
__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_blocks7.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_blocks7.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_blocks7.cloneBlock)(blockA, {
[selectionA.attributeKey]: (0, import_rich_text3.toHTMLString)({ value: valueA })
});
const cloneB = (0, import_blocks7.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_blocks7.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
}
},
...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_blocks7.getBlockType)(blockA.name);
const blockBType = (0, import_blocks7.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_blocks7.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_blocks7.getDefaultBlockName)();
return select3.canInsertBlockType(
defaultBlockName2,
anchorRootClientId
) ? (0, import_blocks7.createBlock)(defaultBlockName2) : (0, import_blocks7.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_blocks7.createBlock)(blockB.name).clientId : blockB.clientId,
attributes: {
...blockB.attributes,
[attributeKeyB]: (0, import_rich_text3.toHTMLString)({ value: valueB })
}
};
const defaultBlockName = (0, import_blocks7.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_blocks7.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_blocks7.getBlockType)(head.name);
const firstBlocks = headType.merge && firstBlock.name === headType.name ? [firstBlock] : (0, import_blocks7.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_blocks7.isUnmodifiedBlock)(head)) {
output.push(head);
}
output.push(firstBlock);
}
const lastBlock = clonedBlocks.pop();
const tailType = (0, import_blocks7.getBlockType)(tail.name);
if (clonedBlocks.length) {
output.push(...clonedBlocks);
}
if (lastBlock) {
const lastBlocks = tailType.merge && tailType.name === lastBlock.name ? [lastBlock] : (0, import_blocks7.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_blocks7.isUnmodifiedBlock)(tail)) {
output.push(tail);
}
}
} else if (!(0, import_blocks7.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_blocks7.getBlockType)(blockA.name);
if (!blockAType || select3.getBlockEditingMode(clientIdA) === "disabled" || select3.getBlockEditingMode(clientIdB) === "disabled") {
return;
}
const blockB = select3.getBlock(clientIdB);
if (!blockAType.merge && (0, import_blocks7.getBlockSupport)(blockA.name, "__experimentalOnMerge")) {
const blocksWithTheSameType2 = (0, import_blocks7.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_blocks7.isUnmodifiedDefaultBlock)(blockA)) {
dispatch.removeBlock(
clientIdA,
select3.isBlockSelected(clientIdA)
);
return;
}
if ((0, import_blocks7.isUnmodifiedDefaultBlock)(blockB)) {
dispatch.removeBlock(
clientIdB,
select3.isBlockSelected(clientIdB)
);
return;
}
if (!blockAType.merge) {
if ((0, import_blocks7.isUnmodifiedBlock)(blockB, "content")) {
dispatch.removeBlock(
clientIdB,
select3.isBlockSelected(clientIdB)
);
} else {
dispatch.selectBlock(blockA.clientId);
}
return;
}
const blockBType = (0, import_blocks7.getBlockType)(blockB.name);
const { clientId, attributeKey, offset } = select3.getSelectionStart();
const selectedBlockType = clientId === clientIdA ? blockAType : blockBType;
const attributeDefinition = selectedBlockType.attributes[attributeKey];
const canRestoreTextSelection = (clientId === clientIdA || clientId === clientIdB) && attributeKey !== void 0 && offset !== 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_blocks7.cloneBlock)(blockA);
const cloneB = (0, import_blocks7.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,
offset,
offset
);
selectedBlock.attributes[attributeKey] = (0, import_rich_text3.toHTMLString)({
value
});
}
const blocksWithTheSameType = blockA.name === blockB.name ? [cloneB] : (0, import_blocks7.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, index) => ({ dispatch }) => {
const defaultBlockName = (0, import_blocks7.getDefaultBlockName)();
if (!defaultBlockName) {
return;
}
const block = (0, import_blocks7.createBlock)(defaultBlockName, attributes);
return dispatch.insertBlock(block, index, rootClientId);
};
function updateBlockListSettings(clientId, settings2) {
return {
type: "UPDATE_BLOCK_LIST_SETTINGS",
clientId,
settings: settings2
};
}
function updateSettings(settings2) {
return __experimentalUpdateSettings(settings2, {
stripExperimentalSettings: true
});
}
function __unstableSaveReusableBlock(id, updatedId) {
return {
type: "SAVE_REUSABLE_BLOCK_SUCCESS",
id,
updatedId
};
}
function __unstableMarkLastChangeAsPersistent() {
return { type: "MARK_LAST_CHANGE_AS_PERSISTENT" };
}
function __unstableMarkNextChangeAsNotPersistent() {
return { type: "MARK_NEXT_CHANGE_AS_NOT_PERSISTENT" };
}
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_blocks7.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_blocks7.__experimentalCloneSanitizedBlock)(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 isLocked = select3.getTemplateLock(rootClientId);
if (isLocked) {
return;
}
const blockIndex = select3.getBlockIndex(clientId);
const directInsertBlock = rootClientId ? select3.getDirectInsertBlock(rootClientId) : null;
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_blocks7.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 isLocked = select3.getTemplateLock(rootClientId);
if (isLocked) {
return;
}
const blockIndex = select3.getBlockIndex(clientId);
const directInsertBlock = rootClientId ? select3.getDirectInsertBlock(rootClientId) : null;
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_blocks7.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[]>`."
);
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
};
}
// packages/block-editor/build-module/store/index.mjs
var storeConfig = {
reducer: reducer_default,
selectors: selectors_exports,
actions: actions_exports
};
var store = (0, import_data5.createReduxStore)(STORE_NAME, {
...storeConfig,
persist: ["preferences"]
});
var registeredStore = (0, import_data5.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_runtime118 = __toESM(require_jsx_runtime(), 1);
function Warning({ className, actions, children, secondaryActions }) {
return /* @__PURE__ */ (0, import_jsx_runtime118.jsx)("div", { style: { display: "contents", all: "initial" }, children: /* @__PURE__ */ (0, import_jsx_runtime118.jsx)("div", { className: clsx_default(className, "block-editor-warning"), children: /* @__PURE__ */ (0, import_jsx_runtime118.jsxs)("div", { className: "block-editor-warning__contents", children: [
/* @__PURE__ */ (0, import_jsx_runtime118.jsx)("p", { className: "block-editor-warning__message", children }),
(actions?.length > 0 || secondaryActions) && /* @__PURE__ */ (0, import_jsx_runtime118.jsxs)("div", { className: "block-editor-warning__actions", children: [
actions?.length > 0 && actions.map((action, i2) => /* @__PURE__ */ (0, import_jsx_runtime118.jsx)(
"span",
{
className: "block-editor-warning__action",
children: action
},
i2
)),
secondaryActions && /* @__PURE__ */ (0, import_jsx_runtime118.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_runtime118.jsx)(import_components3.MenuGroup, { children: secondaryActions.map(
(item, pos) => /* @__PURE__ */ (0, import_jsx_runtime118.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_runtime119 = __toESM(require_jsx_runtime(), 1);
function MultipleUsageWarning({
originalBlockClientId,
name,
onReplace
}) {
const { selectBlock: selectBlock2 } = (0, import_data6.useDispatch)(store);
const blockType = (0, import_blocks8.getBlockType)(name);
return /* @__PURE__ */ (0, import_jsx_runtime119.jsxs)(
warning_default,
{
actions: [
/* @__PURE__ */ (0, import_jsx_runtime119.jsx)(
import_components4.Button,
{
__next40pxDefaultSize: true,
variant: "secondary",
onClick: () => selectBlock2(originalBlockClientId),
children: (0, import_i18n7.__)("Find original")
},
"find-original"
),
/* @__PURE__ */ (0, import_jsx_runtime119.jsx)(
import_components4.Button,
{
__next40pxDefaultSize: true,
variant: "secondary",
onClick: () => onReplace([]),
children: (0, import_i18n7.__)("Remove")
},
"remove"
)
],
children: [
/* @__PURE__ */ (0, import_jsx_runtime119.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_runtime120 = __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_blocks9.hasBlockSupport)(name, "layout", false) || (0, import_blocks9.hasBlockSupport)(name, "__experimentalLayout", false);
const { originalBlockClientId } = (0, import_element8.useContext)(PrivateBlockContext);
return /* @__PURE__ */ (0, import_jsx_runtime120.jsxs)(
Provider,
{
value: (0, import_element8.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
}),
[
name,
isSelected,
clientId,
layoutSupport,
layout,
__unstableLayoutClassNames,
mayDisplayControls,
mayDisplayParentControls,
mayDisplayPatternEditingControls,
blockEditingMode,
bindings,
isPreviewMode
]
),
children: [
/* @__PURE__ */ (0, import_jsx_runtime120.jsx)(edit_default, { ...props }),
originalBlockClientId && /* @__PURE__ */ (0, import_jsx_runtime120.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_data7.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_runtime121 = __toESM(require_jsx_runtime(), 1);
var { kebabCase: kebabCase2 } = unlock(import_components5.privateApis);
var upperFirst = ([firstLetter, ...rest]) => firstLetter.toUpperCase() + rest.join("");
var withCustomColorPalette = (colorsArray) => (0, import_compose2.createHigherOrderComponent)(
(WrappedComponent) => (props) => /* @__PURE__ */ (0, import_jsx_runtime121.jsx)(WrappedComponent, { ...props, colors: colorsArray }),
"withCustomColorPalette"
);
var withEditorColorPalette = () => (0, import_compose2.createHigherOrderComponent)(
(WrappedComponent) => (props) => {
const [userPalette, themePalette, defaultPalette] = useSettings(
"color.palette.custom",
"color.palette.theme",
"color.palette.default"
);
const allColors = (0, import_element9.useMemo)(
() => [
...userPalette || [],
...themePalette || [],
...defaultPalette || []
],
[userPalette, themePalette, defaultPalette]
);
return /* @__PURE__ */ (0, import_jsx_runtime121.jsx)(WrappedComponent, { ...props, colors: allColors });
},
"withEditorColorPalette"
);
function createColorHOC(colorTypes, withColorPalette) {
const colorMap = colorTypes.reduce((colorObject, colorType) => {
return {
...colorObject,
...typeof colorType === "string" ? { [colorType]: kebabCase2(colorType) } : colorType
};
}, {});
return (0, import_compose2.compose)([
withColorPalette,
(WrappedComponent) => {
return class extends import_element9.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_runtime121.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_element10 = __toESM(require_element(), 1);
var import_data8 = __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 __experimentalUseGradient({
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_element10.useMemo)(
() => [
...userGradientPalette || [],
...themeGradientPalette || [],
...defaultGradientPalette || []
],
[userGradientPalette, themeGradientPalette, defaultGradientPalette]
);
const { gradient, customGradient } = (0, import_data8.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_data8.useDispatch)(store);
const setGradient = (0, import_element10.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: kebabCase3 } = 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 }) => size === value);
if (fontSizeObject) {
return fontSizeObject;
}
return {
size: value
};
}
function getFontSizeClass(fontSizeSlug) {
if (!fontSizeSlug) {
return;
}
return `has-${kebabCase3(fontSizeSlug)}-font-size`;
}
// packages/block-editor/build-module/components/font-sizes/fluid-utils.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) {
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.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: roundToPrecision(returnValue, 3),
unit
};
}
function roundToPrecision(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_runtime122 = __toESM(require_jsx_runtime(), 1);
function FontSizePicker(props) {
const [fontSizes, customFontSize] = useSettings(
"typography.fontSizes",
"typography.customFontSize"
);
return /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(
import_components7.FontSizePicker,
{
...props,
fontSizes,
disableCustomFontSizes: !customFontSize,
__next40pxDefaultSize: true
}
);
}
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_element11 = __toESM(require_element(), 1);
var import_jsx_runtime123 = __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) => (props) => {
const [fontSizes] = useSettings("typography.fontSizes");
return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(
WrappedComponent,
{
...props,
fontSizes: fontSizes || DEFAULT_FONT_SIZES
}
);
},
"withFontSizes"
),
(WrappedComponent) => {
return class extends import_element11.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 }) => size === 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_runtime123.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_runtime124 = __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_runtime124.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_runtime125 = __toESM(require_jsx_runtime(), 1);
var AlignmentControl = (props) => {
return /* @__PURE__ */ (0, import_jsx_runtime125.jsx)(ui_default, { ...props, isToolbar: false });
};
var AlignmentToolbar = (props) => {
return /* @__PURE__ */ (0, import_jsx_runtime125.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_element15 = __toESM(require_element(), 1);
var import_blocks12 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/autocompleters/block.mjs
var import_data10 = __toESM(require_data(), 1);
var import_blocks11 = __toESM(require_blocks(), 1);
var import_element14 = __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 __222() {
this.constructor = d2;
}
d2.prototype = b2 === null ? Object.create(b2) : (__222.prototype = b2.prototype, new __222());
}
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_blocks10 = __toESM(require_blocks(), 1);
var import_data9 = __toESM(require_data(), 1);
var import_element12 = __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_element12.useMemo)(
() => ({ [isFiltered]: !!isQuick }),
[isQuick]
);
const [items] = (0, import_data9.useSelect)(
(select3) => [
select3(store).getInserterItems(
rootClientId,
options
)
],
[rootClientId, options]
);
const { getClosestAllowedInsertionPoint: getClosestAllowedInsertionPoint2 } = unlock(
(0, import_data9.useSelect)(store)
);
const { createErrorNotice } = (0, import_data9.useDispatch)(import_notices2.store);
const [categories, collections] = (0, import_data9.useSelect)((select3) => {
const { getCategories, getCollections } = select3(import_blocks10.store);
return [getCategories(), getCollections()];
}, []);
const onSelectItem = (0, import_element12.useCallback)(
({ name, initialAttributes, innerBlocks, syncStatus, content }, shouldFocusBlock) => {
const destinationClientId = getClosestAllowedInsertionPoint2(
name,
rootClientId
);
if (destinationClientId === null) {
const title = (0, import_blocks10.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_blocks10.parse)(content, {
__unstableSkipMigrationLogs: true
}) : (0, import_blocks10.createBlock)(
name,
initialAttributes,
(0, import_blocks10.createBlocksFromInnerBlocksTemplate)(innerBlocks)
);
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_element13 = __toESM(require_element(), 1);
var import_jsx_runtime126 = __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_runtime126.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_runtime126.jsx)(
"span",
{
style,
className: clsx_default("block-editor-block-icon", className, {
"has-colors": showColors
}),
children: renderedIcon
}
);
}
var block_icon_default = (0, import_element13.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_runtime127 = __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_data10.useSelect)((select3) => {
const {
getSelectedBlockClientId: getSelectedBlockClientId2,
getBlock: getBlock2,
getBlockListSettings: getBlockListSettings2,
getBlockRootClientId: getBlockRootClientId2
} = select3(store);
const { getActiveBlockVariation } = select3(import_blocks11.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_element14.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_element14.useMemo)(
() => filteredItems.map((blockItem) => {
const { title, icon, isDisabled } = blockItem;
return {
key: `block-${blockItem.id}`,
value: blockItem,
label: /* @__PURE__ */ (0, import_jsx_runtime127.jsxs)(import_jsx_runtime127.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime127.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, syncStatus, blocks: blocks2 } = inserterItem;
return {
action: "replace",
value: syncStatus === "unsynced" ? (blocks2 ?? []).map(
(block) => (0, import_blocks11.cloneBlock)(block)
) : (0, import_blocks11.createBlock)(
name,
initialAttributes,
(0, import_blocks11.createBlocksFromInnerBlocksTemplate)(
innerBlocks
)
)
};
}
};
}
var block_default = createBlockCompleter();
// packages/block-editor/build-module/autocompleters/link.mjs
var import_api_fetch = __toESM(require_api_fetch(), 1);
var import_url2 = __toESM(require_url(), 1);
var import_html_entities = __toESM(require_html_entities(), 1);
var import_jsx_runtime128 = __toESM(require_jsx_runtime(), 1);
var SHOWN_SUGGESTIONS = 10;
function createLinkCompleter() {
return {
name: "links",
className: "block-editor-autocompleters__link",
triggerPrefix: "[[",
options: async (letters) => {
let options = await (0, import_api_fetch.default)({
path: (0, import_url2.addQueryArgs)("/wp/v2/search", {
per_page: SHOWN_SUGGESTIONS,
search: letters,
type: "post",
order_by: "menu_order"
})
});
options = options.filter((option) => option.title !== "");
return options;
},
getOptionKeywords(item) {
const expansionWords = item.title.split(/\s+/);
return [...expansionWords];
},
getOptionLabel(item) {
return /* @__PURE__ */ (0, import_jsx_runtime128.jsxs)(import_jsx_runtime128.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime128.jsx)(
icon_default,
{
icon: item.subtype === "page" ? page_default : post_default
},
"icon"
),
(0, import_html_entities.decodeEntities)(item.title)
] });
},
getOptionCompletion(item) {
return /* @__PURE__ */ (0, import_jsx_runtime128.jsx)("a", { href: item.url, children: item.title });
}
};
}
var link_default2 = createLinkCompleter();
// 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_element15.useMemo)(() => {
let filteredCompleters = [...completers, link_default2];
if (name === (0, import_blocks12.getDefaultBlockName)() || (0, import_blocks12.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_data11 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/block-list/layout.mjs
var import_element17 = __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_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/block-editor/build-module/layouts/utils.mjs
function appendSelectors(selectors, append = "") {
return selectors.split(",").map(
(subselector) => `${subselector}${append ? ` ${append}` : ""}`
).join(",");
}
function getBlockGapCSS(selector3, layoutDefinitions = LAYOUT_DEFINITIONS, 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", "right", "bottom", "left"];
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(
(size) => String(size.slug) === slug
);
return spacingSize?.size;
}
function getPresetValueFromCustomValue(value, spacingSizes) {
if (!value || isValueSpacingPreset(value) || value === "0") {
return value;
}
const spacingMatch = spacingSizes.find(
(size) => String(size.size) === String(value)
);
if (spacingMatch?.slug) {
return `var:preset|spacing|${spacingMatch.slug}`;
}
return value;
}
function getSpacingPresetCssVar(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(sides, axis) {
if (!sides || !sides.length) {
return false;
}
const hasHorizontalSupport = sides.includes("horizontal") || sides.includes("left") && sides.includes("right");
const hasVerticalSupport = sides.includes("vertical") || sides.includes("top") && sides.includes("bottom");
if (axis === "horizontal") {
return hasHorizontalSupport;
}
if (axis === "vertical") {
return hasVerticalSupport;
}
return hasHorizontalSupport || hasVerticalSupport;
}
function hasBalancedSidesSupport(sides = []) {
const counts = { top: 0, right: 0, bottom: 0, left: 0 };
sides.forEach((side) => counts[side] += 1);
return (counts.top + counts.bottom) % 2 === 0 && (counts.left + counts.right) % 2 === 0;
}
function getInitialView(values = {}, sides) {
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(sides);
const hasOnlyAxialSides = sides?.includes("horizontal") && sides?.includes("vertical") && sides?.length === 2;
if (hasAxisSupport(sides) && (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 (sides?.length === 1 && !sideValues.length) {
return sides[0];
}
return VIEWS.custom;
}
// packages/block-editor/build-module/hooks/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/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 flexWrapOptions = ["wrap", "nowrap"];
var flex_default = {
name: "flex",
label: (0, import_i18n12.__)("Flex"),
inspectorControls: function FlexLayoutInspectorControls({
layout = {},
onChange,
layoutBlockSupport = {}
}) {
const {
allowOrientation = true,
allowJustification = true,
allowWrap = true
} = layoutBlockSupport;
return /* @__PURE__ */ (0, import_jsx_runtime130.jsxs)(import_jsx_runtime130.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime130.jsxs)(import_components11.Flex, { children: [
allowJustification && /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(import_components11.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
FlexLayoutJustifyContentControl,
{
layout,
onChange
}
) }),
allowOrientation && /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(import_components11.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
OrientationControl,
{
layout,
onChange
}
) })
] }),
allowWrap && /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(FlexWrapControl, { layout, onChange })
] });
},
toolBarControls: function FlexLayoutToolbarControls({
layout = {},
onChange,
layoutBlockSupport
}) {
const { allowVerticalAlignment = true, allowJustification = true } = layoutBlockSupport;
if (!allowJustification && !allowVerticalAlignment) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime130.jsxs)(block_controls_default, { group: "block", __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
}
)
] });
},
getLayoutStyle: function getLayoutStyle({
selector: selector3,
layout,
style,
blockName,
hasBlockGapSupport,
layoutDefinitions = LAYOUT_DEFINITIONS
}) {
const { orientation = "horizontal" } = layout;
const blockGapValue = style?.spacing?.blockGap && !shouldSkipSerialization(blockName, "spacing", "blockGap") ? getGapCSSValue(style?.spacing?.blockGap, "0.5em") : void 0;
const justifyContent = justifyContentMap[layout.justifyContent];
const flexWrap = flexWrapOptions.includes(layout.flexWrap) ? layout.flexWrap : "wrap";
const verticalAlignment = verticalAlignmentMap[layout.verticalAlignment];
const alignItems = alignItemsMap[layout.justifyContent] || alignItemsMap.left;
let output = "";
const rules = [];
if (flexWrap && flexWrap !== "wrap") {
rules.push(`flex-wrap: ${flexWrap}`);
}
if (orientation === "horizontal") {
if (verticalAlignment) {
rules.push(`align-items: ${verticalAlignment}`);
}
if (justifyContent) {
rules.push(`justify-content: ${justifyContent}`);
}
} else {
if (verticalAlignment) {
rules.push(`justify-content: ${verticalAlignment}`);
}
rules.push("flex-direction: column");
rules.push(`align-items: ${alignItems}`);
}
if (rules.length) {
output = `${appendSelectors(selector3)} {
${rules.join("; ")};
}`;
}
if (hasBlockGapSupport && blockGapValue) {
output += getBlockGapCSS(
selector3,
layoutDefinitions,
"flex",
blockGapValue
);
}
return output;
},
getOrientation(layout) {
const { orientation = "horizontal" } = layout;
return orientation;
},
getAlignments() {
return [];
}
};
function FlexLayoutVerticalAlignmentControl({ layout, onChange }) {
const { orientation = "horizontal" } = layout;
const defaultVerticalAlignment = orientation === "horizontal" ? defaultAlignments.horizontal : defaultAlignments.vertical;
const { verticalAlignment = defaultVerticalAlignment } = layout;
const onVerticalAlignmentChange = (value) => {
onChange({
...layout,
verticalAlignment: value
});
};
return /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
BlockVerticalAlignmentControl,
{
onChange: onVerticalAlignmentChange,
value: verticalAlignment,
controls: orientation === "horizontal" ? ["top", "center", "bottom", "stretch"] : ["top", "center", "bottom", "space-between"]
}
);
}
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,
{
__next40pxDefaultSize: true,
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,
{
__next40pxDefaultSize: true,
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_DEFINITIONS
}) {
const blockGapStyleValue = getGapCSSValue(style?.spacing?.blockGap);
let blockGapValue = "";
if (!shouldSkipSerialization(blockName, "spacing", "blockGap")) {
if (blockGapStyleValue?.top) {
blockGapValue = getGapCSSValue(blockGapStyleValue?.top);
} else if (typeof blockGapStyleValue === "string") {
blockGapValue = getGapCSSValue(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_engine = __toESM(require_style_engine(), 1);
var import_jsx_runtime131 = __toESM(require_jsx_runtime(), 1);
var constrained_default = {
name: "constrained",
label: (0, import_i18n14.__)("Constrained"),
inspectorControls: function DefaultLayoutInspectorControls2({
layout,
onChange,
layoutBlockSupport = {}
}) {
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"]
});
return /* @__PURE__ */ (0, import_jsx_runtime131.jsxs)(
import_components13.__experimentalVStack,
{
spacing: 4,
className: "block-editor-hooks__layout-constrained",
children: [
allowCustomContentAndWideSize && /* @__PURE__ */ (0, import_jsx_runtime131.jsxs)(import_jsx_runtime131.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
import_components13.__experimentalUnitControl,
{
__next40pxDefaultSize: true,
label: (0, import_i18n14.__)("Content width"),
labelPosition: "top",
value: 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.jsx)(
import_components13.__experimentalUnitControl,
{
__next40pxDefaultSize: true,
label: (0, import_i18n14.__)("Wide width"),
labelPosition: "top",
value: 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.__experimentalToggleGroupControl,
{
__next40pxDefaultSize: true,
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
}) {
const { allowJustification = true } = layoutBlockSupport;
if (!allowJustification) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(block_controls_default, { group: "block", __experimentalShareWithChildBlocks: true, children: /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
DefaultLayoutJustifyContentControl,
{
layout,
onChange
}
) });
},
getLayoutStyle: function getLayoutStyle3({
selector: selector3,
layout = {},
style,
blockName,
hasBlockGapSupport,
layoutDefinitions = LAYOUT_DEFINITIONS
}) {
const { contentSize, wideSize, justifyContent } = layout;
const blockGapStyleValue = getGapCSSValue(style?.spacing?.blockGap);
let blockGapValue = "";
if (!shouldSkipSerialization(blockName, "spacing", "blockGap")) {
if (blockGapStyleValue?.top) {
blockGapValue = getGapCSSValue(blockGapStyleValue?.top);
} else if (typeof blockGapStyleValue === "string") {
blockGapValue = getGapCSSValue(blockGapStyleValue);
}
}
const marginLeft = justifyContent === "left" ? "0 !important" : "auto !important";
const marginRight = justifyContent === "right" ? "0 !important" : "auto !important";
let output = !!contentSize || !!wideSize ? `
${appendSelectors(
selector3,
"> :where(:not(.alignleft):not(.alignright):not(.alignfull))"
)} {
max-width: ${contentSize ?? wideSize};
margin-left: ${marginLeft};
margin-right: ${marginRight};
}
${appendSelectors(selector3, "> .alignwide")} {
max-width: ${wideSize ?? contentSize};
}
${appendSelectors(selector3, "> .alignfull")} {
max-width: none;
}
` : "";
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 (style?.spacing?.padding) {
const paddingValues = (0, import_style_engine.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 && 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_element16 = __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 = {}
}) {
const { allowSizingOnChildren = false } = layoutBlockSupport;
const showColumnsControl = true;
const showMinWidthControl = !layout?.isManualPlacement || window.__experimentalEnableGridInteractivity;
return /* @__PURE__ */ (0, import_jsx_runtime132.jsxs)(import_jsx_runtime132.Fragment, { children: [
window.__experimentalEnableGridInteractivity && /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(
GridLayoutTypeControl,
{
layout,
onChange
}
),
/* @__PURE__ */ (0, import_jsx_runtime132.jsxs)(import_components15.__experimentalVStack, { spacing: 4, children: [
showColumnsControl && /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(
GridLayoutColumnsAndRowsControl,
{
layout,
onChange,
allowSizingOnChildren
}
),
showMinWidthControl && /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(
GridLayoutMinimumWidthControl,
{
layout,
onChange
}
)
] })
] });
},
toolBarControls: function GridLayoutToolbarControls() {
return null;
},
getLayoutStyle: function getLayoutStyle4({
selector: selector3,
layout,
style,
blockName,
hasBlockGapSupport,
layoutDefinitions = LAYOUT_DEFINITIONS
}) {
const {
minimumColumnWidth = null,
columnCount = null,
rowCount = null
} = layout;
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");
}
}
const blockGapValue = style?.spacing?.blockGap && !shouldSkipSerialization(blockName, "spacing", "blockGap") ? getGapCSSValue(style?.spacing?.blockGap, "0.5em") : void 0;
let output = "";
const rules = [];
if (minimumColumnWidth && columnCount > 0) {
const maxValue = `max(${minimumColumnWidth}, ( 100% - (${blockGapValue || "1.2rem"}*${columnCount - 1}) ) / ${columnCount})`;
rules.push(
`grid-template-columns: repeat(auto-fill, minmax(${maxValue}, 1fr))`,
`container-type: inline-size`
);
if (rowCount) {
rules.push(
`grid-template-rows: repeat(${rowCount}, minmax(1rem, auto))`
);
}
} else if (columnCount) {
rules.push(
`grid-template-columns: repeat(${columnCount}, minmax(0, 1fr))`
);
if (rowCount) {
rules.push(
`grid-template-rows: repeat(${rowCount}, minmax(1rem, auto))`
);
}
} else {
rules.push(
`grid-template-columns: repeat(auto-fill, minmax(min(${minimumColumnWidth || "12rem"}, 100%), 1fr))`,
"container-type: inline-size"
);
}
if (rules.length) {
output = `${appendSelectors(selector3)} { ${rules.join(
"; "
)}; }`;
}
if (hasBlockGapSupport && 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,
{
size: "__unstable-large",
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,
{
__next40pxDefaultSize: true,
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,
{
size: "__unstable-large",
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,
{
size: "__unstable-large",
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,
{
__next40pxDefaultSize: true,
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 GridLayoutTypeControl({ layout, onChange }) {
const { columnCount, rowCount, minimumColumnWidth, isManualPlacement } = layout;
const [tempColumnCount, setTempColumnCount] = (0, import_element16.useState)(
columnCount || 3
);
const [tempRowCount, setTempRowCount] = (0, import_element16.useState)(rowCount);
const [tempMinimumColumnWidth, setTempMinimumColumnWidth] = (0, import_element16.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,
{
__next40pxDefaultSize: true,
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_element17.createContext)(defaultLayout);
Layout.displayName = "BlockLayoutContext";
var LayoutProvider = Layout.Provider;
function useLayout() {
return (0, import_element17.useContext)(Layout);
}
function LayoutStyle({ layout = {}, css: css3, ...props }) {
const layoutType = getLayoutType(layout.type);
const [blockGapSupport] = useSettings("spacing.blockGap");
const hasBlockGapSupport = blockGapSupport !== null;
if (layoutType) {
if (css3) {
return /* @__PURE__ */ (0, import_jsx_runtime133.jsx)("style", { children: css3 });
}
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_data11.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_blocks14 = __toESM(require_blocks(), 1);
var import_components18 = __toESM(require_components(), 1);
var import_data14 = __toESM(require_data(), 1);
var import_element19 = __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_blocks13 = __toESM(require_blocks(), 1);
var import_components17 = __toESM(require_components(), 1);
var import_data13 = __toESM(require_data(), 1);
var import_element18 = __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_data12 = __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_data12.useDispatch)(store);
const { getBlockAttributes: getBlockAttributes3 } = (0, import_data12.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_element18.useMemo)(
() => ({
source: sourceKey,
args: field.args || {
key: field.key
}
}),
[field.args, field.key, sourceKey]
);
const blockContext = (0, import_element18.useContext)(block_context_default);
const values = (0, import_data13.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_blocks13.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_element19.useContext)(block_context_default);
const compatibleFields = (0, import_data14.useSelect)(
(select3) => {
const {
getAllBlockBindingsSources,
getBlockBindingsSourceFieldsList,
getBlockType: getBlockType24
} = unlock(select3(import_blocks14.store));
const _attributeType = getBlockType24(blockName).attributes?.[attribute]?.type;
const attributeType = _attributeType === "rich-text" ? "string" : _attributeType;
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_data14.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_blocks14.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: fullscreen_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_data16 = __toESM(require_data(), 1);
var import_i18n21 = __toESM(require_i18n(), 1);
var import_element22 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/block-title/use-block-display-title.mjs
var import_data15 = __toESM(require_data(), 1);
var import_blocks15 = __toESM(require_blocks(), 1);
function useBlockDisplayTitle({
clientId,
maximumLength,
context
}) {
const blockTitle = (0, import_data15.useSelect)(
(select3) => {
if (!clientId) {
return null;
}
const { getBlockName: getBlockName2, getBlockAttributes: getBlockAttributes3 } = select3(store);
const { getBlockType: getBlockType24, getActiveBlockVariation } = select3(import_blocks15.store);
const blockName = getBlockName2(clientId);
const blockType = getBlockType24(blockName);
if (!blockType) {
return null;
}
const attributes = getBlockAttributes3(clientId);
const label = (0, import_blocks15.__experimentalGetBlockLabel)(blockType, attributes, context);
if (label !== blockType.title) {
return label;
}
const match2 = getActiveBlockVariation(blockName, attributes);
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_element21 = __toESM(require_element(), 1);
var import_compose7 = __toESM(require_compose(), 1);
// packages/block-editor/build-module/components/provider/block-refs-provider.mjs
var import_element20 = __toESM(require_element(), 1);
var import_compose6 = __toESM(require_compose(), 1);
var import_jsx_runtime140 = __toESM(require_jsx_runtime(), 1);
var BlockRefs = (0, import_element20.createContext)({ refsMap: (0, import_compose6.observableMap)() });
BlockRefs.displayName = "BlockRefsContext";
function BlockRefsProvider({ children }) {
const value = (0, import_element20.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_element21.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_element21.useContext)(BlockRefs);
(0, import_element21.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_element21.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_data16.useDispatch)(store);
const { clientId, parents, hasSelection } = (0, import_data16.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_element22.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
}
)
}
),
/* @__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 })
}
)
]
}
);
}
var block_breadcrumb_default = BlockBreadcrumb;
// packages/block-editor/build-module/components/block-content-overlay/index.mjs
var import_data17 = __toESM(require_data(), 1);
function useBlockOverlayActive(clientId) {
return (0, import_data17.useSelect)(
(select3) => {
const { __unstableHasActiveBlockOverlayActive: __unstableHasActiveBlockOverlayActive2 } = select3(store);
return __unstableHasActiveBlockOverlayActive2(clientId);
},
[clientId]
);
}
// packages/block-editor/build-module/components/block-canvas/index.mjs
var import_compose67 = __toESM(require_compose(), 1);
var import_element128 = __toESM(require_element(), 1);
var import_data125 = __toESM(require_data(), 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_element94 = __toESM(require_element(), 1);
var import_blocks45 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/components/block-list/block.mjs
var import_element36 = __toESM(require_element(), 1);
var import_blocks22 = __toESM(require_blocks(), 1);
var import_components29 = __toESM(require_components(), 1);
var import_data30 = __toESM(require_data(), 1);
var import_compose17 = __toESM(require_compose(), 1);
var import_dom7 = __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_element24 = __toESM(require_element(), 1);
var import_blocks17 = __toESM(require_blocks(), 1);
var import_data18 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/block-compare/index.mjs
var import_character = __toESM(require_character(), 1);
var import_i18n22 = __toESM(require_i18n(), 1);
var import_blocks16 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/components/block-compare/block-view.mjs
var import_components22 = __toESM(require_components(), 1);
var import_element23 = __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_element23.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 = (0, import_character.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_blocks16.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_blocks17.rawHandler)({
HTML: block.originalContent
});
function BlockInvalidWarning({ clientId }) {
const { block, canInsertHTMLBlock, canInsertClassicBlock } = (0, import_data18.useSelect)(
(select3) => {
const { canInsertBlockType: canInsertBlockType2, getBlock: getBlock2, getBlockRootClientId: getBlockRootClientId2 } = select3(store);
const rootClientId = getBlockRootClientId2(clientId);
return {
block: getBlock2(clientId),
canInsertHTMLBlock: canInsertBlockType2(
"core/html",
rootClientId
),
canInsertClassicBlock: canInsertBlockType2(
"core/freeform",
rootClientId
)
};
},
[clientId]
);
const { replaceBlock: replaceBlock2 } = (0, import_data18.useDispatch)(store);
const [compare2, setCompare] = (0, import_element24.useState)(false);
const onCompareClose = (0, import_element24.useCallback)(() => setCompare(false), []);
const convert = (0, import_element24.useMemo)(
() => ({
toClassic() {
const classicBlock = (0, import_blocks17.createBlock)("core/freeform", {
content: block.originalContent
});
return replaceBlock2(block.clientId, classicBlock);
},
toHTML() {
const htmlBlock = (0, import_blocks17.createBlock)("core/html", {
content: block.originalContent
});
return replaceBlock2(block.clientId, htmlBlock);
},
toBlocks() {
const newBlocks = blockToBlocks(block);
return replaceBlock2(block.clientId, newBlocks);
},
toRecoveredBlock() {
const recoveredBlock = (0, import_blocks17.createBlock)(
block.name,
block.attributes,
block.innerBlocks
);
return replaceBlock2(block.clientId, recoveredBlock);
}
}),
[block, replaceBlock2]
);
const secondaryActions = (0, import_element24.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
},
canInsertClassicBlock && {
title: (0, import_i18n23.__)("Convert to Classic Block"),
onClick: convert.toClassic
}
].filter(Boolean),
[canInsertHTMLBlock, canInsertClassicBlock, 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.") });
var block_crash_warning_default = () => warning;
// packages/block-editor/build-module/components/block-list/block-crash-boundary.mjs
var import_element25 = __toESM(require_element(), 1);
var BlockCrashBoundary = class extends import_element25.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_element26 = __toESM(require_element(), 1);
var import_data19 = __toESM(require_data(), 1);
var import_blocks18 = __toESM(require_blocks(), 1);
var import_jsx_runtime146 = __toESM(require_jsx_runtime(), 1);
function BlockHTML({ clientId }) {
const [html, setHtml] = (0, import_element26.useState)("");
const block = (0, import_data19.useSelect)(
(select3) => select3(store).getBlock(clientId),
[clientId]
);
const { updateBlock: updateBlock2 } = (0, import_data19.useDispatch)(store);
const onChange = () => {
const blockType = (0, import_blocks18.getBlockType)(block.name);
if (!blockType) {
return;
}
const attributes = (0, import_blocks18.getBlockAttributes)(
blockType,
html,
block.attributes
);
const content = html ? html : (0, import_blocks18.getSaveContent)(blockType, attributes);
const [isValid2] = html ? (0, import_blocks18.validateBlock)({
...block,
attributes,
originalContent: content
}) : [true];
updateBlock2(clientId, {
attributes,
originalContent: content,
isValid: isValid2
});
if (!html) {
setHtml(content);
}
};
(0, import_element26.useEffect)(() => {
setHtml((0, import_blocks18.getBlockContent)(block));
}, [block]);
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_element35 = __toESM(require_element(), 1);
var import_i18n30 = __toESM(require_i18n(), 1);
var import_blocks21 = __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 index = arr.findIndex(test);
return index < 0 ? arr.length : index;
}
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 [initial] = (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 = initial;
}
(0, import_react.useEffect)(() => {
committed.current = cache;
if (prevCache == initial) {
initial.inputs = initial.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 = (Component7, host2) => {
const hasInstance = !is.fun(Component7) || Component7.prototype && Component7.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(Component7, _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 = (Component7) => {
const displayName = getDisplayName(Component7) || "Anonymous";
if (is.str(Component7)) {
Component7 = animated2[Component7] || (animated2[Component7] = withAnimated(Component7, hostConfig));
} else {
Component7 = Component7[cacheKey] || (Component7[cacheKey] = withAnimated(Component7, hostConfig));
}
Component7.displayName = `Animated(${displayName})`;
return Component7;
};
eachProp(components, (Component7, key) => {
if (is.arr(components)) {
key = getDisplayName(Component7);
}
animated2[key] = animated2(Component7);
});
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: Provider2
} = ctx;
return React2.createElement(Provider2, {
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_element27 = __toESM(require_element(), 1);
var import_dom2 = __toESM(require_dom(), 1);
var import_data20 = __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_element27.useRef)();
const {
isTyping: isTyping3,
getGlobalBlockCount: getGlobalBlockCount2,
isBlockSelected: isBlockSelected2,
isFirstMultiSelectedBlock: isFirstMultiSelectedBlock2,
isBlockMultiSelected: isBlockMultiSelected2,
isAncestorMultiSelected: isAncestorMultiSelected2,
isDraggingBlocks: isDraggingBlocks2
} = (0, import_data20.useSelect)(store);
const { previous, prevRect } = (0, import_element27.useMemo)(
() => ({
previous: ref.current && getAbsolutePosition(ref.current),
prevRect: ref.current && ref.current.getBoundingClientRect()
}),
[triggerAnimationOnChange]
);
(0, import_element27.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_element28 = __toESM(require_element(), 1);
var import_dom3 = __toESM(require_dom(), 1);
var import_data21 = __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 getBlockClientId(node) {
while (node && node.nodeType !== node.ELEMENT_NODE) {
node = node.parentNode;
}
if (!node) {
return;
}
const elementNode = (
/** @type {Element} */
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.classList.contains("components-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_element28.useRef)();
const { isBlockSelected: isBlockSelected2, isMultiSelecting: isMultiSelecting3, isZoomOut: isZoomOut2 } = unlock(
(0, import_data21.useSelect)(store)
);
(0, import_element28.useEffect)(() => {
if (!isBlockSelected2(clientId) || isMultiSelecting3() || isZoomOut2()) {
return;
}
if (initialPosition2 === void 0 || initialPosition2 === null) {
return;
}
if (!ref.current) {
return;
}
const { ownerDocument } = ref.current;
if (isInsideRootBlock(ref.current, ownerDocument.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;
}
}
(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);
function listener(event) {
if (event.defaultPrevented) {
return;
}
event.preventDefault();
event.currentTarget.classList.toggle(
"is-hovered",
event.type === "mouseover"
);
}
function useIsHovered({ isEnabled = true } = {}) {
return (0, import_compose8.useRefEffect)(
(node) => {
if (!isEnabled) {
return;
}
node.addEventListener("mouseout", listener);
node.addEventListener("mouseover", listener);
return () => {
node.removeEventListener("mouseout", listener);
node.removeEventListener("mouseover", listener);
node.classList.remove("is-hovered");
};
},
[isEnabled]
);
}
// packages/block-editor/build-module/components/block-list/use-block-props/use-focus-handler.mjs
var import_data22 = __toESM(require_data(), 1);
var import_compose9 = __toESM(require_compose(), 1);
function useFocusHandler(clientId) {
const { isBlockSelected: isBlockSelected2 } = (0, import_data22.useSelect)(store);
const { selectBlock: selectBlock2, selectionChange: selectionChange2 } = (0, import_data22.useDispatch)(store);
return (0, import_compose9.useRefEffect)(
(node) => {
function onFocus(event) {
if (node.parentElement.closest('[contenteditable="true"]')) {
return;
}
if (isBlockSelected2(clientId)) {
if (!event.target.isContentEditable) {
selectionChange2(clientId);
}
return;
}
if (!isInsideRootBlock(node, event.target)) {
return;
}
selectBlock2(clientId);
}
node.addEventListener("focusin", onFocus);
return () => {
node.removeEventListener("focusin", onFocus);
};
},
[isBlockSelected2, selectBlock2]
);
}
// packages/block-editor/build-module/components/block-list/use-block-props/use-selected-block-event-handlers.mjs
var import_dom6 = __toESM(require_dom(), 1);
var import_keycodes2 = __toESM(require_keycodes(), 1);
var import_data23 = __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
} = unlock((0, import_data23.useSelect)(store));
const {
insertAfterBlock: insertAfterBlock2,
removeBlock: removeBlock2,
resetZoomLevel: resetZoomLevel2,
startDraggingBlocks: startDraggingBlocks2,
stopDraggingBlocks: stopDraggingBlocks2,
editContentOnlySection: editContentOnlySection2
} = unlock((0, import_data23.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_dom6.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 } = node;
const { defaultView } = ownerDocument;
const selection2 = defaultView.getSelection();
selection2.removeAllRanges();
const dragElement = ownerDocument.createElement("div");
dragElement.style.width = "1px";
dragElement.style.height = "1px";
dragElement.style.position = "fixed";
dragElement.style.visibility = "hidden";
ownerDocument.body.appendChild(dragElement);
event.dataTransfer.setDragImage(dragElement, 0, 0);
const rect = node.getBoundingClientRect();
const clone = node.cloneNode(true);
clone.style.visibility = "hidden";
clone.style.display = "none";
const id = node.id;
node.id = null;
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;
node.after(clone);
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;
function over(e2) {
if (!hasStarted) {
hasStarted = true;
node.style.pointerEvents = "none";
}
const scrollTop = defaultView.scrollY;
const scrollLeft = defaultView.scrollX;
node.style.top = `${(e2.clientY - originClientY + scrollTop - originScrollTop) * inverted}px`;
node.style.left = `${(e2.clientX - originClientX + scrollLeft - originScrollLeft) * inverted}px`;
}
function end() {
ownerDocument.removeEventListener("dragover", over);
ownerDocument.removeEventListener("dragend", end);
ownerDocument.removeEventListener("drop", end);
ownerDocument.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"
);
ownerDocument.documentElement.classList.remove(
"is-dragging"
);
}
ownerDocument.addEventListener("dragover", over);
ownerDocument.addEventListener("dragend", end);
ownerDocument.addEventListener("drop", end);
ownerDocument.addEventListener("scroll", over);
startDraggingBlocks2([clientId]);
document.body.classList.add(
"is-dragging-components-draggable"
);
ownerDocument.documentElement.classList.add("is-dragging");
}
node.addEventListener("keydown", onKeyDown);
node.addEventListener("dragstart", onDragStart);
function onDoubleClick(event) {
const isSection = isSectionBlock2(clientId);
const isAlreadyEditing = editedContentOnlySection2 === clientId;
if (isSection && !isAlreadyEditing) {
event.preventDefault();
editContentOnlySection2(clientId);
}
}
if (window?.__experimentalContentOnlyPatternInsertion) {
node.addEventListener("dblclick", onDoubleClick);
}
return () => {
node.removeEventListener("keydown", onKeyDown);
node.removeEventListener("dragstart", onDragStart);
if (window?.__experimentalContentOnlyPatternInsertion) {
node.removeEventListener("dblclick", onDoubleClick);
}
};
},
[
clientId,
isSelected,
getBlockRootClientId2,
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_element29 = __toESM(require_element(), 1);
function useIntersectionObserver() {
const observer = (0, import_element29.useContext)(IntersectionObserver);
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 } = node;
const { defaultView } = ownerDocument;
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_data24 = __toESM(require_data(), 1);
function useFlashEditableBlocks({
clientId = "",
isEnabled = true
} = {}) {
const { getEnabledClientIdsTree: getEnabledClientIdsTree2 } = unlock((0, import_data24.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 set = nodesByDocument.get(doc);
if (!set) {
set = /* @__PURE__ */ new Set();
nodesByDocument.set(doc, set);
doc.addEventListener("pointerdown", down);
}
set.add(node);
}
function remove3(doc, node) {
const set = nodesByDocument.get(doc);
if (set) {
set.delete(node);
restore(node);
if (set.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, isContentEditable, tagName } = target;
const isInputOrTextArea = ["INPUT", "TEXTAREA"].includes(tagName);
const nodes = nodesByDocument.get(ownerDocument);
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_i18n25 = __toESM(require_i18n(), 1);
var import_element30 = __toESM(require_element(), 1);
var import_components24 = __toESM(require_components(), 1);
var import_data25 = __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
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;
}
if (!BLOCK_VISIBILITY_VIEWPORT_ENTRIES.some(
([, { key }]) => key === viewport
)) {
return false;
}
return blockVisibility2[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;
}
// packages/block-editor/build-module/components/block-visibility/modal.mjs
var import_jsx_runtime147 = __toESM(require_jsx_runtime(), 1);
var css = `/**
* SCSS Variables.
*
* Please use variables from this sheet to ensure consistency across the UI.
* Don't add to this sheet unless you're pretty sure the value will be reused in many places.
* For example, don't add rules to this sheet that affect block visuals. It's purely for UI.
*/
/**
* Colors
*/
/**
* Fonts & basic variables.
*/
/**
* Typography
*/
/**
* Grid System.
* https://make.wordpress.org/design/2019/10/31/proposal-a-consistent-spacing-system-for-wordpress/
*/
/**
* Radius scale.
*/
/**
* Elevation scale.
*/
/**
* Dimensions.
*/
/**
* Mobile specific styles
*/
/**
* Editor styles.
*/
/**
* Block & Editor UI.
*/
/**
* Block paddings.
*/
/**
* React Native specific.
* These variables do not appear to be used anywhere else.
*/
.block-editor-block-visibility-modal {
z-index: 1000001;
}
.block-editor-block-visibility-modal__options {
border: 0;
padding: 0;
list-style: none;
margin: 24px 0;
}
.block-editor-block-visibility-modal__options-item {
display: flex;
align-items: center;
justify-content: space-between;
margin: 0 0 16px 0;
gap: 24px;
}
.block-editor-block-visibility-modal__options-item:last-child {
margin: 0;
}
.block-editor-block-visibility-modal__options-item--everywhere {
flex-direction: column;
align-items: start;
}
.block-editor-block-visibility-modal__options-checkbox--everywhere {
font-weight: 600;
}
.block-editor-block-visibility-modal__options-icon--checked {
fill: #ddd;
}
.block-editor-block-visibility-modal__sub-options {
width: 100%;
padding-inline-start: 12px;
}
.block-editor-block-visibility-modal__description {
font-size: 12px;
color: #757575;
}
.block-editor-block-visibility-info {
padding-top: 4px;
padding-bottom: 4px;
margin: 0 16px 16px;
display: flex;
align-items: center;
justify-content: start;
}
/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VSb290IjoiL2hvbWUvcnVubmVyL3dvcmsvZ3V0ZW5iZXJnL2d1dGVuYmVyZy9wYWNrYWdlcy9ibG9jay1lZGl0b3Ivc3JjL2NvbXBvbmVudHMvYmxvY2stdmlzaWJpbGl0eSIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL0B3b3JkcHJlc3MvYmFzZS1zdHlsZXMvX3ZhcmlhYmxlcy5zY3NzIiwiLi4vLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL0B3b3JkcHJlc3MvYmFzZS1zdHlsZXMvX2NvbG9ycy5zY3NzIiwic3R5bGUuc2NzcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQ0FBO0FBQUE7QUFBQTtBRFVBO0FBQUE7QUFBQTtBQU9BO0FBQUE7QUFBQTtBQTZCQTtBQUFBO0FBQUE7QUFBQTtBQWlCQTtBQUFBO0FBQUE7QUFXQTtBQUFBO0FBQUE7QUFnQkE7QUFBQTtBQUFBO0FBeUJBO0FBQUE7QUFBQTtBQUtBO0FBQUE7QUFBQTtBQWVBO0FBQUE7QUFBQTtBQW1CQTtBQUFBO0FBQUE7QUFTQTtBQUFBO0FBQUE7QUFBQTtBRS9KQTtFQUNDOztBQUVBO0VBQ0M7RUFDQTtFQUNBO0VBQ0E7O0FBRUE7RUFDQztFQUNBO0VBQ0E7RUFDQTtFQUNBLEtGc0NZOztBRW5DYjtFQUNDOztBQUdEO0VBQ0M7RUFDQTs7QUFHRDtFQUNDOztBQUdEO0VBQ0MsTUR4QlE7O0FDNEJWO0VBQ0M7RUFDQSxzQkZhYTs7QUVWZDtFQUNDLFdGdEJnQjtFRXVCaEIsT0R0Q1M7OztBQzBDWDtFQUNDLGFGQ2M7RUVBZDtFQUNBO0VBQ0E7RUFDQTtFQUNBIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBTQ1NTIFZhcmlhYmxlcy5cbiAqXG4gKiBQbGVhc2UgdXNlIHZhcmlhYmxlcyBmcm9tIHRoaXMgc2hlZXQgdG8gZW5zdXJlIGNvbnNpc3RlbmN5IGFjcm9zcyB0aGUgVUkuXG4gKiBEb24ndCBhZGQgdG8gdGhpcyBzaGVldCB1bmxlc3MgeW91J3JlIHByZXR0eSBzdXJlIHRoZSB2YWx1ZSB3aWxsIGJlIHJldXNlZCBpbiBtYW55IHBsYWNlcy5cbiAqIEZvciBleGFtcGxlLCBkb24ndCBhZGQgcnVsZXMgdG8gdGhpcyBzaGVldCB0aGF0IGFmZmVjdCBibG9jayB2aXN1YWxzLiBJdCdzIHB1cmVseSBmb3IgVUkuXG4gKi9cblxuQHVzZSBcIi4vY29sb3JzXCI7XG5cbi8qKlxuICogRm9udHMgJiBiYXNpYyB2YXJpYWJsZXMuXG4gKi9cblxuJGRlZmF1bHQtZm9udDogLWFwcGxlLXN5c3RlbSwgQmxpbmtNYWNTeXN0ZW1Gb250LFwiU2Vnb2UgVUlcIiwgUm9ib3RvLCBPeHlnZW4tU2FucywgVWJ1bnR1LCBDYW50YXJlbGwsXCJIZWx2ZXRpY2EgTmV1ZVwiLCBzYW5zLXNlcmlmOyAvLyBUb2RvOiBkZXByZWNhdGUgaW4gZmF2b3Igb2YgJGZhbWlseSB2YXJpYWJsZXNcbiRkZWZhdWx0LWxpbmUtaGVpZ2h0OiAxLjQ7IC8vIFRvZG86IGRlcHJlY2F0ZSBpbiBmYXZvciBvZiAkbGluZS1oZWlnaHQgdG9rZW5zXG5cbi8qKlxuICogVHlwb2dyYXBoeVxuICovXG5cbi8vIFNpemVzXG4kZm9udC1zaXplLXgtc21hbGw6IDExcHg7XG4kZm9udC1zaXplLXNtYWxsOiAxMnB4O1xuJGZvbnQtc2l6ZS1tZWRpdW06IDEzcHg7XG4kZm9udC1zaXplLWxhcmdlOiAxNXB4O1xuJGZvbnQtc2l6ZS14LWxhcmdlOiAyMHB4O1xuJGZvbnQtc2l6ZS0yeC1sYXJnZTogMzJweDtcblxuLy8gTGluZSBoZWlnaHRzXG4kZm9udC1saW5lLWhlaWdodC14LXNtYWxsOiAxNnB4O1xuJGZvbnQtbGluZS1oZWlnaHQtc21hbGw6IDIwcHg7XG4kZm9udC1saW5lLWhlaWdodC1tZWRpdW06IDI0cHg7XG4kZm9udC1saW5lLWhlaWdodC1sYXJnZTogMjhweDtcbiRmb250LWxpbmUtaGVpZ2h0LXgtbGFyZ2U6IDMycHg7XG4kZm9udC1saW5lLWhlaWdodC0yeC1sYXJnZTogNDBweDtcblxuLy8gV2VpZ2h0c1xuJGZvbnQtd2VpZ2h0LXJlZ3VsYXI6IDQwMDtcbiRmb250LXdlaWdodC1tZWRpdW06IDQ5OTsgLy8gZW5zdXJlcyBmYWxsYmFjayB0byA0MDAgKGluc3RlYWQgb2YgNjAwKVxuXG4vLyBGYW1pbGllc1xuJGZvbnQtZmFtaWx5LWhlYWRpbmdzOiAtYXBwbGUtc3lzdGVtLCBcInN5c3RlbS11aVwiLCBcIlNlZ29lIFVJXCIsIFJvYm90bywgT3h5Z2VuLVNhbnMsIFVidW50dSwgQ2FudGFyZWxsLCBcIkhlbHZldGljYSBOZXVlXCIsIHNhbnMtc2VyaWY7XG4kZm9udC1mYW1pbHktYm9keTogLWFwcGxlLXN5c3RlbSwgXCJzeXN0ZW0tdWlcIiwgXCJTZWdvZSBVSVwiLCBSb2JvdG8sIE94eWdlbi1TYW5zLCBVYnVudHUsIENhbnRhcmVsbCwgXCJIZWx2ZXRpY2EgTmV1ZVwiLCBzYW5zLXNlcmlmO1xuJGZvbnQtZmFtaWx5LW1vbm86IE1lbmxvLCBDb25zb2xhcywgbW9uYWNvLCBtb25vc3BhY2U7XG5cbi8qKlxuICogR3JpZCBTeXN0ZW0uXG4gKiBodHRwczovL21ha2Uud29yZHByZXNzLm9yZy9kZXNpZ24vMjAxOS8xMC8zMS9wcm9wb3NhbC1hLWNvbnNpc3RlbnQtc3BhY2luZy1zeXN0ZW0tZm9yLXdvcmRwcmVzcy9cbiAqL1xuXG4kZ3JpZC11bml0OiA4cHg7XG4kZ3JpZC11bml0LTA1OiAwLjUgKiAkZ3JpZC11bml0O1x0Ly8gNHB4XG4kZ3JpZC11bml0LTEwOiAxICogJGdyaWQtdW5pdDtcdFx0Ly8gOHB4XG4kZ3JpZC11bml0LTE1OiAxLjUgKiAkZ3JpZC11bml0O1x0Ly8gMTJweFxuJGdyaWQtdW5pdC0yMDogMiAqICRncmlkLXVuaXQ7XHRcdC8vIDE2cHhcbiRncmlkLXVuaXQtMzA6IDMgKiAkZ3JpZC11bml0O1x0XHQvLyAyNHB4XG4kZ3JpZC11bml0LTQwOiA0ICogJGdyaWQtdW5pdDtcdFx0Ly8gMzJweFxuJGdyaWQtdW5pdC01MDogNSAqICRncmlkLXVuaXQ7XHRcdC8vIDQwcHhcbiRncmlkLXVuaXQtNjA6IDYgKiAkZ3JpZC11bml0O1x0XHQvLyA0OHB4XG4kZ3JpZC11bml0LTcwOiA3ICogJGdyaWQtdW5pdDtcdFx0Ly8gNTZweFxuJGdyaWQtdW5pdC04MDogOCAqICRncmlkLXVuaXQ7XHRcdC8vIDY0cHhcblxuLyoqXG4gKiBSYWRpdXMgc2NhbGUuXG4gKi9cblxuJHJhZGl1cy14LXNtYWxsOiAxcHg7ICAgLy8gQXBwbGllZCB0byBlbGVtZW50cyBsaWtlIGJ1dHRvbnMgbmVzdGVkIHdpdGhpbiBwcmltaXRpdmVzIGxpa2UgaW5wdXRzLlxuJHJhZGl1cy1zbWFsbDogMnB4OyAgICAgLy8gQXBwbGllZCB0byBtb3N0IHByaW1pdGl2ZXMuXG4kcmFkaXVzLW1lZGl1bTogNHB4OyAgICAvLyBBcHBsaWVkIHRvIGNvbnRhaW5lcnMgd2l0aCBzbWFsbGVyIHBhZGRpbmcuXG4kcmFkaXVzLWxhcmdlOiA4cHg7ICAgICAvLyBBcHBsaWVkIHRvIGNvbnRhaW5lcnMgd2l0aCBsYXJnZXIgcGFkZGluZy5cbiRyYWRpdXMtZnVsbDogOTk5OXB4OyAgIC8vIEZvciBwaWxscy5cbiRyYWRpdXMtcm91bmQ6IDUwJTsgICAgIC8vIEZvciBjaXJjbGVzIGFuZCBvdmFscy5cblxuLyoqXG4gKiBFbGV2YXRpb24gc2NhbGUuXG4gKi9cblxuLy8gRm9yIHNlY3Rpb25zIGFuZCBjb250YWluZXJzIHRoYXQgZ3JvdXAgcmVsYXRlZCBjb250ZW50IGFuZCBjb250cm9scywgd2hpY2ggbWF5IG92ZXJsYXAgb3RoZXIgY29udGVudC4gRXhhbXBsZTogUHJldmlldyBGcmFtZS5cbiRlbGV2YXRpb24teC1zbWFsbDogMCAxcHggMXB4IHJnYmEoY29sb3JzLiRibGFjaywgMC4wMyksIDAgMXB4IDJweCByZ2JhKGNvbG9ycy4kYmxhY2ssIDAuMDIpLCAwIDNweCAzcHggcmdiYShjb2xvcnMuJGJsYWNrLCAwLjAyKSwgMCA0cHggNHB4IHJnYmEoY29sb3JzLiRibGFjaywgMC4wMSk7XG5cbi8vIEZvciBjb21wb25lbnRzIHRoYXQgcHJvdmlkZSBjb250ZXh0dWFsIGZlZWRiYWNrIHdpdGhvdXQgYmVpbmcgaW50cnVzaXZlLiBHZW5lcmFsbHkgbm9uLWludGVycnVwdGl2ZS4gRXhhbXBsZTogVG9vbHRpcHMsIFNuYWNrYmFyLlxuJGVsZXZhdGlvbi1zbWFsbDogMCAxcHggMnB4IHJnYmEoY29sb3JzLiRibGFjaywgMC4wNSksIDAgMnB4IDNweCByZ2JhKGNvbG9ycy4kYmxhY2ssIDAuMDQpLCAwIDZweCA2cHggcmdiYShjb2xvcnMuJGJsYWNrLCAwLjAzKSwgMCA4cHggOHB4IHJnYmEoY29sb3JzLiRibGFjaywgMC4wMik7XG5cbi8vIEZvciBjb21wb25lbnRzIHRoYXQgb2ZmZXIgYWRkaXRpb25hbCBhY3Rpb25zLiBFeGFtcGxlOiBNZW51cywgQ29tbWFuZCBQYWxldHRlXG4kZWxldmF0aW9uLW1lZGl1bTogMCAycHggM3B4IHJnYmEoY29sb3JzLiRibGFjaywgMC4wNSksIDAgNHB4IDVweCByZ2JhKGNvbG9ycy4kYmxhY2ssIDAuMDQpLCAwIDEycHggMTJweCByZ2JhKGNvbG9ycy4kYmxhY2ssIDAuMDMpLCAwIDE2cHggMTZweCByZ2JhKGNvbG9ycy4kYmxhY2ssIDAuMDIpO1xuXG4vLyBGb3IgY29tcG9uZW50cyB0aGF0IGNvbmZpcm0gZGVjaXNpb25zIG9yIGhhbmRsZSBuZWNlc3NhcnkgaW50ZXJydXB0aW9ucy4gRXhhbXBsZTogTW9kYWxzLlxuJGVsZXZhdGlvbi1sYXJnZTogMCA1cHggMTVweCByZ2JhKGNvbG9ycy4kYmxhY2ssIDAuMDgpLCAwIDE1cHggMjdweCByZ2JhKGNvbG9ycy4kYmxhY2ssIDAuMDcpLCAwIDMwcHggMzZweCByZ2JhKGNvbG9ycy4kYmxhY2ssIDAuMDQpLCAwIDUwcHggNDNweCByZ2JhKGNvbG9ycy4kYmxhY2ssIDAuMDIpO1xuXG4vKipcbiAqIERpbWVuc2lvbnMuXG4gKi9cblxuJGljb24tc2l6ZTogMjRweDtcbiRidXR0b24tc2l6ZTogMzZweDtcbiRidXR0b24tc2l6ZS1uZXh0LWRlZmF1bHQtNDBweDogNDBweDsgLy8gdHJhbnNpdGlvbmFyeSB2YXJpYWJsZSBmb3IgbmV4dCBkZWZhdWx0IGJ1dHRvbiBzaXplXG4kYnV0dG9uLXNpemUtc21hbGw6IDI0cHg7XG4kYnV0dG9uLXNpemUtY29tcGFjdDogMzJweDtcbiRoZWFkZXItaGVpZ2h0OiA2NHB4O1xuJHBhbmVsLWhlYWRlci1oZWlnaHQ6ICRncmlkLXVuaXQtNjA7XG4kbmF2LXNpZGViYXItd2lkdGg6IDMwMHB4O1xuJGFkbWluLWJhci1oZWlnaHQ6IDMycHg7XG4kYWRtaW4tYmFyLWhlaWdodC1iaWc6IDQ2cHg7XG4kYWRtaW4tc2lkZWJhci13aWR0aDogMTYwcHg7XG4kYWRtaW4tc2lkZWJhci13aWR0aC1iaWc6IDE5MHB4O1xuJGFkbWluLXNpZGViYXItd2lkdGgtY29sbGFwc2VkOiAzNnB4O1xuJG1vZGFsLW1pbi13aWR0aDogMzUwcHg7XG4kbW9kYWwtd2lkdGgtc21hbGw6IDM4NHB4O1xuJG1vZGFsLXdpZHRoLW1lZGl1bTogNTEycHg7XG4kbW9kYWwtd2lkdGgtbGFyZ2U6IDg0MHB4O1xuJHNwaW5uZXItc2l6ZTogMTZweDtcbiRjYW52YXMtcGFkZGluZzogJGdyaWQtdW5pdC0yMDtcbiRwYWxldHRlLW1heC1oZWlnaHQ6IDM2OHB4O1xuXG4vKipcbiAqIE1vYmlsZSBzcGVjaWZpYyBzdHlsZXNcbiAqL1xuJG1vYmlsZS10ZXh0LW1pbi1mb250LXNpemU6IDE2cHg7IC8vIEFueSBmb250IHNpemUgYmVsb3cgMTZweCB3aWxsIGNhdXNlIE1vYmlsZSBTYWZhcmkgdG8gXCJ6b29tIGluXCIuXG5cbi8qKlxuICogRWRpdG9yIHN0eWxlcy5cbiAqL1xuXG4kc2lkZWJhci13aWR0aDogMjgwcHg7XG4kY29udGVudC13aWR0aDogODQwcHg7XG4kd2lkZS1jb250ZW50LXdpZHRoOiAxMTAwcHg7XG4kd2lkZ2V0LWFyZWEtd2lkdGg6IDcwMHB4O1xuJHNlY29uZGFyeS1zaWRlYmFyLXdpZHRoOiAzNTBweDtcbiRlZGl0b3ItZm9udC1zaXplOiAxNnB4O1xuJGRlZmF1bHQtYmxvY2stbWFyZ2luOiAyOHB4OyAvLyBUaGlzIHZhbHVlIHByb3ZpZGVzIGEgY29uc2lzdGVudCwgY29udGlndW91cyBzcGFjaW5nIGJldHdlZW4gYmxvY2tzLlxuJHRleHQtZWRpdG9yLWZvbnQtc2l6ZTogMTVweDtcbiRlZGl0b3ItbGluZS1oZWlnaHQ6IDEuODtcbiRlZGl0b3ItaHRtbC1mb250OiAkZm9udC1mYW1pbHktbW9ubztcblxuLyoqXG4gKiBCbG9jayAmIEVkaXRvciBVSS5cbiAqL1xuXG4kYmxvY2stdG9vbGJhci1oZWlnaHQ6ICRncmlkLXVuaXQtNjA7XG4kYm9yZGVyLXdpZHRoOiAxcHg7XG4kYm9yZGVyLXdpZHRoLWZvY3VzLWZhbGxiYWNrOiAycHg7IC8vIFRoaXMgZXhpc3RzIGFzIGEgZmFsbGJhY2ssIGFuZCBpcyBpZGVhbGx5IG92ZXJyaWRkZW4gYnkgdmFyKC0td3AtYWRtaW4tYm9yZGVyLXdpZHRoLWZvY3VzKSB1bmxlc3MgaW4gc29tZSBTQVNTIG1hdGggY2FzZXMuXG4kYm9yZGVyLXdpZHRoLXRhYjogMS41cHg7XG4kaGVscHRleHQtZm9udC1zaXplOiAxMnB4O1xuJHJhZGlvLWlucHV0LXNpemU6IDE2cHg7XG4kcmFkaW8taW5wdXQtc2l6ZS1zbTogMjRweDsgLy8gV2lkdGggJiBoZWlnaHQgZm9yIHNtYWxsIHZpZXdwb3J0cy5cblxuLy8gRGVwcmVjYXRlZCwgcGxlYXNlIGF2b2lkIHVzaW5nIHRoZXNlLlxuJGJsb2NrLXBhZGRpbmc6IDE0cHg7IC8vIFVzZWQgdG8gZGVmaW5lIHNwYWNlIGJldHdlZW4gYmxvY2sgZm9vdHByaW50IGFuZCBzdXJyb3VuZGluZyBib3JkZXJzLlxuJHJhZGl1cy1ibG9jay11aTogJHJhZGl1cy1zbWFsbDtcbiRzaGFkb3ctcG9wb3ZlcjogJGVsZXZhdGlvbi14LXNtYWxsO1xuJHNoYWRvdy1tb2RhbDogJGVsZXZhdGlvbi1sYXJnZTtcbiRkZWZhdWx0LWZvbnQtc2l6ZTogJGZvbnQtc2l6ZS1tZWRpdW07XG5cbi8qKlxuICogQmxvY2sgcGFkZGluZ3MuXG4gKi9cblxuLy8gUGFkZGluZyBmb3IgYmxvY2tzIHdpdGggYSBiYWNrZ3JvdW5kIGNvbG9yIChlLmcuIHBhcmFncmFwaCBvciBncm91cCkuXG4kYmxvY2stYmctcGFkZGluZy0tdjogMS4yNWVtO1xuJGJsb2NrLWJnLXBhZGRpbmctLWg6IDIuMzc1ZW07XG5cblxuLyoqXG4gKiBSZWFjdCBOYXRpdmUgc3BlY2lmaWMuXG4gKiBUaGVzZSB2YXJpYWJsZXMgZG8gbm90IGFwcGVhciB0byBiZSB1c2VkIGFueXdoZXJlIGVsc2UuXG4gKi9cblxuLy8gRGltZW5zaW9ucy5cbiRtb2JpbGUtaGVhZGVyLXRvb2xiYXItaGVpZ2h0OiA0NHB4O1xuJG1vYmlsZS1oZWFkZXItdG9vbGJhci1leHBhbmRlZC1oZWlnaHQ6IDUycHg7XG4kbW9iaWxlLWZsb2F0aW5nLXRvb2xiYXItaGVpZ2h0OiA0NHB4O1xuJG1vYmlsZS1mbG9hdGluZy10b29sYmFyLW1hcmdpbjogOHB4O1xuJG1vYmlsZS1jb2xvci1zd2F0Y2g6IDQ4cHg7XG5cbi8vIEJsb2NrIFVJLlxuJG1vYmlsZS1ibG9jay10b29sYmFyLWhlaWdodDogNDRweDtcbiRkaW1tZWQtb3BhY2l0eTogMTtcbiRibG9jay1lZGdlLXRvLWNvbnRlbnQ6IDE2cHg7XG4kc29saWQtYm9yZGVyLXNwYWNlOiAxMnB4O1xuJGRhc2hlZC1ib3JkZXItc3BhY2U6IDZweDtcbiRibG9jay1zZWxlY3RlZC1tYXJnaW46IDNweDtcbiRibG9jay1zZWxlY3RlZC1ib3JkZXItd2lkdGg6IDFweDtcbiRibG9jay1zZWxlY3RlZC1wYWRkaW5nOiAwO1xuJGJsb2NrLXNlbGVjdGVkLWNoaWxkLW1hcmdpbjogNXB4O1xuJGJsb2NrLXNlbGVjdGVkLXRvLWNvbnRlbnQ6ICRibG9jay1lZGdlLXRvLWNvbnRlbnQgLSAkYmxvY2stc2VsZWN0ZWQtbWFyZ2luIC0gJGJsb2NrLXNlbGVjdGVkLWJvcmRlci13aWR0aDtcbiIsIi8qKlxuICogQ29sb3JzXG4gKi9cblxuLy8gV29yZFByZXNzIGdyYXlzLlxuJGJsYWNrOiAjMDAwO1x0XHRcdC8vIFVzZSBvbmx5IHdoZW4geW91IHRydWx5IG5lZWQgcHVyZSBibGFjay4gRm9yIFVJLCB1c2UgJGdyYXktOTAwLlxuJGdyYXktOTAwOiAjMWUxZTFlO1xuJGdyYXktODAwOiAjMmYyZjJmO1xuJGdyYXktNzAwOiAjNzU3NTc1O1x0XHQvLyBNZWV0cyA0LjY6MSAoNC41OjEgaXMgbWluaW11bSkgdGV4dCBjb250cmFzdCBhZ2FpbnN0IHdoaXRlLlxuJGdyYXktNjAwOiAjOTQ5NDk0O1x0XHQvLyBNZWV0cyAzOjEgVUkgb3IgbGFyZ2UgdGV4dCBjb250cmFzdCBhZ2FpbnN0IHdoaXRlLlxuJGdyYXktNDAwOiAjY2NjO1xuJGdyYXktMzAwOiAjZGRkO1x0XHQvLyBVc2VkIGZvciBtb3N0IGJvcmRlcnMuXG4kZ3JheS0yMDA6ICNlMGUwZTA7XHRcdC8vIFVzZWQgc3BhcmluZ2x5IGZvciBsaWdodCBib3JkZXJzLlxuJGdyYXktMTAwOiAjZjBmMGYwO1x0XHQvLyBVc2VkIGZvciBsaWdodCBncmF5IGJhY2tncm91bmRzLlxuJHdoaXRlOiAjZmZmO1xuXG4vLyBPcGFjaXRpZXMgJiBhZGRpdGlvbmFsIGNvbG9ycy5cbiRkYXJrLWdyYXktcGxhY2Vob2xkZXI6IHJnYmEoJGdyYXktOTAwLCAwLjYyKTtcbiRtZWRpdW0tZ3JheS1wbGFjZWhvbGRlcjogcmdiYSgkZ3JheS05MDAsIDAuNTUpO1xuJGxpZ2h0LWdyYXktcGxhY2Vob2xkZXI6IHJnYmEoJHdoaXRlLCAwLjY1KTtcblxuLy8gQWxlcnQgY29sb3JzLlxuJGFsZXJ0LXllbGxvdzogI2YwYjg0OTtcbiRhbGVydC1yZWQ6ICNjYzE4MTg7XG4kYWxlcnQtZ3JlZW46ICM0YWI4NjY7XG5cbi8vIERlcHJlY2F0ZWQsIHBsZWFzZSBhdm9pZCB1c2luZyB0aGVzZS5cbiRkYXJrLXRoZW1lLWZvY3VzOiAkd2hpdGU7XHQvLyBGb2N1cyBjb2xvciB3aGVuIHRoZSB0aGVtZSBpcyBkYXJrLlxuIiwiQHVzZSBcIkB3b3JkcHJlc3MvYmFzZS1zdHlsZXMvdmFyaWFibGVzXCIgYXMgKjtcbkB1c2UgXCJAd29yZHByZXNzL2Jhc2Utc3R5bGVzL2NvbG9yc1wiIGFzICo7XG5AdXNlIFwiQHdvcmRwcmVzcy9iYXNlLXN0eWxlcy96LWluZGV4XCIgYXMgKjtcblxuLmJsb2NrLWVkaXRvci1ibG9jay12aXNpYmlsaXR5LW1vZGFsIHtcblx0ei1pbmRleDogei1pbmRleChcIi5ibG9jay1lZGl0b3ItYmxvY2stdmlzaWJpbGl0eS1tb2RhbFwiKTtcblxuXHQmX19vcHRpb25zIHtcblx0XHRib3JkZXI6IDA7XG5cdFx0cGFkZGluZzogMDtcblx0XHRsaXN0LXN0eWxlOiBub25lO1xuXHRcdG1hcmdpbjogJGdyaWQtdW5pdC0zMCAwO1xuXG5cdFx0Ji1pdGVtIHtcblx0XHRcdGRpc3BsYXk6IGZsZXg7XG5cdFx0XHRhbGlnbi1pdGVtczogY2VudGVyO1xuXHRcdFx0anVzdGlmeS1jb250ZW50OiBzcGFjZS1iZXR3ZWVuO1xuXHRcdFx0bWFyZ2luOiAwIDAgJGdyaWQtdW5pdC0yMCAwO1xuXHRcdFx0Z2FwOiAkZ3JpZC11bml0LTMwO1xuXHRcdH1cblxuXHRcdCYtaXRlbTpsYXN0LWNoaWxkIHtcblx0XHRcdG1hcmdpbjogMDtcblx0XHR9XG5cblx0XHQmLWl0ZW0tLWV2ZXJ5d2hlcmUge1xuXHRcdFx0ZmxleC1kaXJlY3Rpb246IGNvbHVtbjtcblx0XHRcdGFsaWduLWl0ZW1zOiBzdGFydDtcblx0XHR9XG5cblx0XHQmLWNoZWNrYm94LS1ldmVyeXdoZXJlIHtcblx0XHRcdGZvbnQtd2VpZ2h0OiA2MDA7XG5cdFx0fVxuXG5cdFx0Ji1pY29uLS1jaGVja2VkIHtcblx0XHRcdGZpbGw6ICRncmF5LTMwMDtcblx0XHR9XG5cdH1cblxuXHQmX19zdWItb3B0aW9ucyB7XG5cdFx0d2lkdGg6IDEwMCU7XG5cdFx0cGFkZGluZy1pbmxpbmUtc3RhcnQ6ICRncmlkLXVuaXQtMTU7XG5cdH1cblxuXHQmX19kZXNjcmlwdGlvbiB7XG5cdFx0Zm9udC1zaXplOiAkZm9udC1zaXplLXNtYWxsO1xuXHRcdGNvbG9yOiAkZ3JheS03MDA7XG5cdH1cbn1cblxuLmJsb2NrLWVkaXRvci1ibG9jay12aXNpYmlsaXR5LWluZm8ge1xuXHRwYWRkaW5nLXRvcDogJGdyaWQtdW5pdC0wNTtcblx0cGFkZGluZy1ib3R0b206ICRncmlkLXVuaXQtMDU7XG5cdG1hcmdpbjogMCAkZ3JpZC11bml0LTIwICRncmlkLXVuaXQtMjA7XG5cdGRpc3BsYXk6IGZsZXg7XG5cdGFsaWduLWl0ZW1zOiBjZW50ZXI7XG5cdGp1c3RpZnktY29udGVudDogc3RhcnQ7XG59XG4iXX0= */`;
document.head.appendChild(document.createElement("style")).appendChild(document.createTextNode(css));
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_data25.useDispatch)(import_notices3.store);
const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data25.useDispatch)(store);
const blocks2 = (0, import_data25.useSelect)(
(select3) => select3(store).getBlocksByClientId(clientIds) ?? EMPTY_BLOCKS,
[clientIds]
);
const listViewShortcut = (0, import_data25.useSelect)((select3) => {
return select3(import_keyboard_shortcuts.store).getShortcutRepresentation(
"core/editor/toggle-list-view"
);
}, []);
const initialViewportValues = (0, import_element30.useMemo)(() => {
if (blocks2?.length === 0) {
return {
hideEverywhere: false,
viewportChecked: {}
};
}
const viewportValues = {};
BLOCK_VISIBILITY_VIEWPORT_ENTRIES.forEach(([, { key }]) => {
viewportValues[key] = getViewportCheckboxState(blocks2, key);
});
return {
hideEverywhere: getHideEverywhereCheckboxState(blocks2),
viewportChecked: viewportValues
};
}, [blocks2]);
const [viewportChecked, setViewportChecked] = (0, import_element30.useState)(
initialViewportValues?.viewportChecked ?? {}
);
const [hideEverywhere, setHideEverywhere] = (0, import_element30.useState)(
initialViewportValues?.hideEverywhere ?? false
);
const handleViewportCheckboxChange = (0, import_element30.useCallback)(
(viewport, isChecked) => {
setViewportChecked({
...viewportChecked,
[viewport]: isChecked
});
},
[viewportChecked]
);
const noticeMessage = (0, import_element30.useMemo)(() => {
if (!hideEverywhere) {
return (0, import_i18n25.sprintf)(
// translators: %s: The shortcut key to access the List View.
(0, import_i18n25.__)(
"Block visibility settings saved. 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_i18n25.__)(
"Blocks hidden. You can access them via the List View (%s)."
)
) : (
// translators: %s: The shortcut key to access the List View.
(0, import_i18n25.__)(
"Block hidden. You can access it via the List View (%s)."
)
);
return (0, import_i18n25.sprintf)(message2, listViewShortcut);
}, [hideEverywhere, blocks2?.length, listViewShortcut]);
const isAnyViewportChecked = (0, import_element30.useMemo)(
() => Object.values(viewportChecked).some(
(checked) => checked === true || checked === null
),
[viewportChecked]
);
const hasIndeterminateValues = (0, import_element30.useMemo)(() => {
if (hideEverywhere === null) {
return true;
}
return Object.values(viewportChecked).some(
(checked) => checked === null
);
}, [hideEverywhere, viewportChecked]);
const handleSubmit = (0, import_element30.useCallback)(
(event) => {
event.preventDefault();
const newVisibility = hideEverywhere ? false : BLOCK_VISIBILITY_VIEWPORT_ENTRIES.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-saved",
type: "snackbar"
});
onClose();
},
[
blocks2,
clientIds,
createSuccessNotice,
hideEverywhere,
noticeMessage,
onClose,
updateBlockAttributes2,
viewportChecked
]
);
const hasMultipleBlocks = blocks2?.length > 1;
return /* @__PURE__ */ (0, import_jsx_runtime147.jsx)(
import_components24.Modal,
{
title: clientIds?.length > 1 ? (0, import_i18n25.__)("Hide blocks") : (0, import_i18n25.__)("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_i18n25.__)(
"Select the viewport sizes for which you want to hide the blocks. Changes will apply to all selected blocks."
) : (0, import_i18n25.__)(
"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_i18n25.__)("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: BLOCK_VISIBILITY_VIEWPORT_ENTRIES.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_i18n25.sprintf)(
// translators: %s: The viewport name.
(0, import_i18n25.__)("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_i18n25.__)(
"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_i18n25.sprintf)(
// translators: %s: The shortcut key to access the List View.
(0, import_i18n25.__)(
"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_element30.createInterpolateElement)(
(0, import_i18n25.sprintf)(
// translators: %s: The shortcut key to access the List View
(0, import_i18n25.__)(
"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_i18n25.__)("Cancel")
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime147.jsx)(import_components24.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime147.jsx)(
import_components24.Button,
{
variant: "primary",
type: "submit",
__next40pxDefaultSize: true,
children: (0, import_i18n25.__)("Apply")
}
) })
]
}
)
] })
}
);
}
// packages/block-editor/build-module/components/block-visibility/use-block-visibility.mjs
var import_compose15 = __toESM(require_compose(), 1);
var import_element31 = __toESM(require_element(), 1);
function useBlockVisibility(options = {}) {
const {
blockVisibility: blockVisibility2 = void 0,
deviceType = BLOCK_VISIBILITY_VIEWPORTS.desktop.key
} = options;
const isLargerThanMobile = (0, import_compose15.useViewportMatch)("mobile", ">=");
const isLargerThanTablet = (0, import_compose15.useViewportMatch)("medium", ">=");
const currentViewport = (0, import_element31.useMemo)(() => {
if (deviceType === BLOCK_VISIBILITY_VIEWPORTS.mobile.key) {
return BLOCK_VISIBILITY_VIEWPORTS.mobile.key;
}
if (deviceType === BLOCK_VISIBILITY_VIEWPORTS.tablet.key) {
return BLOCK_VISIBILITY_VIEWPORTS.tablet.key;
}
if (!isLargerThanMobile) {
return BLOCK_VISIBILITY_VIEWPORTS.mobile.key;
}
if (isLargerThanMobile && !isLargerThanTablet) {
return BLOCK_VISIBILITY_VIEWPORTS.tablet.key;
}
return BLOCK_VISIBILITY_VIEWPORTS.desktop.key;
}, [deviceType, isLargerThanMobile, isLargerThanTablet]);
const isBlockCurrentlyHidden = (0, import_element31.useMemo)(() => {
if (blockVisibility2 === false) {
return true;
}
if (window.__experimentalHideBlocksBasedOnScreenSize && blockVisibility2?.[currentViewport] === false) {
return true;
}
return false;
}, [blockVisibility2, currentViewport]);
return {
isBlockCurrentlyHidden,
currentViewport
};
}
// packages/block-editor/build-module/components/block-visibility/toolbar.mjs
var import_i18n26 = __toESM(require_i18n(), 1);
var import_components25 = __toESM(require_components(), 1);
var import_element32 = __toESM(require_element(), 1);
var import_data26 = __toESM(require_data(), 1);
var import_blocks19 = __toESM(require_blocks(), 1);
var import_jsx_runtime148 = __toESM(require_jsx_runtime(), 1);
function BlockVisibilityToolbar({ clientIds }) {
const { blocks: blocks2, canToggleBlockVisibility } = (0, import_data26.useSelect)(
(select3) => {
const { getBlockName: getBlockName2, getBlocksByClientId: getBlocksByClientId2 } = select3(store);
const _blocks = getBlocksByClientId2(clientIds);
return {
blocks: _blocks,
canToggleBlockVisibility: _blocks.every(
({ clientId }) => (0, import_blocks19.hasBlockSupport)(
getBlockName2(clientId),
"visibility",
true
)
)
};
},
[clientIds]
);
const hasHiddenBlock = blocks2.some(
(block) => block.attributes.metadata?.blockVisibility === false
);
const hasBlockVisibilityButtonShownRef = (0, import_element32.useRef)(false);
const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data26.useDispatch)(store);
(0, import_element32.useEffect)(() => {
if (hasHiddenBlock) {
hasBlockVisibilityButtonShownRef.current = true;
}
}, [hasHiddenBlock]);
if (!hasHiddenBlock && !hasBlockVisibilityButtonShownRef.current) {
return null;
}
const toggleBlockVisibility = () => {
const attributesByClientId = Object.fromEntries(
blocks2?.map(({ clientId, attributes }) => [
clientId,
{
metadata: cleanEmptyObject({
...attributes?.metadata,
blockVisibility: hasHiddenBlock ? void 0 : false
})
}
])
);
updateBlockAttributes2(clientIds, attributesByClientId, {
uniqueByBlock: true
});
};
return /* @__PURE__ */ (0, import_jsx_runtime148.jsx)(import_jsx_runtime148.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime148.jsx)(import_components25.ToolbarGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime148.jsx)(
import_components25.ToolbarButton,
{
disabled: !canToggleBlockVisibility,
icon: hasHiddenBlock ? unseen_default : seen_default,
label: hasHiddenBlock ? (0, import_i18n26.__)("Hidden") : (0, import_i18n26.__)("Visible"),
onClick: toggleBlockVisibility
}
) }) });
}
// packages/block-editor/build-module/components/block-visibility/viewport-toolbar.mjs
var import_i18n27 = __toESM(require_i18n(), 1);
var import_components26 = __toESM(require_components(), 1);
var import_element33 = __toESM(require_element(), 1);
var import_blocks20 = __toESM(require_blocks(), 1);
var import_data27 = __toESM(require_data(), 1);
var import_jsx_runtime149 = __toESM(require_jsx_runtime(), 1);
function BlockVisibilityViewportToolbar({ clientIds }) {
const hasBlockVisibilityButtonShownRef = (0, import_element33.useRef)(false);
const [isModalOpen, setIsModalOpen] = (0, import_element33.useState)(false);
const { canToggleBlockVisibility, areBlocksHiddenAnywhere: areBlocksHiddenAnywhere2 } = (0, import_data27.useSelect)(
(select3) => {
const {
getBlocksByClientId: getBlocksByClientId2,
getBlockName: getBlockName2,
areBlocksHiddenAnywhere: _areBlocksHiddenAnywhere
} = unlock(select3(store));
const _blocks = getBlocksByClientId2(clientIds);
return {
canToggleBlockVisibility: _blocks.every(
({ clientId }) => (0, import_blocks20.hasBlockSupport)(
getBlockName2(clientId),
"visibility",
true
)
),
areBlocksHiddenAnywhere: _areBlocksHiddenAnywhere(clientIds)
};
},
[clientIds]
);
(0, import_element33.useEffect)(() => {
if (areBlocksHiddenAnywhere2) {
hasBlockVisibilityButtonShownRef.current = true;
}
}, [areBlocksHiddenAnywhere2]);
if (!areBlocksHiddenAnywhere2 && !hasBlockVisibilityButtonShownRef.current) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime149.jsxs)(import_jsx_runtime149.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime149.jsx)(import_components26.ToolbarGroup, { className: "block-editor-block-visibility-toolbar", children: /* @__PURE__ */ (0, import_jsx_runtime149.jsx)(
import_components26.ToolbarButton,
{
disabled: !canToggleBlockVisibility,
icon: areBlocksHiddenAnywhere2 ? unseen_default : seen_default,
label: areBlocksHiddenAnywhere2 ? (0, import_i18n27.__)("Hidden") : (0, import_i18n27.__)("Visible"),
onClick: () => setIsModalOpen(true),
"aria-expanded": isModalOpen,
"aria-haspopup": !isModalOpen ? "dialog" : void 0
}
) }),
isModalOpen && /* @__PURE__ */ (0, import_jsx_runtime149.jsx)(
BlockVisibilityModal,
{
clientIds,
onClose: () => setIsModalOpen(false)
}
)
] });
}
// packages/block-editor/build-module/components/block-visibility/menu-item.mjs
var import_i18n28 = __toESM(require_i18n(), 1);
var import_components27 = __toESM(require_components(), 1);
var import_data28 = __toESM(require_data(), 1);
var import_notices4 = __toESM(require_notices(), 1);
var import_keyboard_shortcuts2 = __toESM(require_keyboard_shortcuts(), 1);
var import_jsx_runtime150 = __toESM(require_jsx_runtime(), 1);
function BlockVisibilityMenuItem({ clientIds }) {
const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data28.useDispatch)(store);
const { createSuccessNotice } = (0, import_data28.useDispatch)(import_notices4.store);
const blocks2 = (0, import_data28.useSelect)(
(select3) => {
return select3(store).getBlocksByClientId(clientIds);
},
[clientIds]
);
const listViewShortcut = (0, import_data28.useSelect)((select3) => {
return select3(import_keyboard_shortcuts2.store).getShortcutRepresentation(
"core/editor/toggle-list-view"
);
}, []);
const hasHiddenBlock = blocks2.some(
(block) => block.attributes.metadata?.blockVisibility === false
);
const toggleBlockVisibility = () => {
const isHiding = !hasHiddenBlock;
const attributesByClientId = Object.fromEntries(
blocks2?.map(({ clientId, attributes }) => [
clientId,
{
metadata: cleanEmptyObject({
...attributes?.metadata,
blockVisibility: isHiding ? false : void 0
})
}
])
);
updateBlockAttributes2(clientIds, attributesByClientId, {
uniqueByBlock: true
});
if (isHiding) {
if (blocks2.length > 1) {
createSuccessNotice(
(0, import_i18n28.sprintf)(
// translators: %s: The shortcut key to access the List View.
(0, import_i18n28.__)(
"Blocks hidden. You can access them via the List View (%s)."
),
listViewShortcut
),
{
id: "block-visibility-hidden",
type: "snackbar"
}
);
} else {
createSuccessNotice(
(0, import_i18n28.sprintf)(
// translators: %s: The shortcut key to access the List View.
(0, import_i18n28.__)(
"Block hidden. You can access it via the List View (%s)."
),
listViewShortcut
),
{
id: "block-visibility-hidden",
type: "snackbar"
}
);
}
}
};
return /* @__PURE__ */ (0, import_jsx_runtime150.jsx)(
import_components27.MenuItem,
{
icon: hasHiddenBlock ? seen_default : unseen_default,
onClick: toggleBlockVisibility,
children: hasHiddenBlock ? (0, import_i18n28.__)("Show") : (0, import_i18n28.__)("Hide")
}
);
}
// packages/block-editor/build-module/components/block-visibility/viewport-menu-item.mjs
var import_i18n29 = __toESM(require_i18n(), 1);
var import_components28 = __toESM(require_components(), 1);
var import_element34 = __toESM(require_element(), 1);
var import_data29 = __toESM(require_data(), 1);
var import_jsx_runtime151 = __toESM(require_jsx_runtime(), 1);
function BlockVisibilityViewportMenuItem({ clientIds }) {
const [isModalOpen, setIsModalOpen] = (0, import_element34.useState)(false);
const areBlocksHiddenAnywhere2 = (0, import_data29.useSelect)(
(select3) => unlock(select3(store)).areBlocksHiddenAnywhere(
clientIds
),
[clientIds]
);
return /* @__PURE__ */ (0, import_jsx_runtime151.jsxs)(import_jsx_runtime151.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime151.jsx)(
import_components28.MenuItem,
{
icon: areBlocksHiddenAnywhere2 ? unseen_default : seen_default,
onClick: () => setIsModalOpen(true),
children: areBlocksHiddenAnywhere2 ? (0, import_i18n29.__)("Show") : (0, import_i18n29.__)("Hide")
}
),
isModalOpen && /* @__PURE__ */ (0, import_jsx_runtime151.jsx)(
BlockVisibilityModal,
{
clientIds,
onClose: () => setIsModalOpen(false)
}
)
] });
}
// packages/block-editor/build-module/components/block-visibility/index.mjs
var hasViewportVisibilityExperiment = typeof window !== "undefined" && window.__experimentalHideBlocksBasedOnScreenSize;
var BlockVisibilityMenuItem2 = hasViewportVisibilityExperiment ? BlockVisibilityViewportMenuItem : BlockVisibilityMenuItem;
var BlockVisibilityToolbar2 = hasViewportVisibilityExperiment ? BlockVisibilityViewportToolbar : BlockVisibilityToolbar;
// packages/block-editor/build-module/components/block-list/use-block-props/index.mjs
function useBlockProps(props = {}, { __unstableIsHtml } = {}) {
const {
clientId,
className,
wrapperProps = {},
isAligned,
index,
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
} = (0, import_element35.useContext)(PrivateBlockContext);
const blockLabel = (0, import_i18n30.sprintf)((0, import_i18n30.__)("Block: %s"), blockTitle);
const htmlSuffix = mode2 === "html" && !__unstableIsHtml ? "-visual" : "";
const ffDragRef = useFirefoxDraggableCompatibility();
const isHoverEnabled = !isWithinSectionBlock;
const mergedRefs = (0, import_compose16.useMergeRefs)([
props.ref,
useFocusFirstElement({ clientId, initialPosition: initialPosition2 }),
useBlockRefProvider(clientId),
useFocusHandler(clientId),
useEventHandlers({ clientId, isSelected }),
useIsHovered({ isEnabled: isHoverEnabled }),
useIntersectionObserver(),
use_moving_animation_default({ triggerAnimationOnChange: index, 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
});
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_blocks21.__unstableGetBlockProps;
// packages/block-editor/build-module/components/block-list/block.mjs
var import_jsx_runtime152 = __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_runtime152.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_element36.useContext)(PrivateBlockContext);
const parentLayout = useLayout() || {};
let blockEdit = /* @__PURE__ */ (0, import_jsx_runtime152.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_blocks22.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_runtime152.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_blocks22.serializeRawBlock)(__unstableBlockSource) : (0, import_blocks22.getSaveContent)(blockType, attributes);
block = /* @__PURE__ */ (0, import_jsx_runtime152.jsxs)(Block, { className: "has-warning", children: [
/* @__PURE__ */ (0, import_jsx_runtime152.jsx)(BlockInvalidWarning, { clientId }),
/* @__PURE__ */ (0, import_jsx_runtime152.jsx)(import_element36.RawHTML, { children: (0, import_dom7.safeHTML)(saveContent) })
] });
} else if (mode2 === "html") {
block = /* @__PURE__ */ (0, import_jsx_runtime152.jsxs)(import_jsx_runtime152.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime152.jsx)("div", { style: { display: "none" }, children: blockEdit }),
/* @__PURE__ */ (0, import_jsx_runtime152.jsx)(Block, { isHtml: true, children: /* @__PURE__ */ (0, import_jsx_runtime152.jsx)(block_html_default, { clientId }) })
] });
} else if (blockType?.apiVersion > 1) {
block = blockEdit;
} else {
block = /* @__PURE__ */ (0, import_jsx_runtime152.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_runtime152.jsx)(
PrivateBlockContext.Provider,
{
value: {
wrapperProps: updatedWrapperProps,
isAligned,
isSelectionWithinCurrentSection,
...context
},
children: /* @__PURE__ */ (0, import_jsx_runtime152.jsx)(
block_crash_boundary_default,
{
fallback: /* @__PURE__ */ (0, import_jsx_runtime152.jsx)(Block, { className: "has-warning", children: /* @__PURE__ */ (0, import_jsx_runtime152.jsx)(block_crash_warning_default, {}) }),
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, index) {
const { rootClientId } = ownProps;
insertBlocks2(blocks2, index, rootClientId);
},
onInsertBlocksAfter(blocks2) {
const { clientId, rootClientId } = ownProps;
const { getBlockIndex: getBlockIndex2 } = registry.select(store);
const index = getBlockIndex2(clientId);
insertBlocks2(blocks2, index + 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_blocks22.getDefaultBlockName)();
const defaultBlockType = (0, import_blocks22.getBlockType)(defaultBlockName);
if (getBlockName2(clientId) !== defaultBlockName) {
const replacement = (0, import_blocks22.switchToBlockType)(
block,
defaultBlockName
);
if (replacement && replacement.length) {
replaceBlocks2(clientId, replacement);
}
} else if ((0, import_blocks22.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_blocks22.createBlock)(defaultBlockName, attributes)]
);
}
}
function moveFirstItemUp(_clientId, changeSelection = true) {
const wrapperBlockName = getBlockName2(_clientId);
const wrapperBlockType = (0, import_blocks22.getBlockType)(wrapperBlockName);
const isTextualWrapper = wrapperBlockType.category === "text";
const targetRootClientId = getBlockRootClientId2(_clientId);
const blockOrder = getBlockOrder2(_clientId);
const [firstClientId] = blockOrder;
if (blockOrder.length === 1 && (0, import_blocks22.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_blocks22.switchToBlockType)(
getBlock2(firstClientId),
(0, import_blocks22.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_blocks22.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_blocks22.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_components29.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: getSettings8,
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 blockWithoutAttributes2 = getBlockWithoutAttributes2(clientId);
if (!blockWithoutAttributes2) {
return;
}
const {
hasBlockSupport: _hasBlockSupport,
getActiveBlockVariation
} = select3(import_blocks22.store);
const attributes2 = getBlockAttributes3(clientId);
const { name: blockName, isValid: isValid22 } = blockWithoutAttributes2;
const blockType2 = (0, import_blocks22.getBlockType)(blockName);
const settings2 = getSettings8();
const {
supportsLayout,
isPreviewMode: isPreviewMode2,
__experimentalBlockBindingsSupportedAttributes
} = settings2;
const bindableAttributes2 = __experimentalBlockBindingsSupportedAttributes?.[blockName];
const blockVisibility22 = attributes2?.metadata?.blockVisibility;
const deviceType2 = settings2?.[deviceTypeKey]?.toLowerCase() || "desktop";
const hasLightBlockWrapper = blockType2?.apiVersion > 1;
const previewContext = {
isPreviewMode: isPreviewMode2,
blockWithoutAttributes: blockWithoutAttributes2,
name: blockName,
attributes: attributes2,
isValid: isValid22,
themeSupportsLayout: supportsLayout,
index: getBlockIndex2(clientId),
isReusable: (0, import_blocks22.isReusableBlock)(blockType2),
className: hasLightBlockWrapper ? attributes2.className : void 0,
defaultClassName: hasLightBlockWrapper ? (0, import_blocks22.getBlockDefaultClassName)(blockName) : void 0,
blockTitle: blockType2?.title,
bindableAttributes: bindableAttributes2,
blockVisibility: blockVisibility22,
deviceType: deviceType2
};
if (isPreviewMode2) {
return previewContext;
}
const _isSelected = isBlockSelected2(clientId);
const canRemove2 = canRemoveBlock2(clientId);
const canMove2 = canMoveBlock2(clientId);
const match2 = getActiveBlockVariation(blockName, attributes2);
const isMultiSelected2 = isBlockMultiSelected2(clientId);
const checkDeep = true;
const isAncestorOfSelectedBlock = hasSelectedInnerBlock2(
clientId,
checkDeep
);
const blockEditingMode2 = getBlockEditingMode2(clientId);
const sectionBlockClientId = _isSectionBlock(clientId) ? clientId : getParentSectionBlock2(clientId);
const multiple = (0, import_blocks22.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
};
},
[clientId, rootClientId]
);
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,
blockWithoutAttributes,
name,
attributes,
isValid: isValid2,
isSelected = false,
themeSupportsLayout,
isEditingContentOnlySection,
blockEditingMode,
mayDisplayControls,
mayDisplayParentControls,
index,
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
} = selectedProps;
const { isBlockCurrentlyHidden } = useBlockVisibility({
blockVisibility: blockVisibility2,
deviceType
});
const block = (0, import_element36.useMemo)(
() => ({ ...blockWithoutAttributes, attributes }),
[blockWithoutAttributes, attributes]
);
if (!selectedProps) {
return null;
}
const privateContext = {
isPreviewMode,
clientId,
className,
index,
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
};
if (isBlockCurrentlyHidden && !isSelected && !isMultiSelected && !hasChildSelected) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime152.jsx)(PrivateBlockContext.Provider, { value: privateContext, children: /* @__PURE__ */ (0, import_jsx_runtime152.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_element36.memo)(BlockListBlockProvider);
// packages/block-editor/build-module/components/block-list-appender/index.mjs
var import_data66 = __toESM(require_data(), 1);
var import_blocks39 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/components/default-block-appender/index.mjs
var import_i18n66 = __toESM(require_i18n(), 1);
var import_html_entities2 = __toESM(require_html_entities(), 1);
var import_data65 = __toESM(require_data(), 1);
var import_keycodes7 = __toESM(require_keycodes(), 1);
// packages/block-editor/build-module/components/inserter/index.mjs
var import_a11y10 = __toESM(require_a11y(), 1);
var import_i18n65 = __toESM(require_i18n(), 1);
var import_components63 = __toESM(require_components(), 1);
var import_element81 = __toESM(require_element(), 1);
var import_data64 = __toESM(require_data(), 1);
var import_compose45 = __toESM(require_compose(), 1);
var import_blocks38 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/components/inserter/menu.mjs
var import_element79 = __toESM(require_element(), 1);
var import_components61 = __toESM(require_components(), 1);
var import_i18n63 = __toESM(require_i18n(), 1);
var import_compose44 = __toESM(require_compose(), 1);
var import_data62 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/inserter/tips.mjs
var import_i18n31 = __toESM(require_i18n(), 1);
var import_element37 = __toESM(require_element(), 1);
var import_components30 = __toESM(require_components(), 1);
var import_jsx_runtime153 = __toESM(require_jsx_runtime(), 1);
var globalTips = [
(0, import_element37.createInterpolateElement)(
(0, import_i18n31.__)(
"While writing, you can press <kbd>/</kbd> to quickly insert new blocks."
),
{ kbd: /* @__PURE__ */ (0, import_jsx_runtime153.jsx)("kbd", {}) }
),
(0, import_element37.createInterpolateElement)(
(0, import_i18n31.__)(
"Indent a list by pressing <kbd>space</kbd> at the beginning of a line."
),
{ kbd: /* @__PURE__ */ (0, import_jsx_runtime153.jsx)("kbd", {}) }
),
(0, import_element37.createInterpolateElement)(
(0, import_i18n31.__)(
"Outdent a list by pressing <kbd>backspace</kbd> at the beginning of a line."
),
{ kbd: /* @__PURE__ */ (0, import_jsx_runtime153.jsx)("kbd", {}) }
),
(0, import_i18n31.__)("Drag files into the editor to automatically insert media blocks."),
(0, import_i18n31.__)("Change a block's type by pressing the block icon on the toolbar.")
];
function Tips() {
const [randomIndex] = (0, import_element37.useState)(
Math.floor(Math.random() * globalTips.length)
);
return /* @__PURE__ */ (0, import_jsx_runtime153.jsx)(import_components30.Tip, { children: globalTips[randomIndex] });
}
var tips_default = Tips;
// packages/block-editor/build-module/components/inserter/preview-panel.mjs
var import_blocks29 = __toESM(require_blocks(), 1);
var import_element54 = __toESM(require_element(), 1);
var import_i18n41 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/block-card/index.mjs
var import_components31 = __toESM(require_components(), 1);
var import_data31 = __toESM(require_data(), 1);
var import_deprecated6 = __toESM(require_deprecated(), 1);
var import_i18n32 = __toESM(require_i18n(), 1);
var import_blocks23 = __toESM(require_blocks(), 1);
var import_jsx_runtime154 = __toESM(require_jsx_runtime(), 1);
var { Badge } = unlock(import_components31.privateApis);
function OptionalParentSelectButton({ children, onClick }) {
if (!onClick) {
return children;
}
return /* @__PURE__ */ (0, import_jsx_runtime154.jsx)(
import_components31.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
}) {
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 } = select3(store);
const parents = getBlockParents2(clientId, true);
const foundParentId = parents.find((parentId) => {
const parentName = getBlockName2(parentId);
return parentName === "core/navigation" || (0, import_blocks23.hasBlockSupport)(parentName, "listView");
});
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_runtime154.jsx)(
"div",
{
className: clsx_default(
"block-editor-block-card",
{
"is-parent": parentClientId,
"is-child": isChild
},
className
),
children: /* @__PURE__ */ (0, import_jsx_runtime154.jsxs)(import_components31.__experimentalVStack, { children: [
/* @__PURE__ */ (0, import_jsx_runtime154.jsxs)(import_components31.__experimentalHStack, { justify: "flex-start", spacing: 0, children: [
parentBlockClientId && /* @__PURE__ */ (0, import_jsx_runtime154.jsx)(
import_components31.Button,
{
onClick: () => selectBlock2(parentBlockClientId),
label: parentBlockName ? (0, import_i18n32.sprintf)(
/* translators: %s: The name of the parent block. */
(0, import_i18n32.__)('Go to "%s" block'),
(0, import_blocks23.getBlockType)(parentBlockName)?.title
) : (0, import_i18n32.__)("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_i18n32.isRTL)() ? chevron_right_default : chevron_left_default,
size: "small"
}
),
isChild && /* @__PURE__ */ (0, import_jsx_runtime154.jsx)("span", { className: "block-editor-block-card__child-indicator-icon", children: /* @__PURE__ */ (0, import_jsx_runtime154.jsx)(import_components31.Icon, { icon: (0, import_i18n32.isRTL)() ? arrow_left_default : arrow_right_default }) }),
/* @__PURE__ */ (0, import_jsx_runtime154.jsxs)(
OptionalParentSelectButton,
{
onClick: parentClientId ? () => {
selectBlock2(parentClientId);
} : void 0,
children: [
/* @__PURE__ */ (0, import_jsx_runtime154.jsx)(block_icon_default, { icon, showColors: true }),
/* @__PURE__ */ (0, import_jsx_runtime154.jsxs)(import_components31.__experimentalVStack, { spacing: 1, children: [
/* @__PURE__ */ (0, import_jsx_runtime154.jsxs)(TitleElement, { className: "block-editor-block-card__title", children: [
/* @__PURE__ */ (0, import_jsx_runtime154.jsx)("span", { className: "block-editor-block-card__name", children: !!name?.length ? name : title }),
!parentClientId && !isChild && !!name?.length && /* @__PURE__ */ (0, import_jsx_runtime154.jsx)(Badge, { children: title })
] }),
children
] })
]
}
)
] }),
!parentClientId && !isChild && description && /* @__PURE__ */ (0, import_jsx_runtime154.jsx)(import_components31.__experimentalText, { 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_compose33 = __toESM(require_compose(), 1);
var import_data53 = __toESM(require_data(), 1);
var import_element53 = __toESM(require_element(), 1);
var import_deprecated7 = __toESM(require_deprecated(), 1);
// packages/block-editor/build-module/components/provider/index.mjs
var import_data38 = __toESM(require_data(), 1);
var import_element44 = __toESM(require_element(), 1);
var import_components32 = __toESM(require_components(), 1);
// packages/upload-media/build-module/store/index.mjs
var import_data32 = __toESM(require_data(), 1);
// packages/upload-media/build-module/store/types.mjs
var Type = /* @__PURE__ */ ((Type2) => {
Type2["Unknown"] = "REDUX_UNKNOWN";
Type2["Add"] = "ADD_ITEM";
Type2["Prepare"] = "PREPARE_ITEM";
Type2["Cancel"] = "CANCEL_ITEM";
Type2["Remove"] = "REMOVE_ITEM";
Type2["RetryItem"] = "RETRY_ITEM";
Type2["PauseItem"] = "PAUSE_ITEM";
Type2["ResumeItem"] = "RESUME_ITEM";
Type2["PauseQueue"] = "PAUSE_QUEUE";
Type2["ResumeQueue"] = "RESUME_QUEUE";
Type2["OperationStart"] = "OPERATION_START";
Type2["OperationFinish"] = "OPERATION_FINISH";
Type2["AddOperations"] = "ADD_OPERATIONS";
Type2["CacheBlobUrl"] = "CACHE_BLOB_URL";
Type2["RevokeBlobUrls"] = "REVOKE_BLOB_URLS";
Type2["UpdateProgress"] = "UPDATE_PROGRESS";
Type2["UpdateSettings"] = "UPDATE_SETTINGS";
return Type2;
})(Type || {});
var ItemStatus = /* @__PURE__ */ ((ItemStatus2) => {
ItemStatus2["Queued"] = "QUEUED";
ItemStatus2["Processing"] = "PROCESSING";
ItemStatus2["Paused"] = "PAUSED";
ItemStatus2["Uploaded"] = "UPLOADED";
ItemStatus2["Error"] = "ERROR";
return ItemStatus2;
})(ItemStatus || {});
var OperationType = /* @__PURE__ */ ((OperationType2) => {
OperationType2["Prepare"] = "PREPARE";
OperationType2["Upload"] = "UPLOAD";
return OperationType2;
})(OperationType || {});
// packages/upload-media/build-module/store/constants.mjs
var STORE_NAME2 = "core/upload-media";
var DEFAULT_MAX_CONCURRENT_UPLOADS = 5;
// packages/upload-media/build-module/store/reducer.mjs
var noop4 = () => {
};
var DEFAULT_STATE = {
queue: [],
queueStatus: "active",
blobUrls: {},
settings: {
mediaUpload: noop4,
maxConcurrentUploads: DEFAULT_MAX_CONCURRENT_UPLOADS
}
};
function reducer(state = DEFAULT_STATE, action = { type: Type.Unknown }) {
switch (action.type) {
case Type.PauseQueue: {
return {
...state,
queueStatus: "paused"
};
}
case Type.ResumeQueue: {
return {
...state,
queueStatus: "active"
};
}
case Type.PauseItem:
return {
...state,
queue: state.queue.map(
(item) => item.id === action.id ? {
...item,
status: ItemStatus.Paused
} : item
)
};
case Type.ResumeItem:
return {
...state,
queue: state.queue.map(
(item) => item.id === action.id ? {
...item,
status: ItemStatus.Processing
} : item
)
};
case Type.Add:
return {
...state,
queue: [...state.queue, action.item]
};
case Type.Cancel:
return {
...state,
queue: state.queue.map(
(item) => item.id === action.id ? {
...item,
error: action.error
} : item
)
};
case Type.RetryItem:
return {
...state,
queue: state.queue.map(
(item) => item.id === action.id ? {
...item,
status: ItemStatus.Processing,
error: void 0,
retryCount: (item.retryCount ?? 0) + 1
} : item
)
};
case Type.Remove:
return {
...state,
queue: state.queue.filter((item) => item.id !== action.id)
};
case Type.OperationStart: {
return {
...state,
queue: state.queue.map(
(item) => item.id === action.id ? {
...item,
currentOperation: action.operation
} : item
)
};
}
case Type.AddOperations:
return {
...state,
queue: state.queue.map((item) => {
if (item.id !== action.id) {
return item;
}
return {
...item,
operations: [
...item.operations || [],
...action.operations
]
};
})
};
case Type.OperationFinish:
return {
...state,
queue: state.queue.map((item) => {
if (item.id !== action.id) {
return item;
}
const operations = item.operations ? item.operations.slice(1) : [];
const attachment = item.attachment || action.item.attachment ? {
...item.attachment,
...action.item.attachment
} : void 0;
return {
...item,
currentOperation: void 0,
operations,
...action.item,
attachment,
additionalData: {
...item.additionalData,
...action.item.additionalData
}
};
})
};
case Type.CacheBlobUrl: {
const blobUrls = state.blobUrls[action.id] || [];
return {
...state,
blobUrls: {
...state.blobUrls,
[action.id]: [...blobUrls, action.blobUrl]
}
};
}
case Type.RevokeBlobUrls: {
const newBlobUrls = { ...state.blobUrls };
delete newBlobUrls[action.id];
return {
...state,
blobUrls: newBlobUrls
};
}
case Type.UpdateProgress:
return {
...state,
queue: state.queue.map(
(item) => item.id === action.id ? {
...item,
progress: action.progress
} : item
)
};
case Type.UpdateSettings: {
return {
...state,
settings: {
...state.settings,
...action.settings
}
};
}
}
return state;
}
var reducer_default2 = reducer;
// packages/upload-media/build-module/store/selectors.mjs
var selectors_exports2 = {};
__export(selectors_exports2, {
getItems: () => getItems,
getSettings: () => getSettings2,
isUploading: () => isUploading,
isUploadingById: () => isUploadingById,
isUploadingByUrl: () => isUploadingByUrl
});
function getItems(state) {
return state.queue;
}
function isUploading(state) {
return state.queue.length >= 1;
}
function isUploadingByUrl(state, url) {
return state.queue.some(
(item) => item.attachment?.url === url || item.sourceUrl === url
);
}
function isUploadingById(state, attachmentId) {
return state.queue.some(
(item) => item.attachment?.id === attachmentId || item.sourceAttachmentId === attachmentId
);
}
function getSettings2(state) {
return state.settings;
}
// packages/upload-media/build-module/store/private-selectors.mjs
var private_selectors_exports2 = {};
__export(private_selectors_exports2, {
getActiveUploadCount: () => getActiveUploadCount,
getAllItems: () => getAllItems,
getBlobUrls: () => getBlobUrls,
getFailedItems: () => getFailedItems,
getItem: () => getItem,
getItemProgress: () => getItemProgress,
getPausedUploadForPost: () => getPausedUploadForPost,
getPendingUploads: () => getPendingUploads,
isBatchUploaded: () => isBatchUploaded,
isPaused: () => isPaused2,
isUploadingToPost: () => isUploadingToPost
});
function getAllItems(state) {
return state.queue;
}
function getItem(state, id) {
return state.queue.find((item) => item.id === id);
}
function isBatchUploaded(state, batchId) {
const batchItems = state.queue.filter(
(item) => batchId === item.batchId
);
return batchItems.length === 0;
}
function isUploadingToPost(state, postOrAttachmentId) {
return state.queue.some(
(item) => item.currentOperation === OperationType.Upload && item.additionalData.post === postOrAttachmentId
);
}
function getPausedUploadForPost(state, postOrAttachmentId) {
return state.queue.find(
(item) => item.status === ItemStatus.Paused && item.additionalData.post === postOrAttachmentId
);
}
function isPaused2(state) {
return state.queueStatus === "paused";
}
function getBlobUrls(state, id) {
return state.blobUrls[id] || [];
}
function getActiveUploadCount(state) {
return state.queue.filter(
(item) => item.currentOperation === OperationType.Upload
).length;
}
function getPendingUploads(state) {
return state.queue.filter((item) => {
const nextOperation = Array.isArray(item.operations?.[0]) ? item.operations[0][0] : item.operations?.[0];
return nextOperation === OperationType.Upload && item.currentOperation !== OperationType.Upload;
});
}
function getFailedItems(state) {
return state.queue.filter((item) => item.error !== void 0);
}
function getItemProgress(state, id) {
const item = state.queue.find((i2) => i2.id === id);
return item?.progress;
}
// packages/upload-media/build-module/store/actions.mjs
var actions_exports2 = {};
__export(actions_exports2, {
addItems: () => addItems,
cancelItem: () => cancelItem,
retryItem: () => retryItem
});
// node_modules/uuid/dist/esm-browser/rng.js
var getRandomValues;
var rnds8 = new Uint8Array(16);
function rng() {
if (!getRandomValues) {
getRandomValues = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
if (!getRandomValues) {
throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
}
}
return getRandomValues(rnds8);
}
// node_modules/uuid/dist/esm-browser/stringify.js
var byteToHex = [];
for (let i2 = 0; i2 < 256; ++i2) {
byteToHex.push((i2 + 256).toString(16).slice(1));
}
function unsafeStringify(arr, offset = 0) {
return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];
}
// node_modules/uuid/dist/esm-browser/native.js
var randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
var native_default = {
randomUUID
};
// node_modules/uuid/dist/esm-browser/v4.js
function v4(options, buf, offset) {
if (native_default.randomUUID && !buf && !options) {
return native_default.randomUUID();
}
options = options || {};
const rnds = options.random || (options.rng || rng)();
rnds[6] = rnds[6] & 15 | 64;
rnds[8] = rnds[8] & 63 | 128;
if (buf) {
offset = offset || 0;
for (let i2 = 0; i2 < 16; ++i2) {
buf[offset + i2] = rnds[i2];
}
return buf;
}
return unsafeStringify(rnds);
}
var v4_default = v4;
// packages/upload-media/build-module/validate-mime-type.mjs
var import_i18n33 = __toESM(require_i18n(), 1);
// packages/upload-media/build-module/upload-error.mjs
var UploadError = class extends Error {
code;
file;
constructor({ code, message: message2, file, cause }) {
super(message2, { cause });
Object.setPrototypeOf(this, new.target.prototype);
this.code = code;
this.file = file;
}
};
// packages/upload-media/build-module/validate-mime-type.mjs
function validateMimeType(file, allowedTypes) {
if (!allowedTypes) {
return;
}
const isAllowedType = allowedTypes.some((allowedType) => {
if (allowedType.includes("/")) {
return allowedType === file.type;
}
return file.type.startsWith(`${allowedType}/`);
});
if (file.type && !isAllowedType) {
throw new UploadError({
code: "MIME_TYPE_NOT_SUPPORTED",
message: (0, import_i18n33.sprintf)(
// translators: %s: file name.
(0, import_i18n33.__)("%s: Sorry, this file type is not supported here."),
file.name
),
file
});
}
}
// packages/upload-media/build-module/validate-mime-type-for-user.mjs
var import_i18n34 = __toESM(require_i18n(), 1);
// packages/upload-media/build-module/get-mime-types-array.mjs
function getMimeTypesArray(wpMimeTypesObject) {
if (!wpMimeTypesObject) {
return null;
}
return Object.entries(wpMimeTypesObject).flatMap(
([extensionsString, mime]) => {
const [type] = mime.split("/");
const extensions = extensionsString.split("|");
return [
mime,
...extensions.map(
(extension) => `${type}/${extension}`
)
];
}
);
}
// packages/upload-media/build-module/validate-mime-type-for-user.mjs
function validateMimeTypeForUser(file, wpAllowedMimeTypes) {
const allowedMimeTypesForUser = getMimeTypesArray(wpAllowedMimeTypes);
if (!allowedMimeTypesForUser) {
return;
}
const isAllowedMimeTypeForUser = allowedMimeTypesForUser.includes(
file.type
);
if (file.type && !isAllowedMimeTypeForUser) {
throw new UploadError({
code: "MIME_TYPE_NOT_ALLOWED_FOR_USER",
message: (0, import_i18n34.sprintf)(
// translators: %s: file name.
(0, import_i18n34.__)(
"%s: Sorry, you are not allowed to upload this file type."
),
file.name
),
file
});
}
}
// packages/upload-media/build-module/validate-file-size.mjs
var import_i18n35 = __toESM(require_i18n(), 1);
function validateFileSize(file, maxUploadFileSize) {
if (file.size <= 0) {
throw new UploadError({
code: "EMPTY_FILE",
message: (0, import_i18n35.sprintf)(
// translators: %s: file name.
(0, import_i18n35.__)("%s: This file is empty."),
file.name
),
file
});
}
if (maxUploadFileSize && file.size > maxUploadFileSize) {
throw new UploadError({
code: "SIZE_ABOVE_LIMIT",
message: (0, import_i18n35.sprintf)(
// translators: %s: file name.
(0, import_i18n35.__)(
"%s: This file exceeds the maximum upload size for this site."
),
file.name
),
file
});
}
}
// packages/upload-media/build-module/store/actions.mjs
function addItems({
files,
onChange,
onSuccess,
onError,
onBatchSuccess,
additionalData,
allowedTypes
}) {
return async ({ select: select3, dispatch }) => {
const batchId = v4_default();
for (const file of files) {
try {
validateMimeType(file, allowedTypes);
validateMimeTypeForUser(
file,
select3.getSettings().allowedMimeTypes
);
} catch (error) {
onError?.(error);
continue;
}
try {
validateFileSize(
file,
select3.getSettings().maxUploadFileSize
);
} catch (error) {
onError?.(error);
continue;
}
dispatch.addItem({
file,
batchId,
onChange,
onSuccess,
onBatchSuccess,
onError,
additionalData
});
}
};
}
function cancelItem(id, error, silent = false) {
return async ({ select: select3, dispatch }) => {
const item = select3.getItem(id);
if (!item) {
return;
}
item.abortController?.abort();
if (!silent) {
const { onError } = item;
onError?.(error ?? new Error("Upload cancelled"));
if (!onError && error) {
console.error("Upload cancelled", error);
}
}
dispatch({
type: Type.Cancel,
id,
error
});
dispatch.removeItem(id);
dispatch.revokeBlobUrls(id);
if (item.batchId && select3.isBatchUploaded(item.batchId)) {
item.onBatchSuccess?.();
}
};
}
function retryItem(id) {
return async ({ select: select3, dispatch }) => {
const item = select3.getItem(id);
if (!item) {
return;
}
if (!item.error) {
return;
}
dispatch({
type: Type.RetryItem,
id
});
dispatch.processItem(id);
};
}
// packages/upload-media/build-module/store/private-actions.mjs
var private_actions_exports2 = {};
__export(private_actions_exports2, {
addItem: () => addItem,
finishOperation: () => finishOperation,
pauseItem: () => pauseItem,
pauseQueue: () => pauseQueue,
prepareItem: () => prepareItem,
processItem: () => processItem,
removeItem: () => removeItem,
resumeItem: () => resumeItem,
resumeQueue: () => resumeQueue,
revokeBlobUrls: () => revokeBlobUrls,
updateItemProgress: () => updateItemProgress,
updateSettings: () => updateSettings2,
uploadItem: () => uploadItem
});
var import_blob = __toESM(require_blob(), 1);
// packages/upload-media/build-module/utils.mjs
var import_url3 = __toESM(require_url(), 1);
var import_i18n36 = __toESM(require_i18n(), 1);
function convertBlobToFile(fileOrBlob) {
if (fileOrBlob instanceof File) {
return fileOrBlob;
}
const ext = fileOrBlob.type.split("/")[1];
const mediaType = "application/pdf" === fileOrBlob.type ? "document" : fileOrBlob.type.split("/")[0];
return new File([fileOrBlob], `${mediaType}.${ext}`, {
type: fileOrBlob.type
});
}
function renameFile(file, name) {
return new File([file], name, {
type: file.type,
lastModified: file.lastModified
});
}
function cloneFile(file) {
return renameFile(file, file.name);
}
// packages/upload-media/build-module/stub-file.mjs
var StubFile = class extends File {
constructor(fileName = "stub-file") {
super([], fileName);
}
};
// packages/upload-media/build-module/store/private-actions.mjs
function addItem({
file: fileOrBlob,
batchId,
onChange,
onSuccess,
onBatchSuccess,
onError,
additionalData = {},
sourceUrl,
sourceAttachmentId,
abortController,
operations
}) {
return async ({ dispatch }) => {
const itemId = v4_default();
const file = convertBlobToFile(fileOrBlob);
let blobUrl;
if (!(file instanceof StubFile)) {
blobUrl = (0, import_blob.createBlobURL)(file);
dispatch({
type: Type.CacheBlobUrl,
id: itemId,
blobUrl
});
}
dispatch({
type: Type.Add,
item: {
id: itemId,
batchId,
status: ItemStatus.Processing,
sourceFile: cloneFile(file),
file,
attachment: {
url: blobUrl
},
additionalData: {
convert_format: false,
...additionalData
},
onChange,
onSuccess,
onBatchSuccess,
onError,
sourceUrl,
sourceAttachmentId,
abortController: abortController || new AbortController(),
operations: Array.isArray(operations) ? operations : [OperationType.Prepare]
}
});
dispatch.processItem(itemId);
};
}
function processItem(id) {
return async ({ select: select3, dispatch }) => {
if (select3.isPaused()) {
return;
}
const item = select3.getItem(id);
const { attachment, onChange, onSuccess, onBatchSuccess, batchId } = item;
const operation = Array.isArray(item.operations?.[0]) ? item.operations[0][0] : item.operations?.[0];
if (operation === OperationType.Upload) {
const settings2 = select3.getSettings();
const activeCount = select3.getActiveUploadCount();
if (activeCount >= settings2.maxConcurrentUploads) {
return;
}
}
if (attachment) {
onChange?.([attachment]);
}
if (!operation) {
if (attachment) {
onSuccess?.([attachment]);
}
dispatch.revokeBlobUrls(id);
if (batchId && select3.isBatchUploaded(batchId)) {
onBatchSuccess?.();
}
return;
}
if (!operation) {
return;
}
dispatch({
type: Type.OperationStart,
id,
operation
});
switch (operation) {
case OperationType.Prepare:
dispatch.prepareItem(item.id);
break;
case OperationType.Upload:
dispatch.uploadItem(id);
break;
}
};
}
function pauseQueue() {
return {
type: Type.PauseQueue
};
}
function resumeQueue() {
return async ({ select: select3, dispatch }) => {
dispatch({
type: Type.ResumeQueue
});
for (const item of select3.getAllItems()) {
dispatch.processItem(item.id);
}
};
}
function pauseItem(id) {
return async ({ dispatch }) => {
dispatch({
type: Type.PauseItem,
id
});
};
}
function resumeItem(id) {
return async ({ select: select3, dispatch }) => {
const item = select3.getItem(id);
if (!item || item.status !== ItemStatus.Paused) {
return;
}
dispatch({
type: Type.ResumeItem,
id
});
dispatch.processItem(id);
};
}
function removeItem(id) {
return async ({ select: select3, dispatch }) => {
const item = select3.getItem(id);
if (!item) {
return;
}
dispatch({
type: Type.Remove,
id
});
};
}
function finishOperation(id, updates) {
return async ({ select: select3, dispatch }) => {
const item = select3.getItem(id);
const previousOperation = item?.currentOperation;
dispatch({
type: Type.OperationFinish,
id,
item: updates
});
dispatch.processItem(id);
if (previousOperation === OperationType.Upload) {
const pendingUploads = select3.getPendingUploads();
for (const pendingItem of pendingUploads) {
dispatch.processItem(pendingItem.id);
}
}
};
}
function prepareItem(id) {
return async ({ dispatch }) => {
const operations = [OperationType.Upload];
dispatch({
type: Type.AddOperations,
id,
operations
});
dispatch.finishOperation(id, {});
};
}
function uploadItem(id) {
return async ({ select: select3, dispatch }) => {
const item = select3.getItem(id);
select3.getSettings().mediaUpload({
filesList: [item.file],
additionalData: item.additionalData,
signal: item.abortController?.signal,
onFileChange: ([attachment]) => {
if (!(0, import_blob.isBlobURL)(attachment.url)) {
dispatch.finishOperation(id, {
attachment
});
}
},
onSuccess: ([attachment]) => {
dispatch.finishOperation(id, {
attachment
});
},
onError: (error) => {
dispatch.cancelItem(id, error);
}
});
};
}
function revokeBlobUrls(id) {
return async ({ select: select3, dispatch }) => {
const blobUrls = select3.getBlobUrls(id);
for (const blobUrl of blobUrls) {
(0, import_blob.revokeBlobURL)(blobUrl);
}
dispatch({
type: Type.RevokeBlobUrls,
id
});
};
}
function updateItemProgress(id, progress) {
return async ({ dispatch }) => {
dispatch({
type: Type.UpdateProgress,
id,
progress
});
};
}
function updateSettings2(settings2) {
return {
type: Type.UpdateSettings,
settings: settings2
};
}
// packages/upload-media/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/upload-media"
);
// packages/upload-media/build-module/store/index.mjs
var storeConfig2 = {
reducer: reducer_default2,
selectors: selectors_exports2,
actions: actions_exports2
};
var store2 = (0, import_data32.createReduxStore)(STORE_NAME2, {
reducer: reducer_default2,
selectors: selectors_exports2,
actions: actions_exports2
});
(0, import_data32.register)(store2);
unlock2(store2).registerPrivateActions(private_actions_exports2);
unlock2(store2).registerPrivateSelectors(private_selectors_exports2);
// packages/upload-media/build-module/components/provider/index.mjs
var import_element39 = __toESM(require_element(), 1);
var import_data34 = __toESM(require_data(), 1);
// packages/upload-media/build-module/components/provider/with-registry-provider.mjs
var import_element38 = __toESM(require_element(), 1);
var import_data33 = __toESM(require_data(), 1);
var import_compose18 = __toESM(require_compose(), 1);
var import_jsx_runtime155 = __toESM(require_jsx_runtime(), 1);
function getSubRegistry(subRegistries, registry, useSubRegistry) {
if (!useSubRegistry) {
return registry;
}
let subRegistry = subRegistries.get(registry);
if (!subRegistry) {
subRegistry = (0, import_data33.createRegistry)({}, registry);
subRegistry.registerStore(STORE_NAME2, storeConfig2);
subRegistries.set(registry, subRegistry);
}
return subRegistry;
}
var withRegistryProvider = (0, import_compose18.createHigherOrderComponent)(
(WrappedComponent) => ({ useSubRegistry = true, ...props }) => {
const registry = (0, import_data33.useRegistry)();
const [subRegistries] = (0, import_element38.useState)(() => /* @__PURE__ */ new WeakMap());
const subRegistry = getSubRegistry(
subRegistries,
registry,
useSubRegistry
);
if (subRegistry === registry) {
return /* @__PURE__ */ (0, import_jsx_runtime155.jsx)(WrappedComponent, { registry, ...props });
}
return /* @__PURE__ */ (0, import_jsx_runtime155.jsx)(import_data33.RegistryProvider, { value: subRegistry, children: /* @__PURE__ */ (0, import_jsx_runtime155.jsx)(WrappedComponent, { registry: subRegistry, ...props }) });
},
"withRegistryProvider"
);
var with_registry_provider_default = withRegistryProvider;
// packages/upload-media/build-module/components/provider/index.mjs
var import_jsx_runtime156 = __toESM(require_jsx_runtime(), 1);
var MediaUploadProvider = with_registry_provider_default((props) => {
const { children, settings: settings2 } = props;
const { updateSettings: updateSettings3 } = unlock2((0, import_data34.useDispatch)(store2));
(0, import_element39.useEffect)(() => {
updateSettings3(settings2);
}, [settings2, updateSettings3]);
return /* @__PURE__ */ (0, import_jsx_runtime156.jsx)(import_jsx_runtime156.Fragment, { children });
});
var provider_default = MediaUploadProvider;
// packages/block-editor/build-module/components/provider/with-registry-provider.mjs
var import_element40 = __toESM(require_element(), 1);
var import_data35 = __toESM(require_data(), 1);
var import_compose19 = __toESM(require_compose(), 1);
var import_jsx_runtime157 = __toESM(require_jsx_runtime(), 1);
function getSubRegistry2(subRegistries, registry, useSubRegistry) {
if (!useSubRegistry) {
return registry;
}
let subRegistry = subRegistries.get(registry);
if (!subRegistry) {
subRegistry = (0, import_data35.createRegistry)({}, registry);
subRegistry.registerStore(STORE_NAME, storeConfig);
subRegistries.set(registry, subRegistry);
}
return subRegistry;
}
var withRegistryProvider2 = (0, import_compose19.createHigherOrderComponent)(
(WrappedComponent) => ({ useSubRegistry = true, ...props }) => {
const registry = (0, import_data35.useRegistry)();
const [subRegistries] = (0, import_element40.useState)(() => /* @__PURE__ */ new WeakMap());
const subRegistry = getSubRegistry2(
subRegistries,
registry,
useSubRegistry
);
if (subRegistry === registry) {
return /* @__PURE__ */ (0, import_jsx_runtime157.jsx)(WrappedComponent, { registry, ...props });
}
return /* @__PURE__ */ (0, import_jsx_runtime157.jsx)(import_data35.RegistryProvider, { value: subRegistry, children: /* @__PURE__ */ (0, import_jsx_runtime157.jsx)(WrappedComponent, { registry: subRegistry, ...props }) });
},
"withRegistryProvider"
);
var with_registry_provider_default2 = withRegistryProvider2;
// packages/block-editor/build-module/components/provider/use-block-sync.mjs
var import_element41 = __toESM(require_element(), 1);
var import_data36 = __toESM(require_data(), 1);
var import_blocks24 = __toESM(require_blocks(), 1);
var noop5 = () => {
};
function useBlockSync({
clientId = null,
value: controlledBlocks,
selection: controlledSelection,
onChange = noop5,
onInput = noop5
}) {
const registry = (0, import_data36.useRegistry)();
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 isControlled = (0, import_data36.useSelect)(
(select3) => {
return !clientId || select3(store).areInnerBlocksControlled(clientId);
},
[clientId]
);
const pendingChangesRef = (0, import_element41.useRef)({ incoming: null, outgoing: [] });
const subscribedRef = (0, import_element41.useRef)(false);
const setControlledBlocks = () => {
if (!controlledBlocks) {
return;
}
__unstableMarkNextChangeAsNotPersistent2();
if (clientId) {
registry.batch(() => {
setHasControlledInnerBlocks2(clientId, true);
const storeBlocks = controlledBlocks.map(
(block) => (0, import_blocks24.cloneBlock)(block)
);
if (subscribedRef.current) {
pendingChangesRef.current.incoming = storeBlocks;
}
__unstableMarkNextChangeAsNotPersistent2();
replaceInnerBlocks2(clientId, storeBlocks);
});
} else {
if (subscribedRef.current) {
pendingChangesRef.current.incoming = controlledBlocks;
}
resetBlocks2(controlledBlocks);
}
};
const unsetControlledBlocks = () => {
__unstableMarkNextChangeAsNotPersistent2();
if (clientId) {
setHasControlledInnerBlocks2(clientId, false);
__unstableMarkNextChangeAsNotPersistent2();
replaceInnerBlocks2(clientId, []);
} else {
resetBlocks2([]);
}
};
const onInputRef = (0, import_element41.useRef)(onInput);
const onChangeRef = (0, import_element41.useRef)(onChange);
(0, import_element41.useEffect)(() => {
onInputRef.current = onInput;
onChangeRef.current = onChange;
}, [onInput, onChange]);
(0, import_element41.useEffect)(() => {
if (pendingChangesRef.current.outgoing.includes(controlledBlocks)) {
if (pendingChangesRef.current.outgoing[pendingChangesRef.current.outgoing.length - 1] === controlledBlocks) {
pendingChangesRef.current.outgoing = [];
}
} else if (getBlocks2(clientId) !== controlledBlocks) {
pendingChangesRef.current.outgoing = [];
setControlledBlocks();
if (controlledSelection) {
resetSelection2(
controlledSelection.selectionStart,
controlledSelection.selectionEnd,
controlledSelection.initialPosition
);
}
}
}, [controlledBlocks, clientId]);
const isMountedRef = (0, import_element41.useRef)(false);
(0, import_element41.useEffect)(() => {
if (!isMountedRef.current) {
isMountedRef.current = true;
return;
}
if (!isControlled) {
pendingChangesRef.current.outgoing = [];
setControlledBlocks();
}
}, [isControlled]);
(0, import_element41.useEffect)(() => {
const {
getSelectedBlocksInitialCaretPosition: getSelectedBlocksInitialCaretPosition2,
isLastBlockChangePersistent: isLastBlockChangePersistent2,
__unstableIsLastBlockChangeIgnored: __unstableIsLastBlockChangeIgnored2,
areInnerBlocksControlled: areInnerBlocksControlled2
} = registry.select(store);
let blocks2 = getBlocks2(clientId);
let isPersistent = isLastBlockChangePersistent2();
let previousAreBlocksDifferent = false;
subscribedRef.current = true;
const unsubscribe = registry.subscribe(() => {
if (clientId !== null && getBlockName2(clientId) === null) {
return;
}
const isStillControlled = !clientId || areInnerBlocksControlled2(clientId);
if (!isStillControlled) {
return;
}
const newIsPersistent = isLastBlockChangePersistent2();
const newBlocks = getBlocks2(clientId);
const areBlocksDifferent = newBlocks !== blocks2;
blocks2 = newBlocks;
if (areBlocksDifferent && (pendingChangesRef.current.incoming || __unstableIsLastBlockChangeIgnored2())) {
pendingChangesRef.current.incoming = null;
isPersistent = newIsPersistent;
return;
}
const didPersistenceChange = previousAreBlocksDifferent && !areBlocksDifferent && newIsPersistent && !isPersistent;
if (areBlocksDifferent || didPersistenceChange) {
isPersistent = newIsPersistent;
pendingChangesRef.current.outgoing.push(blocks2);
const updateParent = isPersistent ? onChangeRef.current : onInputRef.current;
updateParent(blocks2, {
selection: {
selectionStart: getSelectionStart2(),
selectionEnd: getSelectionEnd2(),
initialPosition: getSelectedBlocksInitialCaretPosition2()
}
});
}
previousAreBlocksDifferent = areBlocksDifferent;
}, store);
return () => {
subscribedRef.current = false;
unsubscribe();
};
}, [registry, clientId]);
(0, import_element41.useEffect)(() => {
return () => {
unsetControlledBlocks();
};
}, []);
}
// packages/block-editor/build-module/components/keyboard-shortcuts/index.mjs
var import_element42 = __toESM(require_element(), 1);
var import_data37 = __toESM(require_data(), 1);
var import_keyboard_shortcuts3 = __toESM(require_keyboard_shortcuts(), 1);
var import_i18n37 = __toESM(require_i18n(), 1);
function KeyboardShortcuts() {
return null;
}
function KeyboardShortcutsRegister() {
const { registerShortcut } = (0, import_data37.useDispatch)(import_keyboard_shortcuts3.store);
(0, import_element42.useEffect)(() => {
registerShortcut({
name: "core/block-editor/copy",
category: "block",
description: (0, import_i18n37.__)("Copy the selected block(s)."),
keyCombination: {
modifier: "primary",
character: "c"
}
});
registerShortcut({
name: "core/block-editor/cut",
category: "block",
description: (0, import_i18n37.__)("Cut the selected block(s)."),
keyCombination: {
modifier: "primary",
character: "x"
}
});
registerShortcut({
name: "core/block-editor/paste",
category: "block",
description: (0, import_i18n37.__)("Paste the selected block(s)."),
keyCombination: {
modifier: "primary",
character: "v"
}
});
registerShortcut({
name: "core/block-editor/duplicate",
category: "block",
description: (0, import_i18n37.__)("Duplicate the selected block(s)."),
keyCombination: {
modifier: "primaryShift",
character: "d"
}
});
registerShortcut({
name: "core/block-editor/remove",
category: "block",
description: (0, import_i18n37.__)("Remove the selected block(s)."),
keyCombination: {
modifier: "access",
character: "z"
}
});
registerShortcut({
name: "core/block-editor/paste-styles",
category: "block",
description: (0, import_i18n37.__)(
"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_i18n37.__)(
"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_i18n37.__)(
"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_i18n37.__)("Delete selection."),
keyCombination: {
character: "del"
},
aliases: [
{
character: "backspace"
}
]
});
registerShortcut({
name: "core/block-editor/stop-editing-as-blocks",
category: "block",
description: (0, import_i18n37.__)("Finish editing a design."),
keyCombination: {
character: "escape"
}
});
registerShortcut({
name: "core/block-editor/select-all",
category: "selection",
description: (0, import_i18n37.__)(
"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_i18n37.__)("Clear selection."),
keyCombination: {
character: "escape"
}
});
registerShortcut({
name: "core/block-editor/multi-text-selection",
category: "selection",
description: (0, import_i18n37.__)("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_i18n37.__)("Navigate to the nearest toolbar."),
keyCombination: {
modifier: "alt",
character: "F10"
}
});
registerShortcut({
name: "core/block-editor/move-up",
category: "block",
description: (0, import_i18n37.__)("Move the selected block(s) up."),
keyCombination: {
modifier: "secondary",
character: "t"
}
});
registerShortcut({
name: "core/block-editor/move-down",
category: "block",
description: (0, import_i18n37.__)("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_i18n37.__)("Collapse all other items."),
keyCombination: {
modifier: "alt",
character: "l"
}
});
registerShortcut({
name: "core/block-editor/group",
category: "block",
description: (0, import_i18n37.__)(
"Create a group block from the selected multiple blocks."
),
keyCombination: {
modifier: "primary",
character: "g"
}
});
registerShortcut({
name: "core/block-editor/toggle-block-visibility",
category: "block",
description: (0, import_i18n37.__)("Show or hide the selected block(s)."),
keyCombination: {
modifier: "primaryShift",
character: "h"
}
});
}, [registerShortcut]);
return null;
}
KeyboardShortcuts.Register = KeyboardShortcutsRegister;
var keyboard_shortcuts_default = KeyboardShortcuts;
// packages/block-editor/build-module/components/provider/use-media-upload-settings.mjs
var import_element43 = __toESM(require_element(), 1);
function useMediaUploadSettings(settings2 = {}) {
return (0, import_element43.useMemo)(
() => ({
mediaUpload: settings2.mediaUpload,
mediaSideload: settings2.mediaSideload,
maxUploadFileSize: settings2.maxUploadFileSize,
allowedMimeTypes: settings2.allowedMimeTypes
}),
[settings2]
);
}
var use_media_upload_settings_default = useMediaUploadSettings;
// packages/block-editor/build-module/components/provider/index.mjs
var import_jsx_runtime158 = __toESM(require_jsx_runtime(), 1);
var noop6 = () => {
};
function mediaUpload(registry, {
allowedTypes,
additionalData = {},
filesList,
onError = noop6,
onFileChange,
onSuccess,
onBatchSuccess
}) {
void registry.dispatch(store2).addItems({
files: filesList,
onChange: onFileChange,
onSuccess,
onBatchSuccess,
onError: ({ message: message2 }) => onError(message2),
additionalData,
allowedTypes
});
}
var ExperimentalBlockEditorProvider = with_registry_provider_default2(
(props) => {
const {
settings: _settings,
registry,
stripExperimentalSettings = false
} = props;
const mediaUploadSettings = use_media_upload_settings_default(_settings);
let settings2 = _settings;
if (window.__experimentalMediaProcessing && _settings.mediaUpload) {
settings2 = (0, import_element44.useMemo)(
() => ({
..._settings,
mediaUpload: mediaUpload.bind(null, registry)
}),
[_settings, registry]
);
}
const { __experimentalUpdateSettings: __experimentalUpdateSettings2 } = unlock(
(0, import_data38.useDispatch)(store)
);
(0, import_element44.useEffect)(() => {
__experimentalUpdateSettings2(
{
...settings2,
__internalIsInitialized: true
},
{
stripExperimentalSettings,
reset: true
}
);
}, [
settings2,
stripExperimentalSettings,
__experimentalUpdateSettings2
]);
useBlockSync(props);
const children = /* @__PURE__ */ (0, import_jsx_runtime158.jsxs)(import_components32.SlotFillProvider, { passthrough: true, children: [
!settings2?.isPreviewMode && /* @__PURE__ */ (0, import_jsx_runtime158.jsx)(keyboard_shortcuts_default.Register, {}),
/* @__PURE__ */ (0, import_jsx_runtime158.jsx)(BlockRefsProvider, { children: props.children })
] });
if (window.__experimentalMediaProcessing) {
return /* @__PURE__ */ (0, import_jsx_runtime158.jsx)(
provider_default,
{
settings: mediaUploadSettings,
useSubRegistry: false,
children
}
);
}
return children;
}
);
var BlockEditorProvider = (props) => {
return /* @__PURE__ */ (0, import_jsx_runtime158.jsx)(ExperimentalBlockEditorProvider, { ...props, stripExperimentalSettings: true, children: props.children });
};
var provider_default2 = BlockEditorProvider;
// packages/block-editor/build-module/components/block-preview/auto.mjs
var import_compose32 = __toESM(require_compose(), 1);
var import_data52 = __toESM(require_data(), 1);
var import_element51 = __toESM(require_element(), 1);
var import_components35 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/iframe/index.mjs
var import_element49 = __toESM(require_element(), 1);
var import_i18n40 = __toESM(require_i18n(), 1);
var import_compose31 = __toESM(require_compose(), 1);
var import_components33 = __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_i18n39 = __toESM(require_i18n(), 1);
var import_compose29 = __toESM(require_compose(), 1);
var import_element47 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/writing-flow/use-multi-selection.mjs
var import_compose20 = __toESM(require_compose(), 1);
var import_data39 = __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_data39.useSelect)(selector, []);
return (0, import_compose20.useRefEffect)(
(node) => {
const { ownerDocument } = node;
const { defaultView } = ownerDocument;
if (initialPosition2 === void 0 || initialPosition2 === null) {
return;
}
if (!hasMultiSelection2 || isMultiSelecting3) {
return;
}
const { length } = multiSelectedBlockClientIds;
if (length < 2) {
return;
}
if (!isFullSelection) {
return;
}
node.contentEditable = true;
node.focus();
defaultView.getSelection().removeAllRanges();
},
[
hasMultiSelection2,
isMultiSelecting3,
multiSelectedBlockClientIds,
selectedBlockClientId,
initialPosition2,
isFullSelection
]
);
}
// packages/block-editor/build-module/components/writing-flow/use-tab-nav.mjs
var import_dom8 = __toESM(require_dom(), 1);
var import_keycodes3 = __toESM(require_keycodes(), 1);
var import_data40 = __toESM(require_data(), 1);
var import_compose21 = __toESM(require_compose(), 1);
var import_element45 = __toESM(require_element(), 1);
var import_jsx_runtime159 = __toESM(require_jsx_runtime(), 1);
function useTabNav() {
const containerRef = (
/** @type {typeof useRef<HTMLElement>} */
(0, import_element45.useRef)()
);
const focusCaptureBeforeRef = (0, import_element45.useRef)();
const focusCaptureAfterRef = (0, import_element45.useRef)();
const {
hasMultiSelection: hasMultiSelection2,
getSelectedBlockClientId: getSelectedBlockClientId2,
getBlockCount: getBlockCount2,
getBlockOrder: getBlockOrder2,
getLastFocus: getLastFocus2,
getSectionRootClientId: getSectionRootClientId2,
isZoomOut: isZoomOut2
} = unlock((0, import_data40.useSelect)(store));
const { setLastFocus: setLastFocus2 } = unlock((0, import_data40.useDispatch)(store));
const noCaptureRef = (0, import_element45.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_dom8.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_runtime159.jsx)(
"div",
{
ref: focusCaptureBeforeRef,
tabIndex: "0",
onFocus: onFocusCapture
}
);
const after = /* @__PURE__ */ (0, import_jsx_runtime159.jsx)(
"div",
{
ref: focusCaptureAfterRef,
tabIndex: "0",
onFocus: onFocusCapture
}
);
const ref = (0, import_compose21.useRefEffect)((node) => {
function onKeyDown(event) {
if (event.defaultPrevented) {
return;
}
if (event.keyCode !== import_keycodes3.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_dom8.focus.tabbable[direction](target);
const currentBlock = target.closest("[data-block]");
const isElementPartOfSelectedBlock = currentBlock && nextTabbable && (isInSameBlock(currentBlock, nextTabbable) || isInsideRootBlock(currentBlock, nextTabbable));
if ((0, import_dom8.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: ownerDocument2 } = node;
if (!event.relatedTarget && event.target.hasAttribute("data-block") && ownerDocument2.activeElement === ownerDocument2.body && getBlockCount2() === 0) {
node.focus();
}
}
function preventScrollOnTab(event) {
if (event.keyCode !== import_keycodes3.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_dom8.focus.tabbable[direction](event.target);
if (target === focusCaptureBeforeRef.current || target === focusCaptureAfterRef.current) {
event.preventDefault();
target.focus({ preventScroll: true });
}
}
const { ownerDocument } = node;
const { defaultView } = ownerDocument;
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_compose21.useMergeRefs)([containerRef, ref]);
return [before, mergedRefs, after];
}
// packages/block-editor/build-module/components/writing-flow/use-arrow-nav.mjs
var import_dom10 = __toESM(require_dom(), 1);
var import_keycodes4 = __toESM(require_keycodes(), 1);
var import_data41 = __toESM(require_data(), 1);
var import_compose22 = __toESM(require_compose(), 1);
function isNavigationCandidate(element, keyCode, hasModifier) {
const isVertical = keyCode === import_keycodes4.UP || keyCode === import_keycodes4.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_dom10.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.closest("[inert]")) {
return;
}
if (node.children.length === 1 && isInSameBlock(node, node.firstElementChild) && node.firstElementChild.getAttribute("contenteditable") === "true") {
return;
}
if (!import_dom10.focus.tabbable.isTabbableIndex(node)) {
return false;
}
if (node.isContentEditable && node.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: getSettings8,
hasMultiSelection: hasMultiSelection2,
__unstableIsFullySelected: __unstableIsFullySelected2
} = (0, import_data41.useSelect)(store);
const { selectBlock: selectBlock2 } = (0, import_data41.useDispatch)(store);
return (0, import_compose22.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, target, shiftKey, ctrlKey, altKey, metaKey } = event;
const isUp = keyCode === import_keycodes4.UP;
const isDown = keyCode === import_keycodes4.DOWN;
const isLeft = keyCode === import_keycodes4.LEFT;
const isRight = keyCode === import_keycodes4.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_dom10.isVerticalEdge : import_dom10.isHorizontalEdge;
const { ownerDocument } = node;
const { defaultView } = ownerDocument;
if (!isNav) {
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_dom10.computeCaretRect)(defaultView);
}
const isReverseDir = (0, import_dom10.isRTL)(target) ? !isReverse : isReverse;
const { keepCaretInsideBlock } = getSettings8();
if (shiftKey) {
if (isClosestTabbableABlock(target, isReverse) && isNavEdge(target, isReverse)) {
node.contentEditable = true;
node.focus();
}
} else if (isVertical && (0, import_dom10.isVerticalEdge)(target, isReverse) && // When Alt is pressed, only intercept if the caret is also at
// the horizontal edge.
(altKey ? (0, import_dom10.isHorizontalEdge)(target, isReverseDir) : true) && !keepCaretInsideBlock) {
const closestTabbable = getClosestTabbable(
target,
isReverse,
node,
true
);
if (closestTabbable) {
(0, import_dom10.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_dom10.isHorizontalEdge)(target, isReverseDir) && !keepCaretInsideBlock) {
const closestTabbable = getClosestTabbable(
target,
isReverseDir,
node
);
(0, import_dom10.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-select-all.mjs
var import_dom12 = __toESM(require_dom(), 1);
var import_data42 = __toESM(require_data(), 1);
var import_keyboard_shortcuts5 = __toESM(require_keyboard_shortcuts(), 1);
var import_compose23 = __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_compose23.useRefEffect)((node) => {
function onKeyDown(event) {
if (!isMatch("core/block-editor/select-all", event)) {
return;
}
const selectedClientIds = getSelectedBlockClientIds2();
if (selectedClientIds.length < 2 && !(0, import_dom12.isEntirelySelected)(event.target)) {
return;
}
event.preventDefault();
const [firstSelectedClientId] = selectedClientIds;
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_compose24 = __toESM(require_compose(), 1);
function setContentEditableWrapper(node, value) {
node.contentEditable = value;
if (value) {
node.focus();
}
}
function useDragSelection() {
const { startMultiSelect: startMultiSelect2, stopMultiSelect: stopMultiSelect2 } = (0, import_data43.useDispatch)(store);
const {
isSelectionEnabled: isSelectionEnabled3,
hasSelectedBlock: hasSelectedBlock2,
isDraggingBlocks: isDraggingBlocks2,
isMultiSelecting: isMultiSelecting3
} = (0, import_data43.useSelect)(store);
return (0, import_compose24.useRefEffect)(
(node) => {
const { ownerDocument } = node;
const { defaultView } = ownerDocument;
let anchorElement;
let rafId;
function onMouseUp() {
stopMultiSelect2();
defaultView.removeEventListener("mouseup", onMouseUp);
rafId = 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") {
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(rafId);
};
},
[
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_compose25 = __toESM(require_compose(), 1);
var import_rich_text4 = __toESM(require_rich_text(), 1);
var import_dom13 = __toESM(require_dom(), 1);
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) {
const { focusNode, focusOffset } = selection2;
if (focusNode.nodeType === focusNode.TEXT_NODE) {
return focusNode;
}
if (focusOffset === focusNode.childNodes.length) {
return focusNode;
}
if (focusOffset === 0 && (0, import_dom13.isSelectionForward)(selection2)) {
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 setContentEditableWrapper2(node, value) {
if (node.contentEditable !== String(value)) {
node.contentEditable = value;
if (value) {
node.focus();
}
}
}
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 { getBlockParents: getBlockParents2, getBlockSelectionStart: getBlockSelectionStart2, isMultiSelecting: isMultiSelecting3 } = (0, import_data44.useSelect)(store);
return (0, import_compose25.useRefEffect)(
(node) => {
const { ownerDocument } = node;
const { defaultView } = ownerDocument;
function onSelectionChange(event) {
const selection2 = defaultView.getSelection();
if (!selection2.rangeCount) {
return;
}
const startNode = extractSelectionStartNode(selection2);
const endNode = extractSelectionEndNode(selection2);
if (!node.contains(startNode) || !node.contains(endNode)) {
return;
}
const isClickShift = event.shiftKey && event.type === "mouseup";
if (selection2.isCollapsed && !isClickShift) {
if (node.contentEditable === "true" && !isMultiSelecting3()) {
setContentEditableWrapper2(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) {
setContentEditableWrapper2(node, false);
return;
}
const isSingularSelection = startClientId === endClientId;
if (isSingularSelection) {
if (!isMultiSelecting3()) {
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);
}
}
}
ownerDocument.addEventListener(
"selectionchange",
onSelectionChange
);
defaultView.addEventListener("mouseup", onSelectionChange);
return () => {
ownerDocument.removeEventListener(
"selectionchange",
onSelectionChange
);
defaultView.removeEventListener("mouseup", onSelectionChange);
};
},
[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_compose26 = __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_compose26.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) {
node.contentEditable = true;
node.focus();
}
} 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_compose27 = __toESM(require_compose(), 1);
var import_keycodes5 = __toESM(require_keycodes(), 1);
var import_blocks25 = __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_compose27.useRefEffect)((node) => {
function onBeforeInput(event) {
if (node.contentEditable === "true") {
event.preventDefault();
}
}
function onKeyDown(event) {
if (event.defaultPrevented) {
return;
}
if (!hasMultiSelection2()) {
if (event.keyCode === import_keycodes5.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_blocks25.getBlockTransforms)("from").filter(
({ type }) => type === "enter"
);
const transformation = (0, import_blocks25.findTransform)(
transforms,
(item) => {
return item.regExp.test(
selectedAttributeValue
);
}
);
if (transformation) {
replaceBlocks2(
clientId,
transformation.transform({
content: selectedAttributeValue
})
);
__unstableMarkAutomaticChange2();
return;
}
}
if (!(0, import_blocks25.hasBlockSupport)(blockName, "splitting", false) && !event.__deprecatedOnSplit) {
return;
}
if (canInsertBlockType2(
blockName,
getBlockRootClientId2(clientId)
)) {
__unstableSplitSelection2();
event.preventDefault();
}
}
return;
}
if (event.keyCode === import_keycodes5.ENTER) {
node.contentEditable = false;
event.preventDefault();
if (__unstableIsFullySelected2()) {
replaceBlocks2(
getSelectedBlockClientIds2(),
(0, import_blocks25.createBlock)((0, import_blocks25.getDefaultBlockName)())
);
} else {
__unstableSplitSelection2();
}
} else if (event.keyCode === import_keycodes5.BACKSPACE || event.keyCode === import_keycodes5.DELETE) {
node.contentEditable = false;
event.preventDefault();
if (__unstableIsFullySelected2()) {
removeBlocks2(getSelectedBlockClientIds2());
} else if (__unstableIsSelectionMergeable2()) {
__unstableDeleteSelection2(event.keyCode === import_keycodes5.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)
) {
node.contentEditable = false;
if (__unstableIsSelectionMergeable2()) {
__unstableDeleteSelection2(event.keyCode === import_keycodes5.DELETE);
} else {
event.preventDefault();
node.ownerDocument.defaultView.getSelection().removeAllRanges();
}
}
}
function onCompositionStart(event) {
if (!hasMultiSelection2()) {
return;
}
node.contentEditable = 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_blocks28 = __toESM(require_blocks(), 1);
var import_dom18 = __toESM(require_dom(), 1);
var import_data48 = __toESM(require_data(), 1);
var import_compose28 = __toESM(require_compose(), 1);
// packages/block-editor/build-module/utils/use-notify-copy.mjs
var import_element46 = __toESM(require_element(), 1);
var import_blocks26 = __toESM(require_blocks(), 1);
var import_data47 = __toESM(require_data(), 1);
var import_i18n38 = __toESM(require_i18n(), 1);
var import_notices5 = __toESM(require_notices(), 1);
function useNotifyCopy() {
const { getBlockName: getBlockName2 } = (0, import_data47.useSelect)(store);
const { getBlockType: getBlockType24 } = (0, import_data47.useSelect)(import_blocks26.store);
const { createSuccessNotice } = (0, import_data47.useDispatch)(import_notices5.store);
return (0, import_element46.useCallback)(
(eventType, selectedBlockClientIds) => {
let notice = "";
if (eventType === "copyStyles") {
notice = (0, import_i18n38.__)("Styles copied to clipboard.");
} else if (selectedBlockClientIds.length === 1) {
const clientId = selectedBlockClientIds[0];
const title = getBlockType24(getBlockName2(clientId))?.title;
if (eventType === "copy") {
notice = (0, import_i18n38.sprintf)(
// Translators: %s: Name of the block being copied, e.g. "Paragraph".
(0, import_i18n38.__)('Copied "%s" to clipboard.'),
title
);
} else {
notice = (0, import_i18n38.sprintf)(
// Translators: %s: Name of the block being cut, e.g. "Paragraph".
(0, import_i18n38.__)('Moved "%s" to clipboard.'),
title
);
}
} else if (eventType === "copy") {
notice = (0, import_i18n38.sprintf)(
// Translators: %d: Number of blocks being copied.
(0, import_i18n38._n)(
"Copied %d block to clipboard.",
"Copied %d blocks to clipboard.",
selectedBlockClientIds.length
),
selectedBlockClientIds.length
);
} else {
notice = (0, import_i18n38.sprintf)(
// Translators: %d: Number of blocks being moved.
(0, import_i18n38._n)(
"Moved %d block to clipboard.",
"Moved %d blocks to clipboard.",
selectedBlockClientIds.length
),
selectedBlockClientIds.length
);
}
createSuccessNotice(notice, {
type: "snackbar"
});
},
[createSuccessNotice, getBlockName2, getBlockType24]
);
}
// packages/block-editor/build-module/components/writing-flow/utils.mjs
var import_dom17 = __toESM(require_dom(), 1);
var import_blocks27 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/utils/pasting.mjs
var import_dom16 = __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 (error) {
return;
}
html = removeWindowsFragments(html);
html = removeCharsetMetaTag(html);
const files = (0, import_dom16.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_blocks27.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_blocks27.createBlock)(
wrapperBlockName,
getBlockAttributes3(wrapperBlockClientId),
_blocks
);
}
}
}
const serialized = (0, import_blocks27.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_blocks27.getBlockTransforms)("from");
blocks2 = files.reduce((accumulator, file) => {
const transformation = (0, import_blocks27.findTransform)(
fromTransforms,
(transform) => transform.type === "files" && transform.isMatch([file])
);
if (transformation) {
accumulator.push(transformation.transform([file]));
}
return accumulator;
}, []).flat();
} else {
blocks2 = (0, import_blocks27.pasteHandler)({
HTML: html,
plainText,
mode: "BLOCKS",
canUserUseUnfilteredHTML
});
}
return blocks2;
}
function toPlainText(html) {
html = html.replace(/<br>/g, "\n");
const plainText = (0, import_dom17.__unstableStripHTML)(html).trim();
return plainText.replace(/\n\n+/g, "\n\n");
}
// 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: getSettings8,
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_compose28.useRefEffect)((node) => {
function handler(event) {
if (event.defaultPrevented) {
return;
}
const selectedBlockClientIds = getSelectedBlockClientIds2();
if (selectedBlockClientIds.length === 0) {
return;
}
if (!hasMultiSelection2()) {
const { target } = event;
const { ownerDocument } = target;
const hasSelection = event.type === "copy" || event.type === "cut" ? (0, import_dom18.documentHasUncollapsedSelection)(ownerDocument) : (0, import_dom18.documentHasSelection)(ownerDocument) && !ownerDocument.activeElement.isContentEditable;
if (hasSelection) {
return;
}
}
const { activeElement } = event.target.ownerDocument;
if (!node.contains(activeElement)) {
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 {
event.target.ownerDocument.activeElement.contentEditable = false;
__unstableDeleteSelection2();
}
} else if (event.type === "paste") {
const {
__experimentalCanUserUseUnfilteredHTML: canUserUseUnfilteredHTML,
mediaUpload: mediaUpload2
} = getSettings8();
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_blocks28.getBlockTransforms)("from");
blocks2 = files.reduce((accumulator, file) => {
const transformation = (0, import_blocks28.findTransform)(
fromTransforms,
(transform) => transform.type === "files" && transform.isMatch([file])
);
if (transformation) {
accumulator.push(
transformation.transform([file])
);
}
return accumulator;
}, []).flat();
} else {
blocks2 = (0, import_blocks28.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_blocks28.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_blocks28.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_runtime160 = __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_compose29.useMergeRefs)([
ref,
useClipboardHandler(),
useInput(),
useDragSelection(),
useSelectionObserver(),
useClickSelection(),
useMultiSelection(),
useSelectAll(),
useArrowNav(),
(0, import_compose29.useRefEffect)(
(node) => {
node.tabIndex = 0;
node.dataset.hasMultiSelection = hasMultiSelection2;
if (!hasMultiSelection2) {
return () => {
delete node.dataset.hasMultiSelection;
};
}
node.setAttribute(
"aria-label",
(0, import_i18n39.__)("Multiple selected blocks")
);
return () => {
delete node.dataset.hasMultiSelection;
node.removeAttribute("aria-label");
};
},
[hasMultiSelection2]
)
]),
after
];
}
function WritingFlow({ children, ...props }, forwardedRef) {
const [before, ref, after] = useWritingFlow();
return /* @__PURE__ */ (0, import_jsx_runtime160.jsxs)(import_jsx_runtime160.Fragment, { children: [
before,
/* @__PURE__ */ (0, import_jsx_runtime160.jsx)(
"div",
{
...props,
ref: (0, import_compose29.useMergeRefs)([ref, forwardedRef]),
className: clsx_default(
props.className,
"block-editor-writing-flow"
),
children
}
),
after
] });
}
var writing_flow_default = (0, import_element47.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 (e2) {
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_element48 = __toESM(require_element(), 1);
var import_compose30 = __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_compose30.useResizeObserver)();
const [
containerResizeListener,
{ width: containerWidth, height: containerHeight }
] = (0, import_compose30.useResizeObserver)();
const initialContainerWidthRef = (0, import_element48.useRef)(0);
const isZoomedOut = scale !== 1;
const prefersReducedMotion = (0, import_compose30.useReducedMotion)();
const isAutoScaled = scale === "auto-scaled";
const startAnimationRef = (0, import_element48.useRef)(false);
const animationRef = (0, import_element48.useRef)(null);
(0, import_element48.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_element48.useRef)({
scaleValue,
frameSize,
containerHeight: 0,
scrollTop: 0,
scrollHeight: 0
});
const transitionToRef = (0, import_element48.useRef)({
scaleValue,
frameSize,
containerHeight: 0,
scrollTop: 0,
scrollHeight: 0
});
const startZoomOutAnimation = (0, import_element48.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_element48.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_element48.useRef)(false);
(0, import_element48.useEffect)(() => {
const trigger = iframeDocument && 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_element48.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_runtime161 = __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_compose31.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]);
}
};
});
}
function Iframe({
contentRef,
children,
tabIndex = 0,
scale = 1,
frameSize = 0,
readonly,
forwardedRef: ref,
title = (0, import_i18n40.__)("Editor canvas"),
...props
}) {
const { resolvedAssets, isPreviewMode } = (0, import_data50.useSelect)((select3) => {
const { getSettings: getSettings8 } = select3(store);
const settings2 = getSettings8();
return {
resolvedAssets: settings2.__unstableResolvedAssets,
isPreviewMode: settings2.isPreviewMode
};
}, []);
const { styles = "", scripts = "" } = resolvedAssets;
const [iframeDocument, setIframeDocument] = (0, import_element49.useState)();
const [bodyClasses, setBodyClasses] = (0, import_element49.useState)([]);
const [before, writingFlowRef, after] = useWritingFlow();
const setRef = (0, import_compose31.useRefEffect)((node) => {
node._load = () => {
setIframeDocument(node.contentDocument);
};
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 } = node;
setBodyClasses(
Array.from(ownerDocument.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;
documentElement.classList.add("block-editor-iframe__html");
contentDocument.dir = ownerDocument.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 () => {
delete node._load;
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_compose31.useDisabled)({ isDisabled: !readonly });
const bodyRef = (0, import_compose31.useMergeRefs)([
useBubbleEvents(iframeDocument),
contentRef,
writingFlowRef,
disabledRef
]);
const html = `<!doctype html>
<html>
<head>
<meta charset="utf-8">
<base href="${window.location.origin}">
<script>window.frameElement._load()<\/script>
<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>
${styles}
${scripts}
</head>
<body>
<script>document.currentScript.parentElement.remove()<\/script>
</body>
</html>`;
const [src, cleanup] = (0, import_element49.useMemo)(() => {
const _src = URL.createObjectURL(
new window.Blob([html], { type: "text/html" })
);
return [_src, () => URL.revokeObjectURL(_src)];
}, [html]);
(0, import_element49.useEffect)(() => cleanup, [cleanup]);
const shouldRenderFocusCaptureElements = tabIndex >= 0 && !isPreviewMode;
const iframe = /* @__PURE__ */ (0, import_jsx_runtime161.jsxs)(import_jsx_runtime161.Fragment, { children: [
shouldRenderFocusCaptureElements && before,
/* @__PURE__ */ (0, import_jsx_runtime161.jsx)(
"iframe",
{
...props,
style: {
...props.style,
height: props.style?.height,
border: 0
},
ref: (0, import_compose31.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_element49.createPortal)(
/* @__PURE__ */ (0, import_jsx_runtime161.jsxs)(
"body",
{
ref: bodyRef,
className: clsx_default(
"block-editor-iframe__body",
"editor-styles-wrapper",
...bodyClasses
),
children: [
contentResizeListener,
/* @__PURE__ */ (0, import_jsx_runtime161.jsx)(import_components33.__experimentalStyleProvider, { document: iframeDocument, children })
]
}
),
iframeDocument.documentElement
)
}
),
shouldRenderFocusCaptureElements && after
] });
return /* @__PURE__ */ (0, import_jsx_runtime161.jsxs)("div", { className: "block-editor-iframe__container", children: [
containerResizeListener,
/* @__PURE__ */ (0, import_jsx_runtime161.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_runtime161.jsx)(Iframe, { ...props, forwardedRef: ref });
}
var iframe_default = (0, import_element49.forwardRef)(IframeIfReady);
// packages/block-editor/build-module/components/editor-styles/index.mjs
var import_components34 = __toESM(require_components(), 1);
var import_element50 = __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, offset) {
let nesting = 0;
let result = "";
for (; offset < text.length; offset++) {
const char = text[offset];
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 offset = 0;
for (const token of tokens) {
switch (typeof token) {
case "string":
throw new Error(`Unexpected sequence ${token} found at index ${offset}`);
case "object":
offset += token.content.length;
token.pos = [offset - token.content.length, offset];
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, offset) => {
replacements.push({ value, offset });
return "\uE000".repeat(value.length);
});
selector3 = selector3.replace(STRING_PATTERN, (value, quote, content, offset) => {
replacements.push({ value, offset });
return `${quote}${"\uE001".repeat(content.length)}${quote}`;
});
{
let pos = 0;
let offset;
while ((offset = selector3.indexOf("(", pos)) > -1) {
const value = gobbleParens(selector3, offset);
replacements.push({ value, offset });
selector3 = `${selector3.substring(0, offset)}(${"\xB6".repeat(value.length - 2)})${selector3.substring(offset + value.length)}`;
pos = offset + 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, value } = replacement;
if (!(token.pos[0] <= offset && offset + value.length <= token.pos[1])) {
continue;
}
const { content } = token;
const tokenOffset = offset - 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: " "
},
...tokenizedPrefix
);
return stringify(tokenized);
}
function transformStyle({ css: css3, ignoredSelectors = [], baseURL }, wrapperSelector = "", transformOptions) {
if (!wrapperSelector && !baseURL) {
return css3;
}
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(css3, {}).css;
} catch (error) {
if (error instanceof import_css_syntax_error.default) {
console.warn(
"wp.blockEditor.transformStyles Failed to transform CSS.",
error.message + "\n" + error.showSourceCode(false)
);
} else {
console.warn(
"wp.blockEditor.transformStyles Failed to transform CSS.",
error
);
}
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 css3 = cache.get(style);
if (!css3) {
css3 = transformStyle(style, wrapperSelector, transformOptions);
cache.set(style, css3);
}
return css3;
});
};
var transform_styles_default = transformStyles;
// packages/block-editor/build-module/components/editor-styles/index.mjs
var import_jsx_runtime162 = __toESM(require_jsx_runtime(), 1);
k([names_default, a11y_default]);
function useDarkThemeBodyClassName(styles, scope) {
return (0, import_element50.useCallback)(
(node) => {
if (!node) {
return;
}
const { ownerDocument } = node;
const { defaultView, body } = ownerDocument;
const canvas = scope ? ownerDocument.querySelector(scope) : body;
let backgroundColor;
if (!canvas) {
const tempCanvas = ownerDocument.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_element50.useMemo)(() => {
const _styles = Object.values(styles ?? []);
for (const [id, override] of overrides) {
const index = _styles.findIndex(({ id: _id }) => id === _id);
const overrideWithId = { ...override, id };
if (index === -1) {
_styles.push(overrideWithId);
} else {
_styles[index] = 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_runtime162.jsxs)(import_jsx_runtime162.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime162.jsx)(
"style",
{
ref: useDarkThemeBodyClassName(transformedStyles, scope)
}
),
transformedStyles.map((css3, index) => /* @__PURE__ */ (0, import_jsx_runtime162.jsx)("style", { children: css3 }, index)),
/* @__PURE__ */ (0, import_jsx_runtime162.jsx)(
import_components34.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_element50.memo)(EditorStyles);
// packages/block-editor/build-module/components/block-preview/auto.mjs
var import_jsx_runtime163 = __toESM(require_jsx_runtime(), 1);
var MemoizedBlockList = (0, import_element51.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_compose32.useResizeObserver)();
const { styles } = (0, import_data52.useSelect)((select3) => {
const settings2 = select3(store).getSettings();
return {
styles: settings2.styles
};
}, []);
const editorStyles = (0, import_element51.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_runtime163.jsx)(
import_components35.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_runtime163.jsxs)(
iframe_default,
{
contentRef: (0, import_compose32.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_runtime163.jsx)(editor_styles_default, { styles: editorStyles }),
contentResizeListener,
/* @__PURE__ */ (0, import_jsx_runtime163.jsx)(MemoizedBlockList, { renderAppender: false })
]
}
)
}
);
}
function AutoBlockPreview(props) {
const [containerResizeListener, { width: containerWidth }] = (0, import_compose32.useResizeObserver)();
return /* @__PURE__ */ (0, import_jsx_runtime163.jsxs)(import_jsx_runtime163.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime163.jsx)("div", { style: { position: "relative", width: "100%", height: 0 }, children: containerResizeListener }),
/* @__PURE__ */ (0, import_jsx_runtime163.jsx)("div", { className: "block-editor-block-preview__container", children: !!containerWidth && /* @__PURE__ */ (0, import_jsx_runtime163.jsx)(
ScaledBlockPreview,
{
...props,
containerWidth
}
) })
] });
}
// packages/block-editor/build-module/components/block-preview/async.mjs
var import_element52 = __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_element52.useState)(false);
(0, import_element52.useEffect)(() => {
const context = {};
blockPreviewQueue.add(context, () => {
(0, import_element52.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_runtime164 = __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_element53.useMemo)(
() => ({
...originalSettings,
focusMode: false,
// Disable "Spotlight mode".
isPreviewMode: true
}),
[originalSettings]
);
const renderedBlocks = (0, import_element53.useMemo)(
() => Array.isArray(blocks2) ? blocks2 : [blocks2],
[blocks2]
);
if (!blocks2 || blocks2.length === 0) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime164.jsx)(
ExperimentalBlockEditorProvider,
{
value: renderedBlocks,
settings: settings2,
children: /* @__PURE__ */ (0, import_jsx_runtime164.jsx)(
AutoBlockPreview,
{
viewportWidth,
minHeight,
additionalStyles
}
)
}
);
}
var MemoizedBlockPreview = (0, import_element53.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_element53.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_compose33.useDisabled)();
const ref = (0, import_compose33.useMergeRefs)([props.ref, disabledRef]);
const renderedBlocks = (0, import_element53.useMemo)(
() => Array.isArray(blocks2) ? blocks2 : [blocks2],
[blocks2]
);
const children = /* @__PURE__ */ (0, import_jsx_runtime164.jsxs)(
ExperimentalBlockEditorProvider,
{
value: renderedBlocks,
settings: settings2,
children: [
/* @__PURE__ */ (0, import_jsx_runtime164.jsx)(editor_styles_default, {}),
/* @__PURE__ */ (0, import_jsx_runtime164.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_runtime165 = __toESM(require_jsx_runtime(), 1);
function InserterPreviewPanel({ item }) {
const { name, title, icon, description, initialAttributes, example } = item;
const isReusable = (0, import_blocks29.isReusableBlock)(item);
const blocks2 = (0, import_element54.useMemo)(() => {
if (!example) {
return (0, import_blocks29.createBlock)(name, initialAttributes);
}
return (0, import_blocks29.getBlockFromExample)(name, {
attributes: {
...example.attributes,
...initialAttributes
},
innerBlocks: example.innerBlocks
});
}, [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_runtime165.jsxs)("div", { className: "block-editor-inserter__preview-container", children: [
/* @__PURE__ */ (0, import_jsx_runtime165.jsx)("div", { className: "block-editor-inserter__preview", children: isReusable || example ? /* @__PURE__ */ (0, import_jsx_runtime165.jsx)("div", { className: "block-editor-inserter__preview-content", children: /* @__PURE__ */ (0, import_jsx_runtime165.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_runtime165.jsx)("div", { className: "block-editor-inserter__preview-content-missing", children: (0, import_i18n41.__)("No preview available.") }) }),
!isReusable && /* @__PURE__ */ (0, import_jsx_runtime165.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_i18n45 = __toESM(require_i18n(), 1);
var import_element61 = __toESM(require_element(), 1);
var import_compose35 = __toESM(require_compose(), 1);
// packages/block-editor/build-module/components/block-types-list/index.mjs
var import_blocks32 = __toESM(require_blocks(), 1);
var import_compose34 = __toESM(require_compose(), 1);
// packages/block-editor/build-module/components/inserter-list-item/index.mjs
var import_element60 = __toESM(require_element(), 1);
var import_blocks31 = __toESM(require_blocks(), 1);
var import_components41 = __toESM(require_components(), 1);
var import_keycodes6 = __toESM(require_keycodes(), 1);
// packages/block-editor/build-module/components/inserter-listbox/index.mjs
var import_components38 = __toESM(require_components(), 1);
var import_element58 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/inserter-listbox/group.mjs
var import_element55 = __toESM(require_element(), 1);
var import_i18n42 = __toESM(require_i18n(), 1);
var import_a11y5 = __toESM(require_a11y(), 1);
var import_jsx_runtime166 = __toESM(require_jsx_runtime(), 1);
function InserterListboxGroup(props, ref) {
const [shouldSpeak, setShouldSpeak] = (0, import_element55.useState)(false);
(0, import_element55.useEffect)(() => {
if (shouldSpeak) {
(0, import_a11y5.speak)(
(0, import_i18n42.__)("Use left and right arrow keys to move through blocks")
);
}
}, [shouldSpeak]);
return /* @__PURE__ */ (0, import_jsx_runtime166.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_element55.forwardRef)(InserterListboxGroup);
// packages/block-editor/build-module/components/inserter-listbox/row.mjs
var import_element56 = __toESM(require_element(), 1);
var import_components36 = __toESM(require_components(), 1);
var import_jsx_runtime167 = __toESM(require_jsx_runtime(), 1);
function InserterListboxRow(props, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime167.jsx)(import_components36.Composite.Group, { role: "presentation", ref, ...props });
}
var row_default2 = (0, import_element56.forwardRef)(InserterListboxRow);
// packages/block-editor/build-module/components/inserter-listbox/item.mjs
var import_components37 = __toESM(require_components(), 1);
var import_element57 = __toESM(require_element(), 1);
var import_jsx_runtime168 = __toESM(require_jsx_runtime(), 1);
function InserterListboxItem({ isFirst, as: Component7, children, ...props }, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(
import_components37.Composite.Item,
{
ref,
role: "option",
accessibleWhenDisabled: true,
...props,
render: (htmlProps) => {
const propsWithTabIndex = {
...htmlProps,
tabIndex: isFirst ? 0 : htmlProps.tabIndex
};
if (Component7) {
return /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(Component7, { ...propsWithTabIndex, children });
}
if (typeof children === "function") {
return children(propsWithTabIndex);
}
return /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(import_components37.Button, { __next40pxDefaultSize: true, ...propsWithTabIndex, children });
}
}
);
}
var item_default = (0, import_element57.forwardRef)(InserterListboxItem);
// packages/block-editor/build-module/components/inserter-listbox/index.mjs
var import_jsx_runtime169 = __toESM(require_jsx_runtime(), 1);
function InserterListBoxWrapper({ key, children }) {
return /* @__PURE__ */ (0, import_jsx_runtime169.jsx)(import_element58.Fragment, { children }, key);
}
function InserterListbox({ children }) {
return /* @__PURE__ */ (0, import_jsx_runtime169.jsx)(
import_components38.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_components40 = __toESM(require_components(), 1);
var import_blocks30 = __toESM(require_blocks(), 1);
var import_data54 = __toESM(require_data(), 1);
var import_element59 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/block-draggable/draggable-chip.mjs
var import_i18n43 = __toESM(require_i18n(), 1);
var import_components39 = __toESM(require_components(), 1);
var import_jsx_runtime170 = __toESM(require_jsx_runtime(), 1);
function BlockDraggableChip({
count,
icon,
isPattern,
fadeWhenDisabled
}) {
const patternLabel = isPattern && (0, import_i18n43.__)("Pattern");
return /* @__PURE__ */ (0, import_jsx_runtime170.jsx)("div", { className: "block-editor-block-draggable-chip-wrapper", children: /* @__PURE__ */ (0, import_jsx_runtime170.jsx)(
"div",
{
className: "block-editor-block-draggable-chip",
"data-testid": "block-draggable-chip",
children: /* @__PURE__ */ (0, import_jsx_runtime170.jsxs)(
import_components39.Flex,
{
justify: "center",
className: "block-editor-block-draggable-chip__content",
children: [
/* @__PURE__ */ (0, import_jsx_runtime170.jsx)(import_components39.FlexItem, { children: icon ? /* @__PURE__ */ (0, import_jsx_runtime170.jsx)(block_icon_default, { icon }) : patternLabel || (0, import_i18n43.sprintf)(
/* translators: %d: Number of blocks. */
(0, import_i18n43._n)("%d block", "%d blocks", count),
count
) }),
/* @__PURE__ */ (0, import_jsx_runtime170.jsx)(import_components39.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime170.jsx)(block_icon_default, { icon: drag_handle_default }) }),
fadeWhenDisabled && /* @__PURE__ */ (0, import_jsx_runtime170.jsx)(import_components39.FlexItem, { className: "block-editor-block-draggable-chip__disabled", children: /* @__PURE__ */ (0, import_jsx_runtime170.jsx)("span", { className: "block-editor-block-draggable-chip__disabled-icon" }) })
]
}
)
}
) });
}
// packages/block-editor/build-module/components/inserter-draggable-blocks/index.mjs
var import_jsx_runtime171 = __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_blocks30.store).getBlockType(blockName)?.icon;
},
[blockName]
);
const { startDragging: startDragging2, stopDragging: stopDragging2 } = unlock(
(0, import_data54.useDispatch)(store)
);
const patternBlock = (0, import_element59.useMemo)(() => {
return pattern?.type === INSERTER_PATTERN_TYPES.user && pattern?.syncStatus !== "unsynced" ? [(0, import_blocks30.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_runtime171.jsx)(
import_components40.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_runtime171.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_runtime172 = __toESM(require_jsx_runtime(), 1);
function InserterListItem({
className,
isFirst,
item,
onSelect,
onHover,
isDraggable,
...props
}) {
const isDraggingRef = (0, import_element60.useRef)(false);
const itemIconStyle = item.icon ? {
backgroundColor: item.icon.background,
color: item.icon.foreground
} : {};
const blocks2 = (0, import_element60.useMemo)(
() => [
(0, import_blocks31.createBlock)(
item.name,
item.initialAttributes,
(0, import_blocks31.createBlocksFromInnerBlocksTemplate)(item.innerBlocks)
)
],
[item.name, item.initialAttributes, item.innerBlocks]
);
const isSynced = (0, import_blocks31.isReusableBlock)(item) && item.syncStatus !== "unsynced" || (0, import_blocks31.isTemplatePart)(item);
return /* @__PURE__ */ (0, import_jsx_runtime172.jsx)(
inserter_draggable_blocks_default,
{
isEnabled: isDraggable && !item.isDisabled,
blocks: blocks2,
icon: item.icon,
children: ({ draggable, onDragStart, onDragEnd }) => /* @__PURE__ */ (0, import_jsx_runtime172.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_runtime172.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_keycodes6.isAppleOS)() ? event.metaKey : event.ctrlKey
);
onHover(null);
},
onKeyDown: (event) => {
const { keyCode } = event;
if (keyCode === import_keycodes6.ENTER) {
event.preventDefault();
onSelect(
item,
(0, import_keycodes6.isAppleOS)() ? event.metaKey : event.ctrlKey
);
onHover(null);
}
},
onMouseEnter: () => {
if (isDraggingRef.current) {
return;
}
onHover(item);
},
onMouseLeave: () => onHover(null),
...props,
children: [
/* @__PURE__ */ (0, import_jsx_runtime172.jsx)(
"span",
{
className: "block-editor-block-types-list__item-icon",
style: itemIconStyle,
children: /* @__PURE__ */ (0, import_jsx_runtime172.jsx)(block_icon_default, { icon: item.icon, showColors: true })
}
),
/* @__PURE__ */ (0, import_jsx_runtime172.jsx)("span", { className: "block-editor-block-types-list__item-title", children: /* @__PURE__ */ (0, import_jsx_runtime172.jsx)(import_components41.__experimentalTruncate, { numberOfLines: 3, children: item.title }) })
]
}
)
}
)
}
);
}
var inserter_list_item_default = (0, import_element60.memo)(InserterListItem);
// packages/block-editor/build-module/components/block-types-list/index.mjs
var import_jsx_runtime173 = __toESM(require_jsx_runtime(), 1);
function chunk(array, size) {
const chunks = [];
for (let i2 = 0, j2 = array.length; i2 < j2; i2 += size) {
chunks.push(array.slice(i2, i2 + size));
}
return chunks;
}
function BlockTypesList({
items = [],
onSelect,
onHover = () => {
},
children,
label,
isDraggable = true
}) {
const className = "block-editor-block-types-list";
const listId = (0, import_compose34.useInstanceId)(BlockTypesList, className);
return /* @__PURE__ */ (0, import_jsx_runtime173.jsxs)(group_default2, { className, "aria-label": label, children: [
chunk(items, 3).map((row, i2) => /* @__PURE__ */ (0, import_jsx_runtime173.jsx)(row_default2, { children: row.map((item, j2) => /* @__PURE__ */ (0, import_jsx_runtime173.jsx)(
inserter_list_item_default,
{
item,
className: (0, import_blocks32.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_components42 = __toESM(require_components(), 1);
var import_jsx_runtime174 = __toESM(require_jsx_runtime(), 1);
function InserterPanel({ title, icon, children }) {
return /* @__PURE__ */ (0, import_jsx_runtime174.jsxs)(import_jsx_runtime174.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime174.jsxs)("div", { className: "block-editor-inserter__panel-header", children: [
/* @__PURE__ */ (0, import_jsx_runtime174.jsx)("h2", { className: "block-editor-inserter__panel-title", children: title }),
/* @__PURE__ */ (0, import_jsx_runtime174.jsx)(import_components42.Icon, { icon })
] }),
/* @__PURE__ */ (0, import_jsx_runtime174.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_i18n44 = __toESM(require_i18n(), 1);
var import_jsx_runtime175 = __toESM(require_jsx_runtime(), 1);
function InserterNoResults() {
return /* @__PURE__ */ (0, import_jsx_runtime175.jsx)("div", { className: "block-editor-inserter__no-results", children: /* @__PURE__ */ (0, import_jsx_runtime175.jsx)("p", { children: (0, import_i18n44.__)("No results found.") }) });
}
var no_results_default = InserterNoResults;
// packages/block-editor/build-module/components/inserter/block-types-tab.mjs
var import_jsx_runtime176 = __toESM(require_jsx_runtime(), 1);
var getBlockNamespace = (item) => item.name.split("/")[0];
var MAX_SUGGESTED_ITEMS = 6;
var EMPTY_ARRAY5 = [];
function BlockTypesTabPanel({
items,
collections,
categories,
onSelectItem,
onHover,
showMostUsedBlocks,
className
}) {
const suggestedItems = (0, import_element61.useMemo)(() => {
return orderBy(items, "frecency", "desc").slice(
0,
MAX_SUGGESTED_ITEMS
);
}, [items]);
const uncategorizedItems = (0, import_element61.useMemo)(() => {
return items.filter((item) => !item.category);
}, [items]);
const itemsPerCollection = (0, import_element61.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_element61.useEffect)(() => () => onHover(null), []);
const currentlyRenderedCategories = (0, import_compose35.useAsyncList)(categories);
const didRenderAllCategories = categories.length === currentlyRenderedCategories.length;
const collectionEntries = (0, import_element61.useMemo)(() => {
return Object.entries(collections);
}, [collections]);
const currentlyRenderedCollections = (0, import_compose35.useAsyncList)(
didRenderAllCategories ? collectionEntries : EMPTY_ARRAY5
);
return /* @__PURE__ */ (0, import_jsx_runtime176.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_runtime176.jsx)(panel_default, { title: (0, import_i18n45._x)("Most used", "blocks"), children: /* @__PURE__ */ (0, import_jsx_runtime176.jsx)(
block_types_list_default,
{
items: suggestedItems,
onSelect: onSelectItem,
onHover,
label: (0, import_i18n45._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_runtime176.jsx)(
panel_default,
{
title: category.title,
icon: category.icon,
children: /* @__PURE__ */ (0, import_jsx_runtime176.jsx)(
block_types_list_default,
{
items: categoryItems,
onSelect: onSelectItem,
onHover,
label: category.title
}
)
},
category.slug
);
}),
didRenderAllCategories && uncategorizedItems.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime176.jsx)(
panel_default,
{
className: "block-editor-inserter__uncategorized-blocks-panel",
title: (0, import_i18n45.__)("Uncategorized"),
children: /* @__PURE__ */ (0, import_jsx_runtime176.jsx)(
block_types_list_default,
{
items: uncategorizedItems,
onSelect: onSelectItem,
onHover,
label: (0, import_i18n45.__)("Uncategorized")
}
)
}
),
currentlyRenderedCollections.map(
([namespace, collection]) => {
const collectionItems = itemsPerCollection[namespace];
if (!collectionItems || !collectionItems.length) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime176.jsx)(
panel_default,
{
title: collection.title,
icon: collection.icon,
children: /* @__PURE__ */ (0, import_jsx_runtime176.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_runtime176.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_runtime176.jsx)(inserter_listbox_default, { children: /* @__PURE__ */ (0, import_jsx_runtime176.jsxs)("div", { ref, children: [
!!itemsForCurrentRoot.length && /* @__PURE__ */ (0, import_jsx_runtime176.jsx)(import_jsx_runtime176.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime176.jsx)(
BlockTypesTabPanel,
{
items: itemsForCurrentRoot,
categories,
collections,
onSelectItem,
onHover,
showMostUsedBlocks,
className: "block-editor-inserter__insertable-blocks-at-selection"
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime176.jsx)(
BlockTypesTabPanel,
{
items: itemsRemaining,
categories,
collections,
onSelectItem,
onHover,
showMostUsedBlocks,
className: "block-editor-inserter__all-blocks"
}
)
] }) });
}
var block_types_tab_default = (0, import_element61.forwardRef)(BlockTypesTab);
// packages/block-editor/build-module/components/inserter/block-patterns-tab/index.mjs
var import_element72 = __toESM(require_element(), 1);
var import_compose40 = __toESM(require_compose(), 1);
var import_components52 = __toESM(require_components(), 1);
var import_i18n57 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/inserter/block-patterns-explorer/index.mjs
var import_components47 = __toESM(require_components(), 1);
var import_element68 = __toESM(require_element(), 1);
var import_i18n53 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/inserter/block-patterns-explorer/pattern-explorer-sidebar.mjs
var import_components43 = __toESM(require_components(), 1);
var import_i18n46 = __toESM(require_i18n(), 1);
var import_jsx_runtime177 = __toESM(require_jsx_runtime(), 1);
function PatternCategoriesList({
selectedCategory,
patternCategories,
onClickCategory
}) {
const baseClassName = "block-editor-block-patterns-explorer__sidebar";
return /* @__PURE__ */ (0, import_jsx_runtime177.jsx)("div", { className: `${baseClassName}__categories-list`, children: patternCategories.map(({ name, label }) => {
return /* @__PURE__ */ (0, import_jsx_runtime177.jsx)(
import_components43.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_runtime177.jsx)("div", { className: baseClassName, children: /* @__PURE__ */ (0, import_jsx_runtime177.jsx)(
import_components43.SearchControl,
{
onChange: setSearchValue,
value: searchValue,
label: (0, import_i18n46.__)("Search"),
placeholder: (0, import_i18n46.__)("Search")
}
) });
}
function PatternExplorerSidebar({
selectedCategory,
patternCategories,
onClickCategory,
searchValue,
setSearchValue
}) {
const baseClassName = "block-editor-block-patterns-explorer__sidebar";
return /* @__PURE__ */ (0, import_jsx_runtime177.jsxs)("div", { className: baseClassName, children: [
/* @__PURE__ */ (0, import_jsx_runtime177.jsx)(
PatternsExplorerSearch,
{
searchValue,
setSearchValue
}
),
!searchValue && /* @__PURE__ */ (0, import_jsx_runtime177.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_element66 = __toESM(require_element(), 1);
var import_i18n51 = __toESM(require_i18n(), 1);
var import_compose38 = __toESM(require_compose(), 1);
var import_components46 = __toESM(require_components(), 1);
var import_a11y7 = __toESM(require_a11y(), 1);
// packages/block-editor/build-module/components/block-patterns-list/index.mjs
var import_blocks33 = __toESM(require_blocks(), 1);
var import_element62 = __toESM(require_element(), 1);
var import_components45 = __toESM(require_components(), 1);
var import_compose36 = __toESM(require_compose(), 1);
var import_i18n48 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/block-patterns-paging/index.mjs
var import_components44 = __toESM(require_components(), 1);
var import_i18n47 = __toESM(require_i18n(), 1);
var import_jsx_runtime178 = __toESM(require_jsx_runtime(), 1);
function Pagination({
currentPage,
numPages,
changePage,
totalItems
}) {
return /* @__PURE__ */ (0, import_jsx_runtime178.jsxs)(import_components44.__experimentalVStack, { className: "block-editor-patterns__grid-pagination-wrapper", children: [
/* @__PURE__ */ (0, import_jsx_runtime178.jsx)(import_components44.__experimentalText, { variant: "muted", children: (0, import_i18n47.sprintf)(
// translators: %s: Total number of patterns.
(0, import_i18n47._n)("%s item", "%s items", totalItems),
totalItems
) }),
numPages > 1 && /* @__PURE__ */ (0, import_jsx_runtime178.jsxs)(
import_components44.__experimentalHStack,
{
expanded: false,
spacing: 3,
justify: "flex-start",
className: "block-editor-patterns__grid-pagination",
children: [
/* @__PURE__ */ (0, import_jsx_runtime178.jsxs)(
import_components44.__experimentalHStack,
{
expanded: false,
spacing: 1,
className: "block-editor-patterns__grid-pagination-previous",
children: [
/* @__PURE__ */ (0, import_jsx_runtime178.jsx)(
import_components44.Button,
{
variant: "tertiary",
onClick: () => changePage(1),
disabled: currentPage === 1,
"aria-label": (0, import_i18n47.__)("First page"),
size: "compact",
accessibleWhenDisabled: true,
className: "block-editor-patterns__grid-pagination-button",
children: /* @__PURE__ */ (0, import_jsx_runtime178.jsx)("span", { children: "\xAB" })
}
),
/* @__PURE__ */ (0, import_jsx_runtime178.jsx)(
import_components44.Button,
{
variant: "tertiary",
onClick: () => changePage(currentPage - 1),
disabled: currentPage === 1,
"aria-label": (0, import_i18n47.__)("Previous page"),
size: "compact",
accessibleWhenDisabled: true,
className: "block-editor-patterns__grid-pagination-button",
children: /* @__PURE__ */ (0, import_jsx_runtime178.jsx)("span", { children: "\u2039" })
}
)
]
}
),
/* @__PURE__ */ (0, import_jsx_runtime178.jsx)(import_components44.__experimentalText, { variant: "muted", children: (0, import_i18n47.sprintf)(
// translators: 1: Current page number. 2: Total number of pages.
(0, import_i18n47._x)("%1$s of %2$s", "paging"),
currentPage,
numPages
) }),
/* @__PURE__ */ (0, import_jsx_runtime178.jsxs)(
import_components44.__experimentalHStack,
{
expanded: false,
spacing: 1,
className: "block-editor-patterns__grid-pagination-next",
children: [
/* @__PURE__ */ (0, import_jsx_runtime178.jsx)(
import_components44.Button,
{
variant: "tertiary",
onClick: () => changePage(currentPage + 1),
disabled: currentPage === numPages,
"aria-label": (0, import_i18n47.__)("Next page"),
size: "compact",
accessibleWhenDisabled: true,
className: "block-editor-patterns__grid-pagination-button",
children: /* @__PURE__ */ (0, import_jsx_runtime178.jsx)("span", { children: "\u203A" })
}
),
/* @__PURE__ */ (0, import_jsx_runtime178.jsx)(
import_components44.Button,
{
variant: "tertiary",
onClick: () => changePage(numPages),
disabled: currentPage === numPages,
"aria-label": (0, import_i18n47.__)("Last page"),
size: "compact",
accessibleWhenDisabled: true,
className: "block-editor-patterns__grid-pagination-button",
children: /* @__PURE__ */ (0, import_jsx_runtime178.jsx)("span", { children: "\xBB" })
}
)
]
}
)
]
}
)
] });
}
// packages/block-editor/build-module/components/block-patterns-list/index.mjs
var import_jsx_runtime179 = __toESM(require_jsx_runtime(), 1);
var WithToolTip = ({ showTooltip, title, children }) => {
if (showTooltip) {
return /* @__PURE__ */ (0, import_jsx_runtime179.jsx)(import_components45.Tooltip, { text: title, children });
}
return /* @__PURE__ */ (0, import_jsx_runtime179.jsx)(import_jsx_runtime179.Fragment, { children });
};
function BlockPattern({
id,
isDraggable,
pattern,
onClick,
onHover,
showTitlesAsTooltip,
category,
isSelected
}) {
const [isDragging3, setIsDragging] = (0, import_element62.useState)(false);
const { blocks: blocks2, viewportWidth } = pattern;
const instanceId = (0, import_compose36.useInstanceId)(BlockPattern);
const descriptionId = `block-editor-block-patterns-list__item-description-${instanceId}`;
const isUserPattern = pattern.type === INSERTER_PATTERN_TYPES.user;
const patternBlocks = (0, import_element62.useMemo)(() => {
if (!category || !isDraggable) {
return blocks2;
}
return (blocks2 ?? []).map((block) => {
const clonedBlock = (0, import_blocks33.cloneBlock)(block);
if (clonedBlock.attributes.metadata?.categories?.includes(
category
)) {
clonedBlock.attributes.metadata.categories = [category];
}
return clonedBlock;
});
}, [blocks2, isDraggable, category]);
return /* @__PURE__ */ (0, import_jsx_runtime179.jsx)(
inserter_draggable_blocks_default,
{
isEnabled: isDraggable,
blocks: patternBlocks,
pattern,
children: ({ draggable, onDragStart, onDragEnd }) => /* @__PURE__ */ (0, import_jsx_runtime179.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_runtime179.jsx)(
WithToolTip,
{
showTooltip: showTitlesAsTooltip && !isUserPattern,
title: pattern.title,
children: /* @__PURE__ */ (0, import_jsx_runtime179.jsxs)(
import_components45.Composite.Item,
{
render: /* @__PURE__ */ (0, import_jsx_runtime179.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_runtime179.jsx)(
block_preview_default.Async,
{
placeholder: /* @__PURE__ */ (0, import_jsx_runtime179.jsx)(BlockPatternPlaceholder, {}),
children: /* @__PURE__ */ (0, import_jsx_runtime179.jsx)(
block_preview_default,
{
blocks: blocks2,
viewportWidth
}
)
}
),
(!showTitlesAsTooltip || isUserPattern) && /* @__PURE__ */ (0, import_jsx_runtime179.jsxs)(
import_components45.__experimentalHStack,
{
className: "block-editor-patterns__pattern-details",
spacing: 2,
children: [
isUserPattern && !pattern.syncStatus && /* @__PURE__ */ (0, import_jsx_runtime179.jsx)("div", { className: "block-editor-patterns__pattern-icon-wrapper", children: /* @__PURE__ */ (0, import_jsx_runtime179.jsx)(
icon_default,
{
className: "block-editor-patterns__pattern-icon",
icon: symbol_default
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime179.jsx)("div", { className: "block-editor-block-patterns-list__item-title", children: pattern.title })
]
}
),
!!pattern.description && /* @__PURE__ */ (0, import_jsx_runtime179.jsx)(import_components45.VisuallyHidden, { id: descriptionId, children: pattern.description })
]
}
)
}
)
}
)
}
);
}
function BlockPatternPlaceholder() {
return /* @__PURE__ */ (0, import_jsx_runtime179.jsx)("div", { className: "block-editor-block-patterns-list__item is-placeholder" });
}
function BlockPatternsList({
isDraggable,
blockPatterns,
onHover,
onClickPattern,
orientation,
label = (0, import_i18n48.__)("Block patterns"),
category,
showTitlesAsTooltip,
pagingProps
}, ref) {
const [activeCompositeId, setActiveCompositeId] = (0, import_element62.useState)(void 0);
const [activePattern, setActivePattern] = (0, import_element62.useState)(null);
(0, import_element62.useEffect)(() => {
const firstCompositeItemId = blockPatterns[0]?.name;
setActiveCompositeId(firstCompositeItemId);
}, [blockPatterns]);
const handleClickPattern = (pattern, blocks2) => {
setActivePattern(pattern.name);
onClickPattern(pattern, blocks2);
};
return /* @__PURE__ */ (0, import_jsx_runtime179.jsxs)(
import_components45.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_runtime179.jsx)(
BlockPattern,
{
id: pattern.name,
pattern,
onClick: handleClickPattern,
onHover,
isDraggable,
showTitlesAsTooltip,
category,
isSelected: !!activePattern && activePattern === pattern.name
},
pattern.name
)),
pagingProps && /* @__PURE__ */ (0, import_jsx_runtime179.jsx)(Pagination, { ...pagingProps })
]
}
);
}
var block_patterns_list_default = (0, import_element62.forwardRef)(BlockPatternsList);
// packages/block-editor/build-module/components/inserter/hooks/use-insertion-point.mjs
var import_data55 = __toESM(require_data(), 1);
var import_blocks34 = __toESM(require_blocks(), 1);
var import_i18n49 = __toESM(require_i18n(), 1);
var import_a11y6 = __toESM(require_a11y(), 1);
var import_element63 = __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_element63.useCallback)(
(blocks2, meta, shouldForceFocusBlock = false, _rootClientId) => {
if (shouldForceFocusBlock || shouldFocusBlock || selectBlockOnInsert) {
setLastFocus2(null);
}
const selectedBlock = getSelectedBlock2();
if (!isAppender && selectedBlock && (0, import_blocks34.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_i18n49.sprintf)(
// translators: %d: the name of the block that has been added
(0, import_i18n49._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_element63.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_element64 = __toESM(require_element(), 1);
var import_blocks35 = __toESM(require_blocks(), 1);
var import_data56 = __toESM(require_data(), 1);
var import_i18n50 = __toESM(require_i18n(), 1);
var import_notices6 = __toESM(require_notices(), 1);
var usePatternsState = (onInsert, rootClientId, selectedCategory, isQuick) => {
const options = (0, import_element64.useMemo)(
() => ({ [isFiltered]: !!isQuick }),
[isQuick]
);
const { patternCategories, patterns, userPatternCategories } = (0, import_data56.useSelect)(
(select3) => {
const { getSettings: getSettings8, __experimentalGetAllowedPatterns: __experimentalGetAllowedPatterns2 } = unlock(
select3(store)
);
const {
__experimentalUserPatternCategories,
__experimentalBlockPatternCategories
} = getSettings8();
return {
patterns: __experimentalGetAllowedPatterns2(
rootClientId,
options
),
userPatternCategories: __experimentalUserPatternCategories,
patternCategories: __experimentalBlockPatternCategories
};
},
[rootClientId, options]
);
const { getClosestAllowedInsertionPointForPattern: getClosestAllowedInsertionPointForPattern2 } = unlock(
(0, import_data56.useSelect)(store)
);
const allCategories = (0, import_element64.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_notices6.store);
const onClickPattern = (0, import_element64.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_blocks35.createBlock)("core/block", { ref: pattern.id })] : blocks2;
onInsert(
(patternBlocks ?? []).map((block) => {
const clonedBlock = (0, import_blocks35.cloneBlock)(block);
if (clonedBlock.attributes.metadata?.categories?.includes(
selectedCategory
)) {
clonedBlock.attributes.metadata.categories = [
selectedCategory
];
}
return clonedBlock;
}),
pattern.name,
false,
destinationRootClientId
);
createSuccessNotice(
(0, import_i18n50.sprintf)(
/* translators: %s: block pattern title. */
(0, import_i18n50.__)('Block pattern "%s" inserted.'),
pattern.title
),
{
type: "snackbar",
id: "inserter-notice"
}
);
},
[
createSuccessNotice,
onInsert,
selectedCategory,
rootClientId,
getClosestAllowedInsertionPointForPattern2,
isQuick
]
);
return [patterns, allCategories, onClickPattern];
};
var use_patterns_state_default = usePatternsState;
// packages/block-editor/build-module/components/inserter/hooks/use-patterns-paging.mjs
var import_element65 = __toESM(require_element(), 1);
var import_compose37 = __toESM(require_compose(), 1);
var import_dom19 = __toESM(require_dom(), 1);
var PAGE_SIZE = 20;
function usePatternsPaging(currentCategoryPatterns, currentCategory, scrollContainerRef, currentFilter = "") {
const [currentPage, setCurrentPage] = (0, import_element65.useState)(1);
const previousCategory = (0, import_compose37.usePrevious)(currentCategory);
const previousFilter = (0, import_compose37.usePrevious)(currentFilter);
if ((previousCategory !== currentCategory || previousFilter !== currentFilter) && currentPage !== 1) {
setCurrentPage(1);
}
const totalItems = currentCategoryPatterns.length;
const pageIndex = currentPage - 1;
const categoryPatterns = (0, import_element65.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_dom19.getScrollContainer)(
scrollContainerRef?.current
);
scrollContainer?.scrollTo(0, 0);
setCurrentPage(page);
};
(0, import_element65.useEffect)(
function scrollToTopOnCategoryChange() {
const scrollContainer = (0, import_dom19.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_runtime180 = __toESM(require_jsx_runtime(), 1);
function PatternsListHeader({ filterValue, filteredBlockPatternsLength }) {
if (!filterValue) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(
import_components46.__experimentalHeading,
{
level: 2,
lineHeight: "48px",
className: "block-editor-block-patterns-explorer__search-results-count",
children: (0, import_i18n51.sprintf)(
/* translators: %d: number of patterns. */
(0, import_i18n51._n)(
"%d pattern found",
"%d patterns found",
filteredBlockPatternsLength
),
filteredBlockPatternsLength
)
}
);
}
function PatternList({
searchValue,
selectedCategory,
patternCategories,
rootClientId,
onModalClose
}) {
const container = (0, import_element66.useRef)();
const debouncedSpeak = (0, import_compose38.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_element66.useMemo)(
() => patternCategories.map(
(patternCategory) => patternCategory.name
),
[patternCategories]
);
const filteredBlockPatterns = (0, import_element66.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_element66.useEffect)(() => {
if (!searchValue) {
return;
}
const count = filteredBlockPatterns.length;
const resultsFoundMessage = (0, import_i18n51.sprintf)(
/* translators: %d: number of results. */
(0, import_i18n51._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_element66.useState)(searchValue);
if (searchValue !== previousSearchValue) {
setPreviousSearchValue(searchValue);
pagingProps.changePage(1);
}
const hasItems = !!filteredBlockPatterns?.length;
return /* @__PURE__ */ (0, import_jsx_runtime180.jsxs)(
"div",
{
className: "block-editor-block-patterns-explorer__list",
ref: container,
children: [
/* @__PURE__ */ (0, import_jsx_runtime180.jsx)(
PatternsListHeader,
{
filterValue: searchValue,
filteredBlockPatternsLength: filteredBlockPatterns.length
}
),
/* @__PURE__ */ (0, import_jsx_runtime180.jsx)(inserter_listbox_default, { children: hasItems && /* @__PURE__ */ (0, import_jsx_runtime180.jsxs)(import_jsx_runtime180.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime180.jsx)(
block_patterns_list_default,
{
blockPatterns: pagingProps.categoryPatterns,
onClickPattern: (pattern, blocks2) => {
onClickPattern(pattern, blocks2);
onModalClose();
},
isDraggable: false
}
),
/* @__PURE__ */ (0, import_jsx_runtime180.jsx)(Pagination, { ...pagingProps })
] }) })
]
}
);
}
var pattern_list_default = PatternList;
// packages/block-editor/build-module/components/inserter/block-patterns-tab/use-pattern-categories.mjs
var import_element67 = __toESM(require_element(), 1);
var import_i18n52 = __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_element67.useMemo)(
() => sourceFilter === "all" ? patterns : patterns.filter(
(pattern) => !isPatternFiltered(pattern, sourceFilter)
),
[sourceFilter, patterns]
);
const populatedCategories = (0, import_element67.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_i18n52._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_i18n52.sprintf)(
/* translators: %d: number of categories . */
(0, import_i18n52._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_runtime181 = __toESM(require_jsx_runtime(), 1);
function PatternsExplorer({ initialCategory, rootClientId, onModalClose }) {
const [searchValue, setSearchValue] = (0, import_element68.useState)("");
const [selectedCategory, setSelectedCategory] = (0, import_element68.useState)(
initialCategory?.name
);
const patternCategories = usePatternCategories(rootClientId);
return /* @__PURE__ */ (0, import_jsx_runtime181.jsxs)("div", { className: "block-editor-block-patterns-explorer", children: [
/* @__PURE__ */ (0, import_jsx_runtime181.jsx)(
pattern_explorer_sidebar_default,
{
selectedCategory,
patternCategories,
onClickCategory: setSelectedCategory,
searchValue,
setSearchValue
}
),
/* @__PURE__ */ (0, import_jsx_runtime181.jsx)(
pattern_list_default,
{
searchValue,
selectedCategory,
patternCategories,
rootClientId,
onModalClose
}
)
] });
}
function PatternsExplorerModal({ onModalClose, ...restProps }) {
return /* @__PURE__ */ (0, import_jsx_runtime181.jsx)(
import_components47.Modal,
{
title: (0, import_i18n53.__)("Patterns"),
onRequestClose: onModalClose,
isFullScreen: true,
children: /* @__PURE__ */ (0, import_jsx_runtime181.jsx)(PatternsExplorer, { onModalClose, ...restProps })
}
);
}
var block_patterns_explorer_default = PatternsExplorerModal;
// packages/block-editor/build-module/components/inserter/mobile-tab-navigation.mjs
var import_i18n54 = __toESM(require_i18n(), 1);
var import_components48 = __toESM(require_components(), 1);
var import_jsx_runtime182 = __toESM(require_jsx_runtime(), 1);
function ScreenHeader({ title }) {
return /* @__PURE__ */ (0, import_jsx_runtime182.jsx)(import_components48.__experimentalVStack, { spacing: 0, children: /* @__PURE__ */ (0, import_jsx_runtime182.jsx)(import_components48.__experimentalView, { children: /* @__PURE__ */ (0, import_jsx_runtime182.jsx)(import_components48.__experimentalSpacer, { marginBottom: 0, paddingX: 4, paddingY: 3, children: /* @__PURE__ */ (0, import_jsx_runtime182.jsxs)(import_components48.__experimentalHStack, { spacing: 2, children: [
/* @__PURE__ */ (0, import_jsx_runtime182.jsx)(
import_components48.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_i18n54.isRTL)() ? chevron_right_default : chevron_left_default,
size: "small",
label: (0, import_i18n54.__)("Back")
}
),
/* @__PURE__ */ (0, import_jsx_runtime182.jsx)(import_components48.__experimentalSpacer, { children: /* @__PURE__ */ (0, import_jsx_runtime182.jsx)(import_components48.__experimentalHeading, { level: 5, children: title }) })
] }) }) }) });
}
function MobileTabNavigation({ categories, children }) {
return /* @__PURE__ */ (0, import_jsx_runtime182.jsxs)(
import_components48.Navigator,
{
initialPath: "/",
className: "block-editor-inserter__mobile-tab-navigation",
children: [
/* @__PURE__ */ (0, import_jsx_runtime182.jsx)(import_components48.Navigator.Screen, { path: "/", children: /* @__PURE__ */ (0, import_jsx_runtime182.jsx)(import_components48.__experimentalItemGroup, { children: categories.map((category) => /* @__PURE__ */ (0, import_jsx_runtime182.jsx)(
import_components48.Navigator.Button,
{
path: `/category/${category.name}`,
as: import_components48.__experimentalItem,
isAction: true,
children: /* @__PURE__ */ (0, import_jsx_runtime182.jsxs)(import_components48.__experimentalHStack, { children: [
/* @__PURE__ */ (0, import_jsx_runtime182.jsx)(import_components48.FlexBlock, { children: category.label }),
/* @__PURE__ */ (0, import_jsx_runtime182.jsx)(
icon_default,
{
icon: (0, import_i18n54.isRTL)() ? chevron_left_default : chevron_right_default
}
)
] })
},
category.name
)) }) }),
categories.map((category) => /* @__PURE__ */ (0, import_jsx_runtime182.jsxs)(
import_components48.Navigator.Screen,
{
path: `/category/${category.name}`,
children: [
/* @__PURE__ */ (0, import_jsx_runtime182.jsx)(ScreenHeader, { title: (0, import_i18n54.__)("Back") }),
children(category)
]
},
category.name
))
]
}
);
}
// packages/block-editor/build-module/components/inserter/block-patterns-tab/pattern-category-previews.mjs
var import_element70 = __toESM(require_element(), 1);
var import_i18n56 = __toESM(require_i18n(), 1);
var import_components50 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/inserter/block-patterns-tab/patterns-filter.mjs
var import_components49 = __toESM(require_components(), 1);
var import_i18n55 = __toESM(require_i18n(), 1);
var import_element69 = __toESM(require_element(), 1);
var import_jsx_runtime183 = __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_i18n55._x)("All", "patterns")
},
{
value: INSERTER_PATTERN_TYPES.directory,
label: (0, import_i18n55.__)("Pattern Directory")
},
{
value: INSERTER_PATTERN_TYPES.theme,
label: (0, import_i18n55.__)("Theme & Plugins")
},
{
value: INSERTER_PATTERN_TYPES.user,
label: (0, import_i18n55.__)("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_element69.useMemo)(
() => [
{
value: "all",
label: (0, import_i18n55._x)("All", "patterns")
},
{
value: INSERTER_SYNC_TYPES.full,
label: (0, import_i18n55._x)("Synced", "patterns"),
disabled: shouldDisableSyncFilter
},
{
value: INSERTER_SYNC_TYPES.unsynced,
label: (0, import_i18n55._x)("Not synced", "patterns"),
disabled: shouldDisableSyncFilter
}
],
[shouldDisableSyncFilter]
);
function handleSetSourceFilterChange(newSourceFilter) {
setPatternSourceFilter(newSourceFilter);
if (getShouldDisableSyncFilter(newSourceFilter)) {
setPatternSyncFilter("all");
}
}
return /* @__PURE__ */ (0, import_jsx_runtime183.jsx)(import_jsx_runtime183.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime183.jsx)(
import_components49.DropdownMenu,
{
popoverProps: {
placement: "right-end"
},
label: (0, import_i18n55.__)("Filter patterns"),
toggleProps: { size: "compact" },
icon: /* @__PURE__ */ (0, import_jsx_runtime183.jsx)(
icon_default,
{
icon: /* @__PURE__ */ (0, import_jsx_runtime183.jsx)(
import_components49.SVG,
{
width: "24",
height: "24",
viewBox: "0 0 24 24",
fill: "none",
xmlns: "http://www.w3.org/2000/svg",
children: /* @__PURE__ */ (0, import_jsx_runtime183.jsx)(
import_components49.Path,
{
d: "M10 17.5H14V16H10V17.5ZM6 6V7.5H18V6H6ZM8 12.5H16V11H8V12.5Z",
fill: "currentColor"
}
)
}
)
}
),
children: () => /* @__PURE__ */ (0, import_jsx_runtime183.jsxs)(import_jsx_runtime183.Fragment, { children: [
!shouldHideSourcesFilter && /* @__PURE__ */ (0, import_jsx_runtime183.jsx)(import_components49.MenuGroup, { label: (0, import_i18n55.__)("Source"), children: /* @__PURE__ */ (0, import_jsx_runtime183.jsx)(
import_components49.MenuItemsChoice,
{
choices: PATTERN_SOURCE_MENU_OPTIONS,
onSelect: (value) => {
handleSetSourceFilterChange(value);
scrollContainerRef.current?.scrollTo(
0,
0
);
},
value: currentPatternSourceFilter
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime183.jsx)(import_components49.MenuGroup, { label: (0, import_i18n55.__)("Type"), children: /* @__PURE__ */ (0, import_jsx_runtime183.jsx)(
import_components49.MenuItemsChoice,
{
choices: patternSyncMenuOptions,
onSelect: (value) => {
setPatternSyncFilter(value);
scrollContainerRef.current?.scrollTo(
0,
0
);
},
value: patternSyncFilter
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime183.jsx)("div", { className: "block-editor-inserter__patterns-filter-help", children: (0, import_element69.createInterpolateElement)(
(0, import_i18n55.__)(
"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_runtime183.jsx)(
import_components49.ExternalLink,
{
href: (0, import_i18n55.__)(
"https://wordpress.org/patterns/"
)
}
)
}
) })
] })
}
) });
}
// packages/block-editor/build-module/components/inserter/block-patterns-tab/pattern-category-previews.mjs
var import_jsx_runtime184 = __toESM(require_jsx_runtime(), 1);
var noop7 = () => {
};
function PatternCategoryPreviews({
rootClientId,
onInsert,
onHover = noop7,
category,
showTitlesAsTooltip
}) {
const [allPatterns, , onClickPattern] = use_patterns_state_default(
onInsert,
rootClientId,
category?.name
);
const [patternSyncFilter, setPatternSyncFilter] = (0, import_element70.useState)("all");
const [patternSourceFilter, setPatternSourceFilter] = (0, import_element70.useState)("all");
const availableCategories = usePatternCategories(
rootClientId,
patternSourceFilter
);
const scrollContainerRef = (0, import_element70.useRef)();
const currentCategoryPatterns = (0, import_element70.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_element70.useEffect)(() => () => onHover(null), []);
const onSetPatternSyncFilter = (0, import_element70.useCallback)(
(value) => {
setPatternSyncFilter(value);
changePage(1);
},
[setPatternSyncFilter, changePage]
);
const onSetPatternSourceFilter = (0, import_element70.useCallback)(
(value) => {
setPatternSourceFilter(value);
changePage(1);
},
[setPatternSourceFilter, changePage]
);
return /* @__PURE__ */ (0, import_jsx_runtime184.jsxs)(import_jsx_runtime184.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime184.jsxs)(
import_components50.__experimentalVStack,
{
spacing: 2,
className: "block-editor-inserter__patterns-category-panel-header",
children: [
/* @__PURE__ */ (0, import_jsx_runtime184.jsxs)(import_components50.__experimentalHStack, { children: [
/* @__PURE__ */ (0, import_jsx_runtime184.jsx)(import_components50.FlexBlock, { children: /* @__PURE__ */ (0, import_jsx_runtime184.jsx)(
import_components50.__experimentalHeading,
{
className: "block-editor-inserter__patterns-category-panel-title",
size: 13,
level: 4,
as: "div",
children: category.label
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime184.jsx)(
PatternsFilter,
{
patternSyncFilter,
patternSourceFilter,
setPatternSyncFilter: onSetPatternSyncFilter,
setPatternSourceFilter: onSetPatternSourceFilter,
scrollContainerRef,
category
}
)
] }),
!currentCategoryPatterns.length && /* @__PURE__ */ (0, import_jsx_runtime184.jsx)(
import_components50.__experimentalText,
{
variant: "muted",
className: "block-editor-inserter__patterns-category-no-results",
children: (0, import_i18n56.__)("No results found")
}
)
]
}
),
currentCategoryPatterns.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime184.jsxs)(import_jsx_runtime184.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime184.jsx)(
import_components50.__experimentalText,
{
size: "12",
as: "p",
className: "block-editor-inserter__help-text",
children: (0, import_i18n56.__)("Drag and drop patterns into the canvas.")
}
),
/* @__PURE__ */ (0, import_jsx_runtime184.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_compose39 = __toESM(require_compose(), 1);
var import_components51 = __toESM(require_components(), 1);
var import_element71 = __toESM(require_element(), 1);
var import_jsx_runtime185 = __toESM(require_jsx_runtime(), 1);
var { Tabs } = unlock(import_components51.privateApis);
function CategoryTabs({
categories,
selectedCategory,
onSelectCategory,
children
}) {
const ANIMATION_DURATION = 0.25;
const disableMotion = (0, import_compose39.useReducedMotion)();
const defaultTransition = {
type: "tween",
duration: disableMotion ? 0 : ANIMATION_DURATION,
ease: [0.6, 0, 0.4, 1]
};
const previousSelectedCategory = (0, import_compose39.usePrevious)(selectedCategory);
const selectedTabId = selectedCategory ? selectedCategory.name : null;
const [activeTabId, setActiveId] = (0, import_element71.useState)();
const firstTabId = categories?.[0]?.name;
if (selectedTabId === null && !activeTabId && firstTabId) {
setActiveId(firstTabId);
}
return /* @__PURE__ */ (0, import_jsx_runtime185.jsxs)(
Tabs,
{
selectOnMove: false,
selectedTabId,
orientation: "vertical",
onSelect: (categoryId) => {
onSelectCategory(
categories.find(
(category) => category.name === categoryId
)
);
},
activeTabId,
onActiveTabIdChange: setActiveId,
children: [
/* @__PURE__ */ (0, import_jsx_runtime185.jsx)(Tabs.TabList, { className: "block-editor-inserter__category-tablist", children: categories.map((category) => /* @__PURE__ */ (0, import_jsx_runtime185.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_runtime185.jsx)(
Tabs.TabPanel,
{
tabId: category.name,
focusable: false,
children: /* @__PURE__ */ (0, import_jsx_runtime185.jsx)(
import_components51.__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_runtime186 = __toESM(require_jsx_runtime(), 1);
function BlockPatternsTab({
onSelectCategory,
selectedCategory,
onInsert,
rootClientId,
children
}) {
const [showPatternsExplorer, setShowPatternsExplorer] = (0, import_element72.useState)(false);
const categories = usePatternCategories(rootClientId);
const isMobile = (0, import_compose40.useViewportMatch)("medium", "<");
if (!categories.length) {
return /* @__PURE__ */ (0, import_jsx_runtime186.jsx)(no_results_default, {});
}
return /* @__PURE__ */ (0, import_jsx_runtime186.jsxs)(import_jsx_runtime186.Fragment, { children: [
!isMobile && /* @__PURE__ */ (0, import_jsx_runtime186.jsxs)("div", { className: "block-editor-inserter__block-patterns-tabs-container", children: [
/* @__PURE__ */ (0, import_jsx_runtime186.jsx)(
category_tabs_default,
{
categories,
selectedCategory,
onSelectCategory,
children
}
),
/* @__PURE__ */ (0, import_jsx_runtime186.jsx)(
import_components52.Button,
{
__next40pxDefaultSize: true,
className: "block-editor-inserter__patterns-explore-button",
onClick: () => setShowPatternsExplorer(true),
variant: "secondary",
children: (0, import_i18n57.__)("Explore all patterns")
}
)
] }),
isMobile && /* @__PURE__ */ (0, import_jsx_runtime186.jsx)(MobileTabNavigation, { categories, children: (category) => /* @__PURE__ */ (0, import_jsx_runtime186.jsx)("div", { className: "block-editor-inserter__category-panel", children: /* @__PURE__ */ (0, import_jsx_runtime186.jsx)(
PatternCategoryPreviews,
{
onInsert,
rootClientId,
category
},
category.name
) }) }),
showPatternsExplorer && /* @__PURE__ */ (0, import_jsx_runtime186.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_i18n61 = __toESM(require_i18n(), 1);
var import_compose42 = __toESM(require_compose(), 1);
var import_components57 = __toESM(require_components(), 1);
var import_element75 = __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_i18n60 = __toESM(require_i18n(), 1);
var import_compose41 = __toESM(require_compose(), 1);
// packages/block-editor/build-module/components/inserter/media-tab/media-list.mjs
var import_components54 = __toESM(require_components(), 1);
var import_i18n59 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/inserter/media-tab/media-preview.mjs
var import_components53 = __toESM(require_components(), 1);
var import_i18n58 = __toESM(require_i18n(), 1);
var import_element73 = __toESM(require_element(), 1);
var import_blocks37 = __toESM(require_blocks(), 1);
var import_data57 = __toESM(require_data(), 1);
var import_notices7 = __toESM(require_notices(), 1);
var import_blob2 = __toESM(require_blob(), 1);
var import_url4 = __toESM(require_url(), 1);
// packages/block-editor/build-module/components/inserter/media-tab/utils.mjs
var import_blocks36 = __toESM(require_blocks(), 1);
var import_jsx_runtime187 = __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_runtime187.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_blocks36.createBlock)(`core/${mediaType}`, attributes), preview];
}
// packages/block-editor/build-module/components/inserter/media-tab/media-preview.mjs
var import_jsx_runtime188 = __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 }) {
if (!category.getReportUrl) {
return null;
}
const reportUrl = category.getReportUrl(media);
return /* @__PURE__ */ (0, import_jsx_runtime188.jsx)(
import_components53.DropdownMenu,
{
className: "block-editor-inserter__media-list__item-preview-options",
label: (0, import_i18n58.__)("Options"),
popoverProps: MEDIA_OPTIONS_POPOVER_PROPS,
icon: more_vertical_default,
children: () => /* @__PURE__ */ (0, import_jsx_runtime188.jsx)(import_components53.MenuGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime188.jsx)(
import_components53.MenuItem,
{
onClick: () => window.open(reportUrl, "_blank").focus(),
icon: external_default,
children: (0, import_i18n58.sprintf)(
/* translators: %s: The media type to report e.g: "image", "video", "audio" */
(0, import_i18n58.__)("Report %s"),
category.mediaType
)
}
) })
}
);
}
function InsertExternalImageModal({ onClose, onSubmit }) {
return /* @__PURE__ */ (0, import_jsx_runtime188.jsxs)(
import_components53.Modal,
{
title: (0, import_i18n58.__)("Insert external image"),
onRequestClose: onClose,
className: "block-editor-inserter-media-tab-media-preview-inserter-external-image-modal",
children: [
/* @__PURE__ */ (0, import_jsx_runtime188.jsxs)(import_components53.__experimentalVStack, { spacing: 3, children: [
/* @__PURE__ */ (0, import_jsx_runtime188.jsx)("p", { children: (0, import_i18n58.__)(
"This image cannot be uploaded to your Media Library, but it can still be inserted as an external image."
) }),
/* @__PURE__ */ (0, import_jsx_runtime188.jsx)("p", { children: (0, import_i18n58.__)(
"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_runtime188.jsxs)(
import_components53.Flex,
{
className: "block-editor-block-lock-modal__actions",
justify: "flex-end",
expanded: false,
children: [
/* @__PURE__ */ (0, import_jsx_runtime188.jsx)(import_components53.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime188.jsx)(
import_components53.Button,
{
__next40pxDefaultSize: true,
variant: "tertiary",
onClick: onClose,
children: (0, import_i18n58.__)("Cancel")
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime188.jsx)(import_components53.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime188.jsx)(
import_components53.Button,
{
__next40pxDefaultSize: true,
variant: "primary",
onClick: onSubmit,
children: (0, import_i18n58.__)("Insert")
}
) })
]
}
)
]
}
);
}
function MediaPreview({ media, onClick, category }) {
const [showExternalUploadModal, setShowExternalUploadModal] = (0, import_element73.useState)(false);
const [isHovered, setIsHovered] = (0, import_element73.useState)(false);
const [isInserting, setIsInserting] = (0, import_element73.useState)(false);
const [block, preview] = (0, import_element73.useMemo)(
() => getBlockAndPreviewFromMedia(media, category.mediaType),
[media, category.mediaType]
);
const { createErrorNotice, createSuccessNotice } = (0, import_data57.useDispatch)(import_notices7.store);
const { getSettings: getSettings8, getBlock: getBlock2 } = (0, import_data57.useSelect)(store);
const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data57.useDispatch)(store);
const onMediaInsert = (0, import_element73.useCallback)(
(previewBlock) => {
if (isInserting) {
return;
}
const settings2 = getSettings8();
const clonedBlock = (0, import_blocks37.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_url4.getFilename)(url) || "image.jpg";
const file = new File([blob], fileName, {
type: blob.type
});
settings2.mediaUpload({
filesList: [file],
additionalData: { caption },
onFileChange([img]) {
if ((0, import_blob2.isBlobURL)(img.url)) {
return;
}
if (!getBlock2(clonedBlock.clientId)) {
onClick({
...clonedBlock,
attributes: {
...clonedBlock.attributes,
id: img.id,
url: img.url
}
});
createSuccessNotice(
(0, import_i18n58.__)("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,
getSettings8,
onClick,
createSuccessNotice,
updateBlockAttributes2,
createErrorNotice,
getBlock2
]
);
const title = typeof media.title === "string" ? media.title : media.title?.rendered || (0, import_i18n58.__)("no title");
const onMouseEnter = (0, import_element73.useCallback)(() => setIsHovered(true), []);
const onMouseLeave = (0, import_element73.useCallback)(() => setIsHovered(false), []);
return /* @__PURE__ */ (0, import_jsx_runtime188.jsxs)(import_jsx_runtime188.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime188.jsx)(inserter_draggable_blocks_default, { isEnabled: true, blocks: [block], children: ({ draggable, onDragStart, onDragEnd }) => /* @__PURE__ */ (0, import_jsx_runtime188.jsx)(
"div",
{
className: clsx_default(
"block-editor-inserter__media-list__list-item",
{
"is-hovered": isHovered
}
),
draggable,
onDragStart,
onDragEnd,
children: /* @__PURE__ */ (0, import_jsx_runtime188.jsxs)(
"div",
{
onMouseEnter,
onMouseLeave,
children: [
/* @__PURE__ */ (0, import_jsx_runtime188.jsx)(import_components53.Tooltip, { text: title, children: /* @__PURE__ */ (0, import_jsx_runtime188.jsx)(
import_components53.Composite.Item,
{
render: /* @__PURE__ */ (0, import_jsx_runtime188.jsx)(
"div",
{
"aria-label": title,
role: "option",
className: "block-editor-inserter__media-list__item"
}
),
onClick: () => onMediaInsert(block),
children: /* @__PURE__ */ (0, import_jsx_runtime188.jsxs)("div", { className: "block-editor-inserter__media-list__item-preview", children: [
preview,
isInserting && /* @__PURE__ */ (0, import_jsx_runtime188.jsx)("div", { className: "block-editor-inserter__media-list__item-preview-spinner", children: /* @__PURE__ */ (0, import_jsx_runtime188.jsx)(import_components53.Spinner, {}) })
] })
}
) }),
!isInserting && /* @__PURE__ */ (0, import_jsx_runtime188.jsx)(
MediaPreviewOptions,
{
category,
media
}
)
]
}
)
}
) }),
showExternalUploadModal && /* @__PURE__ */ (0, import_jsx_runtime188.jsx)(
InsertExternalImageModal,
{
onClose: () => setShowExternalUploadModal(false),
onSubmit: () => {
onClick((0, import_blocks37.cloneBlock)(block));
createSuccessNotice((0, import_i18n58.__)("Image inserted."), {
type: "snackbar",
id: "inserter-notice"
});
setShowExternalUploadModal(false);
}
}
)
] });
}
// packages/block-editor/build-module/components/inserter/media-tab/media-list.mjs
var import_jsx_runtime189 = __toESM(require_jsx_runtime(), 1);
function MediaList({
mediaList,
category,
onClick,
label = (0, import_i18n59.__)("Media List")
}) {
return /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
import_components54.Composite,
{
role: "listbox",
className: "block-editor-inserter__media-list",
"aria-label": label,
children: mediaList.map((media, index) => /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
MediaPreview,
{
media,
category,
onClick
},
media.id || media.sourceId || index
))
}
);
}
var media_list_default = MediaList;
// packages/block-editor/build-module/components/inserter/media-tab/hooks.mjs
var import_element74 = __toESM(require_element(), 1);
var import_data58 = __toESM(require_data(), 1);
function useMediaResults(category, query = {}) {
const [mediaList, setMediaList] = (0, import_element74.useState)();
const [isLoading, setIsLoading] = (0, import_element74.useState)(false);
const lastRequestRef = (0, import_element74.useRef)();
(0, import_element74.useEffect)(() => {
(async () => {
const key = JSON.stringify({
category: category.name,
...query
});
lastRequestRef.current = key;
setIsLoading(true);
setMediaList([]);
const _media = await category.fetch?.(query);
if (key === lastRequestRef.current) {
setMediaList(_media);
setIsLoading(false);
}
})();
}, [category.name, ...Object.values(query)]);
return { mediaList, isLoading };
}
function useMediaCategories(rootClientId) {
const [categories, setCategories] = (0, import_element74.useState)([]);
const inserterMediaCategories = (0, import_data58.useSelect)(
(select3) => unlock(select3(store)).getInserterMediaCategories(),
[]
);
const { canInsertImage, canInsertVideo, canInsertAudio } = (0, import_data58.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_element74.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 {
results = await category.fetch({
per_page: 1
});
} catch (e2) {
}
return [category.name, !!results.length];
})
)
);
const canInsertMediaType = {
image: canInsertImage,
video: canInsertVideo,
audio: canInsertAudio
};
inserterMediaCategories.forEach((category) => {
if (canInsertMediaType[category.mediaType] && categoriesHaveMedia.get(category.name)) {
_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_runtime190 = __toESM(require_jsx_runtime(), 1);
var INITIAL_MEDIA_ITEMS_PER_PAGE = 10;
function MediaCategoryPanel({ rootClientId, onInsert, category }) {
const [search, setSearch, debouncedSearch] = (0, import_compose41.useDebouncedInput)();
const { mediaList, isLoading } = useMediaResults(category, {
per_page: !!debouncedSearch ? 20 : INITIAL_MEDIA_ITEMS_PER_PAGE,
search: debouncedSearch
});
const baseCssClass = "block-editor-inserter__media-panel";
const searchLabel = category.labels.search_items || (0, import_i18n60.__)("Search");
return /* @__PURE__ */ (0, import_jsx_runtime190.jsxs)("div", { className: baseCssClass, children: [
/* @__PURE__ */ (0, import_jsx_runtime190.jsx)(
import_components55.SearchControl,
{
className: `${baseCssClass}-search`,
onChange: setSearch,
value: search,
label: searchLabel,
placeholder: searchLabel
}
),
isLoading && /* @__PURE__ */ (0, import_jsx_runtime190.jsx)("div", { className: `${baseCssClass}-spinner`, children: /* @__PURE__ */ (0, import_jsx_runtime190.jsx)(import_components55.Spinner, {}) }),
!isLoading && !mediaList?.length && /* @__PURE__ */ (0, import_jsx_runtime190.jsx)(no_results_default, {}),
!isLoading && !!mediaList?.length && /* @__PURE__ */ (0, import_jsx_runtime190.jsx)(
media_list_default,
{
rootClientId,
onClick: onInsert,
mediaList,
category
}
)
] });
}
// packages/block-editor/build-module/components/media-upload/check.mjs
var import_data59 = __toESM(require_data(), 1);
function MediaUploadCheck({ fallback = null, children }) {
const hasUploadPermissions = (0, import_data59.useSelect)((select3) => {
const { getSettings: getSettings8 } = select3(store);
return !!getSettings8().mediaUpload;
}, []);
return hasUploadPermissions ? children : fallback;
}
var check_default2 = MediaUploadCheck;
// packages/block-editor/build-module/components/media-upload/index.mjs
var import_components56 = __toESM(require_components(), 1);
var MediaUpload = () => null;
var media_upload_default = (0, import_components56.withFilters)("editor.MediaUpload")(MediaUpload);
// packages/block-editor/build-module/components/inserter/media-tab/media-tab.mjs
var import_jsx_runtime191 = __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_compose42.useViewportMatch)("medium", "<");
const baseCssClass = "block-editor-inserter__media-tabs";
const onSelectMedia = (0, import_element75.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_element75.useMemo)(
() => mediaCategories.map((mediaCategory) => ({
...mediaCategory,
label: mediaCategory.labels.name
})),
[mediaCategories]
);
if (!categories.length) {
return /* @__PURE__ */ (0, import_jsx_runtime191.jsx)(no_results_default, {});
}
return /* @__PURE__ */ (0, import_jsx_runtime191.jsxs)(import_jsx_runtime191.Fragment, { children: [
!isMobile && /* @__PURE__ */ (0, import_jsx_runtime191.jsxs)("div", { className: `${baseCssClass}-container`, children: [
/* @__PURE__ */ (0, import_jsx_runtime191.jsx)(
category_tabs_default,
{
categories,
selectedCategory,
onSelectCategory,
children
}
),
/* @__PURE__ */ (0, import_jsx_runtime191.jsx)(check_default2, { children: /* @__PURE__ */ (0, import_jsx_runtime191.jsx)(
media_upload_default,
{
multiple: false,
onSelect: onSelectMedia,
allowedTypes: ALLOWED_MEDIA_TYPES2,
render: ({ open }) => /* @__PURE__ */ (0, import_jsx_runtime191.jsx)(
import_components57.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_i18n61.__)("Open Media Library")
}
)
}
) })
] }),
isMobile && /* @__PURE__ */ (0, import_jsx_runtime191.jsx)(MobileTabNavigation, { categories, children: (category) => /* @__PURE__ */ (0, import_jsx_runtime191.jsx)(
MediaCategoryPanel,
{
onInsert,
rootClientId,
category
}
) })
] });
}
var media_tab_default = MediaTab;
// packages/block-editor/build-module/components/inserter/search-results.mjs
var import_element76 = __toESM(require_element(), 1);
var import_i18n62 = __toESM(require_i18n(), 1);
var import_components59 = __toESM(require_components(), 1);
var import_compose43 = __toESM(require_compose(), 1);
var import_a11y9 = __toESM(require_a11y(), 1);
var import_data60 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/inserter-menu-extension/index.mjs
var import_components58 = __toESM(require_components(), 1);
var { Fill: __unstableInserterMenuExtension, Slot } = (0, import_components58.createSlotFill)(
"__unstableInserterMenuExtension"
);
__unstableInserterMenuExtension.Slot = Slot;
var inserter_menu_extension_default = __unstableInserterMenuExtension;
// packages/block-editor/build-module/components/inserter/search-results.mjs
var import_jsx_runtime192 = __toESM(require_jsx_runtime(), 1);
var INITIAL_INSERTER_RESULTS = 9;
var EMPTY_ARRAY6 = [];
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_compose43.useDebounce)(import_a11y9.speak, 500);
const { prioritizedBlocks } = (0, import_data60.useSelect)(
(select3) => {
const blockListSettings2 = select3(store).getBlockListSettings(rootClientId);
return {
prioritizedBlocks: blockListSettings2?.prioritizedInserterBlocks || EMPTY_ARRAY6
};
},
[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_element76.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_element76.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_element76.useEffect)(() => {
if (!filterValue) {
return;
}
const count = filteredBlockTypes.length + filteredBlockPatterns.length;
const resultsFoundMessage = (0, import_i18n62.sprintf)(
/* translators: %d: number of results. */
(0, import_i18n62._n)("%d result found.", "%d results found.", count),
count
);
debouncedSpeak(resultsFoundMessage);
}, [
filterValue,
debouncedSpeak,
filteredBlockTypes,
filteredBlockPatterns
]);
const currentShownBlockTypes = (0, import_compose43.useAsyncList)(filteredBlockTypes, {
step: INITIAL_INSERTER_RESULTS
});
const hasItems = filteredBlockTypes.length > 0 || filteredBlockPatterns.length > 0;
const blocksUI = !!filteredBlockTypes.length && /* @__PURE__ */ (0, import_jsx_runtime192.jsx)(
panel_default,
{
title: /* @__PURE__ */ (0, import_jsx_runtime192.jsx)(import_components59.VisuallyHidden, { children: (0, import_i18n62.__)("Blocks") }),
children: /* @__PURE__ */ (0, import_jsx_runtime192.jsx)(
block_types_list_default,
{
items: currentShownBlockTypes,
onSelect: onSelectBlockType,
onHover,
label: (0, import_i18n62.__)("Blocks"),
isDraggable
}
)
}
);
const patternsUI = !!filteredBlockPatterns.length && /* @__PURE__ */ (0, import_jsx_runtime192.jsx)(
panel_default,
{
title: /* @__PURE__ */ (0, import_jsx_runtime192.jsx)(import_components59.VisuallyHidden, { children: (0, import_i18n62.__)("Block patterns") }),
children: /* @__PURE__ */ (0, import_jsx_runtime192.jsx)("div", { className: "block-editor-inserter__quick-inserter-patterns", children: /* @__PURE__ */ (0, import_jsx_runtime192.jsx)(
block_patterns_list_default,
{
blockPatterns: filteredBlockPatterns,
onClickPattern,
onHover: onHoverPattern,
isDraggable
}
) })
}
);
return /* @__PURE__ */ (0, import_jsx_runtime192.jsxs)(inserter_listbox_default, { children: [
!showBlockDirectory && !hasItems && /* @__PURE__ */ (0, import_jsx_runtime192.jsx)(no_results_default, {}),
prioritizePatterns ? patternsUI : blocksUI,
!!filteredBlockTypes.length && !!filteredBlockPatterns.length && /* @__PURE__ */ (0, import_jsx_runtime192.jsx)("div", { className: "block-editor-inserter__quick-inserter-separator" }),
prioritizePatterns ? blocksUI : patternsUI,
showBlockDirectory && /* @__PURE__ */ (0, import_jsx_runtime192.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_runtime192.jsx)(no_results_default, {});
}
return null;
}
}
)
] });
}
var search_results_default = InserterSearchResults;
// packages/block-editor/build-module/components/tabbed-sidebar/index.mjs
var import_components60 = __toESM(require_components(), 1);
var import_element77 = __toESM(require_element(), 1);
var import_jsx_runtime193 = __toESM(require_jsx_runtime(), 1);
var { Tabs: Tabs2 } = unlock(import_components60.privateApis);
function TabbedSidebar({ defaultTabId, onClose, onSelect, selectedTab, tabs, closeButtonLabel }, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime193.jsx)("div", { className: "block-editor-tabbed-sidebar", children: /* @__PURE__ */ (0, import_jsx_runtime193.jsxs)(
Tabs2,
{
selectOnMove: false,
defaultTabId,
onSelect,
selectedTabId: selectedTab,
children: [
/* @__PURE__ */ (0, import_jsx_runtime193.jsxs)("div", { className: "block-editor-tabbed-sidebar__tablist-and-close-button", children: [
/* @__PURE__ */ (0, import_jsx_runtime193.jsx)(
import_components60.Button,
{
className: "block-editor-tabbed-sidebar__close-button",
icon: close_small_default,
label: closeButtonLabel,
onClick: () => onClose(),
size: "compact"
}
),
/* @__PURE__ */ (0, import_jsx_runtime193.jsx)(
Tabs2.TabList,
{
className: "block-editor-tabbed-sidebar__tablist",
ref,
children: tabs.map((tab) => /* @__PURE__ */ (0, import_jsx_runtime193.jsx)(
Tabs2.Tab,
{
tabId: tab.name,
className: "block-editor-tabbed-sidebar__tab",
children: tab.title
},
tab.name
))
}
)
] }),
tabs.map((tab) => /* @__PURE__ */ (0, import_jsx_runtime193.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_element77.forwardRef)(TabbedSidebar);
// packages/block-editor/build-module/hooks/use-zoom-out.mjs
var import_data61 = __toESM(require_data(), 1);
var import_element78 = __toESM(require_element(), 1);
function useZoomOut(enabled = true) {
const { setZoomLevel: setZoomLevel2, resetZoomLevel: resetZoomLevel2 } = unlock(
(0, import_data61.useDispatch)(store)
);
const { isZoomedOut, isZoomOut: isZoomOut2 } = (0, import_data61.useSelect)((select3) => {
const { isZoomOut: _isZoomOut } = unlock(select3(store));
return {
isZoomedOut: _isZoomOut(),
isZoomOut: _isZoomOut
};
}, []);
const controlZoomLevelRef = (0, import_element78.useRef)(false);
const isEnabledRef = (0, import_element78.useRef)(enabled);
(0, import_element78.useEffect)(() => {
if (isZoomedOut !== isEnabledRef.current) {
controlZoomLevelRef.current = false;
}
}, [isZoomedOut]);
(0, import_element78.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_runtime194 = __toESM(require_jsx_runtime(), 1);
var NOOP = () => {
};
function InserterMenu({
rootClientId,
clientId,
isAppender,
__experimentalInsertionIndex,
onSelect,
showInserterHelpPanel,
showMostUsedBlocks,
__experimentalFilterValue = "",
shouldFocusBlock = true,
onPatternCategorySelection,
onClose,
__experimentalInitialTab,
__experimentalInitialCategory
}, ref) {
const { isZoomOutMode, hasSectionRootClientId } = (0, import_data62.useSelect)((select3) => {
const { isZoomOut: isZoomOut2, getSectionRootClientId: getSectionRootClientId2 } = unlock(
select3(store)
);
return {
isZoomOutMode: isZoomOut2(),
hasSectionRootClientId: !!getSectionRootClientId2()
};
}, []);
const [filterValue, setFilterValue, delayedFilterValue] = (0, import_compose44.useDebouncedInput)(__experimentalFilterValue);
const [hoveredItem, setHoveredItem] = (0, import_element79.useState)(null);
const [selectedPatternCategory, setSelectedPatternCategory] = (0, import_element79.useState)(
__experimentalInitialCategory
);
const [patternFilter, setPatternFilter] = (0, import_element79.useState)("all");
const [selectedMediaCategory, setSelectedMediaCategory] = (0, import_element79.useState)(null);
const isLargeViewport = (0, import_compose44.useViewportMatch)("large");
const isMobileViewport = (0, import_compose44.useViewportMatch)("medium", "<");
const maybeCloseInserter = isMobileViewport ? onClose : NOOP;
function getInitialTab() {
if (__experimentalInitialTab) {
return __experimentalInitialTab;
}
if (isZoomOutMode) {
return "patterns";
}
return "blocks";
}
const [selectedTab, setSelectedTab] = (0, import_element79.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_element79.useRef)();
const onInsert = (0, import_element79.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_element79.useCallback)(
(blocks2, patternName, ...args) => {
onToggleInsertionPoint(false);
onInsertBlocks(blocks2, { patternName }, ...args);
onSelect();
maybeCloseInserter();
},
[onInsertBlocks, maybeCloseInserter, onSelect, onToggleInsertionPoint]
);
const onHover = (0, import_element79.useCallback)(
(item) => {
onToggleInsertionPoint(item);
setHoveredItem(item);
},
[onToggleInsertionPoint, setHoveredItem]
);
const onClickPatternCategory = (0, import_element79.useCallback)(
(patternCategory, filter) => {
setSelectedPatternCategory(patternCategory);
setPatternFilter(filter);
onPatternCategorySelection?.();
},
[setSelectedPatternCategory, onPatternCategorySelection]
);
const showPatternPanel = selectedTab === "patterns" && !delayedFilterValue && !!selectedPatternCategory;
const showMediaPanel = selectedTab === "media" && !!selectedMediaCategory;
const inserterSearch = (0, import_element79.useMemo)(() => {
if (selectedTab === "media") {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime194.jsxs)(import_jsx_runtime194.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime194.jsx)(
import_components61.SearchControl,
{
className: "block-editor-inserter__search",
onChange: (value) => {
if (hoveredItem) {
setHoveredItem(null);
}
setFilterValue(value);
},
value: filterValue,
label: (0, import_i18n63.__)("Search"),
placeholder: (0, import_i18n63.__)("Search")
}
),
!!delayedFilterValue && /* @__PURE__ */ (0, import_jsx_runtime194.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
]);
const blocksTab = (0, import_element79.useMemo)(() => {
return /* @__PURE__ */ (0, import_jsx_runtime194.jsxs)(import_jsx_runtime194.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime194.jsx)("div", { className: "block-editor-inserter__block-list", children: /* @__PURE__ */ (0, import_jsx_runtime194.jsx)(
block_types_tab_default,
{
ref: blockTypesTabRef,
rootClientId: destinationRootClientId,
onInsert,
onHover,
showMostUsedBlocks
}
) }),
showInserterHelpPanel && /* @__PURE__ */ (0, import_jsx_runtime194.jsxs)("div", { className: "block-editor-inserter__tips", children: [
/* @__PURE__ */ (0, import_jsx_runtime194.jsx)(import_components61.VisuallyHidden, { as: "h2", children: (0, import_i18n63.__)("A tip for using the block editor") }),
/* @__PURE__ */ (0, import_jsx_runtime194.jsx)(tips_default, {})
] })
] });
}, [
destinationRootClientId,
onInsert,
onHover,
showMostUsedBlocks,
showInserterHelpPanel
]);
const patternsTab = (0, import_element79.useMemo)(() => {
return /* @__PURE__ */ (0, import_jsx_runtime194.jsx)(
block_patterns_tab_default,
{
rootClientId: destinationRootClientId,
onInsert: onInsertPattern,
onSelectCategory: onClickPatternCategory,
selectedCategory: selectedPatternCategory,
children: showPatternPanel && /* @__PURE__ */ (0, import_jsx_runtime194.jsx)(
PatternCategoryPreviews,
{
rootClientId: destinationRootClientId,
onInsert: onInsertPattern,
category: selectedPatternCategory,
patternFilter,
showTitlesAsTooltip: true
}
)
}
);
}, [
destinationRootClientId,
onInsertPattern,
onClickPatternCategory,
patternFilter,
selectedPatternCategory,
showPatternPanel
]);
const mediaTab = (0, import_element79.useMemo)(() => {
return /* @__PURE__ */ (0, import_jsx_runtime194.jsx)(
media_tab_default,
{
rootClientId: destinationRootClientId,
selectedCategory: selectedMediaCategory,
onSelectCategory: setSelectedMediaCategory,
onInsert,
children: showMediaPanel && /* @__PURE__ */ (0, import_jsx_runtime194.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_element79.useRef)();
(0, import_element79.useLayoutEffect)(() => {
if (tabsRef.current) {
window.requestAnimationFrame(() => {
tabsRef.current.querySelector('[role="tab"][aria-selected="true"]')?.focus();
});
}
}, []);
return /* @__PURE__ */ (0, import_jsx_runtime194.jsxs)(
"div",
{
className: clsx_default("block-editor-inserter__menu", {
"show-panel": showPatternPanel || showMediaPanel,
"is-zoom-out": isZoomOutMode
}),
ref,
children: [
/* @__PURE__ */ (0, import_jsx_runtime194.jsx)("div", { className: "block-editor-inserter__main-area", children: /* @__PURE__ */ (0, import_jsx_runtime194.jsx)(
tabbed_sidebar_default,
{
ref: tabsRef,
onSelect: handleSetSelectedTab,
onClose,
selectedTab,
closeButtonLabel: (0, import_i18n63.__)("Close Block Inserter"),
tabs: [
{
name: "blocks",
title: (0, import_i18n63.__)("Blocks"),
panel: /* @__PURE__ */ (0, import_jsx_runtime194.jsxs)(import_jsx_runtime194.Fragment, { children: [
inserterSearch,
selectedTab === "blocks" && !delayedFilterValue && blocksTab
] })
},
{
name: "patterns",
title: (0, import_i18n63.__)("Patterns"),
panel: /* @__PURE__ */ (0, import_jsx_runtime194.jsxs)(import_jsx_runtime194.Fragment, { children: [
inserterSearch,
selectedTab === "patterns" && !delayedFilterValue && patternsTab
] })
},
{
name: "media",
title: (0, import_i18n63.__)("Media"),
panel: /* @__PURE__ */ (0, import_jsx_runtime194.jsxs)(import_jsx_runtime194.Fragment, { children: [
inserterSearch,
mediaTab
] })
}
]
}
) }),
showInserterHelpPanel && hoveredItem && /* @__PURE__ */ (0, import_jsx_runtime194.jsx)(
import_components61.Popover,
{
className: "block-editor-inserter__preview-container__popover",
placement: "right-start",
offset: 16,
focusOnMount: false,
animate: false,
children: /* @__PURE__ */ (0, import_jsx_runtime194.jsx)(preview_panel_default, { item: hoveredItem })
}
)
]
}
);
}
var PrivateInserterMenu = (0, import_element79.forwardRef)(InserterMenu);
function PublicInserterMenu(props, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime194.jsx)(
PrivateInserterMenu,
{
...props,
onPatternCategorySelection: NOOP,
ref
}
);
}
var menu_default = (0, import_element79.forwardRef)(PublicInserterMenu);
// packages/block-editor/build-module/components/inserter/quick-inserter.mjs
var import_element80 = __toESM(require_element(), 1);
var import_i18n64 = __toESM(require_i18n(), 1);
var import_components62 = __toESM(require_components(), 1);
var import_data63 = __toESM(require_data(), 1);
var import_jsx_runtime195 = __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_element80.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_data63.useSelect)(
(select3) => {
const { getSettings: getSettings8, getBlockIndex: getBlockIndex2, getBlockCount: getBlockCount2 } = select3(store);
const settings2 = getSettings8();
const index = getBlockIndex2(clientId);
const blockCount = getBlockCount2();
return {
setInserterIsOpened: settings2.__experimentalSetIsInserterOpened,
insertionIndex: index === -1 ? blockCount : index
};
},
[clientId]
);
const showSearch = hasSearch && blockTypes.length > SEARCH_THRESHOLD;
(0, import_element80.useEffect)(() => {
if (setInserterIsOpened) {
setInserterIsOpened(false);
}
}, [setInserterIsOpened]);
const onBrowseAll = () => {
setInserterIsOpened({
filterValue,
onSelect,
rootClientId,
insertionIndex
});
};
return /* @__PURE__ */ (0, import_jsx_runtime195.jsxs)(
"div",
{
className: clsx_default("block-editor-inserter__quick-inserter", {
"has-search": showSearch,
"has-expand": setInserterIsOpened
}),
children: [
showSearch && /* @__PURE__ */ (0, import_jsx_runtime195.jsx)(
import_components62.SearchControl,
{
className: "block-editor-inserter__search",
value: filterValue,
onChange: (value) => {
setFilterValue(value);
},
label: (0, import_i18n64.__)("Search"),
placeholder: (0, import_i18n64.__)("Search")
}
),
/* @__PURE__ */ (0, import_jsx_runtime195.jsx)("div", { className: "block-editor-inserter__quick-inserter-results", children: /* @__PURE__ */ (0, import_jsx_runtime195.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_runtime195.jsx)(
import_components62.Button,
{
__next40pxDefaultSize: true,
className: "block-editor-inserter__quick-inserter-expand",
onClick: onBrowseAll,
"aria-label": (0, import_i18n64.__)(
"Browse all. This will open the main inserter panel in the editor toolbar."
),
children: (0, import_i18n64.__)("Browse all")
}
)
]
}
);
}
// packages/block-editor/build-module/components/inserter/index.mjs
var import_jsx_runtime196 = __toESM(require_jsx_runtime(), 1);
var defaultRenderToggle = ({
onToggle,
disabled,
isOpen,
blockTitle,
hasSingleBlockType,
toggleProps = {}
}) => {
const {
as: Wrapper = import_components63.Button,
label: labelProp,
onClick,
...rest
} = toggleProps;
let label = labelProp;
if (!label && hasSingleBlockType) {
label = (0, import_i18n65.sprintf)(
// translators: %s: the name of the block when there is only one
(0, import_i18n65._x)("Add %s", "directly add the only allowed block"),
blockTitle
);
} else if (!label) {
label = (0, import_i18n65._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_runtime196.jsx)(
Wrapper,
{
__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,
disabled,
...rest
}
);
};
var Inserter = class extends import_element81.Component {
constructor() {
super(...arguments);
this.onToggle = this.onToggle.bind(this);
this.renderToggle = this.renderToggle.bind(this);
this.renderContent = this.renderContent.bind(this);
}
onToggle(isOpen) {
const { onToggle } = this.props;
if (onToggle) {
onToggle(isOpen);
}
}
/**
* Render callback to display Dropdown toggle element.
*
* @param {Object} options
* @param {Function} options.onToggle Callback to invoke when toggle is
* pressed.
* @param {boolean} options.isOpen Whether dropdown is currently open.
*
* @return {Element} Dropdown toggle element.
*/
renderToggle({ onToggle, isOpen }) {
const {
disabled,
blockTitle,
hasSingleBlockType,
directInsertBlock,
toggleProps,
hasItems,
renderToggle: renderToggle3 = defaultRenderToggle
} = this.props;
return renderToggle3({
onToggle,
isOpen,
disabled: disabled || !hasItems,
blockTitle,
hasSingleBlockType,
directInsertBlock,
toggleProps
});
}
/**
* Render callback to display Dropdown content element.
*
* @param {Object} options
* @param {Function} options.onClose Callback to invoke when dropdown is
* closed.
*
* @return {Element} Dropdown content element.
*/
renderContent({ onClose }) {
const {
rootClientId,
clientId,
isAppender,
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,
selectBlockOnInsert
} = this.props;
if (isQuick) {
return /* @__PURE__ */ (0, import_jsx_runtime196.jsx)(
QuickInserter,
{
onSelect: (blocks2) => {
const firstBlock = Array.isArray(blocks2) && blocks2?.length ? blocks2[0] : blocks2;
if (onSelectOrClose && typeof onSelectOrClose === "function") {
onSelectOrClose(firstBlock);
}
onClose();
},
rootClientId,
clientId,
isAppender,
selectBlockOnInsert
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime196.jsx)(
menu_default,
{
onSelect: () => {
onClose();
},
rootClientId,
clientId,
isAppender,
showInserterHelpPanel
}
);
}
render() {
const {
position,
hasSingleBlockType,
directInsertBlock,
insertOnlyAllowedBlock,
__experimentalIsQuick: isQuick,
onSelectOrClose
} = this.props;
if (hasSingleBlockType || directInsertBlock) {
return this.renderToggle({ onToggle: insertOnlyAllowedBlock });
}
return /* @__PURE__ */ (0, import_jsx_runtime196.jsx)(
import_components63.Dropdown,
{
className: "block-editor-inserter",
contentClassName: clsx_default("block-editor-inserter__popover", {
"is-quick": isQuick
}),
popoverProps: { position, shift: true },
onToggle: this.onToggle,
expandOnMobile: true,
headerTitle: (0, import_i18n65.__)("Add a block"),
renderToggle: this.renderToggle,
renderContent: this.renderContent,
onClose: onSelectOrClose
}
);
}
};
var inserter_default = (0, import_compose45.compose)([
(0, import_data64.withSelect)(
(select3, { clientId, rootClientId, shouldDirectInsert = true }) => {
const {
getBlockRootClientId: getBlockRootClientId2,
hasInserterItems: hasInserterItems2,
getAllowedBlocks: getAllowedBlocks2,
getDirectInsertBlock: getDirectInsertBlock2
} = select3(store);
const { getBlockVariations: getBlockVariations2 } = select3(import_blocks38.store);
rootClientId = rootClientId || getBlockRootClientId2(clientId) || void 0;
const allowedBlocks = getAllowedBlocks2(rootClientId);
const directInsertBlock = shouldDirectInsert && getDirectInsertBlock2(rootClientId);
const hasSingleBlockType = allowedBlocks?.length === 1 && getBlockVariations2(allowedBlocks[0].name, "inserter")?.length === 0;
let allowedBlockType = false;
if (hasSingleBlockType) {
allowedBlockType = allowedBlocks[0];
}
return {
hasItems: hasInserterItems2(rootClientId),
hasSingleBlockType,
blockTitle: allowedBlockType ? allowedBlockType.title : "",
allowedBlockType,
directInsertBlock,
rootClientId
};
}
),
(0, import_data64.withDispatch)((dispatch, ownProps, { select: select3 }) => {
return {
insertOnlyAllowedBlock() {
const {
rootClientId,
clientId,
isAppender,
hasSingleBlockType,
allowedBlockType,
directInsertBlock,
onSelectOrClose,
selectBlockOnInsert
} = ownProps;
if (!hasSingleBlockType && !directInsertBlock) {
return;
}
function getAdjacentBlockAttributes(attributesToCopy) {
const { getBlock: getBlock2, getPreviousBlockClientId: getPreviousBlockClientId2 } = select3(store);
if (!attributesToCopy || !clientId && !rootClientId) {
return {};
}
const result = {};
let adjacentAttributes = {};
if (!clientId) {
const parentBlock = getBlock2(rootClientId);
if (parentBlock?.innerBlocks?.length) {
const lastInnerBlock = parentBlock.innerBlocks[parentBlock.innerBlocks.length - 1];
if (directInsertBlock && directInsertBlock?.name === lastInnerBlock.name) {
adjacentAttributes = lastInnerBlock.attributes;
}
}
} else {
const currentBlock = getBlock2(clientId);
const previousBlock = getBlock2(
getPreviousBlockClientId2(clientId)
);
if (currentBlock?.name === previousBlock?.name) {
adjacentAttributes = previousBlock?.attributes || {};
}
}
attributesToCopy.forEach((attribute) => {
if (adjacentAttributes.hasOwnProperty(attribute)) {
result[attribute] = adjacentAttributes[attribute];
}
});
return result;
}
function getInsertionIndex() {
const {
getBlockIndex: getBlockIndex2,
getBlockSelectionEnd: getBlockSelectionEnd2,
getBlockOrder: getBlockOrder2,
getBlockRootClientId: getBlockRootClientId2
} = select3(store);
if (clientId) {
return getBlockIndex2(clientId);
}
const end = getBlockSelectionEnd2();
if (!isAppender && end && getBlockRootClientId2(end) === rootClientId) {
return getBlockIndex2(end) + 1;
}
return getBlockOrder2(rootClientId).length;
}
const { insertBlock: insertBlock2 } = dispatch(store);
let blockToInsert;
if (directInsertBlock) {
const newAttributes = getAdjacentBlockAttributes(
directInsertBlock.attributesToCopy
);
blockToInsert = (0, import_blocks38.createBlock)(directInsertBlock.name, {
...directInsertBlock.attributes || {},
...newAttributes
});
} else {
blockToInsert = (0, import_blocks38.createBlock)(allowedBlockType.name);
}
insertBlock2(
blockToInsert,
getInsertionIndex(),
rootClientId,
selectBlockOnInsert
);
if (onSelectOrClose) {
onSelectOrClose(blockToInsert);
}
const message2 = (0, import_i18n65.sprintf)(
// translators: %s: the name of the block that has been added
(0, import_i18n65.__)("%s block added"),
allowedBlockType.title
);
(0, import_a11y10.speak)(message2);
}
};
}),
// The global inserter should always be visible, we are using ( ! isAppender && ! rootClientId && ! clientId ) as
// a way to detect the global Inserter.
(0, import_compose45.ifCondition)(
({ hasItems, isAppender, rootClientId, clientId }) => hasItems || !isAppender && !rootClientId && !clientId
)
])(Inserter);
// packages/block-editor/build-module/components/default-block-appender/index.mjs
var import_jsx_runtime197 = __toESM(require_jsx_runtime(), 1);
var ZWNBSP = "\uFEFF";
function DefaultBlockAppender({ rootClientId }) {
const { showPrompt, isLocked, placeholder, isManualGrid } = (0, import_data65.useSelect)(
(select3) => {
const {
getBlockCount: getBlockCount2,
getSettings: getSettings8,
getTemplateLock: getTemplateLock2,
getBlockAttributes: getBlockAttributes3
} = select3(store);
const isEmpty4 = !getBlockCount2(rootClientId);
const { bodyPlaceholder } = getSettings8();
return {
showPrompt: isEmpty4,
isLocked: !!getTemplateLock2(rootClientId),
placeholder: bodyPlaceholder,
isManualGrid: getBlockAttributes3(rootClientId)?.layout?.isManualPlacement
};
},
[rootClientId]
);
const { insertDefaultBlock: insertDefaultBlock2, startTyping: startTyping2 } = (0, import_data65.useDispatch)(store);
if (isLocked || isManualGrid) {
return null;
}
const value = (0, import_html_entities2.decodeEntities)(placeholder) || (0, import_i18n66.__)("Type / to choose a block");
const onAppend = () => {
insertDefaultBlock2(void 0, rootClientId);
startTyping2();
};
return /* @__PURE__ */ (0, import_jsx_runtime197.jsxs)(
"div",
{
"data-root-client-id": rootClientId || "",
className: clsx_default("block-editor-default-block-appender", {
"has-visible-prompt": showPrompt
}),
children: [
/* @__PURE__ */ (0, import_jsx_runtime197.jsx)(
"p",
{
tabIndex: "0",
role: "button",
"aria-label": (0, import_i18n66.__)("Add default block"),
className: "block-editor-default-block-appender__content",
onKeyDown: (event) => {
if (import_keycodes7.ENTER === event.keyCode || import_keycodes7.SPACE === event.keyCode) {
onAppend();
}
},
onClick: () => onAppend(),
onFocus: () => {
if (showPrompt) {
onAppend();
}
},
children: showPrompt ? value : ZWNBSP
}
),
/* @__PURE__ */ (0, import_jsx_runtime197.jsx)(
inserter_default,
{
rootClientId,
position: "bottom right",
isAppender: true,
__experimentalIsQuick: true
}
)
]
}
);
}
// packages/block-editor/build-module/components/button-block-appender/index.mjs
var import_components64 = __toESM(require_components(), 1);
var import_element82 = __toESM(require_element(), 1);
var import_i18n67 = __toESM(require_i18n(), 1);
var import_deprecated8 = __toESM(require_deprecated(), 1);
var import_jsx_runtime198 = __toESM(require_jsx_runtime(), 1);
function ButtonBlockAppender({ rootClientId, className, onFocus, tabIndex, onSelect }, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime198.jsx)(
inserter_default,
{
position: "bottom center",
rootClientId,
__experimentalIsQuick: true,
onSelectOrClose: (...args) => {
if (onSelect && typeof onSelect === "function") {
onSelect(...args);
}
},
renderToggle: ({
onToggle,
disabled,
isOpen,
blockTitle,
hasSingleBlockType
}) => {
const isToggleButton = !hasSingleBlockType;
const label = hasSingleBlockType ? (0, import_i18n67.sprintf)(
// translators: %s: the name of the block when there is only one
(0, import_i18n67._x)(
"Add %s",
"directly add the only allowed block"
),
blockTitle
) : (0, import_i18n67._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_runtime198.jsx)(
import_components64.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,
label,
showTooltip: true,
children: /* @__PURE__ */ (0, import_jsx_runtime198.jsx)(icon_default, { icon: plus_default })
}
)
);
},
isAppender: true
}
);
}
var ButtonBlockerAppender = (0, import_element82.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_element82.forwardRef)(ButtonBlockAppender);
// packages/block-editor/build-module/components/block-list-appender/index.mjs
var import_jsx_runtime199 = __toESM(require_jsx_runtime(), 1);
function DefaultAppender({ rootClientId }) {
const canInsertDefaultBlock = (0, import_data66.useSelect)(
(select3) => select3(store).canInsertBlockType(
(0, import_blocks39.getDefaultBlockName)(),
rootClientId
)
);
if (canInsertDefaultBlock) {
return /* @__PURE__ */ (0, import_jsx_runtime199.jsx)(DefaultBlockAppender, { rootClientId });
}
return /* @__PURE__ */ (0, import_jsx_runtime199.jsx)(
button_block_appender_default,
{
rootClientId,
className: "block-list-appender__toggle"
}
);
}
function BlockListAppender({
rootClientId,
CustomAppender,
className,
tagName: TagName = "div"
}) {
const isDragOver = (0, import_data66.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_runtime199.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_runtime199.jsx)(CustomAppender, {}) : /* @__PURE__ */ (0, import_jsx_runtime199.jsx)(DefaultAppender, { rootClientId })
}
);
}
// packages/block-editor/build-module/components/block-list/use-in-between-inserter.mjs
var import_compose50 = __toESM(require_compose(), 1);
var import_data70 = __toESM(require_data(), 1);
var import_element87 = __toESM(require_element(), 1);
var import_i18n69 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/block-tools/insertion-point.mjs
var import_data69 = __toESM(require_data(), 1);
var import_element86 = __toESM(require_element(), 1);
var import_components68 = __toESM(require_components(), 1);
var import_compose49 = __toESM(require_compose(), 1);
// packages/block-editor/build-module/components/block-popover/inbetween.mjs
var import_data67 = __toESM(require_data(), 1);
var import_element83 = __toESM(require_element(), 1);
var import_components65 = __toESM(require_components(), 1);
var import_i18n68 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/block-popover/use-popover-scroll.mjs
var import_compose46 = __toESM(require_compose(), 1);
var import_dom20 = __toESM(require_dom(), 1);
var scrollContainerCache = /* @__PURE__ */ new WeakMap();
function usePopoverScroll(contentRef) {
const effect = (0, import_compose46.useRefEffect)(
(node) => {
function onWheel(event) {
const { deltaX, deltaY, target } = event;
const contentEl = contentRef.current;
let scrollContainer = scrollContainerCache.get(contentEl);
if (!scrollContainer) {
scrollContainer = (0, import_dom20.getScrollContainer)(contentEl);
scrollContainerCache.set(contentEl, scrollContainer);
}
const eventScrollContainer = (0, import_dom20.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_runtime200 = __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_element83.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_data67.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_element83.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_i18n68.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_element83.useLayoutEffect)(() => {
if (!previousElement) {
return;
}
const observer = new window.MutationObserver(forcePopoverRecompute);
observer.observe(previousElement, { attributes: true });
return () => {
observer.disconnect();
};
}, [previousElement]);
(0, import_element83.useLayoutEffect)(() => {
if (!nextElement) {
return;
}
const observer = new window.MutationObserver(forcePopoverRecompute);
observer.observe(nextElement, { attributes: true });
return () => {
observer.disconnect();
};
}, [nextElement]);
(0, import_element83.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_runtime200.jsx)(
import_components65.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_runtime200.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_data68 = __toESM(require_data(), 1);
var import_compose48 = __toESM(require_compose(), 1);
var import_components67 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/block-popover/cover.mjs
var import_element85 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/block-popover/index.mjs
var import_compose47 = __toESM(require_compose(), 1);
var import_components66 = __toESM(require_components(), 1);
var import_element84 = __toESM(require_element(), 1);
var import_jsx_runtime201 = __toESM(require_jsx_runtime(), 1);
var MAX_POPOVER_RECOMPUTE_COUNTER2 = Number.MAX_SAFE_INTEGER;
function BlockPopover({
clientId,
bottomClientId,
children,
__unstablePopoverSlot,
__unstableContentRef,
shift = true,
...props
}, ref) {
const selectedElement = useBlockElement(clientId);
const lastSelectedElement = useBlockElement(bottomClientId ?? clientId);
const mergedRefs = (0, import_compose47.useMergeRefs)([
ref,
use_popover_scroll_default(__unstableContentRef)
]);
const [
popoverDimensionsRecomputeCounter,
forceRecomputePopoverDimensions
] = (0, import_element84.useReducer)(
// Module is there to make sure that the counter doesn't overflow.
(s2) => (s2 + 1) % MAX_POPOVER_RECOMPUTE_COUNTER2,
0
);
(0, import_element84.useLayoutEffect)(() => {
if (!selectedElement) {
return;
}
const observer = new window.MutationObserver(
forceRecomputePopoverDimensions
);
observer.observe(selectedElement, { attributes: true });
return () => {
observer.disconnect();
};
}, [selectedElement]);
const popoverAnchor = (0, import_element84.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_runtime201.jsx)(
import_components66.Popover,
{
ref: mergedRefs,
animate: false,
focusOnMount: false,
anchor: popoverAnchor,
__unstableSlotName: __unstablePopoverSlot,
inline: !__unstablePopoverSlot,
placement: "top-start",
resize: false,
flip: false,
shift,
...props,
className: clsx_default("block-editor-block-popover", props.className),
variant: "unstyled",
children
}
);
}
var PrivateBlockPopover = (0, import_element84.forwardRef)(BlockPopover);
var PublicBlockPopover = ({ clientId, bottomClientId, children, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime201.jsx)(
PrivateBlockPopover,
{
...props,
bottomClientId,
clientId,
__unstableContentRef: void 0,
__unstablePopoverSlot: void 0,
ref,
children
}
);
var block_popover_default = (0, import_element84.forwardRef)(PublicBlockPopover);
// packages/block-editor/build-module/components/block-popover/cover.mjs
var import_jsx_runtime202 = __toESM(require_jsx_runtime(), 1);
function BlockPopoverCover({
clientId,
bottomClientId,
children,
shift = false,
additionalStyles,
...props
}, ref) {
bottomClientId ??= clientId;
const selectedElement = useBlockElement(clientId);
return /* @__PURE__ */ (0, import_jsx_runtime202.jsx)(
PrivateBlockPopover,
{
ref,
clientId,
bottomClientId,
shift,
...props,
children: selectedElement && clientId === bottomClientId ? /* @__PURE__ */ (0, import_jsx_runtime202.jsx)(
CoverContainer,
{
selectedElement,
additionalStyles,
children
}
) : children
}
);
}
function CoverContainer({
selectedElement,
additionalStyles = {},
children
}) {
const [width, setWidth] = (0, import_element85.useState)(selectedElement.offsetWidth);
const [height, setHeight] = (0, import_element85.useState)(selectedElement.offsetHeight);
(0, import_element85.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_element85.useMemo)(() => {
return {
position: "absolute",
width,
height,
...additionalStyles
};
}, [width, height, additionalStyles]);
return /* @__PURE__ */ (0, import_jsx_runtime202.jsx)("div", { style, children });
}
var cover_default = (0, import_element85.forwardRef)(BlockPopoverCover);
// packages/block-editor/build-module/components/block-popover/drop-zone.mjs
var import_jsx_runtime203 = __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_data68.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_compose48.useReducedMotion)();
return /* @__PURE__ */ (0, import_jsx_runtime203.jsx)(
cover_default,
{
clientId,
__unstablePopoverSlot,
__unstableContentRef,
className: "block-editor-block-popover__drop-zone",
children: /* @__PURE__ */ (0, import_jsx_runtime203.jsx)(
import_components67.__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_runtime204 = __toESM(require_jsx_runtime(), 1);
var InsertionPointOpenRef = (0, import_element86.createContext)();
InsertionPointOpenRef.displayName = "InsertionPointOpenRefContext";
function InbetweenInsertionPointPopover({
__unstablePopoverSlot,
__unstableContentRef,
operation = "insert",
nearestSide = "right"
}) {
const { selectBlock: selectBlock2, hideInsertionPoint: hideInsertionPoint2 } = (0, import_data69.useDispatch)(store);
const openRef = (0, import_element86.useContext)(InsertionPointOpenRef);
const ref = (0, import_element86.useRef)();
const {
orientation,
previousClientId,
nextClientId,
rootClientId,
isInserterShown,
isDistractionFree,
isZoomOutMode
} = (0, import_data69.useSelect)((select3) => {
const {
getBlockOrder: getBlockOrder2,
getBlockListSettings: getBlockListSettings2,
getBlockInsertionPoint: getBlockInsertionPoint2,
isBlockBeingDragged: isBlockBeingDragged2,
getPreviousBlockClientId: getPreviousBlockClientId2,
getNextBlockClientId: getNextBlockClientId2,
getSettings: getSettings8,
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 = getSettings8();
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_data69.useSelect)(store);
const disableMotion = (0, import_compose49.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_element86.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_runtime204.jsx)(
inbetween_default,
{
previousClientId,
nextClientId,
__unstablePopoverSlot,
__unstableContentRef,
operation,
nearestSide,
children: /* @__PURE__ */ (0, import_jsx_runtime204.jsxs)(
import_components68.__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_runtime204.jsx)(
import_components68.__unstableMotion.div,
{
variants: lineVariants,
className: "block-editor-block-list__insertion-point-indicator",
"data-testid": "block-list-insertion-point-indicator"
}
),
isInserterShown && /* @__PURE__ */ (0, import_jsx_runtime204.jsx)(
import_components68.__unstableMotion.div,
{
variants: inserterVariants,
className: clsx_default(
"block-editor-block-list__insertion-point-inserter"
),
children: /* @__PURE__ */ (0, import_jsx_runtime204.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_data69.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_runtime204.jsx)(
drop_zone_default,
{
...props
},
`${insertionPoint2.rootClientId}-${insertionPoint2.index}`
) : /* @__PURE__ */ (0, import_jsx_runtime204.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_element87.useContext)(InsertionPointOpenRef);
const isInBetweenInserterDisabled = (0, import_data70.useSelect)(
(select3) => select3(store).getSettings().isDistractionFree || unlock(select3(store)).isZoomOut(),
[]
);
const {
getBlockListSettings: getBlockListSettings2,
getBlockIndex: getBlockIndex2,
isMultiSelecting: isMultiSelecting3,
getSelectedBlockClientIds: getSelectedBlockClientIds2,
getSettings: getSettings8,
getTemplateLock: getTemplateLock2,
__unstableIsWithinBlockOverlay: __unstableIsWithinBlockOverlay2,
getBlockEditingMode: getBlockEditingMode2,
getBlockName: getBlockName2,
getBlockAttributes: getBlockAttributes3,
getParentSectionBlock: getParentSectionBlock2
} = unlock((0, import_data70.useSelect)(store));
const { showInsertionPoint: showInsertionPoint2, hideInsertionPoint: hideInsertionPoint2 } = (0, import_data70.useDispatch)(store);
return (0, import_compose50.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_i18n69.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 && !getSettings8().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 index = getBlockIndex2(clientId);
if (index === 0) {
hideInsertionPoint2();
return;
}
showInsertionPoint2(rootClientId, index, {
__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_data71 = __toESM(require_data(), 1);
var import_compose51 = __toESM(require_compose(), 1);
var import_jsx_runtime205 = __toESM(require_jsx_runtime(), 1);
function useBlockSelectionClearer() {
const { getSettings: getSettings8, hasSelectedBlock: hasSelectedBlock2, hasMultiSelection: hasMultiSelection2 } = (0, import_data71.useSelect)(store);
const { clearSelectedBlock: clearSelectedBlock2 } = (0, import_data71.useDispatch)(store);
const { clearBlockSelection: isEnabled } = getSettings8();
return (0, import_compose51.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_runtime205.jsx)("div", { ref: useBlockSelectionClearer(), ...props });
}
// packages/block-editor/build-module/components/inner-blocks/index.mjs
var import_compose53 = __toESM(require_compose(), 1);
var import_element92 = __toESM(require_element(), 1);
var import_data77 = __toESM(require_data(), 1);
var import_blocks44 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/components/inner-blocks/button-block-appender.mjs
var import_jsx_runtime206 = __toESM(require_jsx_runtime(), 1);
function ButtonBlockAppender2({
showSeparator,
isFloating,
onAddBlock,
isToggle
}) {
const { clientId } = useBlockEditContext();
return /* @__PURE__ */ (0, import_jsx_runtime206.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_runtime207 = __toESM(require_jsx_runtime(), 1);
function DefaultBlockAppender2() {
const { clientId } = useBlockEditContext();
return /* @__PURE__ */ (0, import_jsx_runtime207.jsx)(DefaultBlockAppender, { rootClientId: clientId });
}
// packages/block-editor/build-module/components/inner-blocks/use-nested-settings-update.mjs
var import_element88 = __toESM(require_element(), 1);
var import_data72 = __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 [memo11] = (0, import_element88.useState)(createShallowMemo);
return memo11(value);
}
function useNestedSettingsUpdate(clientId, parentLock, allowedBlocks, prioritizedInserterBlocks, defaultBlock, directInsert, __experimentalDefaultBlock, __experimentalDirectInsert, templateLock, captureToolbars, orientation, layout) {
const registry = (0, import_data72.useRegistry)();
const _allowedBlocks = useShallowMemo(allowedBlocks);
const _prioritizedInserterBlocks = useShallowMemo(
prioritizedInserterBlocks
);
const _templateLock = templateLock === void 0 || parentLock === "contentOnly" ? parentLock : templateLock;
(0, import_element88.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_element89 = __toESM(require_element(), 1);
var import_data73 = __toESM(require_data(), 1);
var import_blocks40 = __toESM(require_blocks(), 1);
function useInnerBlockTemplateSync(clientId, template2, templateLock, templateInsertUpdatesSelection) {
const registry = (0, import_data73.useRegistry)();
const existingTemplateRef = (0, import_element89.useRef)(null);
(0, import_element89.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_blocks40.synchronizeBlocksWithTemplate)(
currentInnerBlocks,
template2
);
if (!(0, import_es64.default)(nextBlocks, currentInnerBlocks)) {
__unstableMarkNextChangeAsNotPersistent2();
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_blocks41 = __toESM(require_blocks(), 1);
var import_data74 = __toESM(require_data(), 1);
function useBlockContext(clientId) {
return (0, import_data74.useSelect)(
(select3) => {
const block = select3(store).getBlock(clientId);
if (!block) {
return void 0;
}
const blockType = select3(import_blocks41.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_data76 = __toESM(require_data(), 1);
var import_element91 = __toESM(require_element(), 1);
var import_compose52 = __toESM(require_compose(), 1);
var import_i18n70 = __toESM(require_i18n(), 1);
var import_blocks43 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/components/use-on-block-drop/index.mjs
var import_element90 = __toESM(require_element(), 1);
var import_blocks42 = __toESM(require_blocks(), 1);
var import_data75 = __toESM(require_data(), 1);
var import_dom22 = __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 (err) {
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_blocks42.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, getSettings8, updateBlockAttributes2, canInsertBlockType2, insertOrReplaceBlocks) {
return (files) => {
if (!getSettings8().mediaUpload) {
return;
}
const transformation = (0, import_blocks42.findTransform)(
(0, import_blocks42.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_blocks42.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: getSettings8,
getBlock: getBlock2
} = (0, import_data75.useSelect)(store);
const { getGroupingBlockName } = (0, import_data75.useSelect)(import_blocks42.store);
const {
insertBlocks: insertBlocks2,
moveBlocksToPosition: moveBlocksToPosition2,
updateBlockAttributes: updateBlockAttributes2,
clearSelectedBlock: clearSelectedBlock2,
replaceBlocks: replaceBlocks2,
removeBlocks: removeBlocks2
} = (0, import_data75.useDispatch)(store);
const registry = (0, import_data75.useRegistry)();
const insertOrReplaceBlocks = (0, import_element90.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) => {
return (0, import_blocks42.createBlock)(
block.name,
block.attributes,
block.innerBlocks
);
});
const areAllImages = blocks2.every((block) => {
return block.name === "core/image";
});
const galleryBlock = canInsertBlockType2(
"core/gallery",
targetRootClientId
);
const wrappedBlocks = (0, import_blocks42.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_element90.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,
getSettings8,
updateBlockAttributes2,
canInsertBlockType2,
insertOrReplaceBlocks
);
const _onHTMLDrop = onHTMLDrop(insertOrReplaceBlocks);
return (event) => {
const files = (0, import_dom22.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_i18n70.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,
blockIndex,
blockOrientation
}) => {
const rect = getBoundingClientRect();
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(getBlockType24, 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) => getBlockType24(name)
);
const targetMatchesDraggedBlockParents = draggedBlockTypes.every(
(block) => {
const [allowedParentName] = block?.parent || [];
if (!allowedParentName) {
return true;
}
return allowedParentName === targetBlockName;
}
);
return areBlocksAllowed && targetMatchesDraggedBlockParents;
}
function isInsertionPoint(targetToCheck, ownerDocument) {
const { defaultView } = ownerDocument;
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_data76.useRegistry)();
const [dropTarget, setDropTarget] = (0, import_element91.useState)({
index: null,
operation: "insert"
});
const { getBlockType: getBlockType24, getBlockVariations: getBlockVariations2, getGroupingBlockName } = (0, import_data76.useSelect)(import_blocks43.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_data76.useSelect)(store));
const {
showInsertionPoint: showInsertionPoint2,
hideInsertionPoint: hideInsertionPoint2,
startDragging: startDragging2,
stopDragging: stopDragging2
} = unlock((0, import_data76.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_compose52.useThrottle)(
(0, import_element91.useCallback)(
(event, ownerDocument) => {
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(
getBlockType24,
allowedBlocks,
draggedBlockNames,
targetBlockName
);
if (!isBlockDroppingAllowed) {
return;
}
const sectionRootClientId = getSectionRootClientId2();
if (isZoomOut2() && sectionRootClientId !== targetRootClientId) {
return;
}
const blocks2 = getBlocks2(targetRootClientId).filter((block) => {
return !((0, import_blocks43.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_blocks43.isUnmodifiedDefaultBlock)(block),
getBoundingClientRect: () => {
const blockElement = ownerDocument.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,
getBlockType24,
getSectionRootClientId2,
isZoomOut2,
getBlocks2,
getBlockListSettings2,
dropZoneElement,
parentBlockClientId,
getBlockIndex2,
registry,
startDragging2,
showInsertionPoint2,
canInsertBlockType2,
isGroupable2,
getBlockVariations2,
getGroupingBlockName
]
),
200
);
return (0, import_compose52.__experimentalUseDropZone)({
dropZoneElement,
isDisabled,
onDrop: onBlockDrop2,
onDragOver(event) {
throttled(event, event.currentTarget.ownerDocument);
},
onDragLeave(event) {
const { ownerDocument } = event.currentTarget;
if (isInsertionPoint(event.relatedTarget, ownerDocument) || isInsertionPoint(event.target, ownerDocument)) {
return;
}
throttled.cancel();
hideInsertionPoint2();
},
onDragEnd() {
throttled.cancel();
stopDragging2();
hideInsertionPoint2();
}
});
}
// packages/block-editor/build-module/components/inner-blocks/index.mjs
var import_jsx_runtime208 = __toESM(require_jsx_runtime(), 1);
var EMPTY_OBJECT = {};
function BlockContext({ children, clientId }) {
const context = useBlockContext(clientId);
return /* @__PURE__ */ (0, import_jsx_runtime208.jsx)(BlockContextProvider, { value: context, children });
}
var BlockListItemsMemo = (0, import_element92.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_blocks44.getBlockSupport)(name, "layout") || (0, import_blocks44.getBlockSupport)(name, "__experimentalLayout") || EMPTY_OBJECT;
const { allowSizingOnChildren = false } = defaultLayoutBlockSupport;
const usedLayout = layout || defaultLayoutBlockSupport;
const memoedLayout = (0, import_element92.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_runtime208.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_runtime208.jsx)(BlockContext, { clientId, children: items });
}
function ControlledInnerBlocks(props) {
useBlockSync(props);
return /* @__PURE__ */ (0, import_jsx_runtime208.jsx)(UncontrolledInnerBlocks, { ...props });
}
var ForwardedInnerBlocks = (0, import_element92.forwardRef)((props, ref) => {
const innerBlocksProps = useInnerBlocksProps({ ref }, props);
return /* @__PURE__ */ (0, import_jsx_runtime208.jsx)("div", { className: "block-editor-inner-blocks", children: /* @__PURE__ */ (0, import_jsx_runtime208.jsx)("div", { ...innerBlocksProps }) });
});
function useInnerBlocksProps(props = {}, options = {}) {
const {
__unstableDisableLayoutClassNames,
__unstableDisableDropZone,
dropZoneElement
} = options;
const {
clientId,
layout = null,
__unstableLayoutClassNames: layoutClassNames = ""
} = useBlockEditContext();
const selected = (0, import_data77.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: hasBlockSupport47, getBlockType: getBlockType24 } = select3(import_blocks44.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: hasBlockSupport47(
blockName,
"__experimentalExposeControlsToChildren",
false
),
name: blockName,
blockType: getBlockType24(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_compose53.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_runtime208.jsx)(InnerBlocks, { ...innerBlocksProps, clientId }) : /* @__PURE__ */ (0, import_jsx_runtime208.jsx)(BlockListItems, { ...options })
};
}
useInnerBlocksProps.save = import_blocks44.__unstableGetInnerBlocksProps;
ForwardedInnerBlocks.DefaultBlockAppender = DefaultBlockAppender2;
ForwardedInnerBlocks.ButtonBlockAppender = ButtonBlockAppender2;
ForwardedInnerBlocks.Content = () => useInnerBlocksProps.save().children;
var inner_blocks_default = ForwardedInnerBlocks;
// packages/block-editor/build-module/components/observe-typing/index.mjs
var import_compose54 = __toESM(require_compose(), 1);
var import_data78 = __toESM(require_data(), 1);
var import_dom23 = __toESM(require_dom(), 1);
var import_keycodes8 = __toESM(require_keycodes(), 1);
var import_jsx_runtime209 = __toESM(require_jsx_runtime(), 1);
var KEY_DOWN_ELIGIBLE_KEY_CODES = /* @__PURE__ */ new Set([
import_keycodes8.UP,
import_keycodes8.RIGHT,
import_keycodes8.DOWN,
import_keycodes8.LEFT,
import_keycodes8.ENTER,
import_keycodes8.BACKSPACE
]);
function isKeyDownEligibleForStartTyping(event) {
const { keyCode, shiftKey } = event;
return !shiftKey && KEY_DOWN_ELIGIBLE_KEY_CODES.has(keyCode);
}
function useMouseMoveTypingReset() {
const isTyping3 = (0, import_data78.useSelect)(
(select3) => select3(store).isTyping(),
[]
);
const { stopTyping: stopTyping2 } = (0, import_data78.useDispatch)(store);
return (0, import_compose54.useRefEffect)(
(node) => {
if (!isTyping3) {
return;
}
const { ownerDocument } = node;
let lastClientX;
let lastClientY;
function stopTypingOnMouseMove(event) {
const { clientX, clientY } = event;
if (lastClientX && lastClientY && (lastClientX !== clientX || lastClientY !== clientY)) {
stopTyping2();
}
lastClientX = clientX;
lastClientY = clientY;
}
ownerDocument.addEventListener(
"mousemove",
stopTypingOnMouseMove
);
return () => {
ownerDocument.removeEventListener(
"mousemove",
stopTypingOnMouseMove
);
};
},
[isTyping3, stopTyping2]
);
}
function useTypingObserver() {
const { isTyping: isTyping3 } = (0, import_data78.useSelect)((select3) => {
const { isTyping: _isTyping } = select3(store);
return {
isTyping: _isTyping()
};
}, []);
const { startTyping: startTyping2, stopTyping: stopTyping2 } = (0, import_data78.useDispatch)(store);
const ref1 = useMouseMoveTypingReset();
const ref2 = (0, import_compose54.useRefEffect)(
(node) => {
const { ownerDocument } = node;
const { defaultView } = ownerDocument;
const selection2 = defaultView.getSelection();
if (isTyping3) {
let stopTypingOnNonTextField2 = function(event) {
const { target } = event;
timerId = defaultView.setTimeout(() => {
if (!(0, import_dom23.isTextField)(target)) {
stopTyping2();
}
});
}, stopTypingOnEscapeKey2 = function(event) {
const { keyCode } = event;
if (keyCode === import_keycodes8.ESCAPE || keyCode === import_keycodes8.TAB) {
stopTyping2();
}
}, stopTypingOnSelectionUncollapse2 = function() {
if (!selection2.isCollapsed) {
stopTyping2();
}
};
var stopTypingOnNonTextField = stopTypingOnNonTextField2, stopTypingOnEscapeKey = stopTypingOnEscapeKey2, stopTypingOnSelectionUncollapse = stopTypingOnSelectionUncollapse2;
let timerId;
node.addEventListener("focus", stopTypingOnNonTextField2);
node.addEventListener("keydown", stopTypingOnEscapeKey2);
ownerDocument.addEventListener(
"selectionchange",
stopTypingOnSelectionUncollapse2
);
return () => {
defaultView.clearTimeout(timerId);
node.removeEventListener(
"focus",
stopTypingOnNonTextField2
);
node.removeEventListener(
"keydown",
stopTypingOnEscapeKey2
);
ownerDocument.removeEventListener(
"selectionchange",
stopTypingOnSelectionUncollapse2
);
};
}
function startTypingInTextField(event) {
const { type, target } = event;
if (!(0, import_dom23.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_compose54.useMergeRefs)([ref1, ref2]);
}
function ObserveTyping({ children }) {
return /* @__PURE__ */ (0, import_jsx_runtime209.jsx)("div", { ref: useTypingObserver(), children });
}
var observe_typing_default = ObserveTyping;
// packages/block-editor/build-module/components/block-list/zoom-out-separator.mjs
var import_components69 = __toESM(require_components(), 1);
var import_compose55 = __toESM(require_compose(), 1);
var import_data79 = __toESM(require_data(), 1);
var import_element93 = __toESM(require_element(), 1);
var import_i18n71 = __toESM(require_i18n(), 1);
var import_jsx_runtime210 = __toESM(require_jsx_runtime(), 1);
function ZoomOutSeparator({
clientId,
rootClientId = "",
position = "top"
}) {
const [isDraggedOver, setIsDraggedOver] = (0, import_element93.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_runtime210.jsx)(import_components69.__unstableAnimatePresence, { children: isVisible && /* @__PURE__ */ (0, import_jsx_runtime210.jsx)(
import_components69.__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_runtime210.jsx)(
import_components69.__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_i18n71.__)("Drop pattern.")
}
)
}
) });
}
// packages/block-editor/build-module/components/block-list/index.mjs
var import_jsx_runtime211 = __toESM(require_jsx_runtime(), 1);
var IntersectionObserver = (0, import_element94.createContext)();
IntersectionObserver.displayName = "IntersectionObserverContext";
var pendingBlockVisibilityUpdatesPerRegistry = /* @__PURE__ */ new WeakMap();
var delayedBlockVisibilityDebounceOptions = {
trailing: true
};
function Root({ className, ...settings2 }) {
const { isOutlineMode, isFocusMode, editedContentOnlySection: editedContentOnlySection2 } = (0, import_data80.useSelect)(
(select3) => {
const {
getSettings: getSettings8,
isTyping: isTyping3,
hasBlockSpotlight: hasBlockSpotlight3,
getEditedContentOnlySection: getEditedContentOnlySection2
} = unlock(select3(store));
const { outlineMode, focusMode } = getSettings8();
return {
isOutlineMode: outlineMode && !isTyping3(),
isFocusMode: focusMode || hasBlockSpotlight3(),
editedContentOnlySection: getEditedContentOnlySection2()
};
},
[]
);
const registry = (0, import_data80.useRegistry)();
const { setBlockVisibility: setBlockVisibility2 } = (0, import_data80.useDispatch)(store);
const delayedBlockVisibilityUpdates = (0, import_compose56.useDebounce)(
(0, import_element94.useCallback)(() => {
const updates = {};
pendingBlockVisibilityUpdatesPerRegistry.get(registry).forEach(([id, isIntersecting]) => {
updates[id] = isIntersecting;
});
setBlockVisibility2(updates);
}, [registry]),
300,
delayedBlockVisibilityDebounceOptions
);
const intersectionObserver = (0, import_element94.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(),
useTypingObserver()
]),
className: clsx_default("is-root-container", className, {
"is-outline-mode": isOutlineMode,
"is-focus-mode": isFocusMode
})
},
settings2
);
return /* @__PURE__ */ (0, import_jsx_runtime211.jsxs)(IntersectionObserver.Provider, { value: intersectionObserver, children: [
/* @__PURE__ */ (0, import_jsx_runtime211.jsx)("div", { ...innerBlocksProps }),
!!editedContentOnlySection2 && /* @__PURE__ */ (0, import_jsx_runtime211.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_element94.useEffect)(() => {
if (!isBlockOrDescendantSelected) {
stopEditingContentOnlySection2();
}
}, [isBlockOrDescendantSelected, stopEditingContentOnlySection2]);
return null;
}
function BlockList(settings2) {
return /* @__PURE__ */ (0, import_jsx_runtime211.jsx)(Provider, { value: DEFAULT_BLOCK_EDIT_CONTEXT, children: /* @__PURE__ */ (0, import_jsx_runtime211.jsx)(Root, { ...settings2 }) });
}
var EMPTY_ARRAY7 = [];
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: getSettings8,
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 (getSettings8().isPreviewMode) {
return {
order: _order,
selectedBlocks: EMPTY_ARRAY7,
visibleBlocks: EMPTY_SET2
};
}
const selectedBlockClientIds = getSelectedBlockClientIds2();
const selectedBlockClientId = selectedBlockClientIds[0];
const showRootAppender = !rootClientId && !selectedBlockClientId && (!_order.length || !canInsertBlockType2(
(0, import_blocks45.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_runtime211.jsxs)(LayoutProvider, { value: layout, children: [
order.map((clientId) => /* @__PURE__ */ (0, import_jsx_runtime211.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_runtime211.jsx)(
ZoomOutSeparator,
{
clientId,
rootClientId,
position: "top"
}
),
/* @__PURE__ */ (0, import_jsx_runtime211.jsx)(
block_default2,
{
rootClientId,
clientId
}
),
isZoomOut2 && /* @__PURE__ */ (0, import_jsx_runtime211.jsx)(
ZoomOutSeparator,
{
clientId,
rootClientId,
position: "bottom"
}
)
]
},
clientId
)),
order.length < 1 && placeholder,
shouldRenderAppender && /* @__PURE__ */ (0, import_jsx_runtime211.jsx)(
BlockListAppender,
{
tagName: __experimentalAppenderTagName,
rootClientId,
CustomAppender
}
)
] });
}
function BlockListItems(props) {
return /* @__PURE__ */ (0, import_jsx_runtime211.jsx)(import_data80.AsyncModeProvider, { value: false, children: /* @__PURE__ */ (0, import_jsx_runtime211.jsx)(Items, { ...props }) });
}
// packages/block-editor/build-module/components/block-tools/index.mjs
var import_data123 = __toESM(require_data(), 1);
var import_dom28 = __toESM(require_dom(), 1);
var import_components117 = __toESM(require_components(), 1);
var import_keyboard_shortcuts9 = __toESM(require_keyboard_shortcuts(), 1);
var import_element127 = __toESM(require_element(), 1);
var import_blocks76 = __toESM(require_blocks(), 1);
var import_a11y12 = __toESM(require_a11y(), 1);
var import_i18n105 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/block-tools/use-block-toolbar-popover-props.mjs
var import_compose59 = __toESM(require_compose(), 1);
var import_data84 = __toESM(require_data(), 1);
var import_dom24 = __toESM(require_dom(), 1);
var import_element99 = __toESM(require_element(), 1);
// packages/block-editor/build-module/hooks/position.mjs
var import_i18n73 = __toESM(require_i18n(), 1);
var import_blocks47 = __toESM(require_blocks(), 1);
var import_components75 = __toESM(require_components(), 1);
var import_compose58 = __toESM(require_compose(), 1);
var import_data83 = __toESM(require_data(), 1);
var import_element98 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/inspector-controls/fill.mjs
var import_components71 = __toESM(require_components(), 1);
var import_warning5 = __toESM(require_warning(), 1);
var import_deprecated10 = __toESM(require_deprecated(), 1);
var import_element95 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/inspector-controls/groups.mjs
var import_components70 = __toESM(require_components(), 1);
var InspectorControlsDefault = (0, import_components70.createSlotFill)("InspectorControls");
var InspectorControlsAdvanced = (0, import_components70.createSlotFill)("InspectorAdvancedControls");
var InspectorControlsBindings = (0, import_components70.createSlotFill)("InspectorControlsBindings");
var InspectorControlsBackground = (0, import_components70.createSlotFill)(
"InspectorControlsBackground"
);
var InspectorControlsBorder = (0, import_components70.createSlotFill)("InspectorControlsBorder");
var InspectorControlsColor = (0, import_components70.createSlotFill)("InspectorControlsColor");
var InspectorControlsFilter = (0, import_components70.createSlotFill)("InspectorControlsFilter");
var InspectorControlsDimensions = (0, import_components70.createSlotFill)(
"InspectorControlsDimensions"
);
var InspectorControlsPosition = (0, import_components70.createSlotFill)("InspectorControlsPosition");
var InspectorControlsTypography = (0, import_components70.createSlotFill)(
"InspectorControlsTypography"
);
var InspectorControlsListView = (0, import_components70.createSlotFill)("InspectorControlsListView");
var InspectorControlsStyles = (0, import_components70.createSlotFill)("InspectorControlsStyles");
var InspectorControlsEffects = (0, import_components70.createSlotFill)("InspectorControlsEffects");
var InspectorControlsContent = (0, import_components70.createSlotFill)("InspectorControlsContent");
var groups = {
default: InspectorControlsDefault,
advanced: InspectorControlsAdvanced,
background: InspectorControlsBackground,
bindings: InspectorControlsBindings,
border: InspectorControlsBorder,
color: InspectorControlsColor,
content: InspectorControlsContent,
dimensions: InspectorControlsDimensions,
effects: InspectorControlsEffects,
filter: InspectorControlsFilter,
list: InspectorControlsListView,
position: InspectorControlsPosition,
settings: InspectorControlsDefault,
// Alias for default.
styles: InspectorControlsStyles,
typography: InspectorControlsTypography
};
var groups_default = groups;
var PrivateInspectorControlsAllowedBlocks = (0, import_components70.createSlotFill)(
/* @__PURE__ */ Symbol("PrivateInspectorControlsAllowedBlocks")
);
// packages/block-editor/build-module/components/inspector-controls/fill.mjs
var import_jsx_runtime212 = __toESM(require_jsx_runtime(), 1);
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 Fill3 = groups_default[group]?.Fill;
if (!Fill3) {
(0, import_warning5.default)(`Unknown InspectorControls group "${group}" provided.`);
return null;
}
const shouldDisplayForPatternEditing = context[mayDisplayPatternEditingControlsKey] && (group === "list" || group === "content");
if (!context[mayDisplayControlsKey] && !shouldDisplayForPatternEditing) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(import_components71.__experimentalStyleProvider, { document, children: /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(Fill3, { children: (fillProps) => {
return /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
ToolsPanelInspectorControl,
{
fillProps,
children,
resetAllFilter
}
);
} }) });
}
function RegisterResetAll({ resetAllFilter, children }) {
const { registerResetAllFilter, deregisterResetAllFilter } = (0, import_element95.useContext)(import_components71.__experimentalToolsPanelContext);
(0, import_element95.useEffect)(() => {
if (resetAllFilter && registerResetAllFilter && deregisterResetAllFilter) {
registerResetAllFilter(resetAllFilter);
return () => {
deregisterResetAllFilter(resetAllFilter);
};
}
}, [resetAllFilter, registerResetAllFilter, deregisterResetAllFilter]);
return children;
}
function ToolsPanelInspectorControl({ children, resetAllFilter, fillProps }) {
const { forwardedContext = [] } = fillProps;
const innerMarkup = /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(RegisterResetAll, { resetAllFilter, children });
return forwardedContext.reduce(
(inner, [Provider2, props]) => /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(Provider2, { ...props, children: inner }),
innerMarkup
);
}
// packages/block-editor/build-module/components/inspector-controls/slot.mjs
var import_components74 = __toESM(require_components(), 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_components72 = __toESM(require_components(), 1);
var import_data81 = __toESM(require_data(), 1);
var import_element96 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/global-styles/utils.mjs
var import_compose57 = __toESM(require_compose(), 1);
function useToolsPanelDropdownMenuProps() {
const isMobile = (0, import_compose57.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 scopeSelector(scope, selector3) {
if (!scope || !selector3) {
return selector3;
}
const scopes = scope.split(",");
const selectors = selector3.split(",");
const selectorsScoped = [];
scopes.forEach((outer) => {
selectors.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_runtime213 = __toESM(require_jsx_runtime(), 1);
function BlockSupportToolsPanel({ children, group, label }) {
const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data81.useDispatch)(store);
const {
getBlockAttributes: getBlockAttributes3,
getMultiSelectedBlockClientIds: getMultiSelectedBlockClientIds2,
getSelectedBlockClientId: getSelectedBlockClientId2,
hasMultiSelection: hasMultiSelection2
} = (0, import_data81.useSelect)(store);
const dropdownMenuProps = useToolsPanelDropdownMenuProps();
const panelId = getSelectedBlockClientId2();
const resetAll = (0, import_element96.useCallback)(
(resetFilters = []) => {
const newAttributes = {};
const clientIds = hasMultiSelection2() ? getMultiSelectedBlockClientIds2() : [panelId];
clientIds.forEach((clientId) => {
const { style } = getBlockAttributes3(clientId);
let newBlockAttributes = { style };
resetFilters.forEach((resetFilter) => {
newBlockAttributes = {
...newBlockAttributes,
...resetFilter(newBlockAttributes)
};
});
newBlockAttributes = {
...newBlockAttributes,
style: cleanEmptyObject(newBlockAttributes.style)
};
newAttributes[clientId] = newBlockAttributes;
});
updateBlockAttributes2(clientIds, newAttributes, true);
},
[
getBlockAttributes3,
getMultiSelectedBlockClientIds2,
hasMultiSelection2,
panelId,
updateBlockAttributes2
]
);
return /* @__PURE__ */ (0, import_jsx_runtime213.jsx)(
import_components72.__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_components73 = __toESM(require_components(), 1);
var import_element97 = __toESM(require_element(), 1);
var import_jsx_runtime214 = __toESM(require_jsx_runtime(), 1);
function BlockSupportSlotContainer({
Slot: Slot6,
fillProps,
...props
}) {
const toolsPanelContext = (0, import_element97.useContext)(import_components73.__experimentalToolsPanelContext);
const computedFillProps = (0, import_element97.useMemo)(
() => ({
...fillProps ?? {},
forwardedContext: [
...fillProps?.forwardedContext ?? [],
[import_components73.__experimentalToolsPanelContext.Provider, { value: toolsPanelContext }]
]
}),
[toolsPanelContext, fillProps]
);
return /* @__PURE__ */ (0, import_jsx_runtime214.jsx)(Slot6, { ...props, fillProps: computedFillProps, bubblesVirtually: true });
}
// packages/block-editor/build-module/components/inspector-controls/slot.mjs
var import_jsx_runtime215 = __toESM(require_jsx_runtime(), 1);
function InspectorControlsSlot({
__experimentalGroup,
group = "default",
label,
fillProps,
...props
}) {
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_components74.__experimentalUseSlotFills)(slotFill?.name);
if (!slotFill) {
(0, import_warning6.default)(`Unknown InspectorControls group "${group}" provided.`);
return null;
}
if (!fills?.length) {
return null;
}
const { Slot: Slot6 } = slotFill;
if (label) {
return /* @__PURE__ */ (0, import_jsx_runtime215.jsx)(BlockSupportToolsPanel, { group, label, children: /* @__PURE__ */ (0, import_jsx_runtime215.jsx)(
BlockSupportSlotContainer,
{
...props,
fillProps,
Slot: Slot6
}
) });
}
return /* @__PURE__ */ (0, import_jsx_runtime215.jsx)(Slot6, { ...props, fillProps, bubblesVirtually: true });
}
// packages/block-editor/build-module/components/inspector-controls/index.mjs
var import_jsx_runtime216 = __toESM(require_jsx_runtime(), 1);
var InspectorControls = InspectorControlsFill;
InspectorControls.Slot = InspectorControlsSlot;
var InspectorAdvancedControls = (props) => {
return /* @__PURE__ */ (0, import_jsx_runtime216.jsx)(InspectorControlsFill, { ...props, group: "advanced" });
};
InspectorAdvancedControls.Slot = (props) => {
return /* @__PURE__ */ (0, import_jsx_runtime216.jsx)(InspectorControlsSlot, { ...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_data82 = __toESM(require_data(), 1);
var import_blocks46 = __toESM(require_blocks(), 1);
var import_i18n72 = __toESM(require_i18n(), 1);
function getPositionTypeLabel(attributes) {
const positionType = attributes?.style?.position?.type;
if (positionType === "sticky") {
return (0, import_i18n72.__)("Sticky");
}
if (positionType === "fixed") {
return (0, import_i18n72.__)("Fixed");
}
return null;
}
function useBlockDisplayInformation(clientId) {
return (0, import_data82.useSelect)(
(select3) => {
if (!clientId) {
return null;
}
const {
getBlockName: getBlockName2,
getBlockAttributes: getBlockAttributes3,
__experimentalGetParsedPattern: __experimentalGetParsedPattern2
} = select3(store);
const { getBlockType: getBlockType24, getActiveBlockVariation } = select3(import_blocks46.store);
const blockName = getBlockName2(clientId);
const blockType = getBlockType24(blockName);
if (!blockType) {
return null;
}
const attributes = getBlockAttributes3(clientId);
const patternName = attributes?.metadata?.patternName;
if (patternName && window?.__experimentalContentOnlyPatternInsertion) {
const pattern = __experimentalGetParsedPattern2(patternName);
const positionLabel2 = getPositionTypeLabel(attributes);
return {
isSynced: false,
title: (0, import_i18n72.__)("Pattern"),
icon: symbol_default,
description: pattern?.description || (0, import_i18n72.__)("A block pattern."),
anchor: attributes?.anchor,
positionLabel: positionLabel2,
positionType: attributes?.style?.position?.type,
name: pattern?.title || attributes?.metadata?.name
};
}
const match2 = getActiveBlockVariation(blockName, attributes);
const isSynced = (0, import_blocks46.isReusableBlock)(blockType) || (0, import_blocks46.isTemplatePart)(blockType);
const syncedTitle = isSynced ? (0, import_blocks46.__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_runtime217 = __toESM(require_jsx_runtime(), 1);
var POSITION_SUPPORT_KEY = "position";
var DEFAULT_OPTION = {
key: "default",
value: "",
name: (0, import_i18n73.__)("Default")
};
var STICKY_OPTION = {
key: "sticky",
value: "sticky",
name: (0, import_i18n73._x)("Sticky", "Name for the value of the CSS position property"),
hint: (0, import_i18n73.__)(
"The block will stick to the top of the window instead of scrolling."
)
};
var FIXED_OPTION = {
key: "fixed",
value: "fixed",
name: (0, import_i18n73._x)("Fixed", "Name for the value of the CSS position property"),
hint: (0, import_i18n73.__)("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_blocks47.getBlockSupport)(blockType, POSITION_SUPPORT_KEY);
return !!(true === support || support?.sticky);
}
function hasFixedPositionSupport(blockType) {
const support = (0, import_blocks47.getBlockSupport)(blockType, POSITION_SUPPORT_KEY);
return !!(true === support || support?.fixed);
}
function hasPositionSupport(blockType) {
const support = (0, import_blocks47.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_data83.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_i18n73.sprintf)(
/* translators: %s: the name of the parent block. */
(0, import_i18n73.__)(
"The block will stick to the scrollable area of the parent %s block."
),
blockInformation.title
) : null;
const options = (0, import_element98.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;
return import_element98.Platform.select({
web: options.length > 1 ? /* @__PURE__ */ (0, import_jsx_runtime217.jsx)(inspector_controls_default, { group: "position", children: /* @__PURE__ */ (0, import_jsx_runtime217.jsx)(import_components75.BaseControl, { help: stickyHelpText, children: /* @__PURE__ */ (0, import_jsx_runtime217.jsx)(
import_components75.CustomSelectControl,
{
__next40pxDefaultSize: true,
label: (0, import_i18n73.__)("Position"),
hideLabelFromVision: true,
describedBy: (0, import_i18n73.sprintf)(
// translators: %s: Currently selected position.
(0, import_i18n73.__)("Currently selected position: %s"),
selectedOption.name
),
options,
value: selectedOption,
onChange: ({ selectedItem }) => {
onChangeType(selectedItem.value);
},
size: "__unstable-large"
}
) }) }) : null,
native: null
});
}
var position_default = {
edit: function Edit2(props) {
const isPositionDisabled = useIsPositionDisabled(props);
if (isPositionDisabled) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime217.jsx)(PositionPanelPure, { ...props });
},
useBlockProps: useBlockProps2,
attributeKeys: ["style"],
hasSupport(name) {
return (0, import_blocks47.hasBlockSupport)(name, POSITION_SUPPORT_KEY);
}
};
var POSITION_BLOCK_PROPS_REFERENCE = {};
function useBlockProps2({ name, style }) {
const hasPositionBlockSupport = (0, import_blocks47.hasBlockSupport)(
name,
POSITION_SUPPORT_KEY
);
const isPositionDisabled = useIsPositionDisabled({ name });
const allowPositionStyles = hasPositionBlockSupport && !isPositionDisabled;
const id = (0, import_compose58.useInstanceId)(POSITION_BLOCK_PROPS_REFERENCE);
const positionSelector = `.wp-container-${id}.wp-container-${id}`;
let css3;
if (allowPositionStyles) {
css3 = getPositionCSS({
selector: positionSelector,
style
}) || "";
}
const className = clsx_default({
[`wp-container-${id}`]: allowPositionStyles && !!css3,
// Only attach a container class if there is generated CSS to be attached.
[`is-position-${style?.position?.type}`]: allowPositionStyles && !!css3 && !!style?.position?.type
});
useStyleOverride({ css: css3 });
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_element99.useState)(0);
const { blockIndex, isSticky } = (0, import_data84.useSelect)(
(select3) => {
const { getBlockIndex: getBlockIndex2, getBlockAttributes: getBlockAttributes3 } = select3(store);
return {
blockIndex: getBlockIndex2(clientId),
isSticky: hasStickyOrFixedPositionValue(
getBlockAttributes3(clientId)
)
};
},
[clientId]
);
const scrollContainer = (0, import_element99.useMemo)(() => {
if (!contentElement) {
return;
}
return (0, import_dom24.getScrollContainer)(contentElement);
}, [contentElement]);
const [props, setProps] = (0, import_element99.useState)(
() => getProps(
contentElement,
selectedBlockElement,
scrollContainer,
toolbarHeight,
isSticky
)
);
const popoverRef = (0, import_compose59.useRefEffect)((popoverNode) => {
setToolbarHeight(popoverNode.offsetHeight);
}, []);
const updateProps = (0, import_element99.useCallback)(
() => setProps(
getProps(
contentElement,
selectedBlockElement,
scrollContainer,
toolbarHeight,
isSticky
)
),
[contentElement, selectedBlockElement, scrollContainer, toolbarHeight]
);
(0, import_element99.useLayoutEffect)(updateProps, [blockIndex, updateProps]);
(0, import_element99.useLayoutEffect)(() => {
if (!contentElement || !selectedBlockElement) {
return;
}
const contentView = contentElement?.ownerDocument?.defaultView;
contentView?.addEventHandler?.("resize", updateProps);
let resizeObserver;
const blockView = selectedBlockElement?.ownerDocument?.defaultView;
if (blockView.ResizeObserver) {
resizeObserver = new blockView.ResizeObserver(updateProps);
resizeObserver.observe(selectedBlockElement);
}
return () => {
contentView?.removeEventHandler?.("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_data85 = __toESM(require_data(), 1);
function useSelectedBlockToolProps(clientId) {
const selectedBlockProps = (0, import_data85.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_runtime218 = __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_runtime218.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_runtime218.jsx)("div", { className: "block-editor-block-list__empty-block-inserter", children: /* @__PURE__ */ (0, import_jsx_runtime218.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_element125 = __toESM(require_element(), 1);
var import_keyboard_shortcuts8 = __toESM(require_keyboard_shortcuts(), 1);
// packages/block-editor/build-module/components/block-toolbar/index.mjs
var import_i18n103 = __toESM(require_i18n(), 1);
var import_data119 = __toESM(require_data(), 1);
var import_element124 = __toESM(require_element(), 1);
var import_compose66 = __toESM(require_compose(), 1);
var import_blocks74 = __toESM(require_blocks(), 1);
var import_components115 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/block-mover/index.mjs
var import_components78 = __toESM(require_components(), 1);
var import_data88 = __toESM(require_data(), 1);
var import_i18n76 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/block-draggable/index.mjs
var import_blocks48 = __toESM(require_blocks(), 1);
var import_components76 = __toESM(require_components(), 1);
var import_data86 = __toESM(require_data(), 1);
var import_element101 = __toESM(require_element(), 1);
var import_compose60 = __toESM(require_compose(), 1);
// packages/block-editor/build-module/components/block-draggable/use-scroll-when-dragging.mjs
var import_dom26 = __toESM(require_dom(), 1);
var import_element100 = __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_element100.useRef)(null);
const velocityYRef = (0, import_element100.useRef)(null);
const scrollParentYRef = (0, import_element100.useRef)(null);
const scrollEditorIntervalRef = (0, import_element100.useRef)(null);
(0, import_element100.useEffect)(
() => () => {
if (scrollEditorIntervalRef.current) {
clearInterval(scrollEditorIntervalRef.current);
scrollEditorIntervalRef.current = null;
}
},
[]
);
const startScrolling = (0, import_element100.useCallback)((event) => {
dragStartYRef.current = event.clientY;
scrollParentYRef.current = (0, import_dom26.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_element100.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_runtime219 = __toESM(require_jsx_runtime(), 1);
var BlockDraggable = ({
appendToOwnerDocument,
children,
clientIds,
cloneClassname,
elementId,
onDragStart,
onDragEnd,
fadeWhenDisabled = false,
dragComponent
}) => {
const {
srcRootClientId,
isDraggable,
icon,
visibleInserter,
getBlockType: getBlockType24
} = (0, import_data86.useSelect)(
(select3) => {
const {
canMoveBlocks: canMoveBlocks2,
getBlockRootClientId: getBlockRootClientId22,
getBlockName: getBlockName2,
getBlockAttributes: getBlockAttributes3,
isBlockInsertionPointVisible: isBlockInsertionPointVisible2
} = select3(store);
const { getBlockType: _getBlockType, getActiveBlockVariation } = select3(import_blocks48.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_element101.useRef)(false);
const [startScrolling, scrollOnDragOver, stopScrolling] = useScrollWhenDragging();
const { getAllowedBlocks: getAllowedBlocks2, getBlockNamesByClientId: getBlockNamesByClientId2, getBlockRootClientId: getBlockRootClientId2 } = (0, import_data86.useSelect)(store);
const { startDraggingBlocks: startDraggingBlocks2, stopDraggingBlocks: stopDraggingBlocks2 } = (0, import_data86.useDispatch)(store);
(0, import_element101.useEffect)(() => {
return () => {
if (isDraggingRef.current) {
stopDraggingBlocks2();
}
};
}, []);
const blockEl = useBlockElement(clientIds[0]);
const editorRoot = blockEl?.closest("body");
(0, import_element101.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(
getBlockType24,
rootAllowedBlocks,
draggedBlockNames,
targetRootBlockName
);
} else {
dropTargetValid = isDropTargetValid(
getBlockType24,
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_compose60.throttle)(onDragOver, 200);
editorRoot.addEventListener("dragover", throttledOnDragOver);
return () => {
editorRoot.removeEventListener("dragover", throttledOnDragOver);
};
}, [
clientIds,
editorRoot,
fadeWhenDisabled,
getAllowedBlocks2,
getBlockNamesByClientId2,
getBlockRootClientId2,
getBlockType24,
visibleInserter
]);
if (!isDraggable) {
return children({ draggable: false });
}
const transferData = {
type: "block",
srcClientIds: clientIds,
srcRootClientId
};
return /* @__PURE__ */ (0, import_jsx_runtime219.jsx)(
import_components76.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_runtime219.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_blocks49 = __toESM(require_blocks(), 1);
var import_components77 = __toESM(require_components(), 1);
var import_compose61 = __toESM(require_compose(), 1);
var import_data87 = __toESM(require_data(), 1);
var import_element102 = __toESM(require_element(), 1);
var import_i18n75 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/block-mover/mover-description.mjs
var import_i18n74 = __toESM(require_i18n(), 1);
var getMovementDirection = (moveDirection, orientation) => {
if (moveDirection === "up") {
if (orientation === "horizontal") {
return (0, import_i18n74.isRTL)() ? "right" : "left";
}
return "up";
} else if (moveDirection === "down") {
if (orientation === "horizontal") {
return (0, import_i18n74.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_i18n74.sprintf)(
// translators: %s: Type of block (i.e. Text, Image etc)
(0, import_i18n74.__)("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_i18n74.sprintf)(
// translators: 1: Type of block (i.e. Text, Image etc), 2: Position of selected block, 3: New position
(0, import_i18n74.__)(
"Move %1$s block from position %2$d down to position %3$d"
),
type,
position,
position + 1
);
}
if (movementDirection === "left") {
return (0, import_i18n74.sprintf)(
// translators: 1: Type of block (i.e. Text, Image etc), 2: Position of selected block, 3: New position
(0, import_i18n74.__)(
"Move %1$s block from position %2$d left to position %3$d"
),
type,
position,
position + 1
);
}
if (movementDirection === "right") {
return (0, import_i18n74.sprintf)(
// translators: 1: Type of block (i.e. Text, Image etc), 2: Position of selected block, 3: New position
(0, import_i18n74.__)(
"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_i18n74.sprintf)(
// translators: 1: Type of block (i.e. Text, Image etc)
(0, import_i18n74.__)(
"Block %1$s is at the end of the content and can\u2019t be moved down"
),
type
);
}
if (movementDirection === "left") {
return (0, import_i18n74.sprintf)(
// translators: 1: Type of block (i.e. Text, Image etc)
(0, import_i18n74.__)(
"Block %1$s is at the end of the content and can\u2019t be moved left"
),
type
);
}
if (movementDirection === "right") {
return (0, import_i18n74.sprintf)(
// translators: 1: Type of block (i.e. Text, Image etc)
(0, import_i18n74.__)(
"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_i18n74.sprintf)(
// translators: 1: Type of block (i.e. Text, Image etc), 2: Position of selected block, 3: New position
(0, import_i18n74.__)("Move %1$s block from position %2$d up to position %3$d"),
type,
position,
position - 1
);
}
if (movementDirection === "left") {
return (0, import_i18n74.sprintf)(
// translators: 1: Type of block (i.e. Text, Image etc), 2: Position of selected block, 3: New position
(0, import_i18n74.__)(
"Move %1$s block from position %2$d left to position %3$d"
),
type,
position,
position - 1
);
}
if (movementDirection === "right") {
return (0, import_i18n74.sprintf)(
// translators: 1: Type of block (i.e. Text, Image etc), 2: Position of selected block, 3: New position
(0, import_i18n74.__)(
"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_i18n74.sprintf)(
// translators: 1: Type of block (i.e. Text, Image etc)
(0, import_i18n74.__)(
"Block %1$s is at the beginning of the content and can\u2019t be moved up"
),
type
);
}
if (movementDirection === "left") {
return (0, import_i18n74.sprintf)(
// translators: 1: Type of block (i.e. Text, Image etc)
(0, import_i18n74.__)(
"Block %1$s is at the beginning of the content and can\u2019t be moved left"
),
type
);
}
if (movementDirection === "right") {
return (0, import_i18n74.sprintf)(
// translators: 1: Type of block (i.e. Text, Image etc)
(0, import_i18n74.__)(
"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_i18n74.__)("All blocks are selected, and cannot be moved");
}
if (dir > 0 && !isLast) {
const movementDirection = getMovementDirection("down", orientation);
if (movementDirection === "down") {
return (0, import_i18n74.sprintf)(
// translators: 1: Number of selected blocks, 2: Position of selected blocks
(0, import_i18n74.__)("Move %1$d blocks from position %2$d down by one place"),
selectedCount,
position
);
}
if (movementDirection === "left") {
return (0, import_i18n74.sprintf)(
// translators: 1: Number of selected blocks, 2: Position of selected blocks
(0, import_i18n74.__)("Move %1$d blocks from position %2$d left by one place"),
selectedCount,
position
);
}
if (movementDirection === "right") {
return (0, import_i18n74.sprintf)(
// translators: 1: Number of selected blocks, 2: Position of selected blocks
(0, import_i18n74.__)("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_i18n74.__)(
"Blocks cannot be moved down as they are already at the bottom"
);
}
if (movementDirection === "left") {
return (0, import_i18n74.__)(
"Blocks cannot be moved left as they are already are at the leftmost position"
);
}
if (movementDirection === "right") {
return (0, import_i18n74.__)(
"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_i18n74.sprintf)(
// translators: 1: Number of selected blocks, 2: Position of selected blocks
(0, import_i18n74.__)("Move %1$d blocks from position %2$d up by one place"),
selectedCount,
position
);
}
if (movementDirection === "left") {
return (0, import_i18n74.sprintf)(
// translators: 1: Number of selected blocks, 2: Position of selected blocks
(0, import_i18n74.__)("Move %1$d blocks from position %2$d left by one place"),
selectedCount,
position
);
}
if (movementDirection === "right") {
return (0, import_i18n74.sprintf)(
// translators: 1: Number of selected blocks, 2: Position of selected blocks
(0, import_i18n74.__)("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_i18n74.__)(
"Blocks cannot be moved up as they are already at the top"
);
}
if (movementDirection === "left") {
return (0, import_i18n74.__)(
"Blocks cannot be moved left as they are already are at the leftmost position"
);
}
if (movementDirection === "right") {
return (0, import_i18n74.__)(
"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_runtime220 = __toESM(require_jsx_runtime(), 1);
var getArrowIcon = (direction, orientation) => {
if (direction === "up") {
if (orientation === "horizontal") {
return (0, import_i18n75.isRTL)() ? chevron_right_default : chevron_left_default;
}
return chevron_up_default;
} else if (direction === "down") {
if (orientation === "horizontal") {
return (0, import_i18n75.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_i18n75.isRTL)() ? (0, import_i18n75.__)("Move right") : (0, import_i18n75.__)("Move left");
}
return (0, import_i18n75.__)("Move up");
} else if (moveDirection === "down") {
if (orientation === "horizontal") {
return (0, import_i18n75.isRTL)() ? (0, import_i18n75.__)("Move left") : (0, import_i18n75.__)("Move right");
}
return (0, import_i18n75.__)("Move down");
}
return null;
};
var BlockMoverButton = (0, import_element102.forwardRef)(
({ clientIds, direction, orientation: moverOrientation, ...props }, ref) => {
const instanceId = (0, import_compose61.useInstanceId)(BlockMoverButton);
const normalizedClientIds = Array.isArray(clientIds) ? clientIds : [clientIds];
const blocksCount = normalizedClientIds.length;
const { disabled } = props;
const {
blockType,
isDisabled,
rootClientId,
isFirst,
isLast,
firstIndex,
orientation = "vertical"
} = (0, import_data87.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_blocks49.getBlockType)(block.name) : null,
isDisabled: disabled || (direction === "up" ? isFirstBlock : isLastBlock),
rootClientId: blockRootClientId,
firstIndex: firstBlockIndex,
isFirst: isFirstBlock,
isLast: isLastBlock,
orientation: moverOrientation || blockListOrientation
};
},
[clientIds, direction]
);
const { moveBlocksDown: moveBlocksDown2, moveBlocksUp: moveBlocksUp2 } = (0, import_data87.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_runtime220.jsxs)(import_jsx_runtime220.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime220.jsx)(
import_components77.Button,
{
__next40pxDefaultSize: true,
ref,
className: clsx_default(
"block-editor-block-mover-button",
`is-${direction}-button`
),
icon: getArrowIcon(direction, orientation),
label: getMovementDirectionLabel(
direction,
orientation
),
"aria-describedby": descriptionId,
...props,
onClick: isDisabled ? null : onClick,
disabled: isDisabled,
accessibleWhenDisabled: true
}
),
/* @__PURE__ */ (0, import_jsx_runtime220.jsx)(import_components77.VisuallyHidden, { id: descriptionId, children: getBlockMoverDescription(
blocksCount,
blockType && blockType.title,
firstIndex,
isFirst,
isLast,
direction === "up" ? -1 : 1,
orientation
) })
] });
}
);
var BlockMoverUpButton = (0, import_element102.forwardRef)((props, ref) => {
return /* @__PURE__ */ (0, import_jsx_runtime220.jsx)(BlockMoverButton, { direction: "up", ref, ...props });
});
var BlockMoverDownButton = (0, import_element102.forwardRef)((props, ref) => {
return /* @__PURE__ */ (0, import_jsx_runtime220.jsx)(BlockMoverButton, { direction: "down", ref, ...props });
});
// packages/block-editor/build-module/components/block-mover/index.mjs
var import_jsx_runtime221 = __toESM(require_jsx_runtime(), 1);
function BlockMover({
clientIds,
hideDragHandle,
isBlockMoverUpButtonDisabled,
isBlockMoverDownButtonDisabled
}) {
const {
canMove,
rootClientId,
isFirst,
isLast,
orientation,
isManualGrid
} = (0, import_data88.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_runtime221.jsxs)(
import_components78.ToolbarGroup,
{
className: clsx_default("block-editor-block-mover", {
"is-horizontal": orientation === "horizontal"
}),
children: [
!hideDragHandle && /* @__PURE__ */ (0, import_jsx_runtime221.jsx)(block_draggable_default, { clientIds, fadeWhenDisabled: true, children: (draggableProps) => /* @__PURE__ */ (0, import_jsx_runtime221.jsx)(
import_components78.Button,
{
__next40pxDefaultSize: true,
icon: drag_handle_default,
className: "block-editor-block-mover__drag-handle",
label: (0, import_i18n76.__)("Drag"),
tabIndex: "-1",
...draggableProps
}
) }),
!isManualGrid && /* @__PURE__ */ (0, import_jsx_runtime221.jsxs)("div", { className: "block-editor-block-mover__move-button-container", children: [
/* @__PURE__ */ (0, import_jsx_runtime221.jsx)(import_components78.ToolbarItem, { children: (itemProps) => /* @__PURE__ */ (0, import_jsx_runtime221.jsx)(
BlockMoverUpButton,
{
disabled: isBlockMoverUpButtonDisabled,
clientIds,
...itemProps
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime221.jsx)(import_components78.ToolbarItem, { children: (itemProps) => /* @__PURE__ */ (0, import_jsx_runtime221.jsx)(
BlockMoverDownButton,
{
disabled: isBlockMoverDownButtonDisabled,
clientIds,
...itemProps
}
) })
] })
]
}
);
}
var block_mover_default = BlockMover;
// packages/block-editor/build-module/components/block-parent-selector/index.mjs
var import_components79 = __toESM(require_components(), 1);
var import_data90 = __toESM(require_data(), 1);
var import_i18n77 = __toESM(require_i18n(), 1);
var import_element104 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/block-toolbar/utils.mjs
var import_data89 = __toESM(require_data(), 1);
var import_element103 = __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_data89.useSelect)(store);
const { toggleBlockHighlight: toggleBlockHighlight2 } = (0, import_data89.useDispatch)(store);
const timeoutRef = (0, import_element103.useRef)();
const isDistractionFree = (0, import_data89.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_element103.useEffect)(
() => () => {
handleOnChange(false);
clearTimeoutRef();
},
[]
);
return {
debouncedShowGestures,
debouncedHideGestures
};
}
function useShowHoveredOrFocusedGestures({
ref,
highlightParent = false,
debounceTimeout = DEBOUNCE_TIMEOUT
}) {
const [isFocused, setIsFocused] = (0, import_element103.useState)(false);
const { debouncedShowGestures, debouncedHideGestures } = useDebouncedShowGestures({
ref,
debounceTimeout,
isFocused,
highlightParent
});
const registerRef = (0, import_element103.useRef)(false);
const isFocusedWithin = () => {
return ref?.current && ref.current.contains(ref.current.ownerDocument.activeElement);
};
(0, import_element103.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_runtime222 = __toESM(require_jsx_runtime(), 1);
function BlockParentSelector() {
const { selectBlock: selectBlock2 } = (0, import_data90.useDispatch)(store);
const { parentClientId } = (0, import_data90.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_element104.useRef)();
const showHoveredOrFocusedGestures = useShowHoveredOrFocusedGestures({
ref: nodeRef,
highlightParent: true
});
return /* @__PURE__ */ (0, import_jsx_runtime222.jsx)(
"div",
{
className: "block-editor-block-parent-selector",
ref: nodeRef,
...showHoveredOrFocusedGestures,
children: /* @__PURE__ */ (0, import_jsx_runtime222.jsx)(
import_components79.ToolbarButton,
{
className: "block-editor-block-parent-selector__button",
onClick: () => selectBlock2(parentClientId),
label: (0, import_i18n77.sprintf)(
/* translators: %s: Name of the block's parent. */
(0, import_i18n77.__)("Select parent block: %s"),
blockInformation?.title
),
showTooltip: true,
icon: /* @__PURE__ */ (0, import_jsx_runtime222.jsx)(block_icon_default, { icon: blockInformation?.icon })
}
)
},
parentClientId
);
}
// packages/block-editor/build-module/components/block-controls/fill.mjs
var import_components81 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/block-controls/groups.mjs
var import_components80 = __toESM(require_components(), 1);
var BlockControlsDefault = (0, import_components80.createSlotFill)("BlockControls");
var BlockControlsBlock = (0, import_components80.createSlotFill)("BlockControlsBlock");
var BlockControlsInline = (0, import_components80.createSlotFill)("BlockFormatControls");
var BlockControlsOther = (0, import_components80.createSlotFill)("BlockControlsOther");
var BlockControlsParent = (0, import_components80.createSlotFill)("BlockControlsParent");
var groups2 = {
default: BlockControlsDefault,
block: BlockControlsBlock,
inline: BlockControlsInline,
other: BlockControlsOther,
parent: BlockControlsParent
};
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_runtime223 = __toESM(require_jsx_runtime(), 1);
function BlockControlsFill({
group = "default",
controls,
children,
__experimentalShareWithChildBlocks = false
}) {
const Fill3 = useBlockControlsFill(
group,
__experimentalShareWithChildBlocks
);
if (!Fill3) {
return null;
}
const innerMarkup = /* @__PURE__ */ (0, import_jsx_runtime223.jsxs)(import_jsx_runtime223.Fragment, { children: [
group === "default" && /* @__PURE__ */ (0, import_jsx_runtime223.jsx)(import_components81.ToolbarGroup, { controls }),
children
] });
return /* @__PURE__ */ (0, import_jsx_runtime223.jsx)(import_components81.__experimentalStyleProvider, { document, children: /* @__PURE__ */ (0, import_jsx_runtime223.jsx)(Fill3, { children: (fillProps) => {
const { forwardedContext = [] } = fillProps;
return forwardedContext.reduce(
(inner, [Provider2, props]) => /* @__PURE__ */ (0, import_jsx_runtime223.jsx)(Provider2, { ...props, children: inner }),
innerMarkup
);
} }) });
}
// packages/block-editor/build-module/components/block-controls/slot.mjs
var import_element105 = __toESM(require_element(), 1);
var import_components82 = __toESM(require_components(), 1);
var import_warning7 = __toESM(require_warning(), 1);
var import_jsx_runtime224 = __toESM(require_jsx_runtime(), 1);
var { ComponentsContext } = unlock(import_components82.privateApis);
function BlockControlsSlot({ group = "default", ...props }) {
const toolbarState = (0, import_element105.useContext)(import_components82.__experimentalToolbarContext);
const contextState = (0, import_element105.useContext)(ComponentsContext);
const fillProps = (0, import_element105.useMemo)(
() => ({
forwardedContext: [
[import_components82.__experimentalToolbarContext.Provider, { value: toolbarState }],
[ComponentsContext.Provider, { value: contextState }]
]
}),
[toolbarState, contextState]
);
const slotFill = groups_default2[group];
const fills = (0, import_components82.__experimentalUseSlotFills)(slotFill.name);
if (!slotFill) {
(0, import_warning7.default)(`Unknown BlockControls group "${group}" provided.`);
return null;
}
if (!fills?.length) {
return null;
}
const { Slot: Slot6 } = slotFill;
const slot = /* @__PURE__ */ (0, import_jsx_runtime224.jsx)(Slot6, { ...props, bubblesVirtually: true, fillProps });
if (group === "default") {
return slot;
}
return /* @__PURE__ */ (0, import_jsx_runtime224.jsx)(import_components82.ToolbarGroup, { children: slot });
}
// packages/block-editor/build-module/components/block-controls/index.mjs
var import_jsx_runtime225 = __toESM(require_jsx_runtime(), 1);
var BlockControls = BlockControlsFill;
BlockControls.Slot = BlockControlsSlot;
var BlockFormatControls = (props) => {
return /* @__PURE__ */ (0, import_jsx_runtime225.jsx)(BlockControlsFill, { group: "inline", ...props });
};
BlockFormatControls.Slot = (props) => {
return /* @__PURE__ */ (0, import_jsx_runtime225.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_components83 = __toESM(require_components(), 1);
var { Fill: __unstableBlockToolbarLastItem, Slot: Slot2 } = (0, import_components83.createSlotFill)(
"__unstableBlockToolbarLastItem"
);
__unstableBlockToolbarLastItem.Slot = Slot2;
var block_toolbar_last_item_default = __unstableBlockToolbarLastItem;
// packages/block-editor/build-module/components/block-settings-menu/index.mjs
var import_components101 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/block-settings-menu/block-settings-dropdown.mjs
var import_blocks62 = __toESM(require_blocks(), 1);
var import_components99 = __toESM(require_components(), 1);
var import_data106 = __toESM(require_data(), 1);
var import_element114 = __toESM(require_element(), 1);
var import_i18n91 = __toESM(require_i18n(), 1);
var import_keyboard_shortcuts6 = __toESM(require_keyboard_shortcuts(), 1);
var import_compose63 = __toESM(require_compose(), 1);
// packages/block-editor/build-module/components/block-actions/index.mjs
var import_data92 = __toESM(require_data(), 1);
var import_blocks52 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/components/use-paste-styles/index.mjs
var import_element107 = __toESM(require_element(), 1);
var import_blocks51 = __toESM(require_blocks(), 1);
var import_data91 = __toESM(require_data(), 1);
var import_notices8 = __toESM(require_notices(), 1);
var import_i18n78 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/hooks/supports.mjs
var import_blocks50 = __toESM(require_blocks(), 1);
var import_element106 = __toESM(require_element(), 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_blocks50.hasBlockSupport)(nameOrType, ALIGN_SUPPORT_KEY);
function hasBorderSupport(nameOrType, feature = "any") {
if (import_element106.Platform.OS !== "web") {
return false;
}
const support = (0, import_blocks50.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_blocks50.getBlockSupport)(nameOrType, COLOR_SUPPORT_KEY);
return colorSupport !== null && typeof colorSupport === "object" && !!colorSupport.gradients;
};
var hasBackgroundColorSupport = (nameOrType) => {
const colorSupport = (0, import_blocks50.getBlockSupport)(nameOrType, COLOR_SUPPORT_KEY);
return colorSupport && colorSupport.background !== false;
};
var hasTextAlignSupport = (nameOrType) => (0, import_blocks50.hasBlockSupport)(nameOrType, TEXT_ALIGN_SUPPORT_KEY);
var hasTextColorSupport = (nameOrType) => {
const colorSupport = (0, import_blocks50.getBlockSupport)(nameOrType, COLOR_SUPPORT_KEY);
return colorSupport && colorSupport.text !== false;
};
var hasCustomClassNameSupport = (nameOrType) => (0, import_blocks50.hasBlockSupport)(nameOrType, CUSTOM_CLASS_NAME_SUPPORT_KEY, true);
var hasFontFamilySupport = (nameOrType) => (0, import_blocks50.hasBlockSupport)(nameOrType, FONT_FAMILY_SUPPORT_KEY);
var hasFontSizeSupport = (nameOrType) => (0, import_blocks50.hasBlockSupport)(nameOrType, FONT_SIZE_SUPPORT_KEY);
var hasLayoutSupport = (nameOrType) => (0, import_blocks50.hasBlockSupport)(nameOrType, LAYOUT_SUPPORT_KEY);
var hasStyleSupport = (nameOrType) => styleSupportKeys.some((key) => (0, import_blocks50.hasBlockSupport)(nameOrType, key));
// packages/block-editor/build-module/components/use-paste-styles/index.mjs
function hasSerializedBlocks(text) {
try {
const blocks2 = (0, import_blocks51.parse)(text, {
__unstableSkipMigrationLogs: true,
__unstableSkipAutop: true
});
if (blocks2.length === 1 && blocks2[0].name === "core/freeform") {
return false;
}
return true;
} catch (err) {
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 index = 0; index < Math.min(sourceBlocks.length, targetBlocks.length); index += 1) {
updateBlockAttributes2(
targetBlocks[index].clientId,
getStyleAttributes(sourceBlocks[index], targetBlocks[index])
);
recursivelyUpdateBlockAttributes(
targetBlocks[index].innerBlocks,
sourceBlocks[index].innerBlocks,
updateBlockAttributes2
);
}
}
function usePasteStyles() {
const registry = (0, import_data91.useRegistry)();
const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data91.useDispatch)(store);
const { createSuccessNotice, createWarningNotice, createErrorNotice } = (0, import_data91.useDispatch)(import_notices8.store);
return (0, import_element107.useCallback)(
async (targetBlocks) => {
let html = "";
try {
if (!window.navigator.clipboard) {
createErrorNotice(
(0, import_i18n78.__)(
"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 (error) {
createErrorNotice(
(0, import_i18n78.__)(
"Unable to paste styles. Please allow browser clipboard permissions before continuing."
),
{
type: "snackbar"
}
);
return;
}
if (!html || !hasSerializedBlocks(html)) {
createWarningNotice(
(0, import_i18n78.__)(
"Unable to paste styles. Block styles couldn't be found within the copied content."
),
{
type: "snackbar"
}
);
return;
}
const copiedBlocks = (0, import_blocks51.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_blocks51.getBlockType)(targetBlocks[0].name)?.title;
createSuccessNotice(
(0, import_i18n78.sprintf)(
// Translators: %s: Name of the block being pasted, e.g. "Paragraph".
(0, import_i18n78.__)("Pasted styles to %s."),
title
),
{ type: "snackbar" }
);
} else {
createSuccessNotice(
(0, import_i18n78.sprintf)(
// Translators: %d: The number of the blocks.
(0, import_i18n78.__)("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: getDefaultBlockName7, getGroupingBlockName } = (0, import_data92.useSelect)(import_blocks52.store);
const selected = (0, import_data92.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(
getDefaultBlockName7(),
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_blocks52.hasBlockSupport)(block.name, "color") || (0, import_blocks52.hasBlockSupport)(block.name, "typography"));
}),
canDuplicate: blocks2.every((block) => {
return !!block && (0, import_blocks52.hasBlockSupport)(block.name, "multiple", true) && canInsertBlockType2(block.name, rootClientId);
})
};
},
[clientIds, getDefaultBlockName7]
);
const { getBlocksByClientId: getBlocksByClientId2, getBlocks: getBlocks2 } = (0, import_data92.useSelect)(store);
const { canRemove, canInsertBlock, canCopyStyles, canDuplicate } = selected;
const {
removeBlocks: removeBlocks2,
replaceBlocks: replaceBlocks2,
duplicateBlocks: duplicateBlocks2,
insertAfterBlock: insertAfterBlock2,
insertBeforeBlock: insertBeforeBlock2,
flashBlock: flashBlock2
} = (0, import_data92.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_blocks52.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/block-comment-icon-slot.mjs
var import_components84 = __toESM(require_components(), 1);
var CommentIconSlotFill = (0, import_components84.createSlotFill)(/* @__PURE__ */ Symbol("CommentIconSlotFill"));
var block_comment_icon_slot_default = CommentIconSlotFill;
// packages/block-editor/build-module/components/block-settings-menu/block-html-convert-button.mjs
var import_i18n79 = __toESM(require_i18n(), 1);
var import_components85 = __toESM(require_components(), 1);
var import_blocks53 = __toESM(require_blocks(), 1);
var import_data93 = __toESM(require_data(), 1);
var import_jsx_runtime226 = __toESM(require_jsx_runtime(), 1);
function BlockHTMLConvertButton({ clientId }) {
const block = (0, import_data93.useSelect)(
(select3) => select3(store).getBlock(clientId),
[clientId]
);
const { replaceBlocks: replaceBlocks2 } = (0, import_data93.useDispatch)(store);
if (!block || block.name !== "core/html") {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime226.jsx)(
import_components85.MenuItem,
{
onClick: () => replaceBlocks2(
clientId,
(0, import_blocks53.rawHandler)({ HTML: (0, import_blocks53.getBlockContent)(block) })
),
children: (0, import_i18n79.__)("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_components86 = __toESM(require_components(), 1);
var { Fill: __unstableBlockSettingsMenuFirstItem, Slot: Slot3 } = (0, import_components86.createSlotFill)(
"__unstableBlockSettingsMenuFirstItem"
);
__unstableBlockSettingsMenuFirstItem.Slot = Slot3;
var block_settings_menu_first_item_default = __unstableBlockSettingsMenuFirstItem;
// packages/block-editor/build-module/components/block-settings-menu-controls/index.mjs
var import_components97 = __toESM(require_components(), 1);
var import_blocks61 = __toESM(require_blocks(), 1);
var import_data104 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/convert-to-group-buttons/index.mjs
var import_components88 = __toESM(require_components(), 1);
var import_i18n81 = __toESM(require_i18n(), 1);
var import_blocks56 = __toESM(require_blocks(), 1);
var import_data96 = __toESM(require_data(), 1);
var import_keycodes9 = __toESM(require_keycodes(), 1);
// packages/block-editor/build-module/components/convert-to-group-buttons/use-convert-to-group-button-props.mjs
var import_blocks54 = __toESM(require_blocks(), 1);
var import_data94 = __toESM(require_data(), 1);
function useConvertToGroupButtonProps(selectedClientIds) {
return (0, import_data94.useSelect)(
(select3) => {
const {
getBlocksByClientId: getBlocksByClientId2,
getSelectedBlockClientIds: getSelectedBlockClientIds2,
isUngroupable: isUngroupable2,
isGroupable: isGroupable2
} = select3(store);
const { getGroupingBlockName, getBlockType: getBlockType24 } = select3(import_blocks54.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 && getBlockType24(firstSelectedBlock.name)?.transforms?.ungroup
};
},
[selectedClientIds]
);
}
// packages/block-editor/build-module/components/convert-to-group-buttons/toolbar.mjs
var import_data95 = __toESM(require_data(), 1);
var import_blocks55 = __toESM(require_blocks(), 1);
var import_components87 = __toESM(require_components(), 1);
var import_i18n80 = __toESM(require_i18n(), 1);
var import_jsx_runtime227 = __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_data95.useDispatch)(store);
const { canRemove, variations } = (0, import_data95.useSelect)(
(select3) => {
const { canRemoveBlocks: canRemoveBlocks2 } = select3(store);
const { getBlockVariations: getBlockVariations2 } = select3(import_blocks55.store);
return {
canRemove: canRemoveBlocks2(clientIds),
variations: getBlockVariations2(
groupingBlockName,
"transform"
)
};
},
[clientIds, groupingBlockName]
);
const onConvertToGroup = (layout) => {
const newBlocks = (0, import_blocks55.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_runtime227.jsxs)(import_components87.ToolbarGroup, { children: [
/* @__PURE__ */ (0, import_jsx_runtime227.jsx)(
import_components87.ToolbarButton,
{
icon: group_default,
label: (0, import_i18n80._x)("Group", "action: convert blocks to group"),
onClick: onConvertToGroup
}
),
canInsertRow && /* @__PURE__ */ (0, import_jsx_runtime227.jsx)(
import_components87.ToolbarButton,
{
icon: row_default,
label: (0, import_i18n80._x)("Row", "action: convert blocks to row"),
onClick: onConvertToRow
}
),
canInsertStack && /* @__PURE__ */ (0, import_jsx_runtime227.jsx)(
import_components87.ToolbarButton,
{
icon: stack_default,
label: (0, import_i18n80._x)("Stack", "action: convert blocks to stack"),
onClick: onConvertToStack
}
),
canInsertGrid && /* @__PURE__ */ (0, import_jsx_runtime227.jsx)(
import_components87.ToolbarButton,
{
icon: grid_default,
label: (0, import_i18n80._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_runtime228 = __toESM(require_jsx_runtime(), 1);
function ConvertToGroupButton({
clientIds,
isGroupable: isGroupable2,
isUngroupable: isUngroupable2,
onUngroup,
blocksSelection,
groupingBlockName,
onClose = () => {
}
}) {
const { getSelectedBlockClientIds: getSelectedBlockClientIds2 } = (0, import_data96.useSelect)(store);
const { replaceBlocks: replaceBlocks2 } = (0, import_data96.useDispatch)(store);
const onConvertToGroup = () => {
const newBlocks = (0, import_blocks56.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_runtime228.jsxs)(import_jsx_runtime228.Fragment, { children: [
isGroupable2 && /* @__PURE__ */ (0, import_jsx_runtime228.jsx)(
import_components88.MenuItem,
{
shortcut: selectedBlockClientIds.length > 1 ? import_keycodes9.displayShortcut.primary("g") : void 0,
onClick: () => {
onConvertToGroup();
onClose();
},
children: (0, import_i18n81._x)("Group", "verb")
}
),
isUngroupable2 && /* @__PURE__ */ (0, import_jsx_runtime228.jsx)(
import_components88.MenuItem,
{
onClick: () => {
onConvertFromGroup();
onClose();
},
children: (0, import_i18n81._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_i18n83 = __toESM(require_i18n(), 1);
var import_element109 = __toESM(require_element(), 1);
var import_components90 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/block-lock/use-block-lock.mjs
var import_data97 = __toESM(require_data(), 1);
function useBlockLock(clientId) {
return (0, import_data97.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_i18n82 = __toESM(require_i18n(), 1);
var import_element108 = __toESM(require_element(), 1);
var import_components89 = __toESM(require_components(), 1);
var import_data98 = __toESM(require_data(), 1);
var import_blocks57 = __toESM(require_blocks(), 1);
var import_jsx_runtime229 = __toESM(require_jsx_runtime(), 1);
var ALLOWS_EDIT_LOCKING = ["core/navigation"];
function getTemplateLockValue(lock4) {
if (lock4.remove && lock4.move) {
return "all";
}
if (lock4.remove && !lock4.move) {
return "insert";
}
return false;
}
function BlockLockModal({ clientId, onClose }) {
const [lock4, setLock] = (0, import_element108.useState)({ move: false, remove: false });
const { isEditLocked, isMoveLocked, isRemoveLocked } = useBlockLock(clientId);
const { allowsEditLocking, templateLock, hasTemplateLock } = (0, import_data98.useSelect)(
(select3) => {
const { getBlockName: getBlockName2, getBlockAttributes: getBlockAttributes3 } = select3(store);
const blockName = getBlockName2(clientId);
const blockType = (0, import_blocks57.getBlockType)(blockName);
return {
allowsEditLocking: ALLOWS_EDIT_LOCKING.includes(blockName),
templateLock: getBlockAttributes3(clientId)?.templateLock,
hasTemplateLock: !!blockType?.attributes?.templateLock
};
},
[clientId]
);
const [applyTemplateLock, setApplyTemplateLock] = (0, import_element108.useState)(
!!templateLock
);
const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data98.useDispatch)(store);
const blockInformation = useBlockDisplayInformation(clientId);
(0, import_element108.useEffect)(() => {
setLock({
move: isMoveLocked,
remove: isRemoveLocked,
...allowsEditLocking ? { edit: isEditLocked } : {}
});
}, [isEditLocked, isMoveLocked, isRemoveLocked, allowsEditLocking]);
const isAllChecked = Object.values(lock4).every(Boolean);
const isMixed = Object.values(lock4).some(Boolean) && !isAllChecked;
return /* @__PURE__ */ (0, import_jsx_runtime229.jsx)(
import_components89.Modal,
{
title: (0, import_i18n82.sprintf)(
/* translators: %s: Name of the block. */
(0, import_i18n82.__)("Lock %s"),
blockInformation.title
),
overlayClassName: "block-editor-block-lock-modal",
onRequestClose: onClose,
size: "small",
children: /* @__PURE__ */ (0, import_jsx_runtime229.jsxs)(
"form",
{
onSubmit: (event) => {
event.preventDefault();
updateBlockAttributes2([clientId], {
lock: lock4,
templateLock: applyTemplateLock ? getTemplateLockValue(lock4) : void 0
});
onClose();
},
children: [
/* @__PURE__ */ (0, import_jsx_runtime229.jsxs)("fieldset", { className: "block-editor-block-lock-modal__options", children: [
/* @__PURE__ */ (0, import_jsx_runtime229.jsx)("legend", { children: (0, import_i18n82.__)("Select the features you want to lock") }),
/* @__PURE__ */ (0, import_jsx_runtime229.jsx)(
"ul",
{
role: "list",
className: "block-editor-block-lock-modal__checklist",
children: /* @__PURE__ */ (0, import_jsx_runtime229.jsxs)("li", { children: [
/* @__PURE__ */ (0, import_jsx_runtime229.jsx)(
import_components89.CheckboxControl,
{
className: "block-editor-block-lock-modal__options-all",
label: (0, import_i18n82.__)("Lock all"),
checked: isAllChecked,
indeterminate: isMixed,
onChange: (newValue) => setLock({
move: newValue,
remove: newValue,
...allowsEditLocking ? { edit: newValue } : {}
})
}
),
/* @__PURE__ */ (0, import_jsx_runtime229.jsxs)(
"ul",
{
role: "list",
className: "block-editor-block-lock-modal__checklist",
children: [
allowsEditLocking && /* @__PURE__ */ (0, import_jsx_runtime229.jsxs)("li", { className: "block-editor-block-lock-modal__checklist-item", children: [
/* @__PURE__ */ (0, import_jsx_runtime229.jsx)(
import_components89.CheckboxControl,
{
label: (0, import_i18n82.__)("Lock editing"),
checked: !!lock4.edit,
onChange: (edit) => setLock((prevLock) => ({
...prevLock,
edit
}))
}
),
/* @__PURE__ */ (0, import_jsx_runtime229.jsx)(
import_components89.Icon,
{
className: "block-editor-block-lock-modal__lock-icon",
icon: lock4.edit ? lock_default : unlock_default
}
)
] }),
/* @__PURE__ */ (0, import_jsx_runtime229.jsxs)("li", { className: "block-editor-block-lock-modal__checklist-item", children: [
/* @__PURE__ */ (0, import_jsx_runtime229.jsx)(
import_components89.CheckboxControl,
{
label: (0, import_i18n82.__)("Lock movement"),
checked: lock4.move,
onChange: (move) => setLock((prevLock) => ({
...prevLock,
move
}))
}
),
/* @__PURE__ */ (0, import_jsx_runtime229.jsx)(
import_components89.Icon,
{
className: "block-editor-block-lock-modal__lock-icon",
icon: lock4.move ? lock_default : unlock_default
}
)
] }),
/* @__PURE__ */ (0, import_jsx_runtime229.jsxs)("li", { className: "block-editor-block-lock-modal__checklist-item", children: [
/* @__PURE__ */ (0, import_jsx_runtime229.jsx)(
import_components89.CheckboxControl,
{
label: (0, import_i18n82.__)("Lock removal"),
checked: lock4.remove,
onChange: (remove5) => setLock((prevLock) => ({
...prevLock,
remove: remove5
}))
}
),
/* @__PURE__ */ (0, import_jsx_runtime229.jsx)(
import_components89.Icon,
{
className: "block-editor-block-lock-modal__lock-icon",
icon: lock4.remove ? lock_default : unlock_default
}
)
] })
]
}
)
] })
}
),
hasTemplateLock && /* @__PURE__ */ (0, import_jsx_runtime229.jsx)(
import_components89.ToggleControl,
{
className: "block-editor-block-lock-modal__template-lock",
label: (0, import_i18n82.__)("Apply to all blocks inside"),
checked: applyTemplateLock,
disabled: lock4.move && !lock4.remove,
onChange: () => setApplyTemplateLock(!applyTemplateLock)
}
)
] }),
/* @__PURE__ */ (0, import_jsx_runtime229.jsxs)(
import_components89.Flex,
{
className: "block-editor-block-lock-modal__actions",
justify: "flex-end",
expanded: false,
children: [
/* @__PURE__ */ (0, import_jsx_runtime229.jsx)(import_components89.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime229.jsx)(
import_components89.Button,
{
variant: "tertiary",
onClick: onClose,
__next40pxDefaultSize: true,
children: (0, import_i18n82.__)("Cancel")
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime229.jsx)(import_components89.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime229.jsx)(
import_components89.Button,
{
variant: "primary",
type: "submit",
__next40pxDefaultSize: true,
children: (0, import_i18n82.__)("Apply")
}
) })
]
}
)
]
}
)
}
);
}
// packages/block-editor/build-module/components/block-lock/menu-item.mjs
var import_jsx_runtime230 = __toESM(require_jsx_runtime(), 1);
function BlockLockMenuItem({ clientId }) {
const { canLock, isLocked } = useBlockLock(clientId);
const [isModalOpen, toggleModal] = (0, import_element109.useReducer)(
(isActive) => !isActive,
false
);
if (!canLock) {
return null;
}
const label = isLocked ? (0, import_i18n83.__)("Unlock") : (0, import_i18n83.__)("Lock");
return /* @__PURE__ */ (0, import_jsx_runtime230.jsxs)(import_jsx_runtime230.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime230.jsx)(
import_components90.MenuItem,
{
icon: isLocked ? unlock_default : lock_outline_default,
onClick: toggleModal,
"aria-expanded": isModalOpen,
"aria-haspopup": "dialog",
children: label
}
),
isModalOpen && /* @__PURE__ */ (0, import_jsx_runtime230.jsx)(BlockLockModal, { clientId, onClose: toggleModal })
] });
}
// packages/block-editor/build-module/components/block-lock/toolbar.mjs
var import_i18n84 = __toESM(require_i18n(), 1);
var import_components91 = __toESM(require_components(), 1);
var import_element110 = __toESM(require_element(), 1);
var import_jsx_runtime231 = __toESM(require_jsx_runtime(), 1);
function BlockLockToolbar({ clientId }) {
const { canLock, isLocked } = useBlockLock(clientId);
const [isModalOpen, toggleModal] = (0, import_element110.useReducer)(
(isActive) => !isActive,
false
);
const hasLockButtonShownRef = (0, import_element110.useRef)(false);
(0, import_element110.useEffect)(() => {
if (isLocked) {
hasLockButtonShownRef.current = true;
}
}, [isLocked]);
if (!isLocked && !hasLockButtonShownRef.current) {
return null;
}
let label = isLocked ? (0, import_i18n84.__)("Unlock") : (0, import_i18n84.__)("Lock");
if (!canLock && isLocked) {
label = (0, import_i18n84.__)("Locked");
}
return /* @__PURE__ */ (0, import_jsx_runtime231.jsxs)(import_jsx_runtime231.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime231.jsx)(import_components91.ToolbarGroup, { className: "block-editor-block-lock-toolbar", children: /* @__PURE__ */ (0, import_jsx_runtime231.jsx)(
import_components91.ToolbarButton,
{
disabled: !canLock,
icon: isLocked ? lock_default : unlock_default,
label,
onClick: toggleModal,
"aria-expanded": isModalOpen,
"aria-haspopup": "dialog"
}
) }),
isModalOpen && /* @__PURE__ */ (0, import_jsx_runtime231.jsx)(BlockLockModal, { clientId, onClose: toggleModal })
] });
}
// packages/block-editor/build-module/components/block-settings-menu/block-mode-toggle.mjs
var import_i18n85 = __toESM(require_i18n(), 1);
var import_components92 = __toESM(require_components(), 1);
var import_blocks58 = __toESM(require_blocks(), 1);
var import_data99 = __toESM(require_data(), 1);
var import_jsx_runtime232 = __toESM(require_jsx_runtime(), 1);
var noop8 = () => {
};
function BlockModeToggle({ clientId, onToggle = noop8 }) {
const { blockType, mode: mode2, enabled } = (0, import_data99.useSelect)(
(select3) => {
const { getBlock: getBlock2, getBlockMode: getBlockMode2, getSettings: getSettings8 } = select3(store);
const block = getBlock2(clientId);
return {
mode: getBlockMode2(clientId),
blockType: block ? (0, import_blocks58.getBlockType)(block.name) : null,
enabled: getSettings8().codeEditingEnabled && !!block?.isValid
};
},
[clientId]
);
const { toggleBlockMode: toggleBlockMode2 } = (0, import_data99.useDispatch)(store);
if (!blockType || !(0, import_blocks58.hasBlockSupport)(blockType, "html", true) || !enabled) {
return null;
}
const label = mode2 === "visual" ? (0, import_i18n85.__)("Edit as HTML") : (0, import_i18n85.__)("Edit visually");
return /* @__PURE__ */ (0, import_jsx_runtime232.jsx)(
import_components92.MenuItem,
{
onClick: () => {
toggleBlockMode2(clientId);
onToggle();
},
children: label
}
);
}
// packages/block-editor/build-module/components/content-lock/modify-content-lock-menu-item.mjs
var import_components93 = __toESM(require_components(), 1);
var import_data100 = __toESM(require_data(), 1);
var import_i18n86 = __toESM(require_i18n(), 1);
var import_jsx_runtime233 = __toESM(require_jsx_runtime(), 1);
function ModifyContentOnlySectionMenuItem({ clientId, onClose }) {
const { templateLock, isLockedByParent, isEditingContentOnlySection } = (0, import_data100.useSelect)(
(select3) => {
const {
getContentLockingParent: getContentLockingParent2,
getTemplateLock: getTemplateLock2,
getEditedContentOnlySection: getEditedContentOnlySection2
} = unlock(select3(store));
return {
templateLock: getTemplateLock2(clientId),
isLockedByParent: !!getContentLockingParent2(clientId),
isEditingContentOnlySection: getEditedContentOnlySection2() === clientId
};
},
[clientId]
);
const blockEditorActions = (0, import_data100.useDispatch)(store);
const isContentLocked = !isLockedByParent && templateLock === "contentOnly";
if (window?.__experimentalContentOnlyPatternInsertion || !isContentLocked && !isEditingContentOnlySection) {
return null;
}
const { editContentOnlySection: editContentOnlySection2 } = unlock(blockEditorActions);
const showContentOnlyModifyButton = !isEditingContentOnlySection && isContentLocked;
return showContentOnlyModifyButton && /* @__PURE__ */ (0, import_jsx_runtime233.jsx)(
import_components93.MenuItem,
{
onClick: () => {
editContentOnlySection2(clientId);
onClose();
},
children: (0, import_i18n86._x)("Modify", "Unlock content locked blocks")
}
);
}
// packages/block-editor/build-module/components/block-rename/rename-control.mjs
var import_components95 = __toESM(require_components(), 1);
var import_i18n88 = __toESM(require_i18n(), 1);
var import_element112 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/block-rename/modal.mjs
var import_components94 = __toESM(require_components(), 1);
var import_i18n87 = __toESM(require_i18n(), 1);
var import_element111 = __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_runtime234 = __toESM(require_jsx_runtime(), 1);
function BlockRenameModal({ clientId, onClose }) {
const [editedBlockName, setEditedBlockName] = (0, import_element111.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_i18n87.sprintf)(
/* translators: %s: new name/label for the block */
(0, import_i18n87.__)('Block name reset to: "%s".'),
editedBlockName
) : (0, import_i18n87.sprintf)(
/* translators: %s: new name/label for the block */
(0, import_i18n87.__)('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_runtime234.jsx)(
import_components94.Modal,
{
title: (0, import_i18n87.__)("Rename"),
onRequestClose: onClose,
overlayClassName: "block-editor-block-rename-modal",
focusOnMount: "firstContentElement",
size: "small",
children: /* @__PURE__ */ (0, import_jsx_runtime234.jsx)(
"form",
{
onSubmit: (e2) => {
e2.preventDefault();
if (!isNameValid) {
return;
}
handleSubmit();
},
children: /* @__PURE__ */ (0, import_jsx_runtime234.jsxs)(import_components94.__experimentalVStack, { spacing: "3", children: [
/* @__PURE__ */ (0, import_jsx_runtime234.jsx)(
import_components94.TextControl,
{
__next40pxDefaultSize: true,
value: editedBlockName ?? blockName,
label: (0, import_i18n87.__)("Name"),
help: hasOverridesWarning ? (0, import_i18n87.__)(
"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_runtime234.jsxs)(import_components94.__experimentalHStack, { justify: "right", children: [
/* @__PURE__ */ (0, import_jsx_runtime234.jsx)(
import_components94.Button,
{
__next40pxDefaultSize: true,
variant: "tertiary",
onClick: onClose,
children: (0, import_i18n87.__)("Cancel")
}
),
/* @__PURE__ */ (0, import_jsx_runtime234.jsx)(
import_components94.Button,
{
__next40pxDefaultSize: true,
accessibleWhenDisabled: true,
disabled: !isNameValid,
variant: "primary",
type: "submit",
children: (0, import_i18n87.__)("Save")
}
)
] })
] })
}
)
}
);
}
// packages/block-editor/build-module/components/block-rename/rename-control.mjs
var import_jsx_runtime235 = __toESM(require_jsx_runtime(), 1);
function BlockRenameControl({ clientId }) {
const [renamingBlock, setRenamingBlock] = (0, import_element112.useState)(false);
return /* @__PURE__ */ (0, import_jsx_runtime235.jsxs)(import_jsx_runtime235.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime235.jsx)(
import_components95.MenuItem,
{
onClick: () => {
setRenamingBlock(true);
},
"aria-expanded": renamingBlock,
"aria-haspopup": "dialog",
children: (0, import_i18n88.__)("Rename")
}
),
renamingBlock && /* @__PURE__ */ (0, import_jsx_runtime235.jsx)(
BlockRenameModal,
{
clientId,
onClose: () => setRenamingBlock(false)
}
)
] });
}
// packages/block-editor/build-module/components/block-rename/use-block-rename.mjs
var import_blocks59 = __toESM(require_blocks(), 1);
function useBlockRename(name) {
return {
canRename: (0, import_blocks59.getBlockSupport)(name, "renaming", true)
};
}
// packages/block-editor/build-module/components/block-settings-menu-controls/edit-section-menu-item.mjs
var import_components96 = __toESM(require_components(), 1);
var import_i18n89 = __toESM(require_i18n(), 1);
var import_data103 = __toESM(require_data(), 1);
var import_blocks60 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/hooks/use-content-only-section-edit.mjs
var import_data102 = __toESM(require_data(), 1);
function useContentOnlySectionEdit(clientId) {
const {
isSectionBlock: isSectionBlock2,
isWithinSection,
isWithinEditedSection,
isEditingContentOnlySection,
editedContentOnlySection: editedContentOnlySection2
} = (0, import_data102.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_data102.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-settings-menu-controls/edit-section-menu-item.mjs
var import_jsx_runtime236 = __toESM(require_jsx_runtime(), 1);
function EditSectionMenuItem({ clientId, onClose }) {
const {
isSectionBlock: isSectionBlock2,
isEditingContentOnlySection,
editContentOnlySection: editContentOnlySection2
} = useContentOnlySectionEdit(clientId);
const { block, onNavigateToEntityRecord } = (0, import_data103.useSelect)(
(select3) => {
const { getBlock: getBlock2, getSettings: getSettings8 } = select3(store);
return {
block: getBlock2(clientId),
onNavigateToEntityRecord: getSettings8().onNavigateToEntityRecord
};
},
[clientId]
);
if (!window?.__experimentalContentOnlyPatternInsertion || !isSectionBlock2 || isEditingContentOnlySection) {
return null;
}
const blockAttributes = block?.attributes || {};
const isSyncedPattern = (0, import_blocks60.isReusableBlock)(block);
const isTemplatePartBlock = (0, import_blocks60.isTemplatePart)(block);
const shouldNavigateToIsolatedEditor = (isSyncedPattern || isTemplatePartBlock) && onNavigateToEntityRecord;
const handleClick = () => {
if (shouldNavigateToIsolatedEditor) {
if (isSyncedPattern) {
onNavigateToEntityRecord({
postId: blockAttributes.ref,
postType: "wp_block"
});
} else if (isTemplatePartBlock) {
const { theme, slug } = blockAttributes;
const templatePartId = theme && slug ? `${theme}//${slug}` : null;
if (templatePartId) {
onNavigateToEntityRecord({
postId: templatePartId,
postType: "wp_template_part"
});
}
}
} else {
editContentOnlySection2(clientId);
}
onClose();
};
return /* @__PURE__ */ (0, import_jsx_runtime236.jsx)(import_components96.MenuItem, { onClick: handleClick, children: (0, import_i18n89._x)("Edit section", "Editing a section in the Editor") });
}
// packages/block-editor/build-module/components/block-settings-menu-controls/index.mjs
var import_jsx_runtime237 = __toESM(require_jsx_runtime(), 1);
var { Fill, Slot: Slot4 } = (0, import_components97.createSlotFill)("BlockSettingsMenuControls");
var BlockSettingsMenuControlsSlot = ({ fillProps, clientIds = null }) => {
const {
selectedBlocks,
selectedClientIds,
isContentOnly,
canToggleSelectedBlocksVisibility
} = (0, import_data104.useSelect)(
(select3) => {
const {
getBlocksByClientId: getBlocksByClientId2,
getBlockNamesByClientId: getBlockNamesByClientId2,
getSelectedBlockClientIds: getSelectedBlockClientIds2,
getBlockEditingMode: getBlockEditingMode2
} = 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_blocks61.hasBlockSupport)(block.name, "visibility", true)
)
};
},
[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_runtime237.jsx)(
Slot4,
{
fillProps: {
...fillProps,
selectedBlocks,
selectedClientIds
},
children: (fills) => {
if (!fills?.length > 0 && !showConvertToGroupButton && !showLockButton) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime237.jsxs)(import_components97.MenuGroup, { children: [
showConvertToGroupButton && /* @__PURE__ */ (0, import_jsx_runtime237.jsx)(
ConvertToGroupButton,
{
...convertToGroupButtonProps,
onClose: fillProps?.onClose
}
),
selectedClientIds.length === 1 && /* @__PURE__ */ (0, import_jsx_runtime237.jsx)(
EditSectionMenuItem,
{
clientId: selectedClientIds[0],
onClose: fillProps?.onClose
}
),
showLockButton && /* @__PURE__ */ (0, import_jsx_runtime237.jsx)(
BlockLockMenuItem,
{
clientId: selectedClientIds[0]
}
),
showRenameButton && /* @__PURE__ */ (0, import_jsx_runtime237.jsx)(
BlockRenameControl,
{
clientId: selectedClientIds[0]
}
),
showVisibilityButton && /* @__PURE__ */ (0, import_jsx_runtime237.jsx)(
BlockVisibilityMenuItem2,
{
clientIds: selectedClientIds
}
),
fills,
selectedClientIds.length === 1 && /* @__PURE__ */ (0, import_jsx_runtime237.jsx)(
ModifyContentOnlySectionMenuItem,
{
clientId: selectedClientIds[0],
onClose: fillProps?.onClose
}
),
fillProps?.count === 1 && !isContentOnly && /* @__PURE__ */ (0, import_jsx_runtime237.jsx)(
BlockModeToggle,
{
clientId: fillProps?.firstBlockClientId,
onToggle: fillProps?.onClose
}
)
] });
}
}
);
};
function BlockSettingsMenuControls({ ...props }) {
return /* @__PURE__ */ (0, import_jsx_runtime237.jsx)(import_components97.__experimentalStyleProvider, { document, children: /* @__PURE__ */ (0, import_jsx_runtime237.jsx)(Fill, { ...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_element113 = __toESM(require_element(), 1);
var import_components98 = __toESM(require_components(), 1);
var import_compose62 = __toESM(require_compose(), 1);
var import_data105 = __toESM(require_data(), 1);
var import_i18n90 = __toESM(require_i18n(), 1);
var import_jsx_runtime238 = __toESM(require_jsx_runtime(), 1);
function BlockParentSelectorMenuItem({
parentClientId,
parentBlockType
}) {
const isSmallViewport = (0, import_compose62.useViewportMatch)("medium", "<");
const { selectBlock: selectBlock2 } = (0, import_data105.useDispatch)(store);
const menuItemRef = (0, import_element113.useRef)();
const gesturesProps = useShowHoveredOrFocusedGestures({
ref: menuItemRef,
highlightParent: true
});
if (!isSmallViewport) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime238.jsx)(
import_components98.MenuItem,
{
...gesturesProps,
ref: menuItemRef,
icon: /* @__PURE__ */ (0, import_jsx_runtime238.jsx)(block_icon_default, { icon: parentBlockType.icon }),
onClick: () => selectBlock2(parentClientId),
children: (0, import_i18n90.sprintf)(
/* translators: %s: Name of the block's parent. */
(0, import_i18n90.__)("Select parent block (%s)"),
parentBlockType.title
)
}
);
}
// packages/block-editor/build-module/components/block-settings-menu/block-settings-dropdown.mjs
var import_jsx_runtime239 = __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_data106.useSelect)(store);
const { removeBlocks: removeBlocks2 } = (0, import_data106.useDispatch)(store);
const notifyCopy = useNotifyCopy();
const ref = (0, import_compose63.useCopyToClipboard)(
() => (0, import_blocks62.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_i18n91.__)("Copy");
return /* @__PURE__ */ (0, import_jsx_runtime239.jsx)(import_components99.MenuItem, { ref, shortcut, children: copyMenuItemLabel });
}
function BlockSettingsDropdown({
block,
clientIds,
children,
__experimentalSelectBlock,
...props
}) {
const count = clientIds.length;
const firstBlockClientId = clientIds[0];
const {
firstParentClientId,
parentBlockType,
previousBlockClientId,
selectedBlockClientIds,
isContentOnly,
isZoomOut: isZoomOut2
} = (0, import_data106.useSelect)(
(select3) => {
const {
getBlockName: getBlockName2,
getBlockRootClientId: getBlockRootClientId2,
getPreviousBlockClientId: getPreviousBlockClientId2,
getSelectedBlockClientIds: getSelectedBlockClientIds22,
getBlockAttributes: getBlockAttributes3,
getBlockEditingMode: getBlockEditingMode2,
isZoomOut: _isZoomOut
} = unlock(select3(store));
const { getActiveBlockVariation } = select3(import_blocks62.store);
const _firstParentClientId = getBlockRootClientId2(firstBlockClientId);
const parentBlockName = _firstParentClientId && getBlockName2(_firstParentClientId);
return {
firstParentClientId: _firstParentClientId,
parentBlockType: _firstParentClientId && (getActiveBlockVariation(
parentBlockName,
getBlockAttributes3(_firstParentClientId)
) || (0, import_blocks62.getBlockType)(parentBlockName)),
previousBlockClientId: getPreviousBlockClientId2(firstBlockClientId),
selectedBlockClientIds: getSelectedBlockClientIds22(),
isContentOnly: getBlockEditingMode2(firstBlockClientId) === "contentOnly",
isZoomOut: _isZoomOut()
};
},
[firstBlockClientId]
);
const { getBlockOrder: getBlockOrder2, getSelectedBlockClientIds: getSelectedBlockClientIds2 } = (0, import_data106.useSelect)(store);
const shortcuts = (0, import_data106.useSelect)((select3) => {
const { getShortcutRepresentation } = select3(import_keyboard_shortcuts6.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_runtime239.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_runtime239.jsx)(
import_components99.DropdownMenu,
{
icon: more_vertical_default,
label: (0, import_i18n91.__)("Options"),
className: "block-editor-block-settings-menu",
popoverProps: POPOVER_PROPS4,
noIcons: true,
...props,
children: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime239.jsxs)(import_jsx_runtime239.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime239.jsxs)(import_components99.MenuGroup, { children: [
/* @__PURE__ */ (0, import_jsx_runtime239.jsx)(
block_settings_menu_first_item_default.Slot,
{
fillProps: { onClose }
}
),
shouldShowBlockParentMenuItem && /* @__PURE__ */ (0, import_jsx_runtime239.jsx)(
BlockParentSelectorMenuItem,
{
parentClientId: firstParentClientId,
parentBlockType
}
),
count === 1 && /* @__PURE__ */ (0, import_jsx_runtime239.jsx)(
block_html_convert_button_default,
{
clientId: firstBlockClientId
}
),
!isContentOnly && /* @__PURE__ */ (0, import_jsx_runtime239.jsx)(
CopyMenuItem,
{
clientIds,
onCopy,
shortcut: shortcuts.copy
}
),
!isContentOnly && /* @__PURE__ */ (0, import_jsx_runtime239.jsx)(
CopyMenuItem,
{
clientIds,
label: (0, import_i18n91.__)("Cut"),
eventType: "cut",
shortcut: shortcuts.cut,
__experimentalUpdateSelection: !__experimentalSelectBlock
}
),
canDuplicate && /* @__PURE__ */ (0, import_jsx_runtime239.jsx)(
import_components99.MenuItem,
{
onClick: (0, import_compose63.pipe)(
onClose,
onDuplicate,
updateSelectionAfterDuplicate
),
shortcut: shortcuts.duplicate,
children: (0, import_i18n91.__)("Duplicate")
}
),
canInsertBlock && !isZoomOut2 && /* @__PURE__ */ (0, import_jsx_runtime239.jsxs)(import_jsx_runtime239.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime239.jsx)(
import_components99.MenuItem,
{
onClick: (0, import_compose63.pipe)(
onClose,
onInsertBefore
),
shortcut: shortcuts.insertBefore,
children: (0, import_i18n91.__)("Add before")
}
),
/* @__PURE__ */ (0, import_jsx_runtime239.jsx)(
import_components99.MenuItem,
{
onClick: (0, import_compose63.pipe)(
onClose,
onInsertAfter
),
shortcut: shortcuts.insertAfter,
children: (0, import_i18n91.__)("Add after")
}
)
] }),
count === 1 && /* @__PURE__ */ (0, import_jsx_runtime239.jsx)(
block_comment_icon_slot_default.Slot,
{
fillProps: {
clientId: firstBlockClientId,
onClose
}
}
)
] }),
canCopyStyles && !isContentOnly && /* @__PURE__ */ (0, import_jsx_runtime239.jsxs)(import_components99.MenuGroup, { children: [
/* @__PURE__ */ (0, import_jsx_runtime239.jsx)(
CopyMenuItem,
{
clientIds,
onCopy,
label: (0, import_i18n91.__)("Copy styles"),
eventType: "copyStyles"
}
),
/* @__PURE__ */ (0, import_jsx_runtime239.jsx)(import_components99.MenuItem, { onClick: onPasteStyles, children: (0, import_i18n91.__)("Paste styles") })
] }),
!isContentOnly && /* @__PURE__ */ (0, import_jsx_runtime239.jsx)(
block_settings_menu_controls_default.Slot,
{
fillProps: {
onClose,
count,
firstBlockClientId
},
clientIds
}
),
typeof children === "function" ? children({ onClose }) : import_element114.Children.map(
(child) => (0, import_element114.cloneElement)(child, { onClose })
),
canRemove && /* @__PURE__ */ (0, import_jsx_runtime239.jsx)(import_components99.MenuGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime239.jsx)(
import_components99.MenuItem,
{
onClick: (0, import_compose63.pipe)(
onClose,
onRemove,
updateSelectionAfterRemove
),
shortcut: shortcuts.remove,
children: (0, import_i18n91.__)("Delete")
}
) })
] })
}
);
}
}
);
}
var block_settings_dropdown_default = BlockSettingsDropdown;
// packages/block-editor/build-module/components/collab/block-comment-icon-toolbar-slot.mjs
var import_components100 = __toESM(require_components(), 1);
var CommentIconToolbarSlotFill = (0, import_components100.createSlotFill)(
/* @__PURE__ */ Symbol("CommentIconToolbarSlotFill")
);
var block_comment_icon_toolbar_slot_default = CommentIconToolbarSlotFill;
// packages/block-editor/build-module/components/block-settings-menu/index.mjs
var import_jsx_runtime240 = __toESM(require_jsx_runtime(), 1);
function BlockSettingsMenu({ clientIds, ...props }) {
return /* @__PURE__ */ (0, import_jsx_runtime240.jsxs)(import_components101.ToolbarGroup, { children: [
/* @__PURE__ */ (0, import_jsx_runtime240.jsx)(block_comment_icon_toolbar_slot_default.Slot, {}),
/* @__PURE__ */ (0, import_jsx_runtime240.jsx)(import_components101.ToolbarItem, { children: (toggleProps) => /* @__PURE__ */ (0, import_jsx_runtime240.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_components102 = __toESM(require_components(), 1);
var import_i18n92 = __toESM(require_i18n(), 1);
var import_data107 = __toESM(require_data(), 1);
var import_jsx_runtime241 = __toESM(require_jsx_runtime(), 1);
function BlockEditVisuallyButton({ clientIds }) {
const clientId = clientIds.length === 1 ? clientIds[0] : void 0;
const canEditVisually = (0, import_data107.useSelect)(
(select3) => !!clientId && select3(store).getBlockMode(clientId) === "html",
[clientId]
);
const { toggleBlockMode: toggleBlockMode2 } = (0, import_data107.useDispatch)(store);
if (!canEditVisually) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime241.jsx)(import_components102.ToolbarGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime241.jsx)(
import_components102.ToolbarButton,
{
onClick: () => {
toggleBlockMode2(clientId);
},
children: (0, import_i18n92.__)("Edit visually")
}
) });
}
// packages/block-editor/build-module/components/navigable-toolbar/index.mjs
var import_components103 = __toESM(require_components(), 1);
var import_element115 = __toESM(require_element(), 1);
var import_data108 = __toESM(require_data(), 1);
var import_deprecated12 = __toESM(require_deprecated(), 1);
var import_dom27 = __toESM(require_dom(), 1);
var import_keyboard_shortcuts7 = __toESM(require_keyboard_shortcuts(), 1);
var import_keycodes10 = __toESM(require_keycodes(), 1);
var import_jsx_runtime242 = __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_dom27.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_element115.useState)(
initialAccessibleToolbarState
);
const determineIsAccessibleToolbar = (0, import_element115.useCallback)(() => {
const tabbables = import_dom27.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_element115.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_element115.useState)(focusOnMount);
const [initialIndex] = (0, import_element115.useState)(defaultIndex);
const focusToolbar = (0, import_element115.useCallback)(() => {
focusFirstTabbableIn(toolbarRef.current);
}, [toolbarRef]);
const focusToolbarViaShortcut = () => {
if (shouldUseKeyboardFocusShortcut) {
focusToolbar();
}
};
(0, import_keyboard_shortcuts7.useShortcut)("core/block-editor/focus-toolbar", focusToolbarViaShortcut);
(0, import_element115.useEffect)(() => {
if (initialFocusOnMount) {
focusToolbar();
}
}, [isAccessibleToolbar, initialFocusOnMount, focusToolbar]);
(0, import_element115.useEffect)(() => {
const navigableToolbarRef = toolbarRef.current;
let raf2 = 0;
if (!initialFocusOnMount && !hasFocusWithin(navigableToolbarRef)) {
raf2 = window.requestAnimationFrame(() => {
const items = getAllFocusableToolbarItemsIn(navigableToolbarRef);
const index = initialIndex || 0;
if (items[index] && hasFocusWithin(navigableToolbarRef)) {
items[index].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 index = items.findIndex((item) => item.tabIndex === 0);
onIndexChange(index);
};
}, [initialIndex, initialFocusOnMount, onIndexChange, toolbarRef]);
const { getLastFocus: getLastFocus2 } = unlock((0, import_data108.useSelect)(store));
(0, import_element115.useEffect)(() => {
const navigableToolbarRef = toolbarRef.current;
if (focusEditorOnEscape) {
const handleKeyDown = (event) => {
const lastFocus2 = getLastFocus2();
if (event.keyCode === import_keycodes10.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_element115.useRef)();
const isAccessibleToolbar = useIsAccessibleToolbar(toolbarRef);
useToolbarFocus({
toolbarRef,
focusOnMount,
defaultIndex: initialIndex,
onIndexChange,
isAccessibleToolbar,
shouldUseKeyboardFocusShortcut,
focusEditorOnEscape
});
if (isAccessibleToolbar) {
return /* @__PURE__ */ (0, import_jsx_runtime242.jsx)(
import_components103.Toolbar,
{
label: props["aria-label"],
ref: toolbarRef,
orientation,
...props,
children
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime242.jsx)(
import_components103.NavigableMenu,
{
orientation,
role: "toolbar",
ref: toolbarRef,
...props,
children
}
);
}
// packages/block-editor/build-module/components/block-toolbar/use-has-block-toolbar.mjs
var import_data109 = __toESM(require_data(), 1);
var import_blocks63 = __toESM(require_blocks(), 1);
function useHasBlockToolbar() {
const enabled = (0, import_data109.useSelect)((select3) => {
const { getBlockEditingMode: getBlockEditingMode2, getBlockName: getBlockName2, getBlockSelectionStart: getBlockSelectionStart2 } = select3(store);
const selectedBlockClientId = getBlockSelectionStart2();
const blockType = selectedBlockClientId && (0, import_blocks63.getBlockType)(getBlockName2(selectedBlockClientId));
return blockType && (0, import_blocks63.hasBlockSupport)(blockType, "__experimentalToolbar", true) && getBlockEditingMode2(selectedBlockClientId) !== "disabled";
}, []);
return enabled;
}
// packages/block-editor/build-module/components/block-toolbar/change-design.mjs
var import_components104 = __toESM(require_components(), 1);
var import_i18n93 = __toESM(require_i18n(), 1);
var import_blocks64 = __toESM(require_blocks(), 1);
var import_element116 = __toESM(require_element(), 1);
var import_data110 = __toESM(require_data(), 1);
var import_jsx_runtime243 = __toESM(require_jsx_runtime(), 1);
var EMPTY_ARRAY8 = [];
var MAX_PATTERNS_TO_SHOW = 6;
var POPOVER_PROPS5 = {
placement: "bottom-start"
};
function ChangeDesign({ clientId }) {
const { categories, currentPatternName, patterns } = (0, import_data110.useSelect)(
(select3) => {
const {
getBlockAttributes: getBlockAttributes3,
getBlockRootClientId: getBlockRootClientId2,
__experimentalGetAllowedPatterns: __experimentalGetAllowedPatterns2
} = select3(store);
const attributes = getBlockAttributes3(clientId);
const _categories = attributes?.metadata?.categories || EMPTY_ARRAY8;
const rootBlock = getBlockRootClientId2(clientId);
const _patterns = _categories.length > 0 ? __experimentalGetAllowedPatterns2(rootBlock) : EMPTY_ARRAY8;
return {
categories: _categories,
currentPatternName: attributes?.metadata?.patternName,
patterns: _patterns
};
},
[clientId]
);
const { replaceBlocks: replaceBlocks2 } = (0, import_data110.useDispatch)(store);
const sameCategoryPatternsWithSingleWrapper = (0, import_element116.useMemo)(() => {
if (categories.length === 0 || !patterns || patterns.length === 0) {
return EMPTY_ARRAY8;
}
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_blocks64.cloneBlock)(block);
});
newBlocks[0].attributes.metadata = {
...newBlocks[0].attributes.metadata,
categories
};
replaceBlocks2(clientId, newBlocks);
};
return /* @__PURE__ */ (0, import_jsx_runtime243.jsx)(
import_components104.Dropdown,
{
popoverProps: POPOVER_PROPS5,
renderToggle: ({ onToggle, isOpen }) => {
return /* @__PURE__ */ (0, import_jsx_runtime243.jsx)(import_components104.ToolbarGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime243.jsx)(
import_components104.ToolbarButton,
{
onClick: () => onToggle(!isOpen),
"aria-expanded": isOpen,
children: (0, import_i18n93.__)("Change design")
}
) });
},
renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime243.jsx)(
import_components104.__experimentalDropdownContentWrapper,
{
className: "block-editor-block-toolbar-change-design-content-wrapper",
paddingSize: "none",
children: /* @__PURE__ */ (0, import_jsx_runtime243.jsx)(
block_patterns_list_default,
{
blockPatterns: sameCategoryPatternsWithSingleWrapper,
onClickPattern,
showTitlesAsTooltip: true
}
)
}
)
}
);
}
// packages/block-editor/build-module/components/block-toolbar/switch-section-style.mjs
var import_components105 = __toESM(require_components(), 1);
var import_i18n95 = __toESM(require_i18n(), 1);
var import_data114 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/block-styles/use-styles-for-block.mjs
var import_data111 = __toESM(require_data(), 1);
var import_blocks65 = __toESM(require_blocks(), 1);
var import_element117 = __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_i18n94 = __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_i18n94._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_element117.useMemo)(() => {
const example = type?.example;
const blockName = type?.name;
if (example && blockName) {
return (0, import_blocks65.getBlockFromExample)(blockName, {
attributes: example.attributes,
innerBlocks: example.innerBlocks
});
}
if (block) {
return (0, import_blocks65.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_blocks65.getBlockType)(block2.name);
const { getBlockStyles: getBlockStyles2 } = select3(import_blocks65.store);
return {
block: !blockType2?.example ? block2 : null,
blockType: blockType2,
styles: getBlockStyles2(block2.name),
className: block2.attributes.className || ""
};
};
const { styles, block, blockType, className } = (0, import_data111.useSelect)(selector3, [
clientId
]);
const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data111.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_data113 = __toESM(require_data(), 1);
var import_element118 = __toESM(require_element(), 1);
// packages/global-styles-engine/build-module/utils/object.mjs
function setImmutably2(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 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/global-styles-engine/build-module/utils/common.mjs
var import_style_engine2 = __toESM(require_style_engine(), 1);
// packages/global-styles-engine/build-module/utils/fluid.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 || !fontSizeParsed?.value) {
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.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: roundToPrecision2(returnValue, 3),
unit
};
}
function roundToPrecision2(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 = getTypographyValueAndUnit2(
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 = getComputedFluidTypographyValue2({
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";
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 }) => size,
classes: []
},
{
path: ["border", "radiusSizes"],
valueKey: "size",
cssVarInfix: "border-radius",
classes: []
},
{
path: ["dimensions", "dimensionSizes"],
valueKey: "size",
cssVarInfix: "dimension",
classes: []
}
];
function scopeSelector2(scope, selector3) {
if (!scope || !selector3) {
return selector3;
}
const scopes = scope.split(",");
const selectors = selector3.split(",");
const selectorsScoped = [];
scopes.forEach((outer) => {
selectors.forEach((inner) => {
selectorsScoped.push(`${outer.trim()} ${inner.trim()}`);
});
});
return selectorsScoped.join(", ");
}
function scopeFeatureSelectors(scope, selectors) {
if (!scope || !selectors) {
return;
}
const featureSelectors = {};
Object.entries(selectors).forEach(([feature, selector3]) => {
if (typeof selector3 === "string") {
featureSelectors[feature] = scopeSelector2(scope, selector3);
}
if (typeof selector3 === "object") {
featureSelectors[feature] = {};
Object.entries(selector3).forEach(
([subfeature, subfeatureSelector]) => {
featureSelectors[feature][subfeature] = scopeSelector2(
scope,
subfeatureSelector
);
}
);
}
});
return featureSelectors;
}
function appendToSelector(selector3, toAppend) {
if (!selector3.includes(",")) {
return selector3 + toAppend;
}
const selectors = selector3.split(",");
const newSelectors = selectors.map((sel) => sel + toAppend);
return newSelectors.join(",");
}
function getBlockStyleVariationSelector(variation, blockSelector) {
const variationClass = `.is-style-${variation}`;
if (!blockSelector) {
return variationClass;
}
const ancestorRegex = /((?::\([^)]+\))?\s*)([^\s:]+)/;
const addVariationClass = (_match, group1, group2) => {
return group1 + group2 + variationClass;
};
const result = blockSelector.split(",").map((part) => part.replace(ancestorRegex, addVariationClass));
return result.join(",");
}
function getResolvedRefValue(ruleValue, tree) {
if (!ruleValue || !tree) {
return ruleValue;
}
if (typeof ruleValue === "object" && "ref" in ruleValue && ruleValue?.ref) {
const resolvedRuleValue = (0, import_style_engine2.getCSSValueFromRawStyle)(
getValueFromObjectPath2(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 ? getValueFromObjectPath2(settings2, [
"blocks",
blockName,
...presetPath
]) : void 0,
getValueFromObjectPath2(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 ? getValueFromObjectPath2(features?.settings ?? {}, [
"blocks",
blockName,
"custom",
...path
]) : void 0) ?? getValueFromObjectPath2(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 = getValueFromObjectPath2(
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/core/render.mjs
var import_blocks66 = __toESM(require_blocks(), 1);
var import_style_engine3 = __toESM(require_style_engine(), 1);
var import_data112 = __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, supports } = blockType;
const hasSelectors = selectors && Object.keys(selectors).length > 0;
const path = Array.isArray(target) ? target.join(".") : target;
let rootSelector = null;
if (hasSelectors && selectors.root) {
rootSelector = selectors?.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 = getValueFromObjectPath2(
selectors,
`${path}.root`,
null
) || getValueFromObjectPath2(selectors, path, null);
return featureSelector2 || fallbackSelector;
}
const featureSelector = supports ? getValueFromObjectPath2(
supports,
`${path}.__experimentalSelector`,
null
) : void 0;
if (!featureSelector) {
return fallbackSelector;
}
return scopeSelector2(rootSelector, featureSelector);
}
let subfeatureSelector;
if (hasSelectors) {
subfeatureSelector = getValueFromObjectPath2(selectors, 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 kebabCase4(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 getSpacingPresetCssVar2(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 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/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_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/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"
};
function getPresetsClasses(blockSelector = "*", blockPresets = {}) {
return PRESET_METADATA.reduce(
(declarations, { path, cssVarInfix, classes }) => {
if (!classes) {
return declarations;
}
const presetByOrigin = getValueFromObjectPath2(
blockPresets,
path,
[]
);
["default", "theme", "custom"].forEach((origin) => {
if (presetByOrigin[origin]) {
presetByOrigin[origin].forEach(
({ slug }) => {
classes.forEach(
({
classSuffix,
propertyName
}) => {
const classSelectorToUse = `.has-${kebabCase4(
slug
)}-${classSuffix}`;
const selectorToUse = blockSelector.split(",").map(
(selector3) => `${selector3}${classSelectorToUse}`
).join(",");
const value = `var(--wp--preset--${cssVarInfix}--${kebabCase4(
slug
)})`;
declarations += `${selectorToUse}{${propertyName}: ${value} !important;}`;
}
);
}
);
}
});
return declarations;
},
""
);
}
function concatFeatureVariationSelectorString(featureSelector, styleVariationSelector) {
const featureSelectors = featureSelector.split(",");
const combinedSelectors = [];
featureSelectors.forEach((selector3) => {
combinedSelectors.push(
`${styleVariationSelector.trim()}${selector3.trim()}`
);
});
return combinedSelectors.join(", ");
}
var getFeatureDeclarations = (selectors, styles) => {
const declarations = {};
Object.entries(selectors).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_blocks66.__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 = getValueFromObjectPath2(
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 (!getValueFromObjectPath2(styleValue, [prop], false)) {
return;
}
const cssProperty = name.startsWith("--") ? name : kebabCase4(name);
declarations.push(
`${cssProperty}: ${(0, import_style_engine3.getCSSValueFromRawStyle)(
getValueFromObjectPath2(styleValue, [prop])
)}`
);
});
} else if (getValueFromObjectPath2(blockStyles, pathToValue, false)) {
const cssProperty = key.startsWith("--") ? key : kebabCase4(key);
declarations.push(
`${cssProperty}: ${(0, import_style_engine3.getCSSValueFromRawStyle)(
getValueFromObjectPath2(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_engine3.getCSSRules)(blockStyles);
extraRules.forEach((rule) => {
if (isRoot && (useRootPaddingAlign || disableRootPadding) && rule.key.startsWith("padding")) {
return;
}
const cssProperty = rule.key.startsWith("--") ? rule.key : kebabCase4(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_DEFINITIONS2,
style,
selector: selector3,
hasBlockGapSupport,
hasFallbackGapSupport,
fallbackGapValue
}) {
let ruleset = "";
let gapValue = hasBlockGapSupport ? getGapCSSValue2(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) {
if (!treeToPickFrom) {
return {};
}
const entries = Object.entries(treeToPickFrom);
const pickedEntries = entries.filter(
([key]) => STYLE_KEYS.includes(key)
);
const clonedEntries = pickedEntries.map(([key, style]) => [
key,
JSON.parse(JSON.stringify(style))
]);
return Object.fromEntries(clonedEntries);
}
var getNodesWithStyles = (tree, blockSelectors) => {
const nodes = [];
if (!tree?.styles) {
return nodes;
}
const styles = pickStyleKeys(tree.styles);
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_blocks66.__EXPERIMENTAL_ELEMENTS).forEach(([name, selector3]) => {
if (tree.styles?.elements?.[name]) {
nodes.push({
styles: tree.styles?.elements?.[name] ?? {},
selector: selector3,
// 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 = pickStyleKeys(node);
const typedNode = node;
if (typedNode?.variations) {
const variations = {};
Object.entries(typedNode.variations).forEach(
([variationName, variation]) => {
const typedVariation = variation;
variations[variationName] = pickStyleKeys(typedVariation);
if (typedVariation?.css) {
variations[variationName].css = typedVariation.css;
}
const variationSelector = typeof blockSelectors !== "string" ? blockSelectors[blockName]?.styleVariationSelectors?.[variationName] : void 0;
Object.entries(
typedVariation?.elements ?? {}
).forEach(([element, elementStyles]) => {
if (elementStyles && import_blocks66.__EXPERIMENTAL_ELEMENTS[element]) {
nodes.push({
styles: elementStyles,
selector: scopeSelector2(
variationSelector,
import_blocks66.__EXPERIMENTAL_ELEMENTS[element]
)
});
}
});
Object.entries(typedVariation?.blocks ?? {}).forEach(
([
variationBlockName,
variationBlockStyles
]) => {
const variationBlockSelector = typeof blockSelectors !== "string" ? scopeSelector2(
variationSelector,
blockSelectors[variationBlockName]?.selector
) : void 0;
const variationDuotoneSelector = typeof blockSelectors !== "string" ? scopeSelector2(
variationSelector,
blockSelectors[variationBlockName]?.duotoneSelector
) : void 0;
const variationFeatureSelectors = typeof blockSelectors !== "string" ? scopeFeatureSelectors(
variationSelector,
blockSelectors[variationBlockName]?.featureSelectors ?? {}
) : void 0;
const variationBlockStyleNodes = pickStyleKeys(variationBlockStyles);
if (variationBlockStyles?.css) {
variationBlockStyleNodes.css = variationBlockStyles.css;
}
if (!variationBlockSelector || typeof blockSelectors === "string") {
return;
}
nodes.push({
selector: variationBlockSelector,
duotoneSelector: variationDuotoneSelector,
featureSelectors: variationFeatureSelectors,
fallbackGapValue: blockSelectors[variationBlockName]?.fallbackGapValue,
hasLayoutSupport: blockSelectors[variationBlockName]?.hasLayoutSupport,
styles: variationBlockStyleNodes
});
Object.entries(
variationBlockStyles.elements ?? {}
).forEach(
([
variationBlockElement,
variationBlockElementStyles
]) => {
if (variationBlockElementStyles && import_blocks66.__EXPERIMENTAL_ELEMENTS[variationBlockElement]) {
nodes.push({
styles: variationBlockElementStyles,
selector: scopeSelector2(
variationBlockSelector,
import_blocks66.__EXPERIMENTAL_ELEMENTS[variationBlockElement]
)
});
}
}
);
}
);
}
);
blockStyles.variations = variations;
}
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,
styleVariationSelectors: blockSelectors[blockName].styleVariationSelectors
});
}
Object.entries(typedNode?.elements ?? {}).forEach(
([elementName, value]) => {
if (typeof blockSelectors !== "string" && value && blockSelectors?.[blockName] && import_blocks66.__EXPERIMENTAL_ELEMENTS[elementName]) {
nodes.push({
styles: value,
selector: blockSelectors[blockName]?.selector.split(",").map((sel) => {
const elementSelectors = import_blocks66.__EXPERIMENTAL_ELEMENTS[elementName].split(",");
return elementSelectors.map(
(elementSelector) => sel + " " + elementSelector
);
}).join(",")
});
}
}
);
}
);
return nodes;
};
var getNodesWithSettings = (tree, blockSelectors) => {
const nodes = [];
if (!tree?.settings) {
return nodes;
}
const pickPresets = (treeToPickFrom) => {
let presets2 = {};
PRESET_METADATA.forEach(({ path }) => {
const value = getValueFromObjectPath2(treeToPickFrom, path, false);
if (value !== false) {
presets2 = setImmutably2(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
});
}
}
);
return nodes;
};
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 nodesWithStyles = getNodesWithStyles(tree, blockSelectors);
const nodesWithSettings = getNodesWithSettings(tree, blockSelectors);
const useRootPaddingAlign = tree?.settings?.useRootPaddingAwareAlignments;
const { contentSize, wideSize } = tree?.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) {
nodesWithStyles.forEach(
({
selector: selector3,
duotoneSelector,
styles,
fallbackGapValue,
hasLayoutSupport: hasLayoutSupport2,
featureSelectors,
styleVariationSelectors,
skipSelectorWrapper
}) => {
if (featureSelectors) {
const featureDeclarations = getFeatureDeclarations(
featureSelectors,
styles
);
Object.entries(featureDeclarations).forEach(
([cssSelector, declarations]) => {
if (declarations.length) {
const rules = declarations.join(";");
ruleset += `:root :where(${cssSelector}){${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(
";"
)};}`;
}
}
if (!disableLayoutStyles && (ROOT_BLOCK_SELECTOR === selector3 || hasLayoutSupport2)) {
ruleset += getLayoutStyles({
style: styles,
selector: selector3,
hasBlockGapSupport,
hasFallbackGapSupport,
fallbackGapValue
});
}
const styleDeclarations = getStylesDeclarations(
styles,
selector3,
useRootPaddingAlign,
tree,
disableRootPadding
);
if (styleDeclarations?.length) {
const generalSelector = skipSelectorWrapper ? selector3 : `:root :where(${selector3})`;
ruleset += `${generalSelector}{${styleDeclarations.join(
";"
)};}`;
}
if (styles?.css) {
ruleset += processCSSNesting(
styles.css,
`:root :where(${selector3})`
);
}
if (options.variationStyles && styleVariationSelectors) {
Object.entries(styleVariationSelectors).forEach(
([styleVariationName, styleVariationSelector]) => {
const styleVariations = styles?.variations?.[styleVariationName];
if (styleVariations) {
if (featureSelectors) {
const featureDeclarations = getFeatureDeclarations(
featureSelectors,
styleVariations
);
Object.entries(
featureDeclarations
).forEach(
([baseSelector, declarations]) => {
if (declarations.length) {
const cssSelector = concatFeatureVariationSelectorString(
baseSelector,
styleVariationSelector
);
const rules = declarations.join(";");
ruleset += `:root :where(${cssSelector}){${rules};}`;
}
}
);
}
const styleVariationDeclarations = getStylesDeclarations(
styleVariations,
styleVariationSelector,
useRootPaddingAlign,
tree
);
if (styleVariationDeclarations.length) {
ruleset += `:root :where(${styleVariationSelector}){${styleVariationDeclarations.join(
";"
)};}`;
}
if (styleVariations?.css) {
ruleset += processCSSNesting(
styleVariations.css,
`:root :where(${styleVariationSelector})`
);
}
}
}
);
}
const pseudoSelectorStyles = Object.entries(styles).filter(
([key]) => key.startsWith(":")
);
if (pseudoSelectorStyles?.length) {
pseudoSelectorStyles.forEach(
([pseudoKey, pseudoStyle]) => {
const pseudoDeclarations = getStylesDeclarations(pseudoStyle);
if (!pseudoDeclarations?.length) {
return;
}
const _selector = selector3.split(",").map((sel) => sel + pseudoKey).join(",");
const pseudoRule = `:root :where(${_selector}){${pseudoDeclarations.join(
";"
)};}`;
ruleset += pseudoRule;
}
);
}
}
);
}
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 = getGapCSSValue2(tree?.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_data112.select)(import_blocks66.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_blocks66.getBlockSupport)(
blockType,
"color.__experimentalDuotone",
false
);
duotoneSelector = duotoneSupport && rootSelector && scopeSelector2(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(css3, blockSelector) {
let processedCSS = "";
if (!css3 || css3.trim() === "") {
return processedCSS;
}
const parts = css3.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(" ") ? scopeSelector2(blockSelector, withoutPseudoElement) : appendToSelector(blockSelector, withoutPseudoElement);
}
processedCSS += `:root :where(${combinedSelector})${pseudoPart}{${cssValue.trim()}}`;
}
});
return processedCSS;
}
// packages/block-editor/build-module/hooks/block-style-variation.mjs
var import_jsx_runtime244 = __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 __unstableBlockStyleVariationOverridesWithConfig({ config: config2 }) {
const { getBlockStyles: getBlockStyles2, overrides } = (0, import_data113.useSelect)(
(select3) => ({
getBlockStyles: select3(import_blocks67.store).getBlockStyles,
overrides: unlock(select3(store)).getStyleOverrides()
}),
[]
);
const { getBlockName: getBlockName2 } = (0, import_data113.useSelect)(store);
const overridesWithConfig = (0, import_element118.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, getBlockStyles2, getBlockName2]);
if (!overridesWithConfig || !overridesWithConfig.length) {
return;
}
return /* @__PURE__ */ (0, import_jsx_runtime244.jsx)(import_jsx_runtime244.Fragment, { children: overridesWithConfig.map((override) => /* @__PURE__ */ (0, import_jsx_runtime244.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 = getValueFromObjectPath(
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_data113.useSelect)((select3) => {
const settings2 = select3(store).getSettings();
return {
globalSettings: settings2.__experimentalFeatures,
globalStyles: settings2[globalStylesDataKey]
};
}, []);
return (0, import_element118.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_data113.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_element118.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_runtime245 = __toESM(require_jsx_runtime(), 1);
var styleIcon = /* @__PURE__ */ (0, import_jsx_runtime245.jsxs)(
import_components105.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_runtime245.jsx)(import_components105.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_runtime245.jsx)(
import_components105.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_data114.useDispatch)(store);
const { globalSettings, globalStyles, blockName } = (0, import_data114.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_runtime245.jsx)(import_components105.ToolbarGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime245.jsx)(
import_components105.ToolbarButton,
{
onClick: handleStyleSwitch,
label: (0, import_i18n95.__)("Shuffle styles"),
children: /* @__PURE__ */ (0, import_jsx_runtime245.jsx)(
import_components105.Icon,
{
icon: styleIcon,
style: {
fill: activeStyleBackground || "transparent"
}
}
)
}
) });
}
var switch_section_style_default = SwitchSectionStyle;
// packages/block-editor/build-module/components/block-toolbar/block-toolbar-icon.mjs
var import_components114 = __toESM(require_components(), 1);
var import_i18n102 = __toESM(require_i18n(), 1);
var import_data118 = __toESM(require_data(), 1);
var import_blocks73 = __toESM(require_blocks(), 1);
var import_preferences2 = __toESM(require_preferences(), 1);
// packages/block-editor/build-module/components/block-switcher/index.mjs
var import_i18n100 = __toESM(require_i18n(), 1);
var import_components112 = __toESM(require_components(), 1);
var import_blocks72 = __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_i18n97 = __toESM(require_i18n(), 1);
var import_components108 = __toESM(require_components(), 1);
var import_blocks69 = __toESM(require_blocks(), 1);
var import_element120 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/block-switcher/preview-block-popover.mjs
var import_i18n96 = __toESM(require_i18n(), 1);
var import_components106 = __toESM(require_components(), 1);
var import_compose64 = __toESM(require_compose(), 1);
var import_jsx_runtime246 = __toESM(require_jsx_runtime(), 1);
function PreviewBlockPopover({ blocks: blocks2 }) {
const isMobile = (0, import_compose64.useViewportMatch)("medium", "<");
if (isMobile) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime246.jsx)("div", { className: "block-editor-block-switcher__popover-preview-container", children: /* @__PURE__ */ (0, import_jsx_runtime246.jsx)(
import_components106.Popover,
{
className: "block-editor-block-switcher__popover-preview",
placement: "right-start",
focusOnMount: false,
offset: 16,
children: /* @__PURE__ */ (0, import_jsx_runtime246.jsxs)("div", { className: "block-editor-block-switcher__preview", children: [
/* @__PURE__ */ (0, import_jsx_runtime246.jsx)("div", { className: "block-editor-block-switcher__preview-title", children: (0, import_i18n96.__)("Preview") }),
/* @__PURE__ */ (0, import_jsx_runtime246.jsx)(block_preview_default, { viewportWidth: 601, blocks: blocks2 })
] })
}
) });
}
// packages/block-editor/build-module/components/block-switcher/block-variation-transformations.mjs
var import_components107 = __toESM(require_components(), 1);
var import_blocks68 = __toESM(require_blocks(), 1);
var import_data115 = __toESM(require_data(), 1);
var import_element119 = __toESM(require_element(), 1);
var import_jsx_runtime247 = __toESM(require_jsx_runtime(), 1);
var EMPTY_OBJECT2 = {};
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_blocks68.store);
const canRemove = canRemoveBlocks2(clientIds);
if (blocks2.length !== 1 || !canRemove) {
return EMPTY_OBJECT2;
}
const [firstBlock] = blocks2;
return {
blockVariationTransformations: getBlockVariations2(
firstBlock.name,
"transform"
),
activeBlockVariation: getActiveBlockVariation(
firstBlock.name,
getBlockAttributes3(firstBlock.clientId)
)
};
},
[clientIds, blocks2]
);
const transformations = (0, import_element119.useMemo)(() => {
return blockVariationTransformations?.filter(
({ name }) => name !== activeBlockVariation?.name
);
}, [blockVariationTransformations, activeBlockVariation]);
return transformations;
}
var BlockVariationTransformations = ({
transformations,
onSelect,
blocks: blocks2
}) => {
const [hoveredTransformItemName, setHoveredTransformItemName] = (0, import_element119.useState)();
return /* @__PURE__ */ (0, import_jsx_runtime247.jsxs)(import_jsx_runtime247.Fragment, { children: [
hoveredTransformItemName && /* @__PURE__ */ (0, import_jsx_runtime247.jsx)(
PreviewBlockPopover,
{
blocks: (0, import_blocks68.cloneBlock)(
blocks2[0],
transformations.find(
({ name }) => name === hoveredTransformItemName
).attributes
)
}
),
transformations?.map((item) => /* @__PURE__ */ (0, import_jsx_runtime247.jsx)(
BlockVariationTransformationItem,
{
item,
onSelect,
setHoveredTransformItemName
},
item.name
))
] });
};
function BlockVariationTransformationItem({
item,
onSelect,
setHoveredTransformItemName
}) {
const { name, icon, title } = item;
return /* @__PURE__ */ (0, import_jsx_runtime247.jsxs)(
import_components107.MenuItem,
{
className: (0, import_blocks68.getBlockMenuDefaultClassName)(name),
onClick: (event) => {
event.preventDefault();
onSelect(name);
},
onMouseLeave: () => setHoveredTransformItemName(null),
onMouseEnter: () => setHoveredTransformItemName(name),
children: [
/* @__PURE__ */ (0, import_jsx_runtime247.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_runtime248 = __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_element120.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 [hoveredTransformItemName, setHoveredTransformItemName] = (0, import_element120.useState)();
const { priorityTextTransformations, restTransformations } = useGroupedTransforms(possibleBlockTransformations);
const hasBothContentTransformations = priorityTextTransformations.length && restTransformations.length;
const restTransformItems = !!restTransformations.length && /* @__PURE__ */ (0, import_jsx_runtime248.jsx)(
RestTransformationItems,
{
restTransformations,
onSelect,
setHoveredTransformItemName
}
);
return /* @__PURE__ */ (0, import_jsx_runtime248.jsxs)(import_jsx_runtime248.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime248.jsxs)(import_components108.MenuGroup, { label: (0, import_i18n97.__)("Transform to"), className, children: [
hoveredTransformItemName && /* @__PURE__ */ (0, import_jsx_runtime248.jsx)(
PreviewBlockPopover,
{
blocks: (0, import_blocks69.switchToBlockType)(
blocks2,
hoveredTransformItemName
)
}
),
!!possibleBlockVariationTransformations?.length && /* @__PURE__ */ (0, import_jsx_runtime248.jsx)(
block_variation_transformations_default,
{
transformations: possibleBlockVariationTransformations,
blocks: blocks2,
onSelect: onSelectVariation
}
),
priorityTextTransformations.map((item) => /* @__PURE__ */ (0, import_jsx_runtime248.jsx)(
BlockTransformationItem,
{
item,
onSelect,
setHoveredTransformItemName
},
item.name
)),
!hasBothContentTransformations && restTransformItems
] }),
!!hasBothContentTransformations && /* @__PURE__ */ (0, import_jsx_runtime248.jsx)(import_components108.MenuGroup, { className, children: restTransformItems })
] });
};
function RestTransformationItems({
restTransformations,
onSelect,
setHoveredTransformItemName
}) {
return restTransformations.map((item) => /* @__PURE__ */ (0, import_jsx_runtime248.jsx)(
BlockTransformationItem,
{
item,
onSelect,
setHoveredTransformItemName
},
item.name
));
}
function BlockTransformationItem({
item,
onSelect,
setHoveredTransformItemName
}) {
const { name, icon, title, isDisabled } = item;
return /* @__PURE__ */ (0, import_jsx_runtime248.jsxs)(
import_components108.MenuItem,
{
className: (0, import_blocks69.getBlockMenuDefaultClassName)(name),
onClick: (event) => {
event.preventDefault();
onSelect(name);
},
disabled: isDisabled,
onMouseLeave: () => setHoveredTransformItemName(null),
onMouseEnter: () => setHoveredTransformItemName(name),
children: [
/* @__PURE__ */ (0, import_jsx_runtime248.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_i18n98 = __toESM(require_i18n(), 1);
var import_components110 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/block-styles/menu-items.mjs
var import_components109 = __toESM(require_components(), 1);
var import_jsx_runtime249 = __toESM(require_jsx_runtime(), 1);
var noop9 = () => {
};
function BlockStylesMenuItems({ clientId, onSwitch = noop9 }) {
const { onSelect, stylesToRender, activeStyle } = useStylesForBlocks({
clientId,
onSwitch
});
if (!stylesToRender || stylesToRender.length === 0) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime249.jsx)(import_jsx_runtime249.Fragment, { children: stylesToRender.map((style) => {
const menuItemText = style.label || style.name;
return /* @__PURE__ */ (0, import_jsx_runtime249.jsx)(
import_components109.MenuItem,
{
icon: activeStyle.name === style.name ? check_default : null,
onClick: () => onSelect(style),
children: /* @__PURE__ */ (0, import_jsx_runtime249.jsx)(
import_components109.__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_runtime250 = __toESM(require_jsx_runtime(), 1);
function BlockStylesMenu({ hoveredBlock, onSwitch }) {
const { clientId } = hoveredBlock;
return /* @__PURE__ */ (0, import_jsx_runtime250.jsx)(
import_components110.MenuGroup,
{
label: (0, import_i18n98.__)("Styles"),
className: "block-editor-block-switcher__styles__menugroup",
children: /* @__PURE__ */ (0, import_jsx_runtime250.jsx)(BlockStylesMenuItems, { clientId, onSwitch })
}
);
}
// packages/block-editor/build-module/components/block-switcher/pattern-transformations-menu.mjs
var import_i18n99 = __toESM(require_i18n(), 1);
var import_element122 = __toESM(require_element(), 1);
var import_compose65 = __toESM(require_compose(), 1);
var import_components111 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/block-switcher/use-transformed-patterns.mjs
var import_element121 = __toESM(require_element(), 1);
var import_blocks71 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/components/block-switcher/utils.mjs
var import_blocks70 = __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_blocks70.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_blocks71.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_element121.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_runtime251 = __toESM(require_jsx_runtime(), 1);
function PatternTransformationsMenu({
blocks: blocks2,
patterns: statePatterns,
onSelect
}) {
const [showTransforms, setShowTransforms] = (0, import_element122.useState)(false);
const patterns = use_transformed_patterns_default(statePatterns, blocks2);
if (!patterns.length) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime251.jsxs)(import_components111.MenuGroup, { className: "block-editor-block-switcher__pattern__transforms__menugroup", children: [
showTransforms && /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(
PreviewPatternsPopover,
{
patterns,
onSelect
}
),
/* @__PURE__ */ (0, import_jsx_runtime251.jsx)(
import_components111.MenuItem,
{
onClick: (event) => {
event.preventDefault();
setShowTransforms(!showTransforms);
},
icon: chevron_right_default,
children: (0, import_i18n99.__)("Patterns")
}
)
] });
}
function PreviewPatternsPopover({ patterns, onSelect }) {
const isMobile = (0, import_compose65.useViewportMatch)("medium", "<");
return /* @__PURE__ */ (0, import_jsx_runtime251.jsx)("div", { className: "block-editor-block-switcher__popover-preview-container", children: /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(
import_components111.Popover,
{
className: "block-editor-block-switcher__popover-preview",
placement: isMobile ? "bottom" : "right-start",
offset: 16,
children: /* @__PURE__ */ (0, import_jsx_runtime251.jsx)("div", { className: "block-editor-block-switcher__preview is-pattern-list-preview", children: /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(
BlockPatternsList2,
{
patterns,
onSelect
}
) })
}
) });
}
function BlockPatternsList2({ patterns, onSelect }) {
return /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(
import_components111.Composite,
{
role: "listbox",
className: "block-editor-block-switcher__preview-patterns-container",
"aria-label": (0, import_i18n99.__)("Patterns list"),
children: patterns.map((pattern) => /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(
BlockPattern2,
{
pattern,
onSelect
},
pattern.name
))
}
);
}
function BlockPattern2({ pattern, onSelect }) {
const baseClassName = "block-editor-block-switcher__preview-patterns-container";
const descriptionId = (0, import_compose65.useInstanceId)(
BlockPattern2,
`${baseClassName}-list__item-description`
);
return /* @__PURE__ */ (0, import_jsx_runtime251.jsxs)("div", { className: `${baseClassName}-list__list-item`, children: [
/* @__PURE__ */ (0, import_jsx_runtime251.jsxs)(
import_components111.Composite.Item,
{
render: /* @__PURE__ */ (0, import_jsx_runtime251.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_runtime251.jsx)(
block_preview_default,
{
blocks: pattern.transformedBlocks,
viewportWidth: pattern.viewportWidth || 500
}
),
/* @__PURE__ */ (0, import_jsx_runtime251.jsx)("div", { className: `${baseClassName}-list__item-title`, children: pattern.title })
]
}
),
!!pattern.description && /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(import_components111.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_runtime252 = __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_blocks72.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) {
const newBlocks = (0, import_blocks72.switchToBlockType)(blocks2, name);
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_blocks72.isTemplatePart)(blocks2[0]) || (0, import_blocks72.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_runtime252.jsx)("p", { className: "block-editor-block-switcher__no-transforms", children: (0, import_i18n100.__)("No transforms.") });
}
const connectedBlockDescription = isSingleBlock ? (0, import_i18n100._x)(
"This block is connected.",
"block toolbar button label and description"
) : (0, import_i18n100._x)(
"These blocks are connected.",
"block toolbar button label and description"
);
return /* @__PURE__ */ (0, import_jsx_runtime252.jsxs)("div", { className: "block-editor-block-switcher__container", children: [
hasPatternTransformation && /* @__PURE__ */ (0, import_jsx_runtime252.jsx)(
pattern_transformations_menu_default,
{
blocks: blocks2,
patterns,
onSelect: (transformedBlocks) => {
onPatternTransform(transformedBlocks);
onClose();
}
}
),
hasBlockOrBlockVariationTransforms && /* @__PURE__ */ (0, import_jsx_runtime252.jsx)(
block_transformations_menu_default,
{
className: "block-editor-block-switcher__transforms__menugroup",
possibleBlockTransformations,
possibleBlockVariationTransformations: blockVariationTransformations,
blocks: blocks2,
onSelect: (name) => {
onBlockTransform(name);
onClose();
},
onSelectVariation: (name) => {
onBlockVariationTransform(name);
onClose();
}
}
),
hasBlockStyles && /* @__PURE__ */ (0, import_jsx_runtime252.jsx)(
BlockStylesMenu,
{
hoveredBlock: blocks2[0],
onSwitch: onClose
}
),
isUsingBindings && /* @__PURE__ */ (0, import_jsx_runtime252.jsx)(import_components112.MenuGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime252.jsx)(import_components112.__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_i18n100.__)("Change block type or style") : (0, import_i18n100.sprintf)(
/* translators: %d: number of blocks. */
(0, import_i18n100._n)(
"Change type of %d block",
"Change type of %d blocks",
clientIds.length
),
clientIds.length
);
return /* @__PURE__ */ (0, import_jsx_runtime252.jsx)(import_components112.ToolbarGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime252.jsx)(import_components112.ToolbarItem, { children: (toggleProps) => /* @__PURE__ */ (0, import_jsx_runtime252.jsx)(
import_components112.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_runtime252.jsx)(
BlockSwitcherDropdownMenuContents,
{
onClose,
clientIds
}
)
}
) }) });
};
var block_switcher_default = BlockSwitcher;
// packages/block-editor/build-module/components/block-toolbar/pattern-overrides-dropdown.mjs
var import_components113 = __toESM(require_components(), 1);
var import_i18n101 = __toESM(require_i18n(), 1);
var import_element123 = __toESM(require_element(), 1);
var import_data117 = __toESM(require_data(), 1);
var import_jsx_runtime253 = __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_i18n101.sprintf)(
/* translators: 1: The block type's name. 2: The block's user-provided name (the same as the override name). */
(0, import_i18n101.__)('This %1$s is editable using the "%2$s" override.'),
blockTitle.toLowerCase(),
blockMetaName
);
} else {
description = (0, import_i18n101.__)("These blocks are editable using overrides.");
}
return /* @__PURE__ */ (0, import_jsx_runtime253.jsx)(import_components113.__experimentalText, { children: description });
}
function PatternOverridesDropdown({
icon,
clientIds,
blockTitle,
label
}) {
const [isOpen, setIsOpen] = (0, import_element123.useState)(false);
const anchorRef = (0, import_element123.useRef)();
return /* @__PURE__ */ (0, import_jsx_runtime253.jsxs)(import_jsx_runtime253.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime253.jsx)(
import_components113.ToolbarButton,
{
ref: anchorRef,
className: "block-editor-block-toolbar__pattern-overrides-indicator",
icon,
label,
onClick: () => setIsOpen(!isOpen),
"aria-expanded": isOpen
}
),
isOpen && /* @__PURE__ */ (0, import_jsx_runtime253.jsx)(
import_components113.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_runtime253.jsx)(
PatternOverridesPopoverContent,
{
clientIds,
blockTitle
}
)
}
)
] });
}
// packages/block-editor/build-module/components/block-toolbar/block-toolbar-icon.mjs
var import_jsx_runtime254 = __toESM(require_jsx_runtime(), 1);
function getBlockIconVariant({ select: select3, clientIds }) {
const {
getBlockName: getBlockName2,
getBlockAttributes: getBlockAttributes3,
getBlockParentsByBlockName: getBlockParentsByBlockName2,
canRemoveBlocks: canRemoveBlocks2,
getTemplateLock: getTemplateLock2,
getBlockEditingMode: getBlockEditingMode2
} = unlock(select3(store));
const { getBlockStyles: getBlockStyles2 } = select3(import_blocks73.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
);
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 isDefaultEditingMode = getBlockEditingMode2(clientIds[0]) === "default";
const _hideTransformsForSections = window?.__experimentalContentOnlyPatternInsertion && hasPatternNameInSelection;
const _showBlockSwitcher = !_hideTransformsForSections && isDefaultEditingMode && (hasBlockStyles || canRemove) && !hasTemplateLock;
const _showPatternOverrides = hasPatternOverrides && hasParentPattern;
if (_showBlockSwitcher) {
return "switcher";
} else if (_showPatternOverrides) {
return "pattern-overrides";
}
return "default";
}
function getBlockIcon({ select: select3, clientIds }) {
const { getBlockName: getBlockName2, getBlockAttributes: getBlockAttributes3 } = unlock(
select3(store)
);
const _isSingleBlock = clientIds.length === 1;
const firstClientId = clientIds[0];
const blockAttributes = getBlockAttributes3(firstClientId);
if (_isSingleBlock && blockAttributes?.metadata?.patternName && window?.__experimentalContentOnlyPatternInsertion) {
return symbol_default;
}
const blockName = getBlockName2(firstClientId);
const blockType = (0, import_blocks73.getBlockType)(blockName);
if (_isSingleBlock) {
const { getActiveBlockVariation } = select3(import_blocks73.store);
const match2 = getActiveBlockVariation(blockName, blockAttributes);
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_i18n102.__)("Multiple blocks selected");
const text = showBlockTitle && blockTitle ? blockTitle : void 0;
const BlockIconElement = /* @__PURE__ */ (0, import_jsx_runtime254.jsx)(
block_icon_default,
{
className: "block-editor-block-toolbar__block-icon",
icon
}
);
if (variant === "switcher") {
return /* @__PURE__ */ (0, import_jsx_runtime254.jsx)(
block_switcher_default,
{
clientIds,
label,
text,
children: BlockIconElement
}
);
}
if (variant === "pattern-overrides") {
return /* @__PURE__ */ (0, import_jsx_runtime254.jsx)(
PatternOverridesDropdown,
{
icon: BlockIconElement,
clientIds,
blockTitle,
label
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime254.jsx)(
import_components114.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_runtime255 = __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
} = (0, import_data119.useSelect)((select3) => {
const {
getBlockName: getBlockName2,
getBlockMode: getBlockMode2,
getBlockParents: getBlockParents2,
getSelectedBlockClientIds: getSelectedBlockClientIds2,
isBlockValid: isBlockValid2,
getBlockEditingMode: getBlockEditingMode2,
getBlockAttributes: getBlockAttributes3,
getTemplateLock: getTemplateLock2,
getParentSectionBlock: getParentSectionBlock2,
isZoomOut: isZoomOut2,
isSectionBlock: isSectionBlock2
} = 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_blocks74.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 _showSwitchSectionStyleButton = window?.__experimentalContentOnlyPatternInsertion && (_isZoomOut || _isSectionBlock);
return {
blockClientId: selectedBlockClientId,
blockClientIds: selectedBlockClientIds,
isDefaultEditingMode: _isDefaultEditingMode,
blockType: selectedBlockClientId && (0, import_blocks74.getBlockType)(_blockName),
shouldShowVisualToolbar: isValid2 && isVisual,
toolbarKey: `${selectedBlockClientId}${parentClientId}`,
showParentSelector: !_isZoomOut && parentBlockType && editingMode !== "contentOnly" && getBlockEditingMode2(parentClientId) !== "disabled" && (0, import_blocks74.hasBlockSupport)(
parentBlockType,
"__experimentalParentSelector",
true
) && selectedBlockClientIds.length === 1,
isUsingBindings: _isUsingBindings,
isSectionContainer: _isSectionBlock,
hasContentOnlyLocking: _hasTemplateLock,
showShuffleButton: _isZoomOut,
showSlots: !_isZoomOut,
showGroupButtons: !_isZoomOut,
showLockButtons: !_isZoomOut,
showBlockVisibilityButton: !_isZoomOut,
showSwitchSectionStyleButton: _showSwitchSectionStyleButton
};
}, []);
const toolbarWrapperRef = (0, import_element124.useRef)(null);
const nodeRef = (0, import_element124.useRef)();
const showHoveredOrFocusedGestures = useShowHoveredOrFocusedGestures({
ref: nodeRef
});
const isLargeViewport = !(0, import_compose66.useViewportMatch)("medium", "<");
const hasBlockToolbar = useHasBlockToolbar();
if (!hasBlockToolbar) {
return null;
}
const isMultiToolbar = blockClientIds.length > 1;
const isSynced = (0, import_blocks74.isReusableBlock)(blockType) || (0, import_blocks74.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_runtime255.jsx)(
NavigableToolbar,
{
focusEditorOnEscape: true,
className: classes,
"aria-label": (0, import_i18n103.__)("Block tools"),
variant: variant === "toolbar" ? void 0 : variant,
focusOnMount,
__experimentalInitialIndex,
__experimentalOnIndexChange,
children: /* @__PURE__ */ (0, import_jsx_runtime255.jsxs)("div", { ref: toolbarWrapperRef, className: innerClasses, children: [
showParentSelector && !isMultiToolbar && isLargeViewport && /* @__PURE__ */ (0, import_jsx_runtime255.jsx)(BlockParentSelector, {}),
(shouldShowVisualToolbar || isMultiToolbar) && /* @__PURE__ */ (0, import_jsx_runtime255.jsx)("div", { ref: nodeRef, ...showHoveredOrFocusedGestures, children: /* @__PURE__ */ (0, import_jsx_runtime255.jsxs)(import_components115.ToolbarGroup, { className: "block-editor-block-toolbar__block-controls", children: [
/* @__PURE__ */ (0, import_jsx_runtime255.jsx)(
BlockToolbarIcon,
{
clientIds: blockClientIds,
isSynced
}
),
isDefaultEditingMode && showBlockVisibilityButton && /* @__PURE__ */ (0, import_jsx_runtime255.jsx)(
BlockVisibilityToolbar2,
{
clientIds: blockClientIds
}
),
!isMultiToolbar && isDefaultEditingMode && showLockButtons && /* @__PURE__ */ (0, import_jsx_runtime255.jsx)(
BlockLockToolbar,
{
clientId: blockClientId
}
),
/* @__PURE__ */ (0, import_jsx_runtime255.jsx)(
block_mover_default,
{
clientIds: blockClientIds,
hideDragHandle
}
)
] }) }),
!hasContentOnlyLocking && shouldShowVisualToolbar && isMultiToolbar && showGroupButtons && /* @__PURE__ */ (0, import_jsx_runtime255.jsx)(toolbar_default, {}),
showShuffleButton && /* @__PURE__ */ (0, import_jsx_runtime255.jsx)(ChangeDesign, { clientId: blockClientIds[0] }),
showSwitchSectionStyleButton && /* @__PURE__ */ (0, import_jsx_runtime255.jsx)(switch_section_style_default, { clientId: blockClientIds[0] }),
shouldShowVisualToolbar && showSlots && /* @__PURE__ */ (0, import_jsx_runtime255.jsxs)(import_jsx_runtime255.Fragment, { children: [
!isSectionContainer && /* @__PURE__ */ (0, import_jsx_runtime255.jsxs)(import_jsx_runtime255.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime255.jsx)(
block_controls_default.Slot,
{
group: "parent",
className: "block-editor-block-toolbar__slot"
}
),
/* @__PURE__ */ (0, import_jsx_runtime255.jsx)(
block_controls_default.Slot,
{
group: "block",
className: "block-editor-block-toolbar__slot"
}
),
/* @__PURE__ */ (0, import_jsx_runtime255.jsx)(block_controls_default.Slot, { className: "block-editor-block-toolbar__slot" }),
/* @__PURE__ */ (0, import_jsx_runtime255.jsx)(
block_controls_default.Slot,
{
group: "inline",
className: "block-editor-block-toolbar__slot"
}
)
] }),
/* @__PURE__ */ (0, import_jsx_runtime255.jsx)(
block_controls_default.Slot,
{
group: "other",
className: "block-editor-block-toolbar__slot"
}
),
/* @__PURE__ */ (0, import_jsx_runtime255.jsx)(block_toolbar_last_item_default.Slot, {})
] }),
/* @__PURE__ */ (0, import_jsx_runtime255.jsx)(BlockEditVisuallyButton, { clientIds: blockClientIds }),
/* @__PURE__ */ (0, import_jsx_runtime255.jsx)(block_settings_menu_default, { clientIds: blockClientIds })
] })
},
toolbarKey
);
}
function BlockToolbar({ hideDragHandle, variant }) {
return /* @__PURE__ */ (0, import_jsx_runtime255.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_runtime256 = __toESM(require_jsx_runtime(), 1);
function BlockToolbarPopover({
clientId,
isTyping: isTyping3,
__unstableContentRef
}) {
const { capturingClientId, isInsertionPointVisible, lastClientId } = useSelectedBlockToolProps(clientId);
const initialToolbarItemIndexRef = (0, import_element125.useRef)();
(0, import_element125.useEffect)(() => {
initialToolbarItemIndexRef.current = void 0;
}, [clientId]);
const { stopTyping: stopTyping2 } = (0, import_data120.useDispatch)(store);
const isToolbarForcedRef = (0, import_element125.useRef)(false);
(0, import_keyboard_shortcuts8.useShortcut)("core/block-editor/focus-toolbar", () => {
isToolbarForcedRef.current = true;
stopTyping2(true);
});
(0, import_element125.useEffect)(() => {
isToolbarForcedRef.current = false;
});
const clientIdToPositionOver = capturingClientId || clientId;
const popoverProps3 = useBlockToolbarPopoverProps({
contentElement: __unstableContentRef?.current,
clientId: clientIdToPositionOver
});
return !isTyping3 && /* @__PURE__ */ (0, import_jsx_runtime256.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_runtime256.jsx)(
PrivateBlockToolbar,
{
focusOnMount: isToolbarForcedRef.current,
__experimentalInitialIndex: initialToolbarItemIndexRef.current,
__experimentalOnIndexChange: (index) => {
initialToolbarItemIndexRef.current = index;
},
variant: "toolbar"
}
)
}
);
}
// packages/block-editor/build-module/components/block-tools/zoom-out-mode-inserters.mjs
var import_data121 = __toESM(require_data(), 1);
var import_element126 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/block-tools/zoom-out-mode-inserter-button.mjs
var import_components116 = __toESM(require_components(), 1);
var import_i18n104 = __toESM(require_i18n(), 1);
var import_jsx_runtime257 = __toESM(require_jsx_runtime(), 1);
function ZoomOutModeInserterButton({ onClick }) {
return /* @__PURE__ */ (0, import_jsx_runtime257.jsx)(
import_components116.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_i18n104._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_runtime258 = __toESM(require_jsx_runtime(), 1);
function ZoomOutModeInserters() {
const [isReady, setIsReady] = (0, import_element126.useState)(false);
const {
hasSelection,
blockOrder,
setInserterIsOpened,
sectionRootClientId,
selectedBlockClientId,
blockInsertionPoint,
insertionPointVisible
} = (0, import_data121.useSelect)((select3) => {
const {
getSettings: getSettings8,
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: getSettings8().__experimentalSetIsInserterOpened,
selectedBlockClientId: getSelectedBlockClientId2(),
blockInsertionPoint: getBlockInsertionPoint2(),
insertionPointVisible: isBlockInsertionPointVisible2()
};
}, []);
const { showInsertionPoint: showInsertionPoint2 } = unlock((0, import_data121.useDispatch)(store));
(0, import_element126.useEffect)(() => {
const timeout = setTimeout(() => {
setIsReady(true);
}, 500);
return () => {
clearTimeout(timeout);
};
}, []);
if (!isReady || !hasSelection) {
return null;
}
const previousClientId = selectedBlockClientId;
const index = blockOrder.findIndex(
(clientId) => selectedBlockClientId === clientId
);
const insertionIndex = index + 1;
const nextClientId = blockOrder[insertionIndex];
if (insertionPointVisible && blockInsertionPoint?.index === insertionIndex) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime258.jsx)(
inbetween_default,
{
previousClientId,
nextClientId,
children: /* @__PURE__ */ (0, import_jsx_runtime258.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_blocks75 = __toESM(require_blocks(), 1);
function useShowBlockTools() {
return (0, import_data122.useSelect)((select3) => {
const {
getSelectedBlockClientId: getSelectedBlockClientId2,
getFirstMultiSelectedBlockClientId: getFirstMultiSelectedBlockClientId2,
getBlock: getBlock2,
getBlockMode: getBlockMode2,
getSettings: getSettings8,
isTyping: isTyping3,
isBlockInterfaceHidden: isBlockInterfaceHidden3
} = unlock(select3(store));
const clientId = getSelectedBlockClientId2() || getFirstMultiSelectedBlockClientId2();
const block = getBlock2(clientId);
const hasSelectedBlock2 = !!clientId && !!block;
const isEmptyDefaultBlock = hasSelectedBlock2 && (0, import_blocks75.isUnmodifiedDefaultBlock)(block, "content") && getBlockMode2(clientId) !== "html";
const _showEmptyBlockSideInserter = clientId && !isTyping3() && isEmptyDefaultBlock;
const _showBlockToolbarPopover = !isBlockInterfaceHidden3() && !getSettings8().hasFixedToolbar && !_showEmptyBlockSideInserter && hasSelectedBlock2 && !isEmptyDefaultBlock;
return {
showEmptyBlockSideInserter: _showEmptyBlockSideInserter,
showBlockToolbarPopover: _showBlockToolbarPopover
};
}, []);
}
// packages/block-editor/build-module/components/block-tools/index.mjs
var import_jsx_runtime259 = __toESM(require_jsx_runtime(), 1);
function selector2(select3) {
const {
getSelectedBlockClientId: getSelectedBlockClientId2,
getFirstMultiSelectedBlockClientId: getFirstMultiSelectedBlockClientId2,
getSettings: getSettings8,
isTyping: isTyping3,
isDragging: isDragging3,
isZoomOut: isZoomOut2
} = unlock(select3(store));
const clientId = getSelectedBlockClientId2() || getFirstMultiSelectedBlockClientId2();
return {
clientId,
hasFixedToolbar: getSettings8().hasFixedToolbar,
isTyping: isTyping3(),
isZoomOutMode: isZoomOut2(),
isDragging: isDragging3()
};
}
function BlockTools({
children,
__unstableContentRef,
...props
}) {
const { clientId, hasFixedToolbar, isTyping: isTyping3, isZoomOutMode, isDragging: isDragging3 } = (0, import_data123.useSelect)(selector2, []);
const [visibilityModalClientIds, setVisibilityModalClientIds] = (0, import_element127.useState)(null);
const isMatch = (0, import_keyboard_shortcuts9.__unstableUseShortcutEventMatch)();
const {
getBlocksByClientId: getBlocksByClientId2,
getSelectedBlockClientIds: getSelectedBlockClientIds2,
getBlockRootClientId: getBlockRootClientId2,
isGroupable: isGroupable2,
getEditedContentOnlySection: getEditedContentOnlySection2
} = unlock((0, import_data123.useSelect)(store));
const { getGroupingBlockName } = (0, import_data123.useSelect)(import_blocks76.store);
const { showEmptyBlockSideInserter, showBlockToolbarPopover } = useShowBlockTools();
const pasteStyles = usePasteStyles();
const {
duplicateBlocks: duplicateBlocks2,
removeBlocks: removeBlocks2,
replaceBlocks: replaceBlocks2,
insertAfterBlock: insertAfterBlock2,
insertBeforeBlock: insertBeforeBlock2,
selectBlock: selectBlock2,
moveBlocksUp: moveBlocksUp2,
moveBlocksDown: moveBlocksDown2,
expandBlock: expandBlock2,
stopEditingContentOnlySection: stopEditingContentOnlySection2,
updateBlockAttributes: updateBlockAttributes2
} = 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_i18n105.sprintf)(
// translators: %d: the name of the block that has been moved
(0, import_i18n105._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_dom28.isTextField)(event.target) || (0, import_dom28.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_blocks76.switchToBlockType)(
blocks2,
groupingBlockName
);
replaceBlocks2(clientIds, newBlocks);
(0, import_a11y12.speak)((0, import_i18n105.__)("Selected blocks are grouped."));
}
} else if (isMatch("core/block-editor/toggle-block-visibility", event)) {
const clientIds = getSelectedBlockClientIds2();
if (clientIds.length) {
event.preventDefault();
const blocks2 = getBlocksByClientId2(clientIds);
const supportsBlockVisibility = blocks2.every(
(block) => (0, import_blocks76.hasBlockSupport)(block.name, "visibility", true)
);
if (!supportsBlockVisibility) {
return;
}
if (window.__experimentalHideBlocksBasedOnScreenSize) {
setVisibilityModalClientIds(clientIds);
} else {
const hasHiddenBlock = blocks2.some(
(block) => block.attributes.metadata?.blockVisibility === false
);
const attributesByClientId = Object.fromEntries(
blocks2.map(
({ clientId: mapClientId, attributes }) => [
mapClientId,
{
metadata: cleanEmptyObject({
...attributes?.metadata,
blockVisibility: hasHiddenBlock ? void 0 : false
})
}
]
)
);
updateBlockAttributes2(clientIds, attributesByClientId, {
uniqueByBlock: true
});
}
}
}
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_runtime259.jsxs)(
"div",
{
...props,
onKeyDown,
className: clsx_default(props.className, {
"block-editor-block-tools--is-dragging": isDragging3
}),
children: [
/* @__PURE__ */ (0, import_jsx_runtime259.jsxs)(InsertionPointOpenRef.Provider, { value: (0, import_element127.useRef)(false), children: [
!isTyping3 && !isZoomOutMode && /* @__PURE__ */ (0, import_jsx_runtime259.jsx)(
InsertionPoint,
{
__unstableContentRef
}
),
showEmptyBlockSideInserter && /* @__PURE__ */ (0, import_jsx_runtime259.jsx)(
EmptyBlockInserter,
{
__unstableContentRef,
clientId
}
),
showBlockToolbarPopover && /* @__PURE__ */ (0, import_jsx_runtime259.jsx)(
BlockToolbarPopover,
{
__unstableContentRef,
clientId,
isTyping: isTyping3
}
),
!isZoomOutMode && !hasFixedToolbar && /* @__PURE__ */ (0, import_jsx_runtime259.jsx)(
import_components117.Popover.Slot,
{
name: "block-toolbar",
ref: blockToolbarRef
}
),
children,
/* @__PURE__ */ (0, import_jsx_runtime259.jsx)(
import_components117.Popover.Slot,
{
name: "__unstable-block-tools-after",
ref: blockToolbarAfterRef
}
),
isZoomOutMode && !isDragging3 && /* @__PURE__ */ (0, import_jsx_runtime259.jsx)(
zoom_out_mode_inserters_default,
{
__unstableContentRef
}
)
] }),
visibilityModalClientIds && /* @__PURE__ */ (0, import_jsx_runtime259.jsx)(
BlockVisibilityModal,
{
clientIds: visibilityModalClientIds,
onClose: () => setVisibilityModalClientIds(null)
}
)
]
}
)
);
}
// packages/block-editor/build-module/components/use-block-commands/index.mjs
var import_i18n106 = __toESM(require_i18n(), 1);
var import_blocks77 = __toESM(require_blocks(), 1);
var import_data124 = __toESM(require_data(), 1);
var import_commands = __toESM(require_commands(), 1);
var import_jsx_runtime260 = __toESM(require_jsx_runtime(), 1);
var getTransformCommands = () => function useTransformCommands() {
const { replaceBlocks: replaceBlocks2, multiSelect: multiSelect2 } = (0, import_data124.useDispatch)(store);
const {
blocks: blocks2,
clientIds,
canRemove,
possibleBlockTransformations,
invalidSelection
} = (0, import_data124.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_blocks77.isTemplatePart)(blocks2[0]);
function selectForMultipleBlocks(insertedBlocks) {
if (insertedBlocks.length > 1) {
multiSelect2(
insertedBlocks[0].clientId,
insertedBlocks[insertedBlocks.length - 1].clientId
);
}
}
function onBlockTransform(name) {
const newBlocks = (0, import_blocks77.switchToBlockType)(blocks2, name);
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 { name, title, icon } = transformation;
return {
name: "core/block-editor/transform-to-" + name.replace("/", "-"),
/* translators: %s: Block or block variation name. */
label: (0, import_i18n106.sprintf)((0, import_i18n106.__)("Transform to %s"), title),
icon: /* @__PURE__ */ (0, import_jsx_runtime260.jsx)(block_icon_default, { icon }),
callback: ({ close }) => {
onBlockTransform(name);
close();
}
};
}
);
return { isLoading: false, commands };
};
var getQuickActionsCommands = () => function useQuickActionsCommands() {
const { clientIds, isUngroupable: isUngroupable2, isGroupable: isGroupable2 } = (0, import_data124.useSelect)(
(select3) => {
const {
getSelectedBlockClientIds: getSelectedBlockClientIds2,
isUngroupable: _isUngroupable,
isGroupable: _isGroupable
} = select3(store);
const selectedBlockClientIds = getSelectedBlockClientIds2();
return {
clientIds: selectedBlockClientIds,
isUngroupable: _isUngroupable(),
isGroupable: _isGroupable()
};
},
[]
);
const {
canInsertBlockType: canInsertBlockType2,
getBlockRootClientId: getBlockRootClientId2,
getBlocksByClientId: getBlocksByClientId2,
canRemoveBlocks: canRemoveBlocks2,
getBlockName: getBlockName2
} = (0, import_data124.useSelect)(store);
const { getDefaultBlockName: getDefaultBlockName7, getGroupingBlockName } = (0, import_data124.useSelect)(import_blocks77.store);
const blocks2 = getBlocksByClientId2(clientIds);
const {
removeBlocks: removeBlocks2,
replaceBlocks: replaceBlocks2,
duplicateBlocks: duplicateBlocks2,
insertAfterBlock: insertAfterBlock2,
insertBeforeBlock: insertBeforeBlock2,
updateBlockAttributes: updateBlockAttributes2
} = (0, import_data124.useDispatch)(store);
const onGroup = () => {
if (!blocks2.length) {
return;
}
const groupingBlockName = getGroupingBlockName();
const newBlocks = (0, import_blocks77.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 rootClientId = getBlockRootClientId2(clientIds[0]);
const canInsertDefaultBlock = canInsertBlockType2(
getDefaultBlockName7(),
rootClientId
);
const canDuplicate = blocks2.every((block) => {
return !!block && (0, import_blocks77.hasBlockSupport)(block.name, "multiple", true) && canInsertBlockType2(block.name, rootClientId);
});
const canRemove = canRemoveBlocks2(clientIds);
const canToggleBlockVisibility = blocks2.every(
({ clientId }) => (0, import_blocks77.hasBlockSupport)(getBlockName2(clientId), "visibility", true)
) && !window.__experimentalHideBlocksBasedOnScreenSize;
const commands = [];
if (canDuplicate) {
commands.push({
name: "duplicate",
label: (0, import_i18n106.__)("Duplicate"),
callback: () => duplicateBlocks2(clientIds, true),
icon: copy_default
});
}
if (canInsertDefaultBlock) {
commands.push(
{
name: "add-before",
label: (0, import_i18n106.__)("Add before"),
callback: () => {
const clientId = Array.isArray(clientIds) ? clientIds[0] : clientId;
insertBeforeBlock2(clientId);
},
icon: plus_default
},
{
name: "add-after",
label: (0, import_i18n106.__)("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_i18n106.__)("Group"),
callback: onGroup,
icon: group_default
});
}
if (isUngroupable2) {
commands.push({
name: "ungroup",
label: (0, import_i18n106.__)("Ungroup"),
callback: onUngroup,
icon: ungroup_default
});
}
if (canRemove) {
commands.push({
name: "remove",
label: (0, import_i18n106.__)("Delete"),
callback: () => removeBlocks2(clientIds, true),
icon: trash_default
});
}
if (canToggleBlockVisibility) {
const hasHiddenBlock = blocks2.some(
(block) => block.attributes.metadata?.blockVisibility === false
);
commands.push({
name: "core/toggle-block-visibility",
label: hasHiddenBlock ? (0, import_i18n106.__)("Show") : (0, import_i18n106.__)("Hide"),
callback: () => {
const attributesByClientId = Object.fromEntries(
blocks2?.map(({ clientId, attributes }) => [
clientId,
{
metadata: cleanEmptyObject({
...attributes?.metadata,
blockVisibility: hasHiddenBlock ? void 0 : false
})
}
])
);
updateBlockAttributes2(clientIds, attributesByClientId, {
uniqueByBlock: true
});
},
icon: hasHiddenBlock ? seen_default : unseen_default
});
}
return {
isLoading: false,
commands: commands.map((command) => ({
...command,
name: "core/block-editor/action-" + command.name,
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_runtime261 = __toESM(require_jsx_runtime(), 1);
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_runtime261.jsx)(BlockList, {}),
styles,
contentRef: contentRefProp,
iframeProps
}) {
useBlockCommands();
const isTabletViewport = (0, import_compose67.useViewportMatch)("medium", "<");
const resetTypingRef = useMouseMoveTypingReset();
const clearerRef = useBlockSelectionClearer();
const localRef = (0, import_element128.useRef)();
const contentRef = (0, import_compose67.useMergeRefs)([contentRefProp, clearerRef, localRef]);
const zoomLevel2 = (0, import_data125.useSelect)(
(select3) => unlock(select3(store)).getZoomLevel(),
[]
);
const zoomOutIframeProps = zoomLevel2 !== 100 && !isTabletViewport ? {
scale: zoomLevel2,
frameSize: "40px"
} : {};
if (!shouldIframe) {
return /* @__PURE__ */ (0, import_jsx_runtime261.jsxs)(
BlockTools,
{
__unstableContentRef: localRef,
style: { height, display: "flex" },
children: [
/* @__PURE__ */ (0, import_jsx_runtime261.jsx)(
editor_styles_default,
{
styles,
scope: ":where(.editor-styles-wrapper)",
transformOptions: EDITOR_STYLE_TRANSFORM_OPTIONS
}
),
/* @__PURE__ */ (0, import_jsx_runtime261.jsx)(
writing_flow_default,
{
ref: contentRef,
className: "editor-styles-wrapper",
tabIndex: -1,
style: {
height: "100%",
width: "100%"
},
children
}
)
]
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime261.jsx)(
BlockTools,
{
__unstableContentRef: localRef,
style: { height, display: "flex" },
children: /* @__PURE__ */ (0, import_jsx_runtime261.jsxs)(
iframe_default,
{
...iframeProps,
...zoomOutIframeProps,
ref: resetTypingRef,
contentRef,
style: {
...iframeProps?.style
},
name: "editor-canvas",
children: [
/* @__PURE__ */ (0, import_jsx_runtime261.jsx)(editor_styles_default, { styles }),
children
]
}
)
}
);
}
function BlockCanvas({ children, height, styles }) {
return /* @__PURE__ */ (0, import_jsx_runtime261.jsx)(ExperimentalBlockCanvas, { height, styles, children });
}
var block_canvas_default = BlockCanvas;
// packages/block-editor/build-module/components/color-style-selector/index.mjs
var import_components118 = __toESM(require_components(), 1);
var import_i18n107 = __toESM(require_i18n(), 1);
var import_keycodes11 = __toESM(require_keycodes(), 1);
var import_deprecated13 = __toESM(require_deprecated(), 1);
var import_jsx_runtime262 = __toESM(require_jsx_runtime(), 1);
var ColorSelectorSVGIcon = () => /* @__PURE__ */ (0, import_jsx_runtime262.jsx)(import_components118.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", children: /* @__PURE__ */ (0, import_jsx_runtime262.jsx)(import_components118.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_runtime262.jsx)("div", { className: "block-library-colors-selector__icon-container", children: /* @__PURE__ */ (0, import_jsx_runtime262.jsx)(
"div",
{
className: `${className} block-library-colors-selector__state-selection`,
style,
children: /* @__PURE__ */ (0, import_jsx_runtime262.jsx)(ColorSelectorSVGIcon, {})
}
) });
};
var renderToggleComponent = ({ TextColor, BackgroundColor }) => ({ onToggle, isOpen }) => {
const openOnArrowDown = (event) => {
if (!isOpen && event.keyCode === import_keycodes11.DOWN) {
event.preventDefault();
onToggle();
}
};
return /* @__PURE__ */ (0, import_jsx_runtime262.jsx)(import_components118.ToolbarGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime262.jsx)(
import_components118.ToolbarButton,
{
className: "components-toolbar__control block-library-colors-selector__toggle",
label: (0, import_i18n107.__)("Open Colors Selector"),
onClick: onToggle,
onKeyDown: openOnArrowDown,
icon: /* @__PURE__ */ (0, import_jsx_runtime262.jsx)(BackgroundColor, { children: /* @__PURE__ */ (0, import_jsx_runtime262.jsx)(TextColor, { children: /* @__PURE__ */ (0, import_jsx_runtime262.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_runtime262.jsx)(
import_components118.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_components125 = __toESM(require_components(), 1);
var import_i18n116 = __toESM(require_i18n(), 1);
var import_data138 = __toESM(require_data(), 1);
var import_element146 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/list-view/index.mjs
var import_compose73 = __toESM(require_compose(), 1);
var import_components124 = __toESM(require_components(), 1);
var import_data137 = __toESM(require_data(), 1);
var import_deprecated14 = __toESM(require_deprecated(), 1);
var import_element145 = __toESM(require_element(), 1);
var import_i18n115 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/list-view/branch.mjs
var import_components122 = __toESM(require_components(), 1);
var import_element138 = __toESM(require_element(), 1);
var import_data130 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/list-view/appender.mjs
var import_compose68 = __toESM(require_compose(), 1);
var import_a11y13 = __toESM(require_a11y(), 1);
var import_data126 = __toESM(require_data(), 1);
var import_element131 = __toESM(require_element(), 1);
var import_i18n108 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/list-view/context.mjs
var import_element129 = __toESM(require_element(), 1);
var ListViewContext = (0, import_element129.createContext)({});
ListViewContext.displayName = "ListViewContext";
var useListViewContext = () => (0, import_element129.useContext)(ListViewContext);
// packages/block-editor/build-module/components/list-view/aria-referenced-text.mjs
var import_element130 = __toESM(require_element(), 1);
var import_jsx_runtime263 = __toESM(require_jsx_runtime(), 1);
function AriaReferencedText({ children, ...props }) {
const ref = (0, import_element130.useRef)();
(0, import_element130.useEffect)(() => {
if (ref.current) {
ref.current.textContent = ref.current.textContent;
}
}, [children]);
return /* @__PURE__ */ (0, import_jsx_runtime263.jsx)("div", { hidden: true, ...props, ref, children });
}
// packages/block-editor/build-module/components/list-view/appender.mjs
var import_jsx_runtime264 = __toESM(require_jsx_runtime(), 1);
var Appender = (0, import_element131.forwardRef)(
({ nestingLevel, blockCount, clientId, ...props }, ref) => {
const { insertedBlock, setInsertedBlock } = useListViewContext();
const instanceId = (0, import_compose68.useInstanceId)(Appender);
const { directInsert, hideInserter } = (0, import_data126.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_element131.useEffect)(() => {
if (!insertedBlockTitle?.length) {
return;
}
(0, import_a11y13.speak)(
(0, import_i18n108.sprintf)(
// translators: %s: name of block being inserted (i.e. Paragraph, Image, Group etc)
(0, import_i18n108.__)("%s block inserted"),
insertedBlockTitle
),
"assertive"
);
}, [insertedBlockTitle]);
if (hideInserter) {
return null;
}
const descriptionId = `list-view-appender__${instanceId}`;
const description = (0, import_i18n108.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_i18n108.__)("Append to %1$s block at position %2$d, Level %3$d"),
blockTitle,
blockCount + 1,
nestingLevel
);
return /* @__PURE__ */ (0, import_jsx_runtime264.jsxs)("div", { className: "list-view-appender", children: [
/* @__PURE__ */ (0, import_jsx_runtime264.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_runtime264.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_components121 = __toESM(require_components(), 1);
var import_compose70 = __toESM(require_compose(), 1);
var import_element137 = __toESM(require_element(), 1);
var import_data129 = __toESM(require_data(), 1);
var import_i18n111 = __toESM(require_i18n(), 1);
var import_keycodes13 = __toESM(require_keycodes(), 1);
var import_is_shallow_equal2 = __toESM(require_is_shallow_equal(), 1);
var import_keyboard_shortcuts10 = __toESM(require_keyboard_shortcuts(), 1);
var import_a11y14 = __toESM(require_a11y(), 1);
// packages/block-editor/build-module/components/list-view/leaf.mjs
var import_components119 = __toESM(require_components(), 1);
var import_compose69 = __toESM(require_compose(), 1);
var import_element132 = __toESM(require_element(), 1);
var import_jsx_runtime265 = __toESM(require_jsx_runtime(), 1);
var AnimatedTreeGridRow = animated(import_components119.__experimentalTreeGridRow);
var ListViewLeaf = (0, import_element132.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_compose69.useMergeRefs)([ref, animationRef]);
return /* @__PURE__ */ (0, import_jsx_runtime265.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_dom29 = __toESM(require_dom(), 1);
var import_element133 = __toESM(require_element(), 1);
function useListViewScrollIntoView({
isSelected,
selectedClientIds,
rowItemRef
}) {
const isSingleSelection = selectedClientIds.length === 1;
(0, import_element133.useLayoutEffect)(() => {
if (!isSelected || !isSingleSelection || !rowItemRef.current) {
return;
}
const scrollContainer = (0, import_dom29.getScrollContainer)(rowItemRef.current);
const { ownerDocument } = rowItemRef.current;
const windowScroll = scrollContainer === ownerDocument.body || scrollContainer === ownerDocument.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_element136 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/list-view/block-select-button.mjs
var import_components120 = __toESM(require_components(), 1);
var import_element135 = __toESM(require_element(), 1);
var import_keycodes12 = __toESM(require_keycodes(), 1);
var import_data128 = __toESM(require_data(), 1);
var import_blocks78 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/components/list-view/expander.mjs
var import_i18n109 = __toESM(require_i18n(), 1);
var import_jsx_runtime266 = __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_runtime266.jsx)(
"span",
{
className: "block-editor-list-view__expander",
onClick: (event) => onClick(event, { forceToggle: true }),
"aria-hidden": "true",
"data-testid": "list-view-expander",
children: /* @__PURE__ */ (0, import_jsx_runtime266.jsx)(icon_default, { icon: (0, import_i18n109.isRTL)() ? chevron_left_small_default : chevron_right_small_default })
}
)
);
}
// packages/block-editor/build-module/components/list-view/use-list-view-images.mjs
var import_element134 = __toESM(require_element(), 1);
var import_data127 = __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_data127.useSelect)(
(select3) => {
return { block: select3(store).getBlock(clientId) };
},
[clientId]
);
const images = (0, import_element134.useMemo)(() => {
return getImagesFromBlock(block, isExpanded);
}, [block, isExpanded]);
return images;
}
// packages/block-editor/build-module/components/list-view/block-select-button.mjs
var import_jsx_runtime267 = __toESM(require_jsx_runtime(), 1);
var { Badge: Badge2 } = unlock(import_components120.privateApis);
function ListViewBlockSelectButton({
className,
block: { clientId },
onClick,
onContextMenu,
onMouseDown,
onToggleExpanded,
tabIndex,
onFocus,
onDragStart,
onDragEnd,
draggable,
isExpanded,
ariaDescribedBy
}, ref) {
const blockInformation = useBlockDisplayInformation(clientId);
const blockTitle = useBlockDisplayTitle({
clientId,
context: "list-view"
});
const { isLocked } = useBlockLock(clientId);
const { canToggleBlockVisibility, isBlockHidden: isBlockHidden2, hasPatternName } = (0, import_data128.useSelect)(
(select3) => {
const { getBlockName: getBlockName2, getBlockAttributes: getBlockAttributes3 } = select3(store);
const { areBlocksHiddenAnywhere: areBlocksHiddenAnywhere2 } = unlock(
select3(store)
);
const blockAttributes = getBlockAttributes3(clientId);
return {
canToggleBlockVisibility: (0, import_blocks78.hasBlockSupport)(
getBlockName2(clientId),
"visibility",
true
),
isBlockHidden: areBlocksHiddenAnywhere2([clientId]),
hasPatternName: !!blockAttributes?.metadata?.patternName
};
},
[clientId]
);
const shouldShowLockIcon = isLocked;
const shouldShowBlockVisibilityIcon = canToggleBlockVisibility && isBlockHidden2;
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_keycodes12.ENTER || event.keyCode === import_keycodes12.SPACE) {
onClick(event);
}
}
return /* @__PURE__ */ (0, import_jsx_runtime267.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: `#block-${clientId}`,
"aria-describedby": ariaDescribedBy,
"aria-expanded": isExpanded,
children: [
/* @__PURE__ */ (0, import_jsx_runtime267.jsx)(ListViewExpander, { onClick: onToggleExpanded }),
/* @__PURE__ */ (0, import_jsx_runtime267.jsx)(
block_icon_default,
{
icon: hasPatternName ? symbol_default : blockInformation?.icon,
showColors: true,
context: "list-view"
}
),
/* @__PURE__ */ (0, import_jsx_runtime267.jsxs)(
import_components120.__experimentalHStack,
{
alignment: "center",
className: "block-editor-list-view-block-select-button__label-wrapper",
justify: "flex-start",
spacing: 1,
children: [
/* @__PURE__ */ (0, import_jsx_runtime267.jsx)("span", { className: "block-editor-list-view-block-select-button__title", children: /* @__PURE__ */ (0, import_jsx_runtime267.jsx)(import_components120.__experimentalTruncate, { ellipsizeMode: "auto", children: blockTitle }) }),
blockInformation?.anchor && /* @__PURE__ */ (0, import_jsx_runtime267.jsx)("span", { className: "block-editor-list-view-block-select-button__anchor-wrapper", children: /* @__PURE__ */ (0, import_jsx_runtime267.jsx)(Badge2, { className: "block-editor-list-view-block-select-button__anchor", children: blockInformation.anchor }) }),
isSticky && /* @__PURE__ */ (0, import_jsx_runtime267.jsx)("span", { className: "block-editor-list-view-block-select-button__sticky", children: /* @__PURE__ */ (0, import_jsx_runtime267.jsx)(icon_default, { icon: pin_small_default }) }),
images.length ? /* @__PURE__ */ (0, import_jsx_runtime267.jsx)(
"span",
{
className: "block-editor-list-view-block-select-button__images",
"aria-hidden": true,
children: images.map((image, index) => /* @__PURE__ */ (0, import_jsx_runtime267.jsx)(
"span",
{
className: "block-editor-list-view-block-select-button__image",
style: {
backgroundImage: `url(${image.url})`,
zIndex: images.length - index
// Ensure the first image is on top, and subsequent images are behind.
}
},
image.clientId
))
}
) : null,
shouldShowBlockVisibilityIcon && /* @__PURE__ */ (0, import_jsx_runtime267.jsx)("span", { className: "block-editor-list-view-block-select-button__block-visibility", children: /* @__PURE__ */ (0, import_jsx_runtime267.jsx)(icon_default, { icon: unseen_default }) }),
shouldShowLockIcon && /* @__PURE__ */ (0, import_jsx_runtime267.jsx)("span", { className: "block-editor-list-view-block-select-button__lock", children: /* @__PURE__ */ (0, import_jsx_runtime267.jsx)(icon_default, { icon: lock_small_default }) })
]
}
)
]
}
);
}
var block_select_button_default = (0, import_element135.forwardRef)(ListViewBlockSelectButton);
// packages/block-editor/build-module/components/list-view/block-contents.mjs
var import_jsx_runtime268 = __toESM(require_jsx_runtime(), 1);
var ListViewBlockContents = (0, import_element136.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_runtime268.jsxs)(import_jsx_runtime268.Fragment, { children: [
AdditionalBlockContent && /* @__PURE__ */ (0, import_jsx_runtime268.jsx)(
AdditionalBlockContent,
{
block,
insertedBlock,
setInsertedBlock
}
),
/* @__PURE__ */ (0, import_jsx_runtime268.jsx)(
block_draggable_default,
{
appendToOwnerDocument: true,
clientIds: draggableClientIds,
cloneClassname: "block-editor-list-view-draggable-chip",
children: ({ draggable, onDragStart, onDragEnd }) => /* @__PURE__ */ (0, import_jsx_runtime268.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_i18n110 = __toESM(require_i18n(), 1);
var import_dom30 = __toESM(require_dom(), 1);
var getBlockPositionDescription = (position, siblingCount, level) => (0, import_i18n110.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_i18n110.__)("Block %1$d of %2$d, Level %3$d."),
position,
siblingCount,
level
);
var getBlockPropertiesDescription = (blockInformation, isLocked) => [
blockInformation?.positionLabel ? `${(0, import_i18n110.sprintf)(
// translators: %s: Position of selected block, e.g. "Sticky" or "Fixed".
(0, import_i18n110.__)("Position: %s"),
blockInformation.positionLabel
)}.` : void 0,
isLocked ? (0, import_i18n110.__)("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) => {
import_dom30.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_runtime269 = __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_element137.useRef)(null);
const rowRef = (0, import_element137.useRef)(null);
const settingsRef = (0, import_element137.useRef)(null);
const [isHovered, setIsHovered] = (0, import_element137.useState)(false);
const [settingsAnchorRect, setSettingsAnchorRect] = (0, import_element137.useState)();
const [visibilityModalClientIds, setVisibilityModalClientIds] = (0, import_element137.useState)(null);
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,
updateBlockAttributes: updateBlockAttributes2
} = unlock((0, import_data129.useDispatch)(store));
const debouncedToggleBlockHighlight = (0, import_compose70.useDebounce)(
toggleBlockHighlight2,
50
);
const {
canInsertBlockType: canInsertBlockType2,
getSelectedBlockClientIds: getSelectedBlockClientIds2,
getPreviousBlockClientId: getPreviousBlockClientId2,
getBlockRootClientId: getBlockRootClientId2,
getBlockOrder: getBlockOrder2,
getBlockParents: getBlockParents2,
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, allowRightClickOverrides, isBlockHidden: isBlockHidden2 } = (0, import_data129.useSelect)(
(select3) => {
const {
getBlock: getBlock2,
getBlockName: _getBlockName,
getSettings: getSettings8
} = select3(store);
const { isBlockHidden: _isBlockHidden } = unlock(
select3(store)
);
return {
block: getBlock2(clientId),
blockName: _getBlockName(clientId),
allowRightClickOverrides: getSettings8().allowRightClickOverrides,
isBlockHidden: _isBlockHidden(clientId)
};
},
[clientId]
);
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_compose70.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_shortcuts10.__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;
}
const isDeleteKey = [import_keycodes13.BACKSPACE, import_keycodes13.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_i18n111.__)("Selected blocks are grouped."));
const newlySelectedBlocks = getSelectedBlockClientIds2();
updateFocusAndSelection(newlySelectedBlocks[0], false);
}
} else if (isMatch("core/block-editor/toggle-block-visibility", event)) {
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 (window.__experimentalHideBlocksBasedOnScreenSize) {
setVisibilityModalClientIds(blocksToUpdate);
} else {
const hasHiddenBlock = blocks2.some(
(blockToUpdate) => blockToUpdate.attributes.metadata?.blockVisibility === false
);
const attributesByClientId = Object.fromEntries(
blocks2.map(({ clientId: mapClientId, attributes }) => [
mapClientId,
{
metadata: cleanEmptyObject({
...attributes?.metadata,
blockVisibility: hasHiddenBlock ? void 0 : false
})
}
])
);
updateBlockAttributes2(blocksToUpdate, attributesByClientId, {
uniqueByBlock: true
});
}
}
}
const onMouseEnter = (0, import_element137.useCallback)(() => {
setIsHovered(true);
debouncedToggleBlockHighlight(clientId, true);
}, [clientId, setIsHovered, debouncedToggleBlockHighlight]);
const onMouseLeave = (0, import_element137.useCallback)(() => {
setIsHovered(false);
debouncedToggleBlockHighlight(clientId, false);
}, [clientId, setIsHovered, debouncedToggleBlockHighlight]);
const selectEditorBlock = (0, import_element137.useCallback)(
(event) => {
selectBlock2(event, clientId);
event.preventDefault();
},
[clientId, selectBlock2]
);
const updateFocusAndSelection = (0, import_element137.useCallback)(
(focusClientId, shouldSelectBlock) => {
if (shouldSelectBlock) {
selectBlock2(void 0, focusClientId, null, null);
}
focusListItem(focusClientId, treeGridElementRef?.current);
},
[selectBlock2, treeGridElementRef]
);
const toggleExpanded = (0, import_element137.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_element137.useCallback)(
(event) => {
const { ownerDocument } = settingsRef?.current || {};
if (!ownerDocument || !ownerDocument.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_element137.useCallback)(
(event) => {
if (allowRightClickOverrides && event.button === 2) {
event.preventDefault();
}
},
[allowRightClickOverrides]
);
const settingsPopoverAnchor = (0, import_element137.useMemo)(() => {
const { ownerDocument } = rowRef?.current || {};
if (!settingsAnchorRect || !ownerDocument) {
return void 0;
}
return {
ownerDocument,
getBoundingClientRect() {
return settingsAnchorRect;
}
};
}, [settingsAnchorRect]);
const clearSettingsAnchorRect = (0, import_element137.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 = isBlockHidden2 ? (0, import_i18n111.__)("Block is hidden.") : null;
const hasSiblings = siblingBlockCount > 0;
const hasRenderedMovers = showBlockMovers && hasSiblings;
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 (!showBlockActions) {
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,
"is-displacement-normal": displacement === "normal",
"is-displacement-up": displacement === "up",
"is-displacement-down": displacement === "down",
"is-after-dragged-blocks": isAfterDraggedBlocks,
"is-nesting": isNesting
});
const dropdownClientIds = selectedClientIds.includes(clientId) ? selectedClientIds : [clientId];
const currentlyEditingBlockInCanvas = isSelected && selectedClientIds.length === 1;
return /* @__PURE__ */ (0, import_jsx_runtime269.jsxs)(
leaf_default,
{
className: classes,
isDragged,
onKeyDown,
onMouseEnter,
onMouseLeave,
onFocus: onMouseEnter,
onBlur: 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_runtime269.jsx)(
import_components121.__experimentalTreeGridCell,
{
className: "block-editor-list-view-block__contents-cell",
colSpan,
ref: cellRef,
"aria-selected": !!isSelected,
children: ({ ref, tabIndex, onFocus }) => /* @__PURE__ */ (0, import_jsx_runtime269.jsxs)("div", { className: "block-editor-list-view-block__contents-container", children: [
/* @__PURE__ */ (0, import_jsx_runtime269.jsx)(
block_contents_default,
{
block,
onClick: selectEditorBlock,
onContextMenu,
onMouseDown,
onToggleExpanded: toggleExpanded,
isSelected,
position,
siblingBlockCount,
level,
ref,
tabIndex: currentlyEditingBlockInCanvas ? 0 : tabIndex,
onFocus,
isExpanded: canEditBlock2 ? isExpanded : void 0,
selectedClientIds,
ariaDescribedBy: descriptionId
}
),
/* @__PURE__ */ (0, import_jsx_runtime269.jsx)(AriaReferencedText, { id: descriptionId, children: [
blockPositionDescription,
blockPropertiesDescription,
blockVisibilityDescription
].filter(Boolean).join(" ") })
] })
}
),
hasRenderedMovers && /* @__PURE__ */ (0, import_jsx_runtime269.jsx)(import_jsx_runtime269.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime269.jsxs)(
import_components121.__experimentalTreeGridCell,
{
className: moverCellClassName,
withoutGridItem: true,
children: [
/* @__PURE__ */ (0, import_jsx_runtime269.jsx)(import_components121.__experimentalTreeGridItem, { children: ({ ref, tabIndex, onFocus }) => /* @__PURE__ */ (0, import_jsx_runtime269.jsx)(
BlockMoverUpButton,
{
orientation: "vertical",
clientIds: [clientId],
ref,
tabIndex,
onFocus
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime269.jsx)(import_components121.__experimentalTreeGridItem, { children: ({ ref, tabIndex, onFocus }) => /* @__PURE__ */ (0, import_jsx_runtime269.jsx)(
BlockMoverDownButton,
{
orientation: "vertical",
clientIds: [clientId],
ref,
tabIndex,
onFocus
}
) })
]
}
) }),
showBlockActions && BlockSettingsMenu2 && /* @__PURE__ */ (0, import_jsx_runtime269.jsx)(
import_components121.__experimentalTreeGridCell,
{
className: listViewBlockSettingsClassName,
"aria-selected": !!isSelected,
ref: settingsRef,
children: ({ ref, tabIndex, onFocus }) => /* @__PURE__ */ (0, import_jsx_runtime269.jsx)(
BlockSettingsMenu2,
{
clientIds: dropdownClientIds,
block,
icon: more_vertical_default,
label: (0, import_i18n111.__)("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
}
)
}
),
visibilityModalClientIds && /* @__PURE__ */ (0, import_jsx_runtime269.jsx)(
BlockVisibilityModal,
{
clientIds: visibilityModalClientIds,
onClose: () => setVisibilityModalClientIds(null)
}
)
]
}
);
}
var block_default3 = (0, import_element137.memo)(ListViewBlock);
// packages/block-editor/build-module/components/list-view/branch.mjs
var import_jsx_runtime270 = __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 noop10 = () => {
};
function ListViewBranch(props) {
const {
blocks: blocks2,
selectBlock: selectBlock2 = noop10,
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_element138.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_runtime270.jsxs)(import_jsx_runtime270.Fragment, { children: [
filteredBlocks.map((block, index) => {
const { clientId, innerBlocks } = block;
if (index > 0) {
nextPositionRef.current += countBlocks(
filteredBlocks[index - 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 = index + 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] || index === 0 || index === blockCount - 1;
return /* @__PURE__ */ (0, import_jsx_runtime270.jsxs)(import_data130.AsyncModeProvider, { value: !isSelected, children: [
showBlock && /* @__PURE__ */ (0, import_jsx_runtime270.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_runtime270.jsx)("tr", { children: /* @__PURE__ */ (0, import_jsx_runtime270.jsx)("td", { className: "block-editor-list-view-placeholder" }) }),
hasNestedBlocks && shouldExpand && !isDragged && /* @__PURE__ */ (0, import_jsx_runtime270.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_runtime270.jsx)(
import_components122.__experimentalTreeGridRow,
{
level,
setSize: rowCount,
positionInSet: rowCount,
isExpanded: true,
children: /* @__PURE__ */ (0, import_jsx_runtime270.jsx)(import_components122.__experimentalTreeGridCell, { children: (treeGridCellProps) => /* @__PURE__ */ (0, import_jsx_runtime270.jsx)(
Appender,
{
clientId: parentId,
nestingLevel: level,
blockCount,
...treeGridCellProps
}
) })
}
)
] });
}
var branch_default = (0, import_element138.memo)(ListViewBranch);
// packages/block-editor/build-module/components/list-view/drop-indicator.mjs
var import_components123 = __toESM(require_components(), 1);
var import_dom31 = __toESM(require_dom(), 1);
var import_element139 = __toESM(require_element(), 1);
var import_i18n112 = __toESM(require_i18n(), 1);
var import_jsx_runtime271 = __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_element139.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_i18n112.isRTL)();
const getDropIndicatorWidth = (0, import_element139.useCallback)(
(targetElementRect, indent) => {
if (!targetElement) {
return 0;
}
let width = targetElement.offsetWidth;
const scrollContainer = (0, import_dom31.getScrollContainer)(
targetElement,
"horizontal"
);
const ownerDocument = targetElement.ownerDocument;
const windowScroll = scrollContainer === ownerDocument.body || scrollContainer === ownerDocument.documentElement;
if (scrollContainer && !windowScroll) {
const scrollContainerRect = scrollContainer.getBoundingClientRect();
const distanceBetweenContainerAndTarget = (0, import_i18n112.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_element139.useMemo)(() => {
if (!targetElement) {
return {};
}
const targetElementRect = targetElement.getBoundingClientRect();
return {
width: getDropIndicatorWidth(targetElementRect, 0)
};
}, [getDropIndicatorWidth, targetElement]);
const horizontalScrollOffsetStyle = (0, import_element139.useMemo)(() => {
if (!targetElement) {
return {};
}
const scrollContainer = (0, import_dom31.getScrollContainer)(targetElement);
const ownerDocument = targetElement.ownerDocument;
const windowScroll = scrollContainer === ownerDocument.body || scrollContainer === ownerDocument.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_element139.useMemo)(() => {
if (!rootBlockElement) {
return 1;
}
const _ariaLevel = parseInt(
rootBlockElement.getAttribute("aria-level"),
10
);
return _ariaLevel ? _ariaLevel + 1 : 1;
}, [rootBlockElement]);
const hasAdjacentSelectedBranch = (0, import_element139.useMemo)(() => {
if (!targetElement) {
return false;
}
return targetElement.classList.contains("is-branch-selected");
}, [targetElement]);
const popoverAnchor = (0, import_element139.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_dom31.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_runtime271.jsx)(
import_components123.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_runtime271.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_runtime271.jsxs)(
"div",
{
className: "block-editor-list-view-leaf",
"aria-level": ariaLevel,
children: [
/* @__PURE__ */ (0, import_jsx_runtime271.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_runtime271.jsx)(ListViewExpander, { onClick: () => {
} }),
/* @__PURE__ */ (0, import_jsx_runtime271.jsx)(
block_icon_default,
{
icon: blockInformation?.icon,
showColors: true,
context: "list-view"
}
),
/* @__PURE__ */ (0, import_jsx_runtime271.jsx)(
import_components123.__experimentalHStack,
{
alignment: "center",
className: "block-editor-list-view-block-select-button__label-wrapper",
justify: "flex-start",
spacing: 1,
children: /* @__PURE__ */ (0, import_jsx_runtime271.jsx)("span", { className: "block-editor-list-view-block-select-button__title", children: /* @__PURE__ */ (0, import_jsx_runtime271.jsx)(import_components123.__experimentalTruncate, { ellipsizeMode: "auto", children: blockTitle }) })
}
)
]
}
),
/* @__PURE__ */ (0, import_jsx_runtime271.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_i18n113 = __toESM(require_i18n(), 1);
var import_data131 = __toESM(require_data(), 1);
var import_element140 = __toESM(require_element(), 1);
var import_keycodes14 = __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: getBlockType24 } = (0, import_data131.useSelect)(import_blocks80.store);
const updateBlockSelection = (0, import_element140.useCallback)(
async (event, clientId, destinationClientId, focusPosition) => {
if (!event?.shiftKey && event?.keyCode !== import_keycodes14.ESCAPE) {
selectBlock2(clientId, focusPosition);
return;
}
event.preventDefault();
const isOnlyDeselection = event.type === "keydown" && event.keyCode === import_keycodes14.ESCAPE;
const isKeyPress = event.type === "keydown" && (event.keyCode === import_keycodes14.UP || event.keyCode === import_keycodes14.DOWN || event.keyCode === import_keycodes14.HOME || event.keyCode === import_keycodes14.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_keycodes14.HOME || event.keyCode === import_keycodes14.END) && updatedSelectedBlocks.length > 1) {
return;
}
const selectionDiff = selectedBlocks.filter(
(blockId) => !updatedSelectedBlocks.includes(blockId)
);
let label;
if (selectionDiff.length === 1) {
const title = getBlockType24(
getBlockName2(selectionDiff[0])
)?.title;
if (title) {
label = (0, import_i18n113.sprintf)(
/* translators: %s: block name */
(0, import_i18n113.__)("%s deselected."),
title
);
}
} else if (selectionDiff.length > 1) {
label = (0, import_i18n113.sprintf)(
/* translators: %s: number of deselected blocks */
(0, import_i18n113.__)("%s blocks deselected."),
selectionDiff.length
);
}
if (label) {
(0, import_a11y15.speak)(label, "assertive");
}
},
[
clearSelectedBlock2,
getBlockName2,
getBlockType24,
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_element141 = __toESM(require_element(), 1);
function useListViewBlockIndexes(blocks2) {
const blockIndexes = (0, import_element141.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,
getEnabledClientIdsTree: getEnabledClientIdsTree2
} = unlock(select3(store));
return {
selectedClientIds: getSelectedBlockClientIds2(),
draggedClientIds: getDraggedBlockClientIds2(),
clientIdsTree: blocks2 ?? getEnabledClientIdsTree2(rootClientId)
};
},
[blocks2, rootClientId]
);
}
// packages/block-editor/build-module/components/list-view/use-list-view-collapse-items.mjs
var import_element142 = __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_element142.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_element143 = __toESM(require_element(), 1);
var import_compose71 = __toESM(require_compose(), 1);
var import_i18n114 = __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, index) {
const nextBlockData = blocksData[index + 1];
if (nextBlockData && nextBlockData.isDraggedBlock) {
return getNextNonDraggedBlock(blocksData, index + 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 index = blocksData.indexOf(blockData);
const previousBlockData = blocksData[index - 1];
if (edge === "top" && previousBlockData && previousBlockData.rootClientId === blockData.rootClientId && !previousBlockData.isDraggedBlock) {
candidateBlockData = previousBlockData;
candidateEdge = "bottom";
candidateRect = previousBlockData.element.getBoundingClientRect();
candidateBlockIndex = index - 1;
} else {
candidateBlockData = blockData;
candidateEdge = edge;
candidateRect = rect;
candidateBlockIndex = index;
}
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 offset = isDraggingBelow ? 1 : 0;
return {
rootClientId: candidateBlockData.rootClientId,
clientId: candidateBlockData.clientId,
blockIndex: candidateBlockData.blockIndex + offset,
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_element143.useState)();
const { rootClientId: targetRootClientId, blockIndex: targetBlockIndex } = target || {};
const onBlockDrop2 = useOnBlockDrop(targetRootClientId, targetBlockIndex);
const rtl = (0, import_i18n114.isRTL)();
const previousRootClientId = (0, import_compose71.usePrevious)(targetRootClientId);
const maybeExpandBlock = (0, import_element143.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_compose71.useThrottle)(
maybeExpandBlock,
500,
EXPAND_THROTTLE_OPTIONS
);
(0, import_element143.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_compose71.useThrottle)(
(0, import_element143.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_compose71.__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_element144 = __toESM(require_element(), 1);
var import_data135 = __toESM(require_data(), 1);
function useListViewExpandSelectedItem({
firstSelectedBlockClientId,
setExpandedState
}) {
const [selectedTreeId, setSelectedTreeId] = (0, import_element144.useState)(null);
const { selectedBlockParentClientIds } = (0, import_data135.useSelect)(
(select3) => {
const { getBlockParents: getBlockParents2 } = select3(store);
return {
selectedBlockParentClientIds: getBlockParents2(
firstSelectedBlockClientId,
false
)
};
},
[firstSelectedBlockClientId]
);
(0, import_element144.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_compose72 = __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: getSettings8,
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_compose72.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
} = getSettings8();
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_runtime272 = __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_compose73.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_element145.useReducer)(expanded, {});
const [insertedBlock, setInsertedBlock] = (0, import_element145.useState)(null);
const { setSelectedTreeId } = useListViewExpandSelectedItem({
firstSelectedBlockClientId: selectedClientIds[0],
setExpandedState
});
const selectEditorBlock = (0, import_element145.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_element145.useRef)();
const clipBoardRef = useClipboardHandler2({
selectBlock: selectEditorBlock
});
const focusSelectedBlock = (0, import_element145.useCallback)(
(node) => {
const [firstSelectedClientId] = getSelectedBlockClientIds2();
if (firstSelectedClientId && node) {
focusListItem(firstSelectedClientId, node);
}
},
[getSelectedBlockClientIds2]
);
const treeGridRef = (0, import_compose73.useMergeRefs)([
clipBoardRef,
focusSelectedBlock,
elementRef,
dropZoneRef,
ref
]);
const expand = (0, import_element145.useCallback)(
(clientId) => {
if (!clientId) {
return;
}
const clientIds = Array.isArray(clientId) ? clientId : [clientId];
setExpandedState({ type: "expand", clientIds });
},
[setExpandedState]
);
const collapse = (0, import_element145.useCallback)(
(clientId) => {
if (!clientId) {
return;
}
setExpandedState({ type: "collapse", clientIds: [clientId] });
},
[setExpandedState]
);
const collapseAll = (0, import_element145.useCallback)(() => {
setExpandedState({ type: "clear" });
}, [setExpandedState]);
const expandRow = (0, import_element145.useCallback)(
(row) => {
expand(row?.dataset?.block);
},
[expand]
);
const collapseRow = (0, import_element145.useCallback)(
(row) => {
collapse(row?.dataset?.block);
},
[collapse]
);
const focusRow = (0, import_element145.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_element145.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_element145.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_compose73.__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_runtime272.jsxs)(import_data137.AsyncModeProvider, { value: true, children: [
/* @__PURE__ */ (0, import_jsx_runtime272.jsx)(
ListViewDropIndicatorPreview,
{
draggedBlockClientId: firstDraggedBlockClientId,
listViewRef: elementRef,
blockDropTarget
}
),
description && /* @__PURE__ */ (0, import_jsx_runtime272.jsx)(import_components124.VisuallyHidden, { id: describedById, children: description }),
/* @__PURE__ */ (0, import_jsx_runtime272.jsx)(
import_components124.__experimentalTreeGrid,
{
id,
className: clsx_default("block-editor-list-view-tree", {
"is-dragging": draggedClientIds?.length > 0 && blockDropTargetIndex !== void 0
}),
"aria-label": (0, import_i18n115.__)("Block navigation structure"),
ref: treeGridRef,
onCollapseRow: collapseRow,
onExpandRow: expandRow,
onFocusRow: focusRow,
applicationAriaLabel: (0, import_i18n115.__)("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_runtime272.jsx)(ListViewContext.Provider, { value: contextValue, children: /* @__PURE__ */ (0, import_jsx_runtime272.jsx)(
branch_default,
{
blocks: clientIdsTree,
parentId: rootClientId,
selectBlock: selectEditorBlock,
showBlockMovers,
fixedListWindow,
selectedClientIds,
isExpanded,
showAppender
}
) })
}
)
] });
}
var PrivateListView = (0, import_element145.forwardRef)(ListViewComponent);
var list_view_default2 = (0, import_element145.forwardRef)((props, ref) => {
return /* @__PURE__ */ (0, import_jsx_runtime272.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_runtime273 = __toESM(require_jsx_runtime(), 1);
function BlockNavigationDropdownToggle({
isEnabled,
onToggle,
isOpen,
innerRef,
...props
}) {
return /* @__PURE__ */ (0, import_jsx_runtime273.jsx)(
import_components125.Button,
{
__next40pxDefaultSize: true,
...props,
ref: innerRef,
icon: list_view_default,
"aria-expanded": isOpen,
"aria-haspopup": "true",
onClick: isEnabled ? onToggle : void 0,
label: (0, import_i18n116.__)("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_runtime273.jsx)(
import_components125.Dropdown,
{
contentClassName: "block-editor-block-navigation__popover",
popoverProps: { placement: "bottom-start" },
renderToggle: ({ isOpen, onToggle }) => /* @__PURE__ */ (0, import_jsx_runtime273.jsx)(
BlockNavigationDropdownToggle,
{
...props,
innerRef: ref,
isOpen,
onToggle,
isEnabled
}
),
renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime273.jsxs)("div", { className: "block-editor-block-navigation__container", children: [
/* @__PURE__ */ (0, import_jsx_runtime273.jsx)("p", { className: "block-editor-block-navigation__label", children: (0, import_i18n116.__)("List view") }),
/* @__PURE__ */ (0, import_jsx_runtime273.jsx)(list_view_default2, {})
] })
}
);
}
var dropdown_default = (0, import_element146.forwardRef)(BlockNavigationDropdown);
// packages/block-editor/build-module/components/block-styles/index.mjs
var import_element148 = __toESM(require_element(), 1);
var import_compose74 = __toESM(require_compose(), 1);
var import_components126 = __toESM(require_components(), 1);
var import_i18n117 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/block-styles/preview-panel.mjs
var import_element147 = __toESM(require_element(), 1);
var import_jsx_runtime274 = __toESM(require_jsx_runtime(), 1);
function BlockStylesPreviewPanel({
genericPreviewBlock,
style,
className,
activeStyle
}) {
const styleClassName = replaceActiveStyle(className, activeStyle, style);
const previewBlocks = (0, import_element147.useMemo)(() => {
return {
name: genericPreviewBlock.name,
title: style.label || style.name,
description: style.description,
initialAttributes: {
...genericPreviewBlock.attributes,
className: styleClassName + " block-editor-block-styles__block-preview-container"
},
example: genericPreviewBlock
};
}, [genericPreviewBlock, style, styleClassName]);
return /* @__PURE__ */ (0, import_jsx_runtime274.jsx)(preview_panel_default, { item: previewBlocks });
}
// packages/block-editor/build-module/components/block-styles/index.mjs
var import_jsx_runtime275 = __toESM(require_jsx_runtime(), 1);
var noop11 = () => {
};
function BlockStyles({ clientId, onSwitch = noop11, onHoverClassName = noop11 }) {
const {
onSelect,
stylesToRender,
activeStyle,
genericPreviewBlock,
className: previewClassName
} = useStylesForBlocks({
clientId,
onSwitch
});
const [hoveredStyle, setHoveredStyle] = (0, import_element148.useState)(null);
const isMobileViewport = (0, import_compose74.useViewportMatch)("medium", "<");
const dropdownMenuProps = useToolsPanelDropdownMenuProps();
if (!stylesToRender || stylesToRender.length === 0) {
return null;
}
const debouncedSetHoveredStyle = (0, import_compose74.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_runtime275.jsx)(
import_components126.__experimentalToolsPanel,
{
label: (0, import_i18n117.__)("Styles"),
resetAll: onDeselect,
panelId: clientId,
hasInnerWrapper: true,
dropdownMenuProps,
children: /* @__PURE__ */ (0, import_jsx_runtime275.jsx)(
import_components126.__experimentalToolsPanelItem,
{
hasValue,
label: (0, import_i18n117.__)("Variation"),
onDeselect,
isShownByDefault: true,
panelId: clientId,
children: /* @__PURE__ */ (0, import_jsx_runtime275.jsxs)("div", { className: "block-editor-block-styles", children: [
/* @__PURE__ */ (0, import_jsx_runtime275.jsx)("div", { className: "block-editor-block-styles__variants", children: stylesToRender.map((style) => {
const buttonText = style.label || style.name;
return /* @__PURE__ */ (0, import_jsx_runtime275.jsx)(
import_components126.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_runtime275.jsx)(
import_components126.__experimentalTruncate,
{
numberOfLines: 1,
className: "block-editor-block-styles__item-text",
children: buttonText
}
)
},
style.name
);
}) }),
hoveredStyle && !isMobileViewport && /* @__PURE__ */ (0, import_jsx_runtime275.jsx)(
import_components126.Popover,
{
placement: "left-start",
offset: 34,
focusOnMount: false,
children: /* @__PURE__ */ (0, import_jsx_runtime275.jsx)(
"div",
{
className: "block-editor-block-styles__preview-panel",
onMouseLeave: () => styleItemHandler(null),
children: /* @__PURE__ */ (0, import_jsx_runtime275.jsx)(
BlockStylesPreviewPanel,
{
activeStyle,
className: previewClassName,
genericPreviewBlock,
style: hoveredStyle
}
)
}
)
}
)
] })
}
)
}
);
}
var block_styles_default = BlockStyles;
// packages/block-editor/build-module/components/block-heading-level-dropdown/index.mjs
var import_components128 = __toESM(require_components(), 1);
var import_i18n118 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/block-heading-level-dropdown/heading-level-icon.mjs
var import_components127 = __toESM(require_components(), 1);
var import_jsx_runtime276 = __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_runtime276.jsx)(import_components127.Icon, { icon: LEVEL_TO_PATH[level] });
}
return null;
}
// packages/block-editor/build-module/components/block-heading-level-dropdown/index.mjs
var import_jsx_runtime277 = __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_runtime277.jsx)(
import_components128.ToolbarDropdownMenu,
{
popoverProps: POPOVER_PROPS6,
icon: /* @__PURE__ */ (0, import_jsx_runtime277.jsx)(HeadingLevelIcon, { level: value }),
label: (0, import_i18n118.__)("Change level"),
controls: validOptions.map((targetLevel) => {
const isActive = targetLevel === value;
return {
icon: /* @__PURE__ */ (0, import_jsx_runtime277.jsx)(HeadingLevelIcon, { level: targetLevel }),
title: targetLevel === 0 ? (0, import_i18n118.__)("Paragraph") : (0, import_i18n118.sprintf)(
// translators: %d: heading level e.g: "1", "2", "3"
(0, import_i18n118.__)("Heading %d"),
targetLevel
),
isActive,
onClick() {
onChange(targetLevel);
},
role: "menuitemradio"
};
})
}
);
}
// packages/block-editor/build-module/components/block-variation-picker/index.mjs
var import_i18n119 = __toESM(require_i18n(), 1);
var import_components129 = __toESM(require_components(), 1);
var import_jsx_runtime278 = __toESM(require_jsx_runtime(), 1);
function BlockVariationPicker({
icon = layout_default,
label = (0, import_i18n119.__)("Choose variation"),
instructions = (0, import_i18n119.__)("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_runtime278.jsxs)(
import_components129.Placeholder,
{
icon,
label,
instructions,
className: classes,
children: [
/* @__PURE__ */ (0, import_jsx_runtime278.jsx)(
"ul",
{
className: "block-editor-block-variation-picker__variations",
role: "list",
"aria-label": (0, import_i18n119.__)("Block variations"),
children: variations.map((variation) => /* @__PURE__ */ (0, import_jsx_runtime278.jsxs)("li", { children: [
/* @__PURE__ */ (0, import_jsx_runtime278.jsx)(
import_components129.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_runtime278.jsx)("span", { className: "block-editor-block-variation-picker__variation-label", children: variation.title })
] }, variation.name))
}
),
allowSkip && /* @__PURE__ */ (0, import_jsx_runtime278.jsx)("div", { className: "block-editor-block-variation-picker__skip", children: /* @__PURE__ */ (0, import_jsx_runtime278.jsx)(
import_components129.Button,
{
__next40pxDefaultSize: true,
variant: "link",
onClick: () => onSelect(),
children: (0, import_i18n119.__)("Skip")
}
) })
]
}
);
}
var block_variation_picker_default = BlockVariationPicker;
// packages/block-editor/build-module/components/block-pattern-setup/index.mjs
var import_data140 = __toESM(require_data(), 1);
var import_blocks81 = __toESM(require_blocks(), 1);
var import_components131 = __toESM(require_components(), 1);
var import_element149 = __toESM(require_element(), 1);
var import_compose75 = __toESM(require_compose(), 1);
var import_i18n121 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/block-pattern-setup/setup-toolbar.mjs
var import_i18n120 = __toESM(require_i18n(), 1);
var import_components130 = __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_runtime279 = __toESM(require_jsx_runtime(), 1);
var Actions = ({ onBlockPatternSelect }) => /* @__PURE__ */ (0, import_jsx_runtime279.jsx)("div", { className: "block-editor-block-pattern-setup__actions", children: /* @__PURE__ */ (0, import_jsx_runtime279.jsx)(
import_components130.Button,
{
__next40pxDefaultSize: true,
variant: "primary",
onClick: onBlockPatternSelect,
children: (0, import_i18n120.__)("Choose")
}
) });
var CarouselNavigation = ({
handlePrevious,
handleNext,
activeSlide,
totalSlides
}) => /* @__PURE__ */ (0, import_jsx_runtime279.jsxs)("div", { className: "block-editor-block-pattern-setup__navigation", children: [
/* @__PURE__ */ (0, import_jsx_runtime279.jsx)(
import_components130.Button,
{
size: "compact",
icon: (0, import_i18n120.isRTL)() ? chevron_right_default : chevron_left_default,
label: (0, import_i18n120.__)("Previous pattern"),
onClick: handlePrevious,
disabled: activeSlide === 0,
accessibleWhenDisabled: true
}
),
/* @__PURE__ */ (0, import_jsx_runtime279.jsx)(
import_components130.Button,
{
size: "compact",
icon: (0, import_i18n120.isRTL)() ? chevron_left_default : chevron_right_default,
label: (0, import_i18n120.__)("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_runtime279.jsxs)("div", { className: "block-editor-block-pattern-setup__display-controls", children: [
/* @__PURE__ */ (0, import_jsx_runtime279.jsx)(
import_components130.Button,
{
size: "compact",
icon: stretch_full_width_default,
label: (0, import_i18n120.__)("Carousel view"),
onClick: () => setViewMode(VIEWMODES.carousel),
isPressed: isCarouselView
}
),
/* @__PURE__ */ (0, import_jsx_runtime279.jsx)(
import_components130.Button,
{
size: "compact",
icon: grid_default,
label: (0, import_i18n120.__)("Grid view"),
onClick: () => setViewMode(VIEWMODES.grid),
isPressed: viewMode === VIEWMODES.grid
}
)
] });
return /* @__PURE__ */ (0, import_jsx_runtime279.jsxs)("div", { className: "block-editor-block-pattern-setup__toolbar", children: [
isCarouselView && /* @__PURE__ */ (0, import_jsx_runtime279.jsx)(
CarouselNavigation,
{
handlePrevious,
handleNext,
activeSlide,
totalSlides
}
),
displayControls,
isCarouselView && /* @__PURE__ */ (0, import_jsx_runtime279.jsx)(Actions, { onBlockPatternSelect })
] });
};
var setup_toolbar_default = SetupToolbar;
// packages/block-editor/build-module/components/block-pattern-setup/use-patterns-setup.mjs
var import_data139 = __toESM(require_data(), 1);
function usePatternsSetup(clientId, blockName, filterPatternsFn) {
return (0, import_data139.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_runtime280 = __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_runtime280.jsx)("div", { className: "block-editor-block-pattern-setup__carousel", children: /* @__PURE__ */ (0, import_jsx_runtime280.jsx)("div", { className: containerClass, children: /* @__PURE__ */ (0, import_jsx_runtime280.jsx)("div", { className: "carousel-container", children: patterns.map((pattern, index) => /* @__PURE__ */ (0, import_jsx_runtime280.jsx)(
BlockPatternSlide,
{
active: index === activeSlide,
className: slideClass.get(index) || "",
pattern
},
pattern.name
)) }) }) });
}
return /* @__PURE__ */ (0, import_jsx_runtime280.jsx)("div", { className: "block-editor-block-pattern-setup__grid", children: /* @__PURE__ */ (0, import_jsx_runtime280.jsx)(
import_components131.Composite,
{
role: "listbox",
className: containerClass,
"aria-label": (0, import_i18n121.__)("Patterns list"),
children: patterns.map((pattern) => /* @__PURE__ */ (0, import_jsx_runtime280.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_compose75.useInstanceId)(
BlockPattern3,
`${baseClassName}__item-description`
);
return /* @__PURE__ */ (0, import_jsx_runtime280.jsx)("div", { className: `${baseClassName}__list-item`, children: /* @__PURE__ */ (0, import_jsx_runtime280.jsxs)(
import_components131.Composite.Item,
{
render: /* @__PURE__ */ (0, import_jsx_runtime280.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_runtime280.jsx)(
block_preview_default,
{
blocks: blocks2,
viewportWidth
}
),
showTitles && /* @__PURE__ */ (0, import_jsx_runtime280.jsx)("div", { className: `${baseClassName}__item-title`, children: pattern.title }),
!!description && /* @__PURE__ */ (0, import_jsx_runtime280.jsx)(import_components131.VisuallyHidden, { id: descriptionId, children: description })
]
}
) });
}
function BlockPatternSlide({ active, className, pattern, minHeight }) {
const { blocks: blocks2, title, description } = pattern;
const descriptionId = (0, import_compose75.useInstanceId)(
BlockPatternSlide,
"block-editor-block-pattern-setup-list__item-description"
);
return /* @__PURE__ */ (0, import_jsx_runtime280.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_runtime280.jsx)(block_preview_default, { blocks: blocks2, minHeight }),
!!description && /* @__PURE__ */ (0, import_jsx_runtime280.jsx)(import_components131.VisuallyHidden, { id: descriptionId, children: description })
]
}
);
}
var BlockPatternSetup = ({
clientId,
blockName,
filterPatternsFn,
onBlockPatternSelect,
initialViewMode = VIEWMODES.carousel,
showTitles = false
}) => {
const [viewMode, setViewMode] = (0, import_element149.useState)(initialViewMode);
const [activeSlide, setActiveSlide] = (0, import_element149.useState)(0);
const { replaceBlock: replaceBlock2 } = (0, import_data140.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_runtime280.jsx)(import_jsx_runtime280.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime280.jsxs)(
"div",
{
className: `block-editor-block-pattern-setup view-mode-${viewMode}`,
children: [
/* @__PURE__ */ (0, import_jsx_runtime280.jsx)(
SetupContent,
{
viewMode,
activeSlide,
patterns,
onBlockPatternSelect: onPatternSelectCallback,
showTitles
}
),
/* @__PURE__ */ (0, import_jsx_runtime280.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_i18n122 = __toESM(require_i18n(), 1);
var import_components132 = __toESM(require_components(), 1);
var import_data141 = __toESM(require_data(), 1);
var import_element150 = __toESM(require_element(), 1);
var import_jsx_runtime281 = __toESM(require_jsx_runtime(), 1);
var { Menu: Menu3 } = unlock(import_components132.privateApis);
function VariationsButtons({
className,
onSelectVariation,
selectedValue,
variations
}) {
return /* @__PURE__ */ (0, import_jsx_runtime281.jsxs)("fieldset", { className, children: [
/* @__PURE__ */ (0, import_jsx_runtime281.jsx)(import_components132.VisuallyHidden, { as: "legend", children: (0, import_i18n122.__)("Transform to variation") }),
variations.map((variation) => /* @__PURE__ */ (0, import_jsx_runtime281.jsx)(
import_components132.Button,
{
__next40pxDefaultSize: true,
size: "compact",
icon: /* @__PURE__ */ (0, import_jsx_runtime281.jsx)(block_icon_default, { icon: variation.icon, showColors: true }),
isPressed: selectedValue === variation.name,
label: selectedValue === variation.name ? variation.title : (0, import_i18n122.sprintf)(
/* translators: %s: Block or block variation name. */
(0, import_i18n122.__)("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_runtime281.jsx)("div", { className, children: /* @__PURE__ */ (0, import_jsx_runtime281.jsxs)(Menu3, { children: [
/* @__PURE__ */ (0, import_jsx_runtime281.jsx)(
Menu3.TriggerButton,
{
render: /* @__PURE__ */ (0, import_jsx_runtime281.jsx)(
import_components132.Button,
{
className: "block-editor-block-variation-transforms__button",
__next40pxDefaultSize: true,
variant: "secondary",
children: (0, import_i18n122.__)("Transform to variation")
}
)
}
),
/* @__PURE__ */ (0, import_jsx_runtime281.jsx)(Menu3.Popover, { position: "bottom", children: /* @__PURE__ */ (0, import_jsx_runtime281.jsx)(Menu3.Group, { children: variations.map((variation) => /* @__PURE__ */ (0, import_jsx_runtime281.jsxs)(
Menu3.RadioItem,
{
value: variation.name,
checked: selectedValue === variation.name,
onChange: () => onSelectVariation(variation.name),
children: [
/* @__PURE__ */ (0, import_jsx_runtime281.jsx)(Menu3.ItemLabel, { children: variation.title }),
variation.description && /* @__PURE__ */ (0, import_jsx_runtime281.jsx)(Menu3.ItemHelpText, { children: variation.description })
]
},
variation.name
)) }) })
] }) });
}
function VariationsToggleGroupControl({
className,
onSelectVariation,
selectedValue,
variations
}) {
return /* @__PURE__ */ (0, import_jsx_runtime281.jsx)("div", { className, children: /* @__PURE__ */ (0, import_jsx_runtime281.jsx)(
import_components132.__experimentalToggleGroupControl,
{
label: (0, import_i18n122.__)("Transform to variation"),
value: selectedValue,
hideLabelFromVision: true,
onChange: onSelectVariation,
__next40pxDefaultSize: true,
children: variations.map((variation) => /* @__PURE__ */ (0, import_jsx_runtime281.jsx)(
import_components132.__experimentalToggleGroupControlOptionIcon,
{
icon: /* @__PURE__ */ (0, import_jsx_runtime281.jsx)(block_icon_default, { icon: variation.icon, showColors: true }),
value: variation.name,
label: selectedValue === variation.name ? variation.title : (0, import_i18n122.sprintf)(
/* translators: %s: Block or block variation name. */
(0, import_i18n122.__)("Transform to %s"),
variation.title
)
},
variation.name
))
}
) });
}
function __experimentalBlockVariationTransforms({ blockClientId }) {
const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data141.useDispatch)(store);
const { activeBlockVariation, variations, isContentOnly, isSection } = (0, import_data141.useSelect)(
(select3) => {
const { getActiveBlockVariation, getBlockVariations: getBlockVariations2 } = select3(import_blocks82.store);
const {
getBlockName: getBlockName2,
getBlockAttributes: getBlockAttributes3,
getBlockEditingMode: getBlockEditingMode2,
isSectionBlock: isSectionBlock2
} = unlock(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"),
isContentOnly: getBlockEditingMode2(blockClientId) === "contentOnly" && !isContentBlock4,
isSection: isSectionBlock2(blockClientId)
};
},
[blockClientId]
);
const selectedValue = activeBlockVariation?.name;
const hasUniqueIcons = (0, import_element150.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
});
};
const hideVariationsForSections = window?.__experimentalContentOnlyPatternInsertion && isSection;
if (!variations?.length || isContentOnly || hideVariationsForSections) {
return null;
}
const baseClass = "block-editor-block-variation-transforms";
const showButtons = variations.length > 6;
const ButtonComponent = showButtons ? VariationsButtons : VariationsToggleGroupControl;
const Component7 = hasUniqueIcons ? ButtonComponent : VariationsDropdown;
return /* @__PURE__ */ (0, import_jsx_runtime281.jsx)(
Component7,
{
className: baseClass,
onSelectVariation,
selectedValue,
variations
}
);
}
var block_variation_transforms_default = __experimentalBlockVariationTransforms;
// packages/block-editor/build-module/components/block-vertical-alignment-control/ui.mjs
var import_i18n123 = __toESM(require_i18n(), 1);
var import_components133 = __toESM(require_components(), 1);
var import_jsx_runtime282 = __toESM(require_jsx_runtime(), 1);
var BLOCK_ALIGNMENTS_CONTROLS2 = {
top: {
icon: justify_top_default,
title: (0, import_i18n123._x)("Align top", "Block vertical alignment setting")
},
center: {
icon: justify_center_vertical_default,
title: (0, import_i18n123._x)("Align middle", "Block vertical alignment setting")
},
bottom: {
icon: justify_bottom_default,
title: (0, import_i18n123._x)("Align bottom", "Block vertical alignment setting")
},
stretch: {
icon: justify_stretch_vertical_default,
title: (0, import_i18n123._x)("Stretch to fill", "Block vertical alignment setting")
},
"space-between": {
icon: justify_space_between_vertical_default,
title: (0, import_i18n123._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_components133.ToolbarGroup : import_components133.ToolbarDropdownMenu;
const extraProps = isToolbar ? { isCollapsed: isCollapsed3 } : {};
return /* @__PURE__ */ (0, import_jsx_runtime282.jsx)(
UIComponent,
{
icon: activeAlignment ? activeAlignment.icon : defaultAlignmentControl.icon,
label: (0, import_i18n123._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_runtime283 = __toESM(require_jsx_runtime(), 1);
var BlockVerticalAlignmentControl = (props) => {
return /* @__PURE__ */ (0, import_jsx_runtime283.jsx)(ui_default3, { ...props, isToolbar: false });
};
var BlockVerticalAlignmentToolbar = (props) => {
return /* @__PURE__ */ (0, import_jsx_runtime283.jsx)(ui_default3, { ...props, isToolbar: true });
};
// packages/block-editor/build-module/components/border-radius-control/index.mjs
var import_components138 = __toESM(require_components(), 1);
var import_element152 = __toESM(require_element(), 1);
var import_i18n127 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/border-radius-control/linked-button.mjs
var import_components134 = __toESM(require_components(), 1);
var import_i18n124 = __toESM(require_i18n(), 1);
var import_jsx_runtime284 = __toESM(require_jsx_runtime(), 1);
function LinkedButton({ isLinked, ...props }) {
const label = isLinked ? (0, import_i18n124.__)("Unlink radii") : (0, import_i18n124.__)("Link radii");
return /* @__PURE__ */ (0, import_jsx_runtime284.jsx)(
import_components134.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_components135 = __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_components135.__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_components137 = __toESM(require_components(), 1);
var import_compose76 = __toESM(require_compose(), 1);
var import_i18n125 = __toESM(require_i18n(), 1);
var import_element151 = __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((size) => {
return String(size.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((size) => String(size.slug) === slug);
return preset?.size;
}
function getPresetValueFromCustomValue2(value, spacingSizes, presetType) {
if (!value || isValuePreset(value, presetType) || value === "0") {
return value;
}
const spacingMatch = spacingSizes.find(
(size) => String(size.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_components136 = __toESM(require_components(), 1);
var import_jsx_runtime285 = __toESM(require_jsx_runtime(), 1);
function CustomValueControls({
allowNegativeOnDrag,
ariaLabel,
allPlaceholder,
minValue,
parsedQuantity,
computedUnit,
units: units2,
isMixed,
step,
max,
showTooltip,
value,
minimumCustomValue,
onCustomValueChange,
onCustomValueSliderChange,
onUnitChange,
onMouseOut,
onMouseOver,
setMinValue
}) {
const unitControl = /* @__PURE__ */ (0, import_jsx_runtime285.jsx)(
import_components136.__experimentalUnitControl,
{
className: "preset-input-control__unit-control",
disableUnits: isMixed,
hideLabelFromVision: true,
label: ariaLabel,
min: minValue,
onChange: onCustomValueChange,
onUnitChange,
onBlur: onMouseOut,
onFocus: onMouseOver,
onMouseOut,
onMouseOver,
size: "__unstable-large",
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_runtime285.jsx)(import_components136.Tooltip, { text: ariaLabel, placement: "top", children: /* @__PURE__ */ (0, import_jsx_runtime285.jsx)("div", { className: "preset-input-control__tooltip-wrapper", children: unitControl }) }) : unitControl;
return /* @__PURE__ */ (0, import_jsx_runtime285.jsxs)(import_jsx_runtime285.Fragment, { children: [
wrappedUnitControl,
/* @__PURE__ */ (0, import_jsx_runtime285.jsx)(
import_components136.RangeControl,
{
className: "preset-input-control__custom-value-range",
hideLabelFromVision: true,
initialPosition: 0,
label: ariaLabel,
max,
min: 0,
onBlur: onMouseOut,
onChange: onCustomValueSliderChange,
onFocus: onMouseOver,
onMouseOut,
onMouseOver,
step,
value: parsedQuantity,
withInputField: false,
__next40pxDefaultSize: true
}
)
] });
}
// packages/block-editor/build-module/components/preset-input-control/index.mjs
var import_jsx_runtime286 = __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_element151.useMemo)(
() => getPresetValueFromCustomValue2(valueProp, presets, presetType),
[valueProp, presets, presetType]
);
const className = classNameProp ?? "preset-input-control";
const marks = presets.slice(1, presets.length - 1).map((_newValue, index) => ({
value: index + 1,
label: void 0
}));
const hasPresets = marks.length > 0;
const showRangeControl = presets.length <= RANGE_CONTROL_MAX_SIZE2;
const allPlaceholder = isMixed ? (0, import_i18n125.__)("Mixed") : null;
const [minValue, setMinValue] = (0, import_element151.useState)(minimumCustomValue);
const [showCustomValueControl, setShowCustomValueControl] = (0, import_element151.useState)(
!disableCustomValues && value !== void 0 && !isValuePreset(value, presetType)
);
let currentValue = null;
const previousValue = (0, import_compose76.usePrevious)(value);
(0, import_element151.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_i18n125.sprintf)((0, import_i18n125.__)("Custom (%s)"), value)
) : (0, import_i18n125.__)("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((size, index) => ({
key: index,
name: size.name
}));
const resolvedPresetValue = isValuePreset(value, presetType) ? getCustomValueFromPreset2(value, presets, presetType) : value;
const [parsedQuantity, parsedUnit] = (0, import_components137.__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 max = unitConfig?.max ?? customValueSettings[computedUnit]?.max ?? 10;
const handleCustomValueChange = (newValue) => {
const isNumeric = !isNaN(parseFloat(newValue));
const newCustomValue = isNumeric ? newValue : void 0;
if (newCustomValue !== void 0) {
onChange(newCustomValue);
}
};
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_runtime286.jsxs)(
import_components137.__experimentalHStack,
{
className: `preset-input-control__wrapper ${className}__wrapper`,
children: [
icon && /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
import_components137.Icon,
{
className: "preset-input-control__icon",
icon,
size: ICON_SIZE
}
),
(!hasPresets || showCustomValueControl) && /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
CustomValueControls,
{
allowNegativeOnDrag,
ariaLabel,
allPlaceholder,
minValue,
parsedQuantity,
computedUnit,
units: units2,
isMixed,
step,
max,
showTooltip,
value,
minimumCustomValue,
onCustomValueChange: handleCustomValueChange,
onCustomValueSliderChange: handleCustomValueSliderChange,
onUnitChange,
onMouseOut,
onMouseOver,
setMinValue
}
),
hasPresets && showRangeControl && !showCustomValueControl && /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
import_components137.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,
__next40pxDefaultSize: true
}
),
hasPresets && !showRangeControl && !showCustomValueControl && /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
import_components137.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,
size: "__unstable-large",
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_runtime286.jsx)(
import_components137.Button,
{
className: "preset-input-control__custom-toggle",
icon: settings_default,
iconSize: ICON_SIZE,
isPressed: showCustomValueControl,
label: showCustomValueControl ? (0, import_i18n125.__)("Use preset") : (0, import_i18n125.__)("Set custom value"),
onClick: () => {
setShowCustomValueControl(!showCustomValueControl);
},
size: "small"
}
)
]
}
);
}
// packages/block-editor/build-module/components/border-radius-control/constants.mjs
var import_i18n126 = __toESM(require_i18n(), 1);
var RANGE_CONTROL_MAX_SIZE3 = 8;
var EMPTY_ARRAY9 = [];
var CORNERS = {
all: (0, import_i18n126.__)("Border radius"),
topLeft: (0, import_i18n126.__)("Top left"),
topRight: (0, import_i18n126.__)("Top right"),
bottomLeft: (0, import_i18n126.__)("Bottom left"),
bottomRight: (0, import_i18n126.__)("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_runtime287 = __toESM(require_jsx_runtime(), 1);
function useBorderRadiusSizes(presets) {
const defaultSizes = presets?.default ?? EMPTY_ARRAY9;
const customSizes = presets?.custom ?? EMPTY_ARRAY9;
const themeSizes = presets?.theme ?? EMPTY_ARRAY9;
return (0, import_element152.useMemo)(() => {
const sizes = [
{ name: (0, import_i18n127.__)("None"), slug: "0", size: 0 },
...customSizes,
...themeSizes,
...defaultSizes
];
return sizes.length > RANGE_CONTROL_MAX_SIZE3 ? [
{
name: (0, import_i18n127.__)("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_element152.useState)(
!hasDefinedValues(values) || !hasMixedValues(values)
);
const options = useBorderRadiusSizes(presets);
const [selectedUnits, setSelectedUnits] = (0, import_element152.useState)({
flat: typeof values === "string" ? (0, import_components138.__experimentalParseQuantityAndUnitFromRawValue)(values)[1] : void 0,
topLeft: (0, import_components138.__experimentalParseQuantityAndUnitFromRawValue)(values?.topLeft)[1],
topRight: (0, import_components138.__experimentalParseQuantityAndUnitFromRawValue)(values?.topRight)[1],
bottomLeft: (0, import_components138.__experimentalParseQuantityAndUnitFromRawValue)(values?.bottomLeft)[1],
bottomRight: (0, import_components138.__experimentalParseQuantityAndUnitFromRawValue)(
values?.bottomRight
)[1]
});
const [availableUnits] = useSettings("spacing.units");
const units2 = (0, import_components138.__experimentalUseCustomUnits)({
availableUnits: availableUnits || ["px", "em", "rem"]
});
const toggleLinked = () => setIsLinked(!isLinked);
return /* @__PURE__ */ (0, import_jsx_runtime287.jsxs)("fieldset", { className: "components-border-radius-control", children: [
/* @__PURE__ */ (0, import_jsx_runtime287.jsxs)(import_components138.__experimentalHStack, { className: "components-border-radius-control__header", children: [
/* @__PURE__ */ (0, import_jsx_runtime287.jsx)(import_components138.BaseControl.VisualLabel, { as: "legend", children: (0, import_i18n127.__)("Radius") }),
/* @__PURE__ */ (0, import_jsx_runtime287.jsx)(LinkedButton, { onClick: toggleLinked, isLinked })
] }),
isLinked ? /* @__PURE__ */ (0, import_jsx_runtime287.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_runtime287.jsx)(import_components138.__experimentalVStack, { children: [
"topLeft",
"topRight",
"bottomLeft",
"bottomRight"
].map((corner) => /* @__PURE__ */ (0, import_jsx_runtime287.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_components139 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/color-palette/with-color-context.mjs
var import_compose77 = __toESM(require_compose(), 1);
var import_jsx_runtime288 = __toESM(require_jsx_runtime(), 1);
var with_color_context_default = (0, import_compose77.createHigherOrderComponent)((WrappedComponent) => {
return (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_runtime288.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_components139.ColorPalette);
// packages/block-editor/build-module/components/colors-gradients/control.mjs
var import_i18n128 = __toESM(require_i18n(), 1);
var import_components140 = __toESM(require_components(), 1);
var import_jsx_runtime289 = __toESM(require_jsx_runtime(), 1);
var { Tabs: Tabs3 } = unlock(import_components140.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,
gradientValue,
clearable,
showTitle = true,
enableAlpha,
headingLevel
}) {
const canChooseAColor = onColorChange && (colors2 && colors2.length > 0 || !disableCustomColors);
const canChooseAGradient = onGradientChange && (gradients && gradients.length > 0 || !disableCustomGradients);
if (!canChooseAColor && !canChooseAGradient) {
return null;
}
const tabPanels = {
[TAB_IDS.color]: /* @__PURE__ */ (0, import_jsx_runtime289.jsx)(
import_components140.ColorPalette,
{
value: colorValue,
onChange: canChooseAGradient ? (newColor) => {
onColorChange(newColor);
onGradientChange();
} : onColorChange,
...{ colors: colors2, disableCustomColors },
__experimentalIsRenderedInSidebar,
clearable,
enableAlpha,
headingLevel
}
),
[TAB_IDS.gradient]: /* @__PURE__ */ (0, import_jsx_runtime289.jsx)(
import_components140.GradientPicker,
{
value: gradientValue,
onChange: canChooseAColor ? (newGradient) => {
onGradientChange(newGradient);
onColorChange();
} : onGradientChange,
...{ gradients, disableCustomGradients },
__experimentalIsRenderedInSidebar,
clearable,
headingLevel
}
)
};
const renderPanelType = (type) => /* @__PURE__ */ (0, import_jsx_runtime289.jsx)("div", { className: "block-editor-color-gradient-control__panel", children: tabPanels[type] });
return /* @__PURE__ */ (0, import_jsx_runtime289.jsx)(
import_components140.BaseControl,
{
className: clsx_default(
"block-editor-color-gradient-control",
className
),
children: /* @__PURE__ */ (0, import_jsx_runtime289.jsx)("fieldset", { className: "block-editor-color-gradient-control__fieldset", children: /* @__PURE__ */ (0, import_jsx_runtime289.jsxs)(import_components140.__experimentalVStack, { spacing: 1, children: [
showTitle && /* @__PURE__ */ (0, import_jsx_runtime289.jsx)("legend", { children: /* @__PURE__ */ (0, import_jsx_runtime289.jsx)("div", { className: "block-editor-color-gradient-control__color-indicator", children: /* @__PURE__ */ (0, import_jsx_runtime289.jsx)(import_components140.BaseControl.VisualLabel, { children: label }) }) }),
canChooseAColor && canChooseAGradient && /* @__PURE__ */ (0, import_jsx_runtime289.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime289.jsxs)(
Tabs3,
{
defaultTabId: gradientValue ? TAB_IDS.gradient : !!canChooseAColor && TAB_IDS.color,
children: [
/* @__PURE__ */ (0, import_jsx_runtime289.jsxs)(Tabs3.TabList, { children: [
/* @__PURE__ */ (0, import_jsx_runtime289.jsx)(Tabs3.Tab, { tabId: TAB_IDS.color, children: (0, import_i18n128.__)("Color") }),
/* @__PURE__ */ (0, import_jsx_runtime289.jsx)(Tabs3.Tab, { tabId: TAB_IDS.gradient, children: (0, import_i18n128.__)("Gradient") })
] }),
/* @__PURE__ */ (0, import_jsx_runtime289.jsx)(
Tabs3.TabPanel,
{
tabId: TAB_IDS.color,
className: "block-editor-color-gradient-control__panel",
focusable: false,
children: tabPanels.color
}
),
/* @__PURE__ */ (0, import_jsx_runtime289.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_runtime289.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_runtime289.jsx)(ColorGradientControlInner, { ...props });
}
return /* @__PURE__ */ (0, import_jsx_runtime289.jsx)(ColorGradientControlSelect, { ...props });
}
var control_default = ColorGradientControl;
// packages/block-editor/build-module/components/color-palette/control.mjs
var import_jsx_runtime290 = __toESM(require_jsx_runtime(), 1);
function ColorPaletteControl({
onChange,
value,
...otherProps
}) {
return /* @__PURE__ */ (0, import_jsx_runtime290.jsx)(
control_default,
{
...otherProps,
onColorChange: onChange,
colorValue: value,
gradients: [],
disableCustomGradients: true
}
);
}
// packages/block-editor/build-module/components/contrast-checker/index.mjs
var import_i18n129 = __toESM(require_i18n(), 1);
var import_components141 = __toESM(require_components(), 1);
var import_a11y17 = __toESM(require_a11y(), 1);
var import_jsx_runtime291 = __toESM(require_jsx_runtime(), 1);
k([names_default, a11y_default]);
function ContrastChecker({
backgroundColor,
fallbackBackgroundColor,
fallbackTextColor,
fallbackLinkColor,
fontSize,
// Font size value in pixels.
isLargeText,
textColor,
linkColor,
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_i18n129.__)("text color")
},
{
color: currentLinkColor,
description: (0, import_i18n129.__)("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;
}
message2 = backgroundColorBrightness < colordTextColor.brightness() ? (0, import_i18n129.sprintf)(
// translators: %s is a type of text color, e.g., "text color" or "link color".
(0, import_i18n129.__)(
"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_i18n129.sprintf)(
// translators: %s is a type of text color, e.g., "text color" or "link color".
(0, import_i18n129.__)(
"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_i18n129.__)(
"This color combination may be hard for people to read."
);
break;
}
if (textHasTransparency && enableAlphaChecker) {
message2 = (0, import_i18n129.__)("Transparent text may be hard for people to read.");
speakMessage = (0, import_i18n129.__)(
"Transparent text may be hard for people to read."
);
}
}
if (!message2) {
return null;
}
(0, import_a11y17.speak)(speakMessage);
return /* @__PURE__ */ (0, import_jsx_runtime291.jsx)("div", { className: "block-editor-contrast-checker", children: /* @__PURE__ */ (0, import_jsx_runtime291.jsx)(
import_components141.Notice,
{
spokenMessage: null,
status: "warning",
isDismissible: false,
children: message2
}
) });
}
var contrast_checker_default = ContrastChecker;
// packages/block-editor/build-module/components/date-format-picker/index.mjs
var import_i18n130 = __toESM(require_i18n(), 1);
var import_date = __toESM(require_date(), 1);
var import_element153 = __toESM(require_element(), 1);
var import_components142 = __toESM(require_components(), 1);
var import_jsx_runtime292 = __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_runtime292.jsxs)(
import_components142.__experimentalVStack,
{
as: "fieldset",
spacing: 4,
className: "block-editor-date-format-picker",
children: [
/* @__PURE__ */ (0, import_jsx_runtime292.jsx)(import_components142.VisuallyHidden, { as: "legend", children: (0, import_i18n130.__)("Date format") }),
/* @__PURE__ */ (0, import_jsx_runtime292.jsx)(
import_components142.ToggleControl,
{
label: (0, import_i18n130.__)("Default format"),
help: `${(0, import_i18n130.__)("Example:")} ${(0, import_date.dateI18n)(
defaultFormat,
exampleDate
)}`,
checked: !format6,
onChange: (checked) => onChange(checked ? null : defaultFormat)
}
),
format6 && /* @__PURE__ */ (0, import_jsx_runtime292.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_i18n130._x)("n/j/Y", "short date format"),
/* translators: See https://www.php.net/manual/datetime.format.php */
(0, import_i18n130._x)("n/j/Y g:i A", "short date format with time"),
/* translators: See https://www.php.net/manual/datetime.format.php */
(0, import_i18n130._x)("M j, Y", "medium date format"),
/* translators: See https://www.php.net/manual/datetime.format.php */
(0, import_i18n130._x)("M j, Y g:i A", "medium date format with time"),
/* translators: See https://www.php.net/manual/datetime.format.php */
(0, import_i18n130._x)("F j, Y", "long date format"),
/* translators: See https://www.php.net/manual/datetime.format.php */
(0, import_i18n130._x)("M j", "short date format without the year")
])
];
const suggestedOptions = [
...suggestedFormats.map((suggestedFormat, index) => ({
key: `suggested-${index}`,
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_i18n130.__)("Custom"),
className: "block-editor-date-format-picker__custom-format-select-control__custom-option",
hint: (0, import_i18n130.__)("Enter your own date format")
};
const [isCustom, setIsCustom] = (0, import_element153.useState)(
() => !!format6 && !suggestedOptions.some((option) => option.format === format6)
);
return /* @__PURE__ */ (0, import_jsx_runtime292.jsxs)(import_components142.__experimentalVStack, { children: [
/* @__PURE__ */ (0, import_jsx_runtime292.jsx)(
import_components142.CustomSelectControl,
{
__next40pxDefaultSize: true,
label: (0, import_i18n130.__)("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_runtime292.jsx)(
import_components142.TextControl,
{
__next40pxDefaultSize: true,
label: (0, import_i18n130.__)("Custom format"),
hideLabelFromVision: true,
help: (0, import_element153.createInterpolateElement)(
(0, import_i18n130.__)(
"Enter a date or time <Link>format string</Link>."
),
{
Link: /* @__PURE__ */ (0, import_jsx_runtime292.jsx)(
import_components142.ExternalLink,
{
href: (0, import_i18n130.__)(
"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_components143 = __toESM(require_components(), 1);
var import_i18n131 = __toESM(require_i18n(), 1);
var import_keycodes15 = __toESM(require_keycodes(), 1);
var import_compose78 = __toESM(require_compose(), 1);
var import_jsx_runtime293 = __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_runtime293.jsx)(import_components143.ColorIndicator, { className: "block-editor-duotone-control__unset-indicator" });
} else if (value) {
toolbarIcon = /* @__PURE__ */ (0, import_jsx_runtime293.jsx)(import_components143.DuotoneSwatch, { values: value });
} else {
toolbarIcon = /* @__PURE__ */ (0, import_jsx_runtime293.jsx)(icon_default, { icon: filter_default });
}
const actionLabel = (0, import_i18n131.__)("Apply duotone filter");
const id = (0, import_compose78.useInstanceId)(DuotoneControl, "duotone-control", idProp);
const descriptionId = `${id}__description`;
return /* @__PURE__ */ (0, import_jsx_runtime293.jsx)(
import_components143.Dropdown,
{
popoverProps: {
className: "block-editor-duotone-control__popover",
headerTitle: (0, import_i18n131.__)("Duotone")
},
renderToggle: ({ isOpen, onToggle }) => {
const openOnArrowDown = (event) => {
if (!isOpen && event.keyCode === import_keycodes15.DOWN) {
event.preventDefault();
onToggle();
}
};
return /* @__PURE__ */ (0, import_jsx_runtime293.jsx)(
import_components143.ToolbarButton,
{
showTooltip: true,
onClick: onToggle,
"aria-haspopup": "true",
"aria-expanded": isOpen,
onKeyDown: openOnArrowDown,
label: actionLabel,
icon: toolbarIcon
}
);
},
renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime293.jsxs)(import_components143.MenuGroup, { label: (0, import_i18n131.__)("Duotone"), children: [
/* @__PURE__ */ (0, import_jsx_runtime293.jsx)("p", { children: (0, import_i18n131.__)(
"Create a two-tone color effect without losing your original image."
) }),
/* @__PURE__ */ (0, import_jsx_runtime293.jsx)(
import_components143.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_components144 = __toESM(require_components(), 1);
var import_deprecated16 = __toESM(require_deprecated(), 1);
var import_element154 = __toESM(require_element(), 1);
var import_i18n135 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/utils/get-font-styles-and-weights.mjs
var import_i18n134 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/utils/format-font-style.mjs
var import_i18n132 = __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_i18n132._x)("Regular", "font style");
break;
case "italic":
name = (0, import_i18n132._x)("Italic", "font style");
break;
case "oblique":
name = (0, import_i18n132._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_i18n133 = __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_i18n133._x)("Regular", "font weight");
break;
case "bold":
case "700":
name = (0, import_i18n133._x)("Bold", "font weight");
break;
case "100":
name = (0, import_i18n133._x)("Thin", "font weight");
break;
case "200":
name = (0, import_i18n133._x)("Extra Light", "font weight");
break;
case "300":
name = (0, import_i18n133._x)("Light", "font weight");
break;
case "500":
name = (0, import_i18n133._x)("Medium", "font weight");
break;
case "600":
name = (0, import_i18n133._x)("Semi Bold", "font weight");
break;
case "800":
name = (0, import_i18n133._x)("Extra Bold", "font weight");
break;
case "900":
name = (0, import_i18n133._x)("Black", "font weight");
break;
case "1000":
name = (0, import_i18n133._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_i18n134._x)("Regular", "font style"),
value: "normal"
},
{
name: (0, import_i18n134._x)("Italic", "font style"),
value: "italic"
}
];
var FONT_WEIGHTS = [
{
name: (0, import_i18n134._x)("Thin", "font weight"),
value: "100"
},
{
name: (0, import_i18n134._x)("Extra Light", "font weight"),
value: "200"
},
{
name: (0, import_i18n134._x)("Light", "font weight"),
value: "300"
},
{
name: (0, import_i18n134._x)("Regular", "font weight"),
value: "400"
},
{
name: (0, import_i18n134._x)("Medium", "font weight"),
value: "500"
},
{
name: (0, import_i18n134._x)("Semi Bold", "font weight"),
value: "600"
},
{
name: (0, import_i18n134._x)("Bold", "font weight"),
value: "700"
},
{
name: (0, import_i18n134._x)("Extra Bold", "font weight"),
value: "800"
},
{
name: (0, import_i18n134._x)("Black", "font weight"),
value: "900"
},
{
name: (0, import_i18n134._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;
let [startValue, endValue] = face.fontWeight.split(" ");
startValue = parseInt(startValue.slice(0, 1));
if (endValue === "1000") {
endValue = 10;
} else {
endValue = parseInt(endValue.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_i18n134._x)("Bold", "font weight"),
value: "700"
});
}
if (!fontStyles.some((style) => style.value === "italic")) {
fontStyles.push({
name: (0, import_i18n134._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_i18n134.sprintf)(
/* translators: 1: Font weight name. 2: Font style name. */
(0, import_i18n134._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_runtime294 = __toESM(require_jsx_runtime(), 1);
var getFontAppearanceLabel = (hasFontStyles, hasFontWeights) => {
if (!hasFontStyles) {
return (0, import_i18n135.__)("Font weight");
}
if (!hasFontWeights) {
return (0, import_i18n135.__)("Font style");
}
return (0, import_i18n135.__)("Appearance");
};
function FontAppearanceControl(props) {
const {
/** Start opting into the larger default height that will become the default size in a future version. */
__next40pxDefaultSize = false,
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_i18n135.__)("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_element154.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_i18n135.__)("No selected font appearance");
}
if (!hasFontStyles) {
return (0, import_i18n135.sprintf)(
// translators: %s: Currently selected font weight.
(0, import_i18n135.__)("Currently selected font weight: %s"),
currentSelection.name
);
}
if (!hasFontWeights) {
return (0, import_i18n135.sprintf)(
// translators: %s: Currently selected font style.
(0, import_i18n135.__)("Currently selected font style: %s"),
currentSelection.name
);
}
return (0, import_i18n135.sprintf)(
// translators: %s: Currently selected font appearance.
(0, import_i18n135.__)("Currently selected font appearance: %s"),
currentSelection.name
);
};
if (!__next40pxDefaultSize && (otherProps.size === void 0 || otherProps.size === "default")) {
(0, import_deprecated16.default)(
`36px default size for wp.blockEditor.__experimentalFontAppearanceControl`,
{
since: "6.8",
version: "7.1",
hint: "Set the `__next40pxDefaultSize` prop to true to start opting into the new default size, which will become the default in a future version."
}
);
}
return hasStylesOrWeights && /* @__PURE__ */ (0, import_jsx_runtime294.jsx)(
import_components144.CustomSelectControl,
{
...otherProps,
className: "components-font-appearance-control",
__next40pxDefaultSize,
__shouldNotWarnDeprecated36pxSize: true,
label,
describedBy: getDescribedBy(),
options: selectOptions,
value: currentSelection,
onChange: ({ selectedItem }) => onChange(selectedItem.style)
}
);
}
// packages/block-editor/build-module/components/font-family/index.mjs
var import_components145 = __toESM(require_components(), 1);
var import_deprecated17 = __toESM(require_deprecated(), 1);
var import_i18n136 = __toESM(require_i18n(), 1);
var import_jsx_runtime295 = __toESM(require_jsx_runtime(), 1);
function FontFamilyControl({
/** Start opting into the larger default height that will become the default size in a future version. */
__next40pxDefaultSize = false,
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_i18n136.__)("Default")
},
...fontFamilies.map(({ fontFamily, name }) => ({
key: fontFamily,
name: name || fontFamily,
style: { fontFamily }
}))
];
if (!__next40pxDefaultSize && (props.size === void 0 || props.size === "default")) {
(0, import_deprecated17.default)(
`36px default size for wp.blockEditor.__experimentalFontFamilyControl`,
{
since: "6.8",
version: "7.1",
hint: "Set the `__next40pxDefaultSize` prop to true to start opting into the new default size, which will become the default in a future version."
}
);
}
const selectedValue = options.find((option) => option.key === value) ?? "";
return /* @__PURE__ */ (0, import_jsx_runtime295.jsx)(
import_components145.CustomSelectControl,
{
__next40pxDefaultSize,
__shouldNotWarnDeprecated36pxSize: true,
label: (0, import_i18n136.__)("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_components146 = __toESM(require_components(), 1);
var import_deprecated18 = __toESM(require_deprecated(), 1);
var import_i18n137 = __toESM(require_i18n(), 1);
var import_jsx_runtime296 = __toESM(require_jsx_runtime(), 1);
function LetterSpacingControl({
__next40pxDefaultSize = false,
value,
onChange,
__unstableInputWidth = "60px",
...otherProps
}) {
const [availableUnits] = useSettings("spacing.units");
const units2 = (0, import_components146.__experimentalUseCustomUnits)({
availableUnits: availableUnits || ["px", "em", "rem"],
defaultValues: { px: 2, em: 0.2, rem: 0.2 }
});
if (!__next40pxDefaultSize && (otherProps.size === void 0 || otherProps.size === "default")) {
(0, import_deprecated18.default)(
`36px default size for wp.blockEditor.__experimentalLetterSpacingControl`,
{
since: "6.8",
version: "7.1",
hint: "Set the `__next40pxDefaultSize` prop to true to start opting into the new default size, which will become the default in a future version."
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(
import_components146.__experimentalUnitControl,
{
__next40pxDefaultSize,
__shouldNotWarnDeprecated36pxSize: true,
...otherProps,
label: (0, import_i18n137.__)("Letter spacing"),
value,
__unstableInputWidth,
units: units2,
onChange
}
);
}
// packages/block-editor/build-module/components/text-decoration-control/index.mjs
var import_i18n138 = __toESM(require_i18n(), 1);
var import_components147 = __toESM(require_components(), 1);
var import_jsx_runtime297 = __toESM(require_jsx_runtime(), 1);
var TEXT_DECORATIONS = [
{
label: (0, import_i18n138.__)("None"),
value: "none",
icon: reset_default
},
{
label: (0, import_i18n138.__)("Underline"),
value: "underline",
icon: format_underline_default
},
{
label: (0, import_i18n138.__)("Strikethrough"),
value: "line-through",
icon: format_strikethrough_default
}
];
function TextDecorationControl({
value,
onChange,
className
}) {
return /* @__PURE__ */ (0, import_jsx_runtime297.jsx)(
import_components147.__experimentalToggleGroupControl,
{
isDeselectable: true,
__next40pxDefaultSize: true,
label: (0, import_i18n138.__)("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_runtime297.jsx)(
import_components147.__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_i18n139 = __toESM(require_i18n(), 1);
var import_components148 = __toESM(require_components(), 1);
var import_jsx_runtime298 = __toESM(require_jsx_runtime(), 1);
var TEXT_TRANSFORMS = [
{
label: (0, import_i18n139.__)("None"),
value: "none",
icon: reset_default
},
{
label: (0, import_i18n139.__)("Uppercase"),
value: "uppercase",
icon: format_uppercase_default
},
{
label: (0, import_i18n139.__)("Lowercase"),
value: "lowercase",
icon: format_lowercase_default
},
{
label: (0, import_i18n139.__)("Capitalize"),
value: "capitalize",
icon: format_capitalize_default
}
];
function TextTransformControl({ className, value, onChange }) {
return /* @__PURE__ */ (0, import_jsx_runtime298.jsx)(
import_components148.__experimentalToggleGroupControl,
{
isDeselectable: true,
__next40pxDefaultSize: true,
label: (0, import_i18n139.__)("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_runtime298.jsx)(
import_components148.__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_i18n140 = __toESM(require_i18n(), 1);
var import_components149 = __toESM(require_components(), 1);
var import_jsx_runtime299 = __toESM(require_jsx_runtime(), 1);
var WRITING_MODES = [
{
label: (0, import_i18n140.__)("Horizontal"),
value: "horizontal-tb",
icon: text_horizontal_default
},
{
label: (0, import_i18n140.__)("Vertical"),
value: (0, import_i18n140.isRTL)() ? "vertical-lr" : "vertical-rl",
icon: text_vertical_default
}
];
function WritingModeControl({ className, value, onChange }) {
return /* @__PURE__ */ (0, import_jsx_runtime299.jsx)(
import_components149.__experimentalToggleGroupControl,
{
isDeselectable: true,
__next40pxDefaultSize: true,
label: (0, import_i18n140.__)("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_runtime299.jsx)(
import_components149.__experimentalToggleGroupControlOptionIcon,
{
value: option.value,
icon: option.icon,
label: option.label
},
option.value
);
})
}
);
}
// packages/block-editor/build-module/components/colors-gradients/dropdown.mjs
var import_components150 = __toESM(require_components(), 1);
var import_element155 = __toESM(require_element(), 1);
var import_i18n141 = __toESM(require_i18n(), 1);
var import_jsx_runtime300 = __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_runtime300.jsx)(
import_components150.__experimentalToolsPanelItem,
{
hasValue: () => {
return !!setting.colorValue || !!setting.gradientValue;
},
label: setting.label,
onDeselect: clearValue,
isShownByDefault: setting.isShownByDefault !== void 0 ? setting.isShownByDefault : true,
...props,
className: "block-editor-tools-panel-color-gradient-settings__item",
panelId,
resetAllFilter: setting.resetAllFilter,
children
}
);
};
var LabeledColorIndicator = ({ colorValue, label }) => /* @__PURE__ */ (0, import_jsx_runtime300.jsxs)(import_components150.__experimentalHStack, { justify: "flex-start", children: [
/* @__PURE__ */ (0, import_jsx_runtime300.jsx)(
import_components150.ColorIndicator,
{
className: "block-editor-panel-color-gradient-settings__color-indicator",
colorValue
}
),
/* @__PURE__ */ (0, import_jsx_runtime300.jsx)(
import_components150.FlexItem,
{
className: "block-editor-panel-color-gradient-settings__color-name",
title: label,
children: label
}
)
] });
var renderToggle = (settings2) => ({ onToggle, isOpen }) => {
const {
clearable,
colorValue,
gradientValue,
onColorChange,
onGradientChange,
label
} = settings2;
const colorButtonRef = (0, import_element155.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_runtime300.jsxs)(import_jsx_runtime300.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime300.jsx)(import_components150.Button, { __next40pxDefaultSize: true, ...toggleProps, children: /* @__PURE__ */ (0, import_jsx_runtime300.jsx)(
LabeledColorIndicator,
{
colorValue: value,
label
}
) }),
clearable && value && /* @__PURE__ */ (0, import_jsx_runtime300.jsx)(
import_components150.Button,
{
__next40pxDefaultSize: true,
label: (0, import_i18n141.__)("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_runtime300.jsx)(import_jsx_runtime300.Fragment, { children: settings2.map((setting, index) => {
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_runtime300.jsx)(
WithToolsPanelItem,
{
setting,
...props,
children: /* @__PURE__ */ (0, import_jsx_runtime300.jsx)(
import_components150.Dropdown,
{
popoverProps: popoverProps3,
className: "block-editor-tools-panel-color-gradient-settings__dropdown",
renderToggle: renderToggle(toggleSettings),
renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime300.jsx)(import_components150.__experimentalDropdownContentWrapper, { paddingSize: "none", children: /* @__PURE__ */ (0, import_jsx_runtime300.jsx)("div", { className: "block-editor-panel-color-gradient-settings__dropdown-content", children: /* @__PURE__ */ (0, import_jsx_runtime300.jsx)(
control_default,
{
...controlProps
}
) }) })
}
)
},
index
);
}) });
}
// packages/block-editor/build-module/components/colors-gradients/panel-color-gradient-settings.mjs
var import_components151 = __toESM(require_components(), 1);
var import_data142 = __toESM(require_data(), 1);
var import_compose79 = __toESM(require_compose(), 1);
// packages/block-editor/build-module/components/colors-gradients/use-multiple-origin-colors-and-gradients.mjs
var import_element156 = __toESM(require_element(), 1);
var import_i18n142 = __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_element156.useMemo)(() => {
const result = [];
if (themeColors && themeColors.length) {
result.push({
name: (0, import_i18n142._x)(
"Theme",
"Indicates this palette comes from the theme."
),
slug: "theme",
colors: themeColors
});
}
if (shouldDisplayDefaultColors && defaultColors && defaultColors.length) {
result.push({
name: (0, import_i18n142._x)(
"Default",
"Indicates this palette comes from WordPress."
),
slug: "default",
colors: defaultColors
});
}
if (customColors && customColors.length) {
result.push({
name: (0, import_i18n142._x)(
"Custom",
"Indicates this palette is created by the user."
),
slug: "custom",
colors: customColors
});
}
return result;
}, [
customColors,
themeColors,
defaultColors,
shouldDisplayDefaultColors
]);
colorGradientSettings.gradients = (0, import_element156.useMemo)(() => {
const result = [];
if (themeGradients && themeGradients.length) {
result.push({
name: (0, import_i18n142._x)(
"Theme",
"Indicates this palette comes from the theme."
),
slug: "theme",
gradients: themeGradients
});
}
if (shouldDisplayDefaultGradients && defaultGradients && defaultGradients.length) {
result.push({
name: (0, import_i18n142._x)(
"Default",
"Indicates this palette comes from WordPress."
),
slug: "default",
gradients: defaultGradients
});
}
if (customGradients && customGradients.length) {
result.push({
name: (0, import_i18n142._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_runtime301 = __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_compose79.useInstanceId)(PanelColorGradientSettingsInner);
const { batch } = (0, import_data142.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_runtime301.jsxs)(
import_components151.__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_runtime301.jsx)(
ColorGradientSettingsDropdown,
{
settings: settings2,
panelId,
...{
colors: colors2,
gradients,
disableCustomColors,
disableCustomGradients,
__experimentalIsRenderedInSidebar,
enableAlpha
}
}
),
!!children && /* @__PURE__ */ (0, import_jsx_runtime301.jsxs)(import_jsx_runtime301.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime301.jsx)(import_components151.__experimentalSpacer, { marginY: 4 }),
" ",
children
] })
]
}
);
};
var PanelColorGradientSettingsSelect = (props) => {
const colorGradientSettings = useMultipleOriginColorsAndGradients();
return /* @__PURE__ */ (0, import_jsx_runtime301.jsx)(
PanelColorGradientSettingsInner,
{
...{ ...colorGradientSettings, ...props }
}
);
};
var PanelColorGradientSettings = (props) => {
if (colorsAndGradientKeys2.every((key) => props.hasOwnProperty(key))) {
return /* @__PURE__ */ (0, import_jsx_runtime301.jsx)(PanelColorGradientSettingsInner, { ...props });
}
return /* @__PURE__ */ (0, import_jsx_runtime301.jsx)(PanelColorGradientSettingsSelect, { ...props });
};
var panel_color_gradient_settings_default = PanelColorGradientSettings;
// packages/block-editor/build-module/components/dimension-control/index.mjs
var import_element157 = __toESM(require_element(), 1);
var import_components152 = __toESM(require_components(), 1);
var import_i18n143 = __toESM(require_i18n(), 1);
var import_jsx_runtime302 = __toESM(require_jsx_runtime(), 1);
var EMPTY_ARRAY10 = [];
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_ARRAY10;
const customSizes = presets?.custom ?? EMPTY_ARRAY10;
const themeSizes = presets?.theme ?? EMPTY_ARRAY10;
return (0, import_element157.useMemo)(() => {
const sizes = [
{ name: (0, import_i18n143.__)("None"), slug: "0", size: 0 },
...customSizes,
...themeSizes,
...defaultSizes
];
return sizes;
}, [customSizes, themeSizes, defaultSizes]);
}
function DimensionControl({
label = (0, import_i18n143.__)("Dimension"),
onChange,
value
}) {
const [dimensionSizes, availableUnits] = useSettings(
"dimensions.dimensionSizes",
"spacing.units"
);
const units2 = (0, import_components152.__experimentalUseCustomUnits)({
availableUnits: availableUnits || [
"%",
"px",
"em",
"rem",
"vh",
"vw"
]
});
const options = useDimensionSizes(dimensionSizes);
const [selectedUnit, setSelectedUnit] = (0, import_element157.useState)(() => {
const [, unit] = (0, import_components152.__experimentalParseQuantityAndUnitFromRawValue)(value);
return unit || units2[0]?.value || "px";
});
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);
}
setSelectedUnit(newUnit);
};
return /* @__PURE__ */ (0, import_jsx_runtime302.jsxs)("fieldset", { className: "block-editor-dimension-control", children: [
/* @__PURE__ */ (0, import_jsx_runtime302.jsx)(import_components152.BaseControl.VisualLabel, { as: "legend", children: label }),
/* @__PURE__ */ (0, import_jsx_runtime302.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_element158 = __toESM(require_element(), 1);
var import_components153 = __toESM(require_components(), 1);
var import_i18n144 = __toESM(require_i18n(), 1);
var import_deprecated19 = __toESM(require_deprecated(), 1);
var import_jsx_runtime303 = __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_i18n144.__)("Height"),
onChange,
value
}) {
(0, import_deprecated19.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_components153.__experimentalUseCustomUnits)({
availableUnits: availableUnits || [
"%",
"px",
"em",
"rem",
"vh",
"vw"
]
});
const selectedUnit = (0, import_element158.useMemo)(
() => (0, import_components153.__experimentalParseQuantityAndUnitFromRawValue)(value),
[value]
)[1] || units2[0]?.value || "px";
const handleSliderChange = (next) => {
onChange([next, selectedUnit].join(""));
};
const handleUnitChange = (newUnit) => {
const [currentValue, currentUnit] = (0, import_components153.__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_runtime303.jsxs)("fieldset", { className: "block-editor-height-control", children: [
/* @__PURE__ */ (0, import_jsx_runtime303.jsx)(import_components153.BaseControl.VisualLabel, { as: "legend", children: label }),
/* @__PURE__ */ (0, import_jsx_runtime303.jsxs)(import_components153.Flex, { children: [
/* @__PURE__ */ (0, import_jsx_runtime303.jsx)(import_components153.FlexItem, { isBlock: true, children: /* @__PURE__ */ (0, import_jsx_runtime303.jsx)(
import_components153.__experimentalUnitControl,
{
value,
units: units2,
onChange,
onUnitChange: handleUnitChange,
min: 0,
size: "__unstable-large",
label,
hideLabelFromVision: true
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime303.jsx)(import_components153.FlexItem, { isBlock: true, children: /* @__PURE__ */ (0, import_jsx_runtime303.jsx)(import_components153.__experimentalSpacer, { marginX: 2, marginBottom: 0, children: /* @__PURE__ */ (0, import_jsx_runtime303.jsx)(
import_components153.RangeControl,
{
__next40pxDefaultSize: true,
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_components159 = __toESM(require_components(), 1);
// node_modules/react-easy-crop/index.module.js
var React3 = __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 clamp(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(max, value) {
return Math.min(max, 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 = clamp(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 = clamp(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 clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
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 = React3.createRef();
_this.imageRef = React3.createRef();
_this.videoRef = React3.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 = clamp(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 React3.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 ? React3.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 && React3.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 React3.createElement("source", __assign({
key: item.src
}, item));
})), this.state.cropSize && React3.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;
})(React3.Component)
);
// packages/image-cropper/build-module/components/image-cropper/index.mjs
var import_element161 = __toESM(require_element(), 1);
// packages/image-cropper/build-module/provider/index.mjs
var import_element160 = __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_element159 = __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", (error) => reject(error));
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, flip = { 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(flip.horizontal ? -1 : 1, flip.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_element159.useState)(
DEFAULT_CROPPER_STATE
);
const [resetState, setInternalResetState] = (0, import_element159.useState)(null);
const setCropperState = (0, import_element159.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_element159.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_element159.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_element159.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_element159.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_element159.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_runtime304 = __toESM(require_jsx_runtime(), 1);
var ImageCropperContext = (0, import_element160.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_element160.useMemo)(() => {
return {
...cropperApi
};
}, [cropperApi]);
return /* @__PURE__ */ (0, import_jsx_runtime304.jsx)(ImageCropperContext.Provider, { value: contextValue, children });
}
var useImageCropper = () => {
const context = (0, import_element160.useContext)(ImageCropperContext);
if (!context) {
throw new Error("Missing ImageCropperContext");
}
return context;
};
// packages/image-cropper/build-module/components/image-cropper/index.mjs
var import_jsx_runtime305 = __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 } = 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_element161.useCallback)(
(areaPercentage, areaPixels) => {
setCropperState({
croppedArea: areaPercentage,
croppedAreaPixels: areaPixels
});
},
[setCropperState]
);
return /* @__PURE__ */ (0, import_jsx_runtime305.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(${flip.horizontal ? 180 : 0}deg)`,
`rotateX(${flip.vertical ? 180 : 0}deg)`,
`scale(${zoom})`
].join(" "),
...props
}
);
}
// packages/block-editor/build-module/components/image-editor/aspect-ratio-dropdown.mjs
var import_components154 = __toESM(require_components(), 1);
var import_i18n146 = __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_element164 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/image-editor/use-save-image.mjs
var import_data143 = __toESM(require_data(), 1);
var import_element162 = __toESM(require_element(), 1);
var import_i18n145 = __toESM(require_i18n(), 1);
var import_notices9 = __toESM(require_notices(), 1);
var import_dom32 = __toESM(require_dom(), 1);
var messages = {
crop: (0, import_i18n145.__)("Image cropped."),
rotate: (0, import_i18n145.__)("Image rotated."),
cropAndRotate: (0, import_i18n145.__)("Image cropped and rotated.")
};
function useSaveImage({
crop,
rotation,
url,
id,
onSaveImage,
onFinishEditing
}) {
const { createErrorNotice, createSuccessNotice } = (0, import_data143.useDispatch)(import_notices9.store);
const [isInProgress, setIsInProgress] = (0, import_element162.useState)(false);
const { editMediaEntity } = (0, import_data143.useSelect)((select3) => {
const settings2 = select3(store).getSettings();
return {
editMediaEntity: settings2?.[mediaEditKey]
};
}, []);
const cancel = (0, import_element162.useCallback)(() => {
setIsInProgress(false);
onFinishEditing();
}, [onFinishEditing]);
const apply = (0, import_element162.useCallback)(async () => {
if (!editMediaEntity) {
onFinishEditing();
createErrorNotice(
(0, import_i18n145.__)("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_i18n145.__)("Undo"),
onClick: () => {
onSaveImage({
id,
url
});
}
}
]
});
}
} catch (error) {
createErrorNotice(
(0, import_i18n145.sprintf)(
/* translators: %s: Error message. */
(0, import_i18n145.__)("Could not edit image. %s"),
(0, import_dom32.__unstableStripHTML)(error.message)
),
{
id: "image-editing-error",
type: "snackbar"
}
);
} finally {
setIsInProgress(false);
onFinishEditing();
}
}, [
crop,
rotation,
id,
url,
onSaveImage,
createErrorNotice,
createSuccessNotice,
onFinishEditing,
editMediaEntity
]);
return (0, import_element162.useMemo)(
() => ({
isInProgress,
apply,
cancel
}),
[isInProgress, apply, cancel]
);
}
// packages/block-editor/build-module/components/image-editor/use-transform-image.mjs
var import_element163 = __toESM(require_element(), 1);
var import_hooks6 = __toESM(require_hooks(), 1);
function useTransformImage({
url,
naturalWidth,
naturalHeight
}) {
const [editedUrl, setEditedUrl] = (0, import_element163.useState)();
const { cropperState, setCropperState } = useImageCropper();
const { zoom, aspectRatio, crop, croppedArea } = cropperState;
const setZoom = (0, import_element163.useCallback)(
(newZoom) => {
setCropperState({ zoom: newZoom });
},
[setCropperState]
);
const setAspectRatio = (0, import_element163.useCallback)(
(newAspect) => {
setCropperState({ aspectRatio: newAspect });
},
[setCropperState]
);
const defaultAspect = naturalWidth / naturalHeight;
const rotatedAspect = naturalHeight / naturalWidth;
(0, import_element163.useEffect)(() => {
setAspectRatio(defaultAspect);
}, []);
const [internalRotation, setInternalRotation] = (0, import_element163.useState)(0);
const rotateClockwise = (0, import_element163.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_element163.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_runtime306 = __toESM(require_jsx_runtime(), 1);
var ImageEditingContext = (0, import_element164.createContext)({});
ImageEditingContext.displayName = "ImageEditingContext";
var useImageEditingContext = () => (0, import_element164.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_element164.useMemo)(
() => ({
...transformImage,
...saveImage
}),
[transformImage, saveImage]
);
return /* @__PURE__ */ (0, import_jsx_runtime306.jsx)(ImageEditingContext.Provider, { value: providerValue, children });
}
// packages/block-editor/build-module/components/image-editor/aspect-ratio-dropdown.mjs
var import_jsx_runtime307 = __toESM(require_jsx_runtime(), 1);
function AspectRatioGroup({
aspectRatios,
isDisabled,
label,
onClick,
value
}) {
return /* @__PURE__ */ (0, import_jsx_runtime307.jsx)(import_components154.MenuGroup, { label, children: aspectRatios.map(({ name, slug, ratio }) => /* @__PURE__ */ (0, import_jsx_runtime307.jsx)(
import_components154.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_runtime307.jsx)(
import_components154.DropdownMenu,
{
icon: aspect_ratio_default,
label: (0, import_i18n146.__)("Aspect Ratio"),
popoverProps: POPOVER_PROPS7,
toggleProps,
children: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime307.jsxs)(import_jsx_runtime307.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime307.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_i18n146.__)("Original"),
ratio: defaultAspect
},
...showDefaultRatios ? defaultRatios.map(presetRatioAsNumber).filter(({ ratio }) => ratio === 1) : []
]
}
),
themeRatios?.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime307.jsx)(
AspectRatioGroup,
{
label: (0, import_i18n146.__)("Theme"),
isDisabled: isInProgress,
onClick: (newAspect) => {
setAspect(newAspect);
onClose();
},
value: aspect,
aspectRatios: themeRatios
}
),
showDefaultRatios && /* @__PURE__ */ (0, import_jsx_runtime307.jsx)(
AspectRatioGroup,
{
label: (0, import_i18n146.__)("Landscape"),
isDisabled: isInProgress,
onClick: (newAspect) => {
setAspect(newAspect);
onClose();
},
value: aspect,
aspectRatios: defaultRatios.map(presetRatioAsNumber).filter(({ ratio }) => ratio > 1)
}
),
showDefaultRatios && /* @__PURE__ */ (0, import_jsx_runtime307.jsx)(
AspectRatioGroup,
{
label: (0, import_i18n146.__)("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_components155 = __toESM(require_components(), 1);
var import_compose80 = __toESM(require_compose(), 1);
var import_jsx_runtime308 = __toESM(require_jsx_runtime(), 1);
function ImageCropper2({
url,
width,
height,
naturalHeight,
naturalWidth,
borderProps
}) {
const { isInProgress, editedUrl, rotation } = useImageEditingContext();
const [contentResizeListener, { width: clientWidth }] = (0, import_compose80.useResizeObserver)();
let editedHeight = height || clientWidth * naturalHeight / naturalWidth;
if (rotation % 180 === 90) {
editedHeight = clientWidth * naturalWidth / naturalHeight;
}
const area = /* @__PURE__ */ (0, import_jsx_runtime308.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_runtime308.jsx)(ImageCropper, { src: editedUrl || url }),
isInProgress && /* @__PURE__ */ (0, import_jsx_runtime308.jsx)(import_components155.Spinner, {})
]
}
);
return /* @__PURE__ */ (0, import_jsx_runtime308.jsxs)(import_jsx_runtime308.Fragment, { children: [
contentResizeListener,
area
] });
}
// packages/block-editor/build-module/components/image-editor/zoom-dropdown.mjs
var import_components156 = __toESM(require_components(), 1);
var import_i18n147 = __toESM(require_i18n(), 1);
var import_jsx_runtime309 = __toESM(require_jsx_runtime(), 1);
function ZoomDropdown() {
const { isInProgress, zoom, setZoom } = useImageEditingContext();
return /* @__PURE__ */ (0, import_jsx_runtime309.jsx)(
import_components156.Dropdown,
{
contentClassName: "wp-block-image__zoom",
popoverProps: POPOVER_PROPS7,
renderToggle: ({ isOpen, onToggle }) => /* @__PURE__ */ (0, import_jsx_runtime309.jsx)(
import_components156.ToolbarButton,
{
icon: search_default,
label: (0, import_i18n147.__)("Zoom"),
onClick: onToggle,
"aria-expanded": isOpen,
disabled: isInProgress
}
),
renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime309.jsx)(import_components156.__experimentalDropdownContentWrapper, { paddingSize: "medium", children: /* @__PURE__ */ (0, import_jsx_runtime309.jsx)(
import_components156.RangeControl,
{
__next40pxDefaultSize: true,
label: (0, import_i18n147.__)("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_components157 = __toESM(require_components(), 1);
var import_i18n148 = __toESM(require_i18n(), 1);
var import_jsx_runtime310 = __toESM(require_jsx_runtime(), 1);
function RotationButton() {
const { isInProgress, rotateClockwise } = useImageEditingContext();
return /* @__PURE__ */ (0, import_jsx_runtime310.jsx)(
import_components157.ToolbarButton,
{
icon: rotate_right_default,
label: (0, import_i18n148.__)("Rotate"),
onClick: rotateClockwise,
disabled: isInProgress
}
);
}
// packages/block-editor/build-module/components/image-editor/form-controls.mjs
var import_components158 = __toESM(require_components(), 1);
var import_i18n149 = __toESM(require_i18n(), 1);
var import_jsx_runtime311 = __toESM(require_jsx_runtime(), 1);
function FormControls() {
const { isInProgress, apply, cancel } = useImageEditingContext();
return /* @__PURE__ */ (0, import_jsx_runtime311.jsxs)(import_jsx_runtime311.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime311.jsx)(import_components158.ToolbarButton, { onClick: apply, disabled: isInProgress, children: (0, import_i18n149.__)("Apply") }),
/* @__PURE__ */ (0, import_jsx_runtime311.jsx)(import_components158.ToolbarButton, { onClick: cancel, children: (0, import_i18n149.__)("Cancel") })
] });
}
// packages/block-editor/build-module/components/image-editor/index.mjs
var import_jsx_runtime312 = __toESM(require_jsx_runtime(), 1);
function ImageEditor({
id,
url,
width,
height,
naturalHeight,
naturalWidth,
onSaveImage,
onFinishEditing,
borderProps
}) {
return /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(ImageCropperProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime312.jsxs)(
ImageEditingProvider,
{
id,
url,
naturalWidth,
naturalHeight,
onSaveImage,
onFinishEditing,
children: [
/* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
ImageCropper2,
{
borderProps,
url,
width,
height,
naturalHeight,
naturalWidth
}
),
/* @__PURE__ */ (0, import_jsx_runtime312.jsxs)(block_controls_default, { children: [
/* @__PURE__ */ (0, import_jsx_runtime312.jsxs)(import_components159.ToolbarGroup, { children: [
/* @__PURE__ */ (0, import_jsx_runtime312.jsx)(ZoomDropdown, {}),
/* @__PURE__ */ (0, import_jsx_runtime312.jsx)(import_components159.ToolbarItem, { children: (toggleProps) => /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
AspectRatioDropdown,
{
toggleProps
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime312.jsx)(RotationButton, {})
] }),
/* @__PURE__ */ (0, import_jsx_runtime312.jsx)(import_components159.ToolbarGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(FormControls, {}) })
] })
]
}
) });
}
// packages/block-editor/build-module/components/image-size-control/index.mjs
var import_components160 = __toESM(require_components(), 1);
var import_i18n150 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/image-size-control/use-dimension-handler.mjs
var import_element165 = __toESM(require_element(), 1);
function useDimensionHandler(customHeight, customWidth, defaultHeight, defaultWidth, onChange) {
const [currentWidth, setCurrentWidth] = (0, import_element165.useState)(
customWidth ?? defaultWidth ?? ""
);
const [currentHeight, setCurrentHeight] = (0, import_element165.useState)(
customHeight ?? defaultHeight ?? ""
);
(0, import_element165.useEffect)(() => {
if (customWidth === void 0 && defaultWidth !== void 0) {
setCurrentWidth(defaultWidth);
}
if (customHeight === void 0 && defaultHeight !== void 0) {
setCurrentHeight(defaultHeight);
}
}, [defaultWidth, defaultHeight]);
(0, import_element165.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_runtime313 = __toESM(require_jsx_runtime(), 1);
var IMAGE_SIZE_PRESETS = [25, 50, 75, 100];
var noop12 = () => {
};
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 = noop12
}) {
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_runtime313.jsxs)(import_components160.__experimentalVStack, { className: "block-editor-image-size-control", spacing: "4", children: [
imageSizeOptions && imageSizeOptions.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime313.jsx)(
import_components160.SelectControl,
{
label: (0, import_i18n150.__)("Resolution"),
value: slug,
options: imageSizeOptions,
onChange: onChangeImage,
help: imageSizeHelp,
size: "__unstable-large"
}
),
isResizable && /* @__PURE__ */ (0, import_jsx_runtime313.jsxs)(import_jsx_runtime313.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime313.jsxs)(import_components160.__experimentalHStack, { align: "baseline", spacing: "4", children: [
/* @__PURE__ */ (0, import_jsx_runtime313.jsx)(
import_components160.__experimentalNumberControl,
{
label: (0, import_i18n150.__)("Width"),
value: currentWidth,
min: 1,
onChange: (value) => updateDimension("width", value),
size: "__unstable-large"
}
),
/* @__PURE__ */ (0, import_jsx_runtime313.jsx)(
import_components160.__experimentalNumberControl,
{
label: (0, import_i18n150.__)("Height"),
value: currentHeight,
min: 1,
onChange: (value) => updateDimension("height", value),
size: "__unstable-large"
}
)
] }),
/* @__PURE__ */ (0, import_jsx_runtime313.jsx)(
import_components160.__experimentalToggleGroupControl,
{
label: (0, import_i18n150.__)("Image size presets"),
hideLabelFromVision: true,
onChange: handleUpdateDimensions,
value: selectedValue,
isBlock: true,
__next40pxDefaultSize: true,
children: IMAGE_SIZE_PRESETS.map((scale) => {
return /* @__PURE__ */ (0, import_jsx_runtime313.jsx)(
import_components160.__experimentalToggleGroupControlOption,
{
value: scale,
label: (0, import_i18n150.sprintf)(
/* translators: %d: Percentage value. */
(0, import_i18n150.__)("%d%%"),
scale
)
},
scale
);
})
}
)
] })
] });
}
// packages/block-editor/build-module/components/justify-content-control/ui.mjs
var import_components161 = __toESM(require_components(), 1);
var import_i18n151 = __toESM(require_i18n(), 1);
var import_jsx_runtime314 = __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_i18n151.__)("Justify items left"),
isActive: "left" === value,
onClick: () => handleClick("left")
},
{
name: "center",
icon: justify_center_default,
title: (0, import_i18n151.__)("Justify items center"),
isActive: "center" === value,
onClick: () => handleClick("center")
},
{
name: "right",
icon: justify_right_default,
title: (0, import_i18n151.__)("Justify items right"),
isActive: "right" === value,
onClick: () => handleClick("right")
},
{
name: "space-between",
icon: justify_space_between_default,
title: (0, import_i18n151.__)("Space between items"),
isActive: "space-between" === value,
onClick: () => handleClick("space-between")
},
{
name: "stretch",
icon: justify_stretch_default,
title: (0, import_i18n151.__)("Stretch items"),
isActive: "stretch" === value,
onClick: () => handleClick("stretch")
}
];
const UIComponent = isToolbar ? import_components161.ToolbarGroup : import_components161.ToolbarDropdownMenu;
const extraProps = isToolbar ? { isCollapsed: isCollapsed3 } : {};
return /* @__PURE__ */ (0, import_jsx_runtime314.jsx)(
UIComponent,
{
icon,
popoverProps: popoverProps3,
label: (0, import_i18n151.__)("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_runtime315 = __toESM(require_jsx_runtime(), 1);
var JustifyContentControl = (props) => {
return /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(ui_default4, { ...props, isToolbar: false });
};
var JustifyToolbar = (props) => {
return /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(ui_default4, { ...props, isToolbar: true });
};
// packages/block-editor/build-module/components/link-control/index.mjs
var import_components169 = __toESM(require_components(), 1);
var import_i18n161 = __toESM(require_i18n(), 1);
var import_element173 = __toESM(require_element(), 1);
var import_compose84 = __toESM(require_compose(), 1);
var import_dom35 = __toESM(require_dom(), 1);
var import_keycodes16 = __toESM(require_keycodes(), 1);
var import_is_shallow_equal3 = __toESM(require_is_shallow_equal(), 1);
var import_data147 = __toESM(require_data(), 1);
var import_preferences4 = __toESM(require_preferences(), 1);
var import_deprecated23 = __toESM(require_deprecated(), 1);
// packages/block-editor/build-module/components/link-control/settings-drawer.mjs
var import_components162 = __toESM(require_components(), 1);
var import_compose81 = __toESM(require_compose(), 1);
var import_i18n152 = __toESM(require_i18n(), 1);
var import_element166 = __toESM(require_element(), 1);
var import_jsx_runtime316 = __toESM(require_jsx_runtime(), 1);
function LinkSettingsDrawer({ children, settingsOpen, setSettingsOpen }) {
const prefersReducedMotion = (0, import_compose81.useReducedMotion)();
const MaybeAnimatePresence = prefersReducedMotion ? import_element166.Fragment : import_components162.__unstableAnimatePresence;
const MaybeMotionDiv = prefersReducedMotion ? "div" : import_components162.__unstableMotion.div;
const id = (0, import_compose81.useInstanceId)(LinkSettingsDrawer);
const settingsDrawerId = `link-control-settings-drawer-${id}`;
return /* @__PURE__ */ (0, import_jsx_runtime316.jsxs)(import_jsx_runtime316.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime316.jsx)(
import_components162.Button,
{
__next40pxDefaultSize: true,
className: "block-editor-link-control__drawer-toggle",
"aria-expanded": settingsOpen,
onClick: () => setSettingsOpen(!settingsOpen),
icon: (0, import_i18n152.isRTL)() ? chevron_left_small_default : chevron_right_small_default,
"aria-controls": settingsDrawerId,
children: (0, import_i18n152._x)("Advanced", "Additional link settings")
}
),
/* @__PURE__ */ (0, import_jsx_runtime316.jsx)(MaybeAnimatePresence, { children: settingsOpen && /* @__PURE__ */ (0, import_jsx_runtime316.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_runtime316.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_element169 = __toESM(require_element(), 1);
var import_i18n157 = __toESM(require_i18n(), 1);
var import_deprecated22 = __toESM(require_deprecated(), 1);
// packages/block-editor/build-module/components/link-control/search-results.mjs
var import_i18n156 = __toESM(require_i18n(), 1);
var import_components165 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/link-control/search-create-button.mjs
var import_i18n153 = __toESM(require_i18n(), 1);
var import_components163 = __toESM(require_components(), 1);
var import_element167 = __toESM(require_element(), 1);
var import_jsx_runtime317 = __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_element167.createInterpolateElement)(
(0, import_i18n153.sprintf)(
/* translators: %s: search term. */
(0, import_i18n153.__)("Create: <mark>%s</mark>"),
searchTerm
),
{ mark: /* @__PURE__ */ (0, import_jsx_runtime317.jsx)("mark", {}) }
);
}
return /* @__PURE__ */ (0, import_jsx_runtime317.jsx)(
import_components163.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_i18n154 = __toESM(require_i18n(), 1);
var import_components164 = __toESM(require_components(), 1);
var import_dom33 = __toESM(require_dom(), 1);
var import_url5 = __toESM(require_url(), 1);
var import_compose82 = __toESM(require_compose(), 1);
var import_deprecated20 = __toESM(require_deprecated(), 1);
var import_jsx_runtime318 = __toESM(require_jsx_runtime(), 1);
var TYPES = {
post: {
icon: post_list_default,
label: (0, import_i18n154.__)("Post")
},
page: {
icon: page_default,
label: (0, import_i18n154.__)("Page")
},
post_tag: {
icon: tag_default,
label: (0, import_i18n154.__)("Tag")
},
category: {
icon: category_default,
label: (0, import_i18n154.__)("Category")
},
attachment: {
icon: file_default,
label: (0, import_i18n154.__)("Attachment")
}
};
function SearchItemIcon({ isURL: isURL3, suggestion }) {
let icon = null;
if (isURL3) {
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_runtime318.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_compose82.pipe)(
import_url5.safeDecodeURI,
import_url5.getPath,
defaultTo(""),
partialRight(import_url5.filterURLForDisplay, 24),
removeTrailingSlash,
addLeadingSlash
)(url);
}
var LinkControlSearchItem = ({
itemProps,
suggestion,
searchTerm,
onClick,
isURL: isURL3 = false,
shouldShowType = false
}) => {
const info = isURL3 ? (0, import_i18n154.__)("Press ENTER to add this link") : getURLForDisplay(suggestion.url);
return /* @__PURE__ */ (0, import_jsx_runtime318.jsx)(
import_components164.MenuItem,
{
...itemProps,
info,
iconPosition: "left",
icon: /* @__PURE__ */ (0, import_jsx_runtime318.jsx)(SearchItemIcon, { suggestion, isURL: isURL3 }),
onClick,
shortcut: shouldShowType && getVisualTypeName(suggestion),
className: "block-editor-link-control__search-item",
children: /* @__PURE__ */ (0, import_jsx_runtime318.jsx)(
import_components164.TextHighlight,
{
text: (0, import_dom33.__unstableStripHTML)(suggestion.title),
highlight: searchTerm
}
)
}
);
};
function getVisualTypeName(suggestion) {
if (suggestion.isFrontPage) {
return (0, import_i18n154.__)("Front page");
}
if (suggestion.isBlogHome) {
return (0, import_i18n154.__)("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_deprecated20.default)("wp.blockEditor.__experimentalLinkControlSearchItem", {
since: "6.8"
});
return /* @__PURE__ */ (0, import_jsx_runtime318.jsx)(LinkControlSearchItem, { ...props });
};
// packages/block-editor/build-module/components/link-control/constants.mjs
var import_i18n155 = __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_i18n155.__)("Open in new tab")
}
];
// packages/block-editor/build-module/components/link-control/search-results.mjs
var import_deprecated21 = __toESM(require_deprecated(), 1);
var import_jsx_runtime319 = __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_i18n156.__)("Suggestions") : (0, import_i18n156.sprintf)(
/* translators: %s: search term. */
(0, import_i18n156.__)('Search results for "%s"'),
currentInputValue
);
return /* @__PURE__ */ (0, import_jsx_runtime319.jsx)("div", { className: "block-editor-link-control__search-results-wrapper", children: /* @__PURE__ */ (0, import_jsx_runtime319.jsx)(
"div",
{
...suggestionsListProps,
className: resultsListClasses,
"aria-label": labelText,
children: /* @__PURE__ */ (0, import_jsx_runtime319.jsx)(import_components165.MenuGroup, { children: suggestions.map((suggestion, index) => {
if (shouldShowCreateSuggestion && CREATE_TYPE === suggestion.type) {
return /* @__PURE__ */ (0, import_jsx_runtime319.jsx)(
search_create_button_default,
{
searchTerm: currentInputValue,
buttonText: createSuggestionButtonText,
onClick: () => handleSuggestionClick(suggestion),
itemProps: buildSuggestionItemProps(
suggestion,
index
),
isSelected: index === selectedSuggestion
},
suggestion.type
);
}
if (CREATE_TYPE === suggestion.type) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime319.jsx)(
search_item_default,
{
itemProps: buildSuggestionItemProps(
suggestion,
index
),
suggestion,
index,
onClick: () => {
handleSuggestionClick(suggestion);
},
isSelected: index === 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_deprecated21.default)("wp.blockEditor.__experimentalLinkControlSearchResults", {
since: "6.8"
});
return /* @__PURE__ */ (0, import_jsx_runtime319.jsx)(LinkControlSearchResults, { ...props });
};
// packages/block-editor/build-module/components/link-control/use-search-handler.mjs
var import_url6 = __toESM(require_url(), 1);
var import_element168 = __toESM(require_element(), 1);
var import_data144 = __toESM(require_data(), 1);
var handleNoop = () => Promise.resolve([]);
var handleDirectEntry = (val) => {
let type = URL_TYPE;
const protocol = (0, import_url6.getProtocol)(val) || "";
if (protocol.includes("mailto")) {
type = MAILTO_TYPE;
}
if (protocol.includes("tel")) {
type = TEL_TYPE;
}
if (val?.startsWith("#")) {
type = INTERNAL_TYPE;
}
return Promise.resolve([
{
id: val,
title: val,
url: type === "URL" ? (0, import_url6.prependHTTP)(val) : val,
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_data144.useSelect)(
(select3) => {
const { getSettings: getSettings8 } = select3(store);
return {
pageOnFront: getSettings8().pageOnFront,
pageForPosts: getSettings8().pageForPosts,
fetchSearchSuggestions: getSettings8().__experimentalFetchLinkSuggestions
};
},
[]
);
const directEntryHandler = allowDirectEntry ? handleDirectEntry : handleNoop;
return (0, import_element168.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_runtime320 = __toESM(require_jsx_runtime(), 1);
var noopSearchHandler = () => Promise.resolve([]);
var noop13 = () => {
};
var LinkControlSearchInput = (0, import_element169.forwardRef)(
({
value,
children,
currentLink = {},
className = null,
placeholder = null,
withCreateSuggestion = false,
onCreateSuggestion = noop13,
onChange = noop13,
onSelect = noop13,
showSuggestions = true,
renderSuggestions = (props) => /* @__PURE__ */ (0, import_jsx_runtime320.jsx)(search_results_default2, { ...props }),
fetchSuggestions = null,
allowDirectEntry = true,
showInitialSuggestions = false,
suggestionsQuery = {},
withURLSuggestion = true,
createSuggestionButtonText,
hideLabelFromVision = false,
suffix,
isEntity = false
}, ref) => {
const genericSearchHandler = useSearchHandler(
suggestionsQuery,
allowDirectEntry,
withCreateSuggestion,
withURLSuggestion
);
const searchHandler = showSuggestions ? fetchSuggestions || genericSearchHandler : noopSearchHandler;
const [focusedSuggestion, setFocusedSuggestion] = (0, import_element169.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 (e2) {
}
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_i18n157.__)("Search or type URL");
const label = hideLabelFromVision && placeholder !== "" ? _placeholder : (0, import_i18n157.__)("Link");
return /* @__PURE__ */ (0, import_jsx_runtime320.jsxs)("div", { className: "block-editor-link-control__search-input-container", children: [
/* @__PURE__ */ (0, import_jsx_runtime320.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,
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_deprecated22.default)("wp.blockEditor.__experimentalLinkControlSearchInput", {
since: "6.8"
});
return /* @__PURE__ */ (0, import_jsx_runtime320.jsx)(LinkControlSearchInput, { ...props });
};
// packages/block-editor/build-module/components/link-control/link-preview.mjs
var import_i18n158 = __toESM(require_i18n(), 1);
var import_components167 = __toESM(require_components(), 1);
var import_compose83 = __toESM(require_compose(), 1);
var import_url7 = __toESM(require_url(), 1);
var import_dom34 = __toESM(require_dom(), 1);
var import_data146 = __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_components166 = __toESM(require_components(), 1);
var { Slot: ViewerSlot, Fill: ViewerFill } = (0, import_components166.createSlotFill)(
"BlockEditorLinkControlViewer"
);
// packages/block-editor/build-module/components/link-control/use-rich-url-data.mjs
var import_data145 = __toESM(require_data(), 1);
var import_element170 = __toESM(require_element(), 1);
function reducer2(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_element170.useReducer)(reducer2, {
richData: null,
isFetching: false
});
const { fetchRichUrlData } = (0, import_data145.useSelect)((select3) => {
const { getSettings: getSettings8 } = select3(store);
return {
fetchRichUrlData: getSettings8().__experimentalFetchRichUrlData
};
}, []);
(0, import_element170.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_runtime321 = __toESM(require_jsx_runtime(), 1);
function filterTitleForDisplay(title) {
return title.replace(/^[a-z\-.\+]+[0-9]*:(\/\/)?/i, "").replace(/^www\./i, "");
}
function LinkPreview({
value,
onEditClick,
hasRichPreviews = false,
hasUnlinkControl = false,
onRemove
}) {
const showIconLabels = (0, import_data146.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_url7.filterURLForDisplay)((0, import_url7.safeDecodeURI)(value.url), 24) || "";
const isEmptyURL = !value?.url?.length;
const displayTitle = !isEmptyURL && (0, import_dom34.__unstableStripHTML)(richData?.title || value?.title || displayURL);
const isUrlRedundant = !value?.url || filterTitleForDisplay(displayTitle) === displayURL;
let icon;
if (richData?.icon) {
icon = /* @__PURE__ */ (0, import_jsx_runtime321.jsx)("img", { src: richData?.icon, alt: "" });
} else if (isEmptyURL) {
icon = /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(icon_default, { icon: info_default, size: 32 });
} else {
icon = /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(icon_default, { icon: globe_default });
}
const { createNotice } = (0, import_data146.useDispatch)(import_notices10.store);
const ref = (0, import_compose83.useCopyToClipboard)(value.url, () => {
createNotice("info", (0, import_i18n158.__)("Link copied to clipboard."), {
isDismissible: true,
type: "snackbar"
});
});
return /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
import_components167.Flex,
{
role: "group",
"aria-label": (0, import_i18n158.__)("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_runtime321.jsxs)(import_components167.Flex, { gap: 0, children: [
/* @__PURE__ */ (0, import_jsx_runtime321.jsxs)(
import_components167.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_i18n158.__)("Link information")
),
justify: "start",
children: [
/* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
import_components167.Flex,
{
className: clsx_default(
"block-editor-link-control__preview-icon",
{
"is-image": richData?.icon
}
),
justify: "center",
children: icon
}
),
/* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
import_components167.Flex,
{
className: "block-editor-link-control__preview-details",
direction: "column",
gap: 1,
children: !isEmptyURL ? /* @__PURE__ */ (0, import_jsx_runtime321.jsxs)(import_jsx_runtime321.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
import_components167.ExternalLink,
{
className: "block-editor-link-control__preview-title",
href: value.url,
children: /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(import_components167.__experimentalTruncate, { numberOfLines: 1, children: displayTitle })
}
),
!isUrlRedundant && /* @__PURE__ */ (0, import_jsx_runtime321.jsx)("span", { className: "block-editor-link-control__preview-info", children: /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(import_components167.__experimentalTruncate, { numberOfLines: 1, children: displayURL }) })
] }) : /* @__PURE__ */ (0, import_jsx_runtime321.jsx)("span", { className: "block-editor-link-control__preview-error-notice", children: (0, import_i18n158.__)("Link is empty") })
}
)
]
}
),
/* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
import_components167.Button,
{
icon: pencil_default,
label: (0, import_i18n158.__)("Edit link"),
onClick: onEditClick,
size: "compact",
showTooltip: !showIconLabels
}
),
hasUnlinkControl && /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
import_components167.Button,
{
icon: link_off_default,
label: (0, import_i18n158.__)("Remove link"),
onClick: onRemove,
size: "compact",
showTooltip: !showIconLabels
}
),
/* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
import_components167.Button,
{
icon: copy_small_default,
label: (0, import_i18n158.__)("Copy link"),
ref,
accessibleWhenDisabled: true,
disabled: isEmptyURL,
size: "compact",
showTooltip: !showIconLabels
}
),
/* @__PURE__ */ (0, import_jsx_runtime321.jsx)(ViewerSlot, { fillProps: value })
] })
}
);
}
// packages/block-editor/build-module/components/link-control/settings.mjs
var import_i18n159 = __toESM(require_i18n(), 1);
var import_components168 = __toESM(require_components(), 1);
var import_jsx_runtime322 = __toESM(require_jsx_runtime(), 1);
var noop14 = () => {
};
var LinkControlSettings = ({ value, onChange = noop14, 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_runtime322.jsx)(
"div",
{
className: "block-editor-link-control__setting",
children: renderedContent
},
setting.id
);
}
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime322.jsx)(
import_components168.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_runtime322.jsxs)("fieldset", { className: "block-editor-link-control__settings", children: [
/* @__PURE__ */ (0, import_jsx_runtime322.jsx)(import_components168.VisuallyHidden, { as: "legend", children: (0, import_i18n159.__)("Currently selected link settings") }),
theSettings
] });
};
var settings_default2 = LinkControlSettings;
// packages/block-editor/build-module/components/link-control/use-create-page.mjs
var import_i18n160 = __toESM(require_i18n(), 1);
var import_element171 = __toESM(require_element(), 1);
function useCreatePage(handleCreatePage) {
const cancelableCreateSuggestion = (0, import_element171.useRef)();
const [isCreatingPage, setIsCreatingPage] = (0, import_element171.useState)(false);
const [errorMessage, setErrorMessage] = (0, import_element171.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 (error) {
if (error && error.isCanceled) {
return;
}
setErrorMessage(
error.message || (0, import_i18n160.__)(
"An unknown error occurred during creation. Please try again."
)
);
throw error;
} finally {
setIsCreatingPage(false);
}
};
(0, import_element171.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),
(error) => hasCanceled_ ? reject({ isCanceled: true }) : reject(error)
);
});
return {
promise: wrappedPromise,
cancel() {
hasCanceled_ = true;
}
};
};
// packages/block-editor/build-module/components/link-control/use-internal-value.mjs
var import_element172 = __toESM(require_element(), 1);
var import_fast_deep_equal = __toESM(require_fast_deep_equal(), 1);
function useInternalValue(value) {
const [internalValue, setInternalValue] = (0, import_element172.useState)(value || {});
const [previousValue, setPreviousValue] = (0, import_element172.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_runtime323 = __toESM(require_jsx_runtime(), 1);
var noop15 = () => {
};
var PREFERENCE_SCOPE = "core/block-editor";
var PREFERENCE_KEY = "linkControlSettingsDrawer";
function LinkControl({
searchInputPlaceholder,
value,
settings: settings2 = DEFAULT_LINK_SETTINGS,
onChange = noop15,
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_element173.useState)(false);
const { advancedSettingsPreference } = (0, import_data147.useSelect)((select3) => {
const prefsStore = select3(import_preferences4.store);
return {
advancedSettingsPreference: prefsStore.get(PREFERENCE_SCOPE, PREFERENCE_KEY) ?? false
};
}, []);
const { set: setPreference } = (0, import_data147.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_element173.useRef)(true);
const wrapperNode = (0, import_element173.useRef)();
const textInputRef = (0, import_element173.useRef)();
const searchInputRef = (0, import_element173.useRef)();
const entityUrlFallbackRef = (0, import_element173.useRef)();
const settingsKeys = settings2.map(({ id }) => id);
const [
internalControlValue,
setInternalControlValue,
setInternalURLInputValue,
setInternalTextInputValue,
createSetInternalSettingValueHandler
] = useInternalValue(value);
const isEntity = handleEntities && !!internalControlValue?.id;
const baseId = (0, import_compose84.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_element173.useState)(
forceIsEditingLink !== void 0 ? forceIsEditingLink : !value || !value.url
);
const { createPage, isCreatingPage, errorMessage } = useCreatePage(createSuggestion);
(0, import_element173.useEffect)(() => {
if (forceIsEditingLink === void 0) {
return;
}
setIsEditingLink(forceIsEditingLink);
}, [forceIsEditingLink]);
(0, import_element173.useEffect)(() => {
if (isMountingRef.current) {
return;
}
const nextFocusTarget = import_dom35.focus.focusable.find(wrapperNode.current)[0] || wrapperNode.current;
nextFocusTarget.focus();
}, [isEditingLink, isCreatingPage]);
(0, import_element173.useEffect)(() => {
isMountingRef.current = false;
return () => {
isMountingRef.current = true;
};
}, []);
const hasLinkValue = value?.url?.trim()?.length > 0;
const stopEditing = () => {
setIsEditingLink(false);
};
const handleSelectSuggestion = (updatedValue) => {
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
});
stopEditing();
};
const handleSubmit = () => {
if (valueHasChanges) {
onChange({
...value,
...internalControlValue,
url: currentUrlInputValue
});
}
stopEditing();
};
const handleSubmitWithEnter = (event) => {
const { keyCode } = event;
if (keyCode === import_keycodes16.ENTER && !currentInputIsEmpty) {
event.preventDefault();
handleSubmit();
}
};
const resetInternalValues = () => {
setInternalControlValue(value);
};
const handleCancel = (event) => {
event.preventDefault();
event.stopPropagation();
resetInternalValues();
if (hasLinkValue) {
stopEditing();
} else {
onRemove?.();
}
onCancel?.();
};
const [shouldFocusSearchInput, setShouldFocusSearchInput] = (0, import_element173.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_element173.useEffect)(() => {
if (shouldFocusSearchInput) {
searchInputRef.current?.focus();
setShouldFocusSearchInput(false);
}
}, [shouldFocusSearchInput]);
const currentUrlInputValue = propInputValue || internalControlValue?.url || "";
const currentInputIsEmpty = !currentUrlInputValue?.trim()?.length;
const shownUnlinkControl = onRemove && value && !isEditingLink && !isCreatingPage;
const showActions = isEditingLink && hasLinkValue;
const showTextControl = hasLinkValue && hasTextControl;
const isEditing = (isEditingLink || !value) && !isCreatingPage;
const isDisabled = !valueHasChanges || currentInputIsEmpty;
const showSettings = !!settings2?.length && isEditingLink && hasLinkValue;
const previewValue = (0, import_element173.useMemo)(() => {
if (value?.kind === "taxonomy" && !value?.url && entityUrlFallbackRef.current) {
return {
...value,
url: entityUrlFallbackRef.current
};
}
return value;
}, [value]);
return /* @__PURE__ */ (0, import_jsx_runtime323.jsxs)(
"div",
{
tabIndex: -1,
ref: wrapperNode,
className: "block-editor-link-control",
children: [
isCreatingPage && /* @__PURE__ */ (0, import_jsx_runtime323.jsxs)("div", { className: "block-editor-link-control__loading", children: [
/* @__PURE__ */ (0, import_jsx_runtime323.jsx)(import_components169.Spinner, {}),
" ",
(0, import_i18n161.__)("Creating"),
"\u2026"
] }),
isEditing && /* @__PURE__ */ (0, import_jsx_runtime323.jsxs)(import_jsx_runtime323.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime323.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_runtime323.jsx)(
import_components169.TextControl,
{
ref: textInputRef,
className: "block-editor-link-control__field block-editor-link-control__text-content",
label: (0, import_i18n161.__)("Text"),
value: internalControlValue?.title,
onChange: setInternalTextInputValue,
onKeyDown: handleSubmitWithEnter,
__next40pxDefaultSize: true
}
),
/* @__PURE__ */ (0, import_jsx_runtime323.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: setInternalURLInputValue,
onSelect: handleSelectSuggestion,
showInitialSuggestions,
allowDirectEntry: !noDirectEntry,
showSuggestions,
suggestionsQuery,
withURLSuggestion: !noURLSuggestion,
createSuggestionButtonText,
hideLabelFromVision: !showTextControl,
isEntity,
suffix: /* @__PURE__ */ (0, import_jsx_runtime323.jsx)(
SearchSuffixControl,
{
isEntity,
showActions,
isDisabled,
onUnlink: handleUnlink,
onSubmit: handleSubmit,
helpTextId
}
)
}
),
isEntity && helpTextId && /* @__PURE__ */ (0, import_jsx_runtime323.jsx)(
"p",
{
id: helpTextId,
className: "block-editor-link-control__help",
children: (0, import_i18n161.sprintf)(
/* translators: %s: entity type (e.g., page, post) */
(0, import_i18n161.__)("Synced with the selected %s."),
internalControlValue?.type || "item"
)
}
)
]
}
),
errorMessage && /* @__PURE__ */ (0, import_jsx_runtime323.jsx)(
import_components169.Notice,
{
className: "block-editor-link-control__search-error",
status: "error",
isDismissible: false,
children: errorMessage
}
)
] }),
value && !isEditingLink && !isCreatingPage && /* @__PURE__ */ (0, import_jsx_runtime323.jsx)(
LinkPreview,
{
value: previewValue,
onEditClick: () => setIsEditingLink(true),
hasRichPreviews,
hasUnlinkControl: shownUnlinkControl,
onRemove: () => {
onRemove();
setIsEditingLink(true);
}
},
previewValue?.url
),
showSettings && /* @__PURE__ */ (0, import_jsx_runtime323.jsx)("div", { className: "block-editor-link-control__tools", children: !currentInputIsEmpty && /* @__PURE__ */ (0, import_jsx_runtime323.jsx)(
settings_drawer_default,
{
settingsOpen: isSettingsOpen,
setSettingsOpen: setSettingsOpenWithPreference,
children: /* @__PURE__ */ (0, import_jsx_runtime323.jsx)(
settings_default2,
{
value: internalControlValue,
settings: settings2,
onChange: createSetInternalSettingValueHandler(
settingsKeys
)
}
)
}
) }),
showActions && /* @__PURE__ */ (0, import_jsx_runtime323.jsxs)(
import_components169.__experimentalHStack,
{
justify: "right",
className: "block-editor-link-control__search-actions",
children: [
/* @__PURE__ */ (0, import_jsx_runtime323.jsx)(
import_components169.Button,
{
__next40pxDefaultSize: true,
variant: "tertiary",
onClick: handleCancel,
children: (0, import_i18n161.__)("Cancel")
}
),
/* @__PURE__ */ (0, import_jsx_runtime323.jsx)(
import_components169.Button,
{
__next40pxDefaultSize: true,
variant: "primary",
onClick: isDisabled ? noop15 : handleSubmit,
className: "block-editor-link-control__search-submit",
"aria-disabled": isDisabled,
children: (0, import_i18n161.__)("Apply")
}
)
]
}
),
!isCreatingPage && renderControlBottom && renderControlBottom()
]
}
);
}
function SearchSuffixControl({
isEntity,
showActions,
isDisabled,
onUnlink,
onSubmit,
helpTextId
}) {
if (isEntity) {
return /* @__PURE__ */ (0, import_jsx_runtime323.jsx)(
import_components169.Button,
{
icon: link_off_default,
onClick: onUnlink,
"aria-describedby": helpTextId,
showTooltip: true,
label: (0, import_i18n161.__)("Unsync and edit"),
__next40pxDefaultSize: true
}
);
}
if (showActions) {
return void 0;
}
return /* @__PURE__ */ (0, import_jsx_runtime323.jsx)(import_components169.__experimentalInputControlSuffixWrapper, { variant: "control", children: /* @__PURE__ */ (0, import_jsx_runtime323.jsx)(
import_components169.Button,
{
onClick: isDisabled ? noop15 : onSubmit,
label: (0, import_i18n161.__)("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_deprecated23.default)("wp.blockEditor.__experimentalLinkControl", {
since: "6.8",
alternative: "wp.blockEditor.LinkControl"
});
return /* @__PURE__ */ (0, import_jsx_runtime323.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_i18n162 = __toESM(require_i18n(), 1);
var import_components170 = __toESM(require_components(), 1);
var import_deprecated24 = __toESM(require_deprecated(), 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_runtime324 = __toESM(require_jsx_runtime(), 1);
var LineHeightControl = ({
/** Start opting into the larger default height that will become the default size in a future version. */
__next40pxDefaultSize = false,
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}`);
};
if (!__next40pxDefaultSize && (otherProps.size === void 0 || otherProps.size === "default")) {
(0, import_deprecated24.default)(`36px default size for wp.blockEditor.LineHeightControl`, {
since: "6.8",
version: "7.1",
hint: "Set the `__next40pxDefaultSize` prop to true to start opting into the new default size, which will become the default in a future version."
});
}
return /* @__PURE__ */ (0, import_jsx_runtime324.jsx)("div", { className: "block-editor-line-height-control", children: /* @__PURE__ */ (0, import_jsx_runtime324.jsx)(
import_components170.__experimentalNumberControl,
{
...otherProps,
__shouldNotWarnDeprecated36pxSize: true,
__next40pxDefaultSize,
__unstableInputWidth,
__unstableStateReducer: stateReducer,
onChange: handleOnChange,
label: (0, import_i18n162.__)("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_i18n163 = __toESM(require_i18n(), 1);
var import_a11y18 = __toESM(require_a11y(), 1);
var import_components171 = __toESM(require_components(), 1);
var import_data148 = __toESM(require_data(), 1);
var import_keycodes17 = __toESM(require_keycodes(), 1);
var import_compose85 = __toESM(require_compose(), 1);
var import_dom36 = __toESM(require_dom(), 1);
var import_notices11 = __toESM(require_notices(), 1);
var import_element174 = __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_runtime325 = __toESM(require_jsx_runtime(), 1);
var noop16 = () => {
};
var uniqueId = 0;
var MediaReplaceFlow = ({
mediaURL,
mediaId,
mediaIds,
allowedTypes,
accept,
onError,
onSelect,
onSelectURL,
onReset,
onToggleFeaturedImage,
useFeaturedImage,
onFilesUpload = noop16,
name = (0, import_i18n163.__)("Replace"),
createNotice,
removeNotice,
children,
multiple = false,
addToGallery,
handleUpload = true,
variant,
popoverProps: popoverProps3,
renderToggle: renderToggle3,
className
}) => {
const { mediaUpload: mediaUpload2, allowedMimeTypes } = (0, import_data148.useSelect)((select3) => {
const { getSettings: getSettings8 } = select3(store);
const settings2 = getSettings8();
return {
mediaUpload: settings2.mediaUpload,
allowedMimeTypes: settings2.allowedMimeTypes
};
}, []);
const errorNoticeID = `block-editor/media-replace-flow/error-notice/${++uniqueId}`;
const computedAccept = (0, import_element174.useMemo)(
() => getComputedAcceptAttribute(
allowedTypes,
allowedMimeTypes,
accept
),
[allowedTypes, allowedMimeTypes, accept]
);
const onUploadError = (message2) => {
const safeMessage = (0, import_dom36.__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_i18n163.__)("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_keycodes17.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_runtime325.jsx)(
import_components171.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_runtime325.jsx)(
import_components171.ToolbarButton,
{
"aria-expanded": isOpen,
"aria-haspopup": "true",
onClick: onToggle,
onKeyDown: openOnArrowDown,
children: name
}
);
},
renderContent: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime325.jsxs)(import_jsx_runtime325.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime325.jsxs)(import_components171.NavigableMenu, { className: "block-editor-media-replace-flow__media-upload-menu", children: [
/* @__PURE__ */ (0, import_jsx_runtime325.jsxs)(check_default2, { children: [
/* @__PURE__ */ (0, import_jsx_runtime325.jsx)(
media_upload_default,
{
gallery,
addToGallery,
multiple,
value: multiple ? mediaIds : mediaId,
onSelect: (media) => selectMedia(media, onClose),
allowedTypes,
render: ({ open }) => /* @__PURE__ */ (0, import_jsx_runtime325.jsx)(
import_components171.MenuItem,
{
icon: media_default,
onClick: open,
children: (0, import_i18n163.__)("Open Media Library")
}
)
}
),
/* @__PURE__ */ (0, import_jsx_runtime325.jsx)(
import_components171.FormFileUpload,
{
onChange: (event) => {
uploadFiles(event, onClose);
},
accept: computedAccept,
multiple: !!multiple,
render: ({ openFileDialog }) => {
return /* @__PURE__ */ (0, import_jsx_runtime325.jsx)(
import_components171.MenuItem,
{
icon: upload_default,
onClick: () => {
openFileDialog();
},
children: (0, import_i18n163._x)("Upload", "verb")
}
);
}
}
)
] }),
onToggleFeaturedImage && /* @__PURE__ */ (0, import_jsx_runtime325.jsx)(
import_components171.MenuItem,
{
icon: post_featured_image_default,
onClick: onToggleFeaturedImage,
isPressed: useFeaturedImage,
children: (0, import_i18n163.__)("Use featured image")
}
),
mediaURL && onReset && /* @__PURE__ */ (0, import_jsx_runtime325.jsx)(
import_components171.MenuItem,
{
onClick: () => {
onReset();
onClose();
},
children: (0, import_i18n163.__)("Reset")
}
),
typeof children === "function" ? children({ onClose }) : children
] }),
onSelectURL && /* @__PURE__ */ (0, import_jsx_runtime325.jsxs)("form", { className: "block-editor-media-flow__url-input", children: [
/* @__PURE__ */ (0, import_jsx_runtime325.jsx)("span", { className: "block-editor-media-replace-flow__image-url-label", children: (0, import_i18n163.__)("Current media URL:") }),
/* @__PURE__ */ (0, import_jsx_runtime325.jsx)(
link_control_default,
{
value: { url: mediaURL },
settings: [],
showSuggestions: false,
onChange: ({ url }) => {
onSelectURL(url);
},
searchInputPlaceholder: (0, import_i18n163.__)(
"Paste or type URL"
)
}
)
] })
] })
}
);
};
var media_replace_flow_default = (0, import_compose85.compose)([
(0, import_data148.withDispatch)((dispatch) => {
const { createNotice, removeNotice } = dispatch(import_notices11.store);
return {
createNotice,
removeNotice
};
}),
(0, import_components171.withFilters)("editor.MediaReplaceFlow")
])(MediaReplaceFlow);
// packages/block-editor/build-module/components/media-placeholder/index.mjs
var import_components177 = __toESM(require_components(), 1);
var import_i18n168 = __toESM(require_i18n(), 1);
var import_element177 = __toESM(require_element(), 1);
var import_data150 = __toESM(require_data(), 1);
var import_deprecated26 = __toESM(require_deprecated(), 1);
// packages/block-editor/build-module/components/url-popover/index.mjs
var import_i18n167 = __toESM(require_i18n(), 1);
var import_element176 = __toESM(require_element(), 1);
var import_components176 = __toESM(require_components(), 1);
var import_deprecated25 = __toESM(require_deprecated(), 1);
// packages/block-editor/build-module/components/url-popover/link-viewer.mjs
var import_i18n164 = __toESM(require_i18n(), 1);
var import_components173 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/url-popover/link-viewer-url.mjs
var import_components172 = __toESM(require_components(), 1);
var import_url8 = __toESM(require_url(), 1);
var import_jsx_runtime326 = __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_runtime326.jsx)("span", { className: linkClassName });
}
return /* @__PURE__ */ (0, import_jsx_runtime326.jsx)(import_components172.ExternalLink, { className: linkClassName, href: url, children: urlLabel || (0, import_url8.filterURLForDisplay)((0, import_url8.safeDecodeURI)(url)) });
}
// packages/block-editor/build-module/components/url-popover/link-viewer.mjs
var import_jsx_runtime327 = __toESM(require_jsx_runtime(), 1);
function LinkViewer({
className,
linkClassName,
onEditLinkClick,
url,
urlLabel,
...props
}) {
return /* @__PURE__ */ (0, import_jsx_runtime327.jsxs)(
"div",
{
className: clsx_default(
"block-editor-url-popover__link-viewer",
className
),
...props,
children: [
/* @__PURE__ */ (0, import_jsx_runtime327.jsx)(
LinkViewerURL,
{
url,
urlLabel,
className: linkClassName
}
),
onEditLinkClick && /* @__PURE__ */ (0, import_jsx_runtime327.jsx)(
import_components173.Button,
{
icon: pencil_default,
label: (0, import_i18n164.__)("Edit"),
onClick: onEditLinkClick,
size: "compact"
}
)
]
}
);
}
// packages/block-editor/build-module/components/url-popover/link-editor.mjs
var import_i18n166 = __toESM(require_i18n(), 1);
var import_components175 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/url-input/index.mjs
var import_i18n165 = __toESM(require_i18n(), 1);
var import_element175 = __toESM(require_element(), 1);
var import_keycodes18 = __toESM(require_keycodes(), 1);
var import_components174 = __toESM(require_components(), 1);
var import_compose86 = __toESM(require_compose(), 1);
var import_data149 = __toESM(require_data(), 1);
var import_url9 = __toESM(require_url(), 1);
var import_jsx_runtime328 = __toESM(require_jsx_runtime(), 1);
var import_react4 = __toESM(require_react(), 1);
function isFunction(maybeFunc) {
return typeof maybeFunc === "function";
}
var URLInput = class extends import_element175.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_element175.createRef)();
this.inputRef = props.inputRef || (0, import_element175.createRef)();
this.updateSuggestions = (0, import_compose86.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(index) {
return (ref) => {
this.suggestionNodes[index] = 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_url9.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_i18n165.sprintf)(
/* translators: %d: number of results. */
(0, import_i18n165._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_i18n165.__)("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_keycodes18.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_keycodes18.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_keycodes18.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_keycodes18.UP: {
event.preventDefault();
const previousIndex = !selectedSuggestion ? suggestions.length - 1 : selectedSuggestion - 1;
this.setState({
selectedSuggestion: previousIndex
});
break;
}
case import_keycodes18.DOWN: {
event.preventDefault();
const nextIndex = selectedSuggestion === null || selectedSuggestion === suggestions.length - 1 ? 0 : selectedSuggestion + 1;
this.setState({
selectedSuggestion: nextIndex
});
break;
}
case import_keycodes18.TAB: {
if (this.state.selectedSuggestion !== null) {
this.selectLink(suggestion);
this.props.speak((0, import_i18n165.__)("Link selected."));
}
break;
}
case import_keycodes18.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_runtime328.jsxs)(import_jsx_runtime328.Fragment, { children: [
this.renderControl(),
this.renderSuggestions()
] });
}
renderControl() {
const {
label = null,
className,
isFullWidth,
instanceId,
placeholder = (0, import_i18n165.__)("Paste URL or type to search"),
__experimentalRenderControl: renderControl,
value = "",
hideLabelFromVision = false,
help = null,
disabled = false
} = 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: true,
type: "text",
name: inputId,
autoComplete: "off",
onChange: disabled ? () => {
} : this.onChange,
// Disable onChange when disabled
onFocus: disabled ? () => {
} : this.onFocus,
// Disable onFocus when disabled
placeholder,
onKeyDown: disabled ? () => {
} : this.onKeyDown,
// Disable onKeyDown when disabled
role: "combobox",
"aria-label": label ? void 0 : (0, import_i18n165.__)("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,
suffix: this.props.suffix,
help
};
if (renderControl) {
return renderControl(controlProps, inputProps, loading);
}
return /* @__PURE__ */ (0, import_jsx_runtime328.jsxs)(import_components174.BaseControl, { ...controlProps, children: [
/* @__PURE__ */ (0, import_jsx_runtime328.jsx)(import_components174.__experimentalInputControl, { ...inputProps, __next40pxDefaultSize: true }),
loading && /* @__PURE__ */ (0, import_jsx_runtime328.jsx)(import_components174.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, index) => {
return {
role: "option",
tabIndex: "-1",
id: `${suggestionOptionIdPrefix}-${index}`,
ref: this.bindSuggestionNode(index),
"aria-selected": index === 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_runtime328.jsx)(import_components174.Popover, { placement: "bottom", focusOnMount: false, children: /* @__PURE__ */ (0, import_jsx_runtime328.jsx)(
"div",
{
...suggestionsListProps,
className: clsx_default("block-editor-url-input__suggestions", {
[`${className}__suggestions`]: className
}),
children: suggestions.map((suggestion, index) => /* @__PURE__ */ (0, import_react4.createElement)(
import_components174.Button,
{
__next40pxDefaultSize: true,
...buildSuggestionItemProps(suggestion, index),
key: suggestion.id,
className: clsx_default(
"block-editor-url-input__suggestion",
{
"is-selected": index === selectedSuggestion
}
),
onClick: () => this.handleOnClick(suggestion)
},
suggestion.title
))
}
) });
}
};
var url_input_default = (0, import_compose86.compose)(
import_compose86.withSafeTimeout,
import_components174.withSpokenMessages,
import_compose86.withInstanceId,
(0, import_data149.withSelect)((select3, props) => {
if (isFunction(props.__experimentalFetchLinkSuggestions)) {
return;
}
const { getSettings: getSettings8 } = select3(store);
return {
__experimentalFetchLinkSuggestions: getSettings8().__experimentalFetchLinkSuggestions
};
})
)(URLInput);
// packages/block-editor/build-module/components/url-popover/link-editor.mjs
var import_jsx_runtime329 = __toESM(require_jsx_runtime(), 1);
function LinkEditor({
autocompleteRef,
className,
onChangeInputValue,
value,
...props
}) {
return /* @__PURE__ */ (0, import_jsx_runtime329.jsxs)(
"form",
{
className: clsx_default(
"block-editor-url-popover__link-editor",
className
),
...props,
children: [
/* @__PURE__ */ (0, import_jsx_runtime329.jsx)(
url_input_default,
{
value,
onChange: onChangeInputValue,
autocompleteRef
}
),
/* @__PURE__ */ (0, import_jsx_runtime329.jsx)(
import_components175.Button,
{
icon: keyboard_return_default,
label: (0, import_i18n166.__)("Apply"),
type: "submit",
size: "compact"
}
)
]
}
);
}
// packages/block-editor/build-module/components/url-popover/index.mjs
var import_jsx_runtime330 = __toESM(require_jsx_runtime(), 1);
var { __experimentalPopoverLegacyPositionToPlacement } = unlock(
import_components176.privateApis
);
var DEFAULT_PLACEMENT = "bottom";
var URLPopover = (0, import_element176.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_deprecated25.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_element176.useState)(false);
const showSettings = !!renderSettings && isSettingsExpanded;
const toggleSettingsVisibility = () => {
setIsSettingsExpanded(!isSettingsExpanded);
};
return /* @__PURE__ */ (0, import_jsx_runtime330.jsxs)(
import_components176.Popover,
{
ref,
role: "dialog",
"aria-modal": "true",
"aria-label": (0, import_i18n167.__)("Edit URL"),
className: "block-editor-url-popover",
focusOnMount,
placement: computedPlacement,
shift: true,
variant: "toolbar",
...popoverProps3,
children: [
/* @__PURE__ */ (0, import_jsx_runtime330.jsx)("div", { className: "block-editor-url-popover__input-container", children: /* @__PURE__ */ (0, import_jsx_runtime330.jsxs)("div", { className: "block-editor-url-popover__row", children: [
children,
!!renderSettings && /* @__PURE__ */ (0, import_jsx_runtime330.jsx)(
import_components176.Button,
{
className: "block-editor-url-popover__settings-toggle",
icon: chevron_down_default,
label: (0, import_i18n167.__)("Link settings"),
onClick: toggleSettingsVisibility,
"aria-expanded": isSettingsExpanded,
size: "compact"
}
)
] }) }),
showSettings && /* @__PURE__ */ (0, import_jsx_runtime330.jsx)("div", { className: "block-editor-url-popover__settings", children: renderSettings() }),
additionalControls && !showSettings && /* @__PURE__ */ (0, import_jsx_runtime330.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_runtime331 = __toESM(require_jsx_runtime(), 1);
var noop17 = () => {
};
var InsertFromURLPopover = ({
src,
onChange,
onSubmit,
onClose,
popoverAnchor
}) => /* @__PURE__ */ (0, import_jsx_runtime331.jsx)(url_popover_default, { anchor: popoverAnchor, onClose, children: /* @__PURE__ */ (0, import_jsx_runtime331.jsx)(
"form",
{
className: "block-editor-media-placeholder__url-input-form",
onSubmit,
children: /* @__PURE__ */ (0, import_jsx_runtime331.jsx)(
import_components177.__experimentalInputControl,
{
__next40pxDefaultSize: true,
label: (0, import_i18n168.__)("URL"),
type: "text",
hideLabelFromVision: true,
placeholder: (0, import_i18n168.__)("Paste or type URL"),
onChange,
value: src,
suffix: /* @__PURE__ */ (0, import_jsx_runtime331.jsx)(import_components177.__experimentalInputControlSuffixWrapper, { variant: "control", children: /* @__PURE__ */ (0, import_jsx_runtime331.jsx)(
import_components177.Button,
{
size: "small",
icon: keyboard_return_default,
label: (0, import_i18n168.__)("Apply"),
type: "submit"
}
) })
}
)
}
) });
var URLSelectionUI = ({ src, onChangeSrc, onSelectURL }) => {
const [popoverAnchor, setPopoverAnchor] = (0, import_element177.useState)(null);
const [isURLInputVisible, setIsURLInputVisible] = (0, import_element177.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_runtime331.jsxs)("div", { className: "block-editor-media-placeholder__url-input-container", children: [
/* @__PURE__ */ (0, import_jsx_runtime331.jsx)(
import_components177.Button,
{
__next40pxDefaultSize: true,
className: "block-editor-media-placeholder__button",
onClick: openURLInput,
isPressed: isURLInputVisible,
variant: "secondary",
"aria-haspopup": "dialog",
ref: setPopoverAnchor,
children: (0, import_i18n168.__)("Insert from URL")
}
),
isURLInputVisible && /* @__PURE__ */ (0, import_jsx_runtime331.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 = noop17,
onHTMLDrop: deprecatedOnHTMLDrop,
children,
mediaLibraryButton,
placeholder,
style
}) {
if (deprecatedOnHTMLDrop) {
(0, import_deprecated26.default)("wp.blockEditor.MediaPlaceholder onHTMLDrop prop", {
since: "6.2",
version: "6.4"
});
}
const { mediaUpload: mediaUpload2, allowedMimeTypes } = (0, import_data150.useSelect)((select3) => {
const { getSettings: getSettings8 } = select3(store);
const settings2 = getSettings8();
return {
mediaUpload: settings2.mediaUpload,
allowedMimeTypes: settings2.allowedMimeTypes
};
}, []);
const [src, setSrc] = (0, import_element177.useState)("");
(0, import_element177.useEffect)(() => {
setSrc(value?.src ?? "");
}, [value?.src]);
const computedAccept = (0, import_element177.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_i18n168.__)(
"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_i18n168.__)(
"Drag and drop an image or video, upload, or choose from your library."
);
if (isAudio) {
instructions = (0, import_i18n168.__)(
"Drag and drop an audio file, upload, or choose from your library."
);
} else if (isImage) {
instructions = (0, import_i18n168.__)(
"Drag and drop an image, upload, or choose from your library."
);
} else if (isVideo) {
instructions = (0, import_i18n168.__)(
"Drag and drop a video, upload, or choose from your library."
);
}
}
if (title === void 0) {
title = (0, import_i18n168.__)("Media");
if (isAudio) {
title = (0, import_i18n168.__)("Audio");
} else if (isImage) {
title = (0, import_i18n168.__)("Image");
} else if (isVideo) {
title = (0, import_i18n168.__)("Video");
}
}
}
const placeholderClassName = clsx_default(
"block-editor-media-placeholder",
className,
{
"is-appender": isAppender
}
);
return /* @__PURE__ */ (0, import_jsx_runtime331.jsxs)(
import_components177.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_runtime331.jsx)(
import_components177.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_runtime331.jsx)(
import_components177.Button,
{
__next40pxDefaultSize: true,
className: "block-editor-media-placeholder__cancel-button",
title: (0, import_i18n168.__)("Cancel"),
variant: "link",
onClick: onCancel,
children: (0, import_i18n168.__)("Cancel")
}
);
};
const renderUrlSelectionUI = () => {
return onSelectURL && /* @__PURE__ */ (0, import_jsx_runtime331.jsx)(
URLSelectionUI,
{
src,
onChangeSrc: setSrc,
onSelectURL
}
);
};
const renderFeaturedImageToggle = () => {
return onToggleFeaturedImage && /* @__PURE__ */ (0, import_jsx_runtime331.jsx)("div", { className: "block-editor-media-placeholder__url-input-container", children: /* @__PURE__ */ (0, import_jsx_runtime331.jsx)(
import_components177.Button,
{
__next40pxDefaultSize: true,
className: "block-editor-media-placeholder__button",
onClick: onToggleFeaturedImage,
variant: "secondary",
children: (0, import_i18n168.__)("Use featured image")
}
) });
};
const renderMediaUploadChecked = () => {
const defaultButton = ({ open }) => {
return /* @__PURE__ */ (0, import_jsx_runtime331.jsx)(
import_components177.Button,
{
__next40pxDefaultSize: true,
variant: "secondary",
onClick: () => {
open();
},
children: (0, import_i18n168.__)("Media Library")
}
);
};
const libraryButton = mediaLibraryButton ?? defaultButton;
const uploadMediaLibraryButton = /* @__PURE__ */ (0, import_jsx_runtime331.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_runtime331.jsxs)(import_jsx_runtime331.Fragment, { children: [
renderDropZone(),
/* @__PURE__ */ (0, import_jsx_runtime331.jsx)(
import_components177.FormFileUpload,
{
onChange: onUpload,
accept: computedAccept,
multiple: !!multiple,
render: ({ openFileDialog }) => {
const content = /* @__PURE__ */ (0, import_jsx_runtime331.jsxs)(import_jsx_runtime331.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime331.jsx)(
import_components177.Button,
{
__next40pxDefaultSize: true,
variant: "primary",
className: clsx_default(
"block-editor-media-placeholder__button",
"block-editor-media-placeholder__upload-button"
),
onClick: openFileDialog,
children: (0, import_i18n168._x)("Upload", "verb")
}
),
uploadMediaLibraryButton,
renderUrlSelectionUI(),
renderFeaturedImageToggle(),
renderCancelLink()
] });
return renderPlaceholder(content);
}
}
)
] });
}
if (mediaUpload2) {
const content = /* @__PURE__ */ (0, import_jsx_runtime331.jsxs)(import_jsx_runtime331.Fragment, { children: [
renderDropZone(),
/* @__PURE__ */ (0, import_jsx_runtime331.jsx)(
import_components177.FormFileUpload,
{
render: ({ openFileDialog }) => /* @__PURE__ */ (0, import_jsx_runtime331.jsx)(
import_components177.Button,
{
__next40pxDefaultSize: true,
onClick: openFileDialog,
variant: "primary",
className: clsx_default(
"block-editor-media-placeholder__button",
"block-editor-media-placeholder__upload-button"
),
children: (0, import_i18n168._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_runtime331.jsx)(check_default2, { children: renderDropZone() });
}
return /* @__PURE__ */ (0, import_jsx_runtime331.jsx)(
check_default2,
{
fallback: renderPlaceholder(renderUrlSelectionUI()),
children: renderMediaUploadChecked()
}
);
}
var media_placeholder_default = (0, import_components177.withFilters)("editor.MediaPlaceholder")(MediaPlaceholder);
// packages/block-editor/build-module/components/panel-color-settings/index.mjs
var import_jsx_runtime332 = __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_runtime332.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_element190 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/editable-text/index.mjs
var import_element189 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/rich-text/index.mjs
var import_es65 = __toESM(require_es6(), 1);
var import_element188 = __toESM(require_element(), 1);
var import_data154 = __toESM(require_data(), 1);
var import_compose88 = __toESM(require_compose(), 1);
var import_rich_text15 = __toESM(require_rich_text(), 1);
var import_components181 = __toESM(require_components(), 1);
var import_blocks88 = __toESM(require_blocks(), 1);
var import_deprecated30 = __toESM(require_deprecated(), 1);
var import_i18n171 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/rich-text/format-toolbar-container.mjs
var import_i18n170 = __toESM(require_i18n(), 1);
var import_components179 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/rich-text/format-toolbar/index.mjs
var import_i18n169 = __toESM(require_i18n(), 1);
var import_components178 = __toESM(require_components(), 1);
var import_jsx_runtime333 = __toESM(require_jsx_runtime(), 1);
var POPOVER_PROPS8 = {
placement: "bottom-start"
};
var FormatToolbar = () => {
return /* @__PURE__ */ (0, import_jsx_runtime333.jsxs)(import_jsx_runtime333.Fragment, { children: [
["bold", "italic", "link", "unknown"].map((format6) => /* @__PURE__ */ (0, import_jsx_runtime333.jsx)(
import_components178.Slot,
{
name: `RichText.ToolbarControls.${format6}`
},
format6
)),
/* @__PURE__ */ (0, import_jsx_runtime333.jsx)(import_components178.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_runtime333.jsx)(import_components178.ToolbarItem, { children: (toggleProps) => /* @__PURE__ */ (0, import_jsx_runtime333.jsx)(
import_components178.DropdownMenu,
{
icon: chevron_down_default,
label: (0, import_i18n169.__)("More"),
toggleProps: {
...toggleProps,
className: clsx_default(
toggleProps.className,
{ "is-pressed": hasActive }
),
description: (0, import_i18n169.__)(
"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_runtime334 = __toESM(require_jsx_runtime(), 1);
function InlineToolbar({ popoverAnchor }) {
return /* @__PURE__ */ (0, import_jsx_runtime334.jsx)(
import_components179.Popover,
{
placement: "top",
focusOnMount: false,
anchor: popoverAnchor,
className: "block-editor-rich-text__inline-format-toolbar",
__unstableSlotName: "block-toolbar",
children: /* @__PURE__ */ (0, import_jsx_runtime334.jsx)(
NavigableToolbar,
{
className: "block-editor-rich-text__inline-format-toolbar-group",
"aria-label": (0, import_i18n170.__)("Format tools"),
children: /* @__PURE__ */ (0, import_jsx_runtime334.jsx)(import_components179.ToolbarGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime334.jsx)(format_toolbar_default, {}) })
}
)
}
);
}
var FormatToolbarContainer = ({ inline, editableContentElement }) => {
if (inline) {
return /* @__PURE__ */ (0, import_jsx_runtime334.jsx)(InlineToolbar, { popoverAnchor: editableContentElement });
}
return /* @__PURE__ */ (0, import_jsx_runtime334.jsx)(block_controls_default, { group: "inline", children: /* @__PURE__ */ (0, import_jsx_runtime334.jsx)(format_toolbar_default, {}) });
};
var format_toolbar_container_default = FormatToolbarContainer;
// packages/block-editor/build-module/components/rich-text/use-mark-persistent.mjs
var import_element178 = __toESM(require_element(), 1);
var import_data151 = __toESM(require_data(), 1);
function useMarkPersistent({ html, value }) {
const previousTextRef = (0, import_element178.useRef)();
const hasActiveFormats = !!value.activeFormats?.length;
const { __unstableMarkLastChangeAsPersistent: __unstableMarkLastChangeAsPersistent2 } = (0, import_data151.useDispatch)(store);
(0, import_element178.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/use-format-types.mjs
var import_element179 = __toESM(require_element(), 1);
var import_data152 = __toESM(require_data(), 1);
var import_rich_text5 = __toESM(require_rich_text(), 1);
function formatTypesSelector(select3) {
return select3(import_rich_text5.store).getFormatTypes();
}
var interactiveContentTags = /* @__PURE__ */ new Set([
"a",
"audio",
"button",
"details",
"embed",
"iframe",
"input",
"label",
"select",
"textarea",
"video"
]);
function prefixSelectKeys(selected, prefix2) {
if (typeof selected !== "object") {
return { [prefix2]: selected };
}
return Object.fromEntries(
Object.entries(selected).map(([key, value]) => [
`${prefix2}.${key}`,
value
])
);
}
function getPrefixedSelectKeys(selected, prefix2) {
if (selected[prefix2]) {
return selected[prefix2];
}
return Object.keys(selected).filter((key) => key.startsWith(prefix2 + ".")).reduce((accumulator, key) => {
accumulator[key.slice(prefix2.length + 1)] = selected[key];
return accumulator;
}, {});
}
function useFormatTypes({
clientId,
identifier,
allowedFormats,
withoutInteractiveFormatting,
disableNoneEssentialFormatting = false
}) {
const allFormatTypes = (0, import_data152.useSelect)(formatTypesSelector, []);
const formatTypes = (0, import_element179.useMemo)(() => {
return allFormatTypes.filter(
({
name,
interactive,
tagName,
[essentialFormatKey]: isEssential
}) => {
if (allowedFormats && !allowedFormats.includes(name)) {
return false;
}
if (disableNoneEssentialFormatting && !isEssential) {
return false;
}
if (withoutInteractiveFormatting && (interactive || interactiveContentTags.has(tagName))) {
return false;
}
return true;
}
);
}, [
allFormatTypes,
allowedFormats,
disableNoneEssentialFormatting,
withoutInteractiveFormatting
]);
const keyedSelected = (0, import_data152.useSelect)(
(select3) => formatTypes.reduce((accumulator, type) => {
if (!type.__experimentalGetPropsForEditableTreePreparation) {
return accumulator;
}
return {
...accumulator,
...prefixSelectKeys(
type.__experimentalGetPropsForEditableTreePreparation(
select3,
{
richTextIdentifier: identifier,
blockClientId: clientId
}
),
type.name
)
};
}, {}),
[formatTypes, clientId, identifier]
);
const dispatch = (0, import_data152.useDispatch)();
const prepareHandlers = [];
const valueHandlers = [];
const changeHandlers = [];
const dependencies = [];
for (const key in keyedSelected) {
dependencies.push(keyedSelected[key]);
}
formatTypes.forEach((type) => {
if (type.__experimentalCreatePrepareEditableTree) {
const handler = type.__experimentalCreatePrepareEditableTree(
getPrefixedSelectKeys(keyedSelected, type.name),
{
richTextIdentifier: identifier,
blockClientId: clientId
}
);
if (type.__experimentalCreateOnChangeEditableValue) {
valueHandlers.push(handler);
} else {
prepareHandlers.push(handler);
}
}
if (type.__experimentalCreateOnChangeEditableValue) {
let dispatchers = {};
if (type.__experimentalGetPropsForEditableTreeChangeHandler) {
dispatchers = type.__experimentalGetPropsForEditableTreeChangeHandler(
dispatch,
{
richTextIdentifier: identifier,
blockClientId: clientId
}
);
}
const selected = getPrefixedSelectKeys(keyedSelected, type.name);
changeHandlers.push(
type.__experimentalCreateOnChangeEditableValue(
{
...typeof selected === "object" ? selected : {},
...dispatchers
},
{
richTextIdentifier: identifier,
blockClientId: clientId
}
)
);
}
});
return {
formatTypes,
prepareHandlers,
valueHandlers,
changeHandlers,
dependencies
};
}
// packages/block-editor/build-module/components/rich-text/event-listeners/index.mjs
var import_element181 = __toESM(require_element(), 1);
var import_compose87 = __toESM(require_compose(), 1);
// packages/block-editor/build-module/components/rich-text/event-listeners/before-input-rules.mjs
var import_rich_text6 = __toESM(require_rich_text(), 1);
var import_hooks7 = __toESM(require_hooks(), 1);
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_text6.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_text6.insert)(value, startChar, start2, start2);
newValue = (0, import_rich_text6.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 } = element;
const { defaultView } = ownerDocument;
const newEvent = new defaultView.InputEvent("input", init);
window.queueMicrotask(() => {
event.target.dispatchEvent(newEvent);
});
event.preventDefault();
}
element.addEventListener("beforeinput", onInput);
return () => {
element.removeEventListener("beforeinput", onInput);
};
};
// packages/block-editor/build-module/components/rich-text/event-listeners/input-rules.mjs
var import_rich_text8 = __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_text7 = __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_text7.insert)(value, addText);
}
// packages/block-editor/build-module/components/rich-text/event-listeners/input-rules.mjs
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_text8.toHTMLString)({
value: (0, import_rich_text8.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();
}
}
element.addEventListener("input", onInput);
element.addEventListener("compositionend", onInput);
return () => {
element.removeEventListener("input", onInput);
element.removeEventListener("compositionend", onInput);
};
};
// packages/block-editor/build-module/components/rich-text/event-listeners/insert-replacement-text.mjs
var insert_replacement_text_default = (props) => (element) => {
function onInput(event) {
if (event.inputType !== "insertReplacementText") {
return;
}
const { registry } = props.current;
registry.dispatch(store).__unstableMarkLastChangeAsPersistent();
}
element.addEventListener("beforeinput", onInput);
return () => {
element.removeEventListener("beforeinput", onInput);
};
};
// packages/block-editor/build-module/components/rich-text/event-listeners/remove-browser-shortcuts.mjs
var import_keycodes19 = __toESM(require_keycodes(), 1);
var remove_browser_shortcuts_default = () => (node) => {
function onKeydown(event) {
if (import_keycodes19.isKeyboardEvent.primary(event, "z") || import_keycodes19.isKeyboardEvent.primary(event, "y") || import_keycodes19.isKeyboardEvent.primaryShift(event, "z")) {
event.preventDefault();
}
}
node.addEventListener("keydown", onKeydown);
return () => {
node.removeEventListener("keydown", onKeydown);
};
};
// packages/block-editor/build-module/components/rich-text/event-listeners/shortcuts.mjs
var shortcuts_default = (props) => (element) => {
const { keyboardShortcuts } = props.current;
function onKeyDown(event) {
for (const keyboardShortcut of keyboardShortcuts.current) {
keyboardShortcut(event);
}
}
element.addEventListener("keydown", onKeyDown);
return () => {
element.removeEventListener("keydown", onKeyDown);
};
};
// packages/block-editor/build-module/components/rich-text/event-listeners/input-events.mjs
var input_events_default = (props) => (element) => {
const { inputEvents } = props.current;
function onInput(event) {
for (const keyboardShortcut of inputEvents.current) {
keyboardShortcut(event);
}
}
element.addEventListener("input", onInput);
return () => {
element.removeEventListener("input", onInput);
};
};
// packages/block-editor/build-module/components/rich-text/event-listeners/undo-automatic-change.mjs
var import_keycodes20 = __toESM(require_keycodes(), 1);
var undo_automatic_change_default = (props) => (element) => {
function onKeyDown(event) {
const { keyCode } = event;
if (event.defaultPrevented) {
return;
}
if (keyCode !== import_keycodes20.BACKSPACE && keyCode !== import_keycodes20.ESCAPE) {
return;
}
const { registry } = props.current;
const { didAutomaticChange: didAutomaticChange2, getSettings: getSettings8 } = registry.select(store);
const { __experimentalUndo } = getSettings8();
if (!__experimentalUndo) {
return;
}
if (!didAutomaticChange2()) {
return;
}
event.preventDefault();
__experimentalUndo();
}
element.addEventListener("keydown", onKeyDown);
return () => {
element.removeEventListener("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_text9 = __toESM(require_rich_text(), 1);
var import_url10 = __toESM(require_url(), 1);
// packages/block-editor/build-module/components/rich-text/utils.mjs
var import_element180 = __toESM(require_element(), 1);
var import_blocks84 = __toESM(require_blocks(), 1);
var import_jsx_runtime335 = __toESM(require_jsx_runtime(), 1);
function addActiveFormats(value, activeFormats) {
if (activeFormats?.length) {
let index = value.formats.length;
while (index--) {
value.formats[index] = [
...activeFormats,
...value.formats[index] || []
];
}
}
}
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 paste_handler_default = (props) => (element) => {
function _onPaste(event) {
const {
disableFormats,
onChange,
value,
formatTypes,
tagName,
onReplace,
__unstableEmbedURLOnPaste,
preserveWhiteSpace,
pastePlainText
} = props.current;
if (!element.contains(event.target)) {
return;
}
if (event.defaultPrevented) {
return;
}
const { plainText, html } = getPasteEventData(event);
event.preventDefault();
window.console.log("Received HTML:\n\n", html);
window.console.log("Received plain text:\n\n", plainText);
if (disableFormats) {
onChange((0, import_rich_text9.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_text9.create)({ html: content2 });
addActiveFormats(valueToInsert, value.activeFormats);
onChange((0, import_rich_text9.insert)(value, valueToInsert));
}
}
if (isInternal) {
pasteInline(html);
return;
}
if (pastePlainText) {
onChange((0, import_rich_text9.insert)(value, (0, import_rich_text9.create)({ text: plainText })));
return;
}
let mode2 = "INLINE";
const trimmedPlainText = plainText.trim();
if (__unstableEmbedURLOnPaste && (0, import_rich_text9.isEmpty)(value) && (0, import_url10.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);
} else if (content.length > 0) {
if (onReplace && (0, import_rich_text9.isEmpty)(value)) {
onReplace(content, content.length - 1, -1);
}
}
}
const { defaultView } = element.ownerDocument;
defaultView.addEventListener("paste", _onPaste);
return () => {
defaultView.removeEventListener("paste", _onPaste);
};
};
// packages/block-editor/build-module/components/rich-text/event-listeners/delete.mjs
var import_keycodes21 = __toESM(require_keycodes(), 1);
var import_rich_text10 = __toESM(require_rich_text(), 1);
var delete_default = (props) => (element) => {
function onKeyDown(event) {
const { keyCode } = event;
if (event.defaultPrevented) {
return;
}
const { value, onMerge, onRemove } = props.current;
if (keyCode === import_keycodes21.DELETE || keyCode === import_keycodes21.BACKSPACE) {
const { start: start2, end, text } = value;
const isReverse = keyCode === import_keycodes21.BACKSPACE;
const hasActiveFormats = value.activeFormats && !!value.activeFormats.length;
if (!(0, import_rich_text10.isCollapsed)(value) || hasActiveFormats || isReverse && start2 !== 0 || !isReverse && end !== text.length) {
return;
}
if (onMerge) {
onMerge(!isReverse);
} else if (onRemove && (0, import_rich_text10.isEmpty)(value) && isReverse) {
onRemove(!isReverse);
}
event.preventDefault();
}
}
element.addEventListener("keydown", onKeyDown);
return () => {
element.removeEventListener("keydown", onKeyDown);
};
};
// packages/block-editor/build-module/components/rich-text/event-listeners/enter.mjs
var import_keycodes22 = __toESM(require_keycodes(), 1);
var import_rich_text11 = __toESM(require_rich_text(), 1);
var enter_default = (props) => (element) => {
function onKeyDownDeprecated(event) {
if (event.keyCode !== import_keycodes22.ENTER) {
return;
}
const { onReplace, onSplit } = props.current;
if (onReplace && onSplit) {
event.__deprecatedOnSplit = true;
}
}
function onKeyDown(event) {
if (event.defaultPrevented) {
return;
}
if (event.target !== element) {
return;
}
if (event.keyCode !== import_keycodes22.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_text11.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_text11.remove)(_value));
onSplitAtDoubleLineEnd();
});
} else if (!disableLineBreaks) {
onChange((0, import_rich_text11.insert)(value, "\n"));
}
}
const { defaultView } = element.ownerDocument;
defaultView.addEventListener("keydown", onKeyDown);
element.addEventListener("keydown", onKeyDownDeprecated);
return () => {
defaultView.removeEventListener("keydown", onKeyDown);
element.removeEventListener("keydown", onKeyDownDeprecated);
};
};
// 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_element181.useRef)(props);
(0, import_element181.useInsertionEffect)(() => {
propsRef.current = props;
});
const refEffects = (0, import_element181.useMemo)(
() => allEventListeners.map((refEffect) => refEffect(propsRef)),
[propsRef]
);
return (0, import_compose87.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_text12 = __toESM(require_rich_text(), 1);
var import_element182 = __toESM(require_element(), 1);
var import_jsx_runtime336 = __toESM(require_jsx_runtime(), 1);
var import_react5 = __toESM(require_react(), 1);
var DEFAULT_BLOCK_CONTEXT2 = {};
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_element182.useContext)(block_context_default);
const context = (0, import_element182.useMemo)(() => {
return usesContext ? Object.fromEntries(
Object.entries(blockContext).filter(
([key]) => usesContext.includes(key)
)
) : DEFAULT_BLOCK_CONTEXT2;
}, [usesContext, blockContext]);
if (!EditFunction) {
return null;
}
const activeFormat = (0, import_rich_text12.getActiveFormat)(value, name);
const isActive = activeFormat !== void 0;
const activeObject = (0, import_rich_text12.getActiveObject)(value);
const isObjectActive = activeObject !== void 0 && activeObject.type === name;
return /* @__PURE__ */ (0, import_jsx_runtime336.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_react5.createElement)(Edit3, { settings: settings2, ...props, key: settings2.name }));
}
// packages/block-editor/build-module/components/rich-text/content.mjs
var import_element183 = __toESM(require_element(), 1);
var import_blocks86 = __toESM(require_blocks(), 1);
var import_deprecated27 = __toESM(require_deprecated(), 1);
var import_jsx_runtime337 = __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_deprecated27.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 Content({
value,
tagName: Tag,
multiline,
format: format6,
...props
}) {
value = /* @__PURE__ */ (0, import_jsx_runtime337.jsx)(import_element183.RawHTML, { children: valueToHTMLString(value, multiline) });
return Tag ? /* @__PURE__ */ (0, import_jsx_runtime337.jsx)(Tag, { ...props, children: value }) : value;
}
// packages/block-editor/build-module/components/rich-text/with-deprecations.mjs
var import_element185 = __toESM(require_element(), 1);
var import_blocks87 = __toESM(require_blocks(), 1);
var import_rich_text14 = __toESM(require_rich_text(), 1);
var import_deprecated29 = __toESM(require_deprecated(), 1);
// packages/block-editor/build-module/components/rich-text/multiline.mjs
var import_element184 = __toESM(require_element(), 1);
var import_deprecated28 = __toESM(require_deprecated(), 1);
var import_data153 = __toESM(require_data(), 1);
var import_keycodes23 = __toESM(require_keycodes(), 1);
var import_rich_text13 = __toESM(require_rich_text(), 1);
var import_jsx_runtime338 = __toESM(require_jsx_runtime(), 1);
function RichTextMultiline({
children,
identifier,
tagName: TagName = "div",
value = "",
onChange,
multiline,
...props
}, forwardedRef) {
(0, import_deprecated28.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_runtime338.jsx)(TagName, { ref: forwardedRef, children: values.map((_value, index) => {
return /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
RichTextWrapper,
{
identifier: `${identifier}-${index}`,
tagName: multilineTagName,
value: _value,
onChange: (newValue) => {
const newValues = values.slice();
newValues[index] = newValue;
_onChange(newValues);
},
isSelected: void 0,
onKeyDown: (event) => {
if (event.keyCode !== import_keycodes23.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_text13.create)({ html: _value });
richTextValue.start = start2;
richTextValue.end = end;
const array = (0, import_rich_text13.split)(richTextValue).map(
(v2) => (0, import_rich_text13.toHTMLString)({ value: v2 })
);
const newValues = values.slice();
newValues.splice(index, 1, ...array);
_onChange(newValues);
selectionChange2(
clientId,
`${identifier}-${index + 1}`,
0,
0
);
},
onMerge: (forward) => {
const newValues = values.slice();
let offset = 0;
if (forward) {
if (!newValues[index + 1]) {
return;
}
newValues.splice(
index,
2,
newValues[index] + newValues[index + 1]
);
offset = newValues[index].length - 1;
} else {
if (!newValues[index - 1]) {
return;
}
newValues.splice(
index - 1,
2,
newValues[index - 1] + newValues[index]
);
offset = newValues[index - 1].length - 1;
}
_onChange(newValues);
selectionChange2(
clientId,
`${identifier}-${index - (forward ? 0 : 1)}`,
offset,
offset
);
},
...props
},
index
);
}) });
}
var multiline_default = (0, import_element184.forwardRef)(RichTextMultiline);
// packages/block-editor/build-module/components/rich-text/with-deprecations.mjs
var import_jsx_runtime339 = __toESM(require_jsx_runtime(), 1);
function withDeprecations(Component7) {
return (0, import_element185.forwardRef)((props, ref) => {
let value = props.value;
let onChange = props.onChange;
if (Array.isArray(value)) {
(0, import_deprecated29.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_text14.__unstableCreateElement)(document, newValue).childNodes
)
);
}
const NewComponent = props.multiline ? multiline_default : Component7;
return /* @__PURE__ */ (0, import_jsx_runtime339.jsx)(
NewComponent,
{
...props,
value,
onChange,
ref
}
);
});
}
// packages/block-editor/build-module/components/rich-text/shortcut.mjs
var import_keycodes24 = __toESM(require_keycodes(), 1);
var import_element186 = __toESM(require_element(), 1);
function RichTextShortcut({ character, type, onUse }) {
const keyboardShortcuts = (0, import_element186.useContext)(keyboardShortcutContext);
const onUseRef = (0, import_element186.useRef)();
onUseRef.current = onUse;
(0, import_element186.useEffect)(() => {
function callback(event) {
if (import_keycodes24.isKeyboardEvent[type](event, character)) {
onUseRef.current();
event.preventDefault();
}
}
keyboardShortcuts.current.add(callback);
return () => {
keyboardShortcuts.current.delete(callback);
};
}, [character, type]);
return null;
}
// packages/block-editor/build-module/components/rich-text/toolbar-button.mjs
var import_components180 = __toESM(require_components(), 1);
var import_keycodes25 = __toESM(require_keycodes(), 1);
var import_jsx_runtime340 = __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_keycodes25.displayShortcut[shortcutType](shortcutCharacter);
}
return /* @__PURE__ */ (0, import_jsx_runtime340.jsx)(import_components180.Fill, { name: fillName, children: /* @__PURE__ */ (0, import_jsx_runtime340.jsx)(import_components180.ToolbarButton, { ...props, shortcut }) });
}
// packages/block-editor/build-module/components/rich-text/input-event.mjs
var import_element187 = __toESM(require_element(), 1);
function __unstableRichTextInputEvent({ inputType, onInput }) {
const callbacks = (0, import_element187.useContext)(inputEventContext);
const onInputRef = (0, import_element187.useRef)();
onInputRef.current = onInput;
(0, import_element187.useEffect)(() => {
function callback(event) {
if (event.inputType === inputType) {
onInputRef.current();
event.preventDefault();
}
}
callbacks.current.add(callback);
return () => {
callbacks.current.delete(callback);
};
}, [inputType]);
return null;
}
// packages/block-editor/build-module/components/rich-text/index.mjs
var import_jsx_runtime341 = __toESM(require_jsx_runtime(), 1);
var keyboardShortcutContext = (0, import_element188.createContext)();
keyboardShortcutContext.displayName = "keyboardShortcutContext";
var inputEventContext = (0, import_element188.createContext)();
inputEventContext.displayName = "inputEventContext";
var instanceIdKey = /* @__PURE__ */ Symbol("instanceId");
function removeNativeProps(props) {
const {
__unstableMobileNoFocusOnMount,
deleteEnter,
placeholderTextColor,
textAlign,
selectionColor,
tagsToEliminate,
disableEditingMenu,
fontSize,
fontFamily,
fontWeight,
fontStyle,
minWidth,
maxWidth,
disableSuggestions,
disableAutocorrection,
...restProps
} = props;
return restProps;
}
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) {
props = removeNativeProps(props);
if (onSplit) {
(0, import_deprecated30.default)("wp.blockEditor.RichText onSplit prop", {
since: "6.4",
alternative: 'block.json support key: "splitting"'
});
}
const instanceId = (0, import_compose88.useInstanceId)(RichTextWrapper);
const anchorRef = (0, import_element188.useRef)();
const [anchorElement, setAnchorElement] = (0, import_element188.useState)(null);
const context = useBlockEditContext();
const { clientId, isSelected: isBlockSelected2, name: blockName } = context;
const blockBindings = context[blockBindingsKey];
const blockContext = (0, import_element188.useContext)(block_context_default);
const registry = (0, import_data154.useRegistry)();
const selector3 = (select3) => {
if (!isBlockSelected2) {
return { isSelected: false };
}
const { getSelectionStart: getSelectionStart22, getSelectionEnd: getSelectionEnd22, getBlockEditingMode: getBlockEditingMode2 } = 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,
isContentOnly: getBlockEditingMode2(clientId) === "contentOnly"
};
};
const { selectionStart, selectionEnd, isSelected, isContentOnly } = (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_i18n171.sprintf)(
/* translators: %s: connected field label or source label */
(0, import_i18n171.__)("Add %s"),
bindingKey
);
const _bindingsLabel = _disableBoundBlock ? relatedBinding?.args?.key || blockBindingsSource?.label : (0, import_i18n171.sprintf)(
/* translators: %s: source label or key */
(0, import_i18n171.__)("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 { 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_element188.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 {
formatTypes,
prepareHandlers,
valueHandlers,
changeHandlers,
dependencies
} = useFormatTypes({
clientId,
identifier,
allowedFormats: adjustedAllowedFormats,
withoutInteractiveFormatting,
disableNoneEssentialFormatting: isContentOnly
});
function addEditorOnlyFormats(value2) {
return valueHandlers.reduce(
(accumulator, fn) => fn(accumulator, value2.text),
value2.formats
);
}
function removeEditorOnlyFormats(value2) {
formatTypes.forEach((formatType) => {
if (formatType.__experimentalCreatePrepareEditableTree) {
value2 = (0, import_rich_text15.removeFormat)(
value2,
formatType.name,
0,
value2.text.length
);
}
});
return value2.formats;
}
function addInvisibleFormats(value2) {
return prepareHandlers.reduce(
(accumulator, fn) => fn(accumulator, value2.text),
value2.formats
);
}
const {
value,
getValue,
onChange,
ref: richTextRef
} = (0, import_rich_text15.__unstableUseRichText)({
value: adjustedValue,
onChange(html, { __unstableFormats, __unstableText }) {
adjustedOnChange(html);
Object.values(changeHandlers).forEach((changeHandler) => {
changeHandler(__unstableFormats, __unstableText);
});
},
selectionStart,
selectionEnd,
onSelectionChange,
placeholder: bindingsPlaceholder || placeholder,
__unstableIsSelected: isSelected,
__unstableDisableFormats: disableFormats,
preserveWhiteSpace,
__unstableDependencies: [...dependencies, tagName],
__unstableAfterParse: addEditorOnlyFormats,
__unstableBeforeSerialize: removeEditorOnlyFormats,
__unstableAddInvisibleFormats: addInvisibleFormats
});
const autocompleteProps = useBlockEditorAutocompleteProps({
onReplace,
completers: autocompleters,
record: value,
onChange
});
useMarkPersistent({ html: adjustedValue, value });
const keyboardShortcuts = (0, import_element188.useRef)(/* @__PURE__ */ new Set());
const inputEvents = (0, import_element188.useRef)(/* @__PURE__ */ new Set());
function onFocus() {
anchorRef.current?.focus();
}
const TagName = tagName;
return /* @__PURE__ */ (0, import_jsx_runtime341.jsxs)(import_jsx_runtime341.Fragment, { children: [
isSelected && /* @__PURE__ */ (0, import_jsx_runtime341.jsx)(keyboardShortcutContext.Provider, { value: keyboardShortcuts, children: /* @__PURE__ */ (0, import_jsx_runtime341.jsx)(inputEventContext.Provider, { value: inputEvents, children: /* @__PURE__ */ (0, import_jsx_runtime341.jsxs)(import_components181.Popover.__unstableSlotNameProvider, { value: "__unstable-block-tools-after", children: [
children && children({ value, onChange, onFocus }),
/* @__PURE__ */ (0, import_jsx_runtime341.jsx)(
FormatEdit,
{
value,
onChange,
onFocus,
formatTypes,
forwardedRef: anchorRef
}
)
] }) }) }),
isSelected && hasFormats && /* @__PURE__ */ (0, import_jsx_runtime341.jsx)(
format_toolbar_container_default,
{
inline: inlineToolbar,
editableContentElement: anchorElement
}
),
/* @__PURE__ */ (0, import_jsx_runtime341.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_compose88.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,
removeEditorOnlyFormats,
disableLineBreaks,
onSplitAtEnd,
onSplitAtDoubleLineEnd,
keyboardShortcuts,
inputEvents
}),
anchorRef,
setAnchorElement
]),
contentEditable: !shouldDisableEditing,
suppressContentEditableWarning: true,
className: clsx_default(
"block-editor-rich-text__editable",
props.className,
"rich-text"
),
tabIndex: props.tabIndex === 0 && !shouldDisableEditing ? null : props.tabIndex,
"data-wp-block-attribute-key": identifier
}
)
] });
}
var PrivateRichText = withDeprecations(
(0, import_element188.forwardRef)(RichTextWrapper)
);
PrivateRichText.Content = Content;
PrivateRichText.isEmpty = (value) => {
return !value || value.length === 0;
};
var PublicForwardedRichTextContainer = (0, import_element188.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
} = removeNativeProps(props);
return /* @__PURE__ */ (0, import_jsx_runtime341.jsx)(
Tag,
{
ref,
...contentProps,
dangerouslySetInnerHTML: {
__html: valueToHTMLString(value, multiline)
}
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime341.jsx)(PrivateRichText, { ref, ...props, readOnly: false });
});
PublicForwardedRichTextContainer.Content = Content;
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_runtime342 = __toESM(require_jsx_runtime(), 1);
var EditableText = (0, import_element189.forwardRef)((props, ref) => {
return /* @__PURE__ */ (0, import_jsx_runtime342.jsx)(rich_text_default, { ref, ...props, __unstableDisableFormats: true });
});
EditableText.Content = ({ value = "", tagName: Tag = "div", ...props }) => {
return /* @__PURE__ */ (0, import_jsx_runtime342.jsx)(Tag, { ...props, children: value });
};
var editable_text_default = EditableText;
// packages/block-editor/build-module/components/plain-text/index.mjs
var import_jsx_runtime343 = __toESM(require_jsx_runtime(), 1);
var PlainText = (0, import_element190.forwardRef)(({ __experimentalVersion, ...props }, ref) => {
if (__experimentalVersion === 2) {
return /* @__PURE__ */ (0, import_jsx_runtime343.jsx)(editable_text_default, { ref, ...props });
}
const { className, onChange, ...remainingProps } = props;
return /* @__PURE__ */ (0, import_jsx_runtime343.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_i18n173 = __toESM(require_i18n(), 1);
var import_element191 = __toESM(require_element(), 1);
var import_components183 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/responsive-block-control/label.mjs
var import_compose89 = __toESM(require_compose(), 1);
var import_components182 = __toESM(require_components(), 1);
var import_i18n172 = __toESM(require_i18n(), 1);
var import_jsx_runtime344 = __toESM(require_jsx_runtime(), 1);
function ResponsiveBlockControlLabel({
property,
viewport,
desc
}) {
const instanceId = (0, import_compose89.useInstanceId)(ResponsiveBlockControlLabel);
const accessibleLabel = desc || (0, import_i18n172.sprintf)(
/* translators: 1: property name. 2: viewport name. */
(0, import_i18n172._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_runtime344.jsxs)(import_jsx_runtime344.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime344.jsx)("span", { "aria-describedby": `rbc-desc-${instanceId}`, children: viewport.label }),
/* @__PURE__ */ (0, import_jsx_runtime344.jsx)(import_components182.VisuallyHidden, { as: "span", id: `rbc-desc-${instanceId}`, children: accessibleLabel })
] });
}
// packages/block-editor/build-module/components/responsive-block-control/index.mjs
var import_jsx_runtime345 = __toESM(require_jsx_runtime(), 1);
function ResponsiveBlockControl(props) {
const {
title,
property,
toggleLabel,
onIsResponsiveChange,
renderDefaultControl,
renderResponsiveControls,
isResponsive = false,
defaultLabel = {
id: "all",
label: (0, import_i18n173._x)("All", "screen sizes")
},
viewports = [
{
id: "small",
label: (0, import_i18n173.__)("Small screens")
},
{
id: "medium",
label: (0, import_i18n173.__)("Medium screens")
},
{
id: "large",
label: (0, import_i18n173.__)("Large screens")
}
]
} = props;
if (!title || !property || !renderDefaultControl) {
return null;
}
const toggleControlLabel = toggleLabel || (0, import_i18n173.sprintf)(
/* translators: %s: Property value for the control (eg: margin, padding, etc.). */
(0, import_i18n173.__)("Use the same %s on all screen sizes."),
property
);
const toggleHelpText = (0, import_i18n173.__)(
"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_runtime345.jsx)(
ResponsiveBlockControlLabel,
{
property,
viewport: defaultLabel
}
),
defaultLabel
);
const defaultResponsiveControls = () => {
return viewports.map((viewport) => /* @__PURE__ */ (0, import_jsx_runtime345.jsx)(import_element191.Fragment, { children: renderDefaultControl(
/* @__PURE__ */ (0, import_jsx_runtime345.jsx)(
ResponsiveBlockControlLabel,
{
property,
viewport
}
),
viewport
) }, viewport.id));
};
return /* @__PURE__ */ (0, import_jsx_runtime345.jsxs)("fieldset", { className: "block-editor-responsive-block-control", children: [
/* @__PURE__ */ (0, import_jsx_runtime345.jsx)("legend", { className: "block-editor-responsive-block-control__title", children: title }),
/* @__PURE__ */ (0, import_jsx_runtime345.jsxs)("div", { className: "block-editor-responsive-block-control__inner", children: [
/* @__PURE__ */ (0, import_jsx_runtime345.jsx)(
import_components183.ToggleControl,
{
className: "block-editor-responsive-block-control__toggle",
label: toggleControlLabel,
checked: !isResponsive,
onChange: onIsResponsiveChange,
help: toggleHelpText
}
),
/* @__PURE__ */ (0, import_jsx_runtime345.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_components184 = __toESM(require_components(), 1);
var import_jsx_runtime346 = __toESM(require_jsx_runtime(), 1);
function UnitControl6({ units: unitsProp, ...props }) {
const [availableUnits] = useSettings("spacing.units");
const units2 = (0, import_components184.__experimentalUseCustomUnits)({
availableUnits: availableUnits || ["%", "px", "em", "rem", "vw"],
units: unitsProp
});
return /* @__PURE__ */ (0, import_jsx_runtime346.jsx)(import_components184.__experimentalUnitControl, { units: units2, ...props });
}
// packages/block-editor/build-module/components/url-input/button.mjs
var import_i18n174 = __toESM(require_i18n(), 1);
var import_element192 = __toESM(require_element(), 1);
var import_components185 = __toESM(require_components(), 1);
var import_jsx_runtime347 = __toESM(require_jsx_runtime(), 1);
function URLInputButton({ url, onChange }) {
const [expanded2, toggleExpanded] = (0, import_element192.useReducer)(
(isExpanded) => !isExpanded,
false
);
const submitLink = (event) => {
event.preventDefault();
toggleExpanded();
};
return /* @__PURE__ */ (0, import_jsx_runtime347.jsxs)("div", { className: "block-editor-url-input__button", children: [
/* @__PURE__ */ (0, import_jsx_runtime347.jsx)(
import_components185.Button,
{
size: "compact",
icon: link_default,
label: url ? (0, import_i18n174.__)("Edit link") : (0, import_i18n174.__)("Insert link"),
onClick: toggleExpanded,
className: "components-toolbar__control",
isPressed: !!url
}
),
expanded2 && /* @__PURE__ */ (0, import_jsx_runtime347.jsx)(
"form",
{
className: "block-editor-url-input__button-modal",
onSubmit: submitLink,
children: /* @__PURE__ */ (0, import_jsx_runtime347.jsxs)("div", { className: "block-editor-url-input__button-modal-line", children: [
/* @__PURE__ */ (0, import_jsx_runtime347.jsx)(
import_components185.Button,
{
__next40pxDefaultSize: true,
className: "block-editor-url-input__back",
icon: arrow_left_default,
label: (0, import_i18n174.__)("Close"),
onClick: toggleExpanded
}
),
/* @__PURE__ */ (0, import_jsx_runtime347.jsx)(
url_input_default,
{
value: url || "",
onChange,
suffix: /* @__PURE__ */ (0, import_jsx_runtime347.jsx)(import_components185.__experimentalInputControlSuffixWrapper, { variant: "control", children: /* @__PURE__ */ (0, import_jsx_runtime347.jsx)(
import_components185.Button,
{
size: "small",
icon: keyboard_return_default,
label: (0, import_i18n174.__)("Submit"),
type: "submit"
}
) })
}
)
] })
}
)
] });
}
var button_default = URLInputButton;
// packages/block-editor/build-module/components/url-popover/image-url-input-ui.mjs
var import_i18n175 = __toESM(require_i18n(), 1);
var import_element193 = __toESM(require_element(), 1);
var import_dom37 = __toESM(require_dom(), 1);
var import_components186 = __toESM(require_components(), 1);
var import_url11 = __toESM(require_url(), 1);
var import_jsx_runtime348 = __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 = ["noreferrer", "noopener"];
var ImageURLInputUI = ({
linkDestination,
onChangeUrl,
url,
mediaType = "image",
mediaUrl,
mediaLink,
linkTarget,
linkClass,
rel,
showLightboxSetting,
lightboxEnabled,
onSetLightbox,
resetLightbox
}) => {
const [isOpen, setIsOpen] = (0, import_element193.useState)(false);
const [popoverAnchor, setPopoverAnchor] = (0, import_element193.useState)(null);
const openLinkUI = () => {
setIsOpen(true);
};
const [isEditingLink, setIsEditingLink] = (0, import_element193.useState)(false);
const [urlInput, setUrlInput] = (0, import_element193.useState)(null);
const autocompleteRef = (0, import_element193.useRef)(null);
const wrapperRef = (0, import_element193.useRef)();
(0, import_element193.useEffect)(() => {
if (!wrapperRef.current) {
return;
}
const nextFocusTarget = import_dom37.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_url11.prependHTTP)(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_i18n175.__)("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_i18n175.__)("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_runtime348.jsxs)(import_components186.__experimentalVStack, { spacing: "3", children: [
/* @__PURE__ */ (0, import_jsx_runtime348.jsx)(
import_components186.ToggleControl,
{
label: (0, import_i18n175.__)("Open in new tab"),
onChange: onSetNewTab,
checked: linkTarget === "_blank"
}
),
/* @__PURE__ */ (0, import_jsx_runtime348.jsx)(
import_components186.TextControl,
{
__next40pxDefaultSize: true,
label: (0, import_i18n175.__)("Link relation"),
value: rel ?? "",
onChange: onSetLinkRel,
help: (0, import_element193.createInterpolateElement)(
(0, import_i18n175.__)(
"The <a>Link Relation</a> attribute defines the relationship between a linked resource and the current document."
),
{
a: /* @__PURE__ */ (0, import_jsx_runtime348.jsx)(import_components186.ExternalLink, { href: "https://developer.mozilla.org/docs/Web/HTML/Attributes/rel" })
}
)
}
),
/* @__PURE__ */ (0, import_jsx_runtime348.jsx)(
import_components186.TextControl,
{
__next40pxDefaultSize: true,
label: (0, import_i18n175.__)("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_runtime348.jsxs)("div", { className: "block-editor-url-popover__expand-on-click", children: [
/* @__PURE__ */ (0, import_jsx_runtime348.jsx)(icon_default, { icon: fullscreen_default }),
/* @__PURE__ */ (0, import_jsx_runtime348.jsxs)("div", { className: "text", children: [
/* @__PURE__ */ (0, import_jsx_runtime348.jsx)("p", { children: (0, import_i18n175.__)("Enlarge on click") }),
/* @__PURE__ */ (0, import_jsx_runtime348.jsx)("p", { className: "description", children: (0, import_i18n175.__)("Scales the image with a lightbox effect") })
] }),
/* @__PURE__ */ (0, import_jsx_runtime348.jsx)(
import_components186.Button,
{
icon: link_off_default,
label: (0, import_i18n175.__)("Disable enlarge on click"),
onClick: () => {
onSetLightbox?.(false);
},
size: "compact"
}
)
] });
} else if (!url || isEditingLink) {
return /* @__PURE__ */ (0, import_jsx_runtime348.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_runtime348.jsxs)(import_jsx_runtime348.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime348.jsx)(
url_popover_default.LinkViewer,
{
className: "block-editor-format-toolbar__link-container-content",
url,
onEditLinkClick: startEditLink,
urlLabel
}
),
/* @__PURE__ */ (0, import_jsx_runtime348.jsx)(
import_components186.Button,
{
icon: link_off_default,
label: (0, import_i18n175.__)("Remove link"),
onClick: () => {
onLinkRemove();
resetLightbox?.();
},
size: "compact"
}
)
] });
}
};
return /* @__PURE__ */ (0, import_jsx_runtime348.jsxs)(import_jsx_runtime348.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime348.jsx)(
import_components186.ToolbarButton,
{
icon: link_default,
className: "components-toolbar__control",
label: (0, import_i18n175.__)("Link"),
"aria-expanded": isOpen,
onClick: openLinkUI,
ref: setPopoverAnchor,
isActive: !!url || lightboxEnabled && showLightboxSetting
}
),
isOpen && /* @__PURE__ */ (0, import_jsx_runtime348.jsx)(
url_popover_default,
{
ref: wrapperRef,
anchor: popoverAnchor,
onFocusOutside: onFocusOutside(),
onClose: closeLinkUI,
renderSettings: hideLightboxPanel ? () => advancedOptions : null,
additionalControls: showLinkEditor && /* @__PURE__ */ (0, import_jsx_runtime348.jsxs)(import_components186.NavigableMenu, { children: [
getLinkDestinations().map((link) => /* @__PURE__ */ (0, import_jsx_runtime348.jsx)(
import_components186.MenuItem,
{
icon: link.icon,
iconPosition: "left",
onClick: () => {
setUrlInput(null);
onSetHref(link.url);
stopEditLink();
},
children: link.title
},
link.linkDestination
)),
showLightboxSetting && /* @__PURE__ */ (0, import_jsx_runtime348.jsx)(
import_components186.MenuItem,
{
className: "block-editor-url-popover__expand-on-click",
icon: fullscreen_default,
info: (0, import_i18n175.__)(
"Scale the image with a lightbox effect."
),
iconPosition: "left",
onClick: () => {
setUrlInput(null);
onChangeUrl({
linkDestination: LINK_DESTINATION_NONE,
href: ""
});
onSetLightbox?.(true);
stopEditLink();
},
children: (0, import_i18n175.__)("Enlarge on click")
},
"expand-on-click"
)
] }),
offset: 13,
children: PopoverChildren()
}
)
] });
};
// packages/block-editor/build-module/components/spacing-sizes-control/index.mjs
var import_components189 = __toESM(require_components(), 1);
var import_element196 = __toESM(require_element(), 1);
var import_i18n179 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/spacing-sizes-control/hooks/use-spacing-sizes.mjs
var import_element194 = __toESM(require_element(), 1);
var import_i18n176 = __toESM(require_i18n(), 1);
var EMPTY_ARRAY11 = [];
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_ARRAY11;
const themeSizes = themeSpacingSizes ?? EMPTY_ARRAY11;
const defaultSizes = defaultSpacingSizes && defaultSpacingSizesEnabled !== false ? defaultSpacingSizes : EMPTY_ARRAY11;
return (0, import_element194.useMemo)(() => {
const sizes = [
{ name: (0, import_i18n176.__)("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_i18n176.__)("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_element195 = __toESM(require_element(), 1);
var import_data155 = __toESM(require_data(), 1);
var import_i18n177 = __toESM(require_i18n(), 1);
var import_components187 = __toESM(require_components(), 1);
var import_jsx_runtime349 = __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_components187.__experimentalUseCustomUnits)({
availableUnits: availableUnits || ["px", "em", "rem"]
});
const presets = (0, import_element195.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_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"),
sideLabel,
typeLabel
).trim();
const selectedUnit = units2[0]?.value || "px";
return /* @__PURE__ */ (0, import_jsx_runtime349.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_runtime350 = __toESM(require_jsx_runtime(), 1);
var groupedSides = ["vertical", "horizontal"];
function AxialInputControls({
minimumCustomValue,
onChange,
onMouseOut,
onMouseOver,
sides,
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 = sides?.length ? groupedSides.filter((side) => hasAxisSupport(sides, side)) : groupedSides;
return /* @__PURE__ */ (0, import_jsx_runtime350.jsx)(import_jsx_runtime350.Fragment, { children: filteredSides.map((side) => {
const axisValue = side === "vertical" ? values.top : values.left;
return /* @__PURE__ */ (0, import_jsx_runtime350.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_runtime351 = __toESM(require_jsx_runtime(), 1);
function SeparatedInputControls({
minimumCustomValue,
onChange,
onMouseOut,
onMouseOver,
sides,
spacingSizes,
type,
values
}) {
const filteredSides = sides?.length ? ALL_SIDES.filter((side) => sides.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_runtime351.jsx)(import_jsx_runtime351.Fragment, { children: filteredSides.map((side) => {
return /* @__PURE__ */ (0, import_jsx_runtime351.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_runtime352 = __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_runtime352.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_components188 = __toESM(require_components(), 1);
var import_i18n178 = __toESM(require_i18n(), 1);
var import_jsx_runtime353 = __toESM(require_jsx_runtime(), 1);
function LinkedButton2({ isLinked, ...props }) {
const label = isLinked ? (0, import_i18n178.__)("Unlink sides") : (0, import_i18n178.__)("Link sides");
return /* @__PURE__ */ (0, import_jsx_runtime353.jsx)(
import_components188.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_runtime354 = __toESM(require_jsx_runtime(), 1);
function SpacingSizesControl({
inputProps,
label: labelProp,
minimumCustomValue = 0,
onChange,
onMouseOut,
onMouseOver,
showSideInLabel = true,
sides = ALL_SIDES,
useSelect: useSelect173,
values
}) {
const spacingSizes = useSpacingSizes();
const inputValues = values || DEFAULT_VALUES;
const hasOneSide = sides?.length === 1;
const hasOnlyAxialSides = sides?.includes("horizontal") && sides?.includes("vertical") && sides?.length === 2;
const [view, setView] = (0, import_element196.useState)(getInitialView(inputValues, sides));
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,
spacingSizes,
type: labelProp,
useSelect: useSelect173,
values: inputValues
};
const renderControls = () => {
if (view === VIEWS.axial) {
return /* @__PURE__ */ (0, import_jsx_runtime354.jsx)(AxialInputControls, { ...inputControlProps });
}
if (view === VIEWS.custom) {
return /* @__PURE__ */ (0, import_jsx_runtime354.jsx)(SeparatedInputControls, { ...inputControlProps });
}
return /* @__PURE__ */ (0, import_jsx_runtime354.jsx)(
SingleInputControl,
{
side: view,
...inputControlProps,
showSideInLabel
}
);
};
const sideLabel = ALL_SIDES.includes(view) && showSideInLabel ? LABELS[view] : "";
const label = (0, import_i18n179.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_i18n179._x)("%1$s %2$s", "spacing"),
labelProp,
sideLabel
).trim();
return /* @__PURE__ */ (0, import_jsx_runtime354.jsxs)("fieldset", { className: "spacing-sizes-control", children: [
/* @__PURE__ */ (0, import_jsx_runtime354.jsxs)(import_components189.__experimentalHStack, { className: "spacing-sizes-control__header", children: [
/* @__PURE__ */ (0, import_jsx_runtime354.jsx)(
import_components189.BaseControl.VisualLabel,
{
as: "legend",
className: "spacing-sizes-control__label",
children: label
}
),
!hasOneSide && !hasOnlyAxialSides && /* @__PURE__ */ (0, import_jsx_runtime354.jsx)(
LinkedButton2,
{
label: labelProp,
onClick: toggleLinked,
isLinked: view === VIEWS.axial
}
)
] }),
/* @__PURE__ */ (0, import_jsx_runtime354.jsx)(import_components189.__experimentalVStack, { spacing: 0.5, children: renderControls() })
] });
}
// packages/block-editor/build-module/components/preview-options/index.mjs
var import_deprecated31 = __toESM(require_deprecated(), 1);
function PreviewOptions() {
(0, import_deprecated31.default)("wp.blockEditor.PreviewOptions", {
version: "6.5"
});
return null;
}
// packages/block-editor/build-module/components/use-resize-canvas/index.mjs
var import_element197 = __toESM(require_element(), 1);
function useResizeCanvas(deviceType) {
const [actualWidth, updateActualWidth] = (0, import_element197.useState)(window.innerWidth);
(0, import_element197.useEffect)(() => {
if (deviceType === "Desktop") {
return;
}
const resizeListener = () => updateActualWidth(window.innerWidth);
window.addEventListener("resize", resizeListener);
return () => {
window.removeEventListener("resize", resizeListener);
};
}, [deviceType]);
const getCanvasWidth = (device) => {
let deviceWidth;
switch (device) {
case "Tablet":
deviceWidth = 782 - 1;
break;
case "Mobile":
deviceWidth = 480 - 1;
break;
default:
return null;
}
return deviceWidth < actualWidth ? deviceWidth : actualWidth;
};
const contentInlineStyles = (device) => {
const height = device === "Mobile" ? "768px" : "1024px";
const marginVertical = "40px";
const marginHorizontal = "auto";
switch (device) {
case "Tablet":
case "Mobile":
return {
width: getCanvasWidth(device),
// Keeping margin styles separate to avoid warnings
// when those props get overridden in the iframe component
marginTop: marginVertical,
marginBottom: marginVertical,
marginLeft: marginHorizontal,
marginRight: marginHorizontal,
height,
overflowY: "auto"
};
default:
return {
marginLeft: marginHorizontal,
marginRight: marginHorizontal
};
}
};
return contentInlineStyles(deviceType);
}
// packages/block-editor/build-module/components/block-inspector/index.mjs
var import_i18n204 = __toESM(require_i18n(), 1);
var import_blocks94 = __toESM(require_blocks(), 1);
var import_components214 = __toESM(require_components(), 1);
var import_data173 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/block-inspector/edit-contents.mjs
var import_components190 = __toESM(require_components(), 1);
var import_i18n180 = __toESM(require_i18n(), 1);
var import_data156 = __toESM(require_data(), 1);
var import_blocks89 = __toESM(require_blocks(), 1);
var import_jsx_runtime355 = __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, slug } = blockAttributes;
const templatePartId = theme && slug ? `${theme}//${slug}` : null;
if (templatePartId) {
onNavigateToEntityRecord({
postId: templatePartId,
postType: "wp_template_part"
});
}
}
};
return /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(import_components190.__experimentalVStack, { className: "block-editor-block-inspector-edit-contents", expanded: true, children: /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(
import_components190.Button,
{
className: "block-editor-block-inspector-edit-contents__button",
__next40pxDefaultSize: true,
variant: "secondary",
onClick: handleClick,
children: (0, import_i18n180.__)("Edit section")
}
) });
}
function InlineEditButton({
clientId,
editedContentOnlySection: editedContentOnlySection2,
editContentOnlySection: editContentOnlySection2,
stopEditingContentOnlySection: stopEditingContentOnlySection2
}) {
const handleClick = () => {
if (!editedContentOnlySection2) {
editContentOnlySection2(clientId);
} else {
stopEditingContentOnlySection2();
}
};
return /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(import_components190.__experimentalVStack, { className: "block-editor-block-inspector-edit-contents", expanded: true, children: /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(
import_components190.Button,
{
className: "block-editor-block-inspector-edit-contents__button",
__next40pxDefaultSize: true,
variant: "secondary",
onClick: handleClick,
children: editedContentOnlySection2 ? (0, import_i18n180.__)("Exit section") : (0, import_i18n180.__)("Edit section")
}
) });
}
function EditContents({ clientId }) {
const {
isWithinSection,
isWithinEditedSection,
editedContentOnlySection: editedContentOnlySection2,
editContentOnlySection: editContentOnlySection2,
stopEditingContentOnlySection: stopEditingContentOnlySection2
} = useContentOnlySectionEdit(clientId);
const { block, onNavigateToEntityRecord } = (0, import_data156.useSelect)(
(select3) => {
const { getBlock: getBlock2, getSettings: getSettings8 } = select3(store);
return {
block: getBlock2(clientId),
onNavigateToEntityRecord: getSettings8().onNavigateToEntityRecord
};
},
[clientId]
);
if (!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_runtime355.jsx)(
IsolatedEditButton,
{
block,
onNavigateToEntityRecord,
isSyncedPattern,
isTemplatePartBlock
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime355.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_i18n181 = __toESM(require_i18n(), 1);
var import_components191 = __toESM(require_components(), 1);
var import_element198 = __toESM(require_element(), 1);
var import_jsx_runtime356 = __toESM(require_jsx_runtime(), 1);
function SkipToSelectedBlock() {
const selectedBlockClientId = (0, import_data157.useSelect)(
(select3) => select3(store).getBlockSelectionStart(),
[]
);
const ref = (0, import_element198.useRef)();
useBlockElementRef(selectedBlockClientId, ref);
const onClick = () => {
ref.current?.focus();
};
return selectedBlockClientId ? /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(
import_components191.Button,
{
__next40pxDefaultSize: true,
variant: "secondary",
className: "block-editor-skip-to-selected-block",
onClick,
children: (0, import_i18n181.__)("Skip to the selected block")
}
) : null;
}
// packages/block-editor/build-module/components/multi-selection-inspector/index.mjs
var import_i18n182 = __toESM(require_i18n(), 1);
var import_data158 = __toESM(require_data(), 1);
var import_components192 = __toESM(require_components(), 1);
var import_jsx_runtime357 = __toESM(require_jsx_runtime(), 1);
function MultiSelectionInspector() {
const selectedBlockCount = (0, import_data158.useSelect)(
(select3) => select3(store).getSelectedBlockCount(),
[]
);
return /* @__PURE__ */ (0, import_jsx_runtime357.jsxs)(
import_components192.__experimentalHStack,
{
justify: "flex-start",
spacing: 2,
className: "block-editor-multi-selection-inspector__card",
children: [
/* @__PURE__ */ (0, import_jsx_runtime357.jsx)(block_icon_default, { icon: copy_default, showColors: true }),
/* @__PURE__ */ (0, import_jsx_runtime357.jsx)("div", { className: "block-editor-multi-selection-inspector__card-title", children: (0, import_i18n182.sprintf)(
/* translators: %d: number of blocks */
(0, import_i18n182._n)("%d Block", "%d Blocks", selectedBlockCount),
selectedBlockCount
) })
]
}
);
}
// packages/block-editor/build-module/components/inspector-controls-tabs/index.mjs
var import_components211 = __toESM(require_components(), 1);
var import_element215 = __toESM(require_element(), 1);
var import_preferences5 = __toESM(require_preferences(), 1);
var import_data169 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/inspector-controls-tabs/utils.mjs
var import_i18n183 = __toESM(require_i18n(), 1);
var TAB_SETTINGS = {
name: "settings",
title: (0, import_i18n183.__)("Settings"),
value: "settings",
icon: cog_default
};
var TAB_STYLES = {
name: "styles",
title: (0, import_i18n183.__)("Styles"),
value: "styles",
icon: styles_default
};
var TAB_CONTENT = {
name: "content",
title: (0, import_i18n183.__)("Content"),
value: "content",
icon: page_default
};
var TAB_LIST_VIEW = {
name: "list",
title: (0, import_i18n183.__)("List View"),
value: "list-view",
icon: list_view_default
};
// packages/block-editor/build-module/components/inspector-controls-tabs/advanced-controls-panel.mjs
var import_components193 = __toESM(require_components(), 1);
var import_i18n184 = __toESM(require_i18n(), 1);
var import_jsx_runtime358 = __toESM(require_jsx_runtime(), 1);
var AdvancedControls = () => {
const fills = (0, import_components193.__experimentalUseSlotFills)(InspectorAdvancedControls.slotName);
const privateFills = (0, import_components193.__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_runtime358.jsxs)(
import_components193.PanelBody,
{
className: "block-editor-block-inspector__advanced",
title: (0, import_i18n184.__)("Advanced"),
initialOpen: false,
children: [
/* @__PURE__ */ (0, import_jsx_runtime358.jsx)(inspector_controls_default.Slot, { group: "advanced" }),
/* @__PURE__ */ (0, import_jsx_runtime358.jsx)(PrivateInspectorControlsAllowedBlocks.Slot, {})
]
}
);
};
var advanced_controls_panel_default = AdvancedControls;
// 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_i18n185 = __toESM(require_i18n(), 1);
var import_jsx_runtime359 = __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_runtime359.jsx)(
import_components194.__experimentalToolsPanel,
{
className: "block-editor-block-inspector__position",
label: (0, import_i18n185.__)("Position"),
resetAll: resetPosition,
dropdownMenuProps,
children: /* @__PURE__ */ (0, import_jsx_runtime359.jsx)(
import_components194.__experimentalToolsPanelItem,
{
isShownByDefault: hasPositionAttribute,
label: (0, import_i18n185.__)("Position"),
hasValue: () => hasPositionAttribute,
onDeselect: resetPosition,
children: /* @__PURE__ */ (0, import_jsx_runtime359.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_runtime359.jsx)(PositionControlsPanel, {});
};
var position_controls_panel_default = PositionControls;
// packages/block-editor/build-module/components/inspector-controls-tabs/settings-tab.mjs
var import_jsx_runtime360 = __toESM(require_jsx_runtime(), 1);
var SettingsTab = ({ showAdvancedControls = false }) => /* @__PURE__ */ (0, import_jsx_runtime360.jsxs)(import_jsx_runtime360.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime360.jsx)(inspector_controls_default.Slot, {}),
/* @__PURE__ */ (0, import_jsx_runtime360.jsx)(position_controls_panel_default, {}),
/* @__PURE__ */ (0, import_jsx_runtime360.jsx)(inspector_controls_default.Slot, { group: "bindings" }),
showAdvancedControls && /* @__PURE__ */ (0, import_jsx_runtime360.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime360.jsx)(advanced_controls_panel_default, {}) })
] });
var settings_tab_default = SettingsTab;
// packages/block-editor/build-module/components/inspector-controls-tabs/styles-tab.mjs
var import_i18n201 = __toESM(require_i18n(), 1);
var import_data167 = __toESM(require_data(), 1);
// packages/block-editor/build-module/hooks/border.mjs
var import_blocks91 = __toESM(require_blocks(), 1);
var import_components208 = __toESM(require_components(), 1);
var import_element211 = __toESM(require_element(), 1);
var import_hooks11 = __toESM(require_hooks(), 1);
var import_data164 = __toESM(require_data(), 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,
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_element199 = __toESM(require_element(), 1);
var import_data160 = __toESM(require_data(), 1);
var import_blocks90 = __toESM(require_blocks(), 1);
var import_i18n186 = __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_element199.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")) {
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",
"writingMode"
].forEach((key) => {
if (!supportedStyles.includes(key)) {
updatedSettings.typography = {
...updatedSettings.typography,
[key]: false
};
}
});
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 sides = Array.isArray(supports?.spacing?.[key]) ? supports?.spacing?.[key] : supports?.spacing?.[key]?.sides;
if (sides?.length && updatedSettings.spacing?.[key]) {
updatedSettings.spacing = {
...updatedSettings.spacing,
[key]: {
...updatedSettings.spacing?.[key],
sides
}
};
}
});
["aspectRatio", "height", "minHeight", "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", "backgroundSize"].forEach((key) => {
if (!supportedStyles.includes(key)) {
updatedSettings.background = {
...updatedSettings.background,
[key]: 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_element199.useMemo)(() => {
const result = [];
if (themeColors && themeColors.length) {
result.push({
name: (0, import_i18n186._x)(
"Theme",
"Indicates this palette comes from the theme."
),
colors: themeColors
});
}
if (shouldDisplayDefaultColors && defaultColors && defaultColors.length) {
result.push({
name: (0, import_i18n186._x)(
"Default",
"Indicates this palette comes from WordPress."
),
colors: defaultColors
});
}
if (customColors && customColors.length) {
result.push({
name: (0, import_i18n186._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_element199.useMemo)(() => {
const result = [];
if (themeGradients && themeGradients.length) {
result.push({
name: (0, import_i18n186._x)(
"Theme",
"Indicates this palette comes from the theme."
),
gradients: themeGradients
});
}
if (shouldDisplayDefaultGradients && defaultGradients && defaultGradients.length) {
result.push({
name: (0, import_i18n186._x)(
"Default",
"Indicates this palette comes from WordPress."
),
gradients: defaultGradients
});
}
if (customGradients && customGradients.length) {
result.push({
name: (0, import_i18n186._x)(
"Custom",
"Indicates this palette is created by the user."
),
gradients: customGradients
});
}
return result;
}, [
customGradients,
themeGradients,
defaultGradients,
shouldDisplayDefaultGradients
]);
}
// packages/block-editor/build-module/components/global-styles/typography-panel.mjs
var import_components196 = __toESM(require_components(), 1);
var import_i18n188 = __toESM(require_i18n(), 1);
var import_element201 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/text-alignment-control/index.mjs
var import_i18n187 = __toESM(require_i18n(), 1);
var import_element200 = __toESM(require_element(), 1);
var import_components195 = __toESM(require_components(), 1);
var import_jsx_runtime361 = __toESM(require_jsx_runtime(), 1);
var TEXT_ALIGNMENT_OPTIONS = [
{
label: (0, import_i18n187.__)("Align text left"),
value: "left",
icon: align_left_default
},
{
label: (0, import_i18n187.__)("Align text center"),
value: "center",
icon: align_center_default
},
{
label: (0, import_i18n187.__)("Align text right"),
value: "right",
icon: align_right_default
},
{
label: (0, import_i18n187.__)("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_element200.useMemo)(
() => TEXT_ALIGNMENT_OPTIONS.filter(
(option) => options.includes(option.value)
),
[options]
);
if (!validOptions.length) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime361.jsx)(
import_components195.__experimentalToggleGroupControl,
{
isDeselectable: true,
__next40pxDefaultSize: true,
label: (0, import_i18n187.__)("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_runtime361.jsx)(
import_components195.__experimentalToggleGroupControlOptionIcon,
{
value: option.value,
icon: option.icon,
label: option.label
},
option.value
);
})
}
);
}
// 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_runtime362 = __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 hasWritingMode = useHasWritingModeControl(settings2);
const hasTextColumns = useHasTextColumnsControl(settings2);
const hasFontSize = useHasFontSizeControl(settings2);
return hasFontFamily || hasLineHeight || hasFontAppearance || hasLetterSpacing || hasTextAlign || hasTextTransform || hasFontSize || hasTextDecoration || hasWritingMode || hasTextColumns;
}
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_i18n188.__)("Font weight");
}
if (!settings2?.typography?.fontWeight) {
return (0, import_i18n188.__)("Font style");
}
return (0, import_i18n188.__)("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 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_runtime362.jsx)(
import_components196.__experimentalToolsPanel,
{
label: (0, import_i18n188.__)("Typography"),
resetAll,
panelId,
dropdownMenuProps,
children
}
);
}
var DEFAULT_CONTROLS3 = {
fontFamily: true,
fontSize: true,
fontAppearance: true,
lineHeight: true,
letterSpacing: true,
textAlign: true,
textTransform: true,
textDecoration: true,
writingMode: true,
textColumns: true
};
function TypographyPanel({
as: Wrapper = TypographyToolsPanel,
value,
onChange,
inheritedValue = value,
settings: settings2,
panelId,
defaultControls = DEFAULT_CONTROLS3
}) {
const decodeValue = (rawValue) => getValueFromVariable({ settings: settings2 }, "", rawValue);
const hasFontFamilyEnabled = useHasFontFamilyControl(settings2);
const fontFamily = decodeValue(inheritedValue?.typography?.fontFamily);
const { fontFamilies, fontFamilyFaces } = (0, import_element201.useMemo)(() => {
return getMergedFontFamiliesAndFontFamilyFaces(settings2, fontFamily);
}, [settings2, fontFamily]);
const setFontFamily = (newValue) => {
const slug = fontFamilies?.find(
({ fontFamily: f2 }) => f2 === newValue
)?.slug;
let updatedValue = setImmutably(
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(
setImmutably(
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_element201.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_element201.useCallback)(() => {
setFontAppearance({});
}, [setFontAppearance]);
const hasLineHeightEnabled = useHasLineHeightControl(settings2);
const lineHeight = decodeValue(inheritedValue?.typography?.lineHeight);
const setLineHeight = (newValue) => {
onChange(
setImmutably(
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(
setImmutably(
value,
["typography", "letterSpacing"],
newValue || void 0
)
);
};
const hasLetterSpacing = () => !!value?.typography?.letterSpacing;
const resetLetterSpacing = () => setLetterSpacing(void 0);
const hasTextColumnsControl = useHasTextColumnsControl(settings2);
const textColumns = decodeValue(inheritedValue?.typography?.textColumns);
const setTextColumns = (newValue) => {
onChange(
setImmutably(
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(
setImmutably(
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(
setImmutably(
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(
setImmutably(
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(
setImmutably(
value,
["typography", "textAlign"],
newValue || void 0
)
);
};
const hasTextAlign = () => !!value?.typography?.textAlign;
const resetTextAlign = () => setTextAlign(void 0);
const resetAllFilter = (0, import_element201.useCallback)((previousValue) => {
return {
...previousValue,
typography: {}
};
}, []);
return /* @__PURE__ */ (0, import_jsx_runtime362.jsxs)(
Wrapper,
{
resetAllFilter,
value,
onChange,
panelId,
children: [
hasFontFamilyEnabled && /* @__PURE__ */ (0, import_jsx_runtime362.jsx)(
import_components196.__experimentalToolsPanelItem,
{
label: (0, import_i18n188.__)("Font"),
hasValue: hasFontFamily,
onDeselect: resetFontFamily,
isShownByDefault: defaultControls.fontFamily,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime362.jsx)(
FontFamilyControl,
{
fontFamilies,
value: fontFamily,
onChange: setFontFamily,
size: "__unstable-large"
}
)
}
),
hasFontSizeEnabled && /* @__PURE__ */ (0, import_jsx_runtime362.jsx)(
import_components196.__experimentalToolsPanelItem,
{
label: (0, import_i18n188.__)("Size"),
hasValue: hasFontSize,
onDeselect: resetFontSize,
isShownByDefault: defaultControls.fontSize,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime362.jsx)(
import_components196.FontSizePicker,
{
value: currentFontSizeSlug || fontSize,
valueMode: currentFontSizeSlug ? "slug" : "literal",
onChange: setFontSize,
fontSizes: mergedFontSizes,
disableCustomFontSizes,
withReset: false,
withSlider: true,
size: "__unstable-large"
}
)
}
),
hasAppearanceControl && /* @__PURE__ */ (0, import_jsx_runtime362.jsx)(
import_components196.__experimentalToolsPanelItem,
{
className: "single-column",
label: appearanceControlLabel,
hasValue: hasFontAppearance,
onDeselect: resetFontAppearance,
isShownByDefault: defaultControls.fontAppearance,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime362.jsx)(
FontAppearanceControl,
{
value: {
fontStyle,
fontWeight
},
onChange: setFontAppearance,
hasFontStyles,
hasFontWeights,
fontFamilyFaces,
size: "__unstable-large"
}
)
}
),
hasLineHeightEnabled && /* @__PURE__ */ (0, import_jsx_runtime362.jsx)(
import_components196.__experimentalToolsPanelItem,
{
className: "single-column",
label: (0, import_i18n188.__)("Line height"),
hasValue: hasLineHeight,
onDeselect: resetLineHeight,
isShownByDefault: defaultControls.lineHeight,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime362.jsx)(
line_height_control_default,
{
__unstableInputWidth: "auto",
value: lineHeight,
onChange: setLineHeight,
size: "__unstable-large"
}
)
}
),
hasLetterSpacingControl && /* @__PURE__ */ (0, import_jsx_runtime362.jsx)(
import_components196.__experimentalToolsPanelItem,
{
className: "single-column",
label: (0, import_i18n188.__)("Letter spacing"),
hasValue: hasLetterSpacing,
onDeselect: resetLetterSpacing,
isShownByDefault: defaultControls.letterSpacing,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime362.jsx)(
LetterSpacingControl,
{
value: letterSpacing,
onChange: setLetterSpacing,
size: "__unstable-large",
__unstableInputWidth: "auto"
}
)
}
),
hasTextColumnsControl && /* @__PURE__ */ (0, import_jsx_runtime362.jsx)(
import_components196.__experimentalToolsPanelItem,
{
className: "single-column",
label: (0, import_i18n188.__)("Columns"),
hasValue: hasTextColumns,
onDeselect: resetTextColumns,
isShownByDefault: defaultControls.textColumns,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime362.jsx)(
import_components196.__experimentalNumberControl,
{
label: (0, import_i18n188.__)("Columns"),
max: MAX_TEXT_COLUMNS,
min: MIN_TEXT_COLUMNS,
onChange: setTextColumns,
size: "__unstable-large",
spinControls: "custom",
value: textColumns,
initialPosition: 1
}
)
}
),
hasTextDecorationControl && /* @__PURE__ */ (0, import_jsx_runtime362.jsx)(
import_components196.__experimentalToolsPanelItem,
{
className: "single-column",
label: (0, import_i18n188.__)("Decoration"),
hasValue: hasTextDecoration,
onDeselect: resetTextDecoration,
isShownByDefault: defaultControls.textDecoration,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime362.jsx)(
TextDecorationControl,
{
value: textDecoration,
onChange: setTextDecoration,
size: "__unstable-large",
__unstableInputWidth: "auto"
}
)
}
),
hasWritingModeControl && /* @__PURE__ */ (0, import_jsx_runtime362.jsx)(
import_components196.__experimentalToolsPanelItem,
{
className: "single-column",
label: (0, import_i18n188.__)("Orientation"),
hasValue: hasWritingMode,
onDeselect: resetWritingMode,
isShownByDefault: defaultControls.writingMode,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime362.jsx)(
WritingModeControl,
{
value: writingMode,
onChange: setWritingMode,
size: "__unstable-large"
}
)
}
),
hasTextTransformControl && /* @__PURE__ */ (0, import_jsx_runtime362.jsx)(
import_components196.__experimentalToolsPanelItem,
{
label: (0, import_i18n188.__)("Letter case"),
hasValue: hasTextTransform,
onDeselect: resetTextTransform,
isShownByDefault: defaultControls.textTransform,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime362.jsx)(
TextTransformControl,
{
value: textTransform,
onChange: setTextTransform,
showNone: true,
isBlock: true,
size: "__unstable-large"
}
)
}
),
hasTextAlignmentControl && /* @__PURE__ */ (0, import_jsx_runtime362.jsxs)(
import_components196.__experimentalToolsPanelItem,
{
label: (0, import_i18n188.__)("Text alignment"),
hasValue: hasTextAlign,
onDeselect: resetTextAlign,
isShownByDefault: defaultControls.textAlign,
panelId,
children: [
/* @__PURE__ */ (0, import_jsx_runtime362.jsx)(
TextAlignmentControl,
{
value: textAlign,
onChange: setTextAlign,
options: ["left", "center", "right", "justify"],
size: "__unstable-large"
}
),
textAlign === "justify" && /* @__PURE__ */ (0, import_jsx_runtime362.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime362.jsx)(import_components196.Notice, { status: "warning", isDismissible: false, children: (0, import_i18n188.__)(
"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_i18n191 = __toESM(require_i18n(), 1);
var import_components199 = __toESM(require_components(), 1);
var import_element203 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/child-layout-control/index.mjs
var import_components197 = __toESM(require_components(), 1);
var import_i18n189 = __toESM(require_i18n(), 1);
var import_element202 = __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_runtime363 = __toESM(require_jsx_runtime(), 1);
function helpText(selfStretch, parentLayout) {
const { orientation = "horizontal" } = parentLayout;
if (selfStretch === "fill") {
return (0, import_i18n189.__)("Stretch to fill available space.");
}
if (selfStretch === "fixed" && orientation === "horizontal") {
return (0, import_i18n189.__)("Specify a fixed width.");
} else if (selfStretch === "fixed") {
return (0, import_i18n189.__)("Specify a fixed height.");
}
return (0, import_i18n189.__)("Fit contents.");
}
function ChildLayoutControl({
value: childLayout = {},
onChange,
parentLayout,
isShownByDefault,
panelId
}) {
const {
type: parentType,
default: { type: defaultParentType = "default" } = {}
} = parentLayout ?? {};
const parentLayoutType = parentType || defaultParentType;
if (parentLayoutType === "flex") {
return /* @__PURE__ */ (0, import_jsx_runtime363.jsx)(
FlexControls,
{
childLayout,
onChange,
parentLayout,
isShownByDefault,
panelId
}
);
} else if (parentLayoutType === "grid") {
return /* @__PURE__ */ (0, import_jsx_runtime363.jsx)(
GridControls,
{
childLayout,
onChange,
parentLayout,
isShownByDefault,
panelId
}
);
}
return null;
}
function FlexControls({
childLayout,
onChange,
parentLayout,
isShownByDefault,
panelId
}) {
const { selfStretch, flexSize } = childLayout;
const { orientation = "horizontal" } = parentLayout ?? {};
const hasFlexValue = () => !!selfStretch;
const flexResetLabel = orientation === "horizontal" ? (0, import_i18n189.__)("Width") : (0, import_i18n189.__)("Height");
const [availableUnits] = useSettings("spacing.units");
const units2 = (0, import_components197.__experimentalUseCustomUnits)({
availableUnits: availableUnits || [
"%",
"px",
"em",
"rem",
"vh",
"vw"
]
});
const resetFlex = () => {
onChange({
selfStretch: void 0,
flexSize: void 0
});
};
(0, import_element202.useEffect)(() => {
if (selfStretch === "fixed" && !flexSize) {
onChange({
...childLayout,
selfStretch: "fit"
});
}
}, []);
return /* @__PURE__ */ (0, import_jsx_runtime363.jsxs)(
import_components197.__experimentalVStack,
{
as: import_components197.__experimentalToolsPanelItem,
spacing: 2,
hasValue: hasFlexValue,
label: flexResetLabel,
onDeselect: resetFlex,
isShownByDefault,
panelId,
children: [
/* @__PURE__ */ (0, import_jsx_runtime363.jsxs)(
import_components197.__experimentalToggleGroupControl,
{
size: "__unstable-large",
label: childLayoutOrientation(parentLayout),
value: selfStretch || "fit",
help: helpText(selfStretch, parentLayout),
onChange: (value) => {
const newFlexSize = value !== "fixed" ? null : flexSize;
onChange({
selfStretch: value,
flexSize: newFlexSize
});
},
isBlock: true,
children: [
/* @__PURE__ */ (0, import_jsx_runtime363.jsx)(
import_components197.__experimentalToggleGroupControlOption,
{
value: "fit",
label: (0, import_i18n189._x)(
"Fit",
"Intrinsic block width in flex layout"
)
},
"fit"
),
/* @__PURE__ */ (0, import_jsx_runtime363.jsx)(
import_components197.__experimentalToggleGroupControlOption,
{
value: "fill",
label: (0, import_i18n189._x)(
"Grow",
"Block with expanding width in flex layout"
)
},
"fill"
),
/* @__PURE__ */ (0, import_jsx_runtime363.jsx)(
import_components197.__experimentalToggleGroupControlOption,
{
value: "fixed",
label: (0, import_i18n189._x)(
"Fixed",
"Block with fixed width in flex layout"
)
},
"fixed"
)
]
}
),
selfStretch === "fixed" && /* @__PURE__ */ (0, import_jsx_runtime363.jsx)(
import_components197.__experimentalUnitControl,
{
size: "__unstable-large",
units: units2,
onChange: (value) => {
onChange({
selfStretch,
flexSize: value
});
},
value: flexSize,
min: 0,
label: flexResetLabel,
hideLabelFromVision: true
}
)
]
}
);
}
function childLayoutOrientation(parentLayout) {
const { orientation = "horizontal" } = parentLayout;
return orientation === "horizontal" ? (0, import_i18n189.__)("Width") : (0, import_i18n189.__)("Height");
}
function GridControls({
childLayout,
onChange,
parentLayout,
isShownByDefault,
panelId
}) {
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;
return /* @__PURE__ */ (0, import_jsx_runtime363.jsxs)(import_jsx_runtime363.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime363.jsxs)(
import_components197.Flex,
{
as: import_components197.__experimentalToolsPanelItem,
hasValue: hasSpanValue,
label: (0, import_i18n189.__)("Grid span"),
onDeselect: resetGridSpans,
isShownByDefault,
panelId,
children: [
/* @__PURE__ */ (0, import_jsx_runtime363.jsx)(import_components197.FlexItem, { style: { width: "50%" }, children: /* @__PURE__ */ (0, import_jsx_runtime363.jsx)(
import_components197.__experimentalInputControl,
{
size: "__unstable-large",
label: (0, import_i18n189.__)("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: columnSpan ?? 1,
min: 1,
max: maxColumnSpan
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime363.jsx)(import_components197.FlexItem, { style: { width: "50%" }, children: /* @__PURE__ */ (0, import_jsx_runtime363.jsx)(
import_components197.__experimentalInputControl,
{
size: "__unstable-large",
label: (0, import_i18n189.__)("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: rowSpan ?? 1,
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_runtime363.jsxs)(
import_components197.Flex,
{
as: import_components197.__experimentalToolsPanelItem,
hasValue: hasStartValue,
label: (0, import_i18n189.__)("Grid placement"),
onDeselect: resetGridStarts,
isShownByDefault: false,
panelId,
children: [
/* @__PURE__ */ (0, import_jsx_runtime363.jsx)(import_components197.FlexItem, { style: { width: "50%" }, children: /* @__PURE__ */ (0, import_jsx_runtime363.jsx)(
import_components197.__experimentalInputControl,
{
size: "__unstable-large",
label: (0, import_i18n189.__)("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_runtime363.jsx)(import_components197.FlexItem, { style: { width: "50%" }, children: /* @__PURE__ */ (0, import_jsx_runtime363.jsx)(
import_components197.__experimentalInputControl,
{
size: "__unstable-large",
label: (0, import_i18n189.__)("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_components198 = __toESM(require_components(), 1);
var import_i18n190 = __toESM(require_i18n(), 1);
var import_jsx_runtime364 = __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_i18n190._x)(
"Original",
"Aspect ratio option for dimensions control"
),
value: "auto"
},
...showDefaultRatios ? defaultOptions2 : [],
...themeOptions ? themeOptions : [],
{
label: (0, import_i18n190._x)("Custom", "Aspect ratio option for dimensions control"),
value: "custom",
disabled: true,
hidden: true
}
];
return /* @__PURE__ */ (0, import_jsx_runtime364.jsx)(
import_components198.__experimentalToolsPanelItem,
{
hasValue: hasValue ? hasValue : () => displayValue !== defaultValue,
label: (0, import_i18n190.__)("Aspect ratio"),
onDeselect: () => onChange(void 0),
isShownByDefault,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime364.jsx)(
import_components198.SelectControl,
{
label: (0, import_i18n190.__)("Aspect ratio"),
value: displayValue,
options: options ?? aspectRatioOptions,
onChange,
size: "__unstable-large"
}
)
}
);
}
// packages/block-editor/build-module/components/global-styles/dimensions-panel.mjs
var import_jsx_runtime365 = __toESM(require_jsx_runtime(), 1);
var AXIAL_SIDES = ["horizontal", "vertical"];
function useHasDimensionsPanel(settings2) {
const hasContentSize = useHasContentSize(settings2);
const hasWideSize = useHasWideSize(settings2);
const hasPadding = useHasPadding(settings2);
const hasMargin = useHasMargin(settings2);
const hasGap = useHasGap(settings2);
const hasHeight = useHasHeight(settings2);
const hasMinHeight = useHasMinHeight(settings2);
const hasWidth = useHasWidth(settings2);
const hasAspectRatio = useHasAspectRatio(settings2);
const hasChildLayout = useHasChildLayout(settings2);
return import_element203.Platform.OS === "web" && (hasContentSize || hasWideSize || hasPadding || hasMargin || hasGap || hasHeight || hasMinHeight || hasWidth || hasAspectRatio || hasChildLayout);
}
function useHasContentSize(settings2) {
return settings2?.layout?.contentSize;
}
function useHasWideSize(settings2) {
return settings2?.layout?.wideSize;
}
function useHasPadding(settings2) {
return settings2?.spacing?.padding;
}
function useHasMargin(settings2) {
return settings2?.spacing?.margin;
}
function useHasGap(settings2) {
return settings2?.spacing?.blockGap;
}
function useHasHeight(settings2) {
return settings2?.dimensions?.height;
}
function useHasMinHeight(settings2) {
return settings2?.dimensions?.minHeight;
}
function useHasWidth(settings2) {
return settings2?.dimensions?.width;
}
function useHasAspectRatio(settings2) {
return settings2?.dimensions?.aspectRatio;
}
function useHasChildLayout(settings2) {
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 useHasSpacingPresets(settings2) {
const { defaultSpacingSizes, spacingSizes } = settings2?.spacing || {};
return defaultSpacingSizes !== false && spacingSizes?.default?.length > 0 || spacingSizes?.theme?.length > 0 || spacingSizes?.custom?.length > 0;
}
function filterValuesBySides(values, sides) {
if (!sides || !values) {
return values;
}
const filteredValues = {};
sides.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_runtime365.jsx)(
import_components199.__experimentalToolsPanel,
{
label: (0, import_i18n191.__)("Dimensions"),
resetAll,
panelId,
dropdownMenuProps,
children
}
);
}
var DEFAULT_CONTROLS4 = {
contentSize: true,
wideSize: true,
padding: true,
margin: true,
blockGap: true,
height: true,
minHeight: true,
width: true,
aspectRatio: true,
childLayout: true
};
function DimensionsPanel({
as: Wrapper = DimensionsToolsPanel,
value,
onChange,
inheritedValue = value,
settings: settings2,
panelId,
defaultControls = DEFAULT_CONTROLS4,
onVisualize = () => {
},
// Special case because the layout controls are not part of the dimensions panel
// in global styles but not in block inspector.
includeLayoutControls = false
}) {
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 = useHasSpacingPresets(settings2);
const units2 = (0, import_components199.__experimentalUseCustomUnits)({
availableUnits: settings2?.spacing?.units || [
"%",
"px",
"em",
"rem",
"vw"
]
});
const minimumMargin = -Infinity;
const [minMarginValue, setMinMarginValue] = (0, import_element203.useState)(minimumMargin);
const showContentSizeControl = useHasContentSize(settings2) && includeLayoutControls;
const contentSizeValue = decodeValue(inheritedValue?.layout?.contentSize);
const setContentSizeValue = (newValue) => {
onChange(
setImmutably(
value,
["layout", "contentSize"],
newValue || void 0
)
);
};
const hasUserSetContentSizeValue = () => !!value?.layout?.contentSize;
const resetContentSizeValue = () => setContentSizeValue(void 0);
const showWideSizeControl = useHasWideSize(settings2) && includeLayoutControls;
const wideSizeValue = decodeValue(inheritedValue?.layout?.wideSize);
const setWideSizeValue = (newValue) => {
onChange(
setImmutably(
value,
["layout", "wideSize"],
newValue || void 0
)
);
};
const hasUserSetWideSizeValue = () => !!value?.layout?.wideSize;
const resetWideSizeValue = () => setWideSizeValue(void 0);
const showPaddingControl = useHasPadding(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(setImmutably(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 = useHasMargin(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(setImmutably(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 = useHasGap(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(
setImmutably(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 = useHasMinHeight(settings2);
const minHeightValue = decodeValue(inheritedValue?.dimensions?.minHeight);
const setMinHeightValue = (newValue) => {
const tempValue = setImmutably(
value,
["dimensions", "minHeight"],
newValue
);
onChange(
setImmutably(
tempValue,
["dimensions", "aspectRatio"],
void 0
)
);
};
const resetMinHeightValue = () => {
setMinHeightValue(void 0);
};
const hasMinHeightValue = () => !!value?.dimensions?.minHeight;
const showHeightControl = useHasHeight(settings2);
const heightValue = decodeValue(inheritedValue?.dimensions?.height);
const setHeightValue = (newValue) => {
const tempValue = setImmutably(
value,
["dimensions", "height"],
newValue
);
onChange(
setImmutably(
tempValue,
["dimensions", "aspectRatio"],
void 0
)
);
};
const resetHeightValue = () => {
setHeightValue(void 0);
};
const hasHeightValue = () => !!value?.dimensions?.height;
const showWidthControl = useHasWidth(settings2);
const widthValue = decodeValue(inheritedValue?.dimensions?.width);
const setWidthValue = (newValue) => {
onChange(setImmutably(value, ["dimensions", "width"], newValue));
};
const resetWidthValue = () => {
setWidthValue(void 0);
};
const hasWidthValue = () => !!value?.dimensions?.width;
const showAspectRatioControl = useHasAspectRatio(settings2);
const aspectRatioValue = decodeValue(
inheritedValue?.dimensions?.aspectRatio
);
const setAspectRatioValue = (newValue) => {
const tempValue = setImmutably(
value,
["dimensions", "aspectRatio"],
newValue
);
onChange(
setImmutably(tempValue, ["dimensions", "minHeight"], void 0)
);
};
const hasAspectRatioValue = () => !!value?.dimensions?.aspectRatio;
const showChildLayoutControl = useHasChildLayout(settings2);
const childLayout = inheritedValue?.layout;
const setChildLayout = (newChildLayout) => {
onChange({
...value,
layout: {
...newChildLayout
}
});
};
const resetAllFilter = (0, import_element203.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,
aspectRatio: void 0,
width: void 0
}
};
}, []);
const onMouseLeaveControls = () => onVisualize(false);
return /* @__PURE__ */ (0, import_jsx_runtime365.jsxs)(
Wrapper,
{
resetAllFilter,
value,
onChange,
panelId,
children: [
(showContentSizeControl || showWideSizeControl) && /* @__PURE__ */ (0, import_jsx_runtime365.jsx)("span", { className: "span-columns", children: (0, import_i18n191.__)("Set the width of the main content area.") }),
showContentSizeControl && /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(
import_components199.__experimentalToolsPanelItem,
{
label: (0, import_i18n191.__)("Content width"),
hasValue: hasUserSetContentSizeValue,
onDeselect: resetContentSizeValue,
isShownByDefault: defaultControls.contentSize ?? DEFAULT_CONTROLS4.contentSize,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(
import_components199.__experimentalUnitControl,
{
__next40pxDefaultSize: true,
label: (0, import_i18n191.__)("Content width"),
labelPosition: "top",
value: contentSizeValue || "",
onChange: (nextContentSize) => {
setContentSizeValue(nextContentSize);
},
units: units2,
prefix: /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(import_components199.__experimentalInputControlPrefixWrapper, { variant: "icon", children: /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(icon_default, { icon: align_none_default }) })
}
)
}
),
showWideSizeControl && /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(
import_components199.__experimentalToolsPanelItem,
{
label: (0, import_i18n191.__)("Wide width"),
hasValue: hasUserSetWideSizeValue,
onDeselect: resetWideSizeValue,
isShownByDefault: defaultControls.wideSize ?? DEFAULT_CONTROLS4.wideSize,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(
import_components199.__experimentalUnitControl,
{
__next40pxDefaultSize: true,
label: (0, import_i18n191.__)("Wide width"),
labelPosition: "top",
value: wideSizeValue || "",
onChange: (nextWideSize) => {
setWideSizeValue(nextWideSize);
},
units: units2,
prefix: /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(import_components199.__experimentalInputControlPrefixWrapper, { variant: "icon", children: /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(icon_default, { icon: stretch_wide_default }) })
}
)
}
),
showPaddingControl && /* @__PURE__ */ (0, import_jsx_runtime365.jsxs)(
import_components199.__experimentalToolsPanelItem,
{
hasValue: hasPaddingValue,
label: (0, import_i18n191.__)("Padding"),
onDeselect: resetPaddingValue,
isShownByDefault: defaultControls.padding ?? DEFAULT_CONTROLS4.padding,
className: clsx_default({
"tools-panel-item-spacing": showSpacingPresetsControl
}),
panelId,
children: [
!showSpacingPresetsControl && /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(
import_components199.BoxControl,
{
__next40pxDefaultSize: true,
values: paddingValues,
onChange: setPaddingValues,
label: (0, import_i18n191.__)("Padding"),
sides: paddingSides,
units: units2,
allowReset: false,
splitOnAxis: isAxialPadding,
inputProps: {
onMouseOver: onMouseOverPadding,
onMouseOut: onMouseLeaveControls
}
}
),
showSpacingPresetsControl && /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(
SpacingSizesControl,
{
values: paddingValues,
onChange: setPaddingValues,
label: (0, import_i18n191.__)("Padding"),
sides: paddingSides,
units: units2,
allowReset: false,
onMouseOver: onMouseOverPadding,
onMouseOut: onMouseLeaveControls
}
)
]
}
),
showMarginControl && /* @__PURE__ */ (0, import_jsx_runtime365.jsxs)(
import_components199.__experimentalToolsPanelItem,
{
hasValue: hasMarginValue,
label: (0, import_i18n191.__)("Margin"),
onDeselect: resetMarginValue,
isShownByDefault: defaultControls.margin ?? DEFAULT_CONTROLS4.margin,
className: clsx_default({
"tools-panel-item-spacing": showSpacingPresetsControl
}),
panelId,
children: [
!showSpacingPresetsControl && /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(
import_components199.BoxControl,
{
__next40pxDefaultSize: true,
values: marginValues,
onChange: setMarginValues,
inputProps: {
min: minMarginValue,
onDragStart: () => {
setMinMarginValue(0);
},
onDragEnd: () => {
setMinMarginValue(minimumMargin);
},
onMouseOver: onMouseOverMargin,
onMouseOut: onMouseLeaveControls
},
label: (0, import_i18n191.__)("Margin"),
sides: marginSides,
units: units2,
allowReset: false,
splitOnAxis: isAxialMargin
}
),
showSpacingPresetsControl && /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(
SpacingSizesControl,
{
values: marginValues,
onChange: setMarginValues,
minimumCustomValue: -Infinity,
label: (0, import_i18n191.__)("Margin"),
sides: marginSides,
units: units2,
allowReset: false,
onMouseOver: onMouseOverMargin,
onMouseOut: onMouseLeaveControls
}
)
]
}
),
showGapControl && /* @__PURE__ */ (0, import_jsx_runtime365.jsxs)(
import_components199.__experimentalToolsPanelItem,
{
hasValue: hasGapValue,
label: (0, import_i18n191.__)("Block spacing"),
onDeselect: resetGapValue,
isShownByDefault: defaultControls.blockGap ?? DEFAULT_CONTROLS4.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_runtime365.jsx)(
import_components199.BoxControl,
{
__next40pxDefaultSize: true,
label: (0, import_i18n191.__)("Block spacing"),
min: 0,
onChange: setGapValues,
units: units2,
sides: gapSides,
values: gapValues,
allowReset: false,
splitOnAxis: isAxialGap
}
) : /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(
import_components199.__experimentalUnitControl,
{
__next40pxDefaultSize: true,
label: (0, import_i18n191.__)("Block spacing"),
min: 0,
onChange: setGapValue,
units: units2,
value: gapValue
}
)),
showSpacingPresetsControl && /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(
SpacingSizesControl,
{
label: (0, import_i18n191.__)("Block spacing"),
min: 0,
onChange: setGapValues,
showSideInLabel: false,
sides: isAxialGap ? gapSides : ["top"],
values: gapValues,
allowReset: false
}
)
]
}
),
showChildLayoutControl && /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(
ChildLayoutControl,
{
value: childLayout,
onChange: setChildLayout,
parentLayout: settings2?.parentLayout,
panelId,
isShownByDefault: defaultControls.childLayout ?? DEFAULT_CONTROLS4.childLayout
}
),
showMinHeightControl && /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(
import_components199.__experimentalToolsPanelItem,
{
hasValue: hasMinHeightValue,
label: (0, import_i18n191.__)("Minimum height"),
onDeselect: resetMinHeightValue,
isShownByDefault: defaultControls.minHeight ?? DEFAULT_CONTROLS4.minHeight,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(
DimensionControl,
{
label: (0, import_i18n191.__)("Minimum height"),
value: minHeightValue,
onChange: setMinHeightValue
}
)
}
),
showHeightControl && /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(
import_components199.__experimentalToolsPanelItem,
{
hasValue: hasHeightValue,
label: (0, import_i18n191.__)("Height"),
onDeselect: resetHeightValue,
isShownByDefault: defaultControls.height ?? DEFAULT_CONTROLS4.height,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(
DimensionControl,
{
label: (0, import_i18n191.__)("Height"),
value: heightValue,
onChange: setHeightValue
}
)
}
),
showWidthControl && /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(
import_components199.__experimentalToolsPanelItem,
{
hasValue: hasWidthValue,
label: (0, import_i18n191.__)("Width"),
onDeselect: resetWidthValue,
isShownByDefault: defaultControls.width ?? DEFAULT_CONTROLS4.width,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(
DimensionControl,
{
label: (0, import_i18n191.__)("Width"),
value: widthValue,
onChange: setWidthValue
}
)
}
),
showAspectRatioControl && /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(
AspectRatioTool,
{
hasValue: hasAspectRatioValue,
value: aspectRatioValue,
onChange: setAspectRatioValue,
panelId,
isShownByDefault: defaultControls.aspectRatio ?? DEFAULT_CONTROLS4.aspectRatio
}
)
]
}
);
}
// packages/block-editor/build-module/components/global-styles/border-panel.mjs
var import_components201 = __toESM(require_components(), 1);
var import_element205 = __toESM(require_element(), 1);
var import_i18n193 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/global-styles/shadow-panel-components.mjs
var import_i18n192 = __toESM(require_i18n(), 1);
var import_components200 = __toESM(require_components(), 1);
var import_element204 = __toESM(require_element(), 1);
var import_jsx_runtime366 = __toESM(require_jsx_runtime(), 1);
var EMPTY_ARRAY12 = [];
function ShadowPopoverContainer({ shadow, onShadowChange, settings: settings2 }) {
const shadows = useShadowPresets(settings2);
return /* @__PURE__ */ (0, import_jsx_runtime366.jsx)("div", { className: "block-editor-global-styles__shadow-popover-container", children: /* @__PURE__ */ (0, import_jsx_runtime366.jsxs)(import_components200.__experimentalVStack, { spacing: 4, children: [
/* @__PURE__ */ (0, import_jsx_runtime366.jsx)(import_components200.__experimentalHeading, { level: 5, children: (0, import_i18n192.__)("Drop shadow") }),
/* @__PURE__ */ (0, import_jsx_runtime366.jsx)(
ShadowPresets,
{
presets: shadows,
activeShadow: shadow,
onSelect: onShadowChange
}
),
/* @__PURE__ */ (0, import_jsx_runtime366.jsx)("div", { className: "block-editor-global-styles__clear-shadow", children: /* @__PURE__ */ (0, import_jsx_runtime366.jsx)(
import_components200.Button,
{
__next40pxDefaultSize: true,
variant: "tertiary",
onClick: () => onShadowChange(void 0),
disabled: !shadow,
accessibleWhenDisabled: true,
children: (0, import_i18n192.__)("Clear")
}
) })
] }) });
}
function ShadowPresets({ presets, activeShadow, onSelect }) {
return !presets ? null : /* @__PURE__ */ (0, import_jsx_runtime366.jsx)(
import_components200.Composite,
{
role: "listbox",
className: "block-editor-global-styles__shadow__list",
"aria-label": (0, import_i18n192.__)("Drop shadows"),
children: presets.map(({ name, slug, shadow }) => /* @__PURE__ */ (0, import_jsx_runtime366.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_runtime366.jsx)(import_components200.Tooltip, { text: label, children: /* @__PURE__ */ (0, import_jsx_runtime366.jsx)(
import_components200.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_runtime366.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_runtime366.jsx)(icon_default, { icon: check_default })
}
)
}
) });
}
function ShadowPopover({ shadow, onShadowChange, settings: settings2 }) {
const popoverProps3 = {
placement: "left-start",
offset: 36,
shift: true
};
return /* @__PURE__ */ (0, import_jsx_runtime366.jsx)(
import_components200.Dropdown,
{
popoverProps: popoverProps3,
className: "block-editor-global-styles__shadow-dropdown",
renderToggle: renderShadowToggle(shadow, onShadowChange),
renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime366.jsx)(import_components200.__experimentalDropdownContentWrapper, { paddingSize: "medium", children: /* @__PURE__ */ (0, import_jsx_runtime366.jsx)(
ShadowPopoverContainer,
{
shadow,
onShadowChange,
settings: settings2
}
) })
}
);
}
function renderShadowToggle(shadow, onShadowChange) {
return ({ onToggle, isOpen }) => {
const shadowButtonRef = (0, import_element204.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_i18n192.__)("Remove")
};
return /* @__PURE__ */ (0, import_jsx_runtime366.jsxs)(import_jsx_runtime366.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime366.jsx)(import_components200.Button, { __next40pxDefaultSize: true, ...toggleProps, children: /* @__PURE__ */ (0, import_jsx_runtime366.jsxs)(import_components200.__experimentalHStack, { justify: "flex-start", children: [
/* @__PURE__ */ (0, import_jsx_runtime366.jsx)(
icon_default,
{
className: "block-editor-global-styles__toggle-icon",
icon: shadow_default,
size: 24
}
),
/* @__PURE__ */ (0, import_jsx_runtime366.jsx)(import_components200.FlexItem, { children: (0, import_i18n192.__)("Drop shadow") })
] }) }),
!!shadow && /* @__PURE__ */ (0, import_jsx_runtime366.jsx)(
import_components200.Button,
{
__next40pxDefaultSize: true,
size: "small",
icon: reset_default,
...removeButtonProps
}
)
] });
};
}
function useShadowPresets(settings2) {
return (0, import_element204.useMemo)(() => {
if (!settings2?.shadow) {
return EMPTY_ARRAY12;
}
const defaultPresetsEnabled = settings2?.shadow?.defaultPresets;
const {
default: defaultShadows,
theme: themeShadows,
custom: customShadows
} = settings2?.shadow?.presets ?? {};
const unsetShadow = {
name: (0, import_i18n192.__)("Unset"),
slug: "unset",
shadow: "none"
};
const shadowPresets = [
...defaultPresetsEnabled && defaultShadows || EMPTY_ARRAY12,
...themeShadows || EMPTY_ARRAY12,
...customShadows || EMPTY_ARRAY12
];
if (shadowPresets.length) {
shadowPresets.unshift(unsetShadow);
}
return shadowPresets;
}, [settings2]);
}
// packages/block-editor/build-module/components/global-styles/border-panel.mjs
var import_jsx_runtime367 = __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_runtime367.jsx)(
import_components201.__experimentalToolsPanel,
{
label,
resetAll,
panelId,
dropdownMenuProps,
children
}
);
}
var DEFAULT_CONTROLS5 = {
radius: true,
color: true,
width: true,
shadow: true
};
function BorderPanel({
as: Wrapper = BorderToolsPanel,
value,
onChange,
inheritedValue = value,
settings: settings2,
panelId,
name,
defaultControls = DEFAULT_CONTROLS5
}) {
const colors2 = useColorsPerOrigin(settings2);
const decodeValue = (0, import_element205.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_element205.useMemo)(() => {
if ((0, import_components201.__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_element205.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(
setImmutably(
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_components201.__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_element205.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_runtime367.jsxs)(
Wrapper,
{
resetAllFilter,
value,
onChange,
panelId,
label,
children: [
(showBorderWidth || showBorderColor) && /* @__PURE__ */ (0, import_jsx_runtime367.jsx)(
import_components201.__experimentalToolsPanelItem,
{
hasValue: () => (0, import_components201.__experimentalIsDefinedBorder)(value?.border),
label: (0, import_i18n193.__)("Border"),
onDeselect: () => resetBorder(),
isShownByDefault: showBorderByDefault,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime367.jsx)(
import_components201.BorderBoxControl,
{
colors: colors2,
enableAlpha: true,
enableStyle: showBorderStyle,
onChange: onBorderChange,
popoverOffset: 40,
popoverPlacement: "left-start",
value: border,
__experimentalIsRenderedInSidebar: true,
size: "__unstable-large",
hideLabelFromVision: !hasShadowControl,
label: (0, import_i18n193.__)("Border")
}
)
}
),
showBorderRadius && /* @__PURE__ */ (0, import_jsx_runtime367.jsx)(
import_components201.__experimentalToolsPanelItem,
{
hasValue: hasBorderRadius,
label: (0, import_i18n193.__)("Radius"),
onDeselect: () => setBorderRadius(void 0),
isShownByDefault: defaultControls.radius,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime367.jsx)(
BorderRadiusControl,
{
presets: settings2?.border?.radiusSizes,
values: borderRadiusValues,
onChange: (newValue) => {
setBorderRadius(newValue || void 0);
}
}
)
}
),
hasShadowControl && /* @__PURE__ */ (0, import_jsx_runtime367.jsxs)(
import_components201.__experimentalToolsPanelItem,
{
label: (0, import_i18n193.__)("Shadow"),
hasValue: hasShadow,
onDeselect: resetShadow,
isShownByDefault: defaultControls.shadow,
panelId,
children: [
hasBorderControl ? /* @__PURE__ */ (0, import_jsx_runtime367.jsx)(import_components201.BaseControl.VisualLabel, { as: "legend", children: (0, import_i18n193.__)("Shadow") }) : null,
/* @__PURE__ */ (0, import_jsx_runtime367.jsx)(
ShadowPopover,
{
shadow,
onShadowChange: setShadow,
settings: settings2
}
)
]
}
)
]
}
);
}
// packages/block-editor/build-module/components/global-styles/color-panel.mjs
var import_components202 = __toESM(require_components(), 1);
var import_element206 = __toESM(require_element(), 1);
var import_i18n194 = __toESM(require_i18n(), 1);
var import_jsx_runtime368 = __toESM(require_jsx_runtime(), 1);
function useHasColorPanel(settings2) {
const hasTextPanel = useHasTextPanel(settings2);
const hasBackgroundPanel = useHasBackgroundColorPanel(settings2);
const hasLinkPanel = useHasLinkPanel(settings2);
const hasHeadingPanel = useHasHeadingPanel(settings2);
const hasButtonPanel = useHasButtonPanel(settings2);
const hasCaptionPanel = useHasCaptionPanel(settings2);
return hasTextPanel || hasBackgroundPanel || 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_runtime368.jsx)(
import_components202.__experimentalToolsPanel,
{
label: label || (0, import_i18n194.__)("Elements"),
resetAll,
panelId,
hasInnerWrapper: true,
headingLevel: 3,
className: "color-block-support-panel",
__experimentalFirstVisibleItemClass: "first",
__experimentalLastVisibleItemClass: "last",
dropdownMenuProps,
children: /* @__PURE__ */ (0, import_jsx_runtime368.jsx)("div", { className: "color-block-support-panel__inner-wrapper", children })
}
);
}
var DEFAULT_CONTROLS6 = {
text: true,
background: true,
link: true,
heading: true,
button: true,
caption: true
};
var popoverProps = {
placement: "left-start",
offset: 36,
shift: true
};
var { Tabs: Tabs4 } = unlock(import_components202.privateApis);
var LabeledColorIndicators = ({ indicators, label }) => /* @__PURE__ */ (0, import_jsx_runtime368.jsxs)(import_components202.__experimentalHStack, { justify: "flex-start", children: [
/* @__PURE__ */ (0, import_jsx_runtime368.jsx)(import_components202.__experimentalZStack, { isLayered: false, offset: -8, children: indicators.map((indicator, index) => /* @__PURE__ */ (0, import_jsx_runtime368.jsx)(import_components202.Flex, { expanded: false, children: /* @__PURE__ */ (0, import_jsx_runtime368.jsx)(import_components202.ColorIndicator, { colorValue: indicator }) }, index)) }),
/* @__PURE__ */ (0, import_jsx_runtime368.jsx)(import_components202.FlexItem, { className: "block-editor-panel-color-gradient-settings__color-name", children: label })
] });
function ColorPanelTab({
isGradient,
inheritedValue,
userValue,
setValue,
colorGradientControlSettings
}) {
return /* @__PURE__ */ (0, import_jsx_runtime368.jsx)(
control_default,
{
...colorGradientControlSettings,
showTitle: false,
enableAlpha: true,
__experimentalIsRenderedInSidebar: true,
colorValue: isGradient ? void 0 : inheritedValue,
gradientValue: isGradient ? inheritedValue : void 0,
onColorChange: isGradient ? void 0 : setValue,
onGradientChange: isGradient ? setValue : void 0,
clearable: inheritedValue === userValue,
headingLevel: 3
}
);
}
function ColorPanelDropdown({
label,
hasValue,
resetValue,
isShownByDefault,
indicators,
tabs,
colorGradientControlSettings,
panelId
}) {
const currentTab = tabs.find((tab) => tab.userValue !== void 0);
const { key: firstTabKey, ...firstTab } = tabs[0] ?? {};
const colorGradientDropdownButtonRef = (0, import_element206.useRef)(void 0);
return /* @__PURE__ */ (0, import_jsx_runtime368.jsx)(
import_components202.__experimentalToolsPanelItem,
{
className: "block-editor-tools-panel-color-gradient-settings__item",
hasValue,
label,
onDeselect: resetValue,
isShownByDefault,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime368.jsx)(
import_components202.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 }
),
"aria-expanded": isOpen,
ref: colorGradientDropdownButtonRef
};
return /* @__PURE__ */ (0, import_jsx_runtime368.jsxs)(import_jsx_runtime368.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime368.jsx)(import_components202.Button, { ...toggleProps, __next40pxDefaultSize: true, children: /* @__PURE__ */ (0, import_jsx_runtime368.jsx)(
LabeledColorIndicators,
{
indicators,
label
}
) }),
hasValue() && /* @__PURE__ */ (0, import_jsx_runtime368.jsx)(
import_components202.Button,
{
__next40pxDefaultSize: true,
label: (0, import_i18n194.__)("Reset"),
className: "block-editor-panel-color-gradient-settings__reset",
size: "small",
icon: reset_default,
onClick: () => {
resetValue();
if (isOpen) {
onToggle();
}
colorGradientDropdownButtonRef.current?.focus();
}
}
)
] });
},
renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime368.jsx)(import_components202.__experimentalDropdownContentWrapper, { paddingSize: "none", children: /* @__PURE__ */ (0, import_jsx_runtime368.jsxs)("div", { className: "block-editor-panel-color-gradient-settings__dropdown-content", children: [
tabs.length === 1 && /* @__PURE__ */ (0, import_jsx_runtime368.jsx)(
ColorPanelTab,
{
...firstTab,
colorGradientControlSettings
},
firstTabKey
),
tabs.length > 1 && /* @__PURE__ */ (0, import_jsx_runtime368.jsxs)(Tabs4, { defaultTabId: currentTab?.key, children: [
/* @__PURE__ */ (0, import_jsx_runtime368.jsx)(Tabs4.TabList, { children: tabs.map((tab) => /* @__PURE__ */ (0, import_jsx_runtime368.jsx)(
Tabs4.Tab,
{
tabId: tab.key,
children: tab.label
},
tab.key
)) }),
tabs.map((tab) => {
const { key: tabKey, ...restTabProps } = tab;
return /* @__PURE__ */ (0, import_jsx_runtime368.jsx)(
Tabs4.TabPanel,
{
tabId: tabKey,
focusable: false,
children: /* @__PURE__ */ (0, import_jsx_runtime368.jsx)(
ColorPanelTab,
{
...restTabProps,
colorGradientControlSettings
},
tabKey
)
},
tabKey
);
})
] })
] }) })
}
)
}
);
}
function ColorPanel({
as: Wrapper = ColorToolsPanel,
value,
onChange,
inheritedValue = value,
settings: settings2,
panelId,
defaultControls = DEFAULT_CONTROLS6,
label,
children
}) {
const colors2 = useColorsPerOrigin(settings2);
const gradients = useGradientsPerOrigin(settings2);
const areCustomSolidsEnabled = settings2?.color?.custom;
const areCustomGradientsEnabled = settings2?.color?.customGradient;
const hasSolidColors = colors2.length > 0 || areCustomSolidsEnabled;
const hasGradientColors = gradients.length > 0 || areCustomGradientsEnabled;
const decodeValue = (rawValue) => getValueFromVariable({ settings: settings2 }, "", rawValue);
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 encodeGradientValue = (gradientValue) => {
const allGradients = gradients.flatMap(
({ gradients: originGradients }) => originGradients
);
const gradientObject = allGradients.find(
({ gradient: gradient2 }) => gradient2 === gradientValue
);
return gradientObject ? "var:preset|gradient|" + gradientObject.slug : gradientValue;
};
const showBackgroundPanel = useHasBackgroundColorPanel(settings2);
const backgroundColor = decodeValue(inheritedValue?.color?.background);
const userBackgroundColor = decodeValue(value?.color?.background);
const gradient = decodeValue(inheritedValue?.color?.gradient);
const userGradient = decodeValue(value?.color?.gradient);
const hasBackground = () => !!userBackgroundColor || !!userGradient;
const setBackgroundColor = (newColor) => {
const newValue = setImmutably(
value,
["color", "background"],
encodeColorValue(newColor)
);
newValue.color.gradient = void 0;
onChange(newValue);
};
const setGradient = (newGradient) => {
const newValue = setImmutably(
value,
["color", "gradient"],
encodeGradientValue(newGradient)
);
newValue.color.background = void 0;
onChange(newValue);
};
const resetBackground = () => {
const newValue = setImmutably(
value,
["color", "background"],
void 0
);
newValue.color.gradient = void 0;
onChange(newValue);
};
const showLinkPanel = useHasLinkPanel(settings2);
const linkColor = decodeValue(
inheritedValue?.elements?.link?.color?.text
);
const userLinkColor = decodeValue(value?.elements?.link?.color?.text);
const setLinkColor = (newColor) => {
onChange(
setImmutably(
value,
["elements", "link", "color", "text"],
encodeColorValue(newColor)
)
);
};
const hoverLinkColor = decodeValue(
inheritedValue?.elements?.link?.[":hover"]?.color?.text
);
const userHoverLinkColor = decodeValue(
value?.elements?.link?.[":hover"]?.color?.text
);
const setHoverLinkColor = (newColor) => {
onChange(
setImmutably(
value,
["elements", "link", ":hover", "color", "text"],
encodeColorValue(newColor)
)
);
};
const hasLink = () => !!userLinkColor || !!userHoverLinkColor;
const resetLink = () => {
let newValue = setImmutably(
value,
["elements", "link", ":hover", "color", "text"],
void 0
);
newValue = setImmutably(
newValue,
["elements", "link", "color", "text"],
void 0
);
onChange(newValue);
};
const showTextPanel = useHasTextPanel(settings2);
const textColor = decodeValue(inheritedValue?.color?.text);
const userTextColor = decodeValue(value?.color?.text);
const hasTextColor = () => !!userTextColor;
const setTextColor = (newColor) => {
let changedObject = setImmutably(
value,
["color", "text"],
encodeColorValue(newColor)
);
if (textColor === linkColor) {
changedObject = setImmutably(
changedObject,
["elements", "link", "color", "text"],
encodeColorValue(newColor)
);
}
onChange(changedObject);
};
const resetTextColor = () => setTextColor(void 0);
const elements = [
{
name: "caption",
label: (0, import_i18n194.__)("Captions"),
showPanel: useHasCaptionPanel(settings2)
},
{
name: "button",
label: (0, import_i18n194.__)("Button"),
showPanel: useHasButtonPanel(settings2)
},
{
name: "heading",
label: (0, import_i18n194.__)("Heading"),
showPanel: useHasHeadingPanel(settings2)
},
{
name: "h1",
label: (0, import_i18n194.__)("H1"),
showPanel: useHasHeadingPanel(settings2)
},
{
name: "h2",
label: (0, import_i18n194.__)("H2"),
showPanel: useHasHeadingPanel(settings2)
},
{
name: "h3",
label: (0, import_i18n194.__)("H3"),
showPanel: useHasHeadingPanel(settings2)
},
{
name: "h4",
label: (0, import_i18n194.__)("H4"),
showPanel: useHasHeadingPanel(settings2)
},
{
name: "h5",
label: (0, import_i18n194.__)("H5"),
showPanel: useHasHeadingPanel(settings2)
},
{
name: "h6",
label: (0, import_i18n194.__)("H6"),
showPanel: useHasHeadingPanel(settings2)
}
];
const resetAllFilter = (0, import_element206.useCallback)(
(previousValue) => {
return {
...previousValue,
color: void 0,
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 = [
showTextPanel && {
key: "text",
label: (0, import_i18n194.__)("Text"),
hasValue: hasTextColor,
resetValue: resetTextColor,
isShownByDefault: defaultControls.text,
indicators: [textColor],
tabs: [
{
key: "text",
label: (0, import_i18n194.__)("Text"),
inheritedValue: textColor,
setValue: setTextColor,
userValue: userTextColor
}
]
},
showBackgroundPanel && {
key: "background",
label: (0, import_i18n194.__)("Background"),
hasValue: hasBackground,
resetValue: resetBackground,
isShownByDefault: defaultControls.background,
indicators: [gradient ?? backgroundColor],
tabs: [
hasSolidColors && {
key: "background",
label: (0, import_i18n194.__)("Color"),
inheritedValue: backgroundColor,
setValue: setBackgroundColor,
userValue: userBackgroundColor
},
hasGradientColors && {
key: "gradient",
label: (0, import_i18n194.__)("Gradient"),
inheritedValue: gradient,
setValue: setGradient,
userValue: userGradient,
isGradient: true
}
].filter(Boolean)
},
showLinkPanel && {
key: "link",
label: (0, import_i18n194.__)("Link"),
hasValue: hasLink,
resetValue: resetLink,
isShownByDefault: defaultControls.link,
indicators: [linkColor, hoverLinkColor],
tabs: [
{
key: "link",
label: (0, import_i18n194.__)("Default"),
inheritedValue: linkColor,
setValue: setLinkColor,
userValue: userLinkColor
},
{
key: "hover",
label: (0, import_i18n194.__)("Hover"),
inheritedValue: hoverLinkColor,
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 = setImmutably(
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) => {
onChange(
setImmutably(
value,
["elements", name, "color", "text"],
encodeColorValue(newTextColor)
)
);
};
const setElementBackgroundColor = (newBackgroundColor) => {
const newValue = setImmutably(
value,
["elements", name, "color", "background"],
encodeColorValue(newBackgroundColor)
);
newValue.elements[name].color.gradient = void 0;
onChange(newValue);
};
const setElementGradient = (newGradient) => {
const newValue = setImmutably(
value,
["elements", name, "color", "gradient"],
encodeGradientValue(newGradient)
);
newValue.elements[name].color.background = void 0;
onChange(newValue);
};
const supportsTextColor = true;
const supportsBackground = name !== "caption";
items.push({
key: name,
label: elementLabel,
hasValue: hasElement,
resetValue: resetElement,
isShownByDefault: defaultControls[name],
indicators: supportsTextColor && supportsBackground ? [
elementTextColor,
elementGradient ?? elementBackgroundColor
] : [
supportsTextColor ? elementTextColor : elementGradient ?? elementBackgroundColor
],
tabs: [
hasSolidColors && supportsTextColor && {
key: "text",
label: (0, import_i18n194.__)("Text"),
inheritedValue: elementTextColor,
setValue: setElementTextColor,
userValue: elementTextUserColor
},
hasSolidColors && supportsBackground && {
key: "background",
label: (0, import_i18n194.__)("Background"),
inheritedValue: elementBackgroundColor,
setValue: setElementBackgroundColor,
userValue: elementBackgroundUserColor
},
hasGradientColors && supportsBackground && {
key: "gradient",
label: (0, import_i18n194.__)("Gradient"),
inheritedValue: elementGradient,
setValue: setElementGradient,
userValue: elementGradientUserColor,
isGradient: true
}
].filter(Boolean)
});
});
return /* @__PURE__ */ (0, import_jsx_runtime368.jsxs)(
Wrapper,
{
resetAllFilter,
value,
onChange,
panelId,
label,
children: [
items.map((item) => {
const { key, ...restItem } = item;
return /* @__PURE__ */ (0, import_jsx_runtime368.jsx)(
ColorPanelDropdown,
{
...restItem,
colorGradientControlSettings: {
colors: colors2,
disableCustomColors: !areCustomSolidsEnabled,
gradients,
disableCustomGradients: !areCustomGradientsEnabled
},
panelId
},
key
);
}),
children
]
}
);
}
// packages/block-editor/build-module/components/global-styles/filters-panel.mjs
var import_components203 = __toESM(require_components(), 1);
var import_i18n195 = __toESM(require_i18n(), 1);
var import_element207 = __toESM(require_element(), 1);
var import_jsx_runtime369 = __toESM(require_jsx_runtime(), 1);
var EMPTY_ARRAY13 = [];
function useMultiOriginColorPresets(settings2, { presetSetting, defaultSetting }) {
const disableDefault = !settings2?.color?.[defaultSetting];
const userPresets = settings2?.color?.[presetSetting]?.custom || EMPTY_ARRAY13;
const themePresets = settings2?.color?.[presetSetting]?.theme || EMPTY_ARRAY13;
const defaultPresets = settings2?.color?.[presetSetting]?.default || EMPTY_ARRAY13;
return (0, import_element207.useMemo)(
() => [
...userPresets,
...themePresets,
...disableDefault ? EMPTY_ARRAY13 : 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_runtime369.jsx)(
import_components203.__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_runtime369.jsxs)(import_components203.__experimentalHStack, { justify: "flex-start", children: [
/* @__PURE__ */ (0, import_jsx_runtime369.jsx)(import_components203.__experimentalZStack, { isLayered: false, offset: -8, children: /* @__PURE__ */ (0, import_jsx_runtime369.jsx)(import_components203.Flex, { expanded: false, children: indicator === "unset" || !indicator ? /* @__PURE__ */ (0, import_jsx_runtime369.jsx)(import_components203.ColorIndicator, { className: "block-editor-duotone-control__unset-indicator" }) : /* @__PURE__ */ (0, import_jsx_runtime369.jsx)(import_components203.DuotoneSwatch, { values: indicator }) }) }),
/* @__PURE__ */ (0, import_jsx_runtime369.jsx)(import_components203.FlexItem, { title: label, children: label })
] });
var renderToggle2 = (duotone, resetDuotone) => ({ onToggle, isOpen }) => {
const duotoneButtonRef = (0, import_element207.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_runtime369.jsxs)(import_jsx_runtime369.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime369.jsx)(import_components203.Button, { __next40pxDefaultSize: true, ...toggleProps, children: /* @__PURE__ */ (0, import_jsx_runtime369.jsx)(
LabeledColorIndicator2,
{
indicator: duotone,
label: (0, import_i18n195.__)("Duotone")
}
) }),
duotone && /* @__PURE__ */ (0, import_jsx_runtime369.jsx)(
import_components203.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(
setImmutably(value, ["filter", "duotone"], duotoneValue)
);
};
const hasDuotone = () => !!value?.filter?.duotone;
const resetDuotone = () => setDuotone(void 0);
const resetAllFilter = (0, import_element207.useCallback)((previousValue) => {
return {
...previousValue,
filter: {
...previousValue.filter,
duotone: void 0
}
};
}, []);
return /* @__PURE__ */ (0, import_jsx_runtime369.jsx)(
Wrapper,
{
resetAllFilter,
value,
onChange,
panelId,
children: hasDuotoneEnabled && /* @__PURE__ */ (0, import_jsx_runtime369.jsx)(
import_components203.__experimentalToolsPanelItem,
{
label: (0, import_i18n195.__)("Duotone"),
hasValue: hasDuotone,
onDeselect: resetDuotone,
isShownByDefault: defaultControls.duotone,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime369.jsx)(
import_components203.Dropdown,
{
popoverProps: popoverProps2,
className: "block-editor-global-styles-filters-panel__dropdown",
renderToggle: renderToggle2(duotone, resetDuotone),
renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime369.jsx)(import_components203.__experimentalDropdownContentWrapper, { paddingSize: "small", children: /* @__PURE__ */ (0, import_jsx_runtime369.jsxs)(import_components203.MenuGroup, { label: (0, import_i18n195.__)("Duotone"), children: [
/* @__PURE__ */ (0, import_jsx_runtime369.jsx)("p", { children: (0, import_i18n195.__)(
"Create a two-tone color effect without losing your original image."
) }),
/* @__PURE__ */ (0, import_jsx_runtime369.jsx)(
import_components203.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_components204 = __toESM(require_components(), 1);
var import_i18n196 = __toESM(require_i18n(), 1);
var import_jsx_runtime370 = __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_runtime370.jsx)(import_jsx_runtime370.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime370.jsx)(
import_components204.__experimentalToolsPanel,
{
label: (0, import_i18n196._x)("Settings", "Image settings"),
resetAll: resetLightbox,
panelId,
dropdownMenuProps,
children: /* @__PURE__ */ (0, import_jsx_runtime370.jsx)(
import_components204.__experimentalToolsPanelItem,
{
hasValue: () => !!value?.lightbox,
label: (0, import_i18n196.__)("Enlarge on click"),
onDeselect: resetLightbox,
isShownByDefault: true,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime370.jsx)(
import_components204.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_components205 = __toESM(require_components(), 1);
var import_element208 = __toESM(require_element(), 1);
var import_i18n197 = __toESM(require_i18n(), 1);
var import_jsx_runtime371 = __toESM(require_jsx_runtime(), 1);
function AdvancedPanel({
value,
onChange,
inheritedValue = value
}) {
const [cssError, setCSSError] = (0, import_element208.useState)(null);
const customCSS = inheritedValue?.css;
function handleOnChange(newValue) {
onChange({
...value,
css: newValue
});
if (cssError) {
const [transformed] = transform_styles_default(
[{ css: newValue }],
".for-validation-only"
);
if (transformed) {
setCSSError(null);
}
}
}
function handleOnBlur(event) {
if (!event?.target?.value) {
setCSSError(null);
return;
}
const [transformed] = transform_styles_default(
[{ css: event.target.value }],
".for-validation-only"
);
setCSSError(
transformed === null ? (0, import_i18n197.__)("There is an error with your CSS structure.") : null
);
}
return /* @__PURE__ */ (0, import_jsx_runtime371.jsxs)(import_components205.__experimentalVStack, { spacing: 3, children: [
cssError && /* @__PURE__ */ (0, import_jsx_runtime371.jsx)(import_components205.Notice, { status: "error", onRemove: () => setCSSError(null), children: cssError }),
/* @__PURE__ */ (0, import_jsx_runtime371.jsx)(
import_components205.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
}
)
] });
}
// packages/block-editor/build-module/components/global-styles/background-panel.mjs
var import_components207 = __toESM(require_components(), 1);
var import_element210 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/background-image-control/index.mjs
var import_components206 = __toESM(require_components(), 1);
var import_i18n198 = __toESM(require_i18n(), 1);
var import_notices12 = __toESM(require_notices(), 1);
var import_url12 = __toESM(require_url(), 1);
var import_element209 = __toESM(require_element(), 1);
var import_data163 = __toESM(require_data(), 1);
var import_dom38 = __toESM(require_dom(), 1);
var import_blob3 = __toESM(require_blob(), 1);
var import_jsx_runtime372 = __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 noop18 = () => {
};
var focusToggleButton = (containerRef) => {
window.requestAnimationFrame(() => {
const [toggleButton] = import_dom38.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 = noop18
}) {
const { isOpen, ...restToggleProps } = toggleProps;
(0, import_element209.useEffect)(() => {
if (typeof isOpen !== "undefined") {
onToggleCallback(isOpen);
}
}, [isOpen, onToggleCallback]);
const renderPreviewContent = () => {
return /* @__PURE__ */ (0, import_jsx_runtime372.jsxs)(
import_components206.__experimentalHStack,
{
justify: "flex-start",
as: "span",
className: "block-editor-global-styles-background-panel__inspector-preview-inner",
children: [
imgUrl && /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(
"span",
{
className: "block-editor-global-styles-background-panel__inspector-image-indicator-wrapper",
"aria-hidden": true,
children: /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(
"span",
{
className: "block-editor-global-styles-background-panel__inspector-image-indicator",
style: {
backgroundImage: `url(${imgUrl})`
}
}
)
}
),
/* @__PURE__ */ (0, import_jsx_runtime372.jsxs)(import_components206.FlexItem, { as: "span", style: imgUrl ? {} : { flexGrow: 1 }, children: [
/* @__PURE__ */ (0, import_jsx_runtime372.jsx)(
import_components206.__experimentalTruncate,
{
numberOfLines: 1,
className: "block-editor-global-styles-background-panel__inspector-media-replace-title",
children: label
}
),
/* @__PURE__ */ (0, import_jsx_runtime372.jsx)(import_components206.VisuallyHidden, { as: "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_runtime372.jsx)(import_components206.Button, { __next40pxDefaultSize: true, ...restToggleProps, children: renderPreviewContent() }) : renderPreviewContent();
}
function BackgroundControlsPanel({
label,
filename,
url: imgUrl,
children,
onToggle: onToggleCallback = noop18,
hasImageValue,
onReset,
containerRef
}) {
if (!hasImageValue) {
return;
}
const imgLabel = label || (0, import_url12.getFilename)(imgUrl) || (0, import_i18n198.__)("Add background image");
return /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(
import_components206.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_runtime372.jsxs)(import_jsx_runtime372.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime372.jsx)(
InspectorImagePreviewItem,
{
imgUrl,
filename,
label: imgLabel,
toggleProps,
as: "button",
onToggleCallback
}
),
onReset && /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(
import_components206.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_runtime372.jsx)(
import_components206.__experimentalDropdownContentWrapper,
{
className: "block-editor-global-styles-background-panel__dropdown-content-wrapper",
paddingSize: "medium",
children
}
)
}
);
}
function LoadingSpinner() {
return /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(import_components206.Placeholder, { className: "block-editor-global-styles-background-panel__loading", children: /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(import_components206.Spinner, {}) });
}
function BackgroundImageControls({
onChange,
style,
inheritedValue,
onRemoveImage = noop18,
onResetImage = noop18,
displayInPanel,
defaultValues,
containerRef
}) {
const [isUploading2, setIsUploading] = (0, import_element209.useState)(false);
const { getSettings: getSettings8 } = (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(
setImmutably(
style,
["background", "backgroundImage"],
void 0
)
);
const onSelectMedia = (media) => {
if (!media || !media.url) {
resetBackgroundImage();
setIsUploading(false);
return;
}
if ((0, import_blob3.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(
setImmutably(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) => {
getSettings8().mediaUpload({
allowedTypes: [IMAGE_BACKGROUND_TYPE],
filesList,
onFileChange([image]) {
onSelectMedia(image);
},
onError: onUploadError,
multiple: false
});
};
const hasValue = hasBackgroundImageValue(style);
const onRemove = () => onChange(
setImmutably(style, ["background"], {
backgroundImage: "none"
})
);
const canRemove = !hasValue && hasBackgroundImageValue(inheritedValue);
const imgLabel = title || (0, import_url12.getFilename)(url) || (0, import_i18n198.__)("Add background image");
return /* @__PURE__ */ (0, import_jsx_runtime372.jsxs)("div", { className: "block-editor-global-styles-background-panel__image-tools-panel-item", children: [
isUploading2 && /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(LoadingSpinner, {}),
/* @__PURE__ */ (0, import_jsx_runtime372.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_runtime372.jsx)(
InspectorImagePreviewItem,
{
imgUrl: url,
filename: title,
label: imgLabel
}
),
renderToggle: (props) => /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(import_components206.Button, { ...props, __next40pxDefaultSize: true }),
onError: onUploadError,
onReset: () => {
focusToggleButton(containerRef);
onResetImage();
},
children: canRemove && /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(
import_components206.MenuItem,
{
onClick: () => {
focusToggleButton(containerRef);
onRemove();
onRemoveImage();
},
children: (0, import_i18n198.__)("Remove")
}
)
}
),
/* @__PURE__ */ (0, import_jsx_runtime372.jsx)(
import_components206.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(
setImmutably(style, ["background"], {
...style?.background,
backgroundPosition: nextPosition,
backgroundRepeat: nextRepeat,
backgroundSize: next
})
);
};
const updateBackgroundPosition = (next) => {
onChange(
setImmutably(
style,
["background", "backgroundPosition"],
coordsToBackgroundPosition(next)
)
);
};
const toggleIsRepeated = () => onChange(
setImmutably(
style,
["background", "backgroundRepeat"],
repeatCheckedValue === true ? "no-repeat" : "repeat"
)
);
const toggleScrollWithPage = () => onChange(
setImmutably(
style,
["background", "backgroundAttachment"],
attachmentValue === "fixed" ? "scroll" : "fixed"
)
);
const backgroundPositionValue = !positionValue && isUploadedImage && "contain" === sizeValue ? defaultValues?.backgroundPosition : positionValue;
return /* @__PURE__ */ (0, import_jsx_runtime372.jsxs)(import_components206.__experimentalVStack, { spacing: 3, className: "single-column", children: [
/* @__PURE__ */ (0, import_jsx_runtime372.jsx)(
import_components206.FocalPointPicker,
{
label: (0, import_i18n198.__)("Focal point"),
url: imageValue,
value: backgroundPositionToCoords(backgroundPositionValue),
onChange: updateBackgroundPosition
}
),
/* @__PURE__ */ (0, import_jsx_runtime372.jsx)(
import_components206.ToggleControl,
{
label: (0, import_i18n198.__)("Fixed background"),
checked: attachmentValue === "fixed",
onChange: toggleScrollWithPage
}
),
/* @__PURE__ */ (0, import_jsx_runtime372.jsxs)(
import_components206.__experimentalToggleGroupControl,
{
size: "__unstable-large",
label: (0, import_i18n198.__)("Size"),
value: currentValueForToggle,
onChange: updateBackgroundSize,
isBlock: true,
help: backgroundSizeHelpText(
sizeValue || defaultValues?.backgroundSize
),
children: [
/* @__PURE__ */ (0, import_jsx_runtime372.jsx)(
import_components206.__experimentalToggleGroupControlOption,
{
value: "cover",
label: (0, import_i18n198._x)(
"Cover",
"Size option for background image control"
)
},
"cover"
),
/* @__PURE__ */ (0, import_jsx_runtime372.jsx)(
import_components206.__experimentalToggleGroupControlOption,
{
value: "contain",
label: (0, import_i18n198._x)(
"Contain",
"Size option for background image control"
)
},
"contain"
),
/* @__PURE__ */ (0, import_jsx_runtime372.jsx)(
import_components206.__experimentalToggleGroupControlOption,
{
value: "auto",
label: (0, import_i18n198._x)(
"Tile",
"Size option for background image control"
)
},
"tile"
)
]
}
),
/* @__PURE__ */ (0, import_jsx_runtime372.jsxs)(import_components206.__experimentalHStack, { justify: "flex-start", spacing: 2, as: "span", children: [
/* @__PURE__ */ (0, import_jsx_runtime372.jsx)(
import_components206.__experimentalUnitControl,
{
"aria-label": (0, import_i18n198.__)("Background image width"),
onChange: updateBackgroundSize,
value: sizeValue,
size: "__unstable-large",
__unstableInputWidth: "100px",
min: 0,
placeholder: (0, import_i18n198.__)("Auto"),
disabled: currentValueForToggle !== "auto" || currentValueForToggle === void 0
}
),
/* @__PURE__ */ (0, import_jsx_runtime372.jsx)(
import_components206.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: getSettings8 } = select3(store);
const _settings = getSettings8();
return {
globalStyles: _settings[globalStylesDataKey],
_links: _settings[globalStylesLinksDataKey]
};
}, []);
const resolvedInheritedValue = (0, import_element209.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(setImmutably(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_element209.useState)(false);
const containerRef = (0, import_element209.useRef)();
return /* @__PURE__ */ (0, import_jsx_runtime372.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_runtime372.jsx)(
BackgroundControlsPanel,
{
label: title,
filename: title,
url,
onToggle: setIsDropDownOpen,
hasImageValue,
onReset: resetBackground,
containerRef,
children: /* @__PURE__ */ (0, import_jsx_runtime372.jsxs)(import_components206.__experimentalVStack, { spacing: 3, className: "single-column", children: [
/* @__PURE__ */ (0, import_jsx_runtime372.jsx)(
BackgroundImageControls,
{
onChange,
style: value,
inheritedValue: resolvedInheritedValue,
displayInPanel: true,
onResetImage: () => {
setIsDropDownOpen(false);
resetBackground();
},
onRemoveImage: () => setIsDropDownOpen(false),
defaultValues,
containerRef
}
),
/* @__PURE__ */ (0, import_jsx_runtime372.jsx)(
BackgroundSizeControls,
{
onChange,
style: value,
defaultValues,
inheritedValue: resolvedInheritedValue
}
)
] })
}
) : /* @__PURE__ */ (0, import_jsx_runtime372.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_i18n199 = __toESM(require_i18n(), 1);
var import_jsx_runtime373 = __toESM(require_jsx_runtime(), 1);
var DEFAULT_CONTROLS8 = {
backgroundImage: true
};
function useHasBackgroundPanel(settings2) {
return import_element210.Platform.OS === "web" && settings2?.background?.backgroundImage;
}
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 BackgroundToolsPanel({
resetAllFilter,
onChange,
value,
panelId,
children,
headerLabel
}) {
const dropdownMenuProps = useToolsPanelDropdownMenuProps();
const resetAll = () => {
const updatedValue = resetAllFilter(value);
onChange(updatedValue);
};
return /* @__PURE__ */ (0, import_jsx_runtime373.jsx)(
import_components207.__experimentalToolsPanel,
{
label: headerLabel,
resetAll,
panelId,
dropdownMenuProps,
children
}
);
}
function BackgroundImagePanel2({
as: Wrapper = BackgroundToolsPanel,
value,
onChange,
inheritedValue,
settings: settings2,
panelId,
defaultControls = DEFAULT_CONTROLS8,
defaultValues = {},
headerLabel = (0, import_i18n199.__)("Background image")
}) {
const showBackgroundImageControl = useHasBackgroundPanel(settings2);
const resetBackground = () => onChange(setImmutably(value, ["background"], {}));
const resetAllFilter = (0, import_element210.useCallback)((previousValue) => {
return {
...previousValue,
background: {}
};
}, []);
return /* @__PURE__ */ (0, import_jsx_runtime373.jsx)(
Wrapper,
{
resetAllFilter,
value,
onChange,
panelId,
headerLabel,
children: showBackgroundImageControl && /* @__PURE__ */ (0, import_jsx_runtime373.jsx)(
import_components207.__experimentalToolsPanelItem,
{
hasValue: () => !!value?.background,
label: (0, import_i18n199.__)("Image"),
onDeselect: resetBackground,
isShownByDefault: defaultControls.backgroundImage,
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime373.jsx)(
BackgroundImagePanel,
{
value,
onChange,
settings: settings2,
inheritedValue,
defaultControls,
defaultValues
}
)
}
)
}
);
}
// packages/block-editor/build-module/hooks/border.mjs
var import_i18n200 = __toESM(require_i18n(), 1);
var import_jsx_runtime374 = __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_components208.__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_components208.__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_element211.useCallback)(
(attributes) => {
const existingStyle = attributesToStyle(attributes);
const updatedStyle = resetAllFilter(existingStyle);
return {
...attributes,
...styleToAttributes(updatedStyle)
};
},
[resetAllFilter]
);
return /* @__PURE__ */ (0, import_jsx_runtime374.jsx)(
inspector_controls_default,
{
group: "border",
resetAllFilter: attributesResetAllFilter,
label,
children
}
);
}
function BorderPanel2({ clientId, name, setAttributes, settings: settings2 }) {
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 value = (0, import_element211.useMemo)(() => {
return attributesToStyle({ style, borderColor });
}, [style, borderColor]);
const onChange = (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_runtime374.jsx)(
BorderPanel,
{
as: BordersInspectorControl,
panelId: clientId,
settings: settings2,
value,
onChange,
defaultControls
}
);
}
function hasBorderSupport2(blockName, feature = "any") {
if (import_element211.Platform.OS !== "web") {
return false;
}
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_i18n200.__)("Border & Shadow");
}
if (hasShadowControl) {
return (0, import_i18n200.__)("Shadow");
}
return (0, import_i18n200.__)("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_hooks11.addFilter)(
"blocks.registerBlockType",
"core/border/addAttributes",
addAttributes
);
// packages/block-editor/build-module/hooks/color.mjs
var import_hooks12 = __toESM(require_hooks(), 1);
var import_blocks93 = __toESM(require_blocks(), 1);
var import_element214 = __toESM(require_element(), 1);
var import_data166 = __toESM(require_data(), 1);
// packages/block-editor/build-module/hooks/background.mjs
var import_blocks92 = __toESM(require_blocks(), 1);
var import_data165 = __toESM(require_data(), 1);
var import_element212 = __toESM(require_element(), 1);
var import_jsx_runtime375 = __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_blocks92.getBlockSupport)(blockName, BACKGROUND_SUPPORT_KEY);
if (support === true) {
return true;
}
if (feature === "any") {
return !!support?.backgroundImage || !!support?.backgroundSize || !!support?.backgroundRepeat;
}
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) ? "has-background" : "";
}
function BackgroundInspectorControl({ children }) {
const resetAllFilter = (0, import_element212.useCallback)((attributes) => {
return {
...attributes,
style: {
...attributes.style,
background: void 0
}
};
}, []);
return /* @__PURE__ */ (0, import_jsx_runtime375.jsx)(inspector_controls_default, { group: "background", resetAllFilter, children });
}
function BackgroundImagePanel3({
clientId,
name,
setAttributes,
settings: settings2
}) {
const { style, inheritedValue } = (0, import_data165.useSelect)(
(select3) => {
const { getBlockAttributes: getBlockAttributes3, getSettings: getSettings8 } = select3(store);
const _settings = getSettings8();
return {
style: getBlockAttributes3(clientId)?.style,
/*
* To ensure we pass down the right inherited values:
* @TODO 1. Pass inherited value down to all block style controls,
* See: packages/block-editor/src/hooks/style.js
* @TODO 2. Add support for block style variations,
* See implementation: packages/block-editor/src/hooks/block-style-variation.js
*/
inheritedValue: _settings[globalStylesDataKey]?.blocks?.[name]
};
},
[clientId, name]
);
if (!useHasBackgroundPanel(settings2) || !hasBackgroundSupport(name, "backgroundImage")) {
return null;
}
const onChange = (newStyle) => {
setAttributes({
style: cleanEmptyObject(newStyle)
});
};
const updatedSettings = {
...settings2,
background: {
...settings2.background,
backgroundSize: settings2?.background?.backgroundSize && hasBackgroundSupport(name, "backgroundSize")
}
};
const defaultControls = (0, import_blocks92.getBlockSupport)(name, [
BACKGROUND_SUPPORT_KEY,
"defaultControls"
]);
return /* @__PURE__ */ (0, import_jsx_runtime375.jsx)(
BackgroundImagePanel2,
{
inheritedValue,
as: BackgroundInspectorControl,
panelId: clientId,
defaultValues: BACKGROUND_BLOCK_DEFAULT_VALUES2,
settings: updatedSettings,
onChange,
defaultControls,
value: style
}
);
}
var background_default = {
useBlockProps: useBlockProps5,
attributeKeys: ["style"],
hasSupport: hasBackgroundSupport
};
// packages/block-editor/build-module/hooks/contrast-checker.mjs
var import_element213 = __toESM(require_element(), 1);
var import_jsx_runtime376 = __toESM(require_jsx_runtime(), 1);
function getComputedValue(node, property) {
return node.ownerDocument.defaultView.getComputedStyle(node).getPropertyValue(property);
}
function getBlockElementColors(blockEl) {
if (!blockEl) {
return {};
}
const firstLinkElement = blockEl.querySelector("a");
const linkColor = !!firstLinkElement?.innerText ? getComputedValue(firstLinkElement, "color") : void 0;
const textColor = getComputedValue(blockEl, "color");
let backgroundColorNode = blockEl;
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 reducer3(prevColors, newColors) {
const hasChanged = Object.keys(newColors).some(
(key) => prevColors[key] !== newColors[key]
);
return hasChanged ? newColors : prevColors;
}
function BlockColorContrastChecker({ clientId }) {
const blockEl = useBlockElement(clientId);
const [colors2, setColors] = (0, import_element213.useReducer)(reducer3, {});
(0, import_element213.useLayoutEffect)(() => {
if (!blockEl) {
return;
}
function updateColors() {
setColors(getBlockElementColors(blockEl));
}
window.requestAnimationFrame(
() => window.requestAnimationFrame(updateColors)
);
});
return /* @__PURE__ */ (0, import_jsx_runtime376.jsx)(
contrast_checker_default,
{
backgroundColor: colors2.backgroundColor,
textColor: colors2.textColor,
linkColor: colors2.linkColor,
enableAlphaChecker: true
}
);
}
// packages/block-editor/build-module/hooks/color.mjs
var import_jsx_runtime377 = __toESM(require_jsx_runtime(), 1);
var COLOR_SUPPORT_KEY2 = "color";
var hasColorSupport = (blockNameOrType) => {
const colorSupport = (0, import_blocks93.getBlockSupport)(blockNameOrType, COLOR_SUPPORT_KEY2);
return colorSupport && (colorSupport.link === true || colorSupport.gradient === true || colorSupport.background !== false || colorSupport.text !== false);
};
var hasLinkColorSupport = (blockType) => {
if (import_element214.Platform.OS !== "web") {
return false;
}
const colorSupport = (0, import_blocks93.getBlockSupport)(blockType, COLOR_SUPPORT_KEY2);
return colorSupport !== null && typeof colorSupport === "object" && !!colorSupport.link;
};
var hasGradientSupport2 = (blockNameOrType) => {
const colorSupport = (0, import_blocks93.getBlockSupport)(blockNameOrType, COLOR_SUPPORT_KEY2);
return colorSupport !== null && typeof colorSupport === "object" && !!colorSupport.gradients;
};
var hasBackgroundColorSupport2 = (blockType) => {
const colorSupport = (0, import_blocks93.getBlockSupport)(blockType, COLOR_SUPPORT_KEY2);
return colorSupport && colorSupport.background !== false;
};
var hasTextColorSupport2 = (blockType) => {
const colorSupport = (0, import_blocks93.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 styleToAttributes2(style) {
const textColorValue = style?.color?.text;
const textColorSlug = textColorValue?.startsWith("var:preset|color|") ? textColorValue.substring("var:preset|color|".length) : void 0;
const backgroundColorValue = style?.color?.background;
const backgroundColorSlug = backgroundColorValue?.startsWith(
"var:preset|color|"
) ? backgroundColorValue.substring("var:preset|color|".length) : void 0;
const gradientValue = style?.color?.gradient;
const gradientSlug = gradientValue?.startsWith("var:preset|gradient|") ? gradientValue.substring("var:preset|gradient|".length) : void 0;
const updatedStyle = { ...style };
updatedStyle.color = {
...updatedStyle.color,
text: textColorSlug ? void 0 : textColorValue,
background: backgroundColorSlug ? void 0 : backgroundColorValue,
gradient: gradientSlug ? void 0 : gradientValue
};
return {
style: cleanEmptyObject(updatedStyle),
textColor: textColorSlug,
backgroundColor: backgroundColorSlug,
gradient: gradientSlug
};
}
function attributesToStyle2(attributes) {
return {
...attributes.style,
color: {
...attributes.style?.color,
text: attributes.textColor ? "var:preset|color|" + attributes.textColor : attributes.style?.color?.text,
background: attributes.backgroundColor ? "var:preset|color|" + attributes.backgroundColor : attributes.style?.color?.background,
gradient: attributes.gradient ? "var:preset|gradient|" + attributes.gradient : attributes.style?.color?.gradient
}
};
}
function ColorInspectorControl({ children, resetAllFilter }) {
const attributesResetAllFilter = (0, import_element214.useCallback)(
(attributes) => {
const existingStyle = attributesToStyle2(attributes);
const updatedStyle = resetAllFilter(existingStyle);
return {
...attributes,
...styleToAttributes2(updatedStyle)
};
},
[resetAllFilter]
);
return /* @__PURE__ */ (0, import_jsx_runtime377.jsx)(
inspector_controls_default,
{
group: "color",
resetAllFilter: attributesResetAllFilter,
children
}
);
}
function ColorEdit({
clientId,
name,
setAttributes,
settings: settings2,
asWrapper,
label,
defaultControls
}) {
const isEnabled = useHasColorPanel(settings2);
const { style, textColor, backgroundColor, gradient } = (0, import_data166.useSelect)(
(select3) => {
if (!isEnabled) {
return {};
}
const {
style: _style,
textColor: _textColor,
backgroundColor: _backgroundColor,
gradient: _gradient
} = select3(store).getBlockAttributes(clientId) || {};
return {
style: _style,
textColor: _textColor,
backgroundColor: _backgroundColor,
gradient: _gradient
};
},
[clientId, isEnabled]
);
const value = (0, import_element214.useMemo)(() => {
return attributesToStyle2({
style,
textColor,
backgroundColor,
gradient
});
}, [style, textColor, backgroundColor, gradient]);
const onChange = (newStyle) => {
setAttributes(styleToAttributes2(newStyle));
};
if (!isEnabled) {
return null;
}
defaultControls = defaultControls ? defaultControls : (0, import_blocks93.getBlockSupport)(name, [
COLOR_SUPPORT_KEY2,
"__experimentalDefaultControls"
]);
const enableContrastChecking = import_element214.Platform.OS === "web" && !value?.color?.gradient && (settings2?.color?.text || settings2?.color?.link) && // Contrast checking is enabled by default.
// Deactivating it requires `enableContrastChecker` to have
// an explicit value of `false`.
false !== (0, import_blocks93.getBlockSupport)(name, [
COLOR_SUPPORT_KEY2,
"enableContrastChecker"
]);
const Wrapper = asWrapper || ColorInspectorControl;
return /* @__PURE__ */ (0, import_jsx_runtime377.jsx)(
ColorPanel,
{
as: Wrapper,
panelId: clientId,
settings: settings2,
value,
onChange,
defaultControls,
label,
enableContrastChecker: false !== (0, import_blocks93.getBlockSupport)(name, [
COLOR_SUPPORT_KEY2,
"enableContrastChecker"
]),
children: enableContrastChecking && /* @__PURE__ */ (0, import_jsx_runtime377.jsx)(BlockColorContrastChecker, { clientId })
}
);
}
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_element214.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, index, 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,
index,
results
);
}
(0, import_hooks12.addFilter)(
"blocks.registerBlockType",
"core/color/addAttribute",
addAttributes2
);
(0, import_hooks12.addFilter)(
"blocks.switchToBlockType.transformedBlock",
"core/color/addTransforms",
addTransforms
);
// packages/block-editor/build-module/components/inspector-controls-tabs/styles-tab.mjs
var import_jsx_runtime378 = __toESM(require_jsx_runtime(), 1);
function SectionBlockColorControls({
blockName,
clientId,
contentClientIds
}) {
const settings2 = useBlockSettings(blockName);
const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data167.useDispatch)(store);
const { hasButton, hasHeading } = (0, import_data167.useSelect)(
(select3) => {
const blockNames = select3(store).getBlockNamesByClientId(
contentClientIds
);
return {
hasButton: blockNames.includes("core/button"),
hasHeading: blockNames.includes("core/heading")
};
},
[contentClientIds]
);
const setAttributes = (newAttributes) => {
updateBlockAttributes2(clientId, newAttributes);
};
return /* @__PURE__ */ (0, import_jsx_runtime378.jsx)(
ColorEdit,
{
clientId,
name: blockName,
settings: settings2,
setAttributes,
asWrapper: ColorToolsPanel,
label: (0, import_i18n201.__)("Color"),
defaultControls: {
text: true,
background: true,
button: hasButton,
heading: hasHeading
}
}
);
}
var StylesTab = ({
blockName,
clientId,
hasBlockStyles,
isSectionBlock: isSectionBlock2,
contentClientIds
}) => {
const borderPanelLabel = useBorderPanelLabel({ blockName });
return /* @__PURE__ */ (0, import_jsx_runtime378.jsxs)(import_jsx_runtime378.Fragment, { children: [
hasBlockStyles && /* @__PURE__ */ (0, import_jsx_runtime378.jsx)(block_styles_default, { clientId }),
isSectionBlock2 && window?.__experimentalContentOnlyPatternInsertion && /* @__PURE__ */ (0, import_jsx_runtime378.jsx)(
SectionBlockColorControls,
{
blockName,
clientId,
contentClientIds
}
),
!isSectionBlock2 && /* @__PURE__ */ (0, import_jsx_runtime378.jsxs)(import_jsx_runtime378.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime378.jsx)(
inspector_controls_default.Slot,
{
group: "color",
label: (0, import_i18n201.__)("Color"),
className: "color-block-support-panel__inner-wrapper"
}
),
/* @__PURE__ */ (0, import_jsx_runtime378.jsx)(
inspector_controls_default.Slot,
{
group: "background",
label: (0, import_i18n201.__)("Background image")
}
),
/* @__PURE__ */ (0, import_jsx_runtime378.jsx)(inspector_controls_default.Slot, { group: "filter" }),
/* @__PURE__ */ (0, import_jsx_runtime378.jsx)(
inspector_controls_default.Slot,
{
group: "typography",
label: (0, import_i18n201.__)("Typography")
}
),
/* @__PURE__ */ (0, import_jsx_runtime378.jsx)(
inspector_controls_default.Slot,
{
group: "dimensions",
label: (0, import_i18n201.__)("Dimensions")
}
),
/* @__PURE__ */ (0, import_jsx_runtime378.jsx)(
inspector_controls_default.Slot,
{
group: "border",
label: borderPanelLabel
}
),
/* @__PURE__ */ (0, import_jsx_runtime378.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_components210 = __toESM(require_components(), 1);
var import_i18n202 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/block-quick-navigation/index.mjs
var import_data168 = __toESM(require_data(), 1);
var import_components209 = __toESM(require_components(), 1);
var import_jsx_runtime379 = __toESM(require_jsx_runtime(), 1);
function BlockQuickNavigation({ clientIds, onSelect }) {
if (!clientIds.length) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime379.jsx)(import_components209.__experimentalVStack, { spacing: 1, children: clientIds.map((clientId) => /* @__PURE__ */ (0, import_jsx_runtime379.jsx)(
BlockQuickNavigationItem,
{
onSelect,
clientId
},
clientId
)) });
}
function BlockQuickNavigationItem({ clientId, onSelect }) {
const blockInformation = useBlockDisplayInformation(clientId);
const blockTitle = useBlockDisplayTitle({
clientId,
context: "list-view"
});
const { isSelected } = (0, import_data168.useSelect)(
(select3) => {
const { isBlockSelected: isBlockSelected2, hasSelectedInnerBlock: hasSelectedInnerBlock2 } = select3(store);
return {
isSelected: isBlockSelected2(clientId) || hasSelectedInnerBlock2(
clientId,
/* deep: */
true
)
};
},
[clientId]
);
const { selectBlock: selectBlock2 } = (0, import_data168.useDispatch)(store);
return /* @__PURE__ */ (0, import_jsx_runtime379.jsx)(
import_components209.Button,
{
__next40pxDefaultSize: true,
className: "block-editor-block-quick-navigation__item",
isPressed: isSelected,
onClick: async () => {
await selectBlock2(clientId);
if (onSelect) {
onSelect(clientId);
}
},
children: /* @__PURE__ */ (0, import_jsx_runtime379.jsxs)(import_components209.Flex, { children: [
/* @__PURE__ */ (0, import_jsx_runtime379.jsx)(import_components209.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime379.jsx)(block_icon_default, { icon: blockInformation?.icon }) }),
/* @__PURE__ */ (0, import_jsx_runtime379.jsx)(import_components209.FlexBlock, { style: { textAlign: "left" }, children: /* @__PURE__ */ (0, import_jsx_runtime379.jsx)(import_components209.__experimentalTruncate, { children: blockTitle }) })
] })
}
);
}
// packages/block-editor/build-module/components/inspector-controls-tabs/content-tab.mjs
var import_jsx_runtime380 = __toESM(require_jsx_runtime(), 1);
var ContentTab = ({ contentClientIds }) => {
if (!contentClientIds || contentClientIds.length === 0) {
return null;
}
const shouldShowBlockFields = window?.__experimentalContentOnlyInspectorFields;
return /* @__PURE__ */ (0, import_jsx_runtime380.jsx)(import_jsx_runtime380.Fragment, { children: !shouldShowBlockFields && /* @__PURE__ */ (0, import_jsx_runtime380.jsx)(import_components210.PanelBody, { title: (0, import_i18n202.__)("Content"), children: /* @__PURE__ */ (0, import_jsx_runtime380.jsx)(BlockQuickNavigation, { clientIds: contentClientIds }) }) });
};
var content_tab_default = ContentTab;
// packages/block-editor/build-module/components/inspector-controls-tabs/index.mjs
var import_jsx_runtime381 = __toESM(require_jsx_runtime(), 1);
var { Tabs: Tabs5 } = unlock(import_components211.privateApis);
function InspectorControlsTabs({
blockName,
clientId,
hasBlockStyles,
tabs,
isSectionBlock: isSectionBlock2,
contentClientIds
}) {
const showIconLabels = (0, import_data169.useSelect)((select3) => {
return select3(import_preferences5.store).get("core", "showIconLabels");
}, []);
const [selectedTabId, setSelectedTabId] = (0, import_element215.useState)(tabs[0]?.name);
const hasUserSelectionRef = (0, import_element215.useRef)(false);
(0, import_element215.useEffect)(() => {
hasUserSelectionRef.current = false;
}, [clientId]);
(0, import_element215.useEffect)(() => {
if (!tabs?.length || hasUserSelectionRef.current) {
return;
}
const firstTabName = tabs[0]?.name;
if (selectedTabId !== firstTabName) {
setSelectedTabId(firstTabName);
}
}, [tabs, selectedTabId]);
const handleTabSelect = (tabId) => {
setSelectedTabId(tabId);
hasUserSelectionRef.current = true;
};
return /* @__PURE__ */ (0, import_jsx_runtime381.jsx)("div", { className: "block-editor-block-inspector__tabs", children: /* @__PURE__ */ (0, import_jsx_runtime381.jsxs)(
Tabs5,
{
selectedTabId,
onSelect: handleTabSelect,
children: [
/* @__PURE__ */ (0, import_jsx_runtime381.jsx)(Tabs5.TabList, { children: tabs.map(
(tab) => showIconLabels ? /* @__PURE__ */ (0, import_jsx_runtime381.jsx)(Tabs5.Tab, { tabId: tab.name, children: tab.title }, tab.name) : /* @__PURE__ */ (0, import_jsx_runtime381.jsx)(import_components211.Tooltip, { text: tab.title, children: /* @__PURE__ */ (0, import_jsx_runtime381.jsx)(
Tabs5.Tab,
{
tabId: tab.name,
"aria-label": tab.title,
children: /* @__PURE__ */ (0, import_jsx_runtime381.jsx)(import_components211.Icon, { icon: tab.icon })
}
) }, tab.name)
) }),
/* @__PURE__ */ (0, import_jsx_runtime381.jsx)(Tabs5.TabPanel, { tabId: TAB_SETTINGS.name, focusable: false, children: /* @__PURE__ */ (0, import_jsx_runtime381.jsx)(settings_tab_default, { showAdvancedControls: !!blockName }) }),
/* @__PURE__ */ (0, import_jsx_runtime381.jsx)(Tabs5.TabPanel, { tabId: TAB_STYLES.name, focusable: false, children: /* @__PURE__ */ (0, import_jsx_runtime381.jsx)(
styles_tab_default,
{
blockName,
clientId,
hasBlockStyles,
isSectionBlock: isSectionBlock2,
contentClientIds
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime381.jsxs)(Tabs5.TabPanel, { tabId: TAB_CONTENT.name, focusable: false, children: [
/* @__PURE__ */ (0, import_jsx_runtime381.jsx)(inspector_controls_default.Slot, { group: "content" }),
/* @__PURE__ */ (0, import_jsx_runtime381.jsx)(content_tab_default, { contentClientIds })
] }),
/* @__PURE__ */ (0, import_jsx_runtime381.jsx)(Tabs5.TabPanel, { tabId: TAB_LIST_VIEW.name, focusable: false, children: /* @__PURE__ */ (0, import_jsx_runtime381.jsx)(inspector_controls_default.Slot, { group: "list" }) })
]
},
clientId
) });
}
// packages/block-editor/build-module/components/inspector-controls-tabs/use-inspector-controls-tabs.mjs
var import_components212 = __toESM(require_components(), 1);
var import_data170 = __toESM(require_data(), 1);
var EMPTY_ARRAY14 = [];
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,
dimensions: dimensionsGroup,
list: listGroup,
position: positionGroup,
styles: stylesGroup,
typography: typographyGroup,
effects: effectsGroup
} = groups_default;
const listFills = (0, import_components212.__experimentalUseSlotFills)(listGroup.name);
const hasListFills = !!listFills && listFills.length;
const contentFills = (0, import_components212.__experimentalUseSlotFills)(contentGroup.name);
const hasContentFills = !!contentFills && contentFills.length;
const styleFills = [
...(0, import_components212.__experimentalUseSlotFills)(borderGroup.name) || [],
...(0, import_components212.__experimentalUseSlotFills)(colorGroup.name) || [],
...(0, import_components212.__experimentalUseSlotFills)(dimensionsGroup.name) || [],
...(0, import_components212.__experimentalUseSlotFills)(stylesGroup.name) || [],
...(0, import_components212.__experimentalUseSlotFills)(typographyGroup.name) || [],
...(0, import_components212.__experimentalUseSlotFills)(effectsGroup.name) || []
];
const hasStyleFills = styleFills.length;
const advancedFills = [
...(0, import_components212.__experimentalUseSlotFills)(InspectorAdvancedControls.slotName) || [],
...(0, import_components212.__experimentalUseSlotFills)(bindingsGroup.name) || []
];
const settingsFills = [
...(0, import_components212.__experimentalUseSlotFills)(defaultGroup.name) || [],
...(0, import_components212.__experimentalUseSlotFills)(positionGroup.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 || // Advanded fills who up in settings tab if available or they blend into the default tab, if there's only one tab.
advancedFills.length && (hasContentTab || hasListFills)) && !isSectionBlock2) {
tabs.push(TAB_SETTINGS);
}
if (hasBlockStyles || hasStyleFills) {
tabs.push(TAB_STYLES);
}
const tabSettings = (0, import_data170.useSelect)((select3) => {
return select3(store).getSettings().blockInspectorTabs;
}, []);
const showTabs = getShowTabs(blockName, tabSettings);
return showTabs ? tabs : EMPTY_ARRAY14;
}
// packages/block-editor/build-module/components/block-inspector/useBlockInspectorAnimationSettings.mjs
var import_data171 = __toESM(require_data(), 1);
function useBlockInspectorAnimationSettings(blockType) {
return (0, import_data171.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/components/block-visibility/block-visibility-info.mjs
var import_components213 = __toESM(require_components(), 1);
var import_data172 = __toESM(require_data(), 1);
var import_i18n203 = __toESM(require_i18n(), 1);
var import_jsx_runtime382 = __toESM(require_jsx_runtime(), 1);
var { Badge: Badge3 } = unlock(import_components213.privateApis);
function BlockVisibilityInfo({ clientId }) {
const { isBlockHidden: isBlockHidden2, hasHiddenParent } = (0, import_data172.useSelect)(
(select3) => {
if (!clientId) {
return { isBlockHidden: false, hasHiddenParent: false };
}
const { isBlockHidden: _isBlockHidden, getBlockParents: getBlockParents2 } = unlock(
select3(store)
);
const blockHidden = _isBlockHidden(clientId);
const parents = getBlockParents2(clientId);
const parentHidden = parents.some(
(parentId) => _isBlockHidden(parentId)
);
return {
isBlockHidden: blockHidden,
hasHiddenParent: parentHidden
};
},
[clientId]
);
if (!(isBlockHidden2 || hasHiddenParent)) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime382.jsx)(Badge3, { className: "block-editor-block-visibility-info", children: /* @__PURE__ */ (0, import_jsx_runtime382.jsxs)(import_components213.__experimentalHStack, { spacing: 2, justify: "start", children: [
/* @__PURE__ */ (0, import_jsx_runtime382.jsx)(import_components213.Icon, { icon: unseen_default }),
/* @__PURE__ */ (0, import_jsx_runtime382.jsx)(import_components213.__experimentalText, { children: isBlockHidden2 ? (0, import_i18n203.__)("Block is hidden") : (0, import_i18n203.__)("Parent block is hidden") })
] }) });
}
// packages/block-editor/build-module/components/block-inspector/index.mjs
var import_jsx_runtime383 = __toESM(require_jsx_runtime(), 1);
function StyleInspectorSlots({
blockName,
showAdvancedControls = true,
showPositionControls = true,
showBindingsControls = true
}) {
const borderPanelLabel = useBorderPanelLabel({ blockName });
return /* @__PURE__ */ (0, import_jsx_runtime383.jsxs)(import_jsx_runtime383.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime383.jsx)(inspector_controls_default.Slot, {}),
/* @__PURE__ */ (0, import_jsx_runtime383.jsx)(
inspector_controls_default.Slot,
{
group: "color",
label: (0, import_i18n204.__)("Color"),
className: "color-block-support-panel__inner-wrapper"
}
),
/* @__PURE__ */ (0, import_jsx_runtime383.jsx)(
inspector_controls_default.Slot,
{
group: "background",
label: (0, import_i18n204.__)("Background image")
}
),
/* @__PURE__ */ (0, import_jsx_runtime383.jsx)(
inspector_controls_default.Slot,
{
group: "typography",
label: (0, import_i18n204.__)("Typography")
}
),
/* @__PURE__ */ (0, import_jsx_runtime383.jsx)(
inspector_controls_default.Slot,
{
group: "dimensions",
label: (0, import_i18n204.__)("Dimensions")
}
),
/* @__PURE__ */ (0, import_jsx_runtime383.jsx)(inspector_controls_default.Slot, { group: "border", label: borderPanelLabel }),
/* @__PURE__ */ (0, import_jsx_runtime383.jsx)(inspector_controls_default.Slot, { group: "styles" }),
showPositionControls && /* @__PURE__ */ (0, import_jsx_runtime383.jsx)(position_controls_panel_default, {}),
showBindingsControls && /* @__PURE__ */ (0, import_jsx_runtime383.jsx)(inspector_controls_default.Slot, { group: "bindings" }),
showAdvancedControls && /* @__PURE__ */ (0, import_jsx_runtime383.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime383.jsx)(advanced_controls_panel_default, {}) })
] });
}
function BlockInspector() {
const {
selectedBlockCount,
selectedBlockClientId,
renderedBlockName,
renderedBlockClientId,
blockType,
isSectionBlock: isSectionBlock2,
isSectionBlockInSelection,
hasBlockStyles,
editedContentOnlySection: editedContentOnlySection2
} = (0, import_data173.useSelect)((select3) => {
const {
getSelectedBlockClientId: getSelectedBlockClientId2,
getSelectedBlockClientIds: getSelectedBlockClientIds2,
getSelectedBlockCount: getSelectedBlockCount2,
getBlockName: getBlockName2,
getParentSectionBlock: getParentSectionBlock2,
isSectionBlock: _isSectionBlock,
getEditedContentOnlySection: getEditedContentOnlySection2,
isWithinEditedContentOnlySection: isWithinEditedContentOnlySection2
} = unlock(select3(store));
const { getBlockStyles: getBlockStyles2 } = select3(import_blocks94.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_blocks94.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(),
selectedBlockClientId: _selectedBlockClientId,
renderedBlockClientId: _renderedBlockClientId,
renderedBlockName: _renderedBlockName,
blockType: _blockType,
isSectionBlockInSelection: _isSectionBlockInSelection,
isSectionBlock: _isSectionBlock(_renderedBlockClientId),
hasBlockStyles: _hasBlockStyles,
editedContentOnlySection: getEditedContentOnlySection2()
};
}, []);
const contentClientIds = (0, import_data173.useSelect)(
(select3) => {
if (!isSectionBlock2 || !renderedBlockClientId) {
return [];
}
const {
getClientIdsOfDescendants: getClientIdsOfDescendants2,
getBlockName: getBlockName2,
getBlockEditingMode: getBlockEditingMode2
} = unlock(select3(store));
const descendants = getClientIdsOfDescendants2(
renderedBlockClientId
);
const navigationDescendants = /* @__PURE__ */ new Set();
descendants.forEach((clientId) => {
if (getBlockName2(clientId) === "core/navigation") {
const navChildren = getClientIdsOfDescendants2(clientId);
navChildren.forEach(
(childId) => navigationDescendants.add(childId)
);
}
});
return descendants.filter((current) => {
if (navigationDescendants.has(current)) {
return false;
}
return getBlockName2(current) !== "core/list-item" && 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;
if (hasSelectedBlocks && !isSectionBlockInSelection) {
return /* @__PURE__ */ (0, import_jsx_runtime383.jsxs)("div", { className: "block-editor-block-inspector", children: [
/* @__PURE__ */ (0, import_jsx_runtime383.jsx)(MultiSelectionInspector, {}),
hasMultipleTabs ? /* @__PURE__ */ (0, import_jsx_runtime383.jsx)(InspectorControlsTabs, { tabs: availableTabs }) : /* @__PURE__ */ (0, import_jsx_runtime383.jsx)(
StyleInspectorSlots,
{
blockName: renderedBlockName,
showAdvancedControls: false,
showPositionControls: false,
showBindingsControls: false
}
)
] });
}
if (hasSelectedBlocks && isSectionBlockInSelection) {
return /* @__PURE__ */ (0, import_jsx_runtime383.jsx)("div", { className: "block-editor-block-inspector", children: /* @__PURE__ */ (0, import_jsx_runtime383.jsx)(MultiSelectionInspector, {}) });
}
const isRenderedBlockUnregistered = renderedBlockName === (0, import_blocks94.getUnregisteredTypeHandlerName)();
const shouldShowWarning = !blockType || !renderedBlockClientId || isRenderedBlockUnregistered;
if (shouldShowWarning) {
return /* @__PURE__ */ (0, import_jsx_runtime383.jsx)("span", { className: "block-editor-block-inspector__no-blocks", children: (0, import_i18n204.__)("No block selected.") });
}
return /* @__PURE__ */ (0, import_jsx_runtime383.jsx)(
BlockInspectorSingleBlockWrapper,
{
animate: blockInspectorAnimationSettings,
wrapper: (children) => /* @__PURE__ */ (0, import_jsx_runtime383.jsx)(
AnimatedContainer,
{
blockInspectorAnimationSettings,
renderedBlockClientId,
children
}
),
children: /* @__PURE__ */ (0, import_jsx_runtime383.jsx)(
BlockInspectorSingleBlock,
{
renderedBlockClientId,
selectedBlockClientId,
blockName: blockType.name,
isSectionBlock: isSectionBlock2,
availableTabs,
contentClientIds,
hasBlockStyles,
editedContentOnlySection: editedContentOnlySection2
}
)
}
);
}
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_runtime383.jsx)(
import_components214.__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,
// The actual block that is selected in the editor. This may or may not
// be the same as the rendered block (e.g., when a child block is selected
// but its parent section block is the main one rendered in the inspector).
selectedBlockClientId,
blockName,
isSectionBlock: isSectionBlock2,
availableTabs,
contentClientIds,
hasBlockStyles,
editedContentOnlySection: editedContentOnlySection2
}) => {
const hasMultipleTabs = availableTabs?.length > 1;
const hasParentChildBlockCards = window?.__experimentalContentOnlyPatternInsertion && editedContentOnlySection2 && editedContentOnlySection2 !== renderedBlockClientId;
const parentBlockInformation = useBlockDisplayInformation(
editedContentOnlySection2
);
const blockInformation = useBlockDisplayInformation(
renderedBlockClientId
);
const isBlockSynced = blockInformation.isSynced;
const shouldShowTabs = !isBlockSynced && hasMultipleTabs;
const isSectionBlockSelected = window?.__experimentalContentOnlyPatternInsertion && selectedBlockClientId === renderedBlockClientId;
return /* @__PURE__ */ (0, import_jsx_runtime383.jsxs)("div", { className: "block-editor-block-inspector", children: [
hasParentChildBlockCards && /* @__PURE__ */ (0, import_jsx_runtime383.jsx)(
block_card_default,
{
...parentBlockInformation,
className: parentBlockInformation.isSynced && "is-synced",
parentClientId: editedContentOnlySection2
}
),
/* @__PURE__ */ (0, import_jsx_runtime383.jsx)(
block_card_default,
{
...blockInformation,
allowParentNavigation: true,
className: isBlockSynced && "is-synced",
isChild: hasParentChildBlockCards,
clientId: renderedBlockClientId
}
),
/* @__PURE__ */ (0, import_jsx_runtime383.jsx)(BlockVisibilityInfo, { clientId: renderedBlockClientId }),
window?.__experimentalContentOnlyPatternInsertion && /* @__PURE__ */ (0, import_jsx_runtime383.jsx)(EditContents, { clientId: renderedBlockClientId }),
/* @__PURE__ */ (0, import_jsx_runtime383.jsx)(block_variation_transforms_default, { blockClientId: renderedBlockClientId }),
shouldShowTabs && /* @__PURE__ */ (0, import_jsx_runtime383.jsx)(
InspectorControlsTabs,
{
hasBlockStyles,
clientId: renderedBlockClientId,
blockName,
tabs: availableTabs,
isSectionBlock: isSectionBlock2,
contentClientIds
}
),
!shouldShowTabs && /* @__PURE__ */ (0, import_jsx_runtime383.jsxs)(import_jsx_runtime383.Fragment, { children: [
hasBlockStyles && /* @__PURE__ */ (0, import_jsx_runtime383.jsx)(block_styles_default, { clientId: renderedBlockClientId }),
/* @__PURE__ */ (0, import_jsx_runtime383.jsx)(content_tab_default, { contentClientIds }),
/* @__PURE__ */ (0, import_jsx_runtime383.jsx)(inspector_controls_default.Slot, { group: "content" }),
/* @__PURE__ */ (0, import_jsx_runtime383.jsx)(inspector_controls_default.Slot, { group: "list" }),
!isSectionBlock2 && /* @__PURE__ */ (0, import_jsx_runtime383.jsx)(StyleInspectorSlots, { blockName }),
isSectionBlock2 && isBlockSynced && isSectionBlockSelected && /* @__PURE__ */ (0, import_jsx_runtime383.jsxs)(import_jsx_runtime383.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime383.jsx)(inspector_controls_default.Slot, {}),
/* @__PURE__ */ (0, import_jsx_runtime383.jsx)(advanced_controls_panel_default, {})
] })
] }),
/* @__PURE__ */ (0, import_jsx_runtime383.jsx)(SkipToSelectedBlock, {}, "back")
] });
};
var block_inspector_default = BlockInspector;
// packages/block-editor/build-module/components/copy-handler/index.mjs
var import_deprecated32 = __toESM(require_deprecated(), 1);
var import_jsx_runtime384 = __toESM(require_jsx_runtime(), 1);
var __unstableUseClipboardHandler = () => {
(0, import_deprecated32.default)("__unstableUseClipboardHandler", {
alternative: "BlockCanvas or WritingFlow",
since: "6.4",
version: "6.7"
});
return useClipboardHandler();
};
function CopyHandler(props) {
(0, import_deprecated32.default)("CopyHandler", {
alternative: "BlockCanvas or WritingFlow",
since: "6.4",
version: "6.7"
});
return /* @__PURE__ */ (0, import_jsx_runtime384.jsx)("div", { ...props, ref: useClipboardHandler() });
}
// packages/block-editor/build-module/components/inserter/library.mjs
var import_data174 = __toESM(require_data(), 1);
var import_element216 = __toESM(require_element(), 1);
var import_jsx_runtime385 = __toESM(require_jsx_runtime(), 1);
var noop19 = () => {
};
function InserterLibrary({
rootClientId,
clientId,
isAppender,
showInserterHelpPanel,
showMostUsedBlocks = false,
__experimentalInsertionIndex,
__experimentalInitialTab,
__experimentalInitialCategory,
__experimentalFilterValue,
onPatternCategorySelection,
onSelect = noop19,
shouldFocusBlock = false,
onClose
}, ref) {
const { destinationRootClientId } = (0, import_data174.useSelect)(
(select3) => {
const { getBlockRootClientId: getBlockRootClientId2 } = select3(store);
const _rootClientId = rootClientId || getBlockRootClientId2(clientId) || void 0;
return {
destinationRootClientId: _rootClientId
};
},
[clientId, rootClientId]
);
return /* @__PURE__ */ (0, import_jsx_runtime385.jsx)(
PrivateInserterMenu,
{
onSelect,
rootClientId: destinationRootClientId,
clientId,
isAppender,
showInserterHelpPanel,
showMostUsedBlocks,
__experimentalInsertionIndex,
__experimentalFilterValue,
onPatternCategorySelection,
__experimentalInitialTab,
__experimentalInitialCategory,
shouldFocusBlock,
ref,
onClose
}
);
}
var PrivateInserterLibrary = (0, import_element216.forwardRef)(InserterLibrary);
function PublicInserterLibrary(props, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime385.jsx)(
PrivateInserterLibrary,
{
...props,
onPatternCategorySelection: void 0,
ref
}
);
}
var library_default = (0, import_element216.forwardRef)(PublicInserterLibrary);
// packages/block-editor/build-module/components/selection-scroll-into-view/index.mjs
var import_deprecated33 = __toESM(require_deprecated(), 1);
function MultiSelectScrollIntoView() {
(0, import_deprecated33.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_compose90 = __toESM(require_compose(), 1);
var import_dom39 = __toESM(require_dom(), 1);
var import_data175 = __toESM(require_data(), 1);
var import_keycodes26 = __toESM(require_keycodes(), 1);
var import_jsx_runtime386 = __toESM(require_jsx_runtime(), 1);
var isIE = window.navigator.userAgent.indexOf("Trident") !== -1;
var arrowKeyCodes = /* @__PURE__ */ new Set([import_keycodes26.UP, import_keycodes26.DOWN, import_keycodes26.LEFT, import_keycodes26.RIGHT]);
var initialTriggerPercentage = 0.75;
function useTypewriter() {
const hasSelectedBlock2 = (0, import_data175.useSelect)(
(select3) => select3(store).hasSelectedBlock(),
[]
);
return (0, import_compose90.useRefEffect)(
(node) => {
if (!hasSelectedBlock2) {
return;
}
const { ownerDocument } = node;
const { defaultView } = ownerDocument;
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_dom39.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_dom39.getScrollContainer)(node);
if (!scrollContainer) {
return;
}
const windowScroll = scrollContainer === ownerDocument.body || scrollContainer === ownerDocument.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() {
ownerDocument.addEventListener(
"selectionchange",
computeCaretRectOnSelectionChange
);
}
function computeCaretRectOnSelectionChange() {
ownerDocument.removeEventListener(
"selectionchange",
computeCaretRectOnSelectionChange
);
computeCaretRectangle();
}
function computeCaretRectangle() {
if (isSelectionEligibleForScroll()) {
caretRect = (0, import_dom39.computeCaretRect)(defaultView);
}
}
function isSelectionEligibleForScroll() {
return node.contains(ownerDocument.activeElement) && ownerDocument.activeElement.isContentEditable;
}
function isLastEditableNode() {
const editableNodes = node.querySelectorAll(
'[contenteditable="true"]'
);
const lastEditableNode = editableNodes[editableNodes.length - 1];
return lastEditableNode === ownerDocument.activeElement;
}
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
);
ownerDocument.removeEventListener(
"selectionchange",
computeCaretRectOnSelectionChange
);
defaultView.cancelAnimationFrame(scrollResizeRafId);
defaultView.cancelAnimationFrame(onKeyDownRafId);
};
},
[hasSelectedBlock2]
);
}
function Typewriter({ children }) {
return /* @__PURE__ */ (0, import_jsx_runtime386.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_element217 = __toESM(require_element(), 1);
var import_deprecated34 = __toESM(require_deprecated(), 1);
var import_jsx_runtime387 = __toESM(require_jsx_runtime(), 1);
var RenderedRefsContext = (0, import_element217.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_element217.useContext)(RenderedRefsContext);
const { name } = useBlockEditContext();
blockName = blockName || name;
const newRenderedBlocks = (0, import_element217.useMemo)(
() => addToBlockType(previouslyRenderedBlocks, blockName, uniqueId2),
[previouslyRenderedBlocks, blockName, uniqueId2]
);
return /* @__PURE__ */ (0, import_jsx_runtime387.jsx)(RenderedRefsContext.Provider, { value: newRenderedBlocks, children });
}
function useHasRecursion(uniqueId2, blockName = "") {
const previouslyRenderedBlocks = (0, import_element217.useContext)(RenderedRefsContext);
const { name } = useBlockEditContext();
blockName = blockName || name;
return Boolean(previouslyRenderedBlocks[blockName]?.has(uniqueId2));
}
var DeprecatedExperimentalRecursionProvider = (props) => {
(0, import_deprecated34.default)("wp.blockEditor.__experimentalRecursionProvider", {
since: "6.5",
alternative: "wp.blockEditor.RecursionProvider"
});
return /* @__PURE__ */ (0, import_jsx_runtime387.jsx)(RecursionProvider, { ...props });
};
var DeprecatedExperimentalUseHasRecursion = (...args) => {
(0, import_deprecated34.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_components216 = __toESM(require_components(), 1);
var import_i18n206 = __toESM(require_i18n(), 1);
var import_element218 = __toESM(require_element(), 1);
var import_date2 = __toESM(require_date(), 1);
// packages/block-editor/build-module/components/inspector-popover-header/index.mjs
var import_components215 = __toESM(require_components(), 1);
var import_i18n205 = __toESM(require_i18n(), 1);
var import_jsx_runtime388 = __toESM(require_jsx_runtime(), 1);
function InspectorPopoverHeader({
title,
help,
actions = [],
onClose
}) {
return /* @__PURE__ */ (0, import_jsx_runtime388.jsxs)(import_components215.__experimentalVStack, { className: "block-editor-inspector-popover-header", spacing: 4, children: [
/* @__PURE__ */ (0, import_jsx_runtime388.jsxs)(import_components215.__experimentalHStack, { alignment: "center", children: [
/* @__PURE__ */ (0, import_jsx_runtime388.jsx)(
import_components215.__experimentalHeading,
{
className: "block-editor-inspector-popover-header__heading",
level: 2,
size: 13,
children: title
}
),
/* @__PURE__ */ (0, import_jsx_runtime388.jsx)(import_components215.__experimentalSpacer, {}),
actions.map(({ label, icon, onClick }) => /* @__PURE__ */ (0, import_jsx_runtime388.jsx)(
import_components215.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_runtime388.jsx)(
import_components215.Button,
{
size: "small",
className: "block-editor-inspector-popover-header__action",
label: (0, import_i18n205.__)("Close"),
icon: close_small_default,
onClick: onClose
}
)
] }),
help && /* @__PURE__ */ (0, import_jsx_runtime388.jsx)(import_components215.__experimentalText, { children: help })
] });
}
// packages/block-editor/build-module/components/publish-date-time-picker/index.mjs
var import_jsx_runtime389 = __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_components216.TimePicker : import_components216.DateTimePicker;
return /* @__PURE__ */ (0, import_jsx_runtime389.jsxs)("div", { ref, className: "block-editor-publish-date-time-picker", children: [
/* @__PURE__ */ (0, import_jsx_runtime389.jsx)(
InspectorPopoverHeader,
{
title: title || (0, import_i18n206.__)("Publish"),
actions: showPopoverHeaderActions ? [
{
label: (0, import_i18n206.__)("Now"),
onClick: () => onChange?.(null)
}
] : void 0,
onClose
}
),
/* @__PURE__ */ (0, import_jsx_runtime389.jsx)(DatePickerComponent, { ...datePickerProps })
] });
}
var PrivatePublishDateTimePicker = (0, import_element218.forwardRef)(PublishDateTimePicker);
function PublicPublishDateTimePicker(props, ref) {
return /* @__PURE__ */ (0, import_jsx_runtime389.jsx)(
PrivatePublishDateTimePicker,
{
...props,
showPopoverHeaderActions: true,
isCompact: false,
ref
}
);
}
var publish_date_time_picker_default = (0, import_element218.forwardRef)(PublicPublishDateTimePicker);
// packages/block-editor/build-module/components/block-editing-mode/index.mjs
var import_data176 = __toESM(require_data(), 1);
var import_element219 = __toESM(require_element(), 1);
function useBlockEditingMode(mode2) {
const context = useBlockEditContext();
const { clientId = "" } = context;
const { setBlockEditingMode: setBlockEditingMode2, unsetBlockEditingMode: unsetBlockEditingMode2 } = (0, import_data176.useDispatch)(store);
const globalBlockEditingMode = (0, import_data176.useSelect)(
(select3) => (
// Avoid adding the subscription if not needed!
clientId ? null : select3(store).getBlockEditingMode()
),
[clientId]
);
(0, import_element219.useEffect)(() => {
if (mode2) {
setBlockEditingMode2(clientId, mode2);
}
return () => {
if (mode2) {
unsetBlockEditingMode2(clientId);
}
};
}, [clientId, mode2, setBlockEditingMode2, unsetBlockEditingMode2]);
return clientId ? context[blockEditingModeKey] : globalBlockEditingMode;
}
// packages/block-editor/build-module/components/tool-selector/index.mjs
var import_deprecated35 = __toESM(require_deprecated(), 1);
var import_element220 = __toESM(require_element(), 1);
function ToolSelector() {
(0, import_deprecated35.default)("wp.blockEditor.ToolSelector", {
since: "6.9",
hint: "The ToolSelector component no longer renders anything."
});
return null;
}
var tool_selector_default = (0, import_element220.forwardRef)(ToolSelector);
// packages/block-editor/build-module/hooks/utils.mjs
var import_jsx_runtime390 = __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, index, 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[index]) {
referenceBlockAttributes = source[index]?.attributes;
} else {
return result;
}
}
let returnBlock = result;
Object.entries(activeSupports).forEach(([support, isActive]) => {
if (isActive) {
migrationPaths[support].forEach((path) => {
const styleValue = getValueFromObjectPath(
referenceBlockAttributes,
path
);
if (styleValue) {
returnBlock = {
...returnBlock,
attributes: setImmutably(
returnBlock.attributes,
path,
styleValue
)
};
}
});
}
});
return returnBlock;
}
function shouldSkipSerialization(blockNameOrType, featureSet, feature) {
const support = (0, import_blocks95.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: css3 }) {
return usePrivateStyleOverride({ id, css: css3 });
}
function usePrivateStyleOverride({
id,
css: css3,
assets,
__unstableType,
variation,
clientId
} = {}) {
const { setStyleOverride: setStyleOverride2, deleteStyleOverride: deleteStyleOverride2 } = unlock(
(0, import_data177.useDispatch)(store)
);
const registry = (0, import_data177.useRegistry)();
const fallbackId = (0, import_element221.useId)();
(0, import_element221.useEffect)(() => {
if (!css3 && !assets) {
return;
}
const _id = id || fallbackId;
const override = {
id,
css: css3,
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,
css3,
clientId,
assets,
__unstableType,
fallbackId,
setStyleOverride2,
deleteStyleOverride2,
registry,
variation
]);
}
function useBlockSettings(name, parentLayout) {
const [
backgroundImage,
backgroundSize,
customFontFamilies,
defaultFontFamilies,
themeFontFamilies,
defaultFontSizesEnabled,
customFontSizes,
defaultFontSizes,
themeFontSizes,
customFontSize,
fontStyle,
fontWeight,
lineHeight,
textAlign,
textColumns,
textDecoration,
writingMode,
textTransform,
letterSpacing,
padding,
margin,
blockGap,
defaultSpacingSizesEnabled,
customSpacingSize,
userSpacingSizes,
defaultSpacingSizes,
themeSpacingSizes,
units2,
aspectRatio,
height,
minHeight,
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",
"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.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.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_element221.useMemo)(() => {
return {
background: {
backgroundImage,
backgroundSize
},
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,
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,
width,
dimensionSizes
},
layout,
parentLayout,
shadow
};
}, [
backgroundImage,
backgroundSize,
customFontFamilies,
defaultFontFamilies,
themeFontFamilies,
defaultFontSizesEnabled,
customFontSizes,
defaultFontSizes,
themeFontSizes,
customFontSize,
fontStyle,
fontWeight,
lineHeight,
textAlign,
textColumns,
textDecoration,
textTransform,
letterSpacing,
writingMode,
padding,
margin,
blockGap,
defaultSpacingSizesEnabled,
customSpacingSize,
userSpacingSizes,
defaultSpacingSizes,
themeSpacingSizes,
units2,
aspectRatio,
height,
minHeight,
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_element221.memo)(settings2.edit) };
});
const withBlockEditHooks = (0, import_compose91.createHigherOrderComponent)(
(OriginalBlockEdit) => (props) => {
const context = useBlockEditContext();
return [
...features.map((feature, i2) => {
const {
Edit: Edit4,
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_runtime390.jsx)(
Edit4,
{
name: props.name,
isSelected: props.isSelected,
clientId: props.clientId,
setAttributes: props.setAttributes,
__unstableParentLayout: props.__unstableParentLayout,
...neededProps
},
i2
);
}),
/* @__PURE__ */ (0, import_jsx_runtime390.jsx)(OriginalBlockEdit, { ...props }, "edit")
];
},
"withBlockEditHooks"
);
(0, import_hooks13.addFilter)("editor.BlockEdit", "core/editor/hooks", withBlockEditHooks);
}
function BlockProps({
index,
useBlockProps: hook,
setAllWrapperProps,
...props
}) {
const wrapperProps = hook(props);
const setWrapperProps = (next) => setAllWrapperProps((prev) => {
const nextAll = [...prev];
nextAll[index] = next;
return nextAll;
});
(0, import_element221.useEffect)(() => {
setWrapperProps(wrapperProps);
return () => {
setWrapperProps(void 0);
};
});
return null;
}
var BlockPropsPure = (0, import_element221.memo)(BlockProps);
function createBlockListBlockFilter(features) {
const withBlockListBlockHooks = (0, import_compose91.createHigherOrderComponent)(
(BlockListBlock2) => (props) => {
const [allWrapperProps, setAllWrapperProps] = (0, import_element221.useState)(
Array(features.length).fill(void 0)
);
return [
...features.map((feature, i2) => {
const {
hasSupport,
attributeKeys = [],
useBlockProps: useBlockProps15,
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_runtime390.jsx)(
BlockPropsPure,
{
index: i2,
useBlockProps: useBlockProps15,
setAllWrapperProps,
name: props.name,
clientId: props.clientId,
...neededProps
},
i2
);
}),
/* @__PURE__ */ (0, import_jsx_runtime390.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_hooks13.addFilter)(
"editor.BlockListBlock",
"core/editor/hooks",
withBlockListBlockHooks
);
}
function createBlockSaveFilter(features) {
function extraPropsFromHooks(props, name, attributes) {
return features.reduce((accu, feature) => {
const { hasSupport, attributeKeys = [], addSaveProps: addSaveProps10 } = 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 addSaveProps10(accu, name, neededAttributes);
}, props);
}
(0, import_hooks13.addFilter)(
"blocks.getSaveContent.extraProps",
"core/editor/hooks",
extraPropsFromHooks,
0
);
(0, import_hooks13.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_blocks96 = __toESM(require_blocks(), 1);
var import_hooks15 = __toESM(require_hooks(), 1);
function migrateLightBlockWrapper(settings2) {
const { apiVersion = 1 } = settings2;
if (apiVersion < 2 && (0, import_blocks96.hasBlockSupport)(settings2, "lightBlockWrapper", false)) {
settings2.apiVersion = 2;
}
return settings2;
}
(0, import_hooks15.addFilter)(
"blocks.registerBlockType",
"core/compat/migrateLightBlockWrapper",
migrateLightBlockWrapper
);
// packages/block-editor/build-module/hooks/cross-origin-isolation.mjs
var import_hooks16 = __toESM(require_hooks(), 1);
var import_compose92 = __toESM(require_compose(), 1);
var import_jsx_runtime391 = __toESM(require_jsx_runtime(), 1);
function addCrossOriginAttributes(el) {
if (!el.hasAttribute("crossorigin")) {
el.setAttribute("crossorigin", "anonymous");
}
if (el.nodeName === "IFRAME" && !el.hasAttribute("credentialless")) {
if (el.getAttribute("src")?.startsWith("blob:")) {
return;
}
el.setAttribute("credentialless", "");
const origSrc = el.getAttribute("src") || "";
el.setAttribute("src", "");
el.setAttribute("src", origSrc);
}
}
if (window.crossOriginIsolated) {
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(
"img,source,script,video,link,iframe"
).forEach((v2) => {
addCrossOriginAttributes(v2);
});
if (el.nodeName === "IFRAME") {
const iframeNode = el;
const isEmbedSandboxIframe = iframeNode.classList.contains(
"components-sandbox"
);
if (!isEmbedSandboxIframe) {
iframeNode.addEventListener("load", () => {
if (iframeNode.contentDocument) {
observer.observe(
iframeNode.contentDocument,
{
childList: true,
attributes: true,
subtree: true
}
);
}
});
}
}
if ([
"IMG",
"SOURCE",
"SCRIPT",
"VIDEO",
"LINK",
"IFRAME"
].includes(el.nodeName)) {
addCrossOriginAttributes(el);
}
});
});
});
});
observer.observe(document.body, {
childList: true,
attributes: true,
subtree: true
});
}
if (window.crossOriginIsolated) {
const supportsCredentialless = "credentialless" in window.HTMLIFrameElement.prototype;
const disableEmbedPreviews = (0, import_compose92.createHigherOrderComponent)(
(BlockEdit2) => (props) => {
if ("core/embed" !== props.name) {
return /* @__PURE__ */ (0, import_jsx_runtime391.jsx)(BlockEdit2, { ...props });
}
const previewable = supportsCredentialless && !["facebook", "smugmug"].includes(
props.attributes.providerNameSlug
);
return /* @__PURE__ */ (0, import_jsx_runtime391.jsx)(
BlockEdit2,
{
...props,
attributes: { ...props.attributes, previewable }
}
);
},
"withDisabledEmbedPreview"
);
(0, import_hooks16.addFilter)(
"editor.BlockEdit",
"media-experiments/disable-embed-previews",
disableEmbedPreviews
);
}
// packages/block-editor/build-module/hooks/align.mjs
var import_hooks17 = __toESM(require_hooks(), 1);
var import_blocks97 = __toESM(require_blocks(), 1);
var import_jsx_runtime392 = __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_blocks97.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_blocks97.getBlockSupport)(blockName, "align"),
(0, import_blocks97.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_blocks97.getBlockType)(blockName);
const blockDefaultAlign = blockType?.attributes?.align?.default;
if (blockDefaultAlign) {
nextAlign = "";
}
}
setAttributes({ align: nextAlign });
};
return /* @__PURE__ */ (0, import_jsx_runtime392.jsx)(block_controls_default, { group: "block", __experimentalShareWithChildBlocks: true, children: /* @__PURE__ */ (0, import_jsx_runtime392.jsx)(
BlockAlignmentControl,
{
value: align,
onChange: updateAlignment,
controls: validAlignments
}
) });
}
var align_default = {
shareWithChildBlocks: true,
edit: BlockEditAlignmentToolbarControlsPure,
useBlockProps: useBlockProps7,
addSaveProps: addAssignedAlign,
attributeKeys: ["align"],
hasSupport(name) {
return (0, import_blocks97.hasBlockSupport)(name, "align", false);
}
};
function useBlockProps7({ name, align }) {
const blockAllowedAlignments = getValidAlignments(
(0, import_blocks97.getBlockSupport)(name, "align"),
(0, import_blocks97.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_blocks97.getBlockSupport)(blockType, "align");
const hasWideBlockSupport = (0, import_blocks97.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_hooks17.addFilter)(
"blocks.registerBlockType",
"core/editor/align/addAttribute",
addAttribute
);
// packages/block-editor/build-module/hooks/lock.mjs
var import_hooks18 = __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_hooks18.addFilter)("blocks.registerBlockType", "core/lock/addAttribute", addAttribute2);
// packages/block-editor/build-module/hooks/allowed-blocks.mjs
var import_hooks19 = __toESM(require_hooks(), 1);
var import_blocks100 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/components/block-allowed-blocks/allowed-blocks-control.mjs
var import_components223 = __toESM(require_components(), 1);
var import_i18n209 = __toESM(require_i18n(), 1);
var import_element225 = __toESM(require_element(), 1);
var import_data180 = __toESM(require_data(), 1);
var import_blocks99 = __toESM(require_blocks(), 1);
// packages/block-editor/build-module/components/block-allowed-blocks/modal.mjs
var import_components222 = __toESM(require_components(), 1);
var import_element224 = __toESM(require_element(), 1);
var import_i18n208 = __toESM(require_i18n(), 1);
var import_data179 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/block-manager/index.mjs
var import_blocks98 = __toESM(require_blocks(), 1);
var import_data178 = __toESM(require_data(), 1);
var import_components221 = __toESM(require_components(), 1);
var import_i18n207 = __toESM(require_i18n(), 1);
var import_element223 = __toESM(require_element(), 1);
var import_compose94 = __toESM(require_compose(), 1);
var import_a11y19 = __toESM(require_a11y(), 1);
// packages/block-editor/build-module/components/block-manager/category.mjs
var import_element222 = __toESM(require_element(), 1);
var import_compose93 = __toESM(require_compose(), 1);
var import_components220 = __toESM(require_components(), 1);
// packages/block-editor/build-module/components/block-manager/checklist.mjs
var import_components219 = __toESM(require_components(), 1);
var import_jsx_runtime393 = __toESM(require_jsx_runtime(), 1);
function BlockTypesChecklist({ blockTypes, value, onItemChange }) {
return /* @__PURE__ */ (0, import_jsx_runtime393.jsx)("ul", { className: "block-editor-block-manager__checklist", children: blockTypes.map((blockType) => /* @__PURE__ */ (0, import_jsx_runtime393.jsxs)(
"li",
{
className: "block-editor-block-manager__checklist-item",
children: [
/* @__PURE__ */ (0, import_jsx_runtime393.jsx)(
import_components219.CheckboxControl,
{
label: blockType.title,
checked: value.includes(blockType.name),
onChange: (...args) => onItemChange(blockType, ...args)
}
),
/* @__PURE__ */ (0, import_jsx_runtime393.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_runtime394 = __toESM(require_jsx_runtime(), 1);
function BlockManagerCategory({
title,
blockTypes,
selectedBlockTypes,
onChange
}) {
const instanceId = (0, import_compose93.useInstanceId)(BlockManagerCategory);
const toggleVisible = (0, import_element222.useCallback)(
(blockType, nextIsChecked) => {
if (nextIsChecked) {
onChange([...selectedBlockTypes, blockType]);
} else {
onChange(
selectedBlockTypes.filter(
({ name }) => name !== blockType.name
)
);
}
},
[selectedBlockTypes, onChange]
);
const toggleAllVisible = (0, import_element222.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_runtime394.jsxs)(
"div",
{
role: "group",
"aria-labelledby": titleId,
className: "block-editor-block-manager__category",
children: [
/* @__PURE__ */ (0, import_jsx_runtime394.jsx)(
import_components220.CheckboxControl,
{
checked: isAllChecked,
onChange: toggleAllVisible,
className: "block-editor-block-manager__category-title",
indeterminate: isIndeterminate,
label: /* @__PURE__ */ (0, import_jsx_runtime394.jsx)("span", { id: titleId, children: title })
}
),
/* @__PURE__ */ (0, import_jsx_runtime394.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_runtime395 = __toESM(require_jsx_runtime(), 1);
function BlockManager({
blockTypes,
selectedBlockTypes,
onChange,
showSelectAll = true
}) {
const debouncedSpeak = (0, import_compose94.useDebounce)(import_a11y19.speak, 500);
const [search, setSearch] = (0, import_element223.useState)("");
const { categories, isMatchingSearchTerm } = (0, import_data178.useSelect)((select3) => {
return {
categories: select3(import_blocks98.store).getCategories(),
isMatchingSearchTerm: select3(import_blocks98.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_element223.useEffect)(() => {
if (!search) {
return;
}
const count = filteredBlockTypes.length;
const resultsFoundMessage = (0, import_i18n207.sprintf)(
/* translators: %d: number of results. */
(0, import_i18n207._n)("%d result found.", "%d results found.", count),
count
);
debouncedSpeak(resultsFoundMessage);
}, [filteredBlockTypes?.length, search, debouncedSpeak]);
return /* @__PURE__ */ (0, import_jsx_runtime395.jsxs)(import_components221.__experimentalVStack, { className: "block-editor-block-manager__content", spacing: 4, children: [
/* @__PURE__ */ (0, import_jsx_runtime395.jsx)(
import_components221.SearchControl,
{
label: (0, import_i18n207.__)("Search for a block"),
placeholder: (0, import_i18n207.__)("Search for a block"),
value: search,
onChange: (nextSearch) => setSearch(nextSearch),
className: "block-editor-block-manager__search"
}
),
showSelectAll && /* @__PURE__ */ (0, import_jsx_runtime395.jsx)(
import_components221.CheckboxControl,
{
className: "block-editor-block-manager__select-all",
label: (0, import_i18n207.__)("Select all"),
checked: isAllChecked,
onChange: () => {
if (isAllChecked) {
onChange([]);
} else {
onChange(blockTypes);
}
},
indeterminate: isIndeterminate
}
),
/* @__PURE__ */ (0, import_jsx_runtime395.jsxs)(
"div",
{
tabIndex: "0",
role: "region",
"aria-label": (0, import_i18n207.__)("Available block types"),
className: "block-editor-block-manager__results",
children: [
filteredBlockTypes.length === 0 && /* @__PURE__ */ (0, import_jsx_runtime395.jsx)("p", { className: "block-editor-block-manager__no-results", children: (0, import_i18n207.__)("No blocks found.") }),
categories.map((category) => /* @__PURE__ */ (0, import_jsx_runtime395.jsx)(
category_default2,
{
title: category.title,
blockTypes: filteredBlockTypes.filter(
(blockType) => blockType.category === category.slug
),
selectedBlockTypes,
onChange
},
category.slug
)),
/* @__PURE__ */ (0, import_jsx_runtime395.jsx)(
category_default2,
{
title: (0, import_i18n207.__)("Uncategorized"),
blockTypes: filteredBlockTypes.filter(
({ category }) => !category
),
selectedBlockTypes,
onChange
}
)
]
}
)
] });
}
// packages/block-editor/build-module/components/block-allowed-blocks/modal.mjs
var import_jsx_runtime396 = __toESM(require_jsx_runtime(), 1);
function BlockAllowedBlocksModal({
clientId,
blockTypes,
selectedBlockTypes,
onClose
}) {
const [currentSelectedBlockTypes, setCurrentSelectedBlockTypes] = (0, import_element224.useState)(selectedBlockTypes);
const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data179.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_runtime396.jsx)(
import_components222.Modal,
{
title: (0, import_i18n208.__)("Manage allowed blocks"),
onRequestClose: onClose,
overlayClassName: "block-editor-block-allowed-blocks-modal",
focusOnMount: "firstContentElement",
size: "medium",
children: /* @__PURE__ */ (0, import_jsx_runtime396.jsxs)(
import_components222.__experimentalVStack,
{
as: "form",
onSubmit: (e2) => {
e2.preventDefault();
handleSubmit();
},
spacing: "4",
children: [
/* @__PURE__ */ (0, import_jsx_runtime396.jsx)(import_components222.__experimentalText, { children: (0, import_i18n208.__)(
"Select which blocks can be added inside this container."
) }),
/* @__PURE__ */ (0, import_jsx_runtime396.jsx)(
BlockManager,
{
blockTypes,
selectedBlockTypes: currentSelectedBlockTypes,
onChange: (newSelectedBlockTypes) => {
setCurrentSelectedBlockTypes(newSelectedBlockTypes);
}
}
),
/* @__PURE__ */ (0, import_jsx_runtime396.jsxs)(
import_components222.Flex,
{
className: "block-editor-block-allowed-blocks-modal__actions",
justify: "flex-end",
expanded: false,
children: [
/* @__PURE__ */ (0, import_jsx_runtime396.jsx)(import_components222.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime396.jsx)(
import_components222.Button,
{
variant: "tertiary",
onClick: onClose,
__next40pxDefaultSize: true,
children: (0, import_i18n208.__)("Cancel")
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime396.jsx)(import_components222.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime396.jsx)(
import_components222.Button,
{
variant: "primary",
type: "submit",
__next40pxDefaultSize: true,
children: (0, import_i18n208.__)("Apply")
}
) })
]
}
)
]
}
)
}
);
}
// packages/block-editor/build-module/components/block-allowed-blocks/allowed-blocks-control.mjs
var import_jsx_runtime397 = __toESM(require_jsx_runtime(), 1);
function BlockAllowedBlocksControl({ clientId }) {
const [isBlockControlOpened, setIsBlockControlOpened] = (0, import_element225.useState)(false);
const { blockTypes, selectedBlockNames } = (0, import_data180.useSelect)(
(select3) => {
const { getBlockAttributes: getBlockAttributes3 } = select3(store);
return {
blockTypes: select3(import_blocks99.store).getBlockTypes(),
selectedBlockNames: getBlockAttributes3(clientId)?.allowedBlocks
};
},
[clientId]
);
const filteredBlockTypes = blockTypes.filter(
(blockType) => (0, import_blocks99.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_runtime397.jsxs)("div", { className: "block-editor-block-allowed-blocks-control", children: [
/* @__PURE__ */ (0, import_jsx_runtime397.jsxs)(
import_components223.BaseControl,
{
help: (0, import_i18n209.__)(
"Specify which blocks are allowed inside this container."
),
children: [
/* @__PURE__ */ (0, import_jsx_runtime397.jsx)(import_components223.BaseControl.VisualLabel, { children: (0, import_i18n209.__)("Allowed Blocks") }),
/* @__PURE__ */ (0, import_jsx_runtime397.jsx)(
import_components223.Button,
{
__next40pxDefaultSize: true,
variant: "secondary",
onClick: () => {
setIsBlockControlOpened(true);
},
className: "block-editor-block-allowed-blocks-control__button",
children: (0, import_i18n209.__)("Manage allowed blocks")
}
)
]
}
),
isBlockControlOpened && /* @__PURE__ */ (0, import_jsx_runtime397.jsx)(
BlockAllowedBlocksModal,
{
clientId,
blockTypes: filteredBlockTypes,
selectedBlockTypes,
onClose: () => setIsBlockControlOpened(false)
}
)
] });
}
// packages/block-editor/build-module/hooks/allowed-blocks.mjs
var import_jsx_runtime398 = __toESM(require_jsx_runtime(), 1);
function BlockEditAllowedBlocksControlPure({ clientId }) {
const blockEditingMode = useBlockEditingMode();
const isContentOnly = blockEditingMode === "contentOnly";
if (isContentOnly) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime398.jsx)(PrivateInspectorControlsAllowedBlocks.Fill, { children: /* @__PURE__ */ (0, import_jsx_runtime398.jsx)(BlockAllowedBlocksControl, { clientId }) });
}
var allowed_blocks_default = {
edit: BlockEditAllowedBlocksControlPure,
attributeKeys: ["allowedBlocks"],
hasSupport(name) {
return (0, import_blocks100.hasBlockSupport)(name, "allowedBlocks");
}
};
function addAttribute3(settings2) {
if (settings2?.attributes?.allowedBlocks?.type) {
return settings2;
}
if ((0, import_blocks100.hasBlockSupport)(settings2, "allowedBlocks")) {
settings2.attributes = {
...settings2.attributes,
allowedBlocks: {
type: "array"
}
};
}
return settings2;
}
(0, import_hooks19.addFilter)(
"blocks.registerBlockType",
"core/allowedBlocks/attribute",
addAttribute3
);
function addTransforms2(result, source, index, results) {
if (!(0, import_blocks100.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[index]?.attributes?.allowedBlocks;
if (!sourceAllowedBlocks) {
return result;
}
const blockType = (0, import_blocks100.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_hooks19.addFilter)(
"blocks.switchToBlockType.transformedBlock",
"core/allowedBlocks/addTransforms",
addTransforms2
);
// packages/block-editor/build-module/hooks/anchor.mjs
var import_hooks20 = __toESM(require_hooks(), 1);
var import_components224 = __toESM(require_components(), 1);
var import_i18n210 = __toESM(require_i18n(), 1);
var import_blocks101 = __toESM(require_blocks(), 1);
var import_element226 = __toESM(require_element(), 1);
var import_jsx_runtime399 = __toESM(require_jsx_runtime(), 1);
var ANCHOR_REGEX = /[\s#]/g;
function addAttribute4(settings2) {
if ("type" in (settings2.attributes?.anchor ?? {})) {
return settings2;
}
if ((0, import_blocks101.hasBlockSupport)(settings2, "anchor")) {
settings2.attributes = {
...settings2.attributes,
anchor: {
type: "string"
}
};
}
return settings2;
}
function BlockEditAnchorControlPure({ anchor, setAttributes }) {
const blockEditingMode = useBlockEditingMode();
if (blockEditingMode !== "default") {
return null;
}
const isWeb = import_element226.Platform.OS === "web";
return /* @__PURE__ */ (0, import_jsx_runtime399.jsx)(inspector_controls_default, { group: "advanced", children: /* @__PURE__ */ (0, import_jsx_runtime399.jsx)(
import_components224.TextControl,
{
__next40pxDefaultSize: true,
className: "html-anchor-control",
label: (0, import_i18n210.__)("HTML anchor"),
help: /* @__PURE__ */ (0, import_jsx_runtime399.jsxs)(import_jsx_runtime399.Fragment, { children: [
(0, import_i18n210.__)(
"Enter a word or two \u2014 without spaces \u2014 to 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."
),
isWeb && /* @__PURE__ */ (0, import_jsx_runtime399.jsxs)(import_jsx_runtime399.Fragment, { children: [
" ",
/* @__PURE__ */ (0, import_jsx_runtime399.jsx)(
import_components224.ExternalLink,
{
href: (0, import_i18n210.__)(
"https://wordpress.org/documentation/article/page-jumps/"
),
children: (0, import_i18n210.__)("Learn more about anchors")
}
)
] })
] }),
value: anchor || "",
placeholder: !isWeb ? (0, import_i18n210.__)("Add an anchor") : null,
onChange: (nextValue) => {
nextValue = nextValue.replace(ANCHOR_REGEX, "-");
setAttributes({
anchor: nextValue !== "" ? nextValue : void 0
});
},
autoCapitalize: "none",
autoComplete: "off"
}
) });
}
var anchor_default = {
addSaveProps: addSaveProps3,
edit: BlockEditAnchorControlPure,
attributeKeys: ["anchor"],
hasSupport(name) {
return (0, import_blocks101.hasBlockSupport)(name, "anchor");
}
};
function addSaveProps3(extraProps, blockType, attributes) {
if ((0, import_blocks101.hasBlockSupport)(blockType, "anchor")) {
extraProps.id = attributes.anchor === "" ? null : attributes.anchor;
}
return extraProps;
}
(0, import_hooks20.addFilter)("blocks.registerBlockType", "core/anchor/attribute", addAttribute4);
// packages/block-editor/build-module/hooks/aria-label.mjs
var import_hooks21 = __toESM(require_hooks(), 1);
var import_blocks102 = __toESM(require_blocks(), 1);
function addAttribute5(settings2) {
if (settings2?.attributes?.ariaLabel?.type) {
return settings2;
}
if ((0, import_blocks102.hasBlockSupport)(settings2, "ariaLabel")) {
settings2.attributes = {
...settings2.attributes,
ariaLabel: {
type: "string"
}
};
}
return settings2;
}
function addSaveProps4(extraProps, blockType, attributes) {
if ((0, import_blocks102.hasBlockSupport)(blockType, "ariaLabel")) {
extraProps["aria-label"] = attributes.ariaLabel === "" ? null : attributes.ariaLabel;
}
return extraProps;
}
var aria_label_default = {
addSaveProps: addSaveProps4,
attributeKeys: ["ariaLabel"],
hasSupport(name) {
return (0, import_blocks102.hasBlockSupport)(name, "ariaLabel");
}
};
(0, import_hooks21.addFilter)(
"blocks.registerBlockType",
"core/ariaLabel/attribute",
addAttribute5
);
// packages/block-editor/build-module/hooks/block-fields/index.mjs
var import_blocks103 = __toESM(require_blocks(), 1);
var import_components254 = __toESM(require_components(), 1);
var import_data183 = __toESM(require_data(), 1);
// node_modules/@base-ui/utils/esm/useRefWithInit.js
var React4 = __toESM(require_react(), 1);
var UNINITIALIZED = {};
function useRefWithInit(init, initArg) {
const ref = React4.useRef(UNINITIALIZED);
if (ref.current === UNINITIALIZED) {
ref.current = init(initArg);
}
return ref;
}
// node_modules/@base-ui/react/esm/utils/useRenderElement.js
var React7 = __toESM(require_react(), 1);
// node_modules/@base-ui/utils/esm/useMergedRefs.js
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, index) => ref !== newRefs[index]);
}
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/esm/getReactElementRef.js
var React6 = __toESM(require_react(), 1);
// node_modules/@base-ui/utils/esm/reactVersion.js
var React5 = __toESM(require_react(), 1);
var majorVersion = parseInt(React5.version, 10);
function isReactVersionAtLeast(reactVersionToCheck) {
return majorVersion >= reactVersionToCheck;
}
// node_modules/@base-ui/utils/esm/getReactElementRef.js
function getReactElementRef(element) {
if (!/* @__PURE__ */ React6.isValidElement(element)) {
return null;
}
const reactElement = element;
const propsWithRef = reactElement.props;
return (isReactVersionAtLeast(19) ? propsWithRef?.ref : reactElement.ref) ?? null;
}
// node_modules/@base-ui/utils/esm/mergeObjects.js
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/react/esm/utils/getStateAttributesProps.js
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/esm/utils/resolveClassName.js
function resolveClassName(className, state) {
return typeof className === "function" ? className(state) : className;
}
// node_modules/@base-ui/react/esm/utils/resolveStyle.js
function resolveStyle(style, state) {
return typeof style === "function" ? style(state) : style;
}
// node_modules/@base-ui/react/esm/merge-props/mergeProps.js
var EMPTY_PROPS = {};
function mergeProps(a2, b2, c6, d2, e2) {
let merged = {
...resolvePropsGetter(a2, EMPTY_PROPS)
};
if (b2) {
merged = mergeOne(merged, b2);
}
if (c6) {
merged = mergeOne(merged, c6);
}
if (d2) {
merged = mergeOne(merged, d2);
}
if (e2) {
merged = mergeOne(merged, e2);
}
return merged;
}
function mergePropsN(props) {
if (props.length === 0) {
return EMPTY_PROPS;
}
if (props.length === 1) {
return resolvePropsGetter(props[0], EMPTY_PROPS);
}
let merged = {
...resolvePropsGetter(props[0], EMPTY_PROPS)
};
for (let i2 = 1; i2 < props.length; i2 += 1) {
merged = mergeOne(merged, props[i2]);
}
return merged;
}
function mergeOne(merged, inputProps) {
if (isPropsGetter(inputProps)) {
return inputProps(merged);
}
return mutablyMergeInto(merged, inputProps);
}
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 theirHandler;
}
return (event) => {
if (isSyntheticEvent(event)) {
const baseUIEvent = event;
makeEventPreventable(baseUIEvent);
const result2 = theirHandler(baseUIEvent);
if (!baseUIEvent.baseUIHandlerPrevented) {
ourHandler?.(baseUIEvent);
}
return result2;
}
const result = theirHandler(event);
ourHandler?.(event);
return result;
};
}
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/utils/esm/empty.js
var EMPTY_ARRAY15 = Object.freeze([]);
var EMPTY_OBJECT3 = Object.freeze({});
// node_modules/@base-ui/react/esm/utils/useRenderElement.js
var import_react6 = __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_OBJECT3;
return evaluateRenderProp(element, renderProp, outProps, state);
}
function useRenderElementProps(componentProps, params = {}) {
const {
className: classNameProp,
style: styleProp,
render: renderProp
} = componentProps;
const {
state = EMPTY_OBJECT3,
ref,
props,
stateAttributesMapping,
enabled = true
} = params;
const className = enabled ? resolveClassName(classNameProp, state) : void 0;
const style = enabled ? resolveStyle(styleProp, state) : void 0;
const stateProps = enabled ? getStateAttributesProps(state, stateAttributesMapping) : EMPTY_OBJECT3;
const outProps = enabled ? mergeObjects(stateProps, Array.isArray(props) ? mergePropsN(props) : props) ?? EMPTY_OBJECT3 : EMPTY_OBJECT3;
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_OBJECT3;
}
if (className !== void 0) {
outProps.className = mergeClassNames(outProps.className, className);
}
if (style !== void 0) {
outProps.style = mergeObjects(outProps.style, style);
}
return outProps;
}
function evaluateRenderProp(element, render4, props, state) {
if (render4) {
if (typeof render4 === "function") {
return render4(props, state);
}
const mergedProps = mergeProps(props, render4.props);
mergedProps.ref = props.ref;
return /* @__PURE__ */ React7.cloneElement(render4, 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(8));
}
function renderTag(Tag, props) {
if (Tag === "button") {
return /* @__PURE__ */ (0, import_react6.createElement)("button", {
type: "button",
...props,
key: props.key
});
}
if (Tag === "img") {
return /* @__PURE__ */ (0, import_react6.createElement)("img", {
alt: "",
...props,
key: props.key
});
}
return /* @__PURE__ */ React7.createElement(Tag, props);
}
// node_modules/@base-ui/react/esm/use-render/useRender.js
function useRender(params) {
return useRenderElement(params.defaultTagName ?? "div", params, params);
}
// packages/ui/build-module/stack/stack.mjs
var import_element227 = __toESM(require_element(), 1);
var css2 = `@layer wp-ui-utilities, wp-ui-components, wp-ui-compositions, wp-ui-overrides;
@layer wp-ui-components {
.style-module__stack__Gc4EG {
display: flex;
}
}
`;
document.head.appendChild(document.createElement("style")).appendChild(document.createTextNode(css2));
var style_default = {
"stack": "style-module__stack__Gc4EG"
};
var Stack = (0, import_element227.forwardRef)(function Stack2({ direction, gap, align, justify, wrap, render: render4, ...props }, ref) {
const style = {
gap: gap && `var(--wpds-dimension-gap-${gap})`,
alignItems: align,
justifyContent: justify,
flexDirection: direction,
flexWrap: wrap
};
const element = useRender({
render: render4,
ref,
props: mergeProps(props, { style, className: style_default.stack })
});
return element;
});
// packages/dataviews/build-module/constants.mjs
var import_i18n211 = __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_i18n211.__)("Sort ascending"),
desc: (0, import_i18n211.__)("Sort descending")
};
// packages/dataviews/build-module/lock-unlock.mjs
var import_private_apis3 = __toESM(require_private_apis(), 1);
var { lock: lock3, unlock: unlock3 } = (0, import_private_apis3.__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_element228 = __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_element228.useState)(staticElements);
const [isLoading, setIsLoading] = (0, import_element228.useState)(false);
(0, import_element228.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
};
}
// packages/dataviews/build-module/utils/operators.mjs
var import_i18n212 = __toESM(require_i18n(), 1);
var import_element229 = __toESM(require_element(), 1);
var import_jsx_runtime400 = __toESM(require_jsx_runtime(), 1);
var filterTextWrappers = {
Name: /* @__PURE__ */ (0, import_jsx_runtime400.jsx)("span", { className: "dataviews-filters__summary-filter-text-name" }),
Value: /* @__PURE__ */ (0, import_jsx_runtime400.jsx)("span", { className: "dataviews-filters__summary-filter-text-value" })
};
var OPERATORS = [
{
name: OPERATOR_IS_ANY,
/* translators: DataViews operator name */
label: (0, import_i18n212.__)("Includes"),
filterText: (filter, activeElements) => (0, import_element229.createInterpolateElement)(
(0, import_i18n212.sprintf)(
/* translators: 1: Filter name (e.g. "Author"). 2: Filter value (e.g. "Admin"): "Author is any: Admin, Editor". */
(0, import_i18n212.__)("<Name>%1$s includes: </Name><Value>%2$s</Value>"),
filter.name,
activeElements.map((element) => element.label).join(", ")
),
filterTextWrappers
),
selection: "multi"
},
{
name: OPERATOR_IS_NONE,
/* translators: DataViews operator name */
label: (0, import_i18n212.__)("Is none of"),
filterText: (filter, activeElements) => (0, import_element229.createInterpolateElement)(
(0, import_i18n212.sprintf)(
/* translators: 1: Filter name (e.g. "Author"). 2: Filter value (e.g. "Admin"): "Author is none of: Admin, Editor". */
(0, import_i18n212.__)("<Name>%1$s is none of: </Name><Value>%2$s</Value>"),
filter.name,
activeElements.map((element) => element.label).join(", ")
),
filterTextWrappers
),
selection: "multi"
},
{
name: OPERATOR_IS_ALL,
/* translators: DataViews operator name */
label: (0, import_i18n212.__)("Includes all"),
filterText: (filter, activeElements) => (0, import_element229.createInterpolateElement)(
(0, import_i18n212.sprintf)(
/* translators: 1: Filter name (e.g. "Author"). 2: Filter value (e.g. "Admin"): "Author includes all: Admin, Editor". */
(0, import_i18n212.__)("<Name>%1$s includes all: </Name><Value>%2$s</Value>"),
filter.name,
activeElements.map((element) => element.label).join(", ")
),
filterTextWrappers
),
selection: "multi"
},
{
name: OPERATOR_IS_NOT_ALL,
/* translators: DataViews operator name */
label: (0, import_i18n212.__)("Is none of"),
filterText: (filter, activeElements) => (0, import_element229.createInterpolateElement)(
(0, import_i18n212.sprintf)(
/* translators: 1: Filter name (e.g. "Author"). 2: Filter value (e.g. "Admin"): "Author is none of: Admin, Editor". */
(0, import_i18n212.__)("<Name>%1$s is none of: </Name><Value>%2$s</Value>"),
filter.name,
activeElements.map((element) => element.label).join(", ")
),
filterTextWrappers
),
selection: "multi"
},
{
name: OPERATOR_BETWEEN,
/* translators: DataViews operator name */
label: (0, import_i18n212.__)("Between (inc)"),
filterText: (filter, activeElements) => (0, import_element229.createInterpolateElement)(
(0, import_i18n212.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_i18n212.__)(
"<Name>%1$s between (inc): </Name><Value>%2$s and %3$s</Value>"
),
filter.name,
activeElements[0].label[0],
activeElements[0].label[1]
),
filterTextWrappers
),
selection: "custom"
},
{
name: OPERATOR_IN_THE_PAST,
/* translators: DataViews operator name */
label: (0, import_i18n212.__)("In the past"),
filterText: (filter, activeElements) => (0, import_element229.createInterpolateElement)(
(0, import_i18n212.sprintf)(
/* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "7 days"): "Date is in the past: 7 days". */
(0, import_i18n212.__)(
"<Name>%1$s is in the past: </Name><Value>%2$s</Value>"
),
filter.name,
`${activeElements[0].value.value} ${activeElements[0].value.unit}`
),
filterTextWrappers
),
selection: "custom"
},
{
name: OPERATOR_OVER,
/* translators: DataViews operator name */
label: (0, import_i18n212.__)("Over"),
filterText: (filter, activeElements) => (0, import_element229.createInterpolateElement)(
(0, import_i18n212.sprintf)(
/* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "7 days"): "Date is over: 7 days". */
(0, import_i18n212.__)("<Name>%1$s is over: </Name><Value>%2$s</Value>"),
filter.name,
`${activeElements[0].value.value} ${activeElements[0].value.unit}`
),
filterTextWrappers
),
selection: "custom"
},
{
name: OPERATOR_IS,
/* translators: DataViews operator name */
label: (0, import_i18n212.__)("Is"),
filterText: (filter, activeElements) => (0, import_element229.createInterpolateElement)(
(0, import_i18n212.sprintf)(
/* translators: 1: Filter name (e.g. "Author"). 2: Filter value (e.g. "Admin"): "Author is: Admin". */
(0, import_i18n212.__)("<Name>%1$s is: </Name><Value>%2$s</Value>"),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
selection: "single"
},
{
name: OPERATOR_IS_NOT,
/* translators: DataViews operator name */
label: (0, import_i18n212.__)("Is not"),
filterText: (filter, activeElements) => (0, import_element229.createInterpolateElement)(
(0, import_i18n212.sprintf)(
/* translators: 1: Filter name (e.g. "Author"). 2: Filter value (e.g. "Admin"): "Author is not: Admin". */
(0, import_i18n212.__)("<Name>%1$s is not: </Name><Value>%2$s</Value>"),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
selection: "single"
},
{
name: OPERATOR_LESS_THAN,
/* translators: DataViews operator name */
label: (0, import_i18n212.__)("Less than"),
filterText: (filter, activeElements) => (0, import_element229.createInterpolateElement)(
(0, import_i18n212.sprintf)(
/* translators: 1: Filter name (e.g. "Count"). 2: Filter value (e.g. "10"): "Count is less than: 10". */
(0, import_i18n212.__)("<Name>%1$s is less than: </Name><Value>%2$s</Value>"),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
selection: "single"
},
{
name: OPERATOR_GREATER_THAN,
/* translators: DataViews operator name */
label: (0, import_i18n212.__)("Greater than"),
filterText: (filter, activeElements) => (0, import_element229.createInterpolateElement)(
(0, import_i18n212.sprintf)(
/* translators: 1: Filter name (e.g. "Count"). 2: Filter value (e.g. "10"): "Count is greater than: 10". */
(0, import_i18n212.__)(
"<Name>%1$s is greater than: </Name><Value>%2$s</Value>"
),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
selection: "single"
},
{
name: OPERATOR_LESS_THAN_OR_EQUAL,
/* translators: DataViews operator name */
label: (0, import_i18n212.__)("Less than or equal"),
filterText: (filter, activeElements) => (0, import_element229.createInterpolateElement)(
(0, import_i18n212.sprintf)(
/* translators: 1: Filter name (e.g. "Count"). 2: Filter value (e.g. "10"): "Count is less than or equal to: 10". */
(0, import_i18n212.__)(
"<Name>%1$s is less than or equal to: </Name><Value>%2$s</Value>"
),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
selection: "single"
},
{
name: OPERATOR_GREATER_THAN_OR_EQUAL,
/* translators: DataViews operator name */
label: (0, import_i18n212.__)("Greater than or equal"),
filterText: (filter, activeElements) => (0, import_element229.createInterpolateElement)(
(0, import_i18n212.sprintf)(
/* translators: 1: Filter name (e.g. "Count"). 2: Filter value (e.g. "10"): "Count is greater than or equal to: 10". */
(0, import_i18n212.__)(
"<Name>%1$s is greater than or equal to: </Name><Value>%2$s</Value>"
),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
selection: "single"
},
{
name: OPERATOR_BEFORE,
/* translators: DataViews operator name */
label: (0, import_i18n212.__)("Before"),
filterText: (filter, activeElements) => (0, import_element229.createInterpolateElement)(
(0, import_i18n212.sprintf)(
/* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "2024-01-01"): "Date is before: 2024-01-01". */
(0, import_i18n212.__)("<Name>%1$s is before: </Name><Value>%2$s</Value>"),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
selection: "single"
},
{
name: OPERATOR_AFTER,
/* translators: DataViews operator name */
label: (0, import_i18n212.__)("After"),
filterText: (filter, activeElements) => (0, import_element229.createInterpolateElement)(
(0, import_i18n212.sprintf)(
/* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "2024-01-01"): "Date is after: 2024-01-01". */
(0, import_i18n212.__)("<Name>%1$s is after: </Name><Value>%2$s</Value>"),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
selection: "single"
},
{
name: OPERATOR_BEFORE_INC,
/* translators: DataViews operator name */
label: (0, import_i18n212.__)("Before (inc)"),
filterText: (filter, activeElements) => (0, import_element229.createInterpolateElement)(
(0, import_i18n212.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_i18n212.__)(
"<Name>%1$s is on or before: </Name><Value>%2$s</Value>"
),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
selection: "single"
},
{
name: OPERATOR_AFTER_INC,
/* translators: DataViews operator name */
label: (0, import_i18n212.__)("After (inc)"),
filterText: (filter, activeElements) => (0, import_element229.createInterpolateElement)(
(0, import_i18n212.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_i18n212.__)(
"<Name>%1$s is on or after: </Name><Value>%2$s</Value>"
),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
selection: "single"
},
{
name: OPERATOR_CONTAINS,
/* translators: DataViews operator name */
label: (0, import_i18n212.__)("Contains"),
filterText: (filter, activeElements) => (0, import_element229.createInterpolateElement)(
(0, import_i18n212.sprintf)(
/* translators: 1: Filter name (e.g. "Title"). 2: Filter value (e.g. "Hello"): "Title contains: Hello". */
(0, import_i18n212.__)("<Name>%1$s contains: </Name><Value>%2$s</Value>"),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
selection: "single"
},
{
name: OPERATOR_NOT_CONTAINS,
/* translators: DataViews operator name */
label: (0, import_i18n212.__)("Doesn't contain"),
filterText: (filter, activeElements) => (0, import_element229.createInterpolateElement)(
(0, import_i18n212.sprintf)(
/* translators: 1: Filter name (e.g. "Title"). 2: Filter value (e.g. "Hello"): "Title doesn't contain: Hello". */
(0, import_i18n212.__)(
"<Name>%1$s doesn't contain: </Name><Value>%2$s</Value>"
),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
selection: "single"
},
{
name: OPERATOR_STARTS_WITH,
/* translators: DataViews operator name */
label: (0, import_i18n212.__)("Starts with"),
filterText: (filter, activeElements) => (0, import_element229.createInterpolateElement)(
(0, import_i18n212.sprintf)(
/* translators: 1: Filter name (e.g. "Title"). 2: Filter value (e.g. "Hello"): "Title starts with: Hello". */
(0, import_i18n212.__)("<Name>%1$s starts with: </Name><Value>%2$s</Value>"),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
selection: "single"
},
{
name: OPERATOR_ON,
/* translators: DataViews operator name */
label: (0, import_i18n212.__)("On"),
filterText: (filter, activeElements) => (0, import_element229.createInterpolateElement)(
(0, import_i18n212.sprintf)(
/* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "2024-01-01"): "Date is: 2024-01-01". */
(0, import_i18n212.__)("<Name>%1$s is: </Name><Value>%2$s</Value>"),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
selection: "single"
},
{
name: OPERATOR_NOT_ON,
/* translators: DataViews operator name */
label: (0, import_i18n212.__)("Not on"),
filterText: (filter, activeElements) => (0, import_element229.createInterpolateElement)(
(0, import_i18n212.sprintf)(
/* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "2024-01-01"): "Date is not: 2024-01-01". */
(0, import_i18n212.__)("<Name>%1$s is not: </Name><Value>%2$s</Value>"),
filter.name,
activeElements[0].label
),
filterTextWrappers
),
selection: "single"
}
];
var getAllOperatorNames = () => OPERATORS.map((op) => op.name);
// packages/dataviews/build-module/components/dataform-controls/checkbox.mjs
var import_components226 = __toESM(require_components(), 1);
var import_element230 = __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_runtime401 = __toESM(require_jsx_runtime(), 1);
var { ValidatedCheckboxControl } = unlock3(import_components226.privateApis);
function Checkbox({
field,
onChange,
data,
hideLabelFromVision,
validity
}) {
const { getValue, setValue, label, description, isValid: isValid2 } = field;
const onChangeControl = (0, import_element230.useCallback)(() => {
onChange(
setValue({ item: data, value: !getValue({ item: data }) })
);
}, [data, getValue, onChange, setValue]);
return /* @__PURE__ */ (0, import_jsx_runtime401.jsx)(
ValidatedCheckboxControl,
{
required: !!field.isValid?.required,
customValidity: getCustomValidity(isValid2, validity),
hidden: hideLabelFromVision,
label,
help: description,
checked: getValue({ item: data }),
onChange: onChangeControl
}
);
}
// packages/dataviews/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");
// packages/dataviews/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);
}
// packages/dataviews/node_modules/date-fns/toDate.js
function toDate(argument, context) {
return constructFrom(context || argument, argument);
}
// packages/dataviews/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;
}
// packages/dataviews/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;
}
}
// packages/dataviews/node_modules/date-fns/_lib/defaultOptions.js
var defaultOptions = {};
function getDefaultOptions() {
return defaultOptions;
}
// packages/dataviews/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;
}
// packages/dataviews/node_modules/date-fns/startOfISOWeek.js
function startOfISOWeek(date, options) {
return startOfWeek(date, { ...options, weekStartsOn: 1 });
}
// packages/dataviews/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;
}
}
// packages/dataviews/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;
}
// packages/dataviews/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);
}
// packages/dataviews/node_modules/date-fns/startOfDay.js
function startOfDay(date, options) {
const _date = toDate(date, options?.in);
_date.setHours(0, 0, 0, 0);
return _date;
}
// packages/dataviews/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);
}
// packages/dataviews/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);
}
// packages/dataviews/node_modules/date-fns/addYears.js
function addYears(date, amount, options) {
return addMonths(date, amount * 12, options);
}
// packages/dataviews/node_modules/date-fns/isDate.js
function isDate(value) {
return value instanceof Date || typeof value === "object" && Object.prototype.toString.call(value) === "[object Date]";
}
// packages/dataviews/node_modules/date-fns/isValid.js
function isValid(date) {
return !(!isDate(date) && typeof date !== "number" || isNaN(+toDate(date)));
}
// packages/dataviews/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;
}
// packages/dataviews/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_;
}
// packages/dataviews/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;
};
// packages/dataviews/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;
};
}
// packages/dataviews/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"
})
};
// packages/dataviews/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];
// packages/dataviews/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 index = args.argumentCallback ? args.argumentCallback(value) : value;
return valuesArray[index];
};
}
// packages/dataviews/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"
})
};
// packages/dataviews/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;
}
// packages/dataviews/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 };
};
}
// packages/dataviews/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: (index) => index + 1
}),
month: buildMatchFn({
matchPatterns: matchMonthPatterns,
defaultMatchWidth: "wide",
parsePatterns: parseMonthPatterns,
defaultParseWidth: "any"
}),
day: buildMatchFn({
matchPatterns: matchDayPatterns,
defaultMatchWidth: "wide",
parsePatterns: parseDayPatterns,
defaultParseWidth: "any"
}),
dayPeriod: buildMatchFn({
matchPatterns: matchDayPeriodPatterns,
defaultMatchWidth: "any",
parsePatterns: parseDayPeriodPatterns,
defaultParseWidth: "any"
})
};
// packages/dataviews/node_modules/date-fns/locale/en-US.js
var enUS = {
code: "en-US",
formatDistance,
formatLong,
formatRelative,
localize,
match,
options: {
weekStartsOn: 0,
firstWeekContainsDate: 1
}
};
// packages/dataviews/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;
}
// packages/dataviews/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;
}
// packages/dataviews/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;
}
}
// packages/dataviews/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;
}
// packages/dataviews/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;
}
// packages/dataviews/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;
}
// packages/dataviews/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);
}
};
// packages/dataviews/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(offset, delimiter = "") {
const sign = offset > 0 ? "-" : "+";
const absOffset = Math.abs(offset);
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(offset, delimiter) {
if (offset % 60 === 0) {
const sign = offset > 0 ? "-" : "+";
return sign + addLeadingZeros(Math.abs(offset) / 60, 2);
}
return formatTimezone(offset, delimiter);
}
function formatTimezone(offset, delimiter = "") {
const sign = offset > 0 ? "-" : "+";
const absOffset = Math.abs(offset);
const hours = addLeadingZeros(Math.trunc(absOffset / 60), 2);
const minutes = addLeadingZeros(absOffset % 60, 2);
return sign + hours + delimiter + minutes;
}
// packages/dataviews/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
};
// packages/dataviews/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`;
}
// packages/dataviews/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, "'");
}
// packages/dataviews/node_modules/date-fns/subDays.js
function subDays(date, amount, options) {
return addDays(date, -amount, options);
}
// packages/dataviews/node_modules/date-fns/subMonths.js
function subMonths(date, amount, options) {
return addMonths(date, -amount, options);
}
// packages/dataviews/node_modules/date-fns/subYears.js
function subYears(date, amount, options) {
return addYears(date, -amount, options);
}
// packages/dataviews/build-module/components/dataform-controls/datetime.mjs
var import_components228 = __toESM(require_components(), 1);
var import_element232 = __toESM(require_element(), 1);
var import_i18n214 = __toESM(require_i18n(), 1);
var import_date4 = __toESM(require_date(), 1);
// packages/dataviews/build-module/components/dataform-controls/utils/relative-date-control.mjs
var import_components227 = __toESM(require_components(), 1);
var import_element231 = __toESM(require_element(), 1);
var import_i18n213 = __toESM(require_i18n(), 1);
var import_jsx_runtime402 = __toESM(require_jsx_runtime(), 1);
var TIME_UNITS_OPTIONS = {
[OPERATOR_IN_THE_PAST]: [
{ value: "days", label: (0, import_i18n213.__)("Days") },
{ value: "weeks", label: (0, import_i18n213.__)("Weeks") },
{ value: "months", label: (0, import_i18n213.__)("Months") },
{ value: "years", label: (0, import_i18n213.__)("Years") }
],
[OPERATOR_OVER]: [
{ value: "days", label: (0, import_i18n213.__)("Days ago") },
{ value: "weeks", label: (0, import_i18n213.__)("Weeks ago") },
{ value: "months", label: (0, import_i18n213.__)("Months ago") },
{ value: "years", label: (0, import_i18n213.__)("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, getValue, setValue } = field;
const fieldValue = getValue({ item: data });
const { value: relValue = "", unit = options[0].value } = fieldValue && typeof fieldValue === "object" ? fieldValue : {};
const onChangeValue = (0, import_element231.useCallback)(
(newValue) => onChange(
setValue({
item: data,
value: { value: Number(newValue), unit }
})
),
[onChange, setValue, data, unit]
);
const onChangeUnit = (0, import_element231.useCallback)(
(newUnit) => onChange(
setValue({
item: data,
value: { value: relValue, unit: newUnit }
})
),
[onChange, setValue, data, relValue]
);
return /* @__PURE__ */ (0, import_jsx_runtime402.jsx)(
import_components227.BaseControl,
{
id,
className: clsx_default(className, "dataviews-controls__relative-date"),
label,
hideLabelFromVision,
children: /* @__PURE__ */ (0, import_jsx_runtime402.jsxs)(Stack, { direction: "row", gap: "xs", children: [
/* @__PURE__ */ (0, import_jsx_runtime402.jsx)(
import_components227.__experimentalNumberControl,
{
__next40pxDefaultSize: true,
className: "dataviews-controls__relative-date-number",
spinControls: "none",
min: 1,
step: 1,
value: relValue,
onChange: onChangeValue
}
),
/* @__PURE__ */ (0, import_jsx_runtime402.jsx)(
import_components227.SelectControl,
{
className: "dataviews-controls__relative-date-unit",
__next40pxDefaultSize: true,
label: (0, import_i18n213.__)("Unit"),
value: unit,
options,
onChange: onChangeUnit,
hideLabelFromVision: true
}
)
] })
}
);
}
// packages/dataviews/build-module/field-types/utils/parse-date-time.mjs
var import_date3 = __toESM(require_date(), 1);
function parseDateTime(dateTimeString) {
if (!dateTimeString) {
return null;
}
const parsed = (0, import_date3.getDate)(dateTimeString);
return parsed && isValid(parsed) ? parsed : null;
}
// packages/dataviews/build-module/components/dataform-controls/datetime.mjs
var import_jsx_runtime403 = __toESM(require_jsx_runtime(), 1);
var { DateCalendar, ValidatedInputControl } = unlock3(import_components228.privateApis);
var formatDateTime = (date) => {
if (!date) {
return "";
}
if (typeof date === "string") {
return date;
}
return format(date, "yyyy-MM-dd'T'HH:mm");
};
function CalendarDateTimeControl({
data,
field,
onChange,
hideLabelFromVision,
validity
}) {
const { id, label, description, setValue, getValue, isValid: isValid2 } = field;
const fieldValue = getValue({ item: data });
const value = typeof fieldValue === "string" ? fieldValue : void 0;
const [calendarMonth, setCalendarMonth] = (0, import_element232.useState)(() => {
const parsedDate = parseDateTime(value);
return parsedDate || /* @__PURE__ */ new Date();
});
const inputControlRef = (0, import_element232.useRef)(null);
const validationTimeoutRef = (0, import_element232.useRef)();
const previousFocusRef = (0, import_element232.useRef)(null);
const onChangeCallback = (0, import_element232.useCallback)(
(newValue) => onChange(setValue({ item: data, value: newValue })),
[data, onChange, setValue]
);
(0, import_element232.useEffect)(() => {
return () => {
if (validationTimeoutRef.current) {
clearTimeout(validationTimeoutRef.current);
}
};
}, []);
const onSelectDate = (0, import_element232.useCallback)(
(newDate) => {
let dateTimeValue;
if (newDate) {
let finalDateTime = newDate;
if (value) {
const currentDateTime = parseDateTime(value);
if (currentDateTime) {
finalDateTime = new Date(newDate);
finalDateTime.setHours(currentDateTime.getHours());
finalDateTime.setMinutes(
currentDateTime.getMinutes()
);
}
}
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_element232.useCallback)(
(newValue) => {
if (newValue) {
const dateTime = new Date(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_date4.getSettings)().l10n.startOfWeek;
const {
timezone: { string: timezoneString }
} = (0, import_date4.getSettings)();
const displayLabel = isValid2?.required && !hideLabelFromVision ? `${label} (${(0, import_i18n214.__)("Required")})` : label;
return /* @__PURE__ */ (0, import_jsx_runtime403.jsx)(
import_components228.BaseControl,
{
id,
label: displayLabel,
help: description,
hideLabelFromVision,
children: /* @__PURE__ */ (0, import_jsx_runtime403.jsxs)(Stack, { direction: "column", gap: "md", children: [
/* @__PURE__ */ (0, import_jsx_runtime403.jsx)(
DateCalendar,
{
style: { width: "100%" },
selected: value ? parseDateTime(value) || void 0 : void 0,
onSelect: onSelectDate,
month: calendarMonth,
onMonthChange: setCalendarMonth,
timeZone: timezoneString || void 0,
weekStartsOn
}
),
/* @__PURE__ */ (0, import_jsx_runtime403.jsx)(
ValidatedInputControl,
{
ref: inputControlRef,
__next40pxDefaultSize: true,
required: !!isValid2?.required,
customValidity: getCustomValidity(isValid2, validity),
type: "datetime-local",
label: (0, import_i18n214.__)("Date time"),
hideLabelFromVision: true,
value: value ? formatDateTime(
parseDateTime(value) || void 0
) : "",
onChange: handleManualDateTimeChange
}
)
] })
}
);
}
function DateTime({
data,
field,
onChange,
hideLabelFromVision,
operator,
validity
}) {
if (operator === OPERATOR_IN_THE_PAST || operator === OPERATOR_OVER) {
return /* @__PURE__ */ (0, import_jsx_runtime403.jsx)(
RelativeDateControl,
{
className: "dataviews-controls__datetime",
data,
field,
onChange,
hideLabelFromVision,
operator
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime403.jsx)(
CalendarDateTimeControl,
{
data,
field,
onChange,
hideLabelFromVision,
validity
}
);
}
// packages/dataviews/build-module/components/dataform-controls/date.mjs
var import_components229 = __toESM(require_components(), 1);
var import_element233 = __toESM(require_element(), 1);
var import_i18n215 = __toESM(require_i18n(), 1);
var import_date5 = __toESM(require_date(), 1);
var import_jsx_runtime404 = __toESM(require_jsx_runtime(), 1);
var { DateCalendar: DateCalendar2, DateRangeCalendar } = unlock3(import_components229.privateApis);
var DATE_PRESETS = [
{
id: "today",
label: (0, import_i18n215.__)("Today"),
getValue: () => (0, import_date5.getDate)(null)
},
{
id: "yesterday",
label: (0, import_i18n215.__)("Yesterday"),
getValue: () => {
const today = (0, import_date5.getDate)(null);
return subDays(today, 1);
}
},
{
id: "past-week",
label: (0, import_i18n215.__)("Past week"),
getValue: () => {
const today = (0, import_date5.getDate)(null);
return subDays(today, 7);
}
},
{
id: "past-month",
label: (0, import_i18n215.__)("Past month"),
getValue: () => {
const today = (0, import_date5.getDate)(null);
return subMonths(today, 1);
}
}
];
var DATE_RANGE_PRESETS = [
{
id: "last-7-days",
label: (0, import_i18n215.__)("Last 7 days"),
getValue: () => {
const today = (0, import_date5.getDate)(null);
return [subDays(today, 7), today];
}
},
{
id: "last-30-days",
label: (0, import_i18n215.__)("Last 30 days"),
getValue: () => {
const today = (0, import_date5.getDate)(null);
return [subDays(today, 30), today];
}
},
{
id: "month-to-date",
label: (0, import_i18n215.__)("Month to date"),
getValue: () => {
const today = (0, import_date5.getDate)(null);
return [startOfMonth(today), today];
}
},
{
id: "last-year",
label: (0, import_i18n215.__)("Last year"),
getValue: () => {
const today = (0, import_date5.getDate)(null);
return [subYears(today, 1), today];
}
},
{
id: "year-to-date",
label: (0, import_i18n215.__)("Year to date"),
getValue: () => {
const today = (0, import_date5.getDate)(null);
return [startOfYear(today), today];
}
}
];
var parseDate = (dateString) => {
if (!dateString) {
return null;
}
const parsed = (0, import_date5.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_element233.useState)(void 0);
const validateRefs = (0, import_element233.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_element233.useEffect)(() => {
if (isTouched) {
const timeoutId = setTimeout(() => {
if (validity) {
setCustomValidity(getCustomValidity(isValid2, validity));
} else {
validateRefs();
}
}, 0);
return () => clearTimeout(timeoutId);
}
return void 0;
}, [isTouched, isValid2, validity, validateRefs]);
const onBlur = (event) => {
if (isTouched) {
return;
}
if (!event.relatedTarget || !event.currentTarget.contains(event.relatedTarget)) {
setIsTouched(true);
}
};
return /* @__PURE__ */ (0, import_jsx_runtime404.jsxs)("div", { onBlur, children: [
children,
/* @__PURE__ */ (0, import_jsx_runtime404.jsx)("div", { "aria-live": "polite", children: customValidity && /* @__PURE__ */ (0, import_jsx_runtime404.jsxs)(
"p",
{
className: clsx_default(
"components-validated-control__indicator",
customValidity.type === "invalid" ? "is-invalid" : void 0,
customValidity.type === "valid" ? "is-valid" : void 0
),
children: [
/* @__PURE__ */ (0, import_jsx_runtime404.jsx)(
import_components229.Icon,
{
className: "components-validated-control__indicator-icon",
icon: error_default,
size: 16,
fill: "currentColor"
}
),
customValidity.message
]
}
) })
] });
}
function CalendarDateControl({
data,
field,
onChange,
hideLabelFromVision,
validity
}) {
const {
id,
label,
setValue,
getValue,
isValid: isValid2,
format: fieldFormat
} = field;
const [selectedPresetId, setSelectedPresetId] = (0, import_element233.useState)(
null
);
const weekStartsOn = fieldFormat.weekStartsOn ?? (0, import_date5.getSettings)().l10n.startOfWeek;
const fieldValue = getValue({ item: data });
const value = typeof fieldValue === "string" ? fieldValue : void 0;
const [calendarMonth, setCalendarMonth] = (0, import_element233.useState)(() => {
const parsedDate = parseDate(value);
return parsedDate || /* @__PURE__ */ new Date();
});
const [isTouched, setIsTouched] = (0, import_element233.useState)(false);
const validityTargetRef = (0, import_element233.useRef)(null);
const onChangeCallback = (0, import_element233.useCallback)(
(newValue) => onChange(setValue({ item: data, value: newValue })),
[data, onChange, setValue]
);
const onSelectDate = (0, import_element233.useCallback)(
(newDate) => {
const dateValue = newDate ? format(newDate, "yyyy-MM-dd") : void 0;
onChangeCallback(dateValue);
setSelectedPresetId(null);
setIsTouched(true);
},
[onChangeCallback]
);
const handlePresetClick = (0, import_element233.useCallback)(
(preset) => {
const presetDate = preset.getValue();
const dateValue = formatDate(presetDate);
setCalendarMonth(presetDate);
onChangeCallback(dateValue);
setSelectedPresetId(preset.id);
setIsTouched(true);
},
[onChangeCallback]
);
const handleManualDateChange = (0, import_element233.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_date5.getSettings)();
const displayLabel = isValid2?.required ? `${label} (${(0, import_i18n215.__)("Required")})` : label;
return /* @__PURE__ */ (0, import_jsx_runtime404.jsx)(
ValidatedDateControl,
{
field,
validity,
inputRefs: validityTargetRef,
isTouched,
setIsTouched,
children: /* @__PURE__ */ (0, import_jsx_runtime404.jsx)(
import_components229.BaseControl,
{
id,
className: "dataviews-controls__date",
label: displayLabel,
hideLabelFromVision,
children: /* @__PURE__ */ (0, import_jsx_runtime404.jsxs)(Stack, { direction: "column", gap: "md", children: [
/* @__PURE__ */ (0, import_jsx_runtime404.jsxs)(
Stack,
{
direction: "row",
gap: "xs",
wrap: "wrap",
justify: "flex-start",
children: [
DATE_PRESETS.map((preset) => {
const isSelected = selectedPresetId === preset.id;
return /* @__PURE__ */ (0, import_jsx_runtime404.jsx)(
import_components229.Button,
{
className: "dataviews-controls__date-preset",
variant: "tertiary",
isPressed: isSelected,
size: "small",
onClick: () => handlePresetClick(preset),
children: preset.label
},
preset.id
);
}),
/* @__PURE__ */ (0, import_jsx_runtime404.jsx)(
import_components229.Button,
{
className: "dataviews-controls__date-preset",
variant: "tertiary",
isPressed: !selectedPresetId,
size: "small",
disabled: !!selectedPresetId,
accessibleWhenDisabled: false,
children: (0, import_i18n215.__)("Custom")
}
)
]
}
),
/* @__PURE__ */ (0, import_jsx_runtime404.jsx)(
import_components229.__experimentalInputControl,
{
__next40pxDefaultSize: true,
ref: validityTargetRef,
type: "date",
label: (0, import_i18n215.__)("Date"),
hideLabelFromVision: true,
value,
onChange: handleManualDateChange,
required: !!field.isValid?.required
}
),
/* @__PURE__ */ (0, import_jsx_runtime404.jsx)(
DateCalendar2,
{
style: { width: "100%" },
selected: value ? parseDate(value) || void 0 : void 0,
onSelect: onSelectDate,
month: calendarMonth,
onMonthChange: setCalendarMonth,
timeZone: timezoneString || void 0,
weekStartsOn
}
)
] })
}
)
}
);
}
function CalendarDateRangeControl({
data,
field,
onChange,
hideLabelFromVision,
validity
}) {
const { id, label, getValue, setValue, format: fieldFormat } = 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_date5.getSettings)().l10n.startOfWeek;
const onChangeCallback = (0, import_element233.useCallback)(
(newValue) => {
onChange(
setValue({
item: data,
value: newValue
})
);
},
[data, onChange, setValue]
);
const [selectedPresetId, setSelectedPresetId] = (0, import_element233.useState)(
null
);
const selectedRange = (0, import_element233.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_element233.useState)(() => {
return selectedRange.from || /* @__PURE__ */ new Date();
});
const [isTouched, setIsTouched] = (0, import_element233.useState)(false);
const fromInputRef = (0, import_element233.useRef)(null);
const toInputRef = (0, import_element233.useRef)(null);
const updateDateRange = (0, import_element233.useCallback)(
(fromDate, toDate2) => {
if (fromDate && toDate2) {
onChangeCallback([
formatDate(fromDate),
formatDate(toDate2)
]);
} else if (!fromDate && !toDate2) {
onChangeCallback(void 0);
}
},
[onChangeCallback]
);
const onSelectCalendarRange = (0, import_element233.useCallback)(
(newRange) => {
updateDateRange(newRange?.from, newRange?.to);
setSelectedPresetId(null);
setIsTouched(true);
},
[updateDateRange]
);
const handlePresetClick = (0, import_element233.useCallback)(
(preset) => {
const [startDate, endDate] = preset.getValue();
setCalendarMonth(startDate);
updateDateRange(startDate, endDate);
setSelectedPresetId(preset.id);
setIsTouched(true);
},
[updateDateRange]
);
const handleManualDateChange = (0, import_element233.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_date5.getSettings)();
const displayLabel = field.isValid?.required ? `${label} (${(0, import_i18n215.__)("Required")})` : label;
return /* @__PURE__ */ (0, import_jsx_runtime404.jsx)(
ValidatedDateControl,
{
field,
validity,
inputRefs: [fromInputRef, toInputRef],
isTouched,
setIsTouched,
children: /* @__PURE__ */ (0, import_jsx_runtime404.jsx)(
import_components229.BaseControl,
{
id,
className: "dataviews-controls__date",
label: displayLabel,
hideLabelFromVision,
children: /* @__PURE__ */ (0, import_jsx_runtime404.jsxs)(Stack, { direction: "column", gap: "md", children: [
/* @__PURE__ */ (0, import_jsx_runtime404.jsxs)(
Stack,
{
direction: "row",
gap: "xs",
wrap: "wrap",
justify: "flex-start",
children: [
DATE_RANGE_PRESETS.map((preset) => {
const isSelected = selectedPresetId === preset.id;
return /* @__PURE__ */ (0, import_jsx_runtime404.jsx)(
import_components229.Button,
{
className: "dataviews-controls__date-preset",
variant: "tertiary",
isPressed: isSelected,
size: "small",
onClick: () => handlePresetClick(preset),
children: preset.label
},
preset.id
);
}),
/* @__PURE__ */ (0, import_jsx_runtime404.jsx)(
import_components229.Button,
{
className: "dataviews-controls__date-preset",
variant: "tertiary",
isPressed: !selectedPresetId,
size: "small",
accessibleWhenDisabled: false,
disabled: !!selectedPresetId,
children: (0, import_i18n215.__)("Custom")
}
)
]
}
),
/* @__PURE__ */ (0, import_jsx_runtime404.jsxs)(
Stack,
{
direction: "row",
gap: "xs",
justify: "space-between",
className: "dataviews-controls__date-range-inputs",
children: [
/* @__PURE__ */ (0, import_jsx_runtime404.jsx)(
import_components229.__experimentalInputControl,
{
__next40pxDefaultSize: true,
ref: fromInputRef,
type: "date",
label: (0, import_i18n215.__)("From"),
hideLabelFromVision: true,
value: value?.[0],
onChange: (newValue) => handleManualDateChange("from", newValue),
required: !!field.isValid?.required
}
),
/* @__PURE__ */ (0, import_jsx_runtime404.jsx)(
import_components229.__experimentalInputControl,
{
__next40pxDefaultSize: true,
ref: toInputRef,
type: "date",
label: (0, import_i18n215.__)("To"),
hideLabelFromVision: true,
value: value?.[1],
onChange: (newValue) => handleManualDateChange("to", newValue),
required: !!field.isValid?.required
}
)
]
}
),
/* @__PURE__ */ (0, import_jsx_runtime404.jsx)(
DateRangeCalendar,
{
style: { width: "100%" },
selected: selectedRange,
onSelect: onSelectCalendarRange,
month: calendarMonth,
onMonthChange: setCalendarMonth,
timeZone: timezone.string || void 0,
weekStartsOn
}
)
] })
}
)
}
);
}
function DateControl({
data,
field,
onChange,
hideLabelFromVision,
operator,
validity
}) {
if (operator === OPERATOR_IN_THE_PAST || operator === OPERATOR_OVER) {
return /* @__PURE__ */ (0, import_jsx_runtime404.jsx)(
RelativeDateControl,
{
className: "dataviews-controls__date",
data,
field,
onChange,
hideLabelFromVision,
operator
}
);
}
if (operator === OPERATOR_BETWEEN) {
return /* @__PURE__ */ (0, import_jsx_runtime404.jsx)(
CalendarDateRangeControl,
{
data,
field,
onChange,
hideLabelFromVision,
validity
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime404.jsx)(
CalendarDateControl,
{
data,
field,
onChange,
hideLabelFromVision,
validity
}
);
}
// packages/dataviews/build-module/components/dataform-controls/email.mjs
var import_components231 = __toESM(require_components(), 1);
// packages/dataviews/build-module/components/dataform-controls/utils/validated-input.mjs
var import_components230 = __toESM(require_components(), 1);
var import_element234 = __toESM(require_element(), 1);
var import_jsx_runtime405 = __toESM(require_jsx_runtime(), 1);
var { ValidatedInputControl: ValidatedInputControl2 } = unlock3(import_components230.privateApis);
function ValidatedText({
data,
field,
onChange,
hideLabelFromVision,
type,
prefix: prefix2,
suffix,
validity
}) {
const { label, placeholder, description, getValue, setValue, isValid: isValid2 } = field;
const value = getValue({ item: data });
const onChangeControl = (0, import_element234.useCallback)(
(newValue) => onChange(
setValue({
item: data,
value: newValue
})
),
[data, setValue, onChange]
);
return /* @__PURE__ */ (0, import_jsx_runtime405.jsx)(
ValidatedInputControl2,
{
required: !!isValid2.required,
customValidity: getCustomValidity(isValid2, validity),
label,
placeholder,
value: value ?? "",
help: description,
onChange: onChangeControl,
hideLabelFromVision,
type,
prefix: prefix2,
suffix,
pattern: isValid2.pattern ? isValid2.pattern.constraint : void 0,
minLength: isValid2.minLength ? isValid2.minLength.constraint : void 0,
maxLength: isValid2.maxLength ? isValid2.maxLength.constraint : void 0,
__next40pxDefaultSize: true
}
);
}
// packages/dataviews/build-module/components/dataform-controls/email.mjs
var import_jsx_runtime406 = __toESM(require_jsx_runtime(), 1);
function Email({
data,
field,
onChange,
hideLabelFromVision,
validity
}) {
return /* @__PURE__ */ (0, import_jsx_runtime406.jsx)(
ValidatedText,
{
...{
data,
field,
onChange,
hideLabelFromVision,
validity,
type: "email",
prefix: /* @__PURE__ */ (0, import_jsx_runtime406.jsx)(import_components231.__experimentalInputControlPrefixWrapper, { variant: "icon", children: /* @__PURE__ */ (0, import_jsx_runtime406.jsx)(import_components231.Icon, { icon: envelope_default }) })
}
}
);
}
// packages/dataviews/build-module/components/dataform-controls/telephone.mjs
var import_components232 = __toESM(require_components(), 1);
var import_jsx_runtime407 = __toESM(require_jsx_runtime(), 1);
function Telephone({
data,
field,
onChange,
hideLabelFromVision,
validity
}) {
return /* @__PURE__ */ (0, import_jsx_runtime407.jsx)(
ValidatedText,
{
...{
data,
field,
onChange,
hideLabelFromVision,
validity,
type: "tel",
prefix: /* @__PURE__ */ (0, import_jsx_runtime407.jsx)(import_components232.__experimentalInputControlPrefixWrapper, { variant: "icon", children: /* @__PURE__ */ (0, import_jsx_runtime407.jsx)(import_components232.Icon, { icon: mobile_default }) })
}
}
);
}
// packages/dataviews/build-module/components/dataform-controls/url.mjs
var import_components233 = __toESM(require_components(), 1);
var import_jsx_runtime408 = __toESM(require_jsx_runtime(), 1);
function Url({
data,
field,
onChange,
hideLabelFromVision,
validity
}) {
return /* @__PURE__ */ (0, import_jsx_runtime408.jsx)(
ValidatedText,
{
...{
data,
field,
onChange,
hideLabelFromVision,
validity,
type: "url",
prefix: /* @__PURE__ */ (0, import_jsx_runtime408.jsx)(import_components233.__experimentalInputControlPrefixWrapper, { variant: "icon", children: /* @__PURE__ */ (0, import_jsx_runtime408.jsx)(import_components233.Icon, { icon: link_default }) })
}
}
);
}
// packages/dataviews/build-module/components/dataform-controls/utils/validated-number.mjs
var import_components234 = __toESM(require_components(), 1);
var import_element235 = __toESM(require_element(), 1);
var import_i18n216 = __toESM(require_i18n(), 1);
var import_jsx_runtime409 = __toESM(require_jsx_runtime(), 1);
var { ValidatedNumberControl } = unlock3(import_components234.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 [min = "", max = ""] = value;
const onChangeMin = (0, import_element235.useCallback)(
(newValue) => onChange([toNumberOrEmpty(newValue), max]),
[onChange, max]
);
const onChangeMax = (0, import_element235.useCallback)(
(newValue) => onChange([min, toNumberOrEmpty(newValue)]),
[onChange, min]
);
return /* @__PURE__ */ (0, import_jsx_runtime409.jsx)(
import_components234.BaseControl,
{
help: (0, import_i18n216.__)("The max. value must be greater than the min. value."),
children: /* @__PURE__ */ (0, import_jsx_runtime409.jsxs)(import_components234.Flex, { direction: "row", gap: 4, children: [
/* @__PURE__ */ (0, import_jsx_runtime409.jsx)(
import_components234.__experimentalNumberControl,
{
label: (0, import_i18n216.__)("Min."),
value: min,
max: max ? Number(max) - step : void 0,
onChange: onChangeMin,
__next40pxDefaultSize: true,
hideLabelFromVision,
step
}
),
/* @__PURE__ */ (0, import_jsx_runtime409.jsx)(
import_components234.__experimentalNumberControl,
{
label: (0, import_i18n216.__)("Max."),
value: max,
min: min ? Number(min) + step : void 0,
onChange: onChangeMax,
__next40pxDefaultSize: true,
hideLabelFromVision,
step
}
)
] })
}
);
}
function ValidatedNumber({
data,
field,
onChange,
hideLabelFromVision,
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 onChangeControl = (0, import_element235.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_element235.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_runtime409.jsx)(
BetweenControls,
{
value: valueBetween,
onChange: onChangeBetweenControls,
hideLabelFromVision,
step
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime409.jsx)(
ValidatedNumberControl,
{
required: !!isValid2.required,
customValidity: getCustomValidity(isValid2, validity),
label,
help: description,
value,
onChange: onChangeControl,
__next40pxDefaultSize: true,
hideLabelFromVision,
step,
min: isValid2.min ? isValid2.min.constraint : void 0,
max: isValid2.max ? isValid2.max.constraint : void 0
}
);
}
// packages/dataviews/build-module/components/dataform-controls/integer.mjs
var import_jsx_runtime410 = __toESM(require_jsx_runtime(), 1);
function Integer(props) {
return /* @__PURE__ */ (0, import_jsx_runtime410.jsx)(ValidatedNumber, { ...props });
}
// packages/dataviews/build-module/components/dataform-controls/number.mjs
var import_jsx_runtime411 = __toESM(require_jsx_runtime(), 1);
function Number2(props) {
return /* @__PURE__ */ (0, import_jsx_runtime411.jsx)(ValidatedNumber, { ...props });
}
// packages/dataviews/build-module/components/dataform-controls/radio.mjs
var import_components235 = __toESM(require_components(), 1);
var import_element236 = __toESM(require_element(), 1);
var import_jsx_runtime412 = __toESM(require_jsx_runtime(), 1);
var { ValidatedRadioControl } = unlock3(import_components235.privateApis);
function Radio({
data,
field,
onChange,
hideLabelFromVision,
validity
}) {
const { label, description, getValue, setValue, isValid: isValid2 } = field;
const { elements, isLoading } = useElements({
elements: field.elements,
getElements: field.getElements
});
const value = getValue({ item: data });
const onChangeControl = (0, import_element236.useCallback)(
(newValue) => onChange(setValue({ item: data, value: newValue })),
[data, onChange, setValue]
);
if (isLoading) {
return /* @__PURE__ */ (0, import_jsx_runtime412.jsx)(import_components235.Spinner, {});
}
return /* @__PURE__ */ (0, import_jsx_runtime412.jsx)(
ValidatedRadioControl,
{
required: !!field.isValid?.required,
customValidity: getCustomValidity(isValid2, validity),
label,
help: description,
onChange: onChangeControl,
options: elements,
selected: value,
hideLabelFromVision
}
);
}
// packages/dataviews/build-module/components/dataform-controls/select.mjs
var import_components236 = __toESM(require_components(), 1);
var import_element237 = __toESM(require_element(), 1);
var import_jsx_runtime413 = __toESM(require_jsx_runtime(), 1);
var { ValidatedSelectControl } = unlock3(import_components236.privateApis);
function Select({
data,
field,
onChange,
hideLabelFromVision,
validity
}) {
const { type, label, description, getValue, setValue, isValid: isValid2 } = field;
const isMultiple = type === "array";
const value = getValue({ item: data }) ?? (isMultiple ? [] : "");
const onChangeControl = (0, import_element237.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_runtime413.jsx)(import_components236.Spinner, {});
}
return /* @__PURE__ */ (0, import_jsx_runtime413.jsx)(
ValidatedSelectControl,
{
required: !!field.isValid?.required,
customValidity: getCustomValidity(isValid2, validity),
label,
value,
help: description,
options: elements,
onChange: onChangeControl,
__next40pxDefaultSize: true,
hideLabelFromVision,
multiple: isMultiple
}
);
}
// packages/dataviews/build-module/components/dataform-controls/text.mjs
var import_element238 = __toESM(require_element(), 1);
var import_jsx_runtime414 = __toESM(require_jsx_runtime(), 1);
function Text11({
data,
field,
onChange,
hideLabelFromVision,
config: config2,
validity
}) {
const { prefix: prefix2, suffix } = config2 || {};
return /* @__PURE__ */ (0, import_jsx_runtime414.jsx)(
ValidatedText,
{
...{
data,
field,
onChange,
hideLabelFromVision,
validity,
prefix: prefix2 ? (0, import_element238.createElement)(prefix2) : void 0,
suffix: suffix ? (0, import_element238.createElement)(suffix) : void 0
}
}
);
}
// packages/dataviews/build-module/components/dataform-controls/toggle.mjs
var import_components237 = __toESM(require_components(), 1);
var import_element239 = __toESM(require_element(), 1);
var import_jsx_runtime415 = __toESM(require_jsx_runtime(), 1);
var { ValidatedToggleControl } = unlock3(import_components237.privateApis);
function Toggle({
field,
onChange,
data,
hideLabelFromVision,
validity
}) {
const { label, description, getValue, setValue, isValid: isValid2 } = field;
const onChangeControl = (0, import_element239.useCallback)(() => {
onChange(
setValue({ item: data, value: !getValue({ item: data }) })
);
}, [onChange, setValue, data, getValue]);
return /* @__PURE__ */ (0, import_jsx_runtime415.jsx)(
ValidatedToggleControl,
{
required: !!isValid2.required,
customValidity: getCustomValidity(isValid2, validity),
hidden: hideLabelFromVision,
label,
help: description,
checked: getValue({ item: data }),
onChange: onChangeControl
}
);
}
// packages/dataviews/build-module/components/dataform-controls/textarea.mjs
var import_components238 = __toESM(require_components(), 1);
var import_element240 = __toESM(require_element(), 1);
var import_jsx_runtime416 = __toESM(require_jsx_runtime(), 1);
var { ValidatedTextareaControl } = unlock3(import_components238.privateApis);
function Textarea({
data,
field,
onChange,
hideLabelFromVision,
config: config2,
validity
}) {
const { rows = 4 } = config2 || {};
const { label, placeholder, description, setValue, isValid: isValid2 } = field;
const value = field.getValue({ item: data });
const onChangeControl = (0, import_element240.useCallback)(
(newValue) => onChange(setValue({ item: data, value: newValue })),
[data, onChange, setValue]
);
return /* @__PURE__ */ (0, import_jsx_runtime416.jsx)(
ValidatedTextareaControl,
{
required: !!isValid2.required,
customValidity: getCustomValidity(isValid2, validity),
label,
placeholder,
value: value ?? "",
help: description,
onChange: onChangeControl,
rows,
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/toggle-group.mjs
var import_components239 = __toESM(require_components(), 1);
var import_element241 = __toESM(require_element(), 1);
var import_jsx_runtime417 = __toESM(require_jsx_runtime(), 1);
var { ValidatedToggleGroupControl } = unlock3(import_components239.privateApis);
function ToggleGroup({
data,
field,
onChange,
hideLabelFromVision,
validity
}) {
const { getValue, setValue, isValid: isValid2 } = field;
const value = getValue({ item: data });
const onChangeControl = (0, import_element241.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_runtime417.jsx)(import_components239.Spinner, {});
}
if (elements.length === 0) {
return null;
}
const selectedOption = elements.find((el) => el.value === value);
return /* @__PURE__ */ (0, import_jsx_runtime417.jsx)(
ValidatedToggleGroupControl,
{
required: !!field.isValid?.required,
customValidity: getCustomValidity(isValid2, validity),
__next40pxDefaultSize: true,
isBlock: true,
label: field.label,
help: selectedOption?.description || field.description,
onChange: onChangeControl,
value,
hideLabelFromVision,
children: elements.map((el) => /* @__PURE__ */ (0, import_jsx_runtime417.jsx)(
import_components239.__experimentalToggleGroupControlOption,
{
label: el.label,
value: el.value
},
el.value
))
}
);
}
// packages/dataviews/build-module/components/dataform-controls/array.mjs
var import_components240 = __toESM(require_components(), 1);
var import_element242 = __toESM(require_element(), 1);
var import_jsx_runtime418 = __toESM(require_jsx_runtime(), 1);
var { ValidatedFormTokenField } = unlock3(import_components240.privateApis);
function ArrayControl({
data,
field,
onChange,
hideLabelFromVision,
validity
}) {
const { label, placeholder, getValue, setValue, isValid: isValid2 } = field;
const value = getValue({ item: data });
const { elements, isLoading } = useElements({
elements: field.elements,
getElements: field.getElements
});
const arrayValueAsElements = (0, import_element242.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_element242.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_runtime418.jsx)(import_components240.Spinner, {});
}
return /* @__PURE__ */ (0, import_jsx_runtime418.jsx)(
ValidatedFormTokenField,
{
required: !!isValid2?.required,
customValidity: getCustomValidity(isValid2, validity),
label: hideLabelFromVision ? void 0 : label,
value: arrayValueAsElements,
onChange: onChangeControl,
placeholder,
suggestions: elements?.map((element) => element.value),
__experimentalValidateInput: (token) => {
if (field.isValid?.elements && elements) {
return elements.some(
(element) => element.value === token || element.label === token
);
}
return true;
},
__experimentalExpandOnFocus: elements && elements.length > 0,
__experimentalShowHowTo: !field.isValid?.elements,
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_runtime418.jsx)("span", { children: element?.label || item });
}
return /* @__PURE__ */ (0, import_jsx_runtime418.jsx)("span", { children: item });
}
}
);
}
// packages/dataviews/build-module/components/dataform-controls/color.mjs
var import_components241 = __toESM(require_components(), 1);
var import_element243 = __toESM(require_element(), 1);
var import_jsx_runtime419 = __toESM(require_jsx_runtime(), 1);
var { ValidatedInputControl: ValidatedInputControl3, Picker } = unlock3(import_components241.privateApis);
var ColorPicker = ({
color,
onColorChange
}) => {
const validColor = color && w(color).isValid() ? color : "#ffffff";
return /* @__PURE__ */ (0, import_jsx_runtime419.jsx)(
import_components241.Dropdown,
{
renderToggle: ({ onToggle, isOpen }) => /* @__PURE__ */ (0, import_jsx_runtime419.jsx)(import_components241.__experimentalInputControlPrefixWrapper, { variant: "icon", children: /* @__PURE__ */ (0, import_jsx_runtime419.jsx)(
"button",
{
type: "button",
onClick: onToggle,
style: {
width: "24px",
height: "24px",
borderRadius: "50%",
backgroundColor: validColor,
border: "1px solid #ddd",
cursor: "pointer",
outline: isOpen ? "2px solid #007cba" : "none",
outlineOffset: "2px",
display: "flex",
alignItems: "center",
justifyContent: "center",
padding: 0,
margin: 0
},
"aria-label": "Open color picker"
}
) }),
renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime419.jsx)("div", { style: { padding: "16px" }, children: /* @__PURE__ */ (0, import_jsx_runtime419.jsx)(
Picker,
{
color: w(validColor),
onChange: onColorChange,
enableAlpha: true
}
) })
}
);
};
function Color({
data,
field,
onChange,
hideLabelFromVision,
validity
}) {
const { label, placeholder, description, setValue, isValid: isValid2 } = field;
const value = field.getValue({ item: data }) || "";
const handleColorChange = (0, import_element243.useCallback)(
(colorObject) => {
onChange(setValue({ item: data, value: colorObject.toHex() }));
},
[data, onChange, setValue]
);
const handleInputChange = (0, import_element243.useCallback)(
(newValue) => {
onChange(setValue({ item: data, value: newValue || "" }));
},
[data, onChange, setValue]
);
return /* @__PURE__ */ (0, import_jsx_runtime419.jsx)(
ValidatedInputControl3,
{
required: !!field.isValid?.required,
customValidity: getCustomValidity(isValid2, validity),
label,
placeholder,
value,
help: description,
onChange: handleInputChange,
hideLabelFromVision,
type: "text",
prefix: /* @__PURE__ */ (0, import_jsx_runtime419.jsx)(
ColorPicker,
{
color: value,
onColorChange: handleColorChange
}
)
}
);
}
// packages/dataviews/build-module/components/dataform-controls/password.mjs
var import_components242 = __toESM(require_components(), 1);
var import_element244 = __toESM(require_element(), 1);
var import_i18n217 = __toESM(require_i18n(), 1);
var import_jsx_runtime420 = __toESM(require_jsx_runtime(), 1);
function Password({
data,
field,
onChange,
hideLabelFromVision,
validity
}) {
const [isVisible, setIsVisible] = (0, import_element244.useState)(false);
const toggleVisibility = (0, import_element244.useCallback)(() => {
setIsVisible((prev) => !prev);
}, []);
return /* @__PURE__ */ (0, import_jsx_runtime420.jsx)(
ValidatedText,
{
...{
data,
field,
onChange,
hideLabelFromVision,
validity,
type: isVisible ? "text" : "password",
suffix: /* @__PURE__ */ (0, import_jsx_runtime420.jsx)(import_components242.__experimentalInputControlSuffixWrapper, { variant: "control", children: /* @__PURE__ */ (0, import_jsx_runtime420.jsx)(
import_components242.Button,
{
icon: isVisible ? unseen_default : seen_default,
onClick: toggleVisibility,
size: "small",
label: isVisible ? (0, import_i18n217.__)("Hide password") : (0, import_i18n217.__)("Show password")
}
) })
}
}
);
}
// 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_runtime421 = __toESM(require_jsx_runtime(), 1);
var FORM_CONTROLS = {
array: ArrayControl,
checkbox: Checkbox,
color: Color,
datetime: DateTime,
date: DateControl,
email: Email,
telephone: Telephone,
url: Url,
integer: Integer,
number: Number2,
password: Password,
radio: Radio,
select: Select,
text: Text11,
toggle: Toggle,
textarea: Textarea,
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_runtime421.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("select");
}
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_i18n218 = __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_runtime422 = __toESM(require_jsx_runtime(), 1);
function render({
item,
field
}) {
if (field.hasElements) {
return /* @__PURE__ */ (0, import_jsx_runtime422.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_i18n218.__)("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_i18n219 = __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_i18n219.__)("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_i18n220 = __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_i18n220.__)("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_date7 = __toESM(require_date(), 1);
var format4 = {
datetime: (0, import_date7.getSettings)().formats.datetime,
weekStartsOn: (0, import_date7.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_date7.dateI18n)(formatDatetime.datetime, (0, import_date7.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
}
};
// packages/dataviews/build-module/field-types/date.mjs
var import_date8 = __toESM(require_date(), 1);
var format5 = {
date: (0, import_date8.getSettings)().formats.date,
weekStartsOn: (0, import_date8.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_date8.dateI18n)(formatDate2.date, (0, import_date8.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
}
};
// packages/dataviews/build-module/field-types/boolean.mjs
var import_i18n221 = __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_i18n221.__)("True");
}
if (value === false) {
return (0, import_i18n221.__)("False");
}
return "";
}
function isValidCustom4(item, field) {
const value = field.getValue({ item });
if (![void 0, "", null].includes(value) && ![true, false].includes(value)) {
return (0, import_i18n221.__)("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_i18n222 = __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_i18n222.__)("Value must be an array.");
}
if (!value.every((v2) => typeof v2 === "string")) {
return (0, import_i18n222.__)("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_i18n223 = __toESM(require_i18n(), 1);
var import_jsx_runtime423 = __toESM(require_jsx_runtime(), 1);
function render3({ item, field }) {
if (field.hasElements) {
return /* @__PURE__ */ (0, import_jsx_runtime423.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_runtime423.jsxs)("div", { style: { display: "flex", alignItems: "center", gap: "8px" }, children: [
/* @__PURE__ */ (0, import_jsx_runtime423.jsx)(
"div",
{
style: {
width: "16px",
height: "16px",
borderRadius: "50%",
backgroundColor: value,
border: "1px solid #ddd",
flexShrink: 0
}
}
),
/* @__PURE__ */ (0, import_jsx_runtime423.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_i18n223.__)("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 getIsValid(field, fieldType) {
let required;
if (field.isValid?.required === true && fieldType.validate.required !== void 0) {
required = {
constraint: true,
validate: fieldType.validate.required
};
}
let elements;
if ((field.isValid?.elements === true || // elements is enabled unless the field opts-out
field.isValid?.elements === void 0 && (!!field.elements || !!field.getElements)) && fieldType.validate.elements !== void 0) {
elements = {
constraint: true,
validate: fieldType.validate.elements
};
}
let min;
if (typeof field.isValid?.min === "number" && fieldType.validate.min !== void 0) {
min = {
constraint: field.isValid.min,
validate: fieldType.validate.min
};
}
let max;
if (typeof field.isValid?.max === "number" && fieldType.validate.max !== void 0) {
max = {
constraint: field.isValid.max,
validate: fieldType.validate.max
};
}
let minLength;
if (typeof field.isValid?.minLength === "number" && fieldType.validate.minLength !== void 0) {
minLength = {
constraint: field.isValid.minLength,
validate: fieldType.validate.minLength
};
}
let maxLength;
if (typeof field.isValid?.maxLength === "number" && fieldType.validate.maxLength !== void 0) {
maxLength = {
constraint: field.isValid.maxLength,
validate: fieldType.validate.maxLength
};
}
let pattern;
if (field.isValid?.pattern !== void 0 && fieldType.validate.pattern !== void 0) {
pattern = {
constraint: field.isValid?.pattern,
validate: fieldType.validate.pattern
};
}
const custom = field.isValid?.custom ?? fieldType.validate.custom;
return {
required,
elements,
min,
max,
minLength,
maxLength,
pattern,
custom
};
}
// 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,
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
),
format: get_format_default(field, fieldType),
getValueFormatted: field.getValueFormatted ?? fieldType.getValueFormatted
};
});
}
// packages/dataviews/build-module/dataform/index.mjs
var import_element254 = __toESM(require_element(), 1);
// packages/dataviews/build-module/components/dataform-context/index.mjs
var import_element245 = __toESM(require_element(), 1);
var import_jsx_runtime424 = __toESM(require_jsx_runtime(), 1);
var DataFormContext = (0, import_element245.createContext)({
fields: []
});
DataFormContext.displayName = "DataFormContext";
function DataFormProvider({
fields,
children
}) {
return /* @__PURE__ */ (0, import_jsx_runtime424.jsx)(DataFormContext.Provider, { value: { fields }, children });
}
var dataform_context_default = DataFormContext;
// packages/dataviews/build-module/components/dataform-layouts/data-form-layout.mjs
var import_element253 = __toESM(require_element(), 1);
// packages/dataviews/build-module/components/dataform-layouts/regular/index.mjs
var import_element246 = __toESM(require_element(), 1);
var import_components243 = __toESM(require_components(), 1);
// packages/dataviews/build-module/components/dataform-layouts/normalize-form.mjs
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];
normalizedLayout = {
type: "panel",
labelPosition: layout?.labelPosition ?? "side",
openAs: layout?.openAs ?? "dropdown",
summary: normalizedSummary
};
} 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_runtime425 = __toESM(require_jsx_runtime(), 1);
function Header({ title }) {
return /* @__PURE__ */ (0, import_jsx_runtime425.jsx)(
Stack,
{
direction: "column",
className: "dataforms-layouts-regular__header",
gap: "md",
children: /* @__PURE__ */ (0, import_jsx_runtime425.jsx)(Stack, { direction: "row", align: "center", children: /* @__PURE__ */ (0, import_jsx_runtime425.jsx)(import_components243.__experimentalHeading, { level: 2, size: 13, children: title }) })
}
);
}
function FormRegularField({
data,
field,
onChange,
hideLabelFromVision,
validity
}) {
const { fields } = (0, import_element246.useContext)(dataform_context_default);
const layout = field.layout;
const form = (0, import_element246.useMemo)(
() => ({
layout: DEFAULT_LAYOUT,
fields: !!field.children ? field.children : []
}),
[field]
);
if (!!field.children) {
return /* @__PURE__ */ (0, import_jsx_runtime425.jsxs)(import_jsx_runtime425.Fragment, { children: [
!hideLabelFromVision && field.label && /* @__PURE__ */ (0, import_jsx_runtime425.jsx)(Header, { title: field.label }),
/* @__PURE__ */ (0, import_jsx_runtime425.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_runtime425.jsxs)(
Stack,
{
direction: "row",
className: "dataforms-layouts-regular__field",
gap: "xs",
children: [
/* @__PURE__ */ (0, import_jsx_runtime425.jsx)(
"div",
{
className: clsx_default(
"dataforms-layouts-regular__field-label",
`dataforms-layouts-regular__field-label--label-position-${labelPosition}`
),
children: fieldDefinition.label
}
),
/* @__PURE__ */ (0, import_jsx_runtime425.jsx)("div", { className: "dataforms-layouts-regular__field-control", children: fieldDefinition.readOnly === true ? /* @__PURE__ */ (0, import_jsx_runtime425.jsx)(
fieldDefinition.render,
{
item: data,
field: fieldDefinition
}
) : /* @__PURE__ */ (0, import_jsx_runtime425.jsx)(
fieldDefinition.Edit,
{
data,
field: fieldDefinition,
onChange,
hideLabelFromVision: true,
validity
},
fieldDefinition.id
) })
]
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime425.jsx)("div", { className: "dataforms-layouts-regular__field", children: fieldDefinition.readOnly === true ? /* @__PURE__ */ (0, import_jsx_runtime425.jsx)(import_jsx_runtime425.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime425.jsxs)(import_jsx_runtime425.Fragment, { children: [
!hideLabelFromVision && labelPosition !== "none" && /* @__PURE__ */ (0, import_jsx_runtime425.jsx)(import_components243.BaseControl.VisualLabel, { children: fieldDefinition.label }),
/* @__PURE__ */ (0, import_jsx_runtime425.jsx)(
fieldDefinition.render,
{
item: data,
field: fieldDefinition
}
)
] }) }) : /* @__PURE__ */ (0, import_jsx_runtime425.jsx)(
fieldDefinition.Edit,
{
data,
field: fieldDefinition,
onChange,
hideLabelFromVision: labelPosition === "none" ? true : hideLabelFromVision,
validity
}
) });
}
// packages/dataviews/build-module/components/dataform-layouts/panel/index.mjs
var import_components247 = __toESM(require_components(), 1);
var import_element250 = __toESM(require_element(), 1);
// packages/dataviews/build-module/components/dataform-layouts/panel/dropdown.mjs
var import_components245 = __toESM(require_components(), 1);
var import_i18n225 = __toESM(require_i18n(), 1);
var import_element247 = __toESM(require_element(), 1);
var import_compose95 = __toESM(require_compose(), 1);
// packages/dataviews/build-module/components/dataform-layouts/panel/summary-button.mjs
var import_components244 = __toESM(require_components(), 1);
var import_i18n224 = __toESM(require_i18n(), 1);
var import_jsx_runtime426 = __toESM(require_jsx_runtime(), 1);
function SummaryButton({
summaryFields,
data,
labelPosition,
fieldLabel,
disabled,
onClick,
"aria-expanded": ariaExpanded
}) {
return /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
import_components244.Button,
{
className: "dataforms-layouts-panel__summary-button",
size: "compact",
variant: ["none", "top"].includes(labelPosition) ? "link" : "tertiary",
"aria-expanded": ariaExpanded,
"aria-label": (0, import_i18n224.sprintf)(
// translators: %s: Field name.
(0, import_i18n224._x)("Edit %s", "field"),
fieldLabel || ""
),
onClick,
disabled,
accessibleWhenDisabled: true,
style: summaryFields.length > 1 ? {
minHeight: "auto",
height: "auto",
alignItems: "flex-start"
} : void 0,
children: summaryFields.length > 1 ? /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
"div",
{
style: {
display: "flex",
flexDirection: "column",
alignItems: "flex-start",
width: "100%",
gap: "2px"
},
children: summaryFields.map((summaryField) => /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
"div",
{
style: { width: "100%" },
children: /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
summaryField.render,
{
item: data,
field: summaryField
}
)
},
summaryField.id
))
}
) : summaryFields.map((summaryField) => /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
summaryField.render,
{
item: data,
field: summaryField
},
summaryField.id
))
}
);
}
var summary_button_default = SummaryButton;
// packages/dataviews/build-module/components/dataform-layouts/panel/dropdown.mjs
var import_jsx_runtime427 = __toESM(require_jsx_runtime(), 1);
function DropdownHeader({
title,
onClose
}) {
return /* @__PURE__ */ (0, import_jsx_runtime427.jsx)(
Stack,
{
direction: "column",
className: "dataforms-layouts-panel__dropdown-header",
gap: "md",
children: /* @__PURE__ */ (0, import_jsx_runtime427.jsxs)(Stack, { direction: "row", gap: "xs", align: "center", children: [
title && /* @__PURE__ */ (0, import_jsx_runtime427.jsx)(import_components245.__experimentalHeading, { level: 2, size: 13, children: title }),
/* @__PURE__ */ (0, import_jsx_runtime427.jsx)(import_components245.__experimentalSpacer, { style: { flex: 1 } }),
onClose && /* @__PURE__ */ (0, import_jsx_runtime427.jsx)(
import_components245.Button,
{
label: (0, import_i18n225.__)("Close"),
icon: close_small_default,
onClick: onClose,
size: "small"
}
)
] })
}
);
}
function PanelDropdown({
data,
field,
onChange,
validity,
labelPosition = "side",
summaryFields,
fieldDefinition,
popoverAnchor,
onOpen
}) {
const fieldLabel = !!field.children ? field.label : fieldDefinition?.label;
const form = (0, import_element247.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_element247.useMemo)(() => {
if (validity === void 0) {
return void 0;
}
if (!!field.children) {
return validity?.children;
}
return { [field.id]: validity };
}, [validity, field]);
const popoverProps3 = (0, import_element247.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 focusOnMountRef = (0, import_compose95.useFocusOnMount)("firstInputElement");
return /* @__PURE__ */ (0, import_jsx_runtime427.jsx)(
import_components245.Dropdown,
{
contentClassName: "dataforms-layouts-panel__field-dropdown",
popoverProps: popoverProps3,
focusOnMount: false,
toggleProps: {
size: "compact",
variant: "tertiary",
tooltipPosition: "middle left"
},
renderToggle: ({ isOpen, onToggle }) => /* @__PURE__ */ (0, import_jsx_runtime427.jsx)(
summary_button_default,
{
summaryFields,
data,
labelPosition,
fieldLabel,
disabled: fieldDefinition.readOnly === true,
onClick: () => {
if (!isOpen && onOpen) {
onOpen();
}
onToggle();
},
"aria-expanded": isOpen
}
),
renderContent: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime427.jsxs)(import_jsx_runtime427.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime427.jsx)(DropdownHeader, { title: fieldLabel, onClose }),
/* @__PURE__ */ (0, import_jsx_runtime427.jsx)("div", { ref: focusOnMountRef, children: /* @__PURE__ */ (0, import_jsx_runtime427.jsx)(
DataFormLayout,
{
data,
form,
onChange,
validity: formValidity,
children: (FieldLayout, childField, childFieldValidity) => /* @__PURE__ */ (0, import_jsx_runtime427.jsx)(
FieldLayout,
{
data,
field: childField,
onChange,
hideLabelFromVision: (form?.fields ?? []).length < 2,
validity: childFieldValidity
},
childField.id
)
}
) })
] })
}
);
}
var dropdown_default2 = PanelDropdown;
// packages/dataviews/build-module/components/dataform-layouts/panel/modal.mjs
var import_deepmerge2 = __toESM(require_cjs(), 1);
var import_components246 = __toESM(require_components(), 1);
var import_i18n227 = __toESM(require_i18n(), 1);
var import_element249 = __toESM(require_element(), 1);
var import_compose96 = __toESM(require_compose(), 1);
// packages/dataviews/build-module/hooks/use-form-validity.mjs
var import_deepmerge = __toESM(require_cjs(), 1);
var import_es66 = __toESM(require_es6(), 1);
var import_element248 = __toESM(require_element(), 1);
var import_i18n226 = __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 === "valid";
}
);
});
}
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 = current[segment];
}
const finalKey = path[path.length - 1];
current[finalKey] = {
...current[finalKey] || {},
...fieldValidity
};
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_i18n226.__)("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_i18n226.__)(
"Value must be one of the elements."
)
}
},
[...path, formField.id]
);
return newFormValidity;
});
}
}).catch((error) => {
if (currentToken !== elementsCounterRef.current[formField.id]) {
return;
}
let errorMessage;
if (error instanceof Error) {
errorMessage = error.message;
} else {
errorMessage = String(error) || (0, import_i18n226.__)(
"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) => {
const newFormValidity = setValidityAtPath(
prev,
{
custom: {
type: "valid",
message: (0, import_i18n226.__)("Valid")
}
},
[...path, formField.id]
);
return newFormValidity;
});
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_i18n226.__)("Validation could not be processed.")
}
},
[...path, formField.id]
);
return newFormValidity;
});
}).catch((error) => {
if (currentToken !== customCounterRef.current[formField.id]) {
return;
}
let errorMessage;
if (error instanceof Error) {
errorMessage = error.message;
} else {
errorMessage = String(error) || (0, import_i18n226.__)(
"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_i18n226.__)("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_i18n226.__)("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_i18n226.__)("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_i18n226.__)("Value is too short.")
}
};
}
if (formField.field?.isValid.maxLength && !formField.field.isValid.maxLength.validate(item, formField.field)) {
return {
maxLength: {
type: "invalid",
message: (0, import_i18n226.__)("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_i18n226.__)("Value must be one of the elements.")
}
};
}
if (!!formField.field && formField.field.isValid.elements && formField.field.hasElements && typeof formField.field.getElements === "function") {
handleElementsValidationAsync(
formField.field.getElements(),
formField,
promiseHandler
);
return {
elements: {
type: "validating",
message: (0, import_i18n226.__)("Validating\u2026")
}
};
}
let customError;
if (!!formField.field && formField.field.isValid.custom) {
try {
const value = formField.field.getValue({ item });
customError = formField.field.isValid.custom(
(0, import_deepmerge.default)(
item,
formField.field.setValue({
item,
value
})
),
formField.field
);
} catch (error) {
let errorMessage;
if (error instanceof Error) {
errorMessage = error.message;
} else {
errorMessage = String(error) || (0, import_i18n226.__)("Unknown error when running custom validation.");
}
return {
custom: {
type: "invalid",
message: errorMessage
}
};
}
}
if (typeof customError === "string") {
return {
custom: {
type: "invalid",
message: customError
}
};
}
if (customError instanceof Promise) {
handleCustomValidationAsync(customError, formField, promiseHandler);
return {
custom: {
type: "validating",
message: (0, import_i18n226.__)("Validating\u2026")
}
};
}
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_element248.useState)();
const customCounterRef = (0, import_element248.useRef)({});
const elementsCounterRef = (0, import_element248.useRef)({});
const previousValuesRef = (0, import_element248.useRef)({});
const validate = (0, import_element248.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_element248.useEffect)(() => {
validate();
}, [validate]);
return {
validity: formValidity,
isValid: isFormValid(formValidity)
};
}
var use_form_validity_default = useFormValidity;
// packages/dataviews/build-module/components/dataform-layouts/panel/modal.mjs
var import_jsx_runtime428 = __toESM(require_jsx_runtime(), 1);
function ModalContent({
data,
field,
onChange,
fieldLabel,
onClose
}) {
const { fields } = (0, import_element249.useContext)(dataform_context_default);
const [changes, setChanges] = (0, import_element249.useState)({});
const modalData = (0, import_element249.useMemo)(() => {
return (0, import_deepmerge2.default)(data, changes, {
arrayMerge: (target, source) => source
});
}, [data, changes]);
const form = (0, import_element249.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_deepmerge2.default)(prev, newValue, {
arrayMerge: (target, source) => source
})
);
};
const focusOnMountRef = (0, import_compose96.useFocusOnMount)("firstInputElement");
return /* @__PURE__ */ (0, import_jsx_runtime428.jsxs)(
import_components246.Modal,
{
className: "dataforms-layouts-panel__modal",
onRequestClose: onClose,
isFullScreen: false,
title: fieldLabel,
size: "medium",
children: [
/* @__PURE__ */ (0, import_jsx_runtime428.jsx)("div", { ref: focusOnMountRef, children: /* @__PURE__ */ (0, import_jsx_runtime428.jsx)(
DataFormLayout,
{
data: modalData,
form,
onChange: handleOnChange,
validity,
children: (FieldLayout, childField, childFieldValidity) => /* @__PURE__ */ (0, import_jsx_runtime428.jsx)(
FieldLayout,
{
data: modalData,
field: childField,
onChange: handleOnChange,
hideLabelFromVision: form.fields.length < 2,
validity: childFieldValidity
},
childField.id
)
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime428.jsxs)(
Stack,
{
direction: "row",
className: "dataforms-layouts-panel__modal-footer",
gap: "sm",
children: [
/* @__PURE__ */ (0, import_jsx_runtime428.jsx)(import_components246.__experimentalSpacer, { style: { flex: 1 } }),
/* @__PURE__ */ (0, import_jsx_runtime428.jsx)(
import_components246.Button,
{
variant: "tertiary",
onClick: onClose,
__next40pxDefaultSize: true,
children: (0, import_i18n227.__)("Cancel")
}
),
/* @__PURE__ */ (0, import_jsx_runtime428.jsx)(
import_components246.Button,
{
variant: "primary",
onClick: onApply,
__next40pxDefaultSize: true,
children: (0, import_i18n227.__)("Apply")
}
)
]
}
)
]
}
);
}
function PanelModal({
data,
field,
onChange,
labelPosition,
summaryFields,
fieldDefinition,
onOpen
}) {
const [isOpen, setIsOpen] = (0, import_element249.useState)(false);
const fieldLabel = !!field.children ? field.label : fieldDefinition?.label;
return /* @__PURE__ */ (0, import_jsx_runtime428.jsxs)(import_jsx_runtime428.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime428.jsx)(
summary_button_default,
{
summaryFields,
data,
labelPosition,
fieldLabel,
disabled: fieldDefinition.readOnly === true,
onClick: () => {
if (onOpen) {
onOpen();
}
setIsOpen(true);
},
"aria-expanded": isOpen
}
),
isOpen && /* @__PURE__ */ (0, import_jsx_runtime428.jsx)(
ModalContent,
{
data,
field,
onChange,
fieldLabel: fieldLabel ?? "",
onClose: () => setIsOpen(false)
}
)
] });
}
var modal_default = PanelModal;
// 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/index.mjs
var import_jsx_runtime429 = __toESM(require_jsx_runtime(), 1);
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 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;
};
var getFieldDefinitionAndSummaryFields = (layout, field, fields) => {
const summaryFields = getSummaryFields(layout.summary, fields);
const fieldDefinition = getFieldDefinition(field, fields);
if (summaryFields.length === 0) {
return {
summaryFields: fieldDefinition ? [fieldDefinition] : [],
fieldDefinition
};
}
return {
summaryFields,
fieldDefinition
};
};
function FormPanelField({
data,
field,
onChange,
validity
}) {
const { fields } = (0, import_element250.useContext)(dataform_context_default);
const layout = field.layout;
const [popoverAnchor, setPopoverAnchor] = (0, import_element250.useState)(
null
);
const [touched, setTouched] = (0, import_element250.useState)(false);
const handleOpen = () => setTouched(true);
const { fieldDefinition, summaryFields } = getFieldDefinitionAndSummaryFields(layout, field, fields);
if (!fieldDefinition) {
return null;
}
const labelPosition = layout.labelPosition;
const errorMessage = getFirstValidationError(validity);
const showError = touched && !!errorMessage;
const labelClassName = clsx_default(
"dataforms-layouts-panel__field-label",
`dataforms-layouts-panel__field-label--label-position-${labelPosition}`,
{ "has-error": showError }
);
const fieldLabel = !!field.children ? field.label : fieldDefinition?.label;
const labelContent = showError ? /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(import_components247.Tooltip, { text: errorMessage, placement: "top", children: /* @__PURE__ */ (0, import_jsx_runtime429.jsxs)(
Stack,
{
direction: "row",
gap: "xs",
className: "dataforms-layouts-panel__field-label-error-content",
justify: "flex-start",
children: [
/* @__PURE__ */ (0, import_jsx_runtime429.jsx)(import_components247.Icon, { icon: error_default, size: 16 }),
/* @__PURE__ */ (0, import_jsx_runtime429.jsx)(import_jsx_runtime429.Fragment, { children: fieldLabel })
]
}
) }) : fieldLabel;
const renderedControl = layout.openAs === "modal" ? /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(
modal_default,
{
data,
field,
onChange,
labelPosition,
summaryFields,
fieldDefinition,
onOpen: handleOpen
}
) : /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(
dropdown_default2,
{
data,
field,
onChange,
validity,
labelPosition,
summaryFields,
fieldDefinition,
popoverAnchor,
onOpen: handleOpen
}
);
if (labelPosition === "top") {
return /* @__PURE__ */ (0, import_jsx_runtime429.jsxs)(
Stack,
{
direction: "column",
className: "dataforms-layouts-panel__field",
children: [
/* @__PURE__ */ (0, import_jsx_runtime429.jsx)(
"div",
{
className: labelClassName,
style: { paddingBottom: 0 },
children: labelContent
}
),
/* @__PURE__ */ (0, import_jsx_runtime429.jsx)("div", { className: "dataforms-layouts-panel__field-control", children: renderedControl })
]
}
);
}
if (labelPosition === "none") {
return /* @__PURE__ */ (0, import_jsx_runtime429.jsxs)(
Stack,
{
direction: "row",
gap: "xs",
className: "dataforms-layouts-panel__field dataforms-layouts-panel__field--label-position-none",
children: [
showError && /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(import_components247.Tooltip, { text: errorMessage, placement: "top", children: /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(
import_components247.Icon,
{
className: "dataforms-layouts-panel__field-label-error-content",
icon: error_default,
size: 16
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime429.jsx)("div", { className: "dataforms-layouts-panel__field-control", children: renderedControl })
]
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime429.jsxs)(
Stack,
{
direction: "row",
gap: "xs",
ref: setPopoverAnchor,
className: "dataforms-layouts-panel__field",
children: [
/* @__PURE__ */ (0, import_jsx_runtime429.jsx)("div", { className: labelClassName, children: labelContent }),
/* @__PURE__ */ (0, import_jsx_runtime429.jsx)("div", { className: "dataforms-layouts-panel__field-control", children: renderedControl })
]
}
);
}
// packages/dataviews/build-module/components/dataform-layouts/card/index.mjs
var import_components248 = __toESM(require_components(), 1);
var import_element251 = __toESM(require_element(), 1);
var import_jsx_runtime430 = __toESM(require_jsx_runtime(), 1);
var NonCollapsibleCardHeader = ({
children,
...props
}) => /* @__PURE__ */ (0, import_jsx_runtime430.jsx)(import_components248.CardHeader, { isBorderless: true, ...props, children: /* @__PURE__ */ (0, import_jsx_runtime430.jsx)(
"div",
{
style: {
height: "40px",
// This is to match the chevron's __next40pxDefaultSize
width: "100%",
display: "flex",
justifyContent: "space-between",
alignItems: "center"
},
children
}
) });
function useCardHeader(layout) {
const { isOpened, isCollapsible } = layout;
const [isOpen, setIsOpen] = (0, import_element251.useState)(isOpened);
(0, import_element251.useEffect)(() => {
setIsOpen(isOpened);
}, [isOpened]);
const toggle = (0, import_element251.useCallback)(() => {
setIsOpen((prev) => !prev);
}, []);
const CollapsibleCardHeader = (0, import_element251.useCallback)(
({
children,
...props
}) => /* @__PURE__ */ (0, import_jsx_runtime430.jsxs)(
import_components248.CardHeader,
{
...props,
onClick: toggle,
style: {
cursor: "pointer",
...props.style
},
isBorderless: true,
children: [
/* @__PURE__ */ (0, import_jsx_runtime430.jsx)(
"div",
{
style: {
width: "100%",
display: "flex",
justifyContent: "space-between",
alignItems: "center"
},
children
}
),
/* @__PURE__ */ (0, import_jsx_runtime430.jsx)(
import_components248.Button,
{
__next40pxDefaultSize: true,
variant: "tertiary",
icon: isOpen ? chevron_up_default : chevron_down_default,
"aria-expanded": isOpen,
"aria-label": isOpen ? "Collapse" : "Expand"
}
)
]
}
),
[toggle, isOpen]
);
const effectiveIsOpen = isCollapsible ? isOpen : true;
const CardHeaderComponent = isCollapsible ? CollapsibleCardHeader : NonCollapsibleCardHeader;
return { isOpen: effectiveIsOpen, CardHeader: CardHeaderComponent };
}
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 FormCardField({
data,
field,
onChange,
hideLabelFromVision,
validity
}) {
const { fields } = (0, import_element251.useContext)(dataform_context_default);
const layout = field.layout;
const form = (0, import_element251.useMemo)(
() => ({
layout: DEFAULT_LAYOUT,
fields: field.children ?? []
}),
[field]
);
const { isOpen, CardHeader } = useCardHeader(layout);
const summaryFields = getSummaryFields(layout.summary, fields);
const visibleSummaryFields = summaryFields.filter(
(summaryField) => isSummaryFieldVisible(summaryField, layout.summary, isOpen)
);
const sizeCard = {
blockStart: "medium",
blockEnd: "medium",
inlineStart: "medium",
inlineEnd: "medium"
};
if (!!field.children) {
const withHeader2 = !!field.label && layout.withHeader;
const sizeCardBody2 = {
blockStart: withHeader2 ? "none" : "medium",
blockEnd: "medium",
inlineStart: "medium",
inlineEnd: "medium"
};
return /* @__PURE__ */ (0, import_jsx_runtime430.jsxs)(import_components248.Card, { className: "dataforms-layouts-card__field", size: sizeCard, children: [
withHeader2 && /* @__PURE__ */ (0, import_jsx_runtime430.jsxs)(CardHeader, { className: "dataforms-layouts-card__field-header", children: [
/* @__PURE__ */ (0, import_jsx_runtime430.jsx)("span", { className: "dataforms-layouts-card__field-header-label", children: field.label }),
visibleSummaryFields.length > 0 && layout.withHeader && /* @__PURE__ */ (0, import_jsx_runtime430.jsx)("div", { className: "dataforms-layouts-card__field-summary", children: visibleSummaryFields.map(
(summaryField) => /* @__PURE__ */ (0, import_jsx_runtime430.jsx)(
summaryField.render,
{
item: data,
field: summaryField
},
summaryField.id
)
) })
] }),
(isOpen || !withHeader2) && // If it doesn't have a header, keep it open.
// Otherwise, the card will not be visible.
/* @__PURE__ */ (0, import_jsx_runtime430.jsxs)(
import_components248.CardBody,
{
size: sizeCardBody2,
className: "dataforms-layouts-card__field-control",
children: [
field.description && /* @__PURE__ */ (0, import_jsx_runtime430.jsx)("div", { className: "dataforms-layouts-card__field-description", children: field.description }),
/* @__PURE__ */ (0, import_jsx_runtime430.jsx)(
DataFormLayout,
{
data,
form,
onChange,
validity: validity?.children
}
)
]
}
)
] });
}
const fieldDefinition = fields.find(
(fieldDef) => fieldDef.id === field.id
);
if (!fieldDefinition || !fieldDefinition.Edit) {
return null;
}
const RegularLayout = getFormFieldLayout("regular")?.component;
if (!RegularLayout) {
return null;
}
const withHeader = !!fieldDefinition.label && layout.withHeader;
const sizeCardBody = {
blockStart: withHeader ? "none" : "medium",
blockEnd: "medium",
inlineStart: "medium",
inlineEnd: "medium"
};
return /* @__PURE__ */ (0, import_jsx_runtime430.jsxs)(import_components248.Card, { className: "dataforms-layouts-card__field", size: sizeCard, children: [
withHeader && /* @__PURE__ */ (0, import_jsx_runtime430.jsxs)(CardHeader, { className: "dataforms-layouts-card__field-header", children: [
/* @__PURE__ */ (0, import_jsx_runtime430.jsx)("span", { className: "dataforms-layouts-card__field-header-label", children: fieldDefinition.label }),
visibleSummaryFields.length > 0 && layout.withHeader && /* @__PURE__ */ (0, import_jsx_runtime430.jsx)("div", { className: "dataforms-layouts-card__field-summary", children: visibleSummaryFields.map((summaryField) => /* @__PURE__ */ (0, import_jsx_runtime430.jsx)(
summaryField.render,
{
item: data,
field: summaryField
},
summaryField.id
)) })
] }),
(isOpen || !withHeader) && // If it doesn't have a header, keep it open.
// Otherwise, the card will not be visible.
/* @__PURE__ */ (0, import_jsx_runtime430.jsx)(
import_components248.CardBody,
{
size: sizeCardBody,
className: "dataforms-layouts-card__field-control",
children: /* @__PURE__ */ (0, import_jsx_runtime430.jsx)(
RegularLayout,
{
data,
field,
onChange,
hideLabelFromVision: hideLabelFromVision || withHeader,
validity
}
)
}
)
] });
}
// packages/dataviews/build-module/components/dataform-layouts/row/index.mjs
var import_components249 = __toESM(require_components(), 1);
var import_jsx_runtime431 = __toESM(require_jsx_runtime(), 1);
function Header2({ title }) {
return /* @__PURE__ */ (0, import_jsx_runtime431.jsx)(
Stack,
{
direction: "column",
className: "dataforms-layouts-row__header",
gap: "md",
children: /* @__PURE__ */ (0, import_jsx_runtime431.jsx)(Stack, { direction: "row", align: "center", children: /* @__PURE__ */ (0, import_jsx_runtime431.jsx)(import_components249.__experimentalHeading, { level: 2, size: 13, children: title }) })
}
);
}
var EMPTY_WRAPPER = ({ children }) => /* @__PURE__ */ (0, import_jsx_runtime431.jsx)(import_jsx_runtime431.Fragment, { children });
function FormRowField({
data,
field,
onChange,
hideLabelFromVision,
validity
}) {
const layout = field.layout;
if (!!field.children) {
const form = {
layout: DEFAULT_LAYOUT,
fields: field.children
};
return /* @__PURE__ */ (0, import_jsx_runtime431.jsxs)("div", { className: "dataforms-layouts-row__field", children: [
!hideLabelFromVision && field.label && /* @__PURE__ */ (0, import_jsx_runtime431.jsx)(Header2, { title: field.label }),
/* @__PURE__ */ (0, import_jsx_runtime431.jsx)(Stack, { direction: "row", align: layout.alignment, gap: "md", children: /* @__PURE__ */ (0, import_jsx_runtime431.jsx)(
DataFormLayout,
{
data,
form,
onChange,
validity: validity?.children,
as: EMPTY_WRAPPER,
children: (FieldLayout, childField, childFieldValidity) => /* @__PURE__ */ (0, import_jsx_runtime431.jsx)(
"div",
{
className: "dataforms-layouts-row__field-control",
style: layout.styles[childField.id],
children: /* @__PURE__ */ (0, import_jsx_runtime431.jsx)(
FieldLayout,
{
data,
field: childField,
onChange,
hideLabelFromVision,
validity: childFieldValidity
}
)
},
childField.id
)
}
) })
] });
}
const RegularLayout = getFormFieldLayout("regular")?.component;
if (!RegularLayout) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime431.jsx)(import_jsx_runtime431.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime431.jsx)("div", { className: "dataforms-layouts-row__field-control", children: /* @__PURE__ */ (0, import_jsx_runtime431.jsx)(
RegularLayout,
{
data,
field,
onChange,
validity
}
) }) });
}
// packages/dataviews/build-module/components/dataform-layouts/details/index.mjs
var import_element252 = __toESM(require_element(), 1);
var import_i18n228 = __toESM(require_i18n(), 1);
var import_jsx_runtime432 = __toESM(require_jsx_runtime(), 1);
function FormDetailsField({
data,
field,
onChange
}) {
const { fields } = (0, import_element252.useContext)(dataform_context_default);
const form = (0, import_element252.useMemo)(
() => ({
layout: DEFAULT_LAYOUT,
fields: field.children ?? []
}),
[field]
);
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_runtime432.jsx)(summaryField.render, { item: data, field: summaryField });
} else {
summaryContent = field.label || (0, import_i18n228.__)("More details");
}
return /* @__PURE__ */ (0, import_jsx_runtime432.jsxs)("details", { className: "dataforms-layouts-details__details", children: [
/* @__PURE__ */ (0, import_jsx_runtime432.jsx)("summary", { className: "dataforms-layouts-details__summary", children: summaryContent }),
/* @__PURE__ */ (0, import_jsx_runtime432.jsx)("div", { className: "dataforms-layouts-details__content", children: /* @__PURE__ */ (0, import_jsx_runtime432.jsx)(
DataFormLayout,
{
data,
form,
onChange
}
) })
] });
}
// packages/dataviews/build-module/components/dataform-layouts/index.mjs
var import_jsx_runtime433 = __toESM(require_jsx_runtime(), 1);
var FORM_FIELD_LAYOUTS = [
{
type: "regular",
component: FormRegularField,
wrapper: ({ children }) => /* @__PURE__ */ (0, import_jsx_runtime433.jsx)(
Stack,
{
direction: "column",
className: "dataforms-layouts__wrapper",
gap: "md",
children
}
)
},
{
type: "panel",
component: FormPanelField,
wrapper: ({ children }) => /* @__PURE__ */ (0, import_jsx_runtime433.jsx)(
Stack,
{
direction: "column",
className: "dataforms-layouts__wrapper",
gap: "xs",
children
}
)
},
{
type: "card",
component: FormCardField,
wrapper: ({ children }) => /* @__PURE__ */ (0, import_jsx_runtime433.jsx)(
Stack,
{
direction: "column",
className: "dataforms-layouts__wrapper",
gap: "lg",
children
}
)
},
{
type: "row",
component: FormRowField,
wrapper: ({
children,
layout
}) => /* @__PURE__ */ (0, import_jsx_runtime433.jsx)(
Stack,
{
direction: "column",
className: "dataforms-layouts__wrapper",
gap: "md",
children: /* @__PURE__ */ (0, import_jsx_runtime433.jsx)("div", { className: "dataforms-layouts-row__field", children: /* @__PURE__ */ (0, import_jsx_runtime433.jsx)(
Stack,
{
direction: "row",
gap: "md",
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_runtime434 = __toESM(require_jsx_runtime(), 1);
var DEFAULT_WRAPPER = ({ children }) => /* @__PURE__ */ (0, import_jsx_runtime434.jsx)(Stack, { direction: "column", className: "dataforms-layouts__wrapper", gap: "md", children });
function DataFormLayout({
data,
form,
onChange,
validity,
children,
as
}) {
const { fields: fieldDefinitions } = (0, import_element253.useContext)(dataform_context_default);
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_runtime434.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]
);
}
return /* @__PURE__ */ (0, import_jsx_runtime434.jsx)(
FieldLayout,
{
data,
field: formField,
onChange,
validity: validity?.[formField.id]
},
formField.id
);
}) });
}
// packages/dataviews/build-module/dataform/index.mjs
var import_jsx_runtime435 = __toESM(require_jsx_runtime(), 1);
function DataForm({
data,
form,
fields,
onChange,
validity
}) {
const normalizedForm = (0, import_element254.useMemo)(() => normalize_form_default(form), [form]);
const normalizedFields = (0, import_element254.useMemo)(
() => normalizeFields(fields),
[fields]
);
if (!form.fields) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime435.jsx)(DataFormProvider, { fields: normalizedFields, children: /* @__PURE__ */ (0, import_jsx_runtime435.jsx)(
DataFormLayout,
{
data,
form: normalizedForm,
onChange,
validity
}
) });
}
// packages/block-editor/build-module/hooks/block-fields/index.mjs
var import_element257 = __toESM(require_element(), 1);
var import_i18n232 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/hooks/block-fields/fields-dropdown-menu.mjs
var import_components250 = __toESM(require_components(), 1);
var import_i18n229 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/hooks/block-fields/use-inspector-popover-placement.mjs
var import_compose97 = __toESM(require_compose(), 1);
function useInspectorPopoverPlacement({ isControl } = { isControl: false }) {
const isMobile = (0, import_compose97.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_runtime436 = __toESM(require_jsx_runtime(), 1);
function FieldsDropdownMenu({
fields,
visibleFields,
onToggleField
}) {
const { popoverProps: popoverProps3 } = useInspectorPopoverPlacement();
if (!fields || fields.length === 0) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime436.jsx)(
import_components250.DropdownMenu,
{
icon: more_vertical_default,
label: (0, import_i18n229.__)("Options"),
popoverProps: popoverProps3,
toggleProps: { size: "small" },
children: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime436.jsx)(import_components250.MenuGroup, { label: (0, import_i18n229.__)("Show / Hide"), children: fields.map((field) => {
const isVisible = visibleFields.includes(field.id);
return /* @__PURE__ */ (0, import_jsx_runtime436.jsx)(
import_components250.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_components251 = __toESM(require_components(), 1);
var import_compose98 = __toESM(require_compose(), 1);
var import_data181 = __toESM(require_data(), 1);
var import_element255 = __toESM(require_element(), 1);
var import_rich_text18 = __toESM(require_rich_text(), 1);
var import_jsx_runtime437 = __toESM(require_jsx_runtime(), 1);
function RichTextControl({
data,
field,
hideLabelFromVision,
onChange,
config: config2 = {}
}) {
const registry = (0, import_data181.useRegistry)();
const attrValue = field.getValue({ item: data });
const fieldConfig = field.config || {};
const { clientId } = config2;
const [selection2, setSelection] = (0, import_element255.useState)({
start: void 0,
end: void 0
});
const [isSelected, setIsSelected] = (0, import_element255.useState)(false);
const anchorRef = (0, import_element255.useRef)();
const inputEvents = (0, import_element255.useRef)(/* @__PURE__ */ new Set());
const keyboardShortcuts = (0, import_element255.useRef)(/* @__PURE__ */ new Set());
const adjustedAllowedFormats = getAllowedFormats({
allowedFormats: fieldConfig?.allowedFormats,
disableFormats: fieldConfig?.disableFormats
});
const {
formatTypes,
prepareHandlers,
valueHandlers,
changeHandlers,
dependencies
} = useFormatTypes({
clientId,
identifier: field.id,
allowedFormats: adjustedAllowedFormats,
withoutInteractiveFormatting: fieldConfig?.withoutInteractiveFormatting,
disableNoneEssentialFormatting: true
});
function addEditorOnlyFormats(value2) {
return valueHandlers.reduce(
(accumulator, fn) => fn(accumulator, value2.text),
value2.formats
);
}
function removeEditorOnlyFormats(value2) {
formatTypes.forEach((formatType) => {
if (formatType.__experimentalCreatePrepareEditableTree) {
value2 = (0, import_rich_text18.removeFormat)(
value2,
formatType.name,
0,
value2.text.length
);
}
});
return value2.formats;
}
function addInvisibleFormats(value2) {
return prepareHandlers.reduce(
(accumulator, fn) => fn(accumulator, value2.text),
value2.formats
);
}
function onFocus() {
anchorRef.current?.focus();
}
const {
value,
getValue,
onChange: onRichTextChange,
ref: richTextRef
} = (0, import_rich_text18.__unstableUseRichText)({
value: attrValue,
onChange(html, { __unstableFormats, __unstableText }) {
onChange(field.setValue({ item: data, value: html }));
Object.values(changeHandlers).forEach((changeHandler) => {
changeHandler(__unstableFormats, __unstableText);
});
},
selectionStart: selection2.start,
selectionEnd: selection2.end,
onSelectionChange: (start2, end) => setSelection({ start: start2, end }),
__unstableIsSelected: isSelected,
preserveWhiteSpace: !!fieldConfig?.preserveWhiteSpace,
placeholder: fieldConfig?.placeholder,
__unstableDisableFormats: fieldConfig?.disableFormats,
__unstableDependencies: dependencies,
__unstableAfterParse: addEditorOnlyFormats,
__unstableBeforeSerialize: removeEditorOnlyFormats,
__unstableAddInvisibleFormats: addInvisibleFormats
});
const { baseControlProps, controlProps } = (0, import_components251.useBaseControlProps)({
hideLabelFromVision: hideLabelFromVision ?? field.hideLabelFromVision,
label: field.label
});
return /* @__PURE__ */ (0, import_jsx_runtime437.jsxs)(import_jsx_runtime437.Fragment, { children: [
isSelected && /* @__PURE__ */ (0, import_jsx_runtime437.jsx)(keyboardShortcutContext.Provider, { value: keyboardShortcuts, children: /* @__PURE__ */ (0, import_jsx_runtime437.jsx)(inputEventContext.Provider, { value: inputEvents, children: /* @__PURE__ */ (0, import_jsx_runtime437.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime437.jsx)(
FormatEdit,
{
value,
onChange: onRichTextChange,
onFocus,
formatTypes,
forwardedRef: anchorRef,
isVisible: false
}
) }) }) }),
/* @__PURE__ */ (0, import_jsx_runtime437.jsx)(import_components251.BaseControl, { ...baseControlProps, children: /* @__PURE__ */ (0, import_jsx_runtime437.jsx)(
"div",
{
className: "block-editor-content-only-controls__rich-text",
role: "textbox",
"aria-multiline": !fieldConfig?.disableLineBreaks,
ref: (0, import_compose98.useMergeRefs)([
richTextRef,
useEventListeners({
registry,
getValue,
onChange: onRichTextChange,
formatTypes,
selectionChange: setSelection,
isSelected,
disableFormats: fieldConfig?.disableFormats,
value,
tagName: "div",
removeEditorOnlyFormats,
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_components252 = __toESM(require_components(), 1);
var import_data182 = __toESM(require_data(), 1);
var import_i18n230 = __toESM(require_i18n(), 1);
var import_jsx_runtime438 = __toESM(require_jsx_runtime(), 1);
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_runtime438.jsx)("div", { className: "block-editor-content-only-controls__media-thumbnail", children: /* @__PURE__ */ (0, import_jsx_runtime438.jsx)(
"img",
{
alt: "",
width: 24,
height: 24,
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_runtime438.jsx)("div", { className: "block-editor-content-only-controls__media-thumbnail", children: /* @__PURE__ */ (0, import_jsx_runtime438.jsx)("img", { alt: "", width: 24, height: 24, 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_runtime438.jsx)(import_components252.Icon, { icon, size: 24 });
}
}
return /* @__PURE__ */ (0, import_jsx_runtime438.jsx)(import_components252.Icon, { icon: media_default, size: 24 });
}
function Media({ data, field, onChange, config: config2 = {} }) {
const { popoverProps: popoverProps3 } = useInspectorPopoverPlacement({
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_data182.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_i18n230.__)("Choose an image\u2026");
} else if (allowedType === "video") {
chooseItemLabel = (0, import_i18n230.__)("Choose a video\u2026");
} else if (allowedType === "application") {
chooseItemLabel = (0, import_i18n230.__)("Choose a file\u2026");
} else {
chooseItemLabel = (0, import_i18n230.__)("Choose a media item\u2026");
}
} else {
chooseItemLabel = (0, import_i18n230.__)("Choose a media item\u2026");
}
return /* @__PURE__ */ (0, import_jsx_runtime438.jsx)(check_default2, { children: /* @__PURE__ */ (0, import_jsx_runtime438.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_runtime438.jsx)(
import_components252.Button,
{
__next40pxDefaultSize: true,
className: "block-editor-content-only-controls__media",
...buttonProps,
children: /* @__PURE__ */ (0, import_jsx_runtime438.jsxs)(
import_components252.__experimentalGrid,
{
rowGap: 0,
columnGap: 8,
templateColumns: "24px 1fr",
className: "block-editor-content-only-controls__media-row",
children: [
url && /* @__PURE__ */ (0, import_jsx_runtime438.jsxs)(import_jsx_runtime438.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime438.jsx)(
MediaThumbnail,
{
attachment,
field,
data,
config: config2
}
),
/* @__PURE__ */ (0, import_jsx_runtime438.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_runtime438.jsxs)(import_jsx_runtime438.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime438.jsx)(
"span",
{
className: "block-editor-content-only-controls__media-placeholder",
style: {
width: "24px",
height: "24px"
}
}
),
/* @__PURE__ */ (0, import_jsx_runtime438.jsx)("span", { className: "block-editor-content-only-controls__media-title", children: chooseItemLabel })
] })
]
}
)
}
)
}
) });
}
// packages/block-editor/build-module/hooks/block-fields/link/index.mjs
var import_components253 = __toESM(require_components(), 1);
var import_element256 = __toESM(require_element(), 1);
var import_i18n231 = __toESM(require_i18n(), 1);
var import_url15 = __toESM(require_url(), 1);
var import_jsx_runtime439 = __toESM(require_jsx_runtime(), 1);
var NEW_TAB_REL2 = "noreferrer 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_url15.prependHTTP)(url),
linkTarget: newLinkTarget,
rel: updatedRel || void 0
};
}
function Link({ data, field, onChange }) {
const [isLinkControlOpen, setIsLinkControlOpen] = (0, import_element256.useState)(false);
const { popoverProps: popoverProps3 } = useInspectorPopoverPlacement({
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_element256.useMemo)(
() => ({ url, opensInNewTab, nofollow }),
[url, opensInNewTab, nofollow]
);
return /* @__PURE__ */ (0, import_jsx_runtime439.jsxs)(import_jsx_runtime439.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime439.jsx)(
import_components253.Button,
{
__next40pxDefaultSize: true,
className: "block-editor-content-only-controls__link",
onClick: () => {
setIsLinkControlOpen(true);
},
children: /* @__PURE__ */ (0, import_jsx_runtime439.jsxs)(
import_components253.__experimentalGrid,
{
rowGap: 0,
columnGap: 8,
templateColumns: "24px 1fr",
className: "block-editor-content-only-controls__link-row",
children: [
url && /* @__PURE__ */ (0, import_jsx_runtime439.jsxs)(import_jsx_runtime439.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime439.jsx)(import_components253.Icon, { icon: link_default, size: 24 }),
/* @__PURE__ */ (0, import_jsx_runtime439.jsx)("span", { className: "block-editor-content-only-controls__link-title", children: url })
] }),
!url && /* @__PURE__ */ (0, import_jsx_runtime439.jsxs)(import_jsx_runtime439.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime439.jsx)(
import_components253.Icon,
{
icon: link_default,
size: 24,
style: { opacity: 0.3 }
}
),
/* @__PURE__ */ (0, import_jsx_runtime439.jsx)("span", { className: "block-editor-content-only-controls__link-title", children: (0, import_i18n231.__)("Link") })
] })
]
}
)
}
),
isLinkControlOpen && /* @__PURE__ */ (0, import_jsx_runtime439.jsx)(
import_components253.Popover,
{
onClose: () => {
setIsLinkControlOpen(false);
},
...popoverProps3 ?? {},
children: /* @__PURE__ */ (0, import_jsx_runtime439.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_runtime440 = __toESM(require_jsx_runtime(), 1);
var { fieldsKey, formKey } = unlock(import_blocks103.privateApis);
function createConfiguredControl2(ControlComponent, config2 = {}) {
return function ConfiguredControl(props) {
return /* @__PURE__ */ (0, import_jsx_runtime440.jsx)(ControlComponent, { ...props, config: config2 });
};
}
function BlockFields({
clientId,
blockType,
setAttributes,
isCollapsed: isCollapsed3 = false
}) {
const blockTitle = useBlockDisplayTitle({
clientId,
context: "list-view"
});
const blockInformation = useBlockDisplayInformation(clientId);
const blockTypeFields = blockType?.[fieldsKey];
const attributes = (0, import_data183.useSelect)(
(select3) => select3(store).getBlockAttributes(clientId),
[clientId]
);
const computedForm = (0, import_element257.useMemo)(() => {
if (!isCollapsed3) {
return blockType?.[formKey];
}
return {
...blockType?.[formKey],
fields: [blockType?.[formKey]?.fields?.[0]]
};
}, [blockType, isCollapsed3]);
const [form, setForm] = (0, import_element257.useState)(computedForm);
const dataFormFields = (0, import_element257.useMemo)(() => {
if (!blockTypeFields?.length) {
return [];
}
return blockTypeFields.map((fieldDef) => {
const field = {
...fieldDef
};
if ("string" === typeof fieldDef.Edit && fieldDef.Edit === "rich-text") {
field.Edit = createConfiguredControl2(RichTextControl, {
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_runtime440.jsxs)("div", { className: "block-editor-block-fields__container", children: [
/* @__PURE__ */ (0, import_jsx_runtime440.jsx)("div", { className: "block-editor-block-fields__header", children: /* @__PURE__ */ (0, import_jsx_runtime440.jsxs)(import_components254.__experimentalHStack, { spacing: 1, children: [
isCollapsed3 && /* @__PURE__ */ (0, import_jsx_runtime440.jsxs)(import_jsx_runtime440.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime440.jsx)(
block_icon_default,
{
className: "block-editor-block-fields__header-icon",
icon: blockInformation?.icon
}
),
/* @__PURE__ */ (0, import_jsx_runtime440.jsx)("h2", { className: "block-editor-block-fields__header-title", children: /* @__PURE__ */ (0, import_jsx_runtime440.jsx)(import_components254.__experimentalTruncate, { numberOfLines: 1, children: blockTitle }) }),
/* @__PURE__ */ (0, import_jsx_runtime440.jsx)(
FieldsDropdownMenu,
{
fields: dataFormFields,
visibleFields: form.fields,
onToggleField: handleToggleField
}
)
] }),
!isCollapsed3 && /* @__PURE__ */ (0, import_jsx_runtime440.jsx)("h2", { className: "block-editor-block-fields__header-title", children: (0, import_i18n232.__)("Content") })
] }) }),
/* @__PURE__ */ (0, import_jsx_runtime440.jsx)(
DataForm,
{
data: attributes,
fields: dataFormFields,
form,
onChange: setAttributes
}
)
] });
}
function hasBlockFieldsSupport(blockName) {
return !!(window?.__experimentalContentOnlyInspectorFields && (0, import_blocks103.getBlockType)(blockName)?.[fieldsKey]);
}
function BlockFieldsPanel(props) {
const { blockType, isSelectionWithinCurrentSection } = (0, import_element257.useContext)(PrivateBlockContext);
return /* @__PURE__ */ (0, import_jsx_runtime440.jsx)(InspectorControlsFill, { group: "content", children: /* @__PURE__ */ (0, import_jsx_runtime440.jsx)(
BlockFields,
{
...props,
blockType,
isCollapsed: isSelectionWithinCurrentSection
}
) });
}
var block_fields_default = {
edit: BlockFieldsPanel,
hasSupport: hasBlockFieldsSupport,
attributeKeys: [],
supportsPatternEditing: true
};
// packages/block-editor/build-module/hooks/custom-class-name.mjs
var import_hooks22 = __toESM(require_hooks(), 1);
var import_components255 = __toESM(require_components(), 1);
var import_i18n233 = __toESM(require_i18n(), 1);
var import_blocks104 = __toESM(require_blocks(), 1);
var import_jsx_runtime441 = __toESM(require_jsx_runtime(), 1);
function addAttribute6(settings2) {
if ((0, import_blocks104.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_runtime441.jsx)(inspector_controls_default, { group: "advanced", children: /* @__PURE__ */ (0, import_jsx_runtime441.jsx)(
import_components255.TextControl,
{
__next40pxDefaultSize: true,
autoComplete: "off",
label: (0, import_i18n233.__)("Additional CSS class(es)"),
value: className || "",
onChange: (nextValue) => {
setAttributes({
className: nextValue !== "" ? nextValue : void 0
});
},
help: (0, import_i18n233.__)("Separate multiple classes with spaces.")
}
) });
}
var custom_class_name_default = {
edit: CustomClassNameControlsPure,
addSaveProps: addSaveProps5,
attributeKeys: ["className"],
hasSupport(name) {
return (0, import_blocks104.hasBlockSupport)(name, "customClassName", true);
}
};
function addSaveProps5(extraProps, blockType, attributes) {
if ((0, import_blocks104.hasBlockSupport)(blockType, "customClassName", true) && attributes.className) {
extraProps.className = clsx_default(
extraProps.className,
attributes.className
);
}
return extraProps;
}
function addTransforms3(result, source, index, results) {
if (!(0, import_blocks104.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[index]) {
const originClassName = source[index]?.attributes.className;
if (originClassName && result.attributes.className === void 0) {
return {
...result,
attributes: {
...result.attributes,
className: originClassName
}
};
}
}
return result;
}
(0, import_hooks22.addFilter)(
"blocks.registerBlockType",
"core/editor/custom-class-name/attribute",
addAttribute6
);
(0, import_hooks22.addFilter)(
"blocks.switchToBlockType.transformedBlock",
"core/customClassName/addTransforms",
addTransforms3
);
// packages/block-editor/build-module/hooks/generated-class-name.mjs
var import_hooks23 = __toESM(require_hooks(), 1);
var import_blocks105 = __toESM(require_blocks(), 1);
function addGeneratedClassName(extraProps, blockType) {
if ((0, import_blocks105.hasBlockSupport)(blockType, "className", true)) {
if (typeof extraProps.className === "string") {
extraProps.className = [
.../* @__PURE__ */ new Set([
(0, import_blocks105.getBlockDefaultClassName)(blockType.name),
...extraProps.className.split(" ")
])
].join(" ").trim();
} else {
extraProps.className = (0, import_blocks105.getBlockDefaultClassName)(blockType.name);
}
}
return extraProps;
}
(0, import_hooks23.addFilter)(
"blocks.getSaveContent.extraProps",
"core/generated-class-name/save-props",
addGeneratedClassName
);
// packages/block-editor/build-module/hooks/style.mjs
var import_element263 = __toESM(require_element(), 1);
var import_hooks27 = __toESM(require_hooks(), 1);
var import_blocks113 = __toESM(require_blocks(), 1);
var import_compose100 = __toESM(require_compose(), 1);
var import_style_engine4 = __toESM(require_style_engine(), 1);
// packages/block-editor/build-module/hooks/typography.mjs
var import_blocks111 = __toESM(require_blocks(), 1);
var import_element260 = __toESM(require_element(), 1);
var import_data185 = __toESM(require_data(), 1);
// packages/block-editor/build-module/hooks/line-height.mjs
var import_blocks106 = __toESM(require_blocks(), 1);
var import_jsx_runtime442 = __toESM(require_jsx_runtime(), 1);
var LINE_HEIGHT_SUPPORT_KEY2 = "typography.lineHeight";
// packages/block-editor/build-module/hooks/font-family.mjs
var import_hooks24 = __toESM(require_hooks(), 1);
var import_blocks107 = __toESM(require_blocks(), 1);
var import_token_list2 = __toESM(require_token_list(), 1);
var import_components257 = __toESM(require_components(), 1);
var FONT_FAMILY_SUPPORT_KEY2 = "typography.__experimentalFontFamily";
var { kebabCase: kebabCase5 } = unlock(import_components257.privateApis);
function addAttributes3(settings2) {
if (!(0, import_blocks107.hasBlockSupport)(settings2, FONT_FAMILY_SUPPORT_KEY2)) {
return settings2;
}
if (!settings2.attributes.fontFamily) {
Object.assign(settings2.attributes, {
fontFamily: {
type: "string"
}
});
}
return settings2;
}
function addSaveProps6(props, blockType, attributes) {
if (!(0, import_blocks107.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 useBlockProps8({ name, fontFamily }) {
return addSaveProps6({}, name, { fontFamily });
}
var font_family_default = {
useBlockProps: useBlockProps8,
addSaveProps: addSaveProps6,
attributeKeys: ["fontFamily"],
hasSupport(name) {
return (0, import_blocks107.hasBlockSupport)(name, FONT_FAMILY_SUPPORT_KEY2);
}
};
(0, import_hooks24.addFilter)(
"blocks.registerBlockType",
"core/fontFamily/addAttribute",
addAttributes3
);
// packages/block-editor/build-module/hooks/font-size.mjs
var import_hooks25 = __toESM(require_hooks(), 1);
var import_blocks108 = __toESM(require_blocks(), 1);
var import_token_list3 = __toESM(require_token_list(), 1);
var import_jsx_runtime443 = __toESM(require_jsx_runtime(), 1);
var FONT_SIZE_SUPPORT_KEY2 = "typography.fontSize";
function addAttributes4(settings2) {
if (!(0, import_blocks108.hasBlockSupport)(settings2, FONT_SIZE_SUPPORT_KEY2)) {
return settings2;
}
if (!settings2.attributes.fontSize) {
Object.assign(settings2.attributes, {
fontSize: {
type: "string"
}
});
}
return settings2;
}
function addSaveProps7(props, blockNameOrType, attributes) {
if (!(0, import_blocks108.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 useBlockProps9({ name, fontSize, style }) {
const [fontSizes, fluidTypographySettings, layoutSettings] = useSettings(
"typography.fontSizes",
"typography.fluid",
"layout"
);
if (!(0, import_blocks108.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 addSaveProps7(props, name, { fontSize });
}
var font_size_default = {
useBlockProps: useBlockProps9,
addSaveProps: addSaveProps7,
attributeKeys: ["fontSize", "style"],
hasSupport(name) {
return (0, import_blocks108.hasBlockSupport)(name, FONT_SIZE_SUPPORT_KEY2);
}
};
var MIGRATION_PATHS2 = {
fontSize: [["fontSize"], ["style", "typography", "fontSize"]]
};
function addTransforms4(result, source, index, results) {
const destinationBlockType = result.name;
const activeSupports = {
fontSize: (0, import_blocks108.hasBlockSupport)(
destinationBlockType,
FONT_SIZE_SUPPORT_KEY2
)
};
return transformStyles2(
activeSupports,
MIGRATION_PATHS2,
result,
source,
index,
results
);
}
(0, import_hooks25.addFilter)(
"blocks.registerBlockType",
"core/font/addAttribute",
addAttributes4
);
(0, import_hooks25.addFilter)(
"blocks.switchToBlockType.transformedBlock",
"core/font-size/addTransforms",
addTransforms4
);
// packages/block-editor/build-module/hooks/text-align.mjs
var import_i18n234 = __toESM(require_i18n(), 1);
var import_blocks109 = __toESM(require_blocks(), 1);
var import_jsx_runtime444 = __toESM(require_jsx_runtime(), 1);
var TEXT_ALIGN_SUPPORT_KEY2 = "typography.textAlign";
var TEXT_ALIGNMENT_OPTIONS2 = [
{
icon: align_left_default,
title: (0, import_i18n234.__)("Align text left"),
align: "left"
},
{
icon: align_center_default,
title: (0, import_i18n234.__)("Align text center"),
align: "center"
},
{
icon: align_right_default,
title: (0, import_i18n234.__)("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 BlockEditTextAlignmentToolbarControlsPure({
style,
name: blockName,
setAttributes
}) {
const settings2 = useBlockSettings(blockName);
const hasTextAlignControl = settings2?.typography?.textAlign;
const blockEditingMode = useBlockEditingMode();
if (!hasTextAlignControl || blockEditingMode !== "default") {
return null;
}
const validTextAlignments = getValidTextAlignments(
(0, import_blocks109.getBlockSupport)(blockName, TEXT_ALIGN_SUPPORT_KEY2)
);
if (!validTextAlignments.length) {
return null;
}
const textAlignmentControls = TEXT_ALIGNMENT_OPTIONS2.filter(
(control) => validTextAlignments.includes(control.align)
);
const onChange = (newTextAlignValue) => {
const newStyle = {
...style,
typography: {
...style?.typography,
textAlign: newTextAlignValue
}
};
setAttributes({ style: cleanEmptyObject(newStyle) });
};
return /* @__PURE__ */ (0, import_jsx_runtime444.jsx)(block_controls_default, { group: "block", children: /* @__PURE__ */ (0, import_jsx_runtime444.jsx)(
AlignmentControl,
{
value: style?.typography?.textAlign,
onChange,
alignmentControls: textAlignmentControls
}
) });
}
var text_align_default = {
edit: BlockEditTextAlignmentToolbarControlsPure,
useBlockProps: useBlockProps10,
addSaveProps: addAssignedTextAlign,
attributeKeys: ["style"],
hasSupport(name) {
return (0, import_blocks109.hasBlockSupport)(name, TEXT_ALIGN_SUPPORT_KEY2, false);
}
};
function useBlockProps10({ name, style }) {
if (!style?.typography?.textAlign) {
return null;
}
const validTextAlignments = getValidTextAlignments(
(0, import_blocks109.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_blocks109.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_hooks26 = __toESM(require_hooks(), 1);
var import_blocks110 = __toESM(require_blocks(), 1);
var import_element259 = __toESM(require_element(), 1);
var import_data184 = __toESM(require_data(), 1);
var import_i18n236 = __toESM(require_i18n(), 1);
var import_components260 = __toESM(require_components(), 1);
var import_compose99 = __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);
const paddingLeft = parseFloat(computedStyle.paddingLeft) || 0;
const paddingRight = parseFloat(computedStyle.paddingRight) || 0;
const range2 = document.createRange();
range2.selectNodeContents(textElement);
while (minSize <= maxSize) {
const midSize = Math.floor((minSize + maxSize) / 2);
applyFontSize(midSize);
const rect = range2.getBoundingClientRect();
const textWidth = rect.width;
const fitsWidth = textElement.scrollWidth <= textElement.clientWidth && textWidth <= textElement.clientWidth - paddingLeft - paddingRight;
const fitsHeight = alreadyHasScrollableHeight || textElement.scrollHeight <= textElement.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_element258 = __toESM(require_element(), 1);
var import_i18n235 = __toESM(require_i18n(), 1);
var import_components259 = __toESM(require_components(), 1);
var import_a11y20 = __toESM(require_a11y(), 1);
var import_jsx_runtime445 = __toESM(require_jsx_runtime(), 1);
function FitTextSizeWarning() {
const message2 = (0, import_i18n235.__)(
"The text may be too small to read. Consider using a larger container or less text."
);
(0, import_element258.useEffect)(() => {
(0, import_a11y20.speak)(message2);
}, [message2]);
return /* @__PURE__ */ (0, import_jsx_runtime445.jsx)("div", { className: "block-editor-fit-text-size-warning", children: /* @__PURE__ */ (0, import_jsx_runtime445.jsx)(
import_components259.Notice,
{
spokenMessage: null,
status: "warning",
isDismissible: false,
children: message2
}
) });
}
// packages/block-editor/build-module/hooks/fit-text.mjs
var import_jsx_runtime446 = __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_blocks110.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_element259.useState)(null);
const hasFitTextSupport2 = (0, import_blocks110.hasBlockSupport)(name, FIT_TEXT_SUPPORT_KEY);
const blockElement = useBlockElement(clientId);
const { blockAttributes, parentId } = (0, import_data184.useSelect)(
(select3) => {
if (!clientId || !hasFitTextSupport2 || !fitText) {
return EMPTY_OBJECT4;
}
return {
blockAttributes: select3(store).getBlockAttributes(clientId),
parentId: select3(store).getBlockRootClientId(clientId)
};
},
[clientId, hasFitTextSupport2, fitText]
);
const applyFitText = (0, import_element259.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 = (size) => {
if (size === 0) {
styleElement.textContent = "";
} else {
styleElement.textContent = `${blockSelector} { font-size: ${size}px !important; }`;
}
};
const optimalSize = optimizeFitText(blockElement, applyFontSizeStyle);
setFontSize(optimalSize);
}, [blockElement, clientId, hasFitTextSupport2, fitText]);
(0, import_element259.useEffect)(() => {
if (!fitText || !blockElement || !clientId || !hasFitTextSupport2) {
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
]);
(0, import_element259.useEffect)(() => {
if (fitText && blockElement && hasFitTextSupport2) {
const frameId = window.requestAnimationFrame(() => {
if (blockElement) {
applyFitText();
}
});
return () => window.cancelAnimationFrame(frameId);
}
}, [
blockAttributes,
fitText,
applyFitText,
blockElement,
hasFitTextSupport2
]);
return { fontSize };
}
function FitTextControl({
clientId,
fitText = false,
setAttributes,
name,
fontSize,
style,
warning: warning6
}) {
if (!(0, import_blocks110.hasBlockSupport)(name, FIT_TEXT_SUPPORT_KEY)) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime446.jsx)(inspector_controls_default, { group: "typography", children: /* @__PURE__ */ (0, import_jsx_runtime446.jsxs)(
import_components260.__experimentalToolsPanelItem,
{
hasValue: () => fitText,
label: (0, import_i18n236.__)("Fit text"),
onDeselect: () => setAttributes({ fitText: void 0 }),
resetAllFilter: () => ({ fitText: void 0 }),
panelId: clientId,
children: [
/* @__PURE__ */ (0, import_jsx_runtime446.jsx)(
import_components260.ToggleControl,
{
label: (0, import_i18n236.__)("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_i18n236.__)("Text will resize to fit its container.") : (0, import_i18n236.__)(
"The text will resize to fit its container, resetting other font size settings."
)
}
),
warning6
]
}
) });
}
function addSaveProps8(props, blockType, attributes) {
if (!(0, import_blocks110.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 useBlockProps11({ name, fitText }) {
if (fitText && (0, import_blocks110.hasBlockSupport)(name, FIT_TEXT_SUPPORT_KEY)) {
return {
className: "has-fit-text"
};
}
return {};
}
(0, import_hooks26.addFilter)(
"blocks.registerBlockType",
"core/fit-text/addAttribute",
addAttributes5
);
var hasFitTextSupport = (blockNameOrType) => {
return (0, import_blocks110.hasBlockSupport)(blockNameOrType, FIT_TEXT_SUPPORT_KEY);
};
function WithFitTextFontSize({ fitText, name, clientId, children }) {
const { fontSize } = useFitText({ fitText, name, clientId });
return children(fontSize);
}
var addFitTextControl = (0, import_compose99.createHigherOrderComponent)((BlockEdit2) => {
return (props) => {
const { name, attributes, clientId, isSelected, setAttributes } = props;
const { fitText } = attributes;
const supportsFitText = (0, import_blocks110.hasBlockSupport)(name, FIT_TEXT_SUPPORT_KEY);
if (!supportsFitText) {
return /* @__PURE__ */ (0, import_jsx_runtime446.jsx)(BlockEdit2, { ...props });
}
return /* @__PURE__ */ (0, import_jsx_runtime446.jsxs)(import_jsx_runtime446.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime446.jsx)(BlockEdit2, { ...props }),
fitText && /* @__PURE__ */ (0, import_jsx_runtime446.jsx)(
WithFitTextFontSize,
{
fitText,
name,
clientId,
children: (fontSize) => isSelected && /* @__PURE__ */ (0, import_jsx_runtime446.jsx)(
FitTextControl,
{
clientId,
fitText,
setAttributes,
name,
fontSize: attributes.fontSize,
style: attributes.style,
warning: fontSize < MIN_FONT_SIZE_FOR_WARNING && /* @__PURE__ */ (0, import_jsx_runtime446.jsx)(FitTextSizeWarning, {})
}
)
}
),
!fitText && isSelected && /* @__PURE__ */ (0, import_jsx_runtime446.jsx)(
FitTextControl,
{
clientId,
fitText,
setAttributes,
name,
fontSize: attributes.fontSize,
style: attributes.style
}
)
] });
};
}, "addFitTextControl");
(0, import_hooks26.addFilter)(
"editor.BlockEdit",
"core/fit-text/add-fit-text-control",
addFitTextControl
);
var fit_text_default = {
useBlockProps: useBlockProps11,
addSaveProps: addSaveProps8,
attributeKeys: ["fitText", "fontSize", "style"],
hasSupport: hasFitTextSupport,
edit: () => null
};
// packages/block-editor/build-module/hooks/typography.mjs
var import_jsx_runtime447 = __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_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,
WRITING_MODE_SUPPORT_KEY2,
TEXT_TRANSFORM_SUPPORT_KEY2,
LETTER_SPACING_SUPPORT_KEY2,
FIT_TEXT_SUPPORT_KEY
];
function styleToAttributes3(style) {
const updatedStyle = { ...omit(style, ["fontFamily"]) };
const fontSizeValue = style?.typography?.fontSize;
const fontFamilyValue = style?.typography?.fontFamily;
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;
updatedStyle.typography = {
...omit(updatedStyle.typography, ["fontFamily"]),
fontSize: fontSizeSlug ? void 0 : fontSizeValue
};
return {
style: cleanEmptyObject(updatedStyle),
fontFamily: fontFamilySlug,
fontSize: fontSizeSlug
};
}
function attributesToStyle3(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
}
};
}
function TypographyInspectorControl({ children, resetAllFilter }) {
const attributesResetAllFilter = (0, import_element260.useCallback)(
(attributes) => {
const existingStyle = attributesToStyle3(attributes);
const updatedStyle = resetAllFilter(existingStyle);
return {
...attributes,
...styleToAttributes3(updatedStyle)
};
},
[resetAllFilter]
);
return /* @__PURE__ */ (0, import_jsx_runtime447.jsx)(
inspector_controls_default,
{
group: "typography",
resetAllFilter: attributesResetAllFilter,
children
}
);
}
function TypographyPanel2({ clientId, name, setAttributes, settings: settings2 }) {
const isEnabled = useHasTypographyPanel(settings2);
const { style, fontFamily, fontSize, fitText } = (0, import_data185.useSelect)(
(select3) => {
if (!isEnabled) {
return {};
}
const {
style: _style,
fontFamily: _fontFamily,
fontSize: _fontSize,
fitText: _fitText
} = select3(store).getBlockAttributes(clientId) || {};
return {
style: _style,
fontFamily: _fontFamily,
fontSize: _fontSize,
fitText: _fitText
};
},
[clientId, isEnabled]
);
const value = (0, import_element260.useMemo)(
() => attributesToStyle3({ style, fontFamily, fontSize }),
[style, fontSize, fontFamily]
);
const onChange = (newStyle) => {
const newAttributes = styleToAttributes3(newStyle);
const hasFontSize = newAttributes.fontSize || newAttributes.style?.typography?.fontSize;
if (hasFontSize && fitText) {
newAttributes.fitText = void 0;
}
setAttributes(newAttributes);
};
if (!isEnabled) {
return null;
}
const defaultControls = (0, import_blocks111.getBlockSupport)(name, [
TYPOGRAPHY_SUPPORT_KEY,
"__experimentalDefaultControls"
]);
return /* @__PURE__ */ (0, import_jsx_runtime447.jsx)(
TypographyPanel,
{
as: TypographyInspectorControl,
panelId: clientId,
settings: settings2,
value,
onChange,
defaultControls
}
);
}
// packages/block-editor/build-module/hooks/dimensions.mjs
var import_element262 = __toESM(require_element(), 1);
var import_data186 = __toESM(require_data(), 1);
var import_blocks112 = __toESM(require_blocks(), 1);
var import_deprecated36 = __toESM(require_deprecated(), 1);
// packages/block-editor/build-module/hooks/spacing-visualizer.mjs
var import_element261 = __toESM(require_element(), 1);
var import_is_shallow_equal4 = __toESM(require_is_shallow_equal(), 1);
var import_jsx_runtime448 = __toESM(require_jsx_runtime(), 1);
function SpacingVisualizer({ clientId, value, computeStyle, forceShow }) {
const blockElement = useBlockElement(clientId);
const [style, updateStyle] = (0, import_element261.useReducer)(
() => computeStyle(blockElement)
);
(0, import_element261.useEffect)(() => {
if (blockElement && forceShow) {
updateStyle();
}
}, [blockElement, forceShow]);
(0, import_element261.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_element261.useRef)(value);
const [isActive, setIsActive] = (0, import_element261.useState)(false);
(0, import_element261.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_runtime448.jsx)(
cover_default,
{
clientId,
__unstablePopoverSlot: "block-toolbar",
children: /* @__PURE__ */ (0, import_jsx_runtime448.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_runtime448.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_runtime448.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_runtime449 = __toESM(require_jsx_runtime(), 1);
var DIMENSIONS_SUPPORT_KEY = "dimensions";
var SPACING_SUPPORT_KEY2 = "spacing";
function useVisualizer() {
const [property, setProperty] = (0, import_element262.useState)(false);
const { hideBlockInterface: hideBlockInterface2, showBlockInterface: showBlockInterface2 } = unlock(
(0, import_data186.useDispatch)(store)
);
(0, import_element262.useEffect)(() => {
if (!property) {
showBlockInterface2();
} else {
hideBlockInterface2();
}
}, [property, showBlockInterface2, hideBlockInterface2]);
return [property, setProperty];
}
function DimensionsInspectorControl({ children, resetAllFilter }) {
const attributesResetAllFilter = (0, import_element262.useCallback)(
(attributes) => {
const existingStyle = attributes.style;
const updatedStyle = resetAllFilter(existingStyle);
return {
...attributes,
style: updatedStyle
};
},
[resetAllFilter]
);
return /* @__PURE__ */ (0, import_jsx_runtime449.jsx)(
inspector_controls_default,
{
group: "dimensions",
resetAllFilter: attributesResetAllFilter,
children
}
);
}
function DimensionsPanel2({ clientId, name, setAttributes, settings: settings2 }) {
const isEnabled = useHasDimensionsPanel(settings2);
const value = (0, import_data186.useSelect)(
(select3) => {
if (!isEnabled) {
return void 0;
}
return select3(store).getBlockAttributes(clientId)?.style;
},
[clientId, isEnabled]
);
const [visualizedProperty, setVisualizedProperty] = useVisualizer();
const onChange = (newStyle) => {
setAttributes({
style: cleanEmptyObject(newStyle)
});
};
if (!isEnabled) {
return null;
}
const defaultDimensionsControls = (0, import_blocks112.getBlockSupport)(name, [
DIMENSIONS_SUPPORT_KEY,
"__experimentalDefaultControls"
]);
const defaultSpacingControls = (0, import_blocks112.getBlockSupport)(name, [
SPACING_SUPPORT_KEY2,
"__experimentalDefaultControls"
]);
const defaultControls = {
...defaultDimensionsControls,
...defaultSpacingControls
};
return /* @__PURE__ */ (0, import_jsx_runtime449.jsxs)(import_jsx_runtime449.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime449.jsx)(
DimensionsPanel,
{
as: DimensionsInspectorControl,
panelId: clientId,
settings: settings2,
value,
onChange,
defaultControls,
onVisualize: setVisualizedProperty
}
),
!!settings2?.spacing?.padding && visualizedProperty === "padding" && /* @__PURE__ */ (0, import_jsx_runtime449.jsx)(
PaddingVisualizer,
{
forceShow: visualizedProperty === "padding",
clientId,
value
}
),
!!settings2?.spacing?.margin && visualizedProperty === "margin" && /* @__PURE__ */ (0, import_jsx_runtime449.jsx)(
MarginVisualizer,
{
forceShow: visualizedProperty === "margin",
clientId,
value
}
)
] });
}
function hasDimensionsSupport(blockName, feature = "any") {
if (import_element262.Platform.OS !== "web") {
return false;
}
const support = (0, import_blocks112.getBlockSupport)(blockName, DIMENSIONS_SUPPORT_KEY);
if (support === true) {
return true;
}
if (feature === "any") {
return !!(support?.aspectRatio || !!support?.height || !!support?.minHeight || !!support?.width);
}
return !!support?.[feature];
}
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 className = clsx_default({
"has-aspect-ratio": !!style?.dimensions?.aspectRatio
});
const inlineStyleOverrides = {};
if (style?.dimensions?.aspectRatio) {
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_deprecated36.default)("wp.blockEditor.__experimentalUseCustomSides", {
since: "6.3",
version: "6.4"
});
}
// packages/block-editor/build-module/hooks/style.mjs
var import_jsx_runtime450 = __toESM(require_jsx_runtime(), 1);
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_blocks113.hasBlockSupport)(nameOrType, key));
function getInlineStyles(styles = {}) {
const output = {};
(0, import_style_engine4.getCSSRules)(styles).forEach((rule) => {
output[rule.key] = rule.value;
});
return output;
}
function addAttribute7(settings2) {
if (!hasStyleSupport2(settings2)) {
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_blocks113.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,
__unstableParentLayout
}) {
const settings2 = useBlockSettings(name, __unstableParentLayout);
const blockEditingMode = useBlockEditingMode();
const passedProps = {
clientId,
name,
setAttributes,
settings: {
...settings2,
typography: {
...settings2.typography,
// The text alignment UI for individual blocks is rendered in
// the block toolbar, so disable it here.
textAlign: false
}
}
};
if (blockEditingMode !== "default") {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime450.jsxs)(import_jsx_runtime450.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime450.jsx)(ColorEdit, { ...passedProps }),
/* @__PURE__ */ (0, import_jsx_runtime450.jsx)(BackgroundImagePanel3, { ...passedProps }),
/* @__PURE__ */ (0, import_jsx_runtime450.jsx)(TypographyPanel2, { ...passedProps }),
/* @__PURE__ */ (0, import_jsx_runtime450.jsx)(BorderPanel2, { ...passedProps }),
/* @__PURE__ */ (0, import_jsx_runtime450.jsx)(DimensionsPanel2, { ...passedProps })
] });
}
var style_default2 = {
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 useBlockProps13({ name, style }) {
const blockElementsContainerIdentifier = (0, import_compose100.useInstanceId)(
STYLE_BLOCK_PROPS_REFERENCE,
"wp-elements"
);
const baseElementSelector = `.${blockElementsContainerIdentifier}`;
const blockElementStyles = style?.elements;
const styles = (0, import_element263.useMemo)(() => {
if (!blockElementStyles) {
return;
}
const elementCSSRules = [];
elementTypes.forEach(({ elementType, pseudo, elements }) => {
const skipSerialization = shouldSkipSerialization(
name,
COLOR_SUPPORT_KEY2,
elementType
);
if (skipSerialization) {
return;
}
const elementStyles = blockElementStyles?.[elementType];
if (elementStyles) {
const selector3 = scopeSelector(
baseElementSelector,
import_blocks113.__EXPERIMENTAL_ELEMENTS[elementType]
);
elementCSSRules.push(
(0, import_style_engine4.compileCSS)(elementStyles, { selector: selector3 })
);
if (pseudo) {
pseudo.forEach((pseudoSelector) => {
if (elementStyles[pseudoSelector]) {
elementCSSRules.push(
(0, import_style_engine4.compileCSS)(elementStyles[pseudoSelector], {
selector: scopeSelector(
baseElementSelector,
`${import_blocks113.__EXPERIMENTAL_ELEMENTS[elementType]}${pseudoSelector}`
)
})
);
}
});
}
}
if (elements) {
elements.forEach((element) => {
if (blockElementStyles[element]) {
elementCSSRules.push(
(0, import_style_engine4.compileCSS)(blockElementStyles[element], {
selector: scopeSelector(
baseElementSelector,
import_blocks113.__EXPERIMENTAL_ELEMENTS[element]
)
})
);
}
});
}
});
return elementCSSRules.length > 0 ? elementCSSRules.join("") : void 0;
}, [baseElementSelector, blockElementStyles, name]);
useStyleOverride({ css: styles });
return addSaveProps9(
{ className: blockElementsContainerIdentifier },
name,
{ style },
skipSerializationPathsEdit
);
}
(0, import_hooks27.addFilter)(
"blocks.registerBlockType",
"core/style/addAttribute",
addAttribute7
);
// packages/block-editor/build-module/hooks/settings.mjs
var import_hooks28 = __toESM(require_hooks(), 1);
var import_blocks114 = __toESM(require_blocks(), 1);
var hasSettingsSupport = (blockType) => (0, import_blocks114.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_hooks28.addFilter)(
"blocks.registerBlockType",
"core/settings/addAttribute",
addAttribute8
);
// packages/block-editor/build-module/hooks/duotone.mjs
var import_blocks115 = __toESM(require_blocks(), 1);
var import_compose101 = __toESM(require_compose(), 1);
var import_hooks29 = __toESM(require_hooks(), 1);
var import_element264 = __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_runtime451 = __toESM(require_jsx_runtime(), 1);
var EMPTY_ARRAY17 = [];
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_element264.useMemo)(
() => [
...userPresets || EMPTY_ARRAY17,
...themePresets || EMPTY_ARRAY17,
...enableDefault && defaultPresets || EMPTY_ARRAY17
],
[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, index) => val === colors2[index]
);
});
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_runtime451.jsxs)(import_jsx_runtime451.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(inspector_controls_default, { group: "filter", children: /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
FiltersPanel,
{
value: { filter: { duotone: duotonePresetOrColors } },
onChange: (newDuotone) => {
const newStyle = {
...style,
color: {
...newDuotone?.filter
}
};
setAttributes({
style: cleanEmptyObject(newStyle)
});
},
settings: settings2
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime451.jsx)(block_controls_default, { group: "block", __experimentalShareWithChildBlocks: true, children: /* @__PURE__ */ (0, import_jsx_runtime451.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_blocks115.hasBlockSupport)(name, "filter.duotone");
}
};
function addDuotoneAttributes(settings2) {
if (!(0, import_blocks115.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 selectors = duotoneSelector.split(",");
const selectorsScoped = selectors.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_element264.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_compose101.useInstanceId)(DUOTONE_BLOCK_PROPS_REFERENCE);
const selector3 = (0, import_element264.useMemo)(() => {
const blockType = (0, import_blocks115.getBlockType)(name);
if (blockType) {
const duotoneSupport = (0, import_blocks115.getBlockSupport)(
blockType,
"filter.duotone",
false
);
if (!duotoneSupport) {
return null;
}
const experimentalDuotone = (0, import_blocks115.getBlockSupport)(
blockType,
"color.__experimentalDuotone",
false
);
if (experimentalDuotone) {
const rootSelector = getBlockSelector(blockType);
return typeof experimentalDuotone === "string" ? scopeSelector(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_hooks29.addFilter)(
"blocks.registerBlockType",
"core/editor/duotone/add-attributes",
addDuotoneAttributes
);
// packages/block-editor/build-module/hooks/layout.mjs
var import_compose102 = __toESM(require_compose(), 1);
var import_hooks30 = __toESM(require_hooks(), 1);
var import_blocks116 = __toESM(require_blocks(), 1);
var import_data187 = __toESM(require_data(), 1);
var import_components262 = __toESM(require_components(), 1);
var import_i18n237 = __toESM(require_i18n(), 1);
var import_jsx_runtime452 = __toESM(require_jsx_runtime(), 1);
var layoutBlockSupportKey = "layout";
var { kebabCase: kebabCase6 } = unlock(import_components262.privateApis);
function hasLayoutBlockSupport(blockName) {
return (0, import_blocks116.hasBlockSupport)(blockName, "layout") || (0, import_blocks116.hasBlockSupport)(blockName, "__experimentalLayout");
}
function useLayoutClasses(blockAttributes = {}, blockName = "") {
const { layout } = blockAttributes;
const { default: defaultBlockLayout } = (0, import_blocks116.getBlockSupport)(blockName, layoutBlockSupportKey) || {};
const usedLayout = layout?.inherit || layout?.contentSize || layout?.wideSize ? { ...layout, type: "constrained" } : layout || defaultBlockLayout || {};
const layoutClassnames = [];
if (LAYOUT_DEFINITIONS[usedLayout?.type || "default"]?.className) {
const baseClassName = LAYOUT_DEFINITIONS[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_data187.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 LayoutPanelPure({
layout,
setAttributes,
name: blockName,
clientId
}) {
const settings2 = useBlockSettings(blockName);
const { layout: layoutSettings } = settings2;
const { themeSupportsLayout } = (0, import_data187.useSelect)((select3) => {
const { getSettings: getSettings8 } = select3(store);
return {
themeSupportsLayout: getSettings8().supportsLayout
};
}, []);
const blockEditingMode = useBlockEditingMode();
if (blockEditingMode !== "default") {
return null;
}
const layoutBlockSupport = (0, import_blocks116.getBlockSupport)(
blockName,
layoutBlockSupportKey,
{}
);
const blockSupportAndThemeSettings = {
...layoutSettings,
...layoutBlockSupport
};
const {
allowSwitching,
allowEditing = true,
allowInheriting = true,
default: defaultBlockLayout
} = blockSupportAndThemeSettings;
if (!allowEditing) {
return null;
}
const blockSupportAndLayout = {
...layoutBlockSupport,
...layout
};
const { type, default: { type: defaultType = "default" } = {} } = blockSupportAndLayout;
const blockLayoutType = type || defaultType;
const showInheritToggle = !!(allowInheriting && (!blockLayoutType || blockLayoutType === "default" || blockLayoutType === "constrained" || blockSupportAndLayout.inherit));
const usedLayout = layout || defaultBlockLayout || {};
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 onChangeType = (newType) => setAttributes({ layout: { type: newType } });
const onChangeLayout = (newLayout) => setAttributes({ layout: newLayout });
return /* @__PURE__ */ (0, import_jsx_runtime452.jsxs)(import_jsx_runtime452.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime452.jsx)(inspector_controls_default, { children: /* @__PURE__ */ (0, import_jsx_runtime452.jsxs)(import_components262.PanelBody, { title: (0, import_i18n237.__)("Layout"), children: [
showInheritToggle && /* @__PURE__ */ (0, import_jsx_runtime452.jsx)(import_jsx_runtime452.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime452.jsx)(
import_components262.ToggleControl,
{
label: (0, import_i18n237.__)("Inner blocks use content width"),
checked: layoutType?.name === "constrained" || hasContentSizeOrLegacySettings,
onChange: () => setAttributes({
layout: {
type: layoutType?.name === "constrained" || hasContentSizeOrLegacySettings ? "default" : "constrained"
}
}),
help: layoutType?.name === "constrained" || hasContentSizeOrLegacySettings ? (0, import_i18n237.__)(
"Nested blocks use content width with options for full and wide widths."
) : (0, import_i18n237.__)(
"Nested blocks will fill the width of this container."
)
}
) }),
!inherit && allowSwitching && /* @__PURE__ */ (0, import_jsx_runtime452.jsx)(
LayoutTypeSwitcher,
{
type: blockLayoutType,
onChange: onChangeType
}
),
layoutType && layoutType.name !== "default" && /* @__PURE__ */ (0, import_jsx_runtime452.jsx)(
layoutType.inspectorControls,
{
layout: usedLayout,
onChange: onChangeLayout,
layoutBlockSupport: blockSupportAndThemeSettings,
name: blockName,
clientId
}
),
constrainedType && displayControlsForLegacyLayouts && /* @__PURE__ */ (0, import_jsx_runtime452.jsx)(
constrainedType.inspectorControls,
{
layout: usedLayout,
onChange: onChangeLayout,
layoutBlockSupport: blockSupportAndThemeSettings,
name: blockName,
clientId
}
)
] }) }),
!inherit && layoutType && /* @__PURE__ */ (0, import_jsx_runtime452.jsx)(
layoutType.toolBarControls,
{
layout: usedLayout,
onChange: onChangeLayout,
layoutBlockSupport,
name: blockName,
clientId
}
)
] });
}
var layout_default2 = {
shareWithChildBlocks: true,
edit: LayoutPanelPure,
attributeKeys: ["layout"],
hasSupport(name) {
return hasLayoutBlockSupport(name);
}
};
function LayoutTypeSwitcher({ type, onChange }) {
return /* @__PURE__ */ (0, import_jsx_runtime452.jsx)(
import_components262.__experimentalToggleGroupControl,
{
__next40pxDefaultSize: true,
isBlock: true,
label: (0, import_i18n237.__)("Layout type"),
hideLabelFromVision: true,
isAdaptiveWidth: true,
value: type,
onChange,
children: getLayoutTypes().map(({ name, label }) => {
return /* @__PURE__ */ (0, import_jsx_runtime452.jsx)(
import_components262.__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,
layoutClasses
}) {
const { name, attributes } = props;
const id = (0, import_compose102.useInstanceId)(BlockListBlock2);
const { layout } = attributes;
const { default: defaultBlockLayout } = (0, import_blocks116.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 css3 = fullLayoutType?.getLayoutStyle?.({
blockName: name,
selector: selector3,
layout: usedLayout,
style: attributes?.style,
hasBlockGapSupport
});
const layoutClassNames = clsx_default(
{
[`${selectorPrefix}${id}`]: !!css3
// Only attach a container class if there is generated CSS to be attached.
},
layoutClasses
);
useStyleOverride({ css: css3 });
return /* @__PURE__ */ (0, import_jsx_runtime452.jsx)(
BlockListBlock2,
{
...props,
__unstableLayoutClassNames: layoutClassNames
}
);
}
var withLayoutStyles = (0, import_compose102.createHigherOrderComponent)(
(BlockListBlock2) => (props) => {
const { clientId, name, attributes } = props;
const blockSupportsLayout = hasLayoutBlockSupport(name);
const layoutClasses = useLayoutClasses(attributes, name);
const extraProps = (0, import_data187.useSelect)(
(select3) => {
if (!blockSupportsLayout) {
return;
}
const { getSettings: getSettings8, getBlockSettings: getBlockSettings2 } = unlock(
select3(store)
);
const { disableLayoutStyles } = getSettings8();
if (disableLayoutStyles) {
return;
}
const [blockGapSupport] = getBlockSettings2(
clientId,
"spacing.blockGap"
);
return { blockGapSupport };
},
[blockSupportsLayout, clientId]
);
if (!extraProps) {
return /* @__PURE__ */ (0, import_jsx_runtime452.jsx)(
BlockListBlock2,
{
...props,
__unstableLayoutClassNames: blockSupportsLayout ? layoutClasses : void 0
}
);
}
return /* @__PURE__ */ (0, import_jsx_runtime452.jsx)(
BlockWithLayoutStyles,
{
block: BlockListBlock2,
props,
layoutClasses,
...extraProps
}
);
},
"withLayoutStyles"
);
(0, import_hooks30.addFilter)(
"blocks.registerBlockType",
"core/layout/addAttribute",
addAttribute9
);
(0, import_hooks30.addFilter)(
"editor.BlockListBlock",
"core/editor/layout/with-layout-styles",
withLayoutStyles
);
// packages/block-editor/build-module/hooks/layout-child.mjs
var import_compose106 = __toESM(require_compose(), 1);
var import_data191 = __toESM(require_data(), 1);
var import_element268 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/grid/grid-visualizer.mjs
var import_element265 = __toESM(require_element(), 1);
var import_data188 = __toESM(require_data(), 1);
var import_compose103 = __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 size of template2.split(" ")) {
const previousTrack = tracks[tracks.length - 1];
const start2 = previousTrack ? previousTrack.end + gap : 0;
const end = start2 + parseFloat(size);
tracks.push({ start: start2, end });
}
return tracks;
}
function getClosestTrack(tracks, position, edge = "start") {
return tracks.reduce(
(closest, track, index) => Math.abs(track[edge] - position) < Math.abs(tracks[closest][edge] - position) ? index : closest,
0
);
}
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_runtime453 = __toESM(require_jsx_runtime(), 1);
function GridVisualizer({ clientId, contentRef, parentLayout }) {
const isDistractionFree = (0, import_data188.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_runtime453.jsx)(
GridVisualizerGrid,
{
gridClientId: clientId,
gridElement,
isManualGrid,
ref: contentRef
}
);
}
var GridVisualizerGrid = (0, import_element265.forwardRef)(
({ gridClientId, gridElement, isManualGrid }, ref) => {
const [gridInfo, setGridInfo] = (0, import_element265.useState)(
() => getGridInfo(gridElement)
);
const [isDroppingAllowed, setIsDroppingAllowed] = (0, import_element265.useState)(false);
(0, import_element265.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);
return () => {
borderBoxSpy.disconnect();
contentBoxSpy.disconnect();
};
}, [gridElement]);
(0, import_element265.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_runtime453.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_runtime453.jsx)(
"div",
{
ref,
className: "block-editor-grid-visualizer__grid",
style: gridInfo.style,
children: isManualGrid ? /* @__PURE__ */ (0, import_jsx_runtime453.jsx)(
ManualGridVisualizer,
{
gridClientId,
gridInfo
}
) : Array.from({ length: gridInfo.numItems }, (_, i2) => /* @__PURE__ */ (0, import_jsx_runtime453.jsx)(
GridVisualizerCell,
{
color: gridInfo.currentColor
},
i2
))
}
)
}
);
}
);
function ManualGridVisualizer({ gridClientId, gridInfo }) {
const [highlightedRect, setHighlightedRect] = (0, import_element265.useState)(null);
const gridItemStyles = (0, import_data188.useSelect)(
(select3) => {
const { getBlockOrder: getBlockOrder2, getBlockStyles: getBlockStyles2 } = unlock(
select3(store)
);
const blockOrder = getBlockOrder2(gridClientId);
return getBlockStyles2(blockOrder);
},
[gridClientId]
);
const occupiedRects = (0, import_element265.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 isCellOccupied = occupiedRects.some(
(rect) => rect.contains(column, row)
);
const isHighlighted = highlightedRect?.contains(column, row) ?? false;
return /* @__PURE__ */ (0, import_jsx_runtime453.jsx)(
GridVisualizerCell,
{
color: gridInfo.currentColor,
className: isHighlighted && "is-highlighted",
children: isCellOccupied ? /* @__PURE__ */ (0, import_jsx_runtime453.jsx)(
GridVisualizerDropZone,
{
column,
row,
gridClientId,
gridInfo,
setHighlightedRect
}
) : /* @__PURE__ */ (0, import_jsx_runtime453.jsx)(
GridVisualizerAppender,
{
column,
row,
gridClientId,
gridInfo,
setHighlightedRect
}
)
},
`${row}-${column}`
);
})
);
}
function GridVisualizerCell({ color, children, className }) {
return /* @__PURE__ */ (0, import_jsx_runtime453.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_data188.useSelect)(store);
const {
updateBlockAttributes: updateBlockAttributes2,
moveBlocksToPosition: moveBlocksToPosition2,
__unstableMarkNextChangeAsNotPersistent: __unstableMarkNextChangeAsNotPersistent2
} = (0, import_data188.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_runtime453.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_data188.useDispatch)(store);
const getNumberOfBlocksBeforeCell = useGetNumberOfBlocksBeforeCell(
gridClientId,
gridInfo.numColumns
);
return /* @__PURE__ */ (0, import_jsx_runtime453.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_data188.useSelect)(store);
return (0, import_compose103.__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_components264 = __toESM(require_components(), 1);
var import_element266 = __toESM(require_element(), 1);
var import_jsx_runtime454 = __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_runtime454.jsx)(
GridItemResizerInner,
{
clientId,
bounds,
blockElement,
rootBlockElement,
onChange,
isManualGrid: isManualPlacement && window.__experimentalEnableGridInteractivity
}
);
}
function GridItemResizerInner({
clientId,
bounds,
blockElement,
rootBlockElement,
onChange,
isManualGrid
}) {
const [resizeDirection, setResizeDirection] = (0, import_element266.useState)(null);
const [enableSide, setEnableSide] = (0, import_element266.useState)({
top: false,
bottom: false,
left: false,
right: false
});
(0, import_element266.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_runtime454.jsx)(
cover_default,
{
className: "block-editor-grid-item-resizer",
clientId,
__unstablePopoverSlot: "__unstable-block-tools-after",
additionalStyles: styles,
children: /* @__PURE__ */ (0, import_jsx_runtime454.jsx)(
import_components264.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_i18n238 = __toESM(require_i18n(), 1);
var import_components265 = __toESM(require_components(), 1);
var import_data189 = __toESM(require_data(), 1);
var import_compose104 = __toESM(require_compose(), 1);
var import_jsx_runtime455 = __toESM(require_jsx_runtime(), 1);
function GridItemMovers({
layout,
parentLayout,
onChange,
gridClientId,
blockClientId
}) {
const { moveBlocksToPosition: moveBlocksToPosition2, __unstableMarkNextChangeAsNotPersistent: __unstableMarkNextChangeAsNotPersistent2 } = (0, import_data189.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_runtime455.jsx)(block_controls_default, { group: "parent", children: /* @__PURE__ */ (0, import_jsx_runtime455.jsxs)(import_components265.ToolbarGroup, { className: "block-editor-grid-item-mover__move-button-container", children: [
/* @__PURE__ */ (0, import_jsx_runtime455.jsx)("div", { className: "block-editor-grid-item-mover__move-horizontal-button-container is-left", children: /* @__PURE__ */ (0, import_jsx_runtime455.jsx)(
GridItemMover,
{
icon: (0, import_i18n238.isRTL)() ? chevron_right_default : chevron_left_default,
label: (0, import_i18n238.__)("Move left"),
description: (0, import_i18n238.__)("Move left"),
isDisabled: columnStart <= 1,
onClick: () => {
onChange({
columnStart: columnStart - 1
});
__unstableMarkNextChangeAsNotPersistent2();
moveBlocksToPosition2(
[blockClientId],
gridClientId,
gridClientId,
getNumberOfBlocksBeforeCell(
columnStart - 1,
rowStart
)
);
}
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime455.jsxs)("div", { className: "block-editor-grid-item-mover__move-vertical-button-container", children: [
/* @__PURE__ */ (0, import_jsx_runtime455.jsx)(
GridItemMover,
{
className: "is-up-button",
icon: chevron_up_default,
label: (0, import_i18n238.__)("Move up"),
description: (0, import_i18n238.__)("Move up"),
isDisabled: rowStart <= 1,
onClick: () => {
onChange({
rowStart: rowStart - 1
});
__unstableMarkNextChangeAsNotPersistent2();
moveBlocksToPosition2(
[blockClientId],
gridClientId,
gridClientId,
getNumberOfBlocksBeforeCell(
columnStart,
rowStart - 1
)
);
}
}
),
/* @__PURE__ */ (0, import_jsx_runtime455.jsx)(
GridItemMover,
{
className: "is-down-button",
icon: chevron_down_default,
label: (0, import_i18n238.__)("Move down"),
description: (0, import_i18n238.__)("Move down"),
isDisabled: rowCount && rowEnd >= rowCount,
onClick: () => {
onChange({
rowStart: rowStart + 1
});
__unstableMarkNextChangeAsNotPersistent2();
moveBlocksToPosition2(
[blockClientId],
gridClientId,
gridClientId,
getNumberOfBlocksBeforeCell(
columnStart,
rowStart + 1
)
);
}
}
)
] }),
/* @__PURE__ */ (0, import_jsx_runtime455.jsx)("div", { className: "block-editor-grid-item-mover__move-horizontal-button-container is-right", children: /* @__PURE__ */ (0, import_jsx_runtime455.jsx)(
GridItemMover,
{
icon: (0, import_i18n238.isRTL)() ? chevron_left_default : chevron_right_default,
label: (0, import_i18n238.__)("Move right"),
description: (0, import_i18n238.__)("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_compose104.useInstanceId)(GridItemMover);
const descriptionId = `block-editor-grid-item-mover-button__description-${instanceId}`;
return /* @__PURE__ */ (0, import_jsx_runtime455.jsxs)(import_jsx_runtime455.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime455.jsx)(
import_components265.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_runtime455.jsx)(import_components265.VisuallyHidden, { id: descriptionId, children: description })
] });
}
// packages/block-editor/build-module/components/grid/use-grid-layout-sync.mjs
var import_data190 = __toESM(require_data(), 1);
var import_element267 = __toESM(require_element(), 1);
var import_compose105 = __toESM(require_compose(), 1);
function useGridLayoutSync({ clientId: gridClientId }) {
const { gridLayout, blockOrder, selectedBlockLayout } = (0, import_data190.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_data190.useSelect)(store);
const { updateBlockAttributes: updateBlockAttributes2, __unstableMarkNextChangeAsNotPersistent: __unstableMarkNextChangeAsNotPersistent2 } = (0, import_data190.useDispatch)(store);
const selectedBlockRect = (0, import_element267.useMemo)(
() => selectedBlockLayout ? new GridRect(selectedBlockLayout) : null,
[selectedBlockLayout]
);
const previouslySelectedBlockRect = (0, import_compose105.usePrevious)(selectedBlockRect);
const previousIsManualPlacement = (0, import_compose105.usePrevious)(
gridLayout.isManualPlacement
);
const previousBlockOrder = (0, import_compose105.usePrevious)(blockOrder);
(0, import_element267.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] = setImmutably(
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] = setImmutably(
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_runtime456 = __toESM(require_jsx_runtime(), 1);
var LAYOUT_CHILD_BLOCK_PROPS_REFERENCE = {};
function useBlockPropsChildLayoutStyles({ style }) {
const shouldRenderChildLayoutStyles = (0, import_data191.useSelect)((select3) => {
return !select3(store).getSettings().disableLayoutStyles;
});
const layout = style?.layout ?? {};
const {
selfStretch,
flexSize,
columnStart,
rowStart,
columnSpan,
rowSpan
} = layout;
const parentLayout = useLayout() || {};
const { columnCount, minimumColumnWidth } = parentLayout;
const id = (0, import_compose106.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 css3 = "";
if (shouldRenderChildLayoutStyles) {
if (selfStretch === "fixed" && flexSize) {
css3 = `${selector3} {
flex-basis: ${flexSize};
box-sizing: border-box;
}`;
} else if (selfStretch === "fill") {
css3 = `${selector3} {
flex-grow: 1;
}`;
} else if (columnStart && columnSpan) {
css3 = `${selector3} {
grid-column: ${columnStart} / span ${columnSpan};
}`;
} else if (columnStart) {
css3 = `${selector3} {
grid-column: ${columnStart};
}`;
} else if (columnSpan) {
css3 = `${selector3} {
grid-column: span ${columnSpan};
}`;
}
if (rowStart && rowSpan) {
css3 += `${selector3} {
grid-row: ${rowStart} / span ${rowSpan};
}`;
} else if (rowStart) {
css3 += `${selector3} {
grid-row: ${rowStart};
}`;
} else if (rowSpan) {
css3 += `${selector3} {
grid-row: span ${rowSpan};
}`;
}
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";
css3 += `@container (max-width: ${Math.max(
containerQueryValue,
minimumContainerQueryValue
)}${parentColumnUnit}) {
${selector3} {
grid-column: ${gridColumnValue};
grid-row: auto;
}
}`;
}
}
useStyleOverride({ css: css3 });
if (!css3) {
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_runtime456.jsx)(
GridTools,
{
clientId,
style,
setAttributes,
allowSizingOnChildren,
isManualPlacement,
parentLayout
}
);
}
function GridTools({
clientId,
style,
setAttributes,
allowSizingOnChildren,
isManualPlacement,
parentLayout
}) {
const { rootClientId, isVisible } = (0, import_data191.useSelect)(
(select3) => {
const {
getBlockRootClientId: getBlockRootClientId2,
getBlockEditingMode: getBlockEditingMode2,
getTemplateLock: getTemplateLock2
} = select3(store);
const _rootClientId = getBlockRootClientId2(clientId);
if (getTemplateLock2(_rootClientId) || getBlockEditingMode2(_rootClientId) !== "default") {
return {
rootClientId: _rootClientId,
isVisible: false
};
}
return {
rootClientId: _rootClientId,
isVisible: true
};
},
[clientId]
);
const [resizerBounds, setResizerBounds] = (0, import_element268.useState)();
if (!isVisible) {
return null;
}
function updateLayout(layout) {
setAttributes({
style: {
...style,
layout: {
...style?.layout,
...layout
}
}
});
}
return /* @__PURE__ */ (0, import_jsx_runtime456.jsxs)(import_jsx_runtime456.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime456.jsx)(
GridVisualizer,
{
clientId: rootClientId,
contentRef: setResizerBounds,
parentLayout
}
),
allowSizingOnChildren && /* @__PURE__ */ (0, import_jsx_runtime456.jsx)(
GridItemResizer,
{
clientId,
bounds: resizerBounds,
onChange: updateLayout,
parentLayout
}
),
isManualPlacement && window.__experimentalEnableGridInteractivity && /* @__PURE__ */ (0, import_jsx_runtime456.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/content-lock-ui.mjs
var import_components266 = __toESM(require_components(), 1);
var import_data192 = __toESM(require_data(), 1);
var import_i18n239 = __toESM(require_i18n(), 1);
var import_element269 = __toESM(require_element(), 1);
var import_jsx_runtime457 = __toESM(require_jsx_runtime(), 1);
function ContentLockControlsPure({ clientId }) {
const { templateLock, isLockedByParent, isEditingContentOnlySection } = (0, import_data192.useSelect)(
(select3) => {
const {
getContentLockingParent: getContentLockingParent2,
getTemplateLock: getTemplateLock2,
getEditedContentOnlySection: getEditedContentOnlySection2
} = unlock(select3(store));
return {
templateLock: getTemplateLock2(clientId),
isLockedByParent: !!getContentLockingParent2(clientId),
isEditingContentOnlySection: getEditedContentOnlySection2() === clientId
};
},
[clientId]
);
const { stopEditingContentOnlySection: stopEditingContentOnlySection2 } = unlock(
(0, import_data192.useDispatch)(store)
);
const isContentLocked = !isLockedByParent && templateLock === "contentOnly";
const stopEditingAsBlockCallback = (0, import_element269.useCallback)(() => {
stopEditingContentOnlySection2();
}, [stopEditingContentOnlySection2]);
if (window?.__experimentalContentOnlyPatternInsertion || !isContentLocked && !isEditingContentOnlySection) {
return null;
}
return isEditingContentOnlySection && /* @__PURE__ */ (0, import_jsx_runtime457.jsx)(block_controls_default, { group: "other", children: /* @__PURE__ */ (0, import_jsx_runtime457.jsx)(import_components266.ToolbarButton, { onClick: stopEditingAsBlockCallback, children: (0, import_i18n239.__)("Done") }) });
}
var content_lock_ui_default = {
edit: ContentLockControlsPure,
hasSupport() {
return true;
}
};
// packages/block-editor/build-module/hooks/metadata.mjs
var import_hooks31 = __toESM(require_hooks(), 1);
var import_blocks117 = __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, index, 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[index]?.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_blocks117.hasBlockSupport)(result.name, "renaming", true)) {
preservedMetadata.name = sourceMetadata.name;
}
if (sourceMetadata.blockVisibility !== void 0 && !result.attributes?.metadata?.blockVisibility && (0, import_blocks117.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_hooks31.addFilter)(
"blocks.registerBlockType",
"core/metadata/addMetaAttribute",
addMetaAttribute
);
(0, import_hooks31.addFilter)(
"blocks.switchToBlockType.transformedBlock",
"core/metadata/addTransforms",
addTransforms5
);
// packages/block-editor/build-module/hooks/block-hooks.mjs
var import_i18n240 = __toESM(require_i18n(), 1);
var import_element270 = __toESM(require_element(), 1);
var import_components268 = __toESM(require_components(), 1);
var import_blocks118 = __toESM(require_blocks(), 1);
var import_data193 = __toESM(require_data(), 1);
var import_jsx_runtime458 = __toESM(require_jsx_runtime(), 1);
var EMPTY_OBJECT5 = {};
function BlockHooksControlPure({
name,
clientId,
metadata: { ignoredHookedBlocks = [] } = {}
}) {
const blockTypes = (0, import_data193.useSelect)(
(select3) => select3(import_blocks118.store).getBlockTypes(),
[]
);
const hookedBlocksForCurrentBlock = (0, import_element270.useMemo)(
() => blockTypes?.filter(
({ name: blockName, blockHooks }) => blockHooks && name in blockHooks || ignoredHookedBlocks.includes(blockName)
),
[blockTypes, name, ignoredHookedBlocks]
);
const hookedBlockClientIds = (0, import_data193.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_data193.useSelect)(store);
const { insertBlock: insertBlock2, removeBlock: removeBlock2 } = (0, import_data193.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_runtime458.jsx)(inspector_controls_default, { children: /* @__PURE__ */ (0, import_jsx_runtime458.jsxs)(
import_components268.PanelBody,
{
className: "block-editor-hooks__block-hooks",
title: (0, import_i18n240.__)("Plugins"),
initialOpen: true,
children: [
/* @__PURE__ */ (0, import_jsx_runtime458.jsx)("p", { className: "block-editor-hooks__block-hooks-helptext", children: (0, import_i18n240.__)(
"Manage the inclusion of blocks added automatically by plugins."
) }),
Object.keys(groupedHookedBlocks).map((vendor) => {
return /* @__PURE__ */ (0, import_jsx_runtime458.jsxs)(import_element270.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime458.jsx)("h3", { children: vendor }),
groupedHookedBlocks[vendor].map((block) => {
const checked = block.name in hookedBlockClientIds;
return /* @__PURE__ */ (0, import_jsx_runtime458.jsx)(
import_components268.ToggleControl,
{
checked,
label: block.title,
onChange: () => {
if (!checked) {
const relativePosition = block.blockHooks[name];
insertBlockIntoDesignatedLocation(
(0, import_blocks118.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_i18n241 = __toESM(require_i18n(), 1);
var import_blocks119 = __toESM(require_blocks(), 1);
var import_components270 = __toESM(require_components(), 1);
var import_data194 = __toESM(require_data(), 1);
var import_element271 = __toESM(require_element(), 1);
var import_compose107 = __toESM(require_compose(), 1);
var import_jsx_runtime459 = __toESM(require_jsx_runtime(), 1);
var useToolsPanelDropdownMenuProps2 = () => {
const isMobile = (0, import_compose107.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_element271.useContext)(block_context_default);
const { removeAllBlockBindings } = useBlockBindingsUtils();
const dropdownMenuProps = useToolsPanelDropdownMenuProps2();
const { bindableAttributes, hasCompatibleFields } = (0, import_data194.useSelect)(
(select3) => {
const { __experimentalBlockBindingsSupportedAttributes } = select3(store).getSettings();
const {
getAllBlockBindingsSources,
getBlockBindingsSourceFieldsList
} = unlock(select3(import_blocks119.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_runtime459.jsx)(inspector_controls_default, { group: "bindings", children: /* @__PURE__ */ (0, import_jsx_runtime459.jsxs)(
import_components270.__experimentalToolsPanel,
{
label: (0, import_i18n241.__)("Attributes"),
resetAll: () => {
removeAllBlockBindings();
},
dropdownMenuProps,
className: "block-editor-bindings__panel",
children: [
/* @__PURE__ */ (0, import_jsx_runtime459.jsx)(import_components270.__experimentalItemGroup, { isBordered: true, isSeparated: true, children: bindableAttributes.map((attribute) => /* @__PURE__ */ (0, import_jsx_runtime459.jsx)(
BlockBindingsAttributeControl,
{
attribute,
blockName,
binding: bindings?.[attribute]
},
attribute
)) }),
/* @__PURE__ */ (0, import_jsx_runtime459.jsx)(import_components270.__experimentalText, { as: "div", variant: "muted", children: /* @__PURE__ */ (0, import_jsx_runtime459.jsx)("p", { children: (0, import_i18n241.__)(
"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_i18n242 = __toESM(require_i18n(), 1);
var import_components271 = __toESM(require_components(), 1);
var import_data195 = __toESM(require_data(), 1);
var import_blocks120 = __toESM(require_blocks(), 1);
var import_element272 = __toESM(require_element(), 1);
var import_jsx_runtime460 = __toESM(require_jsx_runtime(), 1);
var LIST_VIEW_SUPPORT_KEY = "listView";
function hasListViewSupport(nameOrType) {
return (0, import_blocks120.hasBlockSupport)(nameOrType, LIST_VIEW_SUPPORT_KEY);
}
function ListViewPanel({ clientId, name }) {
const { isSelectionWithinCurrentSection } = (0, import_element272.useContext)(PrivateBlockContext);
const isEnabled = hasListViewSupport(name);
const { hasChildren, blockTitle, isNestedListView } = (0, import_data195.useSelect)(
(select3) => {
const { getBlockCount: getBlockCount2, getBlockParents: getBlockParents2, getBlockName: getBlockName2 } = select3(store);
let _isNestedListView = false;
if (isSelectionWithinCurrentSection) {
const parents = getBlockParents2(clientId, true);
_isNestedListView = parents.find((parentId) => {
const parentName = getBlockName2(parentId);
return parentName === "core/navigation" || (0, import_blocks120.hasBlockSupport)(parentName, "listView");
});
}
return {
hasChildren: !!getBlockCount2(clientId),
blockTitle: select3(import_blocks120.store).getBlockType(name)?.title,
isNestedListView: _isNestedListView
};
},
[clientId, name, isSelectionWithinCurrentSection]
);
if (!isEnabled || isNestedListView) {
return null;
}
const showBlockTitle = isSelectionWithinCurrentSection;
return /* @__PURE__ */ (0, import_jsx_runtime460.jsx)(InspectorControlsFill, { group: "list", children: /* @__PURE__ */ (0, import_jsx_runtime460.jsxs)(import_components271.PanelBody, { title: showBlockTitle ? blockTitle : void 0, children: [
!hasChildren && /* @__PURE__ */ (0, import_jsx_runtime460.jsx)("p", { className: "block-editor-block-inspector__no-blocks", children: (0, import_i18n242.__)("No items yet.") }),
/* @__PURE__ */ (0, import_jsx_runtime460.jsx)(
PrivateListView,
{
rootClientId: clientId,
isExpanded: true,
description: blockTitle,
showAppender: true
}
)
] }) });
}
var list_view_default3 = {
edit: ListViewPanel,
hasSupport: hasListViewSupport,
attributeKeys: [],
supportsPatternEditing: true
};
// packages/block-editor/build-module/hooks/block-renaming.mjs
var import_hooks32 = __toESM(require_hooks(), 1);
var import_blocks121 = __toESM(require_blocks(), 1);
function addLabelCallback(settings2) {
if (settings2.__experimentalLabel) {
return settings2;
}
const supportsBlockNaming = (0, import_blocks121.hasBlockSupport)(
settings2,
"renaming",
true
// default value
);
if (supportsBlockNaming) {
settings2.__experimentalLabel = (attributes, { context }) => {
const { metadata } = attributes;
if (context === "list-view" && metadata?.name) {
return metadata.name;
}
};
}
return settings2;
}
(0, import_hooks32.addFilter)(
"blocks.registerBlockType",
"core/metadata/addLabelCallback",
addLabelCallback
);
// packages/block-editor/build-module/hooks/grid-visualizer.mjs
var import_compose108 = __toESM(require_compose(), 1);
var import_hooks33 = __toESM(require_hooks(), 1);
var import_data196 = __toESM(require_data(), 1);
var import_jsx_runtime461 = __toESM(require_jsx_runtime(), 1);
function GridLayoutSync(props) {
useGridLayoutSync(props);
}
function GridTools2({ clientId, layout }) {
const isVisible = (0, import_data196.useSelect)(
(select3) => {
const {
isBlockSelected: isBlockSelected2,
isDraggingBlocks: isDraggingBlocks2,
getTemplateLock: getTemplateLock2,
getBlockEditingMode: getBlockEditingMode2
} = select3(store);
if (!isDraggingBlocks2() && !isBlockSelected2(clientId) || getTemplateLock2(clientId) || getBlockEditingMode2(clientId) !== "default") {
return false;
}
return true;
},
[clientId]
);
return /* @__PURE__ */ (0, import_jsx_runtime461.jsxs)(import_jsx_runtime461.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime461.jsx)(GridLayoutSync, { clientId }),
isVisible && /* @__PURE__ */ (0, import_jsx_runtime461.jsx)(GridVisualizer, { clientId, parentLayout: layout })
] });
}
var addGridVisualizerToBlockEdit = (0, import_compose108.createHigherOrderComponent)(
(BlockEdit2) => (props) => {
if (props.attributes.layout?.type !== "grid") {
return /* @__PURE__ */ (0, import_jsx_runtime461.jsx)(BlockEdit2, { ...props }, "edit");
}
return /* @__PURE__ */ (0, import_jsx_runtime461.jsxs)(import_jsx_runtime461.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime461.jsx)(
GridTools2,
{
clientId: props.clientId,
layout: props.attributes.layout
}
),
/* @__PURE__ */ (0, import_jsx_runtime461.jsx)(BlockEdit2, { ...props }, "edit")
] });
},
"addGridVisualizerToBlockEdit"
);
(0, import_hooks33.addFilter)(
"editor.BlockEdit",
"core/editor/grid-visualizer",
addGridVisualizerToBlockEdit
);
// packages/block-editor/build-module/hooks/auto-inspector-controls.mjs
var import_blocks122 = __toESM(require_blocks(), 1);
var import_components272 = __toESM(require_components(), 1);
var import_data197 = __toESM(require_data(), 1);
var import_element273 = __toESM(require_element(), 1);
var import_i18n243 = __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.__experimentalAutoInspectorControl) {
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;
if (!["string", "number", "integer", "boolean"].includes(type)) {
return null;
}
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_runtime462 = __toESM(require_jsx_runtime(), 1);
function hasAutoInspectorControlAttributes(blockTypeAttributes) {
if (!blockTypeAttributes) {
return false;
}
return Object.values(blockTypeAttributes).some(
(attr) => attr?.__experimentalAutoInspectorControl
);
}
function AutoRegisterControls({ name, clientId, setAttributes }) {
const blockEditingMode = useBlockEditingMode();
const attributes = (0, import_data197.useSelect)(
(select3) => select3(store).getBlockAttributes(clientId),
[clientId]
);
const blockType = (0, import_blocks122.getBlockType)(name);
const { fields, form } = (0, import_element273.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_runtime462.jsx)(inspector_controls_default, { children: /* @__PURE__ */ (0, import_jsx_runtime462.jsx)(import_components272.PanelBody, { title: (0, import_i18n243.__)("Settings"), children: /* @__PURE__ */ (0, import_jsx_runtime462.jsx)(
DataForm,
{
data: attributes,
fields,
form,
onChange: setAttributes
}
) }) });
}
var auto_inspector_controls_default = {
edit: AutoRegisterControls,
attributeKeys: [],
hasSupport(name) {
const blockType = (0, import_blocks122.getBlockType)(name);
return hasAutoInspectorControlAttributes(blockType?.attributes);
}
};
// 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_element274 = __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_element274.useMemo)(
() => [
...userPalette || [],
...themePalette || [],
...defaultPalette || []
],
[userPalette, themePalette, defaultPalette]
);
const gradients = (0, import_element274.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_components273 = __toESM(require_components(), 1);
var { kebabCase: kebabCase7 } = unlock(import_components273.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_element275 = __toESM(require_element(), 1);
function useCachedTruthy(value) {
const [cachedValue, setCachedValue] = (0, import_element275.useState)(value);
(0, import_element275.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_default2,
duotone_default,
fit_text_default,
position_default,
layout_default2,
content_lock_ui_default,
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_default2,
color_default,
dimensions_default,
duotone_default,
font_family_default,
font_size_default,
fit_text_default,
border_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,
fit_text_default,
color_default,
style_default2,
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_element276 = __toESM(require_element(), 1);
var import_blocks123 = __toESM(require_blocks(), 1);
var import_rich_text21 = __toESM(require_rich_text(), 1);
var import_jsx_runtime463 = __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_element276.StrictMode:
case import_element276.Fragment:
return addValuesForElements(props.children, values, innerBlocks);
case import_element276.RawHTML:
return;
case inner_blocks_default.Content:
return addValuesForBlocks(values, innerBlocks);
case Content:
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_blocks123.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_runtime463.jsx)(inner_blocks_default.Content, {})
);
addValuesForElement(saveElement, values, innerBlocks);
}
}
function getRichTextValues(blocks2 = []) {
import_blocks123.__unstableGetBlockProps.skipFilters = true;
const values = [];
addValuesForBlocks(values, blocks2);
import_blocks123.__unstableGetBlockProps.skipFilters = false;
return values.map(
(value) => value instanceof import_rich_text21.RichTextData ? value : import_rich_text21.RichTextData.fromHTMLString(value)
);
}
// packages/block-editor/build-module/components/resizable-box-popover/index.mjs
var import_components274 = __toESM(require_components(), 1);
var import_jsx_runtime464 = __toESM(require_jsx_runtime(), 1);
function ResizableBoxPopover({
clientId,
resizableBoxProps,
...props
}) {
return /* @__PURE__ */ (0, import_jsx_runtime464.jsx)(
cover_default,
{
clientId,
__unstablePopoverSlot: "block-toolbar",
...props,
children: /* @__PURE__ */ (0, import_jsx_runtime464.jsx)(import_components274.ResizableBox, { ...resizableBoxProps })
}
);
}
// packages/block-editor/build-module/components/block-removal-warning-modal/index.mjs
var import_element277 = __toESM(require_element(), 1);
var import_data198 = __toESM(require_data(), 1);
var import_components275 = __toESM(require_components(), 1);
var import_i18n244 = __toESM(require_i18n(), 1);
var import_jsx_runtime465 = __toESM(require_jsx_runtime(), 1);
function BlockRemovalWarningModal({ rules }) {
const { clientIds, selectPrevious, message: message2 } = (0, import_data198.useSelect)(
(select3) => unlock(select3(store)).getRemovalPromptData()
);
const {
clearBlockRemovalPrompt: clearBlockRemovalPrompt2,
setBlockRemovalRules: setBlockRemovalRules2,
privateRemoveBlocks: privateRemoveBlocks2
} = unlock((0, import_data198.useDispatch)(store));
(0, import_element277.useEffect)(() => {
setBlockRemovalRules2(rules);
return () => {
setBlockRemovalRules2();
};
}, [rules, setBlockRemovalRules2]);
if (!message2) {
return;
}
const onConfirmRemoval = () => {
privateRemoveBlocks2(
clientIds,
selectPrevious,
/* force */
true
);
clearBlockRemovalPrompt2();
};
return /* @__PURE__ */ (0, import_jsx_runtime465.jsxs)(
import_components275.Modal,
{
title: (0, import_i18n244.__)("Be careful!"),
onRequestClose: clearBlockRemovalPrompt2,
size: "medium",
children: [
/* @__PURE__ */ (0, import_jsx_runtime465.jsx)("p", { children: message2 }),
/* @__PURE__ */ (0, import_jsx_runtime465.jsxs)(import_components275.__experimentalHStack, { justify: "right", children: [
/* @__PURE__ */ (0, import_jsx_runtime465.jsx)(
import_components275.Button,
{
variant: "tertiary",
onClick: clearBlockRemovalPrompt2,
__next40pxDefaultSize: true,
children: (0, import_i18n244.__)("Cancel")
}
),
/* @__PURE__ */ (0, import_jsx_runtime465.jsx)(
import_components275.Button,
{
variant: "primary",
onClick: onConfirmRemoval,
__next40pxDefaultSize: true,
children: (0, import_i18n244.__)("Delete")
}
)
] })
]
}
);
}
// packages/block-editor/build-module/components/dimensions-tool/index.mjs
var import_element279 = __toESM(require_element(), 1);
// packages/block-editor/build-module/components/dimensions-tool/scale-tool.mjs
var import_components276 = __toESM(require_components(), 1);
var import_element278 = __toESM(require_element(), 1);
var import_i18n245 = __toESM(require_i18n(), 1);
var import_jsx_runtime466 = __toESM(require_jsx_runtime(), 1);
var DEFAULT_SCALE_OPTIONS = [
{
value: "fill",
label: (0, import_i18n245._x)("Fill", "Scale option for dimensions control"),
help: (0, import_i18n245.__)("Fill the space by stretching the content.")
},
{
value: "contain",
label: (0, import_i18n245._x)("Contain", "Scale option for dimensions control"),
help: (0, import_i18n245.__)("Fit the content to the space without clipping.")
},
{
value: "cover",
label: (0, import_i18n245._x)("Cover", "Scale option for dimensions control"),
help: (0, import_i18n245.__)("Fill the space by clipping what doesn't fit.")
},
{
value: "none",
label: (0, import_i18n245._x)("None", "Scale option for dimensions control"),
help: (0, import_i18n245.__)(
"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_i18n245._x)("Scale down", "Scale option for dimensions control"),
help: (0, import_i18n245.__)(
"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 ?? "fill";
const scaleHelp = (0, import_element278.useMemo)(() => {
return options.reduce((acc, option) => {
acc[option.value] = option.help;
return acc;
}, {});
}, [options]);
return /* @__PURE__ */ (0, import_jsx_runtime466.jsx)(
import_components276.__experimentalToolsPanelItem,
{
label: (0, import_i18n245.__)("Scale"),
isShownByDefault,
hasValue: () => displayValue !== defaultValue,
onDeselect: () => onChange(defaultValue),
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime466.jsx)(
import_components276.__experimentalToggleGroupControl,
{
label: (0, import_i18n245.__)("Scale"),
isBlock: true,
help: scaleHelp[displayValue],
value: displayValue,
onChange,
size: "__unstable-large",
children: options.map((option) => /* @__PURE__ */ (0, import_jsx_runtime466.jsx)(
import_components276.__experimentalToggleGroupControlOption,
{
...option
},
option.value
))
}
)
}
);
}
// packages/block-editor/build-module/components/dimensions-tool/width-height-tool.mjs
var import_components277 = __toESM(require_components(), 1);
var import_i18n246 = __toESM(require_i18n(), 1);
var import_jsx_runtime467 = __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_runtime467.jsxs)(import_jsx_runtime467.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime467.jsx)(
import_components277.__experimentalToolsPanelItem,
{
style: { gridColumn: "span 1" },
label: (0, import_i18n246.__)("Width"),
isShownByDefault,
hasValue: () => width !== "",
onDeselect: onDimensionChange("width"),
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime467.jsx)(
import_components277.__experimentalUnitControl,
{
label: (0, import_i18n246.__)("Width"),
placeholder: (0, import_i18n246.__)("Auto"),
labelPosition: "top",
units: units2,
min: 0,
value: width,
onChange: onDimensionChange("width"),
size: "__unstable-large"
}
)
}
),
/* @__PURE__ */ (0, import_jsx_runtime467.jsx)(
import_components277.__experimentalToolsPanelItem,
{
style: { gridColumn: "span 1" },
label: (0, import_i18n246.__)("Height"),
isShownByDefault,
hasValue: () => height !== "",
onDeselect: onDimensionChange("height"),
panelId,
children: /* @__PURE__ */ (0, import_jsx_runtime467.jsx)(
import_components277.__experimentalUnitControl,
{
label: (0, import_i18n246.__)("Height"),
placeholder: (0, import_i18n246.__)("Auto"),
labelPosition: "top",
units: units2,
min: 0,
value: height,
onChange: onDimensionChange("height"),
size: "__unstable-large"
}
)
}
)
] });
}
// packages/block-editor/build-module/components/dimensions-tool/index.mjs
var import_jsx_runtime468 = __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 = "fill",
// Match CSS default value for object-fit.
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 || value.scale === "fill" ? null : value.scale;
const [lastScale, setLastScale] = (0, import_element279.useState)(scale);
const [lastAspectRatio, setLastAspectRatio] = (0, import_element279.useState)(aspectRatio);
const aspectRatioValue = width && height ? "custom" : lastAspectRatio;
const showScaleControl = aspectRatio || width && height;
return /* @__PURE__ */ (0, import_jsx_runtime468.jsxs)(import_jsx_runtime468.Fragment, { children: [
tools.includes("aspectRatio") && /* @__PURE__ */ (0, import_jsx_runtime468.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_runtime468.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_runtime468.jsx)(
ScaleTool,
{
panelId,
options: scaleOptions,
defaultValue: defaultScale,
value: lastScale,
onChange: (nextScale) => {
const nextValue = { ...value };
nextScale = nextScale === "fill" ? null : nextScale;
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_components278 = __toESM(require_components(), 1);
var import_i18n247 = __toESM(require_i18n(), 1);
var import_jsx_runtime469 = __toESM(require_jsx_runtime(), 1);
var DEFAULT_SIZE_OPTIONS = [
{
label: (0, import_i18n247._x)("Thumbnail", "Image size option for resolution control"),
value: "thumbnail"
},
{
label: (0, import_i18n247._x)("Medium", "Image size option for resolution control"),
value: "medium"
},
{
label: (0, import_i18n247._x)("Large", "Image size option for resolution control"),
value: "large"
},
{
label: (0, import_i18n247._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_runtime469.jsx)(
import_components278.__experimentalToolsPanelItem,
{
hasValue: () => displayValue !== defaultValue,
label: (0, import_i18n247.__)("Resolution"),
onDeselect: () => onChange(defaultValue),
isShownByDefault,
panelId,
resetAllFilter,
children: /* @__PURE__ */ (0, import_jsx_runtime469.jsx)(
import_components278.SelectControl,
{
label: (0, import_i18n247.__)("Resolution"),
value: displayValue,
options,
onChange,
help: (0, import_i18n247.__)("Select the size of the source image."),
size: "__unstable-large"
}
)
}
);
}
// packages/block-editor/build-module/components/html-element-control/index.mjs
var import_i18n249 = __toESM(require_i18n(), 1);
var import_components279 = __toESM(require_components(), 1);
var import_data199 = __toESM(require_data(), 1);
// packages/block-editor/build-module/components/html-element-control/messages.mjs
var import_i18n248 = __toESM(require_i18n(), 1);
var htmlElementMessages = {
a: (0, import_i18n248.__)(
"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_i18n248.__)(
"The <article> element should represent a self-contained, syndicatable portion of the document."
),
aside: (0, import_i18n248.__)(
"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_i18n248.__)(
"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_i18n248.__)(
"The <div> element should only be used if the block is a design element with no semantic meaning."
),
footer: (0, import_i18n248.__)(
"The <footer> element should represent a footer for its nearest sectioning element (e.g.: <section>, <article>, <main> etc.)."
),
header: (0, import_i18n248.__)(
"The <header> element should represent introductory content, typically a group of introductory or navigational aids."
),
main: (0, import_i18n248.__)(
"The <main> element should be used for the primary content of your document only."
),
nav: (0, import_i18n248.__)(
"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_i18n248.__)(
"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_runtime470 = __toESM(require_jsx_runtime(), 1);
function HTMLElementControl({
tagName,
onChange,
clientId,
options = [
{ label: (0, import_i18n249.__)("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_data199.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_i18n249.sprintf)(
/* translators: %s: HTML element name */
(0, import_i18n249.__)("%s (Already in use)"),
option.label
)
};
}
return option;
});
return /* @__PURE__ */ (0, import_jsx_runtime470.jsxs)(import_components279.__experimentalVStack, { spacing: 2, className: "block-editor-html-element-control", children: [
/* @__PURE__ */ (0, import_jsx_runtime470.jsx)(
import_components279.SelectControl,
{
__next40pxDefaultSize: true,
label: (0, import_i18n249.__)("HTML element"),
options: modifiedOptions,
value: tagName,
onChange,
help: htmlElementMessages[tagName]
}
),
tagName === "main" && hasMainElementElsewhere && /* @__PURE__ */ (0, import_jsx_runtime470.jsx)(import_components279.Notice, { status: "warning", isDismissible: false, children: (0, import_i18n249.__)(
"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_components281 = __toESM(require_components(), 1);
var import_element280 = __toESM(require_element(), 1);
var import_i18n250 = __toESM(require_i18n(), 1);
// packages/block-editor/build-module/components/link-picker/link-preview.mjs
var import_components280 = __toESM(require_components(), 1);
var import_jsx_runtime471 = __toESM(require_jsx_runtime(), 1);
var { Badge: Badge4 } = unlock(import_components280.privateApis);
function LinkPreview2({ title, url, image, badges }) {
return /* @__PURE__ */ (0, import_jsx_runtime471.jsxs)(import_components280.__experimentalHStack, { justify: "space-between", alignment: "top", children: [
/* @__PURE__ */ (0, import_jsx_runtime471.jsx)(import_components280.FlexItem, { className: "link-preview-button__content", children: /* @__PURE__ */ (0, import_jsx_runtime471.jsxs)(import_components280.__experimentalHStack, { alignment: "top", children: [
image && /* @__PURE__ */ (0, import_jsx_runtime471.jsx)(import_components280.FlexItem, { className: "link-preview-button__image-container", children: /* @__PURE__ */ (0, import_jsx_runtime471.jsx)(
"img",
{
className: "link-preview-button__image",
src: image,
alt: ""
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime471.jsxs)(
import_components280.__experimentalVStack,
{
className: "link-preview-button__details",
alignment: "topLeft",
children: [
/* @__PURE__ */ (0, import_jsx_runtime471.jsx)(
import_components280.__experimentalTruncate,
{
numberOfLines: 1,
className: "link-preview-button__title",
children: title
}
),
url && /* @__PURE__ */ (0, import_jsx_runtime471.jsx)(
import_components280.__experimentalTruncate,
{
numberOfLines: 1,
className: "link-preview-button__hint",
children: url
}
),
badges && badges.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime471.jsx)(
import_components280.__experimentalHStack,
{
className: "link-preview-button__badges",
alignment: "left",
children: badges.map((badge) => /* @__PURE__ */ (0, import_jsx_runtime471.jsx)(
Badge4,
{
intent: badge.intent,
children: badge.label
},
`${badge.label}|${badge.intent}`
))
}
)
]
}
)
] }) }),
/* @__PURE__ */ (0, import_jsx_runtime471.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_runtime472 = __toESM(require_jsx_runtime(), 1);
function LinkPicker({
preview,
onSelect,
suggestionsQuery,
label,
help
}) {
const [isOpen, setIsOpen] = (0, import_element280.useState)(false);
const instanceId = (0, import_element280.useId)();
const dialogTitleId = `link-picker-title-${instanceId}`;
const dialogDescriptionId = `link-picker-description-${instanceId}`;
const anchorRef = (0, import_element280.useRef)(null);
const { baseControlProps, controlProps } = (0, import_components281.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_runtime472.jsxs)(import_components281.BaseControl, { ...baseControlProps, children: [
/* @__PURE__ */ (0, import_jsx_runtime472.jsx)(import_components281.BaseControl.VisualLabel, { children: label }),
/* @__PURE__ */ (0, import_jsx_runtime472.jsxs)(
import_components281.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_runtime472.jsxs)(import_components281.VisuallyHidden, { children: [
label,
":"
] }),
/* @__PURE__ */ (0, import_jsx_runtime472.jsx)(
LinkPreview2,
{
title: preview.title || (0, import_i18n250.__)("Add link"),
url: preview.url,
image: preview.image,
badges: preview.badges
}
)
]
}
),
isOpen && /* @__PURE__ */ (0, import_jsx_runtime472.jsx)(
import_components281.Popover,
{
anchor: anchorRef.current,
onClose: () => setIsOpen(false),
placement: "left-start",
offset: 36,
shift: true,
children: /* @__PURE__ */ (0, import_jsx_runtime472.jsxs)(
"div",
{
role: "dialog",
"aria-labelledby": dialogTitleId,
"aria-describedby": dialogDescriptionId,
children: [
/* @__PURE__ */ (0, import_jsx_runtime472.jsxs)(import_components281.VisuallyHidden, { children: [
/* @__PURE__ */ (0, import_jsx_runtime472.jsx)("h2", { id: dialogTitleId, children: (0, import_i18n250.__)("Select a link") }),
/* @__PURE__ */ (0, import_jsx_runtime472.jsx)("p", { id: dialogDescriptionId, children: (0, import_i18n250.__)(
"Search for and add a link to the navigation item."
) })
] }),
/* @__PURE__ */ (0, import_jsx_runtime472.jsx)(
link_control_default,
{
value: null,
onChange: handleChange,
suggestionsQuery,
showInitialSuggestions: true,
forceIsEditingLink: true,
settings: []
}
)
]
}
)
}
)
] });
}
// packages/block-editor/build-module/private-apis.mjs
var privateApis12 = {};
lock(privateApis12, {
...global_styles_exports,
ExperimentalBlockCanvas,
ExperimentalBlockEditorProvider,
getDuotoneFilter,
getRichTextValues,
PrivateQuickInserter: QuickInserter,
extractWords,
getNormalizedSearchTerms,
normalizeString,
PrivateListView,
ResizableBoxPopover,
useHasBlockToolbar,
cleanEmptyObject,
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,
PrivateBlockPopover,
PrivatePublishDateTimePicker,
useSpacingSizes,
useBlockDisplayTitle,
__unstableBlockStyleVariationOverridesWithConfig,
setBackgroundStyleDefaults: setBackgroundStyleDefaults2,
sectionRootClientIdKey,
CommentIconSlotFill: block_comment_icon_slot_default,
CommentIconToolbarSlotFill: block_comment_icon_toolbar_slot_default,
mediaEditKey,
getMediaSelectKey,
essentialFormatKey,
deviceTypeKey,
isIsolatedEditorKey,
useBlockElement,
useBlockElementRef,
LinkPicker,
useRemoteUrlData: use_rich_url_data_default
});
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
*)
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
*)
*/
//# sourceMappingURL=index.js.map