npm.io
0.2.0 • Published 7 months ago

@10up/block-renderer-core

Licence
MIT
Version
0.2.0
Deps
1
Size
44 kB
Vulns
0
Weekly
0

@10up/block-renderer-core

Shared TypeScript types and Zod schemas for the JSON Block Renderer ecosystem. This package provides the foundational types used across all other packages in the monorepo.

Installation

npm install @10up/block-renderer-core
# or
pnpm add @10up/block-renderer-core

Overview

This package exports three categories of types:

  1. Block Tree Types - The JSON format for representing WordPress blocks
  2. Block Definition Types - Metadata and schemas for block validation
  3. Block JSON Types - TypeScript definitions for WordPress block.json files

Block Tree Format

The block tree uses a flat structure with key references instead of deep nesting. This design (inspired by Vercel's json-render) makes it easier for AI to generate valid structures.

BlockElement

A single block element in the tree:

interface BlockElement {
  /** Unique identifier for this element */
  key: string;
  /** Block name, e.g., "core/paragraph", "core/group" */
  type: string;
  /** Block attributes/props */
  props: Record<string, unknown>;
  /** Keys of child elements (for blocks with InnerBlocks) */
  children?: string[];
  /** Key of the parent element */
  parentKey?: string;
}
BlockTree

The complete block tree structure:

interface BlockTree {
  /** Key of the root element */
  root: string;
  /** Map of element keys to BlockElement objects */
  elements: Record<string, BlockElement>;
}
Example
import type { BlockTree, BlockElement } from '@10up/block-renderer-core';

const tree: BlockTree = {
  root: 'group-1',
  elements: {
    'group-1': {
      key: 'group-1',
      type: 'core/group',
      props: { layout: { type: 'constrained' } },
      children: ['heading-1', 'para-1']
    },
    'heading-1': {
      key: 'heading-1',
      type: 'core/heading',
      props: { content: 'Welcome', level: 2 },
      parentKey: 'group-1'
    },
    'para-1': {
      key: 'para-1',
      type: 'core/paragraph',
      props: { content: 'Hello world' },
      parentKey: 'group-1'
    }
  }
};

Block Template Format

An alternative PHP-style nested array format, useful for migration scripts and server-side rendering:

BlockTemplateEntry

A single entry in a block template:

type BlockTemplateEntry =
  | [string]                                           // Just block type
  | [string, Record<string, unknown>]                  // Block type + attributes
  | [string, Record<string, unknown>, BlockTemplateEntry[]]; // Full entry with children
BlockTemplate

An array of block template entries:

type BlockTemplate = BlockTemplateEntry[];
Example
import type { BlockTemplate, BlockTemplateEntry } from '@10up/block-renderer-core';

const template: BlockTemplate = [
  ['core/group', { layout: { type: 'constrained' } }, [
    ['core/heading', { content: 'Welcome', level: 2 }],
    ['core/paragraph', { content: 'Hello world' }],
  ]],
];

// This corresponds to the WordPress PHP format:
// array(
//   array( 'core/group', array( 'layout' => array( 'type' => 'constrained' ) ), array(
//     array( 'core/heading', array( 'content' => 'Welcome', 'level' => 2 ) ),
//     array( 'core/paragraph', array( 'content' => 'Hello world' ) ),
//   )),
// )
When to Use Each Format
Format Best For
BlockTree (flat) AI generation, complex validation, IDE tooling
BlockTemplate (nested) Migration scripts, PHP-to-JS conversion, manual authoring

Block Definition Types

Used for validation and prompt generation:

BlockDefinition
interface BlockDefinition {
  /** Block name, e.g., "core/paragraph" */
  name: string;
  /** Human-readable title */
  title?: string;
  /** Block description */
  description?: string;
  /** Zod schema for validating block attributes */
  schema: z.ZodObject<z.ZodRawShape>;
  /** Valid parent blocks (direct parent) */
  parent?: string[];
  /** Valid ancestor blocks (anywhere in tree path) */
  ancestor?: string[];
  /** Valid child blocks, or true for any */
  allowedBlocks?: string[] | true;
  /** Whether block supports InnerBlocks (children) */
  hasInnerBlocks: boolean;
  /** Whether block is dynamic (server-rendered) */
  isDynamic: boolean;
  /** Block category */
  category?: string;
  /** Block keywords for search */
  keywords?: string[];
}
BlockCatalog

A map of block names to their definitions:

type BlockCatalog = Map<string, BlockDefinition>;
Validation Result Types
interface ValidationResult {
  valid: boolean;
  errors: string[];
  warnings?: string[];
}

interface TreeValidationResult extends ValidationResult {
  /** Per-element validation results keyed by element key */
  elementResults?: Record<string, ValidationResult>;
}

Block JSON Types

TypeScript definitions matching the WordPress block.json schema:

BlockJson
interface BlockJson {
  name: string;                                    // Required: Block name
  title: string;                                   // Required: Display title
  category?: string;                               // Block category
  description?: string;                            // Block description
  keywords?: string[];                             // Search keywords
  attributes?: Record<string, BlockAttributeDefinition>;
  supports?: BlockSupports;                        // Feature support flags
  parent?: string[];                               // Direct parent constraints
  ancestor?: string[];                             // Ancestor constraints
  allowedBlocks?: string[];                        // Allowed child blocks
  providesContext?: Record<string, string>;        // Context provided to children
  usesContext?: string[];                          // Context consumed from parents
  styles?: Array<{ name: string; label: string; isDefault?: boolean }>;
  variations?: Array<BlockVariation>;
  render?: string;                                 // Server-side render callback
  // ... and more
}
BlockAttributeDefinition
interface BlockAttributeDefinition {
  type?: BlockAttributeType | BlockAttributeType[];
  enum?: (string | number | boolean)[];
  default?: unknown;
  source?: 'attribute' | 'text' | 'html' | 'query' | 'meta' | 'raw';
  selector?: string;
  attribute?: string;
  items?: BlockAttributeDefinition;              // For array types
  properties?: Record<string, BlockAttributeDefinition>; // For object types
}

type BlockAttributeType =
  | 'string' | 'number' | 'integer' | 'boolean'
  | 'object' | 'array' | 'null' | 'rich-text';
BlockSupports

Comprehensive type for WordPress block supports:

interface BlockSupports {
  anchor?: boolean;
  align?: boolean | ('left' | 'center' | 'right' | 'wide' | 'full')[];
  className?: boolean;
  color?: boolean | {
    background?: boolean;
    gradients?: boolean;
    link?: boolean;
    text?: boolean;
  };
  typography?: boolean | {
    fontSize?: boolean;
    lineHeight?: boolean;
    fontFamily?: boolean;
    fontWeight?: boolean;
    // ... and more
  };
  spacing?: boolean | {
    margin?: boolean | ('top' | 'right' | 'bottom' | 'left')[];
    padding?: boolean | ('top' | 'right' | 'bottom' | 'left')[];
    blockGap?: boolean | ('horizontal' | 'vertical')[];
  };
  border?: boolean | { color?: boolean; radius?: boolean; style?: boolean; width?: boolean };
  layout?: boolean | { default?: { type?: 'constrained' | 'flex' | 'flow' | 'grid' } };
  // ... and more
}

Zod Schemas

Runtime validation schemas for block trees:

import { blockTreeSchema, blockElementSchema } from '@10up/block-renderer-core';

// Validate a complete tree
const result = blockTreeSchema.safeParse(input);
if (result.success) {
  const tree: BlockTree = result.data;
} else {
  console.error(result.error.issues);
}

// Validate a single element
const elementResult = blockElementSchema.safeParse(element);
Schema Definitions
// BlockElement schema
const blockElementSchema = z.object({
  key: z.string().min(1),
  type: z.string().min(1),
  props: z.record(z.unknown()),
  children: z.array(z.string()).optional(),
  parentKey: z.string().optional(),
});

// BlockTree schema
const blockTreeSchema = z.object({
  root: z.string().min(1),
  elements: z.record(blockElementSchema),
});

PHP Pattern Options

Options for transforming rendered markup into production-ready PHP patterns with internationalization:

interface PhpPatternOptions {
  /** Theme text domain for translation functions (required) */
  textDomain: string;
  /** Asset directory name for image path detection (default: 'assets') */
  assetDirectory?: string;
}
Example
import type { PhpPatternOptions } from '@10up/block-renderer-core';

const options: PhpPatternOptions = {
  textDomain: 'my-theme',
  assetDirectory: 'assets'
};

// When used with renderBlockTree, text content will be wrapped:
// "Hello World" → <?php echo esc_html__( 'Hello World', 'my-theme' ); ?>
// Image paths will use get_template_directory_uri()

Complete Exports

Types
Type Description
BlockElement Single block in the tree
BlockTree Complete block tree structure
BlockElementSchema Zod inferred type for BlockElement
BlockTreeSchema Zod inferred type for BlockTree
BlockTemplate PHP-style nested array format
BlockTemplateEntry Single entry in a BlockTemplate
BlockTemplateEntrySchema Zod inferred type for BlockTemplateEntry
BlockTemplateSchema Zod inferred type for BlockTemplate
BlockDefinition Block schema and metadata for validation
BlockCatalog Map of block names to definitions
ValidationResult Single element validation result
TreeValidationResult Full tree validation result
BlockJson WordPress block.json structure
BlockSupports Block supports configuration
BlockAttributeDefinition Block attribute definition
BlockAttributeType Attribute type union
PhpPatternOptions Options for PHP pattern transformation
PhpPatternOptionsSchema Zod inferred type for PhpPatternOptions
Schemas
Schema Description
blockElementSchema Zod schema for validating BlockElement
blockTreeSchema Zod schema for validating BlockTree
blockTemplateEntrySchema Zod schema for validating BlockTemplateEntry
blockTemplateSchema Zod schema for validating BlockTemplate
phpPatternOptionsSchema Zod schema for validating PhpPatternOptions

License

MIT

Keywords