Skip to main content

Builder

Interactive editor for creating, testing, and previewing BlockKit JSON structures with real-time rendering and validation

Element Type

blockkit/builder

Usage

React Integration

import { useSmarterElements } from '@smarterservices/smarter-elements';

function MyComponent() {
  const elements = useSmarterElements();
  
  const handleCreateElement = async () => {
    const element = elements.create('blockkit/builder', {
      config: {
        // Add your configuration here
      },
      onReady: () => {
        console.log('Element is ready');
      },
      onError: (error) => {
        console.error('Element error:', error);
      }
    });
    
    // Mount the element
    element.mount('#element-container');
    
    // Or open as modal
    await element.openModal({
      width: '80%',
      maxWidth: '900px'
    });
  };
  
  return (
    <div>
      <button onClick={handleCreateElement}>
        Create Builder
      </button>
      <div id="element-container"></div>
    </div>
  );
}

JavaScript Integration

// Load SmarterElements
import { SmarterElements } from '@smarterservices/smarter-elements';

// Initialize
const elements = new SmarterElements({
  baseUrl: '/elements'
});

// Create element
const element = elements.create('blockkit/builder', {
  config: {
    // Add your configuration here
  },
  onReady: () => {
    console.log('Element is ready');
  },
  onError: (error) => {
    console.error('Element error:', error);
  }
});

// Mount to DOM element
element.mount('#element-container');

// Or open as modal
element.openModal({
  width: '80%',
  maxWidth: '900px'
});

Configuration

Input Parameters

The following parameters can be passed in the config object:
interface InputSchema {
  /**
   * Initial BlockKit JSON to load in the editor
   * @optional
   */
  initialJson?: string;

  /**
   * Initial replacements object for dynamic content
   * @optional
   */
  initialReplacements?: Record<string, any>;

  /**
   * Editor configuration options
   * @optional
   */
  editorConfig?: {
    /**
     * Whether to show line numbers in the editor
     * @default true
     */
    showLineNumbers?: boolean;

    /**
     * Whether to enable syntax highlighting
     * @default true
     */
    syntaxHighlighting?: boolean;

    /**
     * Whether to enable auto-completion
     * @default true
     */
    autoComplete?: boolean;

    /**
     * Editor theme
     * @default "light"
     */
    theme?: 'light' | 'dark';

    /**
     * Font size for the editor
     * @default 14
     */
    fontSize?: number;

    /**
     * Whether to wrap long lines
     * @default true
     */
    wordWrap?: boolean;
  };

  /**
   * Preview configuration options
   * @optional
   */
  previewConfig?: {
    /**
     * Whether to show the preview panel by default
     * @default true
     */
    showPreview?: boolean;

    /**
     * Whether to auto-render on JSON changes
     * @default true
     */
    autoRender?: boolean;

    /**
     * Debounce delay for auto-rendering (in milliseconds)
     * @default 500
     */
    renderDelay?: number;

    /**
     * Theme for the preview
     * @default "light"
     */
    previewTheme?: 'light' | 'dark';
  };

  /**
   * Available element templates to show in the playground
   * @optional
   */
  elementTemplates?: Array<{
    /**
     * Template name
     */
    name: string;

    /**
     * Template description
     */
    description: string;

    /**
     * Template category
     */
    category: string;

    /**
     * BlockKit JSON template
     */
    json: string;

    /**
     * Optional replacements for the template
     */
    replacements?: Record<string, any>;
  }>;

  /**
   * Validation configuration
   * @optional
   */
  validation?: {
    /**
     * Whether to enable real-time validation
     * @default true
     */
    enabled?: boolean;

    /**
     * Whether to show validation errors inline
     * @default true
     */
    showInlineErrors?: boolean;

    /**
     * Whether to show validation warnings
     * @default true
     */
    showWarnings?: boolean;

    /**
     * Custom validation rules
     */
    customRules?: Array<{
      name: string;
      description: string;
      validator: string; // Function as string
    }>;
  };

  /**
   * Export/Import configuration
   * @optional
   */
  exportConfig?: {
    /**
     * Available export formats
     * @default ["json", "javascript", "typescript"]
     */
    formats?: Array<'json' | 'javascript' | 'typescript' | 'html'>;

    /**
     * Whether to include replacements in exports
     * @default true
     */
    includeReplacements?: boolean;

    /**
     * Whether to enable import functionality
     * @default true
     */
    enableImport?: boolean;
  };

}

Output

This element provides the following output interface:
interface OutputSchema {
  /**
   * Current BlockKit JSON in the editor
   */
  currentJson: string;

  /**
   * Current replacements object
   */
  currentReplacements: Record<string, any>;

  /**
   * Parsed BlockKit elements
   */
  parsedBlocks: Array<{
    type: string;
    [key: string]: any;
  }>;

