PluginProbe
Gutenberg / 22.7.0
Gutenberg v22.7.0
24.0.0 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 All 403 releases
gutenberg / build / modules / lazy-editor / index.js

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

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