PluginProbe
Gutenberg / 23.2.1
Gutenberg v23.2.1
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.2.1, at build/modules/lazy-editor/index.js

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