@marvalt/wparser 0.1.22 → 0.1.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1390,7 +1390,7 @@ function renderBlock(block, registry, key, options, page) {
1390
1390
  const children = block.innerBlocks && block.innerBlocks.length
1391
1391
  ? block.innerBlocks.map((child, i) => renderBlock(child, registry, `${key}-${i}`, options, page))
1392
1392
  : undefined;
1393
- const node = Renderer({ block, children, context: { registry, page } });
1393
+ const node = Renderer({ block, children, context: { registry, page, colorMapper: registry.colorMapper } });
1394
1394
  if (options?.debugWrappers) {
1395
1395
  return (jsxRuntimeExports.jsx("div", { "data-block": block.name, className: "wp-block", children: node }, key));
1396
1396
  }
@@ -1662,98 +1662,6 @@ function extractImageUrlWithFallback(block) {
1662
1662
  return getImageUrl(block);
1663
1663
  }
1664
1664
 
1665
- /**
1666
- * Style mapping utilities
1667
- * Maps WordPress block attributes to Tailwind CSS classes
1668
- */
1669
- /**
1670
- * Map WordPress alignment to Tailwind classes
1671
- */
1672
- function getAlignmentClasses(align) {
1673
- if (!align)
1674
- return '';
1675
- switch (align) {
1676
- case 'full':
1677
- return 'w-full';
1678
- case 'wide':
1679
- return 'max-w-7xl mx-auto';
1680
- case 'center':
1681
- return 'mx-auto';
1682
- case 'left':
1683
- return 'mr-auto';
1684
- case 'right':
1685
- return 'ml-auto';
1686
- default:
1687
- return '';
1688
- }
1689
- }
1690
- /**
1691
- * Map WordPress text alignment to Tailwind classes
1692
- */
1693
- function getTextAlignClasses(textAlign) {
1694
- if (!textAlign)
1695
- return '';
1696
- switch (textAlign) {
1697
- case 'center':
1698
- return 'text-center';
1699
- case 'left':
1700
- return 'text-left';
1701
- case 'right':
1702
- return 'text-right';
1703
- default:
1704
- return '';
1705
- }
1706
- }
1707
- /**
1708
- * Map WordPress font size to Tailwind classes
1709
- */
1710
- function getFontSizeClasses(fontSize) {
1711
- if (!fontSize)
1712
- return '';
1713
- // Map WordPress font sizes to Tailwind
1714
- const sizeMap = {
1715
- 'small': 'text-sm',
1716
- 'medium': 'text-base',
1717
- 'large': 'text-lg',
1718
- 'x-large': 'text-xl',
1719
- 'xx-large': 'text-3xl',
1720
- 'xxx-large': 'text-4xl',
1721
- };
1722
- return sizeMap[fontSize] || '';
1723
- }
1724
- /**
1725
- * Get container classes based on layout and alignment
1726
- */
1727
- function getContainerClasses(align, layout) {
1728
- const alignClass = getAlignmentClasses(align);
1729
- // If layout is constrained, use container
1730
- if (layout?.type === 'constrained') {
1731
- return align === 'full' ? 'w-full' : 'container';
1732
- }
1733
- return alignClass || 'container';
1734
- }
1735
- /**
1736
- * Get spacing classes for sections
1737
- */
1738
- function getSectionSpacingClasses() {
1739
- return 'py-16 md:py-24';
1740
- }
1741
- /**
1742
- * Get content spacing classes
1743
- */
1744
- function getContentSpacingClasses() {
1745
- return 'space-y-6';
1746
- }
1747
- /**
1748
- * Build className string from multiple class sources
1749
- */
1750
- function buildClassName(...classes) {
1751
- return classes
1752
- .filter((cls) => Boolean(cls && cls.trim()))
1753
- .join(' ')
1754
- .trim();
1755
- }
1756
-
1757
1665
  /**
1758
1666
  * Cloudflare Images URL helpers for wparser package
1759
1667
  * Formats Cloudflare image URLs with variants for optimal performance
@@ -1790,702 +1698,196 @@ const getCloudflareVariantUrl = (url, options) => {
1790
1698
  return `${base}/${variant}`;
1791
1699
  };
1792
1700
 
1793
- const Paragraph = ({ block, context }) => {
1794
- const content = getBlockTextContent(block);
1701
+ /**
1702
+ * Extract background image URL from a block
1703
+ * Checks various possible sources: cloudflareUrl, url, backgroundImage, innerHTML, featured image
1704
+ */
1705
+ function extractBackgroundImage(block, page) {
1795
1706
  const attrs = block.attributes || {};
1796
- const textAlign = getTextAlignClasses(attrs['align']);
1797
- // Check if content contains shortcodes
1798
- const hasShortcodes = /\[(\w+)/.test(content);
1799
- if (hasShortcodes && context.registry.shortcodes) {
1800
- const parts = renderTextWithShortcodes(content, context.registry);
1801
- // Check if any part is a block-level element (section, div, etc.)
1802
- // If so, render without wrapping in <p> to avoid DOM nesting violations
1803
- const isBlockLevelElement = (element) => {
1804
- if (!React.isValidElement(element)) {
1805
- return false;
1806
- }
1807
- const type = element.type;
1808
- // Check for block-level HTML elements
1809
- if (typeof type === 'string' && ['section', 'div', 'article', 'header', 'footer', 'aside', 'nav'].includes(type)) {
1810
- return true;
1811
- }
1812
- // Check if it's React.Fragment - recursively check its children
1813
- if (type === React.Fragment) {
1814
- const fragmentProps = element.props;
1815
- const children = React.Children.toArray(fragmentProps.children);
1816
- return children.some((child) => isBlockLevelElement(child));
1817
- }
1818
- // Check if it's a React component (likely block-level)
1819
- // Most custom components render block-level content
1820
- if (typeof type === 'function' || (typeof type === 'object' && type !== null && type !== React.Fragment)) {
1821
- return true;
1822
- }
1823
- return false;
1824
- };
1825
- const hasBlockLevelContent = React.Children.toArray(parts).some((part) => isBlockLevelElement(part));
1826
- if (hasBlockLevelContent) {
1827
- // Render block-level content without <p> wrapper
1828
- return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: parts });
1829
- }
1830
- return jsxRuntimeExports.jsx("p", { className: buildClassName('text-gray-700', textAlign), children: parts });
1707
+ // Check if block uses featured image
1708
+ if (attrs['useFeaturedImage'] === true && page?._embedded?.['wp:featuredmedia']?.[0]?.source_url) {
1709
+ return page._embedded['wp:featuredmedia'][0].source_url;
1831
1710
  }
1832
- return jsxRuntimeExports.jsx("p", { className: buildClassName('text-gray-700', textAlign), children: content });
1833
- };
1834
- const Heading = ({ block, children }) => {
1711
+ // Use the improved extraction function that handles incomplete cloudflareUrl
1712
+ // This will check cloudflareUrl first, then innerHTML, then regular attributes
1713
+ return extractImageUrlWithFallback(block);
1714
+ }
1715
+ /**
1716
+ * Extract image URL from a block
1717
+ * Returns Cloudflare URL if available, otherwise WordPress URL
1718
+ */
1719
+ function extractImageUrl(block) {
1720
+ // Use the improved extraction function that handles incomplete cloudflareUrl
1721
+ return extractImageUrlWithFallback(block);
1722
+ }
1723
+ /**
1724
+ * Extract image attributes (url, alt, width, height)
1725
+ */
1726
+ function extractImageAttributes(block) {
1727
+ return getImageAttributes(block);
1728
+ }
1729
+ /**
1730
+ * Extract title/heading text from a block
1731
+ */
1732
+ function extractTitle(block) {
1835
1733
  const attrs = block.attributes || {};
1836
- const { level = 2 } = attrs;
1837
- const content = getBlockTextContent(block);
1838
- const textAlign = getTextAlignClasses(attrs['textAlign']);
1839
- const fontSize = getFontSizeClasses(attrs['fontSize']);
1840
- const Tag = `h${Math.min(Math.max(Number(level) || 2, 1), 6)}`;
1841
- // Default heading sizes if fontSize not specified
1842
- const sizeClass = fontSize || (level === 1 ? 'text-4xl' : level === 2 ? 'text-3xl' : level === 3 ? 'text-2xl' : 'text-xl');
1843
- return (jsxRuntimeExports.jsx(Tag, { className: buildClassName('font-bold text-gray-900', sizeClass, textAlign), children: children ?? content }));
1844
- };
1845
- const Image = ({ block }) => {
1846
- const imageAttrs = getImageAttributes(block);
1847
- if (!imageAttrs.url)
1848
- return null;
1849
- // Use Cloudflare variant URL if it's a Cloudflare image
1850
- let imageUrl = imageAttrs.url;
1851
- if (isCloudflareImageUrl(imageUrl)) {
1852
- const width = imageAttrs.width || 1024;
1853
- const height = imageAttrs.height;
1854
- imageUrl = getCloudflareVariantUrl(imageUrl, { width, height });
1855
- }
1856
- return (jsxRuntimeExports.jsx("img", { src: imageUrl, alt: imageAttrs.alt, width: imageAttrs.width, height: imageAttrs.height, className: "w-full h-auto max-w-full object-contain rounded-lg", loading: "lazy" }));
1857
- };
1858
- const List = ({ block, children }) => {
1734
+ const title = attrs['title'] || attrs['content'] || getBlockTextContent(block);
1735
+ return typeof title === 'string' ? title.trim() : null;
1736
+ }
1737
+ /**
1738
+ * Extract content/text from a block
1739
+ * Returns React node for rendering
1740
+ */
1741
+ function extractContent(block, context) {
1742
+ const text = getBlockTextContent(block);
1743
+ return text || null;
1744
+ }
1745
+ /**
1746
+ * Extract media position from media-text block
1747
+ */
1748
+ function extractMediaPosition(block) {
1859
1749
  const attrs = block.attributes || {};
1860
- const { ordered } = attrs;
1861
- const Tag = ordered ? 'ol' : 'ul';
1862
- return React.createElement(Tag, { className: 'list-disc pl-6 space-y-2 text-gray-700' }, children);
1863
- };
1864
- const ListItem = ({ children }) => {
1865
- return jsxRuntimeExports.jsx("li", { className: "text-gray-700", children: children });
1866
- };
1867
- const Group = ({ block, children }) => {
1750
+ const position = attrs['mediaPosition'] || 'left';
1751
+ return position === 'right' ? 'right' : 'left';
1752
+ }
1753
+ /**
1754
+ * Extract vertical alignment from block
1755
+ */
1756
+ function extractVerticalAlignment(block) {
1868
1757
  const attrs = block.attributes || {};
1869
- const align = attrs['align'];
1870
- // Layout can be an object with type property, or nested structure
1871
- const layout = attrs['layout'];
1872
- // Determine if this is a section-level group (has alignment) or content-level
1873
- const isSection = align === 'full' || align === 'wide';
1874
- const containerClass = getContainerClasses(align, layout);
1875
- const spacingClass = isSection ? getSectionSpacingClasses() : getContentSpacingClasses();
1876
- // Ensure container class is always applied for constrained groups
1877
- const finalContainerClass = layout?.type === 'constrained' && align === 'wide'
1878
- ? 'container'
1879
- : containerClass;
1880
- return (jsxRuntimeExports.jsx("div", { className: buildClassName(finalContainerClass, spacingClass), children: children }));
1881
- };
1882
- const Columns = ({ block, children }) => {
1758
+ const alignment = attrs['verticalAlignment'] || 'center';
1759
+ if (alignment === 'top' || alignment === 'bottom') {
1760
+ return alignment;
1761
+ }
1762
+ return 'center';
1763
+ }
1764
+ /**
1765
+ * Extract alignment (full, wide, contained) from block
1766
+ */
1767
+ function extractAlignment(block) {
1883
1768
  const attrs = block.attributes || {};
1884
1769
  const align = attrs['align'];
1885
- const alignClass = getAlignmentClasses(align);
1886
- return (jsxRuntimeExports.jsx("div", { className: buildClassName('grid grid-cols-1 md:grid-cols-2 gap-6 lg:gap-12', alignClass), children: children }));
1887
- };
1888
- const Column = ({ block, children }) => {
1770
+ if (align === 'full' || align === 'wide') {
1771
+ return align;
1772
+ }
1773
+ return 'contained';
1774
+ }
1775
+ /**
1776
+ * Extract overlay color from cover block
1777
+ */
1778
+ function extractOverlayColor(block) {
1889
1779
  const attrs = block.attributes || {};
1890
- const width = attrs['width'];
1891
- // Handle column width (e.g., "50%" becomes flex-basis)
1892
- const style = width ? { flexBasis: width } : undefined;
1893
- return (jsxRuntimeExports.jsx("div", { className: "space-y-4", style: style, children: children }));
1894
- };
1895
- const Separator = () => jsxRuntimeExports.jsx("hr", { className: "border-gray-200 my-8" });
1896
- const ButtonBlock = ({ block }) => {
1897
- const attrs = block.attributes || {};
1898
- let url = attrs['url'];
1899
- let text = attrs['text'];
1900
- attrs['linkDestination'];
1901
- // Extract from innerHTML if not in attributes (buttons often store data in innerHTML)
1902
- if (!url && block.innerHTML) {
1903
- const linkMatch = block.innerHTML.match(/<a[^>]+href=["']([^"']+)["'][^>]*>([^<]+)<\/a>/i);
1904
- if (linkMatch) {
1905
- url = linkMatch[1];
1906
- text = linkMatch[2] || text;
1907
- }
1908
- }
1909
- // Get text from block content if still missing
1910
- if (!text) {
1911
- text = getBlockTextContent(block);
1780
+ const overlayColor = attrs['overlayColor'];
1781
+ if (typeof overlayColor === 'string') {
1782
+ return overlayColor;
1912
1783
  }
1913
- if (!url && !text)
1914
- return null;
1915
- const buttonText = text || 'Learn more';
1916
- // Handle internal vs external links
1917
- const isExternal = url && (url.startsWith('http://') || url.startsWith('https://'));
1918
- const linkProps = isExternal ? { target: '_blank', rel: 'noopener noreferrer' } : {};
1919
- return (jsxRuntimeExports.jsx("a", { href: url || '#', className: "inline-flex items-center justify-center rounded-md bg-primary px-6 py-3 text-primary-foreground font-medium hover:bg-primary/90 transition-colors", ...linkProps, children: buttonText }));
1920
- };
1921
- const Cover = ({ block, children }) => {
1784
+ return null;
1785
+ }
1786
+ /**
1787
+ * Extract dim ratio (overlay opacity) from cover block
1788
+ */
1789
+ function extractDimRatio(block) {
1922
1790
  const attrs = block.attributes || {};
1923
- const { url, id, backgroundImage, cloudflareUrl, overlayColor, dimRatio = 0, align = 'full', minHeight, minHeightUnit = 'vh', hasParallax, } = attrs;
1924
- // Get background image URL from various possible sources
1925
- // Use the improved extraction function that handles incomplete cloudflareUrl
1926
- let bgImageUrl = null;
1927
- // First, try cloudflareUrl if it's valid
1928
- if (cloudflareUrl && isValidCloudflareUrl(cloudflareUrl)) {
1929
- bgImageUrl = cloudflareUrl;
1930
- }
1931
- // If not valid or not found, try regular attributes
1932
- if (!bgImageUrl) {
1933
- bgImageUrl = url || backgroundImage || (typeof backgroundImage === 'object' && backgroundImage?.url) || null;
1934
- }
1935
- // If still not found, use the fallback extraction (from innerHTML)
1936
- if (!bgImageUrl) {
1937
- bgImageUrl = extractImageUrlWithFallback(block);
1938
- }
1939
- // Convert to Cloudflare URL variant if it's a Cloudflare image
1940
- if (bgImageUrl) {
1941
- if (isCloudflareImageUrl(bgImageUrl)) {
1942
- // Use full width for cover images
1943
- bgImageUrl = getCloudflareVariantUrl(bgImageUrl, { width: 1920 });
1944
- }
1945
- }
1946
- // Build alignment classes
1947
- const alignClass = getAlignmentClasses(align);
1948
- // Build style object
1949
- const style = {};
1950
- if (minHeight) {
1951
- const minHeightValue = typeof minHeight === 'number' ? minHeight : parseFloat(String(minHeight));
1952
- style.minHeight = minHeightUnit === 'vh' ? `${minHeightValue}vh` : `${minHeightValue}px`;
1953
- }
1954
- if (bgImageUrl) {
1955
- style.backgroundImage = `url(${bgImageUrl})`;
1956
- style.backgroundSize = 'cover';
1957
- style.backgroundPosition = 'center';
1958
- if (hasParallax) {
1959
- style.backgroundAttachment = 'fixed';
1960
- }
1791
+ const dimRatio = attrs['dimRatio'];
1792
+ if (typeof dimRatio === 'number') {
1793
+ return dimRatio;
1961
1794
  }
1962
- // Calculate overlay opacity
1963
- const overlayOpacity = typeof dimRatio === 'number' ? dimRatio / 100 : 0;
1964
- return (jsxRuntimeExports.jsxs("div", { className: buildClassName('relative w-full', alignClass), style: style, children: [overlayOpacity > 0 && (jsxRuntimeExports.jsx("span", { className: "absolute inset-0 z-0", style: {
1965
- backgroundColor: overlayColor === 'contrast' ? '#000000' : (overlayColor || '#000000'),
1966
- opacity: overlayOpacity,
1967
- }, "aria-hidden": "true" })), jsxRuntimeExports.jsx("div", { className: buildClassName('relative z-10', align === 'full' ? 'w-full' : 'container mx-auto px-4'), children: children })] }));
1968
- };
1969
- const MediaText = ({ block, children, context }) => {
1795
+ return 0;
1796
+ }
1797
+ /**
1798
+ * Extract min height from block
1799
+ */
1800
+ function extractMinHeight(block) {
1970
1801
  const attrs = block.attributes || {};
1971
- const { mediaPosition = 'left', verticalAlignment = 'center', imageFill = false, align, } = attrs;
1972
- // Access innerBlocks to identify media vs content
1973
- const innerBlocks = block.innerBlocks || [];
1974
- // Find media block (image or video)
1975
- let mediaBlockIndex = innerBlocks.findIndex((b) => b.name === 'core/image' || b.name === 'core/video');
1976
- // Render children - media-text typically has media as first child, then content
1977
- const childrenArray = React.Children.toArray(children);
1978
- let mediaElement = mediaBlockIndex >= 0 && childrenArray[mediaBlockIndex]
1979
- ? childrenArray[mediaBlockIndex]
1980
- : null;
1981
- // If no media element from innerBlocks, try to extract image URL
1982
- if (!mediaElement) {
1983
- const imageUrl = extractImageUrlWithFallback(block);
1984
- if (imageUrl) {
1985
- // Convert to Cloudflare variant if it's a Cloudflare URL
1986
- const finalImageUrl = isCloudflareImageUrl(imageUrl)
1987
- ? getCloudflareVariantUrl(imageUrl, { width: 1024 })
1988
- : imageUrl;
1989
- mediaElement = (jsxRuntimeExports.jsx("img", { src: finalImageUrl, alt: "", className: "w-full h-auto max-w-full rounded-lg shadow-lg object-contain", loading: "lazy" }));
1990
- }
1991
- }
1992
- // Content is all other children
1993
- const contentElements = childrenArray.filter((_, index) => index !== mediaBlockIndex);
1994
- // Build alignment classes - ensure proper container width
1995
- // For 'wide', media-text blocks are typically inside constrained groups (which use 'container' class)
1996
- // So we should use 'w-full' to fill the parent container, not apply another max-width
1997
- // Only use 'max-w-7xl' for truly standalone wide blocks (rare case)
1998
- let alignClass;
1999
- let spacingClass;
2000
- if (align === 'full') {
2001
- alignClass = 'w-full';
2002
- // Full-width blocks are typically top-level sections, so add section spacing
2003
- spacingClass = getSectionSpacingClasses();
2004
- }
2005
- else if (align === 'wide') {
2006
- // Wide blocks are usually inside constrained groups (which already have container and spacing)
2007
- // So just fill the parent container without adding section spacing
2008
- alignClass = 'w-full';
2009
- spacingClass = ''; // No section spacing - parent group handles it
2010
- }
2011
- else {
2012
- // Default to contained width (not full width)
2013
- alignClass = 'container mx-auto';
2014
- // Contained blocks might be standalone, so add section spacing
2015
- spacingClass = getSectionSpacingClasses();
1802
+ const minHeight = attrs['minHeight'];
1803
+ const minHeightUnit = attrs['minHeightUnit'] || 'vh';
1804
+ if (typeof minHeight === 'number') {
1805
+ return { value: minHeight, unit: minHeightUnit };
2016
1806
  }
2017
- // Vertical alignment classes
2018
- const verticalAlignClass = verticalAlignment === 'top' ? 'items-start' :
2019
- verticalAlignment === 'bottom' ? 'items-end' :
2020
- 'items-center';
2021
- // Stack on mobile
2022
- const stackClass = 'flex-col md:flex-row';
2023
- // Media position determines order
2024
- const isMediaRight = mediaPosition === 'right';
2025
- return (jsxRuntimeExports.jsx("div", { className: buildClassName(alignClass, spacingClass), children: jsxRuntimeExports.jsxs("div", { className: buildClassName('flex', stackClass, verticalAlignClass, 'gap-6 lg:gap-12'), children: [jsxRuntimeExports.jsx("div", { className: buildClassName(isMediaRight ? 'order-2' : 'order-1', imageFill ? 'w-full md:w-1/2' : 'flex-shrink-0 md:w-1/2', 'overflow-hidden', // Ensure images don't overflow
2026
- 'max-w-full' // Ensure section doesn't exceed container
2027
- ), children: mediaElement || jsxRuntimeExports.jsx("div", { className: "bg-gray-200 h-64 rounded-lg" }) }), jsxRuntimeExports.jsx("div", { className: buildClassName(isMediaRight ? 'order-1' : 'order-2', 'w-full md:w-1/2', // Explicit width to ensure proper sizing
2028
- 'flex-shrink-0', // Prevent content from shrinking
2029
- getContentSpacingClasses()), children: contentElements.length > 0 ? contentElements : children })] }) }));
2030
- };
2031
- const Fallback = ({ block, children }) => {
2032
- // Minimal fallback; do not render innerHTML directly in v1 for safety
2033
- return jsxRuntimeExports.jsx("div", { "data-unknown-block": block.name, children: children });
2034
- };
2035
- function createDefaultRegistry() {
2036
- const renderers = {
2037
- 'core/paragraph': Paragraph,
2038
- 'core/heading': Heading,
2039
- 'core/image': Image,
2040
- 'core/list': List,
2041
- 'core/list-item': ListItem,
2042
- 'core/group': Group,
2043
- 'core/columns': Columns,
2044
- 'core/column': Column,
2045
- 'core/separator': Separator,
2046
- 'core/button': ButtonBlock,
2047
- 'core/buttons': ({ block, children }) => {
2048
- const attrs = block.attributes || {};
2049
- const layout = attrs['layout'];
2050
- const justifyContent = layout?.justifyContent || 'left';
2051
- const justifyClass = justifyContent === 'center' ? 'justify-center' :
2052
- justifyContent === 'right' ? 'justify-end' :
2053
- 'justify-start';
2054
- return jsxRuntimeExports.jsx("div", { className: buildClassName('flex flex-wrap gap-3', justifyClass), children: children });
2055
- },
2056
- 'core/quote': ({ children }) => jsxRuntimeExports.jsx("blockquote", { className: "border-l-4 pl-4 italic", children: children }),
2057
- 'core/code': ({ block }) => (jsxRuntimeExports.jsx("pre", { className: "bg-gray-100 p-3 rounded text-sm overflow-auto", children: jsxRuntimeExports.jsx("code", { children: getString(block) }) })),
2058
- 'core/preformatted': ({ block }) => jsxRuntimeExports.jsx("pre", { children: getString(block) }),
2059
- 'core/table': ({ children }) => jsxRuntimeExports.jsx("div", { className: "overflow-x-auto", children: jsxRuntimeExports.jsx("table", { className: "table-auto w-full", children: children }) }),
2060
- 'core/table-row': ({ children }) => jsxRuntimeExports.jsx("tr", { children: children }),
2061
- 'core/table-cell': ({ children }) => jsxRuntimeExports.jsx("td", { className: "border px-3 py-2", children: children }),
2062
- // Cover block - hero sections with background images
2063
- 'core/cover': Cover,
2064
- // Media & Text block - side-by-side media and content
2065
- 'core/media-text': MediaText,
2066
- // HTML block - render innerHTML as-is
2067
- // Note: Shortcodes in HTML blocks are not parsed (they would need to be in text content)
2068
- 'core/html': ({ block }) => {
2069
- const html = block.innerHTML || '';
2070
- return jsxRuntimeExports.jsx("div", { dangerouslySetInnerHTML: { __html: html } });
2071
- },
2072
- };
2073
- return {
2074
- renderers,
2075
- shortcodes: {}, // Empty by default - apps extend this
2076
- fallback: Fallback,
2077
- };
2078
- }
2079
- // Legacy function for backward compatibility - use getBlockTextContent instead
2080
- function getString(block) {
2081
- return getBlockTextContent(block);
1807
+ return null;
2082
1808
  }
2083
-
2084
1809
  /**
2085
- * Check if a block matches a pattern
1810
+ * Extract heading level from heading block
2086
1811
  */
2087
- function matchesPattern(block, pattern) {
2088
- // Check block name
2089
- if (block.name !== pattern.name) {
2090
- return false;
2091
- }
2092
- // Check attributes if specified
2093
- if (pattern.attributes) {
2094
- const blockAttrs = block.attributes || {};
2095
- for (const [key, value] of Object.entries(pattern.attributes)) {
2096
- if (blockAttrs[key] !== value) {
2097
- return false;
2098
- }
2099
- }
2100
- }
2101
- // Check innerBlocks patterns if specified
2102
- if (pattern.innerBlocks && pattern.innerBlocks.length > 0) {
2103
- const blockInnerBlocks = block.innerBlocks || [];
2104
- // If pattern specifies innerBlocks, check if block has matching innerBlocks
2105
- for (const innerPattern of pattern.innerBlocks) {
2106
- // Find at least one matching innerBlock
2107
- const hasMatch = blockInnerBlocks.some(innerBlock => matchesPattern(innerBlock, innerPattern));
2108
- if (!hasMatch) {
2109
- return false;
2110
- }
2111
- }
1812
+ function extractHeadingLevel(block) {
1813
+ const attrs = block.attributes || {};
1814
+ const level = attrs['level'];
1815
+ if (typeof level === 'number' && level >= 1 && level <= 6) {
1816
+ return level;
2112
1817
  }
2113
- return true;
1818
+ return 2; // Default to h2
2114
1819
  }
2115
1820
  /**
2116
- * Find the best matching component mapping for a block
2117
- * Returns the mapping with highest priority that matches, or null
1821
+ * Extract text alignment from block
2118
1822
  */
2119
- function findMatchingMapping(block, mappings) {
2120
- // Sort by priority (higher first), then by order in array
2121
- const sortedMappings = [...mappings].sort((a, b) => {
2122
- const priorityA = a.priority ?? 0;
2123
- const priorityB = b.priority ?? 0;
2124
- if (priorityA !== priorityB) {
2125
- return priorityB - priorityA; // Higher priority first
2126
- }
2127
- return 0; // Keep original order for same priority
2128
- });
2129
- // Find first matching mapping
2130
- for (const mapping of sortedMappings) {
2131
- if (matchesPattern(block, mapping.pattern)) {
2132
- return mapping;
2133
- }
1823
+ function extractTextAlign(block) {
1824
+ const attrs = block.attributes || {};
1825
+ const align = attrs['align'] || attrs['textAlign'];
1826
+ if (align === 'left' || align === 'center' || align === 'right') {
1827
+ return align;
2134
1828
  }
2135
1829
  return null;
2136
1830
  }
2137
-
2138
1831
  /**
2139
- * Create an enhanced registry that supports pattern-based component mapping
2140
- *
2141
- * This combines the default registry (for fallback) with app-specific component mappings.
2142
- * When a block matches a pattern, it uses the mapped component. Otherwise, it falls back
2143
- * to the default renderer.
2144
- *
2145
- * @param mappings - Array of component mappings with patterns
2146
- * @param baseRegistry - Optional base registry (defaults to createDefaultRegistry())
2147
- * @returns Enhanced registry with pattern matching capabilities
2148
- *
2149
- * @example
2150
- * ```ts
2151
- * const mappings: ComponentMapping[] = [
2152
- * {
2153
- * pattern: { name: 'core/cover' },
2154
- * component: HomeHeroSection,
2155
- * extractProps: (block) => ({
2156
- * backgroundImage: extractBackgroundImage(block),
2157
- * title: extractTitle(block),
2158
- * }),
2159
- * wrapper: SectionWrapper,
2160
- * },
2161
- * ];
2162
- *
2163
- * const registry = createEnhancedRegistry(mappings);
2164
- * ```
1832
+ * Extract font size from block
2165
1833
  */
2166
- function createEnhancedRegistry(mappings = [], baseRegistry) {
2167
- const base = baseRegistry || createDefaultRegistry();
2168
- // Create enhanced renderers that check patterns first
2169
- const enhancedRenderers = {
2170
- ...base.renderers,
2171
- };
2172
- // Override renderers for blocks that have mappings
2173
- // We need to check patterns at render time, so we create a wrapper renderer
2174
- const createPatternRenderer = (blockName) => {
2175
- return (props) => {
2176
- const { block, context } = props;
2177
- // Find matching mapping
2178
- const mapping = findMatchingMapping(block, mappings);
2179
- if (mapping) {
2180
- // Extract props from block
2181
- const componentProps = mapping.extractProps(block, context);
2182
- // Render component
2183
- const Component = mapping.component;
2184
- const content = jsxRuntimeExports.jsx(Component, { ...componentProps });
2185
- // Wrap with wrapper if provided
2186
- if (mapping.wrapper) {
2187
- const Wrapper = mapping.wrapper;
2188
- return jsxRuntimeExports.jsx(Wrapper, { block: block, children: content });
2189
- }
2190
- return content;
2191
- }
2192
- // Fall back to default renderer
2193
- const defaultRenderer = base.renderers[blockName] || base.fallback;
2194
- return defaultRenderer(props);
2195
- };
2196
- };
2197
- // For each mapping, override the renderer for that block name
2198
- for (const mapping of mappings) {
2199
- const blockName = mapping.pattern.name;
2200
- if (blockName) {
2201
- enhancedRenderers[blockName] = createPatternRenderer(blockName);
2202
- }
2203
- }
2204
- // Create matchBlock function
2205
- const matchBlock = (block) => {
2206
- return findMatchingMapping(block, mappings);
2207
- };
2208
- return {
2209
- ...base,
2210
- renderers: enhancedRenderers,
2211
- mappings,
2212
- matchBlock,
2213
- };
1834
+ function extractFontSize(block) {
1835
+ const attrs = block.attributes || {};
1836
+ const fontSize = attrs['fontSize'];
1837
+ return typeof fontSize === 'string' ? fontSize : null;
2214
1838
  }
2215
-
2216
- const WPContent = ({ blocks, registry, className, page }) => {
2217
- if (!Array.isArray(blocks)) {
2218
- if (process.env.NODE_ENV !== 'production') {
2219
- // eslint-disable-next-line no-console
2220
- console.warn('WPContent: invalid blocks prop');
2221
- }
2222
- return null;
2223
- }
2224
- if (!registry || !registry.renderers) {
2225
- throw new Error('WPContent: registry is required');
2226
- }
2227
- const ast = parseGutenbergBlocks(blocks);
2228
- return (jsxRuntimeExports.jsx("div", { className: className, children: renderNodes(ast, registry, undefined, page) }));
2229
- };
2230
-
2231
1839
  /**
2232
- * Hero logic:
2233
- * - If the content contains a [HEROSECTION] shortcode (case-insensitive), do NOT auto-hero.
2234
- * - Else, if the page has featured media, render a hero section using the image as background.
1840
+ * Convert image URL to Cloudflare variant if it's a Cloudflare URL
2235
1841
  */
2236
- const WPPage = ({ page, registry, className }) => {
2237
- if (!page || !Array.isArray(page.blocks)) {
2238
- if (process.env.NODE_ENV !== 'production') {
2239
- // eslint-disable-next-line no-console
2240
- console.warn('WPPage: invalid page prop');
2241
- }
2242
- return null;
2243
- }
2244
- if (!registry || !registry.renderers) {
2245
- throw new Error('WPPage: registry is required');
2246
- }
2247
- const hasHeroShortcode = React.useMemo(() => detectHeroShortcode(page.blocks), [page.blocks]);
2248
- const featured = getFeaturedImage(page);
2249
- return (jsxRuntimeExports.jsxs("article", { className: className, children: [!hasHeroShortcode && featured && (jsxRuntimeExports.jsx(HeroFromFeatured, { featured: featured, title: page.title?.rendered })), jsxRuntimeExports.jsx(WPContent, { blocks: page.blocks, registry: registry, page: page })] }));
2250
- };
2251
- function detectHeroShortcode(blocks) {
2252
- for (const block of blocks) {
2253
- const html = (block.innerHTML || '').toLowerCase();
2254
- if (html.includes('[herosection]'))
2255
- return true;
2256
- // Check if this is a cover block (which is a hero section)
2257
- if (block.name === 'core/cover')
2258
- return true;
2259
- if (block.innerBlocks?.length && detectHeroShortcode(block.innerBlocks))
2260
- return true;
2261
- }
2262
- return false;
2263
- }
2264
- function getFeaturedImage(page) {
2265
- const fm = page._embedded?.['wp:featuredmedia'];
2266
- if (Array.isArray(fm) && fm.length > 0)
2267
- return fm[0];
2268
- return null;
2269
- }
2270
- const HeroFromFeatured = ({ featured, title }) => {
2271
- const url = featured.source_url;
1842
+ function convertImageToCloudflareVariant(url, options = {}) {
2272
1843
  if (!url)
2273
1844
  return null;
2274
- return (jsxRuntimeExports.jsx("section", { className: "w-full h-[40vh] min-h-[280px] flex items-end bg-cover bg-center", style: { backgroundImage: `url(${url})` }, "aria-label": featured.alt_text || title || 'Hero', children: jsxRuntimeExports.jsx("div", { className: "container mx-auto px-4 py-8 bg-gradient-to-t from-black/50 to-transparent w-full", children: title && jsxRuntimeExports.jsx("h1", { className: "text-white text-4xl font-bold drop-shadow", children: title }) }) }));
2275
- };
2276
-
2277
- class WPErrorBoundary extends React.Component {
2278
- constructor(props) {
2279
- super(props);
2280
- this.state = { hasError: false };
2281
- }
2282
- static getDerivedStateFromError() {
2283
- return { hasError: true };
2284
- }
2285
- componentDidCatch(error) {
2286
- if (process.env.NODE_ENV !== 'production') {
2287
- // eslint-disable-next-line no-console
2288
- console.error('WPErrorBoundary caught error:', error);
2289
- }
2290
- }
2291
- render() {
2292
- if (this.state.hasError) {
2293
- return this.props.fallback ?? null;
2294
- }
2295
- return this.props.children;
1845
+ if (isCloudflareImageUrl(url)) {
1846
+ const width = options.width || 1024;
1847
+ const height = options.height;
1848
+ return getCloudflareVariantUrl(url, { width, height });
2296
1849
  }
1850
+ return url;
2297
1851
  }
2298
-
2299
1852
  /**
2300
- * Extract background image URL from a block
2301
- * Checks various possible sources: cloudflareUrl, url, backgroundImage, innerHTML, featured image
1853
+ * Extract title from innerBlocks (finds first heading block)
2302
1854
  */
2303
- function extractBackgroundImage(block, page) {
2304
- const attrs = block.attributes || {};
2305
- // Check if block uses featured image
2306
- if (attrs['useFeaturedImage'] === true && page?._embedded?.['wp:featuredmedia']?.[0]?.source_url) {
2307
- return page._embedded['wp:featuredmedia'][0].source_url;
1855
+ function extractTitleFromInnerBlocks(block) {
1856
+ const innerBlocks = block.innerBlocks || [];
1857
+ // Recursively search for heading blocks
1858
+ for (const innerBlock of innerBlocks) {
1859
+ if (innerBlock.name === 'core/heading') {
1860
+ return getBlockTextContent(innerBlock);
1861
+ }
1862
+ // Recursively search nested blocks
1863
+ const nestedTitle = extractTitleFromInnerBlocks(innerBlock);
1864
+ if (nestedTitle)
1865
+ return nestedTitle;
2308
1866
  }
2309
- // Use the improved extraction function that handles incomplete cloudflareUrl
2310
- // This will check cloudflareUrl first, then innerHTML, then regular attributes
2311
- return extractImageUrlWithFallback(block);
2312
- }
2313
- /**
2314
- * Extract image URL from a block
2315
- * Returns Cloudflare URL if available, otherwise WordPress URL
2316
- */
2317
- function extractImageUrl(block) {
2318
- // Use the improved extraction function that handles incomplete cloudflareUrl
2319
- return extractImageUrlWithFallback(block);
2320
- }
2321
- /**
2322
- * Extract image attributes (url, alt, width, height)
2323
- */
2324
- function extractImageAttributes(block) {
2325
- return getImageAttributes(block);
2326
- }
2327
- /**
2328
- * Extract title/heading text from a block
2329
- */
2330
- function extractTitle(block) {
2331
- const attrs = block.attributes || {};
2332
- const title = attrs['title'] || attrs['content'] || getBlockTextContent(block);
2333
- return typeof title === 'string' ? title.trim() : null;
2334
- }
2335
- /**
2336
- * Extract content/text from a block
2337
- * Returns React node for rendering
2338
- */
2339
- function extractContent(block, context) {
2340
- const text = getBlockTextContent(block);
2341
- return text || null;
2342
- }
2343
- /**
2344
- * Extract media position from media-text block
2345
- */
2346
- function extractMediaPosition(block) {
2347
- const attrs = block.attributes || {};
2348
- const position = attrs['mediaPosition'] || 'left';
2349
- return position === 'right' ? 'right' : 'left';
1867
+ return null;
2350
1868
  }
2351
1869
  /**
2352
- * Extract vertical alignment from block
1870
+ * Extract subtitle/description from innerBlocks (finds first paragraph block)
2353
1871
  */
2354
- function extractVerticalAlignment(block) {
2355
- const attrs = block.attributes || {};
2356
- const alignment = attrs['verticalAlignment'] || 'center';
2357
- if (alignment === 'top' || alignment === 'bottom') {
2358
- return alignment;
1872
+ function extractSubtitleFromInnerBlocks(block) {
1873
+ const innerBlocks = block.innerBlocks || [];
1874
+ // Recursively search for paragraph blocks
1875
+ for (const innerBlock of innerBlocks) {
1876
+ if (innerBlock.name === 'core/paragraph') {
1877
+ const text = getBlockTextContent(innerBlock);
1878
+ if (text && text.trim()) {
1879
+ return text;
1880
+ }
1881
+ }
1882
+ // Recursively search nested blocks
1883
+ const nestedSubtitle = extractSubtitleFromInnerBlocks(innerBlock);
1884
+ if (nestedSubtitle)
1885
+ return nestedSubtitle;
2359
1886
  }
2360
- return 'center';
1887
+ return null;
2361
1888
  }
2362
1889
  /**
2363
- * Extract alignment (full, wide, contained) from block
2364
- */
2365
- function extractAlignment(block) {
2366
- const attrs = block.attributes || {};
2367
- const align = attrs['align'];
2368
- if (align === 'full' || align === 'wide') {
2369
- return align;
2370
- }
2371
- return 'contained';
2372
- }
2373
- /**
2374
- * Extract overlay color from cover block
2375
- */
2376
- function extractOverlayColor(block) {
2377
- const attrs = block.attributes || {};
2378
- const overlayColor = attrs['overlayColor'];
2379
- if (typeof overlayColor === 'string') {
2380
- return overlayColor;
2381
- }
2382
- return null;
2383
- }
2384
- /**
2385
- * Extract dim ratio (overlay opacity) from cover block
2386
- */
2387
- function extractDimRatio(block) {
2388
- const attrs = block.attributes || {};
2389
- const dimRatio = attrs['dimRatio'];
2390
- if (typeof dimRatio === 'number') {
2391
- return dimRatio;
2392
- }
2393
- return 0;
2394
- }
2395
- /**
2396
- * Extract min height from block
2397
- */
2398
- function extractMinHeight(block) {
2399
- const attrs = block.attributes || {};
2400
- const minHeight = attrs['minHeight'];
2401
- const minHeightUnit = attrs['minHeightUnit'] || 'vh';
2402
- if (typeof minHeight === 'number') {
2403
- return { value: minHeight, unit: minHeightUnit };
2404
- }
2405
- return null;
2406
- }
2407
- /**
2408
- * Extract heading level from heading block
2409
- */
2410
- function extractHeadingLevel(block) {
2411
- const attrs = block.attributes || {};
2412
- const level = attrs['level'];
2413
- if (typeof level === 'number' && level >= 1 && level <= 6) {
2414
- return level;
2415
- }
2416
- return 2; // Default to h2
2417
- }
2418
- /**
2419
- * Extract text alignment from block
2420
- */
2421
- function extractTextAlign(block) {
2422
- const attrs = block.attributes || {};
2423
- const align = attrs['align'] || attrs['textAlign'];
2424
- if (align === 'left' || align === 'center' || align === 'right') {
2425
- return align;
2426
- }
2427
- return null;
2428
- }
2429
- /**
2430
- * Extract font size from block
2431
- */
2432
- function extractFontSize(block) {
2433
- const attrs = block.attributes || {};
2434
- const fontSize = attrs['fontSize'];
2435
- return typeof fontSize === 'string' ? fontSize : null;
2436
- }
2437
- /**
2438
- * Convert image URL to Cloudflare variant if it's a Cloudflare URL
2439
- */
2440
- function convertImageToCloudflareVariant(url, options = {}) {
2441
- if (!url)
2442
- return null;
2443
- if (isCloudflareImageUrl(url)) {
2444
- const width = options.width || 1024;
2445
- const height = options.height;
2446
- return getCloudflareVariantUrl(url, { width, height });
2447
- }
2448
- return url;
2449
- }
2450
- /**
2451
- * Extract title from innerBlocks (finds first heading block)
2452
- */
2453
- function extractTitleFromInnerBlocks(block) {
2454
- const innerBlocks = block.innerBlocks || [];
2455
- // Recursively search for heading blocks
2456
- for (const innerBlock of innerBlocks) {
2457
- if (innerBlock.name === 'core/heading') {
2458
- return getBlockTextContent(innerBlock);
2459
- }
2460
- // Recursively search nested blocks
2461
- const nestedTitle = extractTitleFromInnerBlocks(innerBlock);
2462
- if (nestedTitle)
2463
- return nestedTitle;
2464
- }
2465
- return null;
2466
- }
2467
- /**
2468
- * Extract subtitle/description from innerBlocks (finds first paragraph block)
2469
- */
2470
- function extractSubtitleFromInnerBlocks(block) {
2471
- const innerBlocks = block.innerBlocks || [];
2472
- // Recursively search for paragraph blocks
2473
- for (const innerBlock of innerBlocks) {
2474
- if (innerBlock.name === 'core/paragraph') {
2475
- const text = getBlockTextContent(innerBlock);
2476
- if (text && text.trim()) {
2477
- return text;
2478
- }
2479
- }
2480
- // Recursively search nested blocks
2481
- const nestedSubtitle = extractSubtitleFromInnerBlocks(innerBlock);
2482
- if (nestedSubtitle)
2483
- return nestedSubtitle;
2484
- }
2485
- return null;
2486
- }
2487
- /**
2488
- * Extract buttons from innerBlocks (finds buttons block and extracts button data)
1890
+ * Extract buttons from innerBlocks (finds buttons block and extracts button data)
2489
1891
  */
2490
1892
  function extractButtonsFromInnerBlocks(block) {
2491
1893
  const buttons = [];
@@ -2529,94 +1931,732 @@ function extractButtonsFromInnerBlocks(block) {
2529
1931
  }
2530
1932
  }
2531
1933
  }
2532
- else if (url && text) {
2533
- buttons.push({
2534
- text,
2535
- url,
2536
- isExternal: url.startsWith('http://') || url.startsWith('https://'),
2537
- });
1934
+ else if (url && text) {
1935
+ buttons.push({
1936
+ text,
1937
+ url,
1938
+ isExternal: url.startsWith('http://') || url.startsWith('https://'),
1939
+ });
1940
+ }
1941
+ }
1942
+ }
1943
+ return buttons;
1944
+ }
1945
+ /**
1946
+ * Extract text alignment from inner blocks
1947
+ * Recursively searches for heading or paragraph blocks with textAlign attribute
1948
+ * Also checks group blocks for justifyContent in layout
1949
+ * Priority: heading/paragraph textAlign takes precedence over group justifyContent
1950
+ */
1951
+ function extractTextAlignFromInnerBlocks(block) {
1952
+ const innerBlocks = block.innerBlocks || [];
1953
+ // First, recursively search for heading or paragraph blocks with textAlign
1954
+ // (These take priority over group justifyContent)
1955
+ for (const innerBlock of innerBlocks) {
1956
+ if (innerBlock.name === 'core/heading' || innerBlock.name === 'core/paragraph') {
1957
+ const attrs = innerBlock.attributes || {};
1958
+ const textAlign = attrs['textAlign'];
1959
+ if (textAlign === 'left' || textAlign === 'center' || textAlign === 'right') {
1960
+ return textAlign;
1961
+ }
1962
+ }
1963
+ // Recursively search nested blocks for headings/paragraphs first
1964
+ const nestedAlign = extractTextAlignFromInnerBlocks(innerBlock);
1965
+ if (nestedAlign)
1966
+ return nestedAlign;
1967
+ }
1968
+ // Only check group blocks if no heading/paragraph alignment found
1969
+ for (const innerBlock of innerBlocks) {
1970
+ if (innerBlock.name === 'core/group') {
1971
+ const attrs = innerBlock.attributes || {};
1972
+ const layout = attrs['layout'];
1973
+ const justifyContent = layout?.justifyContent;
1974
+ if (justifyContent === 'left')
1975
+ return 'left';
1976
+ if (justifyContent === 'center')
1977
+ return 'center';
1978
+ if (justifyContent === 'right')
1979
+ return 'right';
1980
+ }
1981
+ }
1982
+ return null;
1983
+ }
1984
+ /**
1985
+ * Parse contentPosition string into horizontal and vertical alignment
1986
+ * Format: "horizontal vertical" (e.g., "center center", "left top", "right bottom")
1987
+ */
1988
+ function parseContentPosition(contentPosition) {
1989
+ if (!contentPosition) {
1990
+ return { horizontal: 'left', vertical: 'center' };
1991
+ }
1992
+ const parts = contentPosition.trim().split(/\s+/);
1993
+ const horizontal = parts[0] || 'left';
1994
+ const vertical = parts[1] || 'center';
1995
+ return {
1996
+ horizontal: (horizontal === 'center' || horizontal === 'right' ? horizontal : 'left'),
1997
+ vertical: (vertical === 'top' || vertical === 'bottom' ? vertical : 'center'),
1998
+ };
1999
+ }
2000
+ /**
2001
+ * Extract video iframe HTML from innerBlocks (finds HTML block with iframe)
2002
+ */
2003
+ function extractVideoIframeFromInnerBlocks(block) {
2004
+ const innerBlocks = block.innerBlocks || [];
2005
+ // Recursively search for HTML blocks with iframe
2006
+ for (const innerBlock of innerBlocks) {
2007
+ if (innerBlock.name === 'core/html' && innerBlock.innerHTML) {
2008
+ // Check if innerHTML contains an iframe
2009
+ if (innerBlock.innerHTML.includes('<iframe')) {
2010
+ return innerBlock.innerHTML;
2011
+ }
2012
+ }
2013
+ // Recursively search nested blocks
2014
+ if (innerBlock.innerBlocks) {
2015
+ const nestedVideo = extractVideoIframeFromInnerBlocks(innerBlock);
2016
+ if (nestedVideo)
2017
+ return nestedVideo;
2018
+ }
2019
+ }
2020
+ return null;
2021
+ }
2022
+ /**
2023
+ * Extract and map background color from block attributes
2024
+ * Uses colorMapper from context to convert WordPress theme colors to app CSS classes
2025
+ *
2026
+ * WordPress controls which color is applied (via backgroundColor attribute),
2027
+ * app controls what it means (via colorMapper function)
2028
+ *
2029
+ * @param block - WordPress block to extract background color from
2030
+ * @param context - Render context containing optional colorMapper
2031
+ * @returns CSS class string (e.g., 'bg-gray-100') or null if no mapping
2032
+ *
2033
+ * @example
2034
+ * ```ts
2035
+ * // In WordPress, group block has: backgroundColor: "accent-5"
2036
+ * // In app, colorMapper maps: "accent-5" → "bg-gray-100"
2037
+ * // Result: extractBackgroundColor returns "bg-gray-100"
2038
+ * ```
2039
+ */
2040
+ function extractBackgroundColor(block, context) {
2041
+ const attrs = block.attributes || {};
2042
+ const wpColorName = attrs['backgroundColor'] || attrs['background'];
2043
+ if (!wpColorName || typeof wpColorName !== 'string') {
2044
+ return null;
2045
+ }
2046
+ // Use colorMapper from context if available
2047
+ if (context.colorMapper) {
2048
+ return context.colorMapper(wpColorName);
2049
+ }
2050
+ // Fallback: return null (no background applied)
2051
+ return null;
2052
+ }
2053
+
2054
+ /**
2055
+ * Style mapping utilities
2056
+ * Maps WordPress block attributes to Tailwind CSS classes
2057
+ */
2058
+ /**
2059
+ * Map WordPress alignment to Tailwind classes
2060
+ */
2061
+ function getAlignmentClasses(align) {
2062
+ if (!align)
2063
+ return '';
2064
+ switch (align) {
2065
+ case 'full':
2066
+ return 'w-full';
2067
+ case 'wide':
2068
+ return 'max-w-7xl mx-auto';
2069
+ case 'center':
2070
+ return 'mx-auto';
2071
+ case 'left':
2072
+ return 'mr-auto';
2073
+ case 'right':
2074
+ return 'ml-auto';
2075
+ default:
2076
+ return '';
2077
+ }
2078
+ }
2079
+ /**
2080
+ * Map WordPress text alignment to Tailwind classes
2081
+ */
2082
+ function getTextAlignClasses(textAlign) {
2083
+ if (!textAlign)
2084
+ return '';
2085
+ switch (textAlign) {
2086
+ case 'center':
2087
+ return 'text-center';
2088
+ case 'left':
2089
+ return 'text-left';
2090
+ case 'right':
2091
+ return 'text-right';
2092
+ default:
2093
+ return '';
2094
+ }
2095
+ }
2096
+ /**
2097
+ * Map WordPress font size to Tailwind classes
2098
+ */
2099
+ function getFontSizeClasses(fontSize) {
2100
+ if (!fontSize)
2101
+ return '';
2102
+ // Map WordPress font sizes to Tailwind
2103
+ const sizeMap = {
2104
+ 'small': 'text-sm',
2105
+ 'medium': 'text-base',
2106
+ 'large': 'text-lg',
2107
+ 'x-large': 'text-xl',
2108
+ 'xx-large': 'text-3xl',
2109
+ 'xxx-large': 'text-4xl',
2110
+ };
2111
+ return sizeMap[fontSize] || '';
2112
+ }
2113
+ /**
2114
+ * Get container classes based on layout and alignment
2115
+ */
2116
+ function getContainerClasses(align, layout) {
2117
+ const alignClass = getAlignmentClasses(align);
2118
+ // If layout is constrained, use container
2119
+ if (layout?.type === 'constrained') {
2120
+ return align === 'full' ? 'w-full' : 'container';
2121
+ }
2122
+ return alignClass || 'container';
2123
+ }
2124
+ /**
2125
+ * Get spacing classes for sections
2126
+ */
2127
+ function getSectionSpacingClasses() {
2128
+ return 'py-16 md:py-24';
2129
+ }
2130
+ /**
2131
+ * Get content spacing classes
2132
+ */
2133
+ function getContentSpacingClasses() {
2134
+ return 'space-y-6';
2135
+ }
2136
+ /**
2137
+ * Build className string from multiple class sources
2138
+ */
2139
+ function buildClassName(...classes) {
2140
+ return classes
2141
+ .filter((cls) => Boolean(cls && cls.trim()))
2142
+ .join(' ')
2143
+ .trim();
2144
+ }
2145
+
2146
+ const Paragraph = ({ block, context }) => {
2147
+ const content = getBlockTextContent(block);
2148
+ const attrs = block.attributes || {};
2149
+ const textAlign = getTextAlignClasses(attrs['align']);
2150
+ // Check if content contains shortcodes
2151
+ const hasShortcodes = /\[(\w+)/.test(content);
2152
+ if (hasShortcodes && context.registry.shortcodes) {
2153
+ const parts = renderTextWithShortcodes(content, context.registry);
2154
+ // Check if any part is a block-level element (section, div, etc.)
2155
+ // If so, render without wrapping in <p> to avoid DOM nesting violations
2156
+ const isBlockLevelElement = (element) => {
2157
+ if (!React.isValidElement(element)) {
2158
+ return false;
2159
+ }
2160
+ const type = element.type;
2161
+ // Check for block-level HTML elements
2162
+ if (typeof type === 'string' && ['section', 'div', 'article', 'header', 'footer', 'aside', 'nav'].includes(type)) {
2163
+ return true;
2164
+ }
2165
+ // Check if it's React.Fragment - recursively check its children
2166
+ if (type === React.Fragment) {
2167
+ const fragmentProps = element.props;
2168
+ const children = React.Children.toArray(fragmentProps.children);
2169
+ return children.some((child) => isBlockLevelElement(child));
2170
+ }
2171
+ // Check if it's a React component (likely block-level)
2172
+ // Most custom components render block-level content
2173
+ if (typeof type === 'function' || (typeof type === 'object' && type !== null && type !== React.Fragment)) {
2174
+ return true;
2175
+ }
2176
+ return false;
2177
+ };
2178
+ const hasBlockLevelContent = React.Children.toArray(parts).some((part) => isBlockLevelElement(part));
2179
+ if (hasBlockLevelContent) {
2180
+ // Render block-level content without <p> wrapper
2181
+ return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: parts });
2182
+ }
2183
+ return jsxRuntimeExports.jsx("p", { className: buildClassName('text-gray-700', textAlign), children: parts });
2184
+ }
2185
+ return jsxRuntimeExports.jsx("p", { className: buildClassName('text-gray-700', textAlign), children: content });
2186
+ };
2187
+ const Heading = ({ block, children }) => {
2188
+ const attrs = block.attributes || {};
2189
+ const { level = 2 } = attrs;
2190
+ const content = getBlockTextContent(block);
2191
+ const textAlign = getTextAlignClasses(attrs['textAlign']);
2192
+ const fontSize = getFontSizeClasses(attrs['fontSize']);
2193
+ const Tag = `h${Math.min(Math.max(Number(level) || 2, 1), 6)}`;
2194
+ // Default heading sizes if fontSize not specified
2195
+ const sizeClass = fontSize || (level === 1 ? 'text-4xl' : level === 2 ? 'text-3xl' : level === 3 ? 'text-2xl' : 'text-xl');
2196
+ return (jsxRuntimeExports.jsx(Tag, { className: buildClassName('font-bold text-gray-900', sizeClass, textAlign), children: children ?? content }));
2197
+ };
2198
+ const Image = ({ block }) => {
2199
+ const imageAttrs = getImageAttributes(block);
2200
+ if (!imageAttrs.url)
2201
+ return null;
2202
+ // Use Cloudflare variant URL if it's a Cloudflare image
2203
+ let imageUrl = imageAttrs.url;
2204
+ if (isCloudflareImageUrl(imageUrl)) {
2205
+ const width = imageAttrs.width || 1024;
2206
+ const height = imageAttrs.height;
2207
+ imageUrl = getCloudflareVariantUrl(imageUrl, { width, height });
2208
+ }
2209
+ return (jsxRuntimeExports.jsx("img", { src: imageUrl, alt: imageAttrs.alt, width: imageAttrs.width, height: imageAttrs.height, className: "w-full h-auto rounded-lg object-cover", style: { maxWidth: '100%', height: 'auto' }, loading: "lazy" }));
2210
+ };
2211
+ const List = ({ block, children }) => {
2212
+ const attrs = block.attributes || {};
2213
+ const { ordered } = attrs;
2214
+ const Tag = ordered ? 'ol' : 'ul';
2215
+ return React.createElement(Tag, { className: 'list-disc pl-6 space-y-2 text-gray-700' }, children);
2216
+ };
2217
+ const ListItem = ({ children }) => {
2218
+ return jsxRuntimeExports.jsx("li", { className: "text-gray-700", children: children });
2219
+ };
2220
+ const Group = ({ block, children, context }) => {
2221
+ const attrs = block.attributes || {};
2222
+ const align = attrs['align'];
2223
+ // Layout can be an object with type property, or nested structure
2224
+ const layout = attrs['layout'];
2225
+ // Extract background color using color mapper
2226
+ const backgroundColor = extractBackgroundColor(block, context);
2227
+ // Determine if this is a section-level group (has alignment) or content-level
2228
+ const isSection = align === 'full' || align === 'wide';
2229
+ const containerClass = getContainerClasses(align, layout);
2230
+ const spacingClass = isSection ? getSectionSpacingClasses() : getContentSpacingClasses();
2231
+ // Ensure container class is always applied for constrained groups
2232
+ const finalContainerClass = layout?.type === 'constrained' && align === 'wide'
2233
+ ? 'container'
2234
+ : containerClass;
2235
+ // Build className with background color if present
2236
+ const className = buildClassName(finalContainerClass, spacingClass, backgroundColor // This will be null if no mapping, which is fine
2237
+ );
2238
+ return (jsxRuntimeExports.jsx("div", { className: className, children: children }));
2239
+ };
2240
+ const Columns = ({ block, children }) => {
2241
+ const attrs = block.attributes || {};
2242
+ const align = attrs['align'];
2243
+ const alignClass = getAlignmentClasses(align);
2244
+ return (jsxRuntimeExports.jsx("div", { className: buildClassName('grid grid-cols-1 md:grid-cols-2 gap-6 lg:gap-12', alignClass), children: children }));
2245
+ };
2246
+ const Column = ({ block, children }) => {
2247
+ const attrs = block.attributes || {};
2248
+ const width = attrs['width'];
2249
+ // Handle column width (e.g., "50%" becomes flex-basis)
2250
+ const style = width ? { flexBasis: width } : undefined;
2251
+ return (jsxRuntimeExports.jsx("div", { className: "space-y-4", style: style, children: children }));
2252
+ };
2253
+ const Separator = () => jsxRuntimeExports.jsx("hr", { className: "border-gray-200 my-8" });
2254
+ const ButtonBlock = ({ block }) => {
2255
+ const attrs = block.attributes || {};
2256
+ let url = attrs['url'];
2257
+ let text = attrs['text'];
2258
+ attrs['linkDestination'];
2259
+ // Extract from innerHTML if not in attributes (buttons often store data in innerHTML)
2260
+ if (!url && block.innerHTML) {
2261
+ const linkMatch = block.innerHTML.match(/<a[^>]+href=["']([^"']+)["'][^>]*>([^<]+)<\/a>/i);
2262
+ if (linkMatch) {
2263
+ url = linkMatch[1];
2264
+ text = linkMatch[2] || text;
2265
+ }
2266
+ }
2267
+ // Get text from block content if still missing
2268
+ if (!text) {
2269
+ text = getBlockTextContent(block);
2270
+ }
2271
+ if (!url && !text)
2272
+ return null;
2273
+ const buttonText = text || 'Learn more';
2274
+ // Handle internal vs external links
2275
+ const isExternal = url && (url.startsWith('http://') || url.startsWith('https://'));
2276
+ const linkProps = isExternal ? { target: '_blank', rel: 'noopener noreferrer' } : {};
2277
+ return (jsxRuntimeExports.jsx("a", { href: url || '#', className: "inline-flex items-center justify-center rounded-md bg-primary px-6 py-3 text-primary-foreground font-medium hover:bg-primary/90 transition-colors", ...linkProps, children: buttonText }));
2278
+ };
2279
+ const Cover = ({ block, children }) => {
2280
+ const attrs = block.attributes || {};
2281
+ const { url, id, backgroundImage, cloudflareUrl, overlayColor, dimRatio = 0, align = 'full', minHeight, minHeightUnit = 'vh', hasParallax, } = attrs;
2282
+ // Get background image URL from various possible sources
2283
+ // Use the improved extraction function that handles incomplete cloudflareUrl
2284
+ let bgImageUrl = null;
2285
+ // First, try cloudflareUrl if it's valid
2286
+ if (cloudflareUrl && isValidCloudflareUrl(cloudflareUrl)) {
2287
+ bgImageUrl = cloudflareUrl;
2288
+ }
2289
+ // If not valid or not found, try regular attributes
2290
+ if (!bgImageUrl) {
2291
+ bgImageUrl = url || backgroundImage || (typeof backgroundImage === 'object' && backgroundImage?.url) || null;
2292
+ }
2293
+ // If still not found, use the fallback extraction (from innerHTML)
2294
+ if (!bgImageUrl) {
2295
+ bgImageUrl = extractImageUrlWithFallback(block);
2296
+ }
2297
+ // Convert to Cloudflare URL variant if it's a Cloudflare image
2298
+ if (bgImageUrl) {
2299
+ if (isCloudflareImageUrl(bgImageUrl)) {
2300
+ // Use full width for cover images
2301
+ bgImageUrl = getCloudflareVariantUrl(bgImageUrl, { width: 1920 });
2302
+ }
2303
+ }
2304
+ // Build alignment classes
2305
+ const alignClass = getAlignmentClasses(align);
2306
+ // Build style object
2307
+ const style = {};
2308
+ if (minHeight) {
2309
+ const minHeightValue = typeof minHeight === 'number' ? minHeight : parseFloat(String(minHeight));
2310
+ style.minHeight = minHeightUnit === 'vh' ? `${minHeightValue}vh` : `${minHeightValue}px`;
2311
+ }
2312
+ if (bgImageUrl) {
2313
+ style.backgroundImage = `url(${bgImageUrl})`;
2314
+ style.backgroundSize = 'cover';
2315
+ style.backgroundPosition = 'center';
2316
+ if (hasParallax) {
2317
+ style.backgroundAttachment = 'fixed';
2318
+ }
2319
+ }
2320
+ // Calculate overlay opacity
2321
+ const overlayOpacity = typeof dimRatio === 'number' ? dimRatio / 100 : 0;
2322
+ return (jsxRuntimeExports.jsxs("div", { className: buildClassName('relative w-full', alignClass), style: style, children: [overlayOpacity > 0 && (jsxRuntimeExports.jsx("span", { className: "absolute inset-0 z-0", style: {
2323
+ backgroundColor: overlayColor === 'contrast' ? '#000000' : (overlayColor || '#000000'),
2324
+ opacity: overlayOpacity,
2325
+ }, "aria-hidden": "true" })), jsxRuntimeExports.jsx("div", { className: buildClassName('relative z-10', align === 'full' ? 'w-full' : 'container mx-auto px-4'), children: children })] }));
2326
+ };
2327
+ const MediaText = ({ block, children, context }) => {
2328
+ const attrs = block.attributes || {};
2329
+ const { mediaPosition = 'left', verticalAlignment = 'center', imageFill = false, align, } = attrs;
2330
+ // Access innerBlocks to identify media vs content
2331
+ const innerBlocks = block.innerBlocks || [];
2332
+ // Find media block (image or video)
2333
+ let mediaBlockIndex = innerBlocks.findIndex((b) => b.name === 'core/image' || b.name === 'core/video');
2334
+ // Render children - media-text typically has media as first child, then content
2335
+ const childrenArray = React.Children.toArray(children);
2336
+ let mediaElement = mediaBlockIndex >= 0 && childrenArray[mediaBlockIndex]
2337
+ ? childrenArray[mediaBlockIndex]
2338
+ : null;
2339
+ // If no media element from innerBlocks, try to extract image URL
2340
+ if (!mediaElement) {
2341
+ const imageUrl = extractImageUrlWithFallback(block);
2342
+ if (imageUrl) {
2343
+ // Convert to Cloudflare variant if it's a Cloudflare URL
2344
+ // extractImageUrlWithFallback already handles incomplete cloudflareUrl by falling back to innerHTML
2345
+ const finalImageUrl = isCloudflareImageUrl(imageUrl)
2346
+ ? getCloudflareVariantUrl(imageUrl, { width: 1024 })
2347
+ : imageUrl;
2348
+ mediaElement = (jsxRuntimeExports.jsx("img", { src: finalImageUrl, alt: "", className: "w-full h-auto rounded-lg shadow-lg object-cover", style: { maxWidth: '100%', height: 'auto' }, loading: "lazy" }));
2349
+ }
2350
+ }
2351
+ // Content is all other children
2352
+ const contentElements = childrenArray.filter((_, index) => index !== mediaBlockIndex);
2353
+ // Build alignment classes - ensure proper container width
2354
+ // For 'wide', media-text blocks are typically inside constrained groups (which use 'container' class)
2355
+ // So we should use 'w-full' to fill the parent container, not apply another max-width
2356
+ // Only use 'max-w-7xl' for truly standalone wide blocks (rare case)
2357
+ let alignClass;
2358
+ let spacingClass;
2359
+ if (align === 'full') {
2360
+ alignClass = 'w-full';
2361
+ // Full-width blocks are typically top-level sections, so add section spacing
2362
+ spacingClass = getSectionSpacingClasses();
2363
+ }
2364
+ else if (align === 'wide') {
2365
+ // Wide blocks are usually inside constrained groups (which already have container and spacing)
2366
+ // So just fill the parent container without adding section spacing
2367
+ alignClass = 'w-full';
2368
+ spacingClass = ''; // No section spacing - parent group handles it
2369
+ }
2370
+ else {
2371
+ // Default to contained width (not full width)
2372
+ alignClass = 'container mx-auto';
2373
+ // Contained blocks might be standalone, so add section spacing
2374
+ spacingClass = getSectionSpacingClasses();
2375
+ }
2376
+ // Vertical alignment classes
2377
+ const verticalAlignClass = verticalAlignment === 'top' ? 'items-start' :
2378
+ verticalAlignment === 'bottom' ? 'items-end' :
2379
+ 'items-center';
2380
+ // Stack on mobile
2381
+ const stackClass = 'flex-col md:flex-row';
2382
+ // Media position determines order
2383
+ const isMediaRight = mediaPosition === 'right';
2384
+ return (jsxRuntimeExports.jsx("div", { className: buildClassName(alignClass, spacingClass), children: jsxRuntimeExports.jsxs("div", { className: buildClassName('flex', stackClass, verticalAlignClass, 'gap-6 lg:gap-12', 'w-full'), children: [jsxRuntimeExports.jsx("div", { className: buildClassName(isMediaRight ? 'order-2' : 'order-1', imageFill ? 'w-full md:w-1/2' : 'w-full md:w-1/2', 'min-w-0', // Allow flex item to shrink below content size
2385
+ 'overflow-hidden' // Ensure images don't overflow
2386
+ ), children: mediaElement || jsxRuntimeExports.jsx("div", { className: "bg-gray-200 h-64 rounded-lg" }) }), jsxRuntimeExports.jsx("div", { className: buildClassName(isMediaRight ? 'order-1' : 'order-2', 'w-full md:w-1/2', // Explicit width to ensure proper sizing
2387
+ 'min-w-0', // Allow flex item to shrink below content size
2388
+ getContentSpacingClasses()), children: contentElements.length > 0 ? contentElements : children })] }) }));
2389
+ };
2390
+ const Fallback = ({ block, children }) => {
2391
+ // Minimal fallback; do not render innerHTML directly in v1 for safety
2392
+ return jsxRuntimeExports.jsx("div", { "data-unknown-block": block.name, children: children });
2393
+ };
2394
+ function createDefaultRegistry(colorMapper) {
2395
+ const renderers = {
2396
+ 'core/paragraph': Paragraph,
2397
+ 'core/heading': Heading,
2398
+ 'core/image': Image,
2399
+ 'core/list': List,
2400
+ 'core/list-item': ListItem,
2401
+ 'core/group': Group,
2402
+ 'core/columns': Columns,
2403
+ 'core/column': Column,
2404
+ 'core/separator': Separator,
2405
+ 'core/button': ButtonBlock,
2406
+ 'core/buttons': ({ block, children }) => {
2407
+ const attrs = block.attributes || {};
2408
+ const layout = attrs['layout'];
2409
+ const justifyContent = layout?.justifyContent || 'left';
2410
+ const justifyClass = justifyContent === 'center' ? 'justify-center' :
2411
+ justifyContent === 'right' ? 'justify-end' :
2412
+ 'justify-start';
2413
+ return jsxRuntimeExports.jsx("div", { className: buildClassName('flex flex-wrap gap-3', justifyClass), children: children });
2414
+ },
2415
+ 'core/quote': ({ children }) => jsxRuntimeExports.jsx("blockquote", { className: "border-l-4 pl-4 italic", children: children }),
2416
+ 'core/code': ({ block }) => (jsxRuntimeExports.jsx("pre", { className: "bg-gray-100 p-3 rounded text-sm overflow-auto", children: jsxRuntimeExports.jsx("code", { children: getString(block) }) })),
2417
+ 'core/preformatted': ({ block }) => jsxRuntimeExports.jsx("pre", { children: getString(block) }),
2418
+ 'core/table': ({ children }) => jsxRuntimeExports.jsx("div", { className: "overflow-x-auto", children: jsxRuntimeExports.jsx("table", { className: "table-auto w-full", children: children }) }),
2419
+ 'core/table-row': ({ children }) => jsxRuntimeExports.jsx("tr", { children: children }),
2420
+ 'core/table-cell': ({ children }) => jsxRuntimeExports.jsx("td", { className: "border px-3 py-2", children: children }),
2421
+ // Cover block - hero sections with background images
2422
+ 'core/cover': Cover,
2423
+ // Media & Text block - side-by-side media and content
2424
+ 'core/media-text': MediaText,
2425
+ // HTML block - render innerHTML as-is
2426
+ // Note: Shortcodes in HTML blocks are not parsed (they would need to be in text content)
2427
+ 'core/html': ({ block }) => {
2428
+ const html = block.innerHTML || '';
2429
+ return jsxRuntimeExports.jsx("div", { dangerouslySetInnerHTML: { __html: html } });
2430
+ },
2431
+ };
2432
+ return {
2433
+ renderers,
2434
+ shortcodes: {}, // Empty by default - apps extend this
2435
+ fallback: Fallback,
2436
+ colorMapper,
2437
+ };
2438
+ }
2439
+ // Legacy function for backward compatibility - use getBlockTextContent instead
2440
+ function getString(block) {
2441
+ return getBlockTextContent(block);
2442
+ }
2443
+
2444
+ /**
2445
+ * Check if a block matches a pattern
2446
+ */
2447
+ function matchesPattern(block, pattern) {
2448
+ // Check block name
2449
+ if (block.name !== pattern.name) {
2450
+ return false;
2451
+ }
2452
+ // Check attributes if specified
2453
+ if (pattern.attributes) {
2454
+ const blockAttrs = block.attributes || {};
2455
+ for (const [key, value] of Object.entries(pattern.attributes)) {
2456
+ if (blockAttrs[key] !== value) {
2457
+ return false;
2458
+ }
2459
+ }
2460
+ }
2461
+ // Check innerBlocks patterns if specified
2462
+ if (pattern.innerBlocks && pattern.innerBlocks.length > 0) {
2463
+ const blockInnerBlocks = block.innerBlocks || [];
2464
+ // If pattern specifies innerBlocks, check if block has matching innerBlocks
2465
+ for (const innerPattern of pattern.innerBlocks) {
2466
+ // Find at least one matching innerBlock
2467
+ const hasMatch = blockInnerBlocks.some(innerBlock => matchesPattern(innerBlock, innerPattern));
2468
+ if (!hasMatch) {
2469
+ return false;
2538
2470
  }
2539
2471
  }
2540
2472
  }
2541
- return buttons;
2473
+ return true;
2542
2474
  }
2543
2475
  /**
2544
- * Extract text alignment from inner blocks
2545
- * Recursively searches for heading or paragraph blocks with textAlign attribute
2546
- * Also checks group blocks for justifyContent in layout
2547
- * Priority: heading/paragraph textAlign takes precedence over group justifyContent
2476
+ * Find the best matching component mapping for a block
2477
+ * Returns the mapping with highest priority that matches, or null
2548
2478
  */
2549
- function extractTextAlignFromInnerBlocks(block) {
2550
- const innerBlocks = block.innerBlocks || [];
2551
- // First, recursively search for heading or paragraph blocks with textAlign
2552
- // (These take priority over group justifyContent)
2553
- for (const innerBlock of innerBlocks) {
2554
- if (innerBlock.name === 'core/heading' || innerBlock.name === 'core/paragraph') {
2555
- const attrs = innerBlock.attributes || {};
2556
- const textAlign = attrs['textAlign'];
2557
- if (textAlign === 'left' || textAlign === 'center' || textAlign === 'right') {
2558
- return textAlign;
2559
- }
2479
+ function findMatchingMapping(block, mappings) {
2480
+ // Sort by priority (higher first), then by order in array
2481
+ const sortedMappings = [...mappings].sort((a, b) => {
2482
+ const priorityA = a.priority ?? 0;
2483
+ const priorityB = b.priority ?? 0;
2484
+ if (priorityA !== priorityB) {
2485
+ return priorityB - priorityA; // Higher priority first
2560
2486
  }
2561
- // Recursively search nested blocks for headings/paragraphs first
2562
- const nestedAlign = extractTextAlignFromInnerBlocks(innerBlock);
2563
- if (nestedAlign)
2564
- return nestedAlign;
2565
- }
2566
- // Only check group blocks if no heading/paragraph alignment found
2567
- for (const innerBlock of innerBlocks) {
2568
- if (innerBlock.name === 'core/group') {
2569
- const attrs = innerBlock.attributes || {};
2570
- const layout = attrs['layout'];
2571
- const justifyContent = layout?.justifyContent;
2572
- if (justifyContent === 'left')
2573
- return 'left';
2574
- if (justifyContent === 'center')
2575
- return 'center';
2576
- if (justifyContent === 'right')
2577
- return 'right';
2487
+ return 0; // Keep original order for same priority
2488
+ });
2489
+ // Find first matching mapping
2490
+ for (const mapping of sortedMappings) {
2491
+ if (matchesPattern(block, mapping.pattern)) {
2492
+ return mapping;
2578
2493
  }
2579
2494
  }
2580
2495
  return null;
2581
2496
  }
2497
+
2582
2498
  /**
2583
- * Parse contentPosition string into horizontal and vertical alignment
2584
- * Format: "horizontal vertical" (e.g., "center center", "left top", "right bottom")
2499
+ * Create an enhanced registry that supports pattern-based component mapping
2500
+ *
2501
+ * This combines the default registry (for fallback) with app-specific component mappings.
2502
+ * When a block matches a pattern, it uses the mapped component. Otherwise, it falls back
2503
+ * to the default renderer.
2504
+ *
2505
+ * @param mappings - Array of component mappings with patterns
2506
+ * @param baseRegistry - Optional base registry (defaults to createDefaultRegistry())
2507
+ * @returns Enhanced registry with pattern matching capabilities
2508
+ *
2509
+ * @example
2510
+ * ```ts
2511
+ * const mappings: ComponentMapping[] = [
2512
+ * {
2513
+ * pattern: { name: 'core/cover' },
2514
+ * component: HomeHeroSection,
2515
+ * extractProps: (block) => ({
2516
+ * backgroundImage: extractBackgroundImage(block),
2517
+ * title: extractTitle(block),
2518
+ * }),
2519
+ * wrapper: SectionWrapper,
2520
+ * },
2521
+ * ];
2522
+ *
2523
+ * const registry = createEnhancedRegistry(mappings);
2524
+ * ```
2585
2525
  */
2586
- function parseContentPosition(contentPosition) {
2587
- if (!contentPosition) {
2588
- return { horizontal: 'left', vertical: 'center' };
2526
+ function createEnhancedRegistry(mappings = [], baseRegistry, colorMapper) {
2527
+ const base = baseRegistry || createDefaultRegistry(colorMapper);
2528
+ // Create enhanced renderers that check patterns first
2529
+ const enhancedRenderers = {
2530
+ ...base.renderers,
2531
+ };
2532
+ // Override renderers for blocks that have mappings
2533
+ // We need to check patterns at render time, so we create a wrapper renderer
2534
+ const createPatternRenderer = (blockName) => {
2535
+ return (props) => {
2536
+ const { block, context } = props;
2537
+ // Find matching mapping
2538
+ const mapping = findMatchingMapping(block, mappings);
2539
+ if (mapping) {
2540
+ // Extract props from block
2541
+ const componentProps = mapping.extractProps(block, context);
2542
+ // Render component
2543
+ const Component = mapping.component;
2544
+ const content = jsxRuntimeExports.jsx(Component, { ...componentProps });
2545
+ // Wrap with wrapper if provided
2546
+ if (mapping.wrapper) {
2547
+ const Wrapper = mapping.wrapper;
2548
+ return jsxRuntimeExports.jsx(Wrapper, { block: block, children: content });
2549
+ }
2550
+ return content;
2551
+ }
2552
+ // Fall back to default renderer
2553
+ const defaultRenderer = base.renderers[blockName] || base.fallback;
2554
+ return defaultRenderer(props);
2555
+ };
2556
+ };
2557
+ // For each mapping, override the renderer for that block name
2558
+ for (const mapping of mappings) {
2559
+ const blockName = mapping.pattern.name;
2560
+ if (blockName) {
2561
+ enhancedRenderers[blockName] = createPatternRenderer(blockName);
2562
+ }
2589
2563
  }
2590
- const parts = contentPosition.trim().split(/\s+/);
2591
- const horizontal = parts[0] || 'left';
2592
- const vertical = parts[1] || 'center';
2564
+ // Create matchBlock function
2565
+ const matchBlock = (block) => {
2566
+ return findMatchingMapping(block, mappings);
2567
+ };
2593
2568
  return {
2594
- horizontal: (horizontal === 'center' || horizontal === 'right' ? horizontal : 'left'),
2595
- vertical: (vertical === 'top' || vertical === 'bottom' ? vertical : 'center'),
2569
+ ...base,
2570
+ renderers: enhancedRenderers,
2571
+ mappings,
2572
+ matchBlock,
2573
+ // Use provided colorMapper or inherit from base registry
2574
+ colorMapper: colorMapper || base.colorMapper,
2596
2575
  };
2597
2576
  }
2577
+
2578
+ const WPContent = ({ blocks, registry, className, page }) => {
2579
+ if (!Array.isArray(blocks)) {
2580
+ if (process.env.NODE_ENV !== 'production') {
2581
+ // eslint-disable-next-line no-console
2582
+ console.warn('WPContent: invalid blocks prop');
2583
+ }
2584
+ return null;
2585
+ }
2586
+ if (!registry || !registry.renderers) {
2587
+ throw new Error('WPContent: registry is required');
2588
+ }
2589
+ const ast = parseGutenbergBlocks(blocks);
2590
+ return (jsxRuntimeExports.jsx("div", { className: className, children: renderNodes(ast, registry, undefined, page) }));
2591
+ };
2592
+
2598
2593
  /**
2599
- * Extract video iframe HTML from innerBlocks (finds HTML block with iframe)
2594
+ * Hero logic:
2595
+ * - If the content contains a [HEROSECTION] shortcode (case-insensitive), do NOT auto-hero.
2596
+ * - Else, if the page has featured media, render a hero section using the image as background.
2600
2597
  */
2601
- function extractVideoIframeFromInnerBlocks(block) {
2602
- const innerBlocks = block.innerBlocks || [];
2603
- // Recursively search for HTML blocks with iframe
2604
- for (const innerBlock of innerBlocks) {
2605
- if (innerBlock.name === 'core/html' && innerBlock.innerHTML) {
2606
- // Check if innerHTML contains an iframe
2607
- if (innerBlock.innerHTML.includes('<iframe')) {
2608
- return innerBlock.innerHTML;
2609
- }
2610
- }
2611
- // Recursively search nested blocks
2612
- if (innerBlock.innerBlocks) {
2613
- const nestedVideo = extractVideoIframeFromInnerBlocks(innerBlock);
2614
- if (nestedVideo)
2615
- return nestedVideo;
2598
+ const WPPage = ({ page, registry, className }) => {
2599
+ if (!page || !Array.isArray(page.blocks)) {
2600
+ if (process.env.NODE_ENV !== 'production') {
2601
+ // eslint-disable-next-line no-console
2602
+ console.warn('WPPage: invalid page prop');
2616
2603
  }
2604
+ return null;
2605
+ }
2606
+ if (!registry || !registry.renderers) {
2607
+ throw new Error('WPPage: registry is required');
2608
+ }
2609
+ const hasHeroShortcode = React.useMemo(() => detectHeroShortcode(page.blocks), [page.blocks]);
2610
+ const featured = getFeaturedImage(page);
2611
+ return (jsxRuntimeExports.jsxs("article", { className: className, children: [!hasHeroShortcode && featured && (jsxRuntimeExports.jsx(HeroFromFeatured, { featured: featured, title: page.title?.rendered })), jsxRuntimeExports.jsx(WPContent, { blocks: page.blocks, registry: registry, page: page })] }));
2612
+ };
2613
+ function detectHeroShortcode(blocks) {
2614
+ for (const block of blocks) {
2615
+ const html = (block.innerHTML || '').toLowerCase();
2616
+ if (html.includes('[herosection]'))
2617
+ return true;
2618
+ // Check if this is a cover block (which is a hero section)
2619
+ if (block.name === 'core/cover')
2620
+ return true;
2621
+ if (block.innerBlocks?.length && detectHeroShortcode(block.innerBlocks))
2622
+ return true;
2617
2623
  }
2624
+ return false;
2625
+ }
2626
+ function getFeaturedImage(page) {
2627
+ const fm = page._embedded?.['wp:featuredmedia'];
2628
+ if (Array.isArray(fm) && fm.length > 0)
2629
+ return fm[0];
2618
2630
  return null;
2619
2631
  }
2632
+ const HeroFromFeatured = ({ featured, title }) => {
2633
+ const url = featured.source_url;
2634
+ if (!url)
2635
+ return null;
2636
+ return (jsxRuntimeExports.jsx("section", { className: "w-full h-[40vh] min-h-[280px] flex items-end bg-cover bg-center", style: { backgroundImage: `url(${url})` }, "aria-label": featured.alt_text || title || 'Hero', children: jsxRuntimeExports.jsx("div", { className: "container mx-auto px-4 py-8 bg-gradient-to-t from-black/50 to-transparent w-full", children: title && jsxRuntimeExports.jsx("h1", { className: "text-white text-4xl font-bold drop-shadow", children: title }) }) }));
2637
+ };
2638
+
2639
+ class WPErrorBoundary extends React.Component {
2640
+ constructor(props) {
2641
+ super(props);
2642
+ this.state = { hasError: false };
2643
+ }
2644
+ static getDerivedStateFromError() {
2645
+ return { hasError: true };
2646
+ }
2647
+ componentDidCatch(error) {
2648
+ if (process.env.NODE_ENV !== 'production') {
2649
+ // eslint-disable-next-line no-console
2650
+ console.error('WPErrorBoundary caught error:', error);
2651
+ }
2652
+ }
2653
+ render() {
2654
+ if (this.state.hasError) {
2655
+ return this.props.fallback ?? null;
2656
+ }
2657
+ return this.props.children;
2658
+ }
2659
+ }
2620
2660
 
2621
2661
  /**
2622
2662
  * Convert image URL with optional Cloudflare variant transformation
@@ -2711,6 +2751,7 @@ exports.convertImageUrls = convertImageUrls;
2711
2751
  exports.createDefaultRegistry = createDefaultRegistry;
2712
2752
  exports.createEnhancedRegistry = createEnhancedRegistry;
2713
2753
  exports.extractAlignment = extractAlignment;
2754
+ exports.extractBackgroundColor = extractBackgroundColor;
2714
2755
  exports.extractBackgroundImage = extractBackgroundImage;
2715
2756
  exports.extractButtonsFromInnerBlocks = extractButtonsFromInnerBlocks;
2716
2757
  exports.extractContent = extractContent;