PluginProbe
Gutenberg / 23.5.2
Gutenberg v23.5.2
23.9.1 23.9.0 23.8.0 23.7.2 23.7.1 23.7.0 23.6.1 23.6.2 23.6.0 23.5.3 23.5.2 23.5.1 23.5.0 23.4.0 23.3.2 23.3.1 23.3.0 23.2.0 23.2.1 23.2.2 23.1.1 23.1.0 23.0.1 12.6.0 7.4.0 All 402 releases
gutenberg / build / modules / lazy-editor / index.js

index.js in Gutenberg 23.5.2, at build/modules/lazy-editor/index.js

2,897 lines 95.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 var __create = Object.create;
2 var __defProp = Object.defineProperty;
3 var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4 var __getOwnPropNames = Object.getOwnPropertyNames;
5 var __getProtoOf = Object.getPrototypeOf;
6 var __hasOwnProp = Object.prototype.hasOwnProperty;
7 var __commonJS = (cb, mod) => function __require() {
8 return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9 };
10 var __copyProps = (to, from, except, desc) => {
11 if (from && typeof from === "object" || typeof from === "function") {
12 for (let key of __getOwnPropNames(from))
13 if (!__hasOwnProp.call(to, key) && key !== except)
14 __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15 }
16 return to;
17 };
18 var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
19 // If the importer is in node compatibility mode or this is not an ESM
20 // file that has been converted to a CommonJS file using a Babel-
21 // compatible transform (i.e. "__esModule" has not been set), then set
22 // "default" to the CommonJS "module.exports" for node compatibility.
23 isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24 mod
25 ));
26
27 // package-external:@wordpress/editor
28 var require_editor = __commonJS({
29 "package-external:@wordpress/editor"(exports, module) {
30 module.exports = window.wp.editor;
31 }
32 });
33
34 // package-external:@wordpress/core-data
35 var require_core_data = __commonJS({
36 "package-external:@wordpress/core-data"(exports, module) {
37 module.exports = window.wp.coreData;
38 }
39 });
40
41 // package-external:@wordpress/data
42 var require_data = __commonJS({
43 "package-external:@wordpress/data"(exports, module) {
44 module.exports = window.wp.data;
45 }
46 });
47
48 // package-external:@wordpress/components
49 var require_components = __commonJS({
50 "package-external:@wordpress/components"(exports, module) {
51 module.exports = window.wp.components;
52 }
53 });
54
55 // package-external:@wordpress/element
56 var require_element = __commonJS({
57 "package-external:@wordpress/element"(exports, module) {
58 module.exports = window.wp.element;
59 }
60 });
61
62 // package-external:@wordpress/style-engine
63 var require_style_engine = __commonJS({
64 "package-external:@wordpress/style-engine"(exports, module) {
65 module.exports = window.wp.styleEngine;
66 }
67 });
68
69 // package-external:@wordpress/i18n
70 var require_i18n = __commonJS({
71 "package-external:@wordpress/i18n"(exports, module) {
72 module.exports = window.wp.i18n;
73 }
74 });
75
76 // package-external:@wordpress/blocks
77 var require_blocks = __commonJS({
78 "package-external:@wordpress/blocks"(exports, module) {
79 module.exports = window.wp.blocks;
80 }
81 });
82
83 // package-external:@wordpress/private-apis
84 var require_private_apis = __commonJS({
85 "package-external:@wordpress/private-apis"(exports, module) {
86 module.exports = window.wp.privateApis;
87 }
88 });
89
90 // vendor-external:react/jsx-runtime
91 var require_jsx_runtime = __commonJS({
92 "vendor-external:react/jsx-runtime"(exports, module) {
93 module.exports = window.ReactJSXRuntime;
94 }
95 });
96
97 // package-external:@wordpress/block-editor
98 var require_block_editor = __commonJS({
99 "package-external:@wordpress/block-editor"(exports, module) {
100 module.exports = window.wp.blockEditor;
101 }
102 });
103
104 // packages/lazy-editor/build-module/components/editor/index.mjs
105 var import_editor = __toESM(require_editor(), 1);
106 var import_core_data5 = __toESM(require_core_data(), 1);
107 var import_data6 = __toESM(require_data(), 1);
108 var import_components = __toESM(require_components(), 1);
109 var import_element4 = __toESM(require_element(), 1);
110
111 // packages/lazy-editor/build-module/hooks/use-styles-id.mjs
112 var import_core_data = __toESM(require_core_data(), 1);
113 var import_data = __toESM(require_data(), 1);
114 function useStylesId({ templateId } = {}) {
115 const { globalStylesId, stylesId } = (0, import_data.useSelect)(
116 (select2) => {
117 const coreDataSelect = select2(import_core_data.store);
118 const template = templateId ? coreDataSelect.getEntityRecord(
119 "postType",
120 "wp_template",
121 templateId
122 ) : null;
123 return {
124 globalStylesId: coreDataSelect.__experimentalGetCurrentGlobalStylesId(),
125 stylesId: template?.styles_id
126 };
127 },
128 [templateId]
129 );
130 return stylesId || globalStylesId;
131 }
132
133 // packages/global-styles-engine/build-module/utils/object.mjs
134 function setImmutably(object, path, value) {
135 path = Array.isArray(path) ? [...path] : [path];
136 object = Array.isArray(object) ? [...object] : { ...object };
137 const leaf = path.pop();
138 let prev = object;
139 for (const key of path) {
140 const lvl = prev[key];
141 prev = prev[key] = Array.isArray(lvl) ? [...lvl] : { ...lvl };
142 }
143 prev[leaf] = value;
144 return object;
145 }
146 var getValueFromObjectPath = (object, path, defaultValue) => {
147 const arrayPath = Array.isArray(path) ? path : path.split(".");
148 let value = object;
149 arrayPath.forEach((fieldName) => {
150 value = value?.[fieldName];
151 });
152 return value ?? defaultValue;
153 };
154
155 // packages/global-styles-engine/build-module/settings/get-setting.mjs
156 var VALID_SETTINGS = [
157 "appearanceTools",
158 "useRootPaddingAwareAlignments",
159 "background.backgroundImage",
160 "background.backgroundRepeat",
161 "background.backgroundSize",
162 "background.backgroundPosition",
163 "background.gradient",
164 "border.color",
165 "border.radius",
166 "border.radiusSizes",
167 "border.style",
168 "border.width",
169 "shadow.presets",
170 "shadow.defaultPresets",
171 "color.background",
172 "color.button",
173 "color.caption",
174 "color.custom",
175 "color.customDuotone",
176 "color.customGradient",
177 "color.defaultDuotone",
178 "color.defaultGradients",
179 "color.defaultPalette",
180 "color.duotone",
181 "color.gradients",
182 "color.heading",
183 "color.link",
184 "color.palette",
185 "color.text",
186 "custom",
187 "dimensions.aspectRatio",
188 "dimensions.height",
189 "dimensions.minHeight",
190 "dimensions.minWidth",
191 "dimensions.width",
192 "dimensions.dimensionSizes",
193 "layout.contentSize",
194 "layout.definitions",
195 "layout.wideSize",
196 "lightbox.enabled",
197 "lightbox.allowEditing",
198 "position.fixed",
199 "position.sticky",
200 "spacing.customSpacingSize",
201 "spacing.defaultSpacingSizes",
202 "spacing.spacingSizes",
203 "spacing.spacingScale",
204 "spacing.blockGap",
205 "spacing.margin",
206 "spacing.padding",
207 "spacing.units",
208 "typography.fluid",
209 "typography.customFontSize",
210 "typography.defaultFontSizes",
211 "typography.dropCap",
212 "typography.fontFamilies",
213 "typography.fontSizes",
214 "typography.fontStyle",
215 "typography.fontWeight",
216 "typography.letterSpacing",
217 "typography.lineHeight",
218 "typography.textAlign",
219 "typography.textColumns",
220 "typography.textDecoration",
221 "typography.textIndent",
222 "typography.textTransform",
223 "typography.writingMode"
224 ];
225 function getSetting(globalStyles, path, blockName) {
226 const appendedBlockPath = blockName ? ".blocks." + blockName : "";
227 const appendedPropertyPath = path ? "." + path : "";
228 const contextualPath = `settings${appendedBlockPath}${appendedPropertyPath}`;
229 const globalPath = `settings${appendedPropertyPath}`;
230 if (path) {
231 return getValueFromObjectPath(globalStyles, contextualPath) ?? getValueFromObjectPath(globalStyles, globalPath);
232 }
233 let result = {};
234 VALID_SETTINGS.forEach((setting) => {
235 const value = getValueFromObjectPath(
236 globalStyles,
237 `settings${appendedBlockPath}.${setting}`
238 ) ?? getValueFromObjectPath(globalStyles, `settings.${setting}`);
239 if (value !== void 0) {
240 result = setImmutably(result, setting.split("."), value);
241 }
242 });
243 return result;
244 }
245
246 // packages/global-styles-engine/build-module/utils/common.mjs
247 var import_style_engine = __toESM(require_style_engine(), 1);
248
249 // packages/global-styles-engine/build-module/utils/fluid.mjs
250 var DEFAULT_MAXIMUM_VIEWPORT_WIDTH = "1600px";
251 var DEFAULT_MINIMUM_VIEWPORT_WIDTH = "320px";
252 var DEFAULT_SCALE_FACTOR = 1;
253 var DEFAULT_MINIMUM_FONT_SIZE_FACTOR_MIN = 0.25;
254 var DEFAULT_MINIMUM_FONT_SIZE_FACTOR_MAX = 0.75;
255 var DEFAULT_MINIMUM_FONT_SIZE_LIMIT = "14px";
256 function getComputedFluidTypographyValue({
257 minimumFontSize,
258 maximumFontSize,
259 fontSize,
260 minimumViewportWidth = DEFAULT_MINIMUM_VIEWPORT_WIDTH,
261 maximumViewportWidth = DEFAULT_MAXIMUM_VIEWPORT_WIDTH,
262 scaleFactor = DEFAULT_SCALE_FACTOR,
263 minimumFontSizeLimit
264 }) {
265 minimumFontSizeLimit = !!getTypographyValueAndUnit(minimumFontSizeLimit) ? minimumFontSizeLimit : DEFAULT_MINIMUM_FONT_SIZE_LIMIT;
266 if (fontSize) {
267 const fontSizeParsed = getTypographyValueAndUnit(fontSize);
268 if (!fontSizeParsed?.unit || !fontSizeParsed?.value) {
269 return null;
270 }
271 const minimumFontSizeLimitParsed = getTypographyValueAndUnit(
272 minimumFontSizeLimit,
273 {
274 coerceTo: fontSizeParsed.unit
275 }
276 );
277 if (!!minimumFontSizeLimitParsed?.value && !minimumFontSize && !maximumFontSize) {
278 if (fontSizeParsed?.value <= minimumFontSizeLimitParsed?.value) {
279 return null;
280 }
281 }
282 if (!maximumFontSize) {
283 maximumFontSize = `${fontSizeParsed.value}${fontSizeParsed.unit}`;
284 }
285 if (!minimumFontSize) {
286 const fontSizeValueInPx = fontSizeParsed.unit === "px" ? fontSizeParsed.value : fontSizeParsed.value * 16;
287 const minimumFontSizeFactor = Math.min(
288 Math.max(
289 1 - 0.075 * Math.log2(fontSizeValueInPx),
290 DEFAULT_MINIMUM_FONT_SIZE_FACTOR_MIN
291 ),
292 DEFAULT_MINIMUM_FONT_SIZE_FACTOR_MAX
293 );
294 const calculatedMinimumFontSize = roundToPrecision(
295 fontSizeParsed.value * minimumFontSizeFactor,
296 3
297 );
298 if (!!minimumFontSizeLimitParsed?.value && calculatedMinimumFontSize < minimumFontSizeLimitParsed?.value) {
299 minimumFontSize = `${minimumFontSizeLimitParsed.value}${minimumFontSizeLimitParsed.unit}`;
300 } else {
301 minimumFontSize = `${calculatedMinimumFontSize}${fontSizeParsed.unit}`;
302 }
303 }
304 }
305 const minimumFontSizeParsed = getTypographyValueAndUnit(minimumFontSize);
306 const fontSizeUnit = minimumFontSizeParsed?.unit || "rem";
307 const maximumFontSizeParsed = getTypographyValueAndUnit(maximumFontSize, {
308 coerceTo: fontSizeUnit
309 });
310 if (!minimumFontSizeParsed || !maximumFontSizeParsed) {
311 return null;
312 }
313 const minimumFontSizeRem = getTypographyValueAndUnit(minimumFontSize, {
314 coerceTo: "rem"
315 });
316 const maximumViewportWidthParsed = getTypographyValueAndUnit(
317 maximumViewportWidth,
318 { coerceTo: fontSizeUnit }
319 );
320 const minimumViewportWidthParsed = getTypographyValueAndUnit(
321 minimumViewportWidth,
322 { coerceTo: fontSizeUnit }
323 );
324 if (!maximumViewportWidthParsed || !minimumViewportWidthParsed || !minimumFontSizeRem) {
325 return null;
326 }
327 const linearDenominator = maximumViewportWidthParsed.value - minimumViewportWidthParsed.value;
328 if (!linearDenominator) {
329 return null;
330 }
331 const minViewportWidthOffsetValue = roundToPrecision(
332 minimumViewportWidthParsed.value / 100,
333 3
334 );
335 const viewportWidthOffset = roundToPrecision(minViewportWidthOffsetValue, 3) + fontSizeUnit;
336 const linearFactor = 100 * ((maximumFontSizeParsed.value - minimumFontSizeParsed.value) / linearDenominator);
337 const linearFactorScaled = roundToPrecision(
338 (linearFactor || 1) * scaleFactor,
339 3
340 );
341 const fluidTargetFontSize = `${minimumFontSizeRem.value}${minimumFontSizeRem.unit} + ((1vw - ${viewportWidthOffset}) * ${linearFactorScaled})`;
342 return `clamp(${minimumFontSize}, ${fluidTargetFontSize}, ${maximumFontSize})`;
343 }
344 function getTypographyValueAndUnit(rawValue, options = {}) {
345 if (typeof rawValue !== "string" && typeof rawValue !== "number") {
346 return null;
347 }
348 if (isFinite(rawValue)) {
349 rawValue = `${rawValue}px`;
350 }
351 const { coerceTo, rootSizeValue, acceptableUnits } = {
352 coerceTo: "",
353 // Default browser font size. Later we could inject some JS to compute this `getComputedStyle( document.querySelector( "html" ) ).fontSize`.
354 rootSizeValue: 16,
355 acceptableUnits: ["rem", "px", "em"],
356 ...options
357 };
358 const acceptableUnitsGroup = acceptableUnits?.join("|");
359 const regexUnits = new RegExp(
360 `^(\\d*\\.?\\d+)(${acceptableUnitsGroup}){1,1}$`
361 );
362 const matches = rawValue.toString().match(regexUnits);
363 if (!matches || matches.length < 3) {
364 return null;
365 }
366 let [, value, unit] = matches;
367 let returnValue = parseFloat(value);
368 if ("px" === coerceTo && ("em" === unit || "rem" === unit)) {
369 returnValue = returnValue * rootSizeValue;
370 unit = coerceTo;
371 }
372 if ("px" === unit && ("em" === coerceTo || "rem" === coerceTo)) {
373 returnValue = returnValue / rootSizeValue;
374 unit = coerceTo;
375 }
376 if (("em" === coerceTo || "rem" === coerceTo) && ("em" === unit || "rem" === unit)) {
377 unit = coerceTo;
378 }
379 if (!unit) {
380 return null;
381 }
382 return {
383 value: roundToPrecision(returnValue, 3),
384 unit
385 };
386 }
387 function roundToPrecision(value, digits = 3) {
388 const base = Math.pow(10, digits);
389 return Math.round(value * base) / base;
390 }
391
392 // packages/global-styles-engine/build-module/utils/typography.mjs
393 function isFluidTypographyEnabled(typographySettings) {
394 const fluidSettings = typographySettings?.fluid;
395 return true === fluidSettings || fluidSettings && typeof fluidSettings === "object" && Object.keys(fluidSettings).length > 0;
396 }
397 function getFluidTypographyOptionsFromSettings(settings) {
398 const typographySettings = settings?.typography ?? {};
399 const layoutSettings = settings?.layout;
400 const defaultMaxViewportWidth = getTypographyValueAndUnit(
401 layoutSettings?.wideSize
402 ) ? layoutSettings?.wideSize : null;
403 return isFluidTypographyEnabled(typographySettings) && defaultMaxViewportWidth ? {
404 fluid: {
405 maxViewportWidth: defaultMaxViewportWidth,
406 ...typeof typographySettings.fluid === "object" ? typographySettings.fluid : {}
407 }
408 } : {
409 fluid: typographySettings?.fluid
410 };
411 }
412 function getTypographyFontSizeValue(preset, settings) {
413 const { size: defaultSize } = preset;
414 if (!defaultSize || "0" === defaultSize || false === preset?.fluid) {
415 return defaultSize;
416 }
417 if (!isFluidTypographyEnabled(settings?.typography) && !isFluidTypographyEnabled(preset)) {
418 return defaultSize;
419 }
420 const fluidTypographySettings = getFluidTypographyOptionsFromSettings(settings)?.fluid ?? {};
421 const fluidFontSizeValue = getComputedFluidTypographyValue({
422 minimumFontSize: typeof preset?.fluid === "boolean" ? void 0 : preset?.fluid?.min,
423 maximumFontSize: typeof preset?.fluid === "boolean" ? void 0 : preset?.fluid?.max,
424 fontSize: defaultSize,
425 minimumFontSizeLimit: typeof fluidTypographySettings === "object" ? fluidTypographySettings?.minFontSize : void 0,
426 maximumViewportWidth: typeof fluidTypographySettings === "object" ? fluidTypographySettings?.maxViewportWidth : void 0,
427 minimumViewportWidth: typeof fluidTypographySettings === "object" ? fluidTypographySettings?.minViewportWidth : void 0
428 });
429 if (!!fluidFontSizeValue) {
430 return fluidFontSizeValue;
431 }
432 return defaultSize;
433 }
434
435 // packages/global-styles-engine/build-module/utils/common.mjs
436 var ROOT_BLOCK_SELECTOR = "body";
437 var ROOT_CSS_PROPERTIES_SELECTOR = ":root";
438 function splitSelectorList(selector) {
439 if (!selector.includes(",")) {
440 return [selector];
441 }
442 const selectors = [];
443 let currentSelector = "";
444 let parenthesesDepth = 0;
445 for (const char of selector) {
446 if (char === "(") {
447 parenthesesDepth++;
448 } else if (char === ")" && parenthesesDepth > 0) {
449 parenthesesDepth--;
450 } else if (char === "," && parenthesesDepth === 0) {
451 selectors.push(currentSelector);
452 currentSelector = "";
453 continue;
454 }
455 currentSelector += char;
456 }
457 selectors.push(currentSelector);
458 return selectors;
459 }
460 var PRESET_METADATA = [
461 {
462 path: ["color", "palette"],
463 valueKey: "color",
464 cssVarInfix: "color",
465 classes: [
466 { classSuffix: "color", propertyName: "color" },
467 {
468 classSuffix: "background-color",
469 propertyName: "background-color"
470 },
471 {
472 classSuffix: "border-color",
473 propertyName: "border-color"
474 }
475 ]
476 },
477 {
478 path: ["color", "gradients"],
479 valueKey: "gradient",
480 cssVarInfix: "gradient",
481 classes: [
482 {
483 classSuffix: "gradient-background",
484 propertyName: "background"
485 }
486 ]
487 },
488 {
489 path: ["color", "duotone"],
490 valueKey: "colors",
491 cssVarInfix: "duotone",
492 valueFunc: ({ slug }) => `url( '#wp-duotone-${slug}' )`,
493 classes: []
494 },
495 {
496 path: ["shadow", "presets"],
497 valueKey: "shadow",
498 cssVarInfix: "shadow",
499 classes: []
500 },
501 {
502 path: ["typography", "fontSizes"],
503 valueFunc: (preset, settings) => getTypographyFontSizeValue(preset, settings),
504 valueKey: "size",
505 cssVarInfix: "font-size",
506 classes: [{ classSuffix: "font-size", propertyName: "font-size" }]
507 },
508 {
509 path: ["typography", "fontFamilies"],
510 valueKey: "fontFamily",
511 cssVarInfix: "font-family",
512 classes: [
513 { classSuffix: "font-family", propertyName: "font-family" }
514 ]
515 },
516 {
517 path: ["spacing", "spacingSizes"],
518 valueKey: "size",
519 cssVarInfix: "spacing",
520 valueFunc: ({ size }) => size,
521 classes: []
522 },
523 {
524 path: ["border", "radiusSizes"],
525 valueKey: "size",
526 cssVarInfix: "border-radius",
527 classes: []
528 },
529 {
530 path: ["dimensions", "dimensionSizes"],
531 valueKey: "size",
532 cssVarInfix: "dimension",
533 classes: []
534 }
535 ];
536 function scopeSelector(scope, selector) {
537 if (!scope || !selector) {
538 return selector;
539 }
540 const scopes = splitSelectorList(scope);
541 const selectors = splitSelectorList(selector);
542 const selectorsScoped = [];
543 scopes.forEach((outer) => {
544 selectors.forEach((inner) => {
545 selectorsScoped.push(`${outer.trim()} ${inner.trim()}`);
546 });
547 });
548 return selectorsScoped.join(", ");
549 }
550 function scopeFeatureSelectors(scope, selectors) {
551 if (!scope || !selectors) {
552 return;
553 }
554 const featureSelectors = {};
555 Object.entries(selectors).forEach(([feature, selector]) => {
556 if (typeof selector === "string") {
557 featureSelectors[feature] = scopeSelector(scope, selector);
558 }
559 if (typeof selector === "object") {
560 featureSelectors[feature] = {};
561 Object.entries(selector).forEach(
562 ([subfeature, subfeatureSelector]) => {
563 featureSelectors[feature][subfeature] = scopeSelector(
564 scope,
565 subfeatureSelector
566 );
567 }
568 );
569 }
570 });
571 return featureSelectors;
572 }
573 function appendToSelector(selector, toAppend) {
574 if (!selector.includes(",")) {
575 return selector + toAppend;
576 }
577 const selectors = splitSelectorList(selector);
578 const newSelectors = selectors.map((sel) => sel + toAppend);
579 return newSelectors.join(",");
580 }
581 function getBlockStyleVariationSelector(variation, blockSelector) {
582 const variationClass = `.is-style-${variation}`;
583 if (!blockSelector) {
584 return variationClass;
585 }
586 const ancestorRegex = /((?::\([^)]+\))?\s*)([^\s:]+)/;
587 const addVariationClass = (_match, group1, group2) => {
588 return group1 + group2 + variationClass;
589 };
590 const result = splitSelectorList(blockSelector).map(
591 (part) => part.replace(ancestorRegex, addVariationClass)
592 );
593 return result.join(",");
594 }
595 function getBlockStyleVariationFeatureSelector(variation, featureSelector) {
596 const variationClass = `.is-style-${variation}`;
597 const selectorParts = splitSelectorList(featureSelector).map(
598 (selector) => {
599 const trimmedSelector = selector.trim();
600 const prefix = `${variationClass} `;
601 if (trimmedSelector.startsWith(prefix)) {
602 return trimmedSelector.slice(prefix.length);
603 }
604 return trimmedSelector;
605 }
606 );
607 return getBlockStyleVariationSelector(
608 variation,
609 selectorParts.join(",")
610 );
611 }
612 function getResolvedRefValue(ruleValue, tree) {
613 if (!ruleValue || !tree) {
614 return ruleValue;
615 }
616 if (typeof ruleValue === "object" && "ref" in ruleValue && ruleValue?.ref) {
617 const resolvedRuleValue = (0, import_style_engine.getCSSValueFromRawStyle)(
618 getValueFromObjectPath(tree, ruleValue.ref)
619 );
620 if (typeof resolvedRuleValue === "object" && resolvedRuleValue !== null && "ref" in resolvedRuleValue && resolvedRuleValue?.ref) {
621 return void 0;
622 }
623 if (resolvedRuleValue === void 0) {
624 return ruleValue;
625 }
626 return resolvedRuleValue;
627 }
628 return ruleValue;
629 }
630 function getResolvedThemeFilePath(file, themeFileURIs) {
631 if (!file || !themeFileURIs || !Array.isArray(themeFileURIs)) {
632 return file;
633 }
634 const uri = themeFileURIs.find(
635 (themeFileUri) => themeFileUri?.name === file
636 );
637 if (!uri?.href) {
638 return file;
639 }
640 return uri?.href;
641 }
642 function getResolvedValue(ruleValue, tree) {
643 if (!ruleValue || !tree) {
644 return ruleValue;
645 }
646 const resolvedValue = getResolvedRefValue(ruleValue, tree);
647 if (typeof resolvedValue === "object" && resolvedValue !== null && "url" in resolvedValue && resolvedValue?.url) {
648 resolvedValue.url = getResolvedThemeFilePath(
649 resolvedValue.url,
650 tree?._links?.["wp:theme-file"]
651 );
652 }
653 return resolvedValue;
654 }
655
656 // packages/global-styles-engine/build-module/style-state-back-compat.mjs
657 var LEGACY_STYLE_STATE_ALIASES = {
658 "@mobile": "mobile",
659 "@tablet": "tablet",
660 "-current": "@current"
661 };
662 function isObjectRecord(value) {
663 return !!value && typeof value === "object" && !Array.isArray(value);
664 }
665 function normalizeStyleStateNode(node) {
666 if (!isObjectRecord(node)) {
667 return node;
668 }
669 let normalized = node;
670 Object.entries(LEGACY_STYLE_STATE_ALIASES).forEach(
671 ([state, legacyState]) => {
672 if (Object.hasOwn(node, legacyState)) {
673 if (normalized === node) {
674 normalized = { ...node };
675 }
676 if (!Object.hasOwn(node, state)) {
677 normalized[state] = node[legacyState];
678 }
679 delete normalized[legacyState];
680 }
681 }
682 );
683 Object.entries(normalized).forEach(([key, value]) => {
684 if (!isObjectRecord(value)) {
685 return;
686 }
687 const normalizedValue = normalizeStyleStateNode(value);
688 if (normalizedValue !== value) {
689 if (normalized === node) {
690 normalized = { ...node };
691 }
692 normalized[key] = normalizedValue;
693 }
694 });
695 return normalized;
696 }
697 function normalizeStyleStateAliases(globalStyles) {
698 if (false) {
699 return globalStyles;
700 }
701 if (!globalStyles?.styles) {
702 return globalStyles;
703 }
704 const styles = normalizeStyleStateNode(globalStyles.styles);
705 return styles === globalStyles.styles ? globalStyles : { ...globalStyles, styles };
706 }
707
708 // packages/global-styles-engine/build-module/core/render.mjs
709 var import_blocks = __toESM(require_blocks(), 1);
710 var import_style_engine2 = __toESM(require_style_engine(), 1);
711 var import_data2 = __toESM(require_data(), 1);
712
713 // packages/global-styles-engine/build-module/core/selectors.mjs
714 function getBlockSelector(blockType, target = "root", options = {}) {
715 if (!target) {
716 return null;
717 }
718 const { fallback = false } = options;
719 const { name, selectors, supports } = blockType;
720 const hasSelectors = selectors && Object.keys(selectors).length > 0;
721 const path = Array.isArray(target) ? target.join(".") : target;
722 let rootSelector = null;
723 if (hasSelectors && selectors.root) {
724 rootSelector = selectors?.root;
725 } else if (supports?.__experimentalSelector) {
726 rootSelector = supports.__experimentalSelector;
727 } else {
728 rootSelector = ".wp-block-" + name.replace("core/", "").replace("/", "-");
729 }
730 if (path === "root") {
731 return rootSelector;
732 }
733 const pathArray = Array.isArray(target) ? target : target.split(".");
734 if (pathArray.length === 1) {
735 const fallbackSelector = fallback ? rootSelector : null;
736 if (hasSelectors) {
737 const featureSelector2 = getValueFromObjectPath(
738 selectors,
739 `${path}.root`,
740 null
741 ) || getValueFromObjectPath(selectors, path, null);
742 return featureSelector2 || fallbackSelector;
743 }
744 const featureSelector = supports ? getValueFromObjectPath(
745 supports,
746 `${path}.__experimentalSelector`,
747 null
748 ) : void 0;
749 if (!featureSelector) {
750 return fallbackSelector;
751 }
752 return scopeSelector(rootSelector, featureSelector);
753 }
754 let subfeatureSelector;
755 if (hasSelectors) {
756 subfeatureSelector = getValueFromObjectPath(selectors, path, null);
757 }
758 if (subfeatureSelector) {
759 return subfeatureSelector;
760 }
761 if (fallback) {
762 return getBlockSelector(blockType, pathArray[0], options);
763 }
764 return null;
765 }
766
767 // node_modules/colord/index.mjs
768 var r = { grad: 0.9, turn: 360, rad: 360 / (2 * Math.PI) };
769 var t = function(r2) {
770 return "string" == typeof r2 ? r2.length > 0 : "number" == typeof r2;
771 };
772 var n = function(r2, t2, n2) {
773 return void 0 === t2 && (t2 = 0), void 0 === n2 && (n2 = Math.pow(10, t2)), Math.round(n2 * r2) / n2 + 0;
774 };
775 var e = function(r2, t2, n2) {
776 return void 0 === t2 && (t2 = 0), void 0 === n2 && (n2 = 1), r2 > n2 ? n2 : r2 > t2 ? r2 : t2;
777 };
778 var u = function(r2) {
779 return (r2 = isFinite(r2) ? r2 % 360 : 0) > 0 ? r2 : r2 + 360;
780 };
781 var a = function(r2) {
782 return { r: e(r2.r, 0, 255), g: e(r2.g, 0, 255), b: e(r2.b, 0, 255), a: e(r2.a) };
783 };
784 var o = function(r2) {
785 return { r: n(r2.r), g: n(r2.g), b: n(r2.b), a: n(r2.a, 3) };
786 };
787 var i = /^#([0-9a-f]{3,8})$/i;
788 var s = function(r2) {
789 var t2 = r2.toString(16);
790 return t2.length < 2 ? "0" + t2 : t2;
791 };
792 var h = function(r2) {
793 var t2 = r2.r, n2 = r2.g, e2 = r2.b, u2 = r2.a, a2 = Math.max(t2, n2, e2), o2 = a2 - Math.min(t2, n2, e2), i2 = o2 ? a2 === t2 ? (n2 - e2) / o2 : a2 === n2 ? 2 + (e2 - t2) / o2 : 4 + (t2 - n2) / o2 : 0;
794 return { h: 60 * (i2 < 0 ? i2 + 6 : i2), s: a2 ? o2 / a2 * 100 : 0, v: a2 / 255 * 100, a: u2 };
795 };
796 var b = function(r2) {
797 var t2 = r2.h, n2 = r2.s, e2 = r2.v, u2 = r2.a;
798 t2 = t2 / 360 * 6, n2 /= 100, e2 /= 100;
799 var a2 = Math.floor(t2), o2 = e2 * (1 - n2), i2 = e2 * (1 - (t2 - a2) * n2), s2 = e2 * (1 - (1 - t2 + a2) * n2), h2 = a2 % 6;
800 return { r: 255 * [e2, i2, o2, o2, s2, e2][h2], g: 255 * [s2, e2, e2, i2, o2, o2][h2], b: 255 * [o2, o2, s2, e2, e2, i2][h2], a: u2 };
801 };
802 var g = function(r2) {
803 return { h: u(r2.h), s: e(r2.s, 0, 100), l: e(r2.l, 0, 100), a: e(r2.a) };
804 };
805 var d = function(r2) {
806 return { h: n(r2.h), s: n(r2.s), l: n(r2.l), a: n(r2.a, 3) };
807 };
808 var f = function(r2) {
809 return b((n2 = (t2 = r2).s, { h: t2.h, s: (n2 *= ((e2 = t2.l) < 50 ? e2 : 100 - e2) / 100) > 0 ? 2 * n2 / (e2 + n2) * 100 : 0, v: e2 + n2, a: t2.a }));
810 var t2, n2, e2;
811 };
812 var c = function(r2) {
813 return { h: (t2 = h(r2)).h, s: (u2 = (200 - (n2 = t2.s)) * (e2 = t2.v) / 100) > 0 && u2 < 200 ? n2 * e2 / 100 / (u2 <= 100 ? u2 : 200 - u2) * 100 : 0, l: u2 / 2, a: t2.a };
814 var t2, n2, e2, u2;
815 };
816 var l = /^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i;
817 var p = /^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i;
818 var v = /^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i;
819 var m = /^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i;
820 var y = { string: [[function(r2) {
821 var t2 = i.exec(r2);
822 return t2 ? (r2 = t2[1]).length <= 4 ? { r: parseInt(r2[0] + r2[0], 16), g: parseInt(r2[1] + r2[1], 16), b: parseInt(r2[2] + r2[2], 16), a: 4 === r2.length ? n(parseInt(r2[3] + r2[3], 16) / 255, 2) : 1 } : 6 === r2.length || 8 === r2.length ? { r: parseInt(r2.substr(0, 2), 16), g: parseInt(r2.substr(2, 2), 16), b: parseInt(r2.substr(4, 2), 16), a: 8 === r2.length ? n(parseInt(r2.substr(6, 2), 16) / 255, 2) : 1 } : null : null;
823 }, "hex"], [function(r2) {
824 var t2 = v.exec(r2) || m.exec(r2);
825 return t2 ? t2[2] !== t2[4] || t2[4] !== t2[6] ? null : a({ r: Number(t2[1]) / (t2[2] ? 100 / 255 : 1), g: Number(t2[3]) / (t2[4] ? 100 / 255 : 1), b: Number(t2[5]) / (t2[6] ? 100 / 255 : 1), a: void 0 === t2[7] ? 1 : Number(t2[7]) / (t2[8] ? 100 : 1) }) : null;
826 }, "rgb"], [function(t2) {
827 var n2 = l.exec(t2) || p.exec(t2);
828 if (!n2) return null;
829 var e2, u2, a2 = g({ h: (e2 = n2[1], u2 = n2[2], void 0 === u2 && (u2 = "deg"), Number(e2) * (r[u2] || 1)), s: Number(n2[3]), l: Number(n2[4]), a: void 0 === n2[5] ? 1 : Number(n2[5]) / (n2[6] ? 100 : 1) });
830 return f(a2);
831 }, "hsl"]], object: [[function(r2) {
832 var n2 = r2.r, e2 = r2.g, u2 = r2.b, o2 = r2.a, i2 = void 0 === o2 ? 1 : o2;
833 return t(n2) && t(e2) && t(u2) ? a({ r: Number(n2), g: Number(e2), b: Number(u2), a: Number(i2) }) : null;
834 }, "rgb"], [function(r2) {
835 var n2 = r2.h, e2 = r2.s, u2 = r2.l, a2 = r2.a, o2 = void 0 === a2 ? 1 : a2;
836 if (!t(n2) || !t(e2) || !t(u2)) return null;
837 var i2 = g({ h: Number(n2), s: Number(e2), l: Number(u2), a: Number(o2) });
838 return f(i2);
839 }, "hsl"], [function(r2) {
840 var n2 = r2.h, a2 = r2.s, o2 = r2.v, i2 = r2.a, s2 = void 0 === i2 ? 1 : i2;
841 if (!t(n2) || !t(a2) || !t(o2)) return null;
842 var h2 = (function(r3) {
843 return { h: u(r3.h), s: e(r3.s, 0, 100), v: e(r3.v, 0, 100), a: e(r3.a) };
844 })({ h: Number(n2), s: Number(a2), v: Number(o2), a: Number(s2) });
845 return b(h2);
846 }, "hsv"]] };
847 var N = function(r2, t2) {
848 for (var n2 = 0; n2 < t2.length; n2++) {
849 var e2 = t2[n2][0](r2);
850 if (e2) return [e2, t2[n2][1]];
851 }
852 return [null, void 0];
853 };
854 var x = function(r2) {
855 return "string" == typeof r2 ? N(r2.trim(), y.string) : "object" == typeof r2 && null !== r2 ? N(r2, y.object) : [null, void 0];
856 };
857 var M = function(r2, t2) {
858 var n2 = c(r2);
859 return { h: n2.h, s: e(n2.s + 100 * t2, 0, 100), l: n2.l, a: n2.a };
860 };
861 var H = function(r2) {
862 return (299 * r2.r + 587 * r2.g + 114 * r2.b) / 1e3 / 255;
863 };
864 var $ = function(r2, t2) {
865 var n2 = c(r2);
866 return { h: n2.h, s: n2.s, l: e(n2.l + 100 * t2, 0, 100), a: n2.a };
867 };
868 var j = (function() {
869 function r2(r3) {
870 this.parsed = x(r3)[0], this.rgba = this.parsed || { r: 0, g: 0, b: 0, a: 1 };
871 }
872 return r2.prototype.isValid = function() {
873 return null !== this.parsed;
874 }, r2.prototype.brightness = function() {
875 return n(H(this.rgba), 2);
876 }, r2.prototype.isDark = function() {
877 return H(this.rgba) < 0.5;
878 }, r2.prototype.isLight = function() {
879 return H(this.rgba) >= 0.5;
880 }, r2.prototype.toHex = function() {
881 return r3 = o(this.rgba), t2 = r3.r, e2 = r3.g, u2 = r3.b, i2 = (a2 = r3.a) < 1 ? s(n(255 * a2)) : "", "#" + s(t2) + s(e2) + s(u2) + i2;
882 var r3, t2, e2, u2, a2, i2;
883 }, r2.prototype.toRgb = function() {
884 return o(this.rgba);
885 }, r2.prototype.toRgbString = function() {
886 return r3 = o(this.rgba), t2 = r3.r, n2 = r3.g, e2 = r3.b, (u2 = r3.a) < 1 ? "rgba(" + t2 + ", " + n2 + ", " + e2 + ", " + u2 + ")" : "rgb(" + t2 + ", " + n2 + ", " + e2 + ")";
887 var r3, t2, n2, e2, u2;
888 }, r2.prototype.toHsl = function() {
889 return d(c(this.rgba));
890 }, r2.prototype.toHslString = function() {
891 return r3 = d(c(this.rgba)), t2 = r3.h, n2 = r3.s, e2 = r3.l, (u2 = r3.a) < 1 ? "hsla(" + t2 + ", " + n2 + "%, " + e2 + "%, " + u2 + ")" : "hsl(" + t2 + ", " + n2 + "%, " + e2 + "%)";
892 var r3, t2, n2, e2, u2;
893 }, r2.prototype.toHsv = function() {
894 return r3 = h(this.rgba), { h: n(r3.h), s: n(r3.s), v: n(r3.v), a: n(r3.a, 3) };
895 var r3;
896 }, r2.prototype.invert = function() {
897 return w({ r: 255 - (r3 = this.rgba).r, g: 255 - r3.g, b: 255 - r3.b, a: r3.a });
898 var r3;
899 }, r2.prototype.saturate = function(r3) {
900 return void 0 === r3 && (r3 = 0.1), w(M(this.rgba, r3));
901 }, r2.prototype.desaturate = function(r3) {
902 return void 0 === r3 && (r3 = 0.1), w(M(this.rgba, -r3));
903 }, r2.prototype.grayscale = function() {
904 return w(M(this.rgba, -1));
905 }, r2.prototype.lighten = function(r3) {
906 return void 0 === r3 && (r3 = 0.1), w($(this.rgba, r3));
907 }, r2.prototype.darken = function(r3) {
908 return void 0 === r3 && (r3 = 0.1), w($(this.rgba, -r3));
909 }, r2.prototype.rotate = function(r3) {
910 return void 0 === r3 && (r3 = 15), this.hue(this.hue() + r3);
911 }, r2.prototype.alpha = function(r3) {
912 return "number" == typeof r3 ? w({ r: (t2 = this.rgba).r, g: t2.g, b: t2.b, a: r3 }) : n(this.rgba.a, 3);
913 var t2;
914 }, r2.prototype.hue = function(r3) {
915 var t2 = c(this.rgba);
916 return "number" == typeof r3 ? w({ h: r3, s: t2.s, l: t2.l, a: t2.a }) : n(t2.h);
917 }, r2.prototype.isEqual = function(r3) {
918 return this.toHex() === w(r3).toHex();
919 }, r2;
920 })();
921 var w = function(r2) {
922 return r2 instanceof j ? r2 : new j(r2);
923 };
924
925 // packages/global-styles-engine/build-module/utils/duotone.mjs
926 function getValuesFromColors(colors = []) {
927 const values = {
928 r: [],
929 g: [],
930 b: [],
931 a: []
932 };
933 colors.forEach((color) => {
934 const rgbColor = w(color).toRgb();
935 values.r.push(rgbColor.r / 255);
936 values.g.push(rgbColor.g / 255);
937 values.b.push(rgbColor.b / 255);
938 values.a.push(rgbColor.a);
939 });
940 return values;
941 }
942 function getDuotoneFilter(id, colors) {
943 const values = getValuesFromColors(colors);
944 return `
945 <svg
946 xmlns:xlink="http://www.w3.org/1999/xlink"
947 viewBox="0 0 0 0"
948 width="0"
949 height="0"
950 focusable="false"
951 role="none"
952 aria-hidden="true"
953 style="visibility: hidden; position: absolute; left: -9999px; overflow: hidden;"
954 >
955 <defs>
956 <filter id="${id}">
957 <!--
958 Use sRGB instead of linearRGB so transparency looks correct.
959 Use perceptual brightness to convert to grayscale.
960 -->
961 <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>
962 <!-- Use sRGB instead of linearRGB to be consistent with how CSS gradients work. -->
963 <feComponentTransfer color-interpolation-filters="sRGB">
964 <feFuncR type="table" tableValues="${values.r.join(" ")}"></feFuncR>
965 <feFuncG type="table" tableValues="${values.g.join(" ")}"></feFuncG>
966 <feFuncB type="table" tableValues="${values.b.join(" ")}"></feFuncB>
967 <feFuncA type="table" tableValues="${values.a.join(" ")}"></feFuncA>
968 </feComponentTransfer>
969 <!-- Re-mask the image with the original transparency since the feColorMatrix above loses that information. -->
970 <feComposite in2="SourceGraphic" operator="in"></feComposite>
971 </filter>
972 </defs>
973 </svg>`;
974 }
975
976 // packages/global-styles-engine/build-module/utils/string.mjs
977 function kebabCase(str) {
978 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();
979 }
980
981 // packages/global-styles-engine/build-module/utils/spacing.mjs
982 function getSpacingPresetCssVar(value) {
983 if (!value) {
984 return;
985 }
986 const slug = value.match(/var:preset\|spacing\|(.+)/);
987 if (!slug) {
988 return value;
989 }
990 return `var(--wp--preset--spacing--${slug[1]})`;
991 }
992
993 // packages/global-styles-engine/build-module/utils/gap.mjs
994 function getGapBoxControlValueFromStyle(blockGapValue) {
995 if (!blockGapValue) {
996 return null;
997 }
998 const isValueString = typeof blockGapValue === "string";
999 return {
1000 top: isValueString ? blockGapValue : blockGapValue?.top,
1001 left: isValueString ? blockGapValue : blockGapValue?.left
1002 };
1003 }
1004 function getGapCSSValue(blockGapValue, defaultValue = "0") {
1005 const blockGapBoxControlValue = getGapBoxControlValueFromStyle(blockGapValue);
1006 if (!blockGapBoxControlValue) {
1007 return null;
1008 }
1009 const row = getSpacingPresetCssVar(blockGapBoxControlValue?.top) || defaultValue;
1010 const column = getSpacingPresetCssVar(blockGapBoxControlValue?.left) || defaultValue;
1011 return row === column ? row : `${row} ${column}`;
1012 }
1013
1014 // packages/global-styles-engine/build-module/utils/background.mjs
1015 var BACKGROUND_BLOCK_DEFAULT_VALUES = {
1016 backgroundSize: "cover",
1017 backgroundPosition: "50% 50%"
1018 // used only when backgroundSize is 'contain'.
1019 };
1020 function setBackgroundStyleDefaults(backgroundStyle) {
1021 if (!backgroundStyle || // @ts-expect-error
1022 !backgroundStyle?.backgroundImage?.url) {
1023 return;
1024 }
1025 let backgroundStylesWithDefaults;
1026 if (!backgroundStyle?.backgroundSize) {
1027 backgroundStylesWithDefaults = {
1028 backgroundSize: BACKGROUND_BLOCK_DEFAULT_VALUES.backgroundSize
1029 };
1030 }
1031 if ("contain" === backgroundStyle?.backgroundSize && !backgroundStyle?.backgroundPosition) {
1032 backgroundStylesWithDefaults = {
1033 backgroundPosition: BACKGROUND_BLOCK_DEFAULT_VALUES.backgroundPosition
1034 };
1035 }
1036 return backgroundStylesWithDefaults;
1037 }
1038
1039 // packages/global-styles-engine/build-module/utils/layout.mjs
1040 var LAYOUT_DEFINITIONS = {
1041 default: {
1042 name: "default",
1043 slug: "flow",
1044 className: "is-layout-flow",
1045 baseStyles: [
1046 {
1047 selector: " > .alignleft",
1048 rules: {
1049 float: "left",
1050 "margin-inline-start": "0",
1051 "margin-inline-end": "2em"
1052 }
1053 },
1054 {
1055 selector: " > .alignright",
1056 rules: {
1057 float: "right",
1058 "margin-inline-start": "2em",
1059 "margin-inline-end": "0"
1060 }
1061 },
1062 {
1063 selector: " > .aligncenter",
1064 rules: {
1065 "margin-left": "auto !important",
1066 "margin-right": "auto !important"
1067 }
1068 }
1069 ],
1070 spacingStyles: [
1071 {
1072 selector: " > :first-child",
1073 rules: {
1074 "margin-block-start": "0"
1075 }
1076 },
1077 {
1078 selector: " > :last-child",
1079 rules: {
1080 "margin-block-end": "0"
1081 }
1082 },
1083 {
1084 selector: " > *",
1085 rules: {
1086 "margin-block-start": null,
1087 "margin-block-end": "0"
1088 }
1089 }
1090 ]
1091 },
1092 constrained: {
1093 name: "constrained",
1094 slug: "constrained",
1095 className: "is-layout-constrained",
1096 baseStyles: [
1097 {
1098 selector: " > .alignleft",
1099 rules: {
1100 float: "left",
1101 "margin-inline-start": "0",
1102 "margin-inline-end": "2em"
1103 }
1104 },
1105 {
1106 selector: " > .alignright",
1107 rules: {
1108 float: "right",
1109 "margin-inline-start": "2em",
1110 "margin-inline-end": "0"
1111 }
1112 },
1113 {
1114 selector: " > .aligncenter",
1115 rules: {
1116 "margin-left": "auto !important",
1117 "margin-right": "auto !important"
1118 }
1119 },
1120 {
1121 selector: " > :where(:not(.alignleft):not(.alignright):not(.alignfull))",
1122 rules: {
1123 "max-width": "var(--wp--style--global--content-size)",
1124 "margin-left": "auto !important",
1125 "margin-right": "auto !important"
1126 }
1127 },
1128 {
1129 selector: " > .alignwide",
1130 rules: {
1131 "max-width": "var(--wp--style--global--wide-size)"
1132 }
1133 }
1134 ],
1135 spacingStyles: [
1136 {
1137 selector: " > :first-child",
1138 rules: {
1139 "margin-block-start": "0"
1140 }
1141 },
1142 {
1143 selector: " > :last-child",
1144 rules: {
1145 "margin-block-end": "0"
1146 }
1147 },
1148 {
1149 selector: " > *",
1150 rules: {
1151 "margin-block-start": null,
1152 "margin-block-end": "0"
1153 }
1154 }
1155 ]
1156 },
1157 flex: {
1158 name: "flex",
1159 slug: "flex",
1160 className: "is-layout-flex",
1161 displayMode: "flex",
1162 baseStyles: [
1163 {
1164 selector: "",
1165 rules: {
1166 "flex-wrap": "wrap",
1167 "align-items": "center"
1168 }
1169 },
1170 {
1171 selector: " > :is(*, div)",
1172 // :is(*, div) instead of just * increases the specificity by 001.
1173 rules: {
1174 margin: "0"
1175 }
1176 }
1177 ],
1178 spacingStyles: [
1179 {
1180 selector: "",
1181 rules: {
1182 gap: null
1183 }
1184 }
1185 ]
1186 },
1187 grid: {
1188 name: "grid",
1189 slug: "grid",
1190 className: "is-layout-grid",
1191 displayMode: "grid",
1192 baseStyles: [
1193 {
1194 selector: " > :is(*, div)",
1195 // :is(*, div) instead of just * increases the specificity by 001.
1196 rules: {
1197 margin: "0"
1198 }
1199 }
1200 ],
1201 spacingStyles: [
1202 {
1203 selector: "",
1204 rules: {
1205 gap: null
1206 }
1207 }
1208 ]
1209 }
1210 };
1211
1212 // packages/global-styles-engine/build-module/core/render.mjs
1213 var ELEMENT_CLASS_NAMES = {
1214 button: "wp-element-button",
1215 caption: "wp-element-caption"
1216 };
1217 var BLOCK_SUPPORT_FEATURE_LEVEL_SELECTORS = {
1218 __experimentalBorder: "border",
1219 color: "color",
1220 dimensions: "dimensions",
1221 spacing: "spacing",
1222 typography: "typography"
1223 };
1224 var VALID_BLOCK_PSEUDO_SELECTORS = {
1225 "core/button": [":hover", ":focus", ":focus-visible", ":active"],
1226 "core/navigation-link": [":hover", ":focus", ":focus-visible", ":active"]
1227 };
1228 var VALID_ELEMENT_PSEUDO_SELECTORS = {
1229 link: [
1230 ":link",
1231 ":any-link",
1232 ":visited",
1233 ":hover",
1234 ":focus",
1235 ":focus-visible",
1236 ":active"
1237 ],
1238 button: [
1239 ":link",
1240 ":any-link",
1241 ":visited",
1242 ":hover",
1243 ":focus",
1244 ":focus-visible",
1245 ":active"
1246 ]
1247 };
1248 var RESPONSIVE_BREAKPOINTS = {
1249 "@mobile": "@media (width <= 480px)",
1250 "@tablet": "@media (480px < width <= 782px)"
1251 };
1252 function getPresetsClasses(blockSelector = "*", blockPresets = {}) {
1253 return PRESET_METADATA.reduce(
1254 (declarations, { path, cssVarInfix, classes }) => {
1255 if (!classes) {
1256 return declarations;
1257 }
1258 const presetByOrigin = getValueFromObjectPath(
1259 blockPresets,
1260 path,
1261 []
1262 );
1263 ["default", "theme", "custom"].forEach((origin) => {
1264 if (presetByOrigin[origin]) {
1265 presetByOrigin[origin].forEach(
1266 ({ slug }) => {
1267 classes.forEach(
1268 ({
1269 classSuffix,
1270 propertyName
1271 }) => {
1272 const classSelectorToUse = `.has-${kebabCase(
1273 slug
1274 )}-${classSuffix}`;
1275 const selectorToUse = blockSelector.split(",").map(
1276 (selector) => `${selector}${classSelectorToUse}`
1277 ).join(",");
1278 const value = `var(--wp--preset--${cssVarInfix}--${kebabCase(
1279 slug
1280 )})`;
1281 declarations += `${selectorToUse}{${propertyName}: ${value} !important;}`;
1282 }
1283 );
1284 }
1285 );
1286 }
1287 });
1288 return declarations;
1289 },
1290 ""
1291 );
1292 }
1293 function getPresetsSvgFilters(blockPresets = {}) {
1294 return PRESET_METADATA.filter(
1295 // Duotone are the only type of filters for now.
1296 (metadata) => metadata.path.at(-1) === "duotone"
1297 ).flatMap((metadata) => {
1298 const presetByOrigin = getValueFromObjectPath(
1299 blockPresets,
1300 metadata.path,
1301 {}
1302 );
1303 return ["default", "theme"].filter((origin) => presetByOrigin[origin]).flatMap(
1304 (origin) => presetByOrigin[origin].map(
1305 (preset) => getDuotoneFilter(
1306 `wp-duotone-${preset.slug}`,
1307 preset.colors
1308 )
1309 )
1310 ).join("");
1311 });
1312 }
1313 function flattenTree(input = {}, prefix, token) {
1314 let result = [];
1315 Object.keys(input).forEach((key) => {
1316 const newKey = prefix + kebabCase(key.replace("/", "-"));
1317 const newLeaf = input[key];
1318 if (newLeaf instanceof Object) {
1319 const newPrefix = newKey + token;
1320 result = [...result, ...flattenTree(newLeaf, newPrefix, token)];
1321 } else {
1322 result.push(`${newKey}: ${newLeaf}`);
1323 }
1324 });
1325 return result;
1326 }
1327 var updateParagraphTextIndentSelector = (featureDeclarations, settings, blockName) => {
1328 if (blockName !== "core/paragraph") {
1329 return featureDeclarations;
1330 }
1331 const blockSettings = settings?.blocks?.["core/paragraph"];
1332 const textIndentSetting = blockSettings?.typography?.textIndent ?? settings?.typography?.textIndent ?? "subsequent";
1333 if (textIndentSetting !== "all") {
1334 return featureDeclarations;
1335 }
1336 const oldSelector = ".wp-block-paragraph + .wp-block-paragraph";
1337 const newSelector = ".wp-block-paragraph";
1338 if (oldSelector in featureDeclarations) {
1339 const declarations = featureDeclarations[oldSelector];
1340 const updated = { ...featureDeclarations };
1341 delete updated[oldSelector];
1342 updated[newSelector] = declarations;
1343 return updated;
1344 }
1345 return featureDeclarations;
1346 };
1347 var updateButtonWidthDeclarations = (featureDeclarations, settings) => {
1348 const buttonSelector = ".wp-block-button";
1349 if (!(buttonSelector in featureDeclarations)) {
1350 return featureDeclarations;
1351 }
1352 const updated = { ...featureDeclarations };
1353 updated[buttonSelector] = updated[buttonSelector].map(
1354 (declaration) => {
1355 const match = declaration.match(/^width:\s*(.+)$/);
1356 if (!match) {
1357 return declaration;
1358 }
1359 const value = match[1];
1360 let percentage = null;
1361 if (value.endsWith("%")) {
1362 percentage = parseFloat(value);
1363 }
1364 const presetPrefix = "var(--wp--preset--dimension--";
1365 if (percentage === null && value.startsWith(presetPrefix) && value.endsWith(")")) {
1366 const slug = value.slice(presetPrefix.length, -1);
1367 const dimensionSizes = {
1368 ...settings?.dimensions?.dimensionSizes ?? {},
1369 ...settings?.blocks?.["core/button"]?.dimensions?.dimensionSizes ?? {}
1370 };
1371 for (const origin of Object.values(dimensionSizes)) {
1372 if (!Array.isArray(origin)) {
1373 continue;
1374 }
1375 for (const preset of origin) {
1376 if (preset.slug === slug && typeof preset.size === "string" && preset.size.endsWith("%")) {
1377 percentage = parseFloat(preset.size);
1378 break;
1379 }
1380 }
1381 if (percentage !== null) {
1382 break;
1383 }
1384 }
1385 }
1386 if (percentage === null || isNaN(percentage)) {
1387 return declaration;
1388 }
1389 return `width: calc(${percentage} * 1% - (var(--wp--style--block-gap, 0.5em) * (1 - ${percentage} / 100)))`;
1390 }
1391 );
1392 return updated;
1393 };
1394 var getFeatureDeclarations = (selectors, styles) => {
1395 const declarations = {};
1396 Object.entries(selectors).forEach(([feature, selector]) => {
1397 if (feature === "root" || !styles?.[feature]) {
1398 return;
1399 }
1400 const isShorthand = typeof selector === "string";
1401 if (!isShorthand && typeof selector === "object" && selector !== null) {
1402 Object.entries(selector).forEach(
1403 ([subfeature, subfeatureSelector]) => {
1404 if (subfeature === "root" || !styles?.[feature][subfeature]) {
1405 return;
1406 }
1407 const subfeatureStyles = {
1408 [feature]: {
1409 [subfeature]: styles[feature][subfeature]
1410 }
1411 };
1412 const newDeclarations = getStylesDeclarations(subfeatureStyles);
1413 declarations[subfeatureSelector] = [
1414 ...declarations[subfeatureSelector] || [],
1415 ...newDeclarations
1416 ];
1417 delete styles[feature][subfeature];
1418 }
1419 );
1420 }
1421 if (isShorthand || typeof selector === "object" && selector !== null && "root" in selector) {
1422 const featureSelector = isShorthand ? selector : selector.root;
1423 const featureStyles = { [feature]: styles[feature] };
1424 const newDeclarations = getStylesDeclarations(featureStyles);
1425 declarations[featureSelector] = [
1426 ...declarations[featureSelector] || [],
1427 ...newDeclarations
1428 ];
1429 delete styles[feature];
1430 }
1431 });
1432 return declarations;
1433 };
1434 function getStylesDeclarations(blockStyles = {}, selector = "", useRootPaddingAlign, tree = {}, disableRootPadding = false) {
1435 const isRoot = ROOT_BLOCK_SELECTOR === selector;
1436 const output = Object.entries(
1437 import_blocks.__EXPERIMENTAL_STYLE_PROPERTY
1438 ).reduce(
1439 (declarations, [key, { value, properties, useEngine, rootOnly }]) => {
1440 if (rootOnly && !isRoot) {
1441 return declarations;
1442 }
1443 const pathToValue = value;
1444 if (pathToValue[0] === "elements" || useEngine) {
1445 return declarations;
1446 }
1447 const styleValue = getValueFromObjectPath(
1448 blockStyles,
1449 pathToValue
1450 );
1451 if (key === "--wp--style--root--padding" && (typeof styleValue === "string" || !useRootPaddingAlign)) {
1452 return declarations;
1453 }
1454 if (properties && typeof styleValue !== "string") {
1455 Object.entries(properties).forEach((entry) => {
1456 const [name, prop] = entry;
1457 if (!getValueFromObjectPath(styleValue, [prop], false)) {
1458 return;
1459 }
1460 const cssProperty = name.startsWith("--") ? name : kebabCase(name);
1461 declarations.push(
1462 `${cssProperty}: ${(0, import_style_engine2.getCSSValueFromRawStyle)(
1463 getValueFromObjectPath(styleValue, [prop])
1464 )}`
1465 );
1466 });
1467 } else if (getValueFromObjectPath(blockStyles, pathToValue, false)) {
1468 const cssProperty = key.startsWith("--") ? key : kebabCase(key);
1469 declarations.push(
1470 `${cssProperty}: ${(0, import_style_engine2.getCSSValueFromRawStyle)(
1471 getValueFromObjectPath(blockStyles, pathToValue)
1472 )}`
1473 );
1474 }
1475 return declarations;
1476 },
1477 []
1478 );
1479 if (!!blockStyles.background) {
1480 if (blockStyles.background?.backgroundImage) {
1481 blockStyles.background.backgroundImage = getResolvedValue(
1482 blockStyles.background.backgroundImage,
1483 tree
1484 );
1485 }
1486 if (!isRoot && !!blockStyles.background?.backgroundImage?.id) {
1487 blockStyles = {
1488 ...blockStyles,
1489 background: {
1490 ...blockStyles.background,
1491 ...setBackgroundStyleDefaults(blockStyles.background)
1492 }
1493 };
1494 }
1495 }
1496 const extraRules = (0, import_style_engine2.getCSSRules)(blockStyles);
1497 extraRules.forEach((rule) => {
1498 if (isRoot && (useRootPaddingAlign || disableRootPadding) && rule.key.startsWith("padding")) {
1499 return;
1500 }
1501 const cssProperty = rule.key.startsWith("--") ? rule.key : kebabCase(rule.key);
1502 let ruleValue = getResolvedValue(rule.value, tree);
1503 if (cssProperty === "font-size") {
1504 ruleValue = getTypographyFontSizeValue(
1505 { name: "", slug: "", size: ruleValue },
1506 tree?.settings
1507 );
1508 }
1509 if (cssProperty === "aspect-ratio") {
1510 output.push("min-height: unset");
1511 }
1512 output.push(`${cssProperty}: ${ruleValue}`);
1513 });
1514 return output;
1515 }
1516 function getLayoutStyles({
1517 layoutDefinitions = LAYOUT_DEFINITIONS,
1518 style,
1519 selector,
1520 hasBlockGapSupport,
1521 hasFallbackGapSupport,
1522 fallbackGapValue
1523 }) {
1524 let ruleset = "";
1525 let gapValue = hasBlockGapSupport ? getGapCSSValue(style?.spacing?.blockGap) : "";
1526 if (hasFallbackGapSupport) {
1527 if (selector === ROOT_BLOCK_SELECTOR) {
1528 gapValue = !gapValue ? "0.5em" : gapValue;
1529 } else if (!hasBlockGapSupport && fallbackGapValue) {
1530 gapValue = fallbackGapValue;
1531 }
1532 }
1533 if (gapValue && layoutDefinitions) {
1534 Object.values(layoutDefinitions).forEach(
1535 ({ className, name, spacingStyles }) => {
1536 if (!hasBlockGapSupport && "flex" !== name && "grid" !== name) {
1537 return;
1538 }
1539 if (spacingStyles?.length) {
1540 spacingStyles.forEach((spacingStyle) => {
1541 const declarations = [];
1542 if (spacingStyle.rules) {
1543 Object.entries(spacingStyle.rules).forEach(
1544 ([cssProperty, cssValue]) => {
1545 declarations.push(
1546 `${cssProperty}: ${cssValue ? cssValue : gapValue}`
1547 );
1548 }
1549 );
1550 }
1551 if (declarations.length) {
1552 let combinedSelector = "";
1553 if (!hasBlockGapSupport) {
1554 combinedSelector = selector === ROOT_BLOCK_SELECTOR ? `:where(.${className}${spacingStyle?.selector || ""})` : `:where(${selector}.${className}${spacingStyle?.selector || ""})`;
1555 } else {
1556 combinedSelector = selector === ROOT_BLOCK_SELECTOR ? `:root :where(.${className})${spacingStyle?.selector || ""}` : `:root :where(${selector}-${className})${spacingStyle?.selector || ""}`;
1557 }
1558 ruleset += `${combinedSelector} { ${declarations.join(
1559 "; "
1560 )}; }`;
1561 }
1562 });
1563 }
1564 }
1565 );
1566 if (selector === ROOT_BLOCK_SELECTOR && hasBlockGapSupport) {
1567 ruleset += `${ROOT_CSS_PROPERTIES_SELECTOR} { --wp--style--block-gap: ${gapValue}; }`;
1568 }
1569 }
1570 if (selector === ROOT_BLOCK_SELECTOR && layoutDefinitions) {
1571 const validDisplayModes = ["block", "flex", "grid"];
1572 Object.values(layoutDefinitions).forEach(
1573 ({ className, displayMode, baseStyles }) => {
1574 if (displayMode && validDisplayModes.includes(displayMode)) {
1575 ruleset += `${selector} .${className} { display:${displayMode}; }`;
1576 }
1577 if (baseStyles?.length) {
1578 baseStyles.forEach((baseStyle) => {
1579 const declarations = [];
1580 if (baseStyle.rules) {
1581 Object.entries(baseStyle.rules).forEach(
1582 ([cssProperty, cssValue]) => {
1583 declarations.push(
1584 `${cssProperty}: ${cssValue}`
1585 );
1586 }
1587 );
1588 }
1589 if (declarations.length) {
1590 const combinedSelector = `.${className}${baseStyle?.selector || ""}`;
1591 ruleset += `${combinedSelector} { ${declarations.join(
1592 "; "
1593 )}; }`;
1594 }
1595 });
1596 }
1597 }
1598 );
1599 }
1600 return ruleset;
1601 }
1602 var STYLE_KEYS = [
1603 "border",
1604 "color",
1605 "dimensions",
1606 "spacing",
1607 "typography",
1608 "filter",
1609 "outline",
1610 "shadow",
1611 "background"
1612 ];
1613 function pickStyleKeys(treeToPickFrom) {
1614 return pickStyleAndPseudoKeys(treeToPickFrom);
1615 }
1616 function pickStyleAndPseudoKeys(treeToPickFrom, blockName) {
1617 if (!treeToPickFrom) {
1618 return {};
1619 }
1620 const entries = Object.entries(treeToPickFrom);
1621 const allowedPseudoSelectors = blockName ? VALID_BLOCK_PSEUDO_SELECTORS[blockName] ?? [] : [];
1622 const pickedEntries = entries.filter(
1623 ([key]) => STYLE_KEYS.includes(key) || allowedPseudoSelectors.includes(key) || RESPONSIVE_BREAKPOINTS[key]
1624 );
1625 const clonedEntries = pickedEntries.map(([key, style]) => [
1626 key,
1627 JSON.parse(JSON.stringify(style))
1628 ]);
1629 return Object.fromEntries(clonedEntries);
1630 }
1631 function getPseudoStyleNodes(node) {
1632 const {
1633 styles,
1634 selector,
1635 featureSelectors,
1636 name,
1637 elementName,
1638 mediaQuery,
1639 variationName
1640 } = node;
1641 const pseudoSelectors = name ? VALID_BLOCK_PSEUDO_SELECTORS[name] ?? [] : VALID_ELEMENT_PSEUDO_SELECTORS[elementName ?? ""] ?? [];
1642 if (!pseudoSelectors.length) {
1643 return [];
1644 }
1645 return pseudoSelectors.flatMap((pseudoSelector) => {
1646 const pseudoStyles = styles?.[pseudoSelector];
1647 if (!pseudoStyles || typeof pseudoStyles !== "object") {
1648 return [];
1649 }
1650 return [
1651 {
1652 styles: JSON.parse(JSON.stringify(pseudoStyles)),
1653 selector,
1654 selectorSuffix: pseudoSelector,
1655 mediaQuery,
1656 featureSelectors: featureSelectors && typeof featureSelectors !== "string" ? featureSelectors : void 0,
1657 name,
1658 elementName,
1659 variationName
1660 }
1661 ];
1662 });
1663 }
1664 function getResponsiveStyleNodes(node) {
1665 const {
1666 styles,
1667 selector,
1668 featureSelectors,
1669 name,
1670 elementName,
1671 isStyleVariation,
1672 variationName
1673 } = node;
1674 if (!name && !elementName) {
1675 return [];
1676 }
1677 return Object.entries(RESPONSIVE_BREAKPOINTS).flatMap(
1678 ([breakpointKey, mediaQuery]) => {
1679 const breakpointStyles = styles?.[breakpointKey];
1680 if (!breakpointStyles || typeof breakpointStyles !== "object") {
1681 return [];
1682 }
1683 return [
1684 {
1685 styles: JSON.parse(JSON.stringify(breakpointStyles)),
1686 selector,
1687 mediaQuery,
1688 featureSelectors: featureSelectors && typeof featureSelectors !== "string" ? featureSelectors : void 0,
1689 name,
1690 elementName,
1691 isStyleVariation,
1692 variationName
1693 }
1694 ];
1695 }
1696 );
1697 }
1698 var getNodesWithStyles = (tree, blockSelectors) => {
1699 const nodes = [];
1700 if (!tree?.styles) {
1701 return nodes;
1702 }
1703 const styles = pickStyleKeys(tree.styles);
1704 if (styles) {
1705 nodes.push({
1706 styles,
1707 selector: ROOT_BLOCK_SELECTOR,
1708 // Root selector (body) styles should not be wrapped in `:root where()` to keep
1709 // specificity at (0,0,1) and maintain backwards compatibility.
1710 skipSelectorWrapper: true
1711 });
1712 }
1713 Object.entries(import_blocks.__EXPERIMENTAL_ELEMENTS).forEach(([name, selector]) => {
1714 if (tree.styles?.elements?.[name]) {
1715 nodes.push({
1716 styles: tree.styles?.elements?.[name] ?? {},
1717 selector,
1718 elementName: name,
1719 // Top level elements that don't use a class name should not receive the
1720 // `:root :where()` wrapper to maintain backwards compatibility.
1721 skipSelectorWrapper: !ELEMENT_CLASS_NAMES[name]
1722 });
1723 }
1724 });
1725 Object.entries(tree.styles?.blocks ?? {}).forEach(
1726 ([blockName, node]) => {
1727 const blockStyles = pickStyleAndPseudoKeys(node, blockName);
1728 const typedNode = node;
1729 const variationNodesToAdd = [];
1730 const variationStyleNodesToAdd = [];
1731 if (typedNode?.variations) {
1732 Object.entries(typedNode.variations).forEach(
1733 ([variationName, variation]) => {
1734 const typedVariation = variation;
1735 const variationStyles = pickStyleAndPseudoKeys(
1736 typedVariation,
1737 blockName
1738 );
1739 if (typedVariation?.css) {
1740 variationStyles.css = typedVariation.css;
1741 }
1742 const variationSelector = typeof blockSelectors !== "string" ? blockSelectors[blockName]?.styleVariationSelectors?.[variationName] : void 0;
1743 if (variationSelector && typeof blockSelectors !== "string") {
1744 const blockSelector = blockSelectors[blockName];
1745 variationStyleNodesToAdd.push({
1746 styles: variationStyles,
1747 selector: variationSelector,
1748 featureSelectors: blockSelector?.featureSelectors,
1749 fallbackGapValue: blockSelector?.fallbackGapValue,
1750 hasLayoutSupport: blockSelector?.hasLayoutSupport,
1751 isStyleVariation: true,
1752 variationName,
1753 layoutSelector: variationSelector + blockSelector.selector,
1754 layoutHasBlockGapSupport: true,
1755 name: blockName
1756 });
1757 }
1758 Object.entries(
1759 typedVariation?.elements ?? {}
1760 ).forEach(([element, elementStyles]) => {
1761 if (elementStyles && import_blocks.__EXPERIMENTAL_ELEMENTS[element]) {
1762 variationNodesToAdd.push({
1763 styles: elementStyles,
1764 selector: scopeSelector(
1765 variationSelector,
1766 import_blocks.__EXPERIMENTAL_ELEMENTS[element]
1767 ),
1768 elementName: element,
1769 isStyleVariation: true
1770 });
1771 }
1772 });
1773 Object.entries(typedVariation?.blocks ?? {}).forEach(
1774 ([
1775 variationBlockName,
1776 variationBlockStyles
1777 ]) => {
1778 const variationBlockSelector = typeof blockSelectors !== "string" ? scopeSelector(
1779 variationSelector,
1780 blockSelectors[variationBlockName]?.selector
1781 ) : void 0;
1782 const variationDuotoneSelector = typeof blockSelectors !== "string" ? scopeSelector(
1783 variationSelector,
1784 blockSelectors[variationBlockName]?.duotoneSelector
1785 ) : void 0;
1786 const variationFeatureSelectors = typeof blockSelectors !== "string" ? scopeFeatureSelectors(
1787 variationSelector,
1788 blockSelectors[variationBlockName]?.featureSelectors ?? {}
1789 ) : void 0;
1790 const variationBlockStyleNodes = pickStyleAndPseudoKeys(
1791 variationBlockStyles,
1792 variationBlockName
1793 );
1794 if (variationBlockStyles?.css) {
1795 variationBlockStyleNodes.css = variationBlockStyles.css;
1796 }
1797 if (!variationBlockSelector || typeof blockSelectors === "string") {
1798 return;
1799 }
1800 variationNodesToAdd.push({
1801 selector: variationBlockSelector,
1802 name: variationBlockName,
1803 isStyleVariation: true,
1804 duotoneSelector: variationDuotoneSelector,
1805 featureSelectors: variationFeatureSelectors,
1806 fallbackGapValue: blockSelectors[variationBlockName]?.fallbackGapValue,
1807 hasLayoutSupport: blockSelectors[variationBlockName]?.hasLayoutSupport,
1808 styles: variationBlockStyleNodes
1809 });
1810 Object.entries(
1811 variationBlockStyles.elements ?? {}
1812 ).forEach(
1813 ([
1814 variationBlockElement,
1815 variationBlockElementStyles
1816 ]) => {
1817 if (variationBlockElementStyles && import_blocks.__EXPERIMENTAL_ELEMENTS[variationBlockElement]) {
1818 variationNodesToAdd.push({
1819 styles: variationBlockElementStyles,
1820 selector: scopeSelector(
1821 variationBlockSelector,
1822 import_blocks.__EXPERIMENTAL_ELEMENTS[variationBlockElement]
1823 ),
1824 elementName: variationBlockElement,
1825 isStyleVariation: true
1826 });
1827 }
1828 }
1829 );
1830 }
1831 );
1832 }
1833 );
1834 }
1835 if (typeof blockSelectors !== "string" && blockSelectors?.[blockName]?.selector) {
1836 nodes.push({
1837 duotoneSelector: blockSelectors[blockName].duotoneSelector,
1838 fallbackGapValue: blockSelectors[blockName].fallbackGapValue,
1839 hasLayoutSupport: blockSelectors[blockName].hasLayoutSupport,
1840 selector: blockSelectors[blockName].selector,
1841 styles: blockStyles,
1842 featureSelectors: blockSelectors[blockName].featureSelectors,
1843 name: blockName
1844 });
1845 }
1846 nodes.push(...variationStyleNodesToAdd);
1847 Object.entries(typedNode?.elements ?? {}).forEach(
1848 ([elementName, value]) => {
1849 if (typeof blockSelectors !== "string" && value && blockSelectors?.[blockName] && import_blocks.__EXPERIMENTAL_ELEMENTS[elementName]) {
1850 nodes.push({
1851 styles: value,
1852 selector: blockSelectors[blockName]?.selector.split(",").map((sel) => {
1853 const elementSelectors = import_blocks.__EXPERIMENTAL_ELEMENTS[elementName].split(",");
1854 return elementSelectors.map(
1855 (elementSelector) => sel + " " + elementSelector
1856 );
1857 }).join(","),
1858 elementName
1859 });
1860 }
1861 }
1862 );
1863 nodes.push(...variationNodesToAdd);
1864 }
1865 );
1866 return nodes;
1867 };
1868 var getNodesWithSettings = (tree, blockSelectors) => {
1869 const nodes = [];
1870 if (!tree?.settings) {
1871 return nodes;
1872 }
1873 const pickPresets = (treeToPickFrom) => {
1874 let presets2 = {};
1875 PRESET_METADATA.forEach(({ path }) => {
1876 const value = getValueFromObjectPath(treeToPickFrom, path, false);
1877 if (value !== false) {
1878 presets2 = setImmutably(presets2, path, value);
1879 }
1880 });
1881 return presets2;
1882 };
1883 const presets = pickPresets(tree.settings);
1884 const custom = tree.settings?.custom;
1885 if (Object.keys(presets).length > 0 || custom) {
1886 nodes.push({
1887 presets,
1888 custom,
1889 selector: ROOT_CSS_PROPERTIES_SELECTOR
1890 });
1891 }
1892 Object.entries(tree.settings?.blocks ?? {}).forEach(
1893 ([blockName, node]) => {
1894 const blockCustom = node.custom;
1895 if (typeof blockSelectors === "string" || !blockSelectors[blockName]) {
1896 return;
1897 }
1898 const blockPresets = pickPresets(node);
1899 if (Object.keys(blockPresets).length > 0 || blockCustom) {
1900 nodes.push({
1901 presets: blockPresets,
1902 custom: blockCustom,
1903 selector: blockSelectors[blockName]?.selector,
1904 featureSelectors: blockSelectors[blockName]?.featureSelectors
1905 });
1906 }
1907 }
1908 );
1909 return nodes;
1910 };
1911 function resolveFeatureSelector(featureSelectors, featureKey, fallback) {
1912 if (!featureSelectors || typeof featureSelectors === "string") {
1913 return fallback;
1914 }
1915 const feature = featureSelectors[featureKey];
1916 if (typeof feature === "string") {
1917 return feature;
1918 }
1919 if (typeof feature === "object" && feature.root) {
1920 return feature.root;
1921 }
1922 return fallback;
1923 }
1924 function getPresetVarDeclarations(presets, mergedSettings, { path, valueKey, valueFunc, cssVarInfix }) {
1925 const presetByOrigin = getValueFromObjectPath(
1926 presets,
1927 path,
1928 []
1929 );
1930 const declarations = [];
1931 for (const origin of ["default", "theme", "custom"]) {
1932 if (!presetByOrigin[origin]) {
1933 continue;
1934 }
1935 for (const value of presetByOrigin[origin]) {
1936 const slug = kebabCase(value.slug);
1937 if (valueKey && !valueFunc) {
1938 declarations.push(
1939 `--wp--preset--${cssVarInfix}--${slug}: ${value[valueKey]}`
1940 );
1941 } else if (valueFunc && typeof valueFunc === "function") {
1942 declarations.push(
1943 `--wp--preset--${cssVarInfix}--${slug}: ${valueFunc(
1944 value,
1945 mergedSettings
1946 )}`
1947 );
1948 }
1949 }
1950 }
1951 return declarations;
1952 }
1953 var generateCustomProperties = (tree, blockSelectors) => {
1954 const nodes = getNodesWithSettings(tree, blockSelectors);
1955 let ruleset = "";
1956 for (const { presets, custom, selector, featureSelectors } of nodes) {
1957 const defaultSelector = selector;
1958 const varsBySelector = {
1959 [defaultSelector]: []
1960 };
1961 if (tree?.settings) {
1962 for (const metadata of PRESET_METADATA) {
1963 const declarations = getPresetVarDeclarations(
1964 presets,
1965 tree.settings,
1966 metadata
1967 );
1968 if (declarations.length === 0) {
1969 continue;
1970 }
1971 const target = resolveFeatureSelector(
1972 featureSelectors,
1973 metadata.path[0],
1974 defaultSelector
1975 );
1976 if (!varsBySelector[target]) {
1977 varsBySelector[target] = [];
1978 }
1979 varsBySelector[target].push(...declarations);
1980 }
1981 }
1982 const customProps = flattenTree(custom, "--wp--custom--", "--");
1983 if (customProps.length > 0) {
1984 varsBySelector[defaultSelector].push(...customProps);
1985 }
1986 for (const [ruleSelector, declarations] of Object.entries(
1987 varsBySelector
1988 )) {
1989 if (declarations.length > 0) {
1990 ruleset += `${ruleSelector}{${declarations.join(";")};}`;
1991 }
1992 }
1993 }
1994 return ruleset;
1995 };
1996 function renderStylesNode(node, {
1997 tree,
1998 useRootPaddingAlign,
1999 disableLayoutStyles,
2000 hasBlockGapSupport,
2001 hasFallbackGapSupport,
2002 disableRootPadding
2003 }) {
2004 const {
2005 selector,
2006 selectorSuffix,
2007 mediaQuery,
2008 duotoneSelector,
2009 styles,
2010 fallbackGapValue,
2011 hasLayoutSupport,
2012 featureSelectors,
2013 layoutSelector,
2014 layoutHasBlockGapSupport,
2015 skipSelectorWrapper,
2016 name,
2017 variationName
2018 } = node;
2019 let ruleset = "";
2020 const effectiveSelector = selectorSuffix ? appendToSelector(selector, selectorSuffix) : selector;
2021 if (featureSelectors && typeof featureSelectors !== "string") {
2022 let featureDeclarations = getFeatureDeclarations(
2023 featureSelectors,
2024 styles
2025 );
2026 featureDeclarations = updateParagraphTextIndentSelector(
2027 featureDeclarations,
2028 tree.settings,
2029 name
2030 );
2031 featureDeclarations = updateButtonWidthDeclarations(
2032 featureDeclarations,
2033 tree.settings
2034 );
2035 Object.entries(featureDeclarations).forEach(
2036 ([featureSelector, declarations]) => {
2037 if (declarations.length) {
2038 let selectorForRule = variationName ? getBlockStyleVariationFeatureSelector(
2039 variationName,
2040 featureSelector
2041 ) : featureSelector;
2042 selectorForRule = selectorSuffix ? appendToSelector(selectorForRule, selectorSuffix) : selectorForRule;
2043 const rules = declarations.join(";");
2044 ruleset += `:root :where(${selectorForRule}){${rules};}`;
2045 }
2046 }
2047 );
2048 }
2049 if (duotoneSelector) {
2050 const duotoneStyles = {};
2051 if (styles?.filter) {
2052 duotoneStyles.filter = styles.filter;
2053 delete styles.filter;
2054 }
2055 const duotoneDeclarations = getStylesDeclarations(duotoneStyles);
2056 if (duotoneDeclarations.length) {
2057 ruleset += `${duotoneSelector}{${duotoneDeclarations.join(
2058 ";"
2059 )};}`;
2060 }
2061 }
2062 const selectorForLayout = layoutSelector ?? effectiveSelector;
2063 const hasBlockGapSupportForLayout = layoutHasBlockGapSupport ?? hasBlockGapSupport;
2064 if (!disableLayoutStyles && (ROOT_BLOCK_SELECTOR === selectorForLayout || hasLayoutSupport)) {
2065 ruleset += getLayoutStyles({
2066 style: styles,
2067 selector: selectorForLayout,
2068 hasBlockGapSupport: hasBlockGapSupportForLayout,
2069 hasFallbackGapSupport,
2070 fallbackGapValue
2071 });
2072 }
2073 const styleDeclarations = getStylesDeclarations(
2074 styles,
2075 effectiveSelector,
2076 useRootPaddingAlign,
2077 tree,
2078 disableRootPadding
2079 );
2080 if (styleDeclarations?.length) {
2081 const generalSelector = skipSelectorWrapper ? effectiveSelector : `:root :where(${effectiveSelector})`;
2082 ruleset += `${generalSelector}{${styleDeclarations.join(";")};}`;
2083 }
2084 if (styles?.css) {
2085 ruleset += processCSSNesting(
2086 styles.css,
2087 `:root :where(${effectiveSelector})`
2088 );
2089 }
2090 if (mediaQuery && ruleset) {
2091 return `${mediaQuery}{${ruleset}}`;
2092 }
2093 return ruleset;
2094 }
2095 var transformToStyles = (tree, blockSelectors, hasBlockGapSupport, hasFallbackGapSupport, disableLayoutStyles = false, disableRootPadding = false, styleOptions = {}) => {
2096 const options = {
2097 blockGap: true,
2098 blockStyles: true,
2099 layoutStyles: true,
2100 marginReset: true,
2101 presets: true,
2102 rootPadding: true,
2103 variationStyles: false,
2104 ...styleOptions
2105 };
2106 const normalizedTree = normalizeStyleStateAliases(tree);
2107 const nodesWithStyles = getNodesWithStyles(
2108 normalizedTree,
2109 blockSelectors
2110 );
2111 const nodesWithSettings = getNodesWithSettings(
2112 normalizedTree,
2113 blockSelectors
2114 );
2115 const useRootPaddingAlign = normalizedTree?.settings?.useRootPaddingAwareAlignments;
2116 const { contentSize, wideSize } = normalizedTree?.settings?.layout || {};
2117 const hasBodyStyles = options.marginReset || options.rootPadding || options.layoutStyles;
2118 let ruleset = "";
2119 if (options.presets && (contentSize || wideSize)) {
2120 ruleset += `${ROOT_CSS_PROPERTIES_SELECTOR} {`;
2121 ruleset = contentSize ? ruleset + ` --wp--style--global--content-size: ${contentSize};` : ruleset;
2122 ruleset = wideSize ? ruleset + ` --wp--style--global--wide-size: ${wideSize};` : ruleset;
2123 ruleset += "}";
2124 }
2125 if (hasBodyStyles) {
2126 ruleset += ":where(body) {margin: 0;";
2127 if (options.rootPadding && useRootPaddingAlign) {
2128 ruleset += `padding-right: 0; padding-left: 0; padding-top: var(--wp--style--root--padding-top); padding-bottom: var(--wp--style--root--padding-bottom) }
2129 .has-global-padding { padding-right: var(--wp--style--root--padding-right); padding-left: var(--wp--style--root--padding-left); }
2130 .has-global-padding > .alignfull { margin-right: calc(var(--wp--style--root--padding-right) * -1); margin-left: calc(var(--wp--style--root--padding-left) * -1); }
2131 .has-global-padding :where(:not(.alignfull.is-layout-flow) > .has-global-padding:not(.wp-block-block, .alignfull)) { padding-right: 0; padding-left: 0; }
2132 .has-global-padding :where(:not(.alignfull.is-layout-flow) > .has-global-padding:not(.wp-block-block, .alignfull)) > .alignfull { margin-left: 0; margin-right: 0;
2133 `;
2134 }
2135 ruleset += "}";
2136 }
2137 if (options.blockStyles) {
2138 nodesWithStyles.forEach((node) => {
2139 if (node.isStyleVariation && !options.variationStyles) {
2140 return;
2141 }
2142 const responsiveNodes = getResponsiveStyleNodes(node);
2143 [
2144 node,
2145 ...responsiveNodes,
2146 ...getPseudoStyleNodes(node),
2147 ...responsiveNodes.flatMap(getPseudoStyleNodes)
2148 ].forEach((expandedNode) => {
2149 ruleset += renderStylesNode(expandedNode, {
2150 tree: normalizedTree,
2151 useRootPaddingAlign,
2152 disableLayoutStyles,
2153 hasBlockGapSupport,
2154 hasFallbackGapSupport,
2155 disableRootPadding
2156 });
2157 });
2158 });
2159 }
2160 if (options.layoutStyles) {
2161 ruleset = ruleset + ".wp-site-blocks > .alignleft { float: left; margin-right: 2em; }";
2162 ruleset = ruleset + ".wp-site-blocks > .alignright { float: right; margin-left: 2em; }";
2163 ruleset = ruleset + ".wp-site-blocks > .aligncenter { justify-content: center; margin-left: auto; margin-right: auto; }";
2164 }
2165 if (options.blockGap && hasBlockGapSupport) {
2166 const gapValue = getGapCSSValue(normalizedTree?.styles?.spacing?.blockGap) || "0.5em";
2167 ruleset = ruleset + `:root :where(.wp-site-blocks) > * { margin-block-start: ${gapValue}; margin-block-end: 0; }`;
2168 ruleset = ruleset + ":root :where(.wp-site-blocks) > :first-child { margin-block-start: 0; }";
2169 ruleset = ruleset + ":root :where(.wp-site-blocks) > :last-child { margin-block-end: 0; }";
2170 }
2171 if (options.presets) {
2172 nodesWithSettings.forEach(({ selector, presets }) => {
2173 if (ROOT_BLOCK_SELECTOR === selector || ROOT_CSS_PROPERTIES_SELECTOR === selector) {
2174 selector = "";
2175 }
2176 const classes = getPresetsClasses(selector, presets);
2177 if (classes.length > 0) {
2178 ruleset += classes;
2179 }
2180 });
2181 }
2182 return ruleset;
2183 };
2184 function generateSvgFilters(tree, blockSelectors) {
2185 const nodesWithSettings = getNodesWithSettings(tree, blockSelectors);
2186 return nodesWithSettings.flatMap(({ presets }) => {
2187 return getPresetsSvgFilters(presets);
2188 });
2189 }
2190 var getSelectorsConfig = (blockType, rootSelector) => {
2191 if (blockType?.selectors && Object.keys(blockType.selectors).length > 0) {
2192 return blockType.selectors;
2193 }
2194 const config = {
2195 root: rootSelector
2196 };
2197 Object.entries(BLOCK_SUPPORT_FEATURE_LEVEL_SELECTORS).forEach(
2198 ([featureKey, featureName]) => {
2199 const featureSelector = getBlockSelector(blockType, featureKey);
2200 if (featureSelector) {
2201 config[featureName] = featureSelector;
2202 }
2203 }
2204 );
2205 return config;
2206 };
2207 var getBlockSelectors = (blockTypes, variationInstanceId) => {
2208 const { getBlockStyles } = (0, import_data2.select)(import_blocks.store);
2209 const result = {};
2210 blockTypes.forEach((blockType) => {
2211 const name = blockType.name;
2212 const selector = getBlockSelector(blockType);
2213 if (!selector) {
2214 return;
2215 }
2216 let duotoneSelector = getBlockSelector(blockType, "filter.duotone");
2217 if (!duotoneSelector) {
2218 const rootSelector = getBlockSelector(blockType);
2219 const duotoneSupport = (0, import_blocks.getBlockSupport)(
2220 blockType,
2221 "color.__experimentalDuotone",
2222 false
2223 );
2224 if (typeof duotoneSupport === "string" && rootSelector) {
2225 duotoneSelector = scopeSelector(rootSelector, duotoneSupport);
2226 }
2227 }
2228 const hasLayoutSupport = !!blockType?.supports?.layout || !!blockType?.supports?.__experimentalLayout;
2229 const fallbackGapValue = (
2230 // @ts-expect-error
2231 blockType?.supports?.spacing?.blockGap?.__experimentalDefault
2232 );
2233 const blockStyleVariations = getBlockStyles(name);
2234 const styleVariationSelectors = {};
2235 blockStyleVariations?.forEach((variation) => {
2236 const variationSuffix = variationInstanceId ? `-${variationInstanceId}` : "";
2237 const variationName = `${variation.name}${variationSuffix}`;
2238 const styleVariationSelector = getBlockStyleVariationSelector(
2239 variationName,
2240 selector
2241 );
2242 styleVariationSelectors[variationName] = styleVariationSelector;
2243 });
2244 const featureSelectors = getSelectorsConfig(blockType, selector);
2245 result[name] = {
2246 duotoneSelector: duotoneSelector ?? void 0,
2247 fallbackGapValue,
2248 featureSelectors: Object.keys(featureSelectors).length ? featureSelectors : void 0,
2249 hasLayoutSupport,
2250 name,
2251 selector,
2252 styleVariationSelectors: blockStyleVariations?.length ? styleVariationSelectors : void 0
2253 };
2254 });
2255 return result;
2256 };
2257 function updateConfigWithSeparator(config) {
2258 const blocks = config.styles?.blocks;
2259 const separatorBlock = blocks?.["core/separator"];
2260 const needsSeparatorStyleUpdate = separatorBlock && separatorBlock.color?.background && !separatorBlock.color?.text && !separatorBlock.border?.color;
2261 if (needsSeparatorStyleUpdate) {
2262 return {
2263 ...config,
2264 styles: {
2265 ...config.styles,
2266 blocks: {
2267 ...blocks,
2268 "core/separator": {
2269 ...separatorBlock,
2270 color: {
2271 ...separatorBlock.color,
2272 text: separatorBlock.color?.background
2273 }
2274 }
2275 }
2276 }
2277 };
2278 }
2279 return config;
2280 }
2281 function processCSSNesting(css, blockSelector) {
2282 let processedCSS = "";
2283 if (!css || css.trim() === "") {
2284 return processedCSS;
2285 }
2286 const parts = css.split("&");
2287 parts.forEach((part) => {
2288 if (!part || part.trim() === "") {
2289 return;
2290 }
2291 const isRootCss = !part.includes("{");
2292 if (isRootCss) {
2293 processedCSS += `:root :where(${blockSelector}){${part.trim()}}`;
2294 } else {
2295 const splitPart = part.replace("}", "").split("{");
2296 if (splitPart.length !== 2) {
2297 return;
2298 }
2299 const [nestedSelector, cssValue] = splitPart;
2300 const matches = nestedSelector.match(/([>+~\s]*::[a-zA-Z-]+)/);
2301 const pseudoPart = matches ? matches[1] : "";
2302 const withoutPseudoElement = matches ? nestedSelector.replace(pseudoPart, "").trim() : nestedSelector.trim();
2303 let combinedSelector;
2304 if (withoutPseudoElement === "") {
2305 combinedSelector = blockSelector;
2306 } else {
2307 combinedSelector = nestedSelector.startsWith(" ") ? scopeSelector(blockSelector, withoutPseudoElement) : appendToSelector(blockSelector, withoutPseudoElement);
2308 }
2309 processedCSS += `:root :where(${combinedSelector})${pseudoPart}{${cssValue.trim()}}`;
2310 }
2311 });
2312 return processedCSS;
2313 }
2314 function generateGlobalStyles(config = {}, blockTypes = [], options = {}) {
2315 const {
2316 hasBlockGapSupport: hasBlockGapSupportOption,
2317 hasFallbackGapSupport: hasFallbackGapSupportOption,
2318 disableLayoutStyles = false,
2319 disableRootPadding = false,
2320 styleOptions = {}
2321 } = options;
2322 const blocks = blockTypes.length > 0 ? blockTypes : (0, import_blocks.getBlockTypes)();
2323 const blockGap = getSetting(config, "spacing.blockGap");
2324 const hasBlockGapSupport = hasBlockGapSupportOption ?? blockGap !== null;
2325 const hasFallbackGapSupport = hasFallbackGapSupportOption ?? !hasBlockGapSupport;
2326 if (!config?.styles || !config?.settings) {
2327 return [[], {}];
2328 }
2329 const updatedConfig = updateConfigWithSeparator(config);
2330 const blockSelectors = getBlockSelectors(blocks);
2331 const customProperties = generateCustomProperties(
2332 updatedConfig,
2333 blockSelectors
2334 );
2335 const globalStyles = transformToStyles(
2336 updatedConfig,
2337 blockSelectors,
2338 hasBlockGapSupport,
2339 hasFallbackGapSupport,
2340 disableLayoutStyles,
2341 disableRootPadding,
2342 styleOptions
2343 );
2344 const svgs = generateSvgFilters(updatedConfig, blockSelectors);
2345 const styles = [
2346 {
2347 css: customProperties,
2348 isGlobalStyles: true
2349 },
2350 {
2351 css: globalStyles,
2352 isGlobalStyles: true
2353 },
2354 // Load custom CSS in own stylesheet so that any invalid CSS entered in the input won't break all the global styles in the editor.
2355 {
2356 css: updatedConfig?.styles?.css ?? "",
2357 isGlobalStyles: true
2358 },
2359 {
2360 assets: svgs,
2361 __unstableType: "svgs",
2362 isGlobalStyles: true
2363 }
2364 ];
2365 blocks.forEach((blockType) => {
2366 const blockStyles = updatedConfig?.styles?.blocks?.[blockType.name];
2367 if (blockStyles?.css) {
2368 const { featureSelectors } = blockSelectors[blockType.name];
2369 const cssFeatureSelector = typeof featureSelectors === "object" ? featureSelectors?.css : void 0;
2370 let resolvedCssSelector;
2371 if (typeof cssFeatureSelector === "string") {
2372 resolvedCssSelector = cssFeatureSelector;
2373 } else if (typeof cssFeatureSelector === "object") {
2374 resolvedCssSelector = cssFeatureSelector?.root;
2375 }
2376 const selector = resolvedCssSelector ?? blockSelectors[blockType.name].selector;
2377 styles.push({
2378 css: processCSSNesting(blockStyles.css, selector),
2379 isGlobalStyles: true
2380 });
2381 }
2382 });
2383 return [styles, updatedConfig.settings];
2384 }
2385
2386 // packages/lazy-editor/build-module/hooks/use-editor-settings.mjs
2387 var import_core_data3 = __toESM(require_core_data(), 1);
2388 var import_element2 = __toESM(require_element(), 1);
2389 var import_data4 = __toESM(require_data(), 1);
2390
2391 // packages/lazy-editor/build-module/hooks/use-global-styles.mjs
2392 var import_core_data2 = __toESM(require_core_data(), 1);
2393 var import_data3 = __toESM(require_data(), 1);
2394 var import_element = __toESM(require_element(), 1);
2395 function useUserGlobalStyles(id) {
2396 const { userGlobalStyles } = (0, import_data3.useSelect)(
2397 (select2) => {
2398 const { getEntityRecord, getEditedEntityRecord, canUser } = select2(import_core_data2.store);
2399 const userCanEditGlobalStyles = canUser("update", {
2400 kind: "root",
2401 name: "globalStyles",
2402 id
2403 });
2404 let record;
2405 if (
2406 /*
2407 * Test that the OPTIONS request for user capabilities is complete
2408 * before fetching the global styles entity record.
2409 * This is to avoid fetching the global styles entity unnecessarily.
2410 */
2411 typeof userCanEditGlobalStyles === "boolean"
2412 ) {
2413 if (userCanEditGlobalStyles) {
2414 record = getEditedEntityRecord(
2415 "root",
2416 "globalStyles",
2417 id
2418 );
2419 } else {
2420 record = getEntityRecord("root", "globalStyles", id, {
2421 context: "view"
2422 });
2423 }
2424 }
2425 return {
2426 userGlobalStyles: record
2427 };
2428 },
2429 [id]
2430 );
2431 return (0, import_element.useMemo)(() => {
2432 if (!userGlobalStyles) {
2433 return {
2434 user: void 0
2435 };
2436 }
2437 const user = userGlobalStyles;
2438 return {
2439 user
2440 };
2441 }, [userGlobalStyles]);
2442 }
2443
2444 // packages/lazy-editor/build-module/lock-unlock.mjs
2445 var import_private_apis = __toESM(require_private_apis(), 1);
2446 var { unlock } = (0, import_private_apis.__dangerousOptInToUnstableAPIsOnlyForCoreModules)(
2447 "I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.",
2448 "@wordpress/lazy-editor"
2449 );
2450
2451 // packages/lazy-editor/build-module/hooks/use-editor-settings.mjs
2452 function useEditorSettings({ stylesId }) {
2453 const { editorSettings } = (0, import_data4.useSelect)(
2454 (select2) => ({
2455 editorSettings: unlock(
2456 select2(import_core_data3.store)
2457 ).getEditorSettings()
2458 }),
2459 []
2460 );
2461 const { user: globalStyles } = useUserGlobalStyles(stylesId);
2462 const [globalStylesCSS] = generateGlobalStyles(globalStyles);
2463 const hasEditorSettings = !!editorSettings;
2464 const styles = (0, import_element2.useMemo)(() => {
2465 if (!hasEditorSettings) {
2466 return [];
2467 }
2468 return [
2469 ...editorSettings?.styles ?? [],
2470 ...globalStylesCSS
2471 ];
2472 }, [hasEditorSettings, editorSettings?.styles, globalStylesCSS]);
2473 return {
2474 isReady: hasEditorSettings,
2475 editorSettings: (0, import_element2.useMemo)(
2476 () => ({
2477 ...editorSettings ?? {},
2478 styles
2479 }),
2480 [editorSettings, styles]
2481 )
2482 };
2483 }
2484
2485 // packages/asset-loader/build-module/index.mjs
2486 function injectImportMap(scriptModules) {
2487 if (!scriptModules || Object.keys(scriptModules).length === 0) {
2488 return;
2489 }
2490 const existingMapElement = document.querySelector(
2491 "script#wp-importmap[type=importmap]"
2492 );
2493 if (existingMapElement) {
2494 try {
2495 const existingMap = JSON.parse(existingMapElement.text);
2496 if (!existingMap.imports) {
2497 existingMap.imports = {};
2498 }
2499 existingMap.imports = {
2500 ...existingMap.imports,
2501 ...scriptModules
2502 };
2503 existingMapElement.text = JSON.stringify(existingMap, null, 2);
2504 } catch (error) {
2505 console.error("Failed to parse or update import map:", error);
2506 }
2507 } else {
2508 const script = document.createElement("script");
2509 script.type = "importmap";
2510 script.id = "wp-importmap";
2511 script.text = JSON.stringify(
2512 {
2513 imports: scriptModules
2514 },
2515 null,
2516 2
2517 );
2518 document.head.appendChild(script);
2519 }
2520 }
2521 function loadStylesheet(handle, styleData) {
2522 return new Promise((resolve) => {
2523 if (!styleData.src) {
2524 resolve();
2525 return;
2526 }
2527 const existingLink = document.getElementById(handle + "-css");
2528 if (existingLink) {
2529 resolve();
2530 return;
2531 }
2532 const link = document.createElement("link");
2533 link.rel = "stylesheet";
2534 link.href = styleData.src + (styleData.version ? "?ver=" + styleData.version : "");
2535 link.id = handle + "-css";
2536 link.media = styleData.media || "all";
2537 link.onload = () => resolve();
2538 link.onerror = () => {
2539 console.error(`Failed to load stylesheet: ${handle}`);
2540 resolve();
2541 };
2542 document.head.appendChild(link);
2543 });
2544 }
2545 function loadScript(handle, scriptData) {
2546 if (!scriptData.src) {
2547 const marker = document.createElement("script");
2548 marker.id = handle + "-js";
2549 marker.textContent = "// Processed: " + handle;
2550 return marker;
2551 }
2552 const script = document.createElement("script");
2553 script.src = scriptData.src + (scriptData.version ? "?ver=" + scriptData.version : "");
2554 script.id = handle + "-js";
2555 script.async = false;
2556 return script;
2557 }
2558 function injectInlineStyle(handle, inlineStyle, position) {
2559 let styleContent = "";
2560 if (Array.isArray(inlineStyle)) {
2561 styleContent = inlineStyle.join("\n");
2562 } else if (typeof inlineStyle === "string") {
2563 styleContent = inlineStyle;
2564 }
2565 if (styleContent && styleContent.trim()) {
2566 const styleId = handle + "-" + position + "-inline-css";
2567 if (!document.getElementById(styleId)) {
2568 const style = document.createElement("style");
2569 style.id = styleId;
2570 style.textContent = styleContent.trim();
2571 document.head.appendChild(style);
2572 }
2573 }
2574 }
2575 function injectInlineScript(handle, inlineScript, position) {
2576 let scriptContent = inlineScript;
2577 if (Array.isArray(scriptContent)) {
2578 scriptContent = scriptContent.join("\n");
2579 }
2580 const script = document.createElement("script");
2581 script.id = handle + "-" + position + "-js";
2582 script.textContent = scriptContent.trim();
2583 return script;
2584 }
2585 function buildDependencyOrderedList(assetsData) {
2586 const visited = /* @__PURE__ */ new Set();
2587 const visiting = /* @__PURE__ */ new Set();
2588 const orderedList = [];
2589 function visit(handle) {
2590 if (visited.has(handle)) {
2591 return;
2592 }
2593 if (visiting.has(handle)) {
2594 console.warn(
2595 `Circular dependency detected for handle: ${handle}`
2596 );
2597 return;
2598 }
2599 visiting.add(handle);
2600 if (assetsData[handle]) {
2601 const deps = assetsData[handle].deps || [];
2602 deps.forEach((dep) => {
2603 if (assetsData[dep]) {
2604 visit(dep);
2605 }
2606 });
2607 }
2608 visiting.delete(handle);
2609 visited.add(handle);
2610 if (assetsData[handle]) {
2611 orderedList.push(handle);
2612 }
2613 }
2614 Object.keys(assetsData).forEach((handle) => {
2615 visit(handle);
2616 });
2617 return orderedList;
2618 }
2619 async function performScriptLoad(scriptElements, destination) {
2620 let parallel = [];
2621 for (const scriptElement of scriptElements) {
2622 if (scriptElement.src) {
2623 const loader = Promise.withResolvers();
2624 scriptElement.onload = () => loader.resolve();
2625 scriptElement.onerror = () => {
2626 console.error(`Failed to load script: ${scriptElement.id}`);
2627 loader.resolve();
2628 };
2629 parallel.push(loader.promise);
2630 } else {
2631 await Promise.all(parallel);
2632 parallel = [];
2633 }
2634 destination.appendChild(scriptElement);
2635 }
2636 await Promise.all(parallel);
2637 parallel = [];
2638 }
2639 async function loadAssets(scriptsData, inlineScripts, stylesData, inlineStyles, htmlTemplates, scriptModules) {
2640 if (scriptModules) {
2641 injectImportMap(scriptModules);
2642 }
2643 const orderedStyles = buildDependencyOrderedList(stylesData);
2644 const orderedScripts = buildDependencyOrderedList(scriptsData);
2645 const stylePromises = [];
2646 for (const handle of orderedStyles) {
2647 const beforeInline = inlineStyles.before?.[handle];
2648 if (beforeInline) {
2649 injectInlineStyle(handle, beforeInline, "before");
2650 }
2651 stylePromises.push(loadStylesheet(handle, stylesData[handle]));
2652 const afterInline = inlineStyles.after?.[handle];
2653 if (afterInline) {
2654 injectInlineStyle(handle, afterInline, "after");
2655 }
2656 }
2657 const scriptElements = [];
2658 for (const handle of orderedScripts) {
2659 const beforeInline = inlineScripts.before?.[handle];
2660 if (beforeInline) {
2661 scriptElements.push(
2662 injectInlineScript(handle, beforeInline, "before")
2663 );
2664 }
2665 scriptElements.push(loadScript(handle, scriptsData[handle]));
2666 const afterInline = inlineScripts.after?.[handle];
2667 if (afterInline) {
2668 scriptElements.push(
2669 injectInlineScript(handle, afterInline, "after")
2670 );
2671 }
2672 }
2673 const scriptsPromise = performScriptLoad(scriptElements, document.body);
2674 await Promise.all([Promise.all(stylePromises), scriptsPromise]);
2675 if (htmlTemplates && htmlTemplates.length > 0) {
2676 htmlTemplates.forEach((templateHtml) => {
2677 const scriptMatch = templateHtml.match(
2678 /<script([^>]*)>(.*?)<\/script>/is
2679 );
2680 if (scriptMatch) {
2681 const attributes = scriptMatch[1];
2682 const content = scriptMatch[2];
2683 const script = document.createElement("script");
2684 const idMatch = attributes.match(/id=["']([^"']+)["']/);
2685 if (idMatch) {
2686 script.id = idMatch[1];
2687 }
2688 const typeMatch = attributes.match(/type=["']([^"']+)["']/);
2689 if (typeMatch) {
2690 script.type = typeMatch[1];
2691 }
2692 script.textContent = content;
2693 document.body.appendChild(script);
2694 }
2695 });
2696 }
2697 }
2698 var index_default = loadAssets;
2699
2700 // packages/lazy-editor/build-module/hooks/use-editor-assets.mjs
2701 var import_core_data4 = __toESM(require_core_data(), 1);
2702 var import_element3 = __toESM(require_element(), 1);
2703 var import_data5 = __toESM(require_data(), 1);
2704 var loadAssetsPromise;
2705 async function loadEditorAssets() {
2706 const load = async () => {
2707 const editorAssets = await unlock(
2708 (0, import_data5.resolveSelect)(import_core_data4.store)
2709 ).getEditorAssets();
2710 await index_default(
2711 editorAssets.scripts || {},
2712 editorAssets.inline_scripts || { before: {}, after: {} },
2713 editorAssets.styles || {},
2714 editorAssets.inline_styles || { before: {}, after: {} },
2715 editorAssets.html_templates || [],
2716 editorAssets.script_modules || {}
2717 );
2718 };
2719 if (!loadAssetsPromise) {
2720 loadAssetsPromise = load();
2721 }
2722 return loadAssetsPromise;
2723 }
2724 function useEditorAssets() {
2725 const editorAssets = (0, import_data5.useSelect)((select2) => {
2726 return unlock(select2(import_core_data4.store)).getEditorAssets();
2727 }, []);
2728 const [assetsLoaded, setAssetsLoaded] = (0, import_element3.useState)(false);
2729 (0, import_element3.useEffect)(() => {
2730 if (editorAssets && !assetsLoaded) {
2731 loadEditorAssets().then(() => {
2732 setAssetsLoaded(true);
2733 }).catch((error) => {
2734 console.error("Failed to load editor assets:", error);
2735 });
2736 }
2737 }, [editorAssets, assetsLoaded]);
2738 return {
2739 isReady: !!editorAssets && assetsLoaded,
2740 assetsLoaded
2741 };
2742 }
2743
2744 // packages/lazy-editor/build-module/components/editor/index.mjs
2745 var import_jsx_runtime = __toESM(require_jsx_runtime(), 1);
2746 var { Editor: PrivateEditor, BackButton } = unlock(import_editor.privateApis);
2747 function Editor({
2748 postType,
2749 postId,
2750 settings,
2751 backButton
2752 }) {
2753 const homePage = (0, import_data6.useSelect)(
2754 (select2) => {
2755 if (postType || postId) {
2756 return null;
2757 }
2758 const { getHomePage } = unlock(select2(import_core_data5.store));
2759 return getHomePage();
2760 },
2761 [postType, postId]
2762 );
2763 const resolvedPostType = postType || homePage?.postType;
2764 const resolvedPostId = postId || homePage?.postId;
2765 const templateId = (0, import_data6.useSelect)(
2766 (select2) => {
2767 if (!resolvedPostType || !resolvedPostId) {
2768 return void 0;
2769 }
2770 if (resolvedPostType === "wp_template") {
2771 return resolvedPostId;
2772 }
2773 return unlock(select2(import_core_data5.store)).getTemplateId(
2774 resolvedPostType,
2775 resolvedPostId
2776 );
2777 },
2778 [resolvedPostType, resolvedPostId]
2779 );
2780 const stylesId = useStylesId({ templateId });
2781 const { isReady: settingsReady, editorSettings } = useEditorSettings({
2782 stylesId
2783 });
2784 const { isReady: assetsReady } = useEditorAssets();
2785 const finalSettings = (0, import_element4.useMemo)(
2786 () => ({
2787 ...editorSettings,
2788 ...settings
2789 }),
2790 [editorSettings, settings]
2791 );
2792 if (!settingsReady || !assetsReady) {
2793 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
2794 "div",
2795 {
2796 style: {
2797 display: "flex",
2798 justifyContent: "center",
2799 alignItems: "center",
2800 height: "100vh"
2801 },
2802 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_components.Spinner, {})
2803 }
2804 );
2805 }
2806 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
2807 PrivateEditor,
2808 {
2809 postType: resolvedPostType,
2810 postId: resolvedPostId,
2811 templateId,
2812 settings: finalSettings,
2813 styles: finalSettings.styles,
2814 children: backButton && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(BackButton, { children: backButton })
2815 }
2816 );
2817 }
2818
2819 // packages/lazy-editor/build-module/components/preview/index.mjs
2820 var import_i18n = __toESM(require_i18n(), 1);
2821 var import_element5 = __toESM(require_element(), 1);
2822 var import_block_editor = __toESM(require_block_editor(), 1);
2823 var import_editor2 = __toESM(require_editor(), 1);
2824 var import_blocks2 = __toESM(require_blocks(), 1);
2825 var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1);
2826 if (typeof document !== "undefined" && true && !document.head.querySelector("style[data-wp-hash='95327475c1']")) {
2827 const style = document.createElement("style");
2828 style.setAttribute("data-wp-hash", "95327475c1");
2829 style.appendChild(document.createTextNode(".lazy-editor-block-preview__container{align-items:center;border-radius:4px;display:flex;flex-direction:column;height:100%;justify-content:center}.dataviews-view-grid .lazy-editor-block-preview__container .block-editor-block-preview__container{height:100%}.dataviews-view-table .lazy-editor-block-preview__container{text-wrap:balance;text-wrap:pretty;flex-grow:0;width:96px}"));
2830 document.head.appendChild(style);
2831 }
2832 var { useStyle } = unlock(import_editor2.privateApis);
2833 function PreviewContent({
2834 blocks,
2835 content,
2836 description
2837 }) {
2838 const descriptionId = (0, import_element5.useId)();
2839 const backgroundColor = useStyle("color.background");
2840 const actualBlocks = (0, import_element5.useMemo)(() => {
2841 return blocks ?? (0, import_blocks2.parse)(content, {
2842 __unstableSkipMigrationLogs: true
2843 });
2844 }, [content, blocks]);
2845 const isEmpty = !actualBlocks?.length;
2846 return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
2847 "div",
2848 {
2849 className: "lazy-editor-block-preview__container",
2850 style: { backgroundColor },
2851 "aria-describedby": !!description ? descriptionId : void 0,
2852 children: [
2853 isEmpty && (0, import_i18n.__)("Empty."),
2854 !isEmpty && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_block_editor.BlockPreview.Async, { children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_block_editor.BlockPreview, { blocks: actualBlocks }) }),
2855 !!description && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { hidden: true, id: descriptionId, children: description })
2856 ]
2857 }
2858 );
2859 }
2860 function Preview({
2861 blocks,
2862 content,
2863 description
2864 }) {
2865 const stylesId = useStylesId();
2866 const { isReady: settingsReady, editorSettings } = useEditorSettings({
2867 stylesId
2868 });
2869 const { isReady: assetsReady } = useEditorAssets();
2870 const finalSettings = (0, import_element5.useMemo)(
2871 () => ({
2872 ...editorSettings,
2873 isPreviewMode: true
2874 }),
2875 [editorSettings]
2876 );
2877 if (!settingsReady || !assetsReady) {
2878 return null;
2879 }
2880 return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_block_editor.BlockEditorProvider, { settings: finalSettings, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2881 PreviewContent,
2882 {
2883 blocks,
2884 content,
2885 description
2886 }
2887 ) });
2888 }
2889 export {
2890 Editor,
2891 Preview,
2892 loadEditorAssets,
2893 useEditorAssets,
2894 useEditorSettings
2895 };
2896 //# sourceMappingURL=index.js.map
2897