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

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