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

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