@marvalt/wparser 0.1.6 → 0.1.8

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.esm.js CHANGED
@@ -1931,6 +1931,138 @@ function getString(block) {
1931
1931
  return getBlockTextContent(block);
1932
1932
  }
1933
1933
 
1934
+ /**
1935
+ * Check if a block matches a pattern
1936
+ */
1937
+ function matchesPattern(block, pattern) {
1938
+ // Check block name
1939
+ if (block.name !== pattern.name) {
1940
+ return false;
1941
+ }
1942
+ // Check attributes if specified
1943
+ if (pattern.attributes) {
1944
+ const blockAttrs = block.attributes || {};
1945
+ for (const [key, value] of Object.entries(pattern.attributes)) {
1946
+ if (blockAttrs[key] !== value) {
1947
+ return false;
1948
+ }
1949
+ }
1950
+ }
1951
+ // Check innerBlocks patterns if specified
1952
+ if (pattern.innerBlocks && pattern.innerBlocks.length > 0) {
1953
+ const blockInnerBlocks = block.innerBlocks || [];
1954
+ // If pattern specifies innerBlocks, check if block has matching innerBlocks
1955
+ for (const innerPattern of pattern.innerBlocks) {
1956
+ // Find at least one matching innerBlock
1957
+ const hasMatch = blockInnerBlocks.some(innerBlock => matchesPattern(innerBlock, innerPattern));
1958
+ if (!hasMatch) {
1959
+ return false;
1960
+ }
1961
+ }
1962
+ }
1963
+ return true;
1964
+ }
1965
+ /**
1966
+ * Find the best matching component mapping for a block
1967
+ * Returns the mapping with highest priority that matches, or null
1968
+ */
1969
+ function findMatchingMapping(block, mappings) {
1970
+ // Sort by priority (higher first), then by order in array
1971
+ const sortedMappings = [...mappings].sort((a, b) => {
1972
+ const priorityA = a.priority ?? 0;
1973
+ const priorityB = b.priority ?? 0;
1974
+ if (priorityA !== priorityB) {
1975
+ return priorityB - priorityA; // Higher priority first
1976
+ }
1977
+ return 0; // Keep original order for same priority
1978
+ });
1979
+ // Find first matching mapping
1980
+ for (const mapping of sortedMappings) {
1981
+ if (matchesPattern(block, mapping.pattern)) {
1982
+ return mapping;
1983
+ }
1984
+ }
1985
+ return null;
1986
+ }
1987
+
1988
+ /**
1989
+ * Create an enhanced registry that supports pattern-based component mapping
1990
+ *
1991
+ * This combines the default registry (for fallback) with app-specific component mappings.
1992
+ * When a block matches a pattern, it uses the mapped component. Otherwise, it falls back
1993
+ * to the default renderer.
1994
+ *
1995
+ * @param mappings - Array of component mappings with patterns
1996
+ * @param baseRegistry - Optional base registry (defaults to createDefaultRegistry())
1997
+ * @returns Enhanced registry with pattern matching capabilities
1998
+ *
1999
+ * @example
2000
+ * ```ts
2001
+ * const mappings: ComponentMapping[] = [
2002
+ * {
2003
+ * pattern: { name: 'core/cover' },
2004
+ * component: HomeHeroSection,
2005
+ * extractProps: (block) => ({
2006
+ * backgroundImage: extractBackgroundImage(block),
2007
+ * title: extractTitle(block),
2008
+ * }),
2009
+ * wrapper: SectionWrapper,
2010
+ * },
2011
+ * ];
2012
+ *
2013
+ * const registry = createEnhancedRegistry(mappings);
2014
+ * ```
2015
+ */
2016
+ function createEnhancedRegistry(mappings = [], baseRegistry) {
2017
+ const base = baseRegistry || createDefaultRegistry();
2018
+ // Create enhanced renderers that check patterns first
2019
+ const enhancedRenderers = {
2020
+ ...base.renderers,
2021
+ };
2022
+ // Override renderers for blocks that have mappings
2023
+ // We need to check patterns at render time, so we create a wrapper renderer
2024
+ const createPatternRenderer = (blockName) => {
2025
+ return (props) => {
2026
+ const { block, context } = props;
2027
+ // Find matching mapping
2028
+ const mapping = findMatchingMapping(block, mappings);
2029
+ if (mapping) {
2030
+ // Extract props from block
2031
+ const componentProps = mapping.extractProps(block, context);
2032
+ // Render component
2033
+ const Component = mapping.component;
2034
+ const content = jsxRuntimeExports.jsx(Component, { ...componentProps });
2035
+ // Wrap with wrapper if provided
2036
+ if (mapping.wrapper) {
2037
+ const Wrapper = mapping.wrapper;
2038
+ return jsxRuntimeExports.jsx(Wrapper, { block: block, children: content });
2039
+ }
2040
+ return content;
2041
+ }
2042
+ // Fall back to default renderer
2043
+ const defaultRenderer = base.renderers[blockName] || base.fallback;
2044
+ return defaultRenderer(props);
2045
+ };
2046
+ };
2047
+ // For each mapping, override the renderer for that block name
2048
+ for (const mapping of mappings) {
2049
+ const blockName = mapping.pattern.name;
2050
+ if (blockName) {
2051
+ enhancedRenderers[blockName] = createPatternRenderer(blockName);
2052
+ }
2053
+ }
2054
+ // Create matchBlock function
2055
+ const matchBlock = (block) => {
2056
+ return findMatchingMapping(block, mappings);
2057
+ };
2058
+ return {
2059
+ ...base,
2060
+ renderers: enhancedRenderers,
2061
+ mappings,
2062
+ matchBlock,
2063
+ };
2064
+ }
2065
+
1934
2066
  const WPContent = ({ blocks, registry, className }) => {
1935
2067
  if (!Array.isArray(blocks)) {
1936
2068
  if (process.env.NODE_ENV !== 'production') {
@@ -2011,5 +2143,367 @@ class WPErrorBoundary extends React.Component {
2011
2143
  }
2012
2144
  }
2013
2145
 
2014
- export { WPContent, WPErrorBoundary, WPPage, buildClassName, createDefaultRegistry, extractTextFromHTML, findShortcodes, getAlignmentClasses, getBlockTextContent, getCloudflareVariantUrl, getContainerClasses, getContentSpacingClasses, getFontSizeClasses, getImageAttributes, getImageUrl, getSectionSpacingClasses, getTextAlignClasses, isCloudflareImageUrl, parseGutenbergBlocks, parseShortcodeAttrs, renderNodes, renderTextWithShortcodes };
2146
+ /**
2147
+ * Extract background image URL from a block
2148
+ * Checks various possible sources: url, backgroundImage, innerHTML
2149
+ */
2150
+ function extractBackgroundImage(block) {
2151
+ const attrs = block.attributes || {};
2152
+ // Try various attribute keys
2153
+ let url = attrs['url'] ||
2154
+ attrs['backgroundImage'] ||
2155
+ (typeof attrs['backgroundImage'] === 'object' && attrs['backgroundImage']?.url);
2156
+ if (typeof url === 'string' && url.trim()) {
2157
+ return url.trim();
2158
+ }
2159
+ // Try to extract from innerHTML if not found in attributes
2160
+ if (block.innerHTML) {
2161
+ // Try img src from innerHTML
2162
+ const imgMatch = block.innerHTML.match(/<img[^>]+src=["']([^"']+)["']/i);
2163
+ if (imgMatch && imgMatch[1]) {
2164
+ return imgMatch[1];
2165
+ }
2166
+ // Try background-image in style attribute
2167
+ const bgMatch = block.innerHTML.match(/background-image:\s*url\(["']?([^"')]+)["']?\)/i);
2168
+ if (bgMatch && bgMatch[1]) {
2169
+ return bgMatch[1];
2170
+ }
2171
+ }
2172
+ return null;
2173
+ }
2174
+ /**
2175
+ * Extract image URL from a block
2176
+ * Returns Cloudflare URL if available, otherwise WordPress URL
2177
+ */
2178
+ function extractImageUrl(block) {
2179
+ return getImageUrl(block);
2180
+ }
2181
+ /**
2182
+ * Extract image attributes (url, alt, width, height)
2183
+ */
2184
+ function extractImageAttributes(block) {
2185
+ return getImageAttributes(block);
2186
+ }
2187
+ /**
2188
+ * Extract title/heading text from a block
2189
+ */
2190
+ function extractTitle(block) {
2191
+ const attrs = block.attributes || {};
2192
+ const title = attrs['title'] || attrs['content'] || getBlockTextContent(block);
2193
+ return typeof title === 'string' ? title.trim() : null;
2194
+ }
2195
+ /**
2196
+ * Extract content/text from a block
2197
+ * Returns React node for rendering
2198
+ */
2199
+ function extractContent(block, context) {
2200
+ const text = getBlockTextContent(block);
2201
+ return text || null;
2202
+ }
2203
+ /**
2204
+ * Extract media position from media-text block
2205
+ */
2206
+ function extractMediaPosition(block) {
2207
+ const attrs = block.attributes || {};
2208
+ const position = attrs['mediaPosition'] || 'left';
2209
+ return position === 'right' ? 'right' : 'left';
2210
+ }
2211
+ /**
2212
+ * Extract vertical alignment from block
2213
+ */
2214
+ function extractVerticalAlignment(block) {
2215
+ const attrs = block.attributes || {};
2216
+ const alignment = attrs['verticalAlignment'] || 'center';
2217
+ if (alignment === 'top' || alignment === 'bottom') {
2218
+ return alignment;
2219
+ }
2220
+ return 'center';
2221
+ }
2222
+ /**
2223
+ * Extract alignment (full, wide, contained) from block
2224
+ */
2225
+ function extractAlignment(block) {
2226
+ const attrs = block.attributes || {};
2227
+ const align = attrs['align'];
2228
+ if (align === 'full' || align === 'wide') {
2229
+ return align;
2230
+ }
2231
+ return 'contained';
2232
+ }
2233
+ /**
2234
+ * Extract overlay color from cover block
2235
+ */
2236
+ function extractOverlayColor(block) {
2237
+ const attrs = block.attributes || {};
2238
+ const overlayColor = attrs['overlayColor'];
2239
+ if (typeof overlayColor === 'string') {
2240
+ return overlayColor;
2241
+ }
2242
+ return null;
2243
+ }
2244
+ /**
2245
+ * Extract dim ratio (overlay opacity) from cover block
2246
+ */
2247
+ function extractDimRatio(block) {
2248
+ const attrs = block.attributes || {};
2249
+ const dimRatio = attrs['dimRatio'];
2250
+ if (typeof dimRatio === 'number') {
2251
+ return dimRatio;
2252
+ }
2253
+ return 0;
2254
+ }
2255
+ /**
2256
+ * Extract min height from block
2257
+ */
2258
+ function extractMinHeight(block) {
2259
+ const attrs = block.attributes || {};
2260
+ const minHeight = attrs['minHeight'];
2261
+ const minHeightUnit = attrs['minHeightUnit'] || 'vh';
2262
+ if (typeof minHeight === 'number') {
2263
+ return { value: minHeight, unit: minHeightUnit };
2264
+ }
2265
+ return null;
2266
+ }
2267
+ /**
2268
+ * Extract heading level from heading block
2269
+ */
2270
+ function extractHeadingLevel(block) {
2271
+ const attrs = block.attributes || {};
2272
+ const level = attrs['level'];
2273
+ if (typeof level === 'number' && level >= 1 && level <= 6) {
2274
+ return level;
2275
+ }
2276
+ return 2; // Default to h2
2277
+ }
2278
+ /**
2279
+ * Extract text alignment from block
2280
+ */
2281
+ function extractTextAlign(block) {
2282
+ const attrs = block.attributes || {};
2283
+ const align = attrs['align'] || attrs['textAlign'];
2284
+ if (align === 'left' || align === 'center' || align === 'right') {
2285
+ return align;
2286
+ }
2287
+ return null;
2288
+ }
2289
+ /**
2290
+ * Extract font size from block
2291
+ */
2292
+ function extractFontSize(block) {
2293
+ const attrs = block.attributes || {};
2294
+ const fontSize = attrs['fontSize'];
2295
+ return typeof fontSize === 'string' ? fontSize : null;
2296
+ }
2297
+ /**
2298
+ * Convert image URL to Cloudflare variant if it's a Cloudflare URL
2299
+ */
2300
+ function convertImageToCloudflareVariant(url, options = {}) {
2301
+ if (!url)
2302
+ return null;
2303
+ if (isCloudflareImageUrl(url)) {
2304
+ const width = options.width || 1024;
2305
+ const height = options.height;
2306
+ return getCloudflareVariantUrl(url, { width, height });
2307
+ }
2308
+ return url;
2309
+ }
2310
+ /**
2311
+ * Extract title from innerBlocks (finds first heading block)
2312
+ */
2313
+ function extractTitleFromInnerBlocks(block) {
2314
+ const innerBlocks = block.innerBlocks || [];
2315
+ // Recursively search for heading blocks
2316
+ for (const innerBlock of innerBlocks) {
2317
+ if (innerBlock.name === 'core/heading') {
2318
+ return getBlockTextContent(innerBlock);
2319
+ }
2320
+ // Recursively search nested blocks
2321
+ const nestedTitle = extractTitleFromInnerBlocks(innerBlock);
2322
+ if (nestedTitle)
2323
+ return nestedTitle;
2324
+ }
2325
+ return null;
2326
+ }
2327
+ /**
2328
+ * Extract subtitle/description from innerBlocks (finds first paragraph block)
2329
+ */
2330
+ function extractSubtitleFromInnerBlocks(block) {
2331
+ const innerBlocks = block.innerBlocks || [];
2332
+ // Recursively search for paragraph blocks
2333
+ for (const innerBlock of innerBlocks) {
2334
+ if (innerBlock.name === 'core/paragraph') {
2335
+ const text = getBlockTextContent(innerBlock);
2336
+ if (text && text.trim()) {
2337
+ return text;
2338
+ }
2339
+ }
2340
+ // Recursively search nested blocks
2341
+ const nestedSubtitle = extractSubtitleFromInnerBlocks(innerBlock);
2342
+ if (nestedSubtitle)
2343
+ return nestedSubtitle;
2344
+ }
2345
+ return null;
2346
+ }
2347
+ /**
2348
+ * Extract buttons from innerBlocks (finds buttons block and extracts button data)
2349
+ */
2350
+ function extractButtonsFromInnerBlocks(block) {
2351
+ const buttons = [];
2352
+ const innerBlocks = block.innerBlocks || [];
2353
+ // Find buttons block
2354
+ const findButtonsBlock = (blocks) => {
2355
+ for (const innerBlock of blocks) {
2356
+ if (innerBlock.name === 'core/buttons') {
2357
+ return innerBlock;
2358
+ }
2359
+ if (innerBlock.innerBlocks) {
2360
+ const found = findButtonsBlock(innerBlock.innerBlocks);
2361
+ if (found)
2362
+ return found;
2363
+ }
2364
+ }
2365
+ return null;
2366
+ };
2367
+ const buttonsBlock = findButtonsBlock(innerBlocks);
2368
+ if (!buttonsBlock || !buttonsBlock.innerBlocks) {
2369
+ return buttons;
2370
+ }
2371
+ // Extract button data from button blocks
2372
+ for (const buttonBlock of buttonsBlock.innerBlocks) {
2373
+ if (buttonBlock.name === 'core/button') {
2374
+ const attrs = buttonBlock.attributes || {};
2375
+ const url = attrs['url'];
2376
+ const text = attrs['text'] || getBlockTextContent(buttonBlock);
2377
+ // Try to extract from innerHTML if not in attributes
2378
+ if (!url && buttonBlock.innerHTML) {
2379
+ const linkMatch = buttonBlock.innerHTML.match(/<a[^>]+href=["']([^"']+)["'][^>]*>([^<]+)<\/a>/i);
2380
+ if (linkMatch) {
2381
+ const extractedUrl = linkMatch[1];
2382
+ const extractedText = linkMatch[2] || text;
2383
+ if (extractedUrl) {
2384
+ buttons.push({
2385
+ text: extractedText || 'Learn More',
2386
+ url: extractedUrl,
2387
+ isExternal: extractedUrl.startsWith('http://') || extractedUrl.startsWith('https://'),
2388
+ });
2389
+ }
2390
+ }
2391
+ }
2392
+ else if (url && text) {
2393
+ buttons.push({
2394
+ text,
2395
+ url,
2396
+ isExternal: url.startsWith('http://') || url.startsWith('https://'),
2397
+ });
2398
+ }
2399
+ }
2400
+ }
2401
+ return buttons;
2402
+ }
2403
+ /**
2404
+ * Extract video iframe HTML from innerBlocks (finds HTML block with iframe)
2405
+ */
2406
+ function extractVideoIframeFromInnerBlocks(block) {
2407
+ const innerBlocks = block.innerBlocks || [];
2408
+ // Recursively search for HTML blocks with iframe
2409
+ for (const innerBlock of innerBlocks) {
2410
+ if (innerBlock.name === 'core/html' && innerBlock.innerHTML) {
2411
+ // Check if innerHTML contains an iframe
2412
+ if (innerBlock.innerHTML.includes('<iframe')) {
2413
+ return innerBlock.innerHTML;
2414
+ }
2415
+ }
2416
+ // Recursively search nested blocks
2417
+ if (innerBlock.innerBlocks) {
2418
+ const nestedVideo = extractVideoIframeFromInnerBlocks(innerBlock);
2419
+ if (nestedVideo)
2420
+ return nestedVideo;
2421
+ }
2422
+ }
2423
+ return null;
2424
+ }
2425
+
2426
+ /**
2427
+ * Convert image URL with optional Cloudflare variant transformation
2428
+ *
2429
+ * @param url - Image URL (WordPress or Cloudflare)
2430
+ * @param options - Conversion options
2431
+ * @returns Converted URL or original if conversion not applicable
2432
+ */
2433
+ function convertImageUrl(url, options = {}) {
2434
+ if (!url)
2435
+ return null;
2436
+ const { convertToCloudflare = true, defaultWidth = 1024, defaultHeight, forceCloudflare = false, } = options;
2437
+ // If already Cloudflare URL and conversion is enabled
2438
+ if (isCloudflareImageUrl(url)) {
2439
+ if (convertToCloudflare) {
2440
+ return getCloudflareVariantUrl(url, {
2441
+ width: defaultWidth,
2442
+ height: defaultHeight,
2443
+ });
2444
+ }
2445
+ return url;
2446
+ }
2447
+ // If force conversion is enabled (not recommended - requires WordPress plugin to provide Cloudflare URLs)
2448
+ if (forceCloudflare) {
2449
+ // This would require additional logic to map WordPress URLs to Cloudflare URLs
2450
+ // which should be handled by the WordPress plugin providing Cloudflare URLs in block data
2451
+ console.warn('forceCloudflare is enabled but URL is not Cloudflare. WordPress plugin should provide Cloudflare URLs in block metadata.');
2452
+ }
2453
+ // Return original URL if not Cloudflare
2454
+ return url;
2455
+ }
2456
+ /**
2457
+ * Batch convert multiple image URLs
2458
+ */
2459
+ function convertImageUrls(urls, options = {}) {
2460
+ return urls.map(url => convertImageUrl(url, options));
2461
+ }
2462
+
2463
+ /**
2464
+ * Generic section wrapper component for consistent spacing and layout
2465
+ *
2466
+ * Usage in component mappings:
2467
+ * ```ts
2468
+ * {
2469
+ * pattern: { name: 'core/cover' },
2470
+ * component: HeroSection,
2471
+ * wrapper: SectionWrapper,
2472
+ * extractProps: (block) => ({ ... })
2473
+ * }
2474
+ * ```
2475
+ */
2476
+ const SectionWrapper = ({ children, background = 'light', spacing = 'medium', container = 'contained', className, block, }) => {
2477
+ // Background classes
2478
+ const backgroundClasses = {
2479
+ light: 'bg-white',
2480
+ dark: 'bg-gray-900 text-white',
2481
+ transparent: 'bg-transparent',
2482
+ };
2483
+ // Spacing classes (vertical padding)
2484
+ const spacingClasses = {
2485
+ none: '',
2486
+ small: 'py-8 md:py-12',
2487
+ medium: 'py-16 md:py-24',
2488
+ large: 'py-24 md:py-32',
2489
+ };
2490
+ // Container classes
2491
+ const containerClasses = {
2492
+ full: 'w-full',
2493
+ wide: 'max-w-7xl mx-auto px-4',
2494
+ contained: 'container mx-auto px-4',
2495
+ };
2496
+ // Extract additional props from block if provided
2497
+ const blockAttrs = block?.attributes || {};
2498
+ const blockBackground = blockAttrs['backgroundColor'] || blockAttrs['background'];
2499
+ const blockSpacing = blockAttrs['spacing'];
2500
+ const blockContainer = blockAttrs['container'] || blockAttrs['align'];
2501
+ // Override with block attributes if present
2502
+ const finalBackground = blockBackground || background;
2503
+ const finalSpacing = blockSpacing || spacing;
2504
+ const finalContainer = blockContainer || container;
2505
+ return (jsxRuntimeExports.jsx("section", { className: buildClassName(backgroundClasses[finalBackground] || backgroundClasses.light, spacingClasses[finalSpacing] || spacingClasses.medium, containerClasses[finalContainer] || containerClasses.contained, className), children: children }));
2506
+ };
2507
+
2508
+ export { SectionWrapper, WPContent, WPErrorBoundary, WPPage, buildClassName, convertImageToCloudflareVariant, convertImageUrl, convertImageUrls, createDefaultRegistry, createEnhancedRegistry, extractAlignment, extractBackgroundImage, extractButtonsFromInnerBlocks, extractContent, extractDimRatio, extractFontSize, extractHeadingLevel, extractImageAttributes, extractImageUrl, extractMediaPosition, extractMinHeight, extractOverlayColor, extractSubtitleFromInnerBlocks, extractTextAlign, extractTextFromHTML, extractTitle, extractTitleFromInnerBlocks, extractVerticalAlignment, extractVideoIframeFromInnerBlocks, findMatchingMapping, findShortcodes, getAlignmentClasses, getBlockTextContent, getCloudflareVariantUrl, getContainerClasses, getContentSpacingClasses, getFontSizeClasses, getImageAttributes, getImageUrl, getSectionSpacingClasses, getTextAlignClasses, isCloudflareImageUrl, matchesPattern, parseGutenbergBlocks, parseShortcodeAttrs, renderNodes, renderTextWithShortcodes };
2015
2509
  //# sourceMappingURL=index.esm.js.map