  /**
   * Validation results
   */
  validationResults: {
    /**
     * Whether the JSON is valid
     */
    isValid: boolean;

    /**
     * Validation errors
     */
    errors: Array<{
      line: number;
      column: number;
      message: string;
      severity: 'error' | 'warning';
    }>;

    /**
     * Block-level validation results
     */
    blockValidation: Array<{
      blockIndex: number;
      isValid: boolean;
      errors: string[];
      warnings: string[];
    }>;
  };

  /**
   * Editor state information
   */
  editorState: {
    /**
     * Current cursor position
     */
    cursorPosition: {
      line: number;
      column: number;
    };

    /**
     * Whether the content has been modified
     */
    isDirty: boolean;

    /**
     * Last save timestamp
     */
    lastSaved?: string;
  };

}

Events

This element emits the following events:
interface EventsSchema {
  /**
   * Fired when the JSON content changes in the editor
   */
  'json-changed': {
    /**
     * New JSON content
     */
    json: string;

    /**
     * Whether the change was made by the user
     */
    userInitiated: boolean;

    /**
     * Change details
     */
    changeInfo: {
      linesAdded: number;
      linesRemoved: number;
      charactersAdded: number;
      charactersRemoved: number;
    };
  };

  /**
   * Fired when replacements are updated
   */
  'replacements-changed': {
    /**
     * New replacements object
     */
    replacements: Record<string, any>;

    /**
     * Previous replacements object
     */
    previousReplacements: Record<string, any>;

    /**
     * Keys that were added, modified, or removed
     */
    changes: {
      added: string[];
      modified: string[];
      removed: string[];
    };
  };

  /**
   * Fired when content is rendered in the preview
   */
  'content-rendered': {
    /**
     * Number of blocks rendered
     */
    blockCount: number;

    /**
     * Rendering time in milliseconds
     */
    renderTime: number;

    /**
     * Whether rendering was successful
     */
    success: boolean;

    /**
     * Render errors, if any
     */
    errors?: string[];
  };

  /**
   * Fired when validation is performed
   */
  'validation-completed': {
    /**
     * Whether validation passed
     */
    isValid: boolean;

    /**
     * Number of errors found
     */
    errorCount: number;

    /**
     * Number of warnings found
     */
    warningCount: number;

    /**
     * Validation results
     */
    results: {
      errors: Array<{
        line: number;
        column: number;
        message: string;
      }>;
      warnings: Array<{
        line: number;
        column: number;
        message: string;
      }>;
    };
  };

  /**
   * Fired when a template is loaded
   */
  'template-loaded': {
    /**
     * Template name
     */
    templateName: string;

    /**
     * Template category
     */
    category: string;

    /**
     * Whether replacements were included
     */
    hasReplacements: boolean;
  };

  /**
   * Fired when content is exported
   */
  'content-exported': {
    /**
     * Export format used
     */
    format: 'json' | 'javascript' | 'typescript' | 'html';

    /**
     * Size of exported content in bytes
     */
    size: number;

    /**
     * Whether replacements were included
     */
    includeReplacements: boolean;
  };

  /**
   * Fired when content is imported
   */
  'content-imported': {
    /**
     * Import source
     */
    source: 'file' | 'paste' | 'url';

    /**
     * Size of imported content in bytes
     */
    size: number;

    /**
     * Whether import was successful
     */
    success: boolean;

    /**
     * Import errors, if any
     */
    errors?: string[];
  };

  /**
   * Fired when user interacts with the preview
   */
  'preview-interaction': {
    /**
     * Type of interaction
     */
    interactionType: 'click' | 'hover' | 'focus';

    /**
     * Block that was interacted with
     */
    blockIndex: number;

    /**
     * Element type that was interacted with
     */
    elementType: string;

    /**
     * Additional interaction data
     */
    data?: Record<string, any>;
  };

}

Event Handling

const element = elements.create('blockkit/builder', {
  onEvent: (eventType, data) => {
    switch (eventType) {
      case 'eventName':
        console.log('Event received:', data);
        break;
    }
  }
});

Examples

Basic Example

const element = elements.create('blockkit/builder', {
  config: {
    // Minimal configuration
  }
});

element.mount('#container');
const element = elements.create('blockkit/builder', {
  config: {
    // Your configuration
  }
});

await element.openModal({
  width: '90%',
  maxWidth: '1000px',
  dismissOnDocumentClick: false,
  escapeClose: true
});

API Reference

Element Methods

  • mount(selector) - Mount element to DOM
  • openModal(options) - Open element in modal
  • destroy() - Clean up and destroy element
  • postMessage(data) - Send message to element
  • on(event, callback) - Listen for events
  • off(event, callback) - Remove event listener
  • width - Modal width (string or number)
  • height - Modal height (string or number)
  • maxWidth - Maximum width constraint
  • maxHeight - Maximum height constraint
  • dismissOnDocumentClick - Close on backdrop click
  • escapeClose - Close on Escape key
  • zIndex - Modal z-index value

This documentation was auto-generated from the element schema.