Skip to content

Builder

tech_e edited this page Dec 23, 2025 · 1 revision

Builder - Layout Rendering Engine

Overview

The Builder module is the core rendering engine for Base Framework. It converts object literal layouts into DOM elements, handles component instantiation, manages directives, and orchestrates the entire rendering process. While most applications use components that internally use Builder, understanding Builder is crucial for advanced scenarios and low-level control.

Core Concepts

Builder serves as the bridge between:

  • Object Layouts: Plain JavaScript objects describing UI structure
  • DOM Elements: Actual HTML elements in the browser
  • Components: Dynamic, stateful UI units
  • Directives: Behavior modifiers for elements

Main Methods

Builder.build(layout, container, parent)

Builds an object literal layout and renders it to the DOM.

import { Builder } from '@base-framework/base';

const layout = {
    tag: 'div',
    class: 'container',
    children: [
        { tag: 'h1', text: 'Hello' },
        { tag: 'p', text: 'World' }
    ]
};

Builder.build(layout, document.body);

Parameters:

  • layout (object|array): Object literal layout or array of layouts
  • container (Element): Parent DOM element to render into
  • parent (Component): Component adding this layout (optional)

Returns: DocumentFragment containing the rendered elements

Builder.render(layout, container, parent)

Renders a component or function-based layout.

import { Component, Builder } from '@base-framework/base';

class MyComponent extends Component
{
    render()
    {
        return { tag: 'div', text: 'Component content' };
    }
}

// Render component instance
const component = new MyComponent();
Builder.render(component, document.body);

// Render object layout (auto-converts to Jot component)
Builder.render({
    render() {
        return { tag: 'div', text: 'Auto-component' };
    }
}, document.body);

What it does:

  • Accepts Component instances or object layouts
  • Auto-converts objects to Jot components
  • Instantiates and renders the component
  • Returns the render result

Builder.rebuild(layout, element, parent)

Rebuilds a layout by clearing the element and building fresh content.

const element = document.querySelector('.dynamic-area');

Builder.rebuild({
    tag: 'div',
    children: [
        { tag: 'h2', text: 'New Content' },
        { tag: 'p', text: 'Rebuilt layout' }
    ]
}, element, parentComponent);

Use cases:

  • Refreshing dynamic content
  • Replacing entire sections
  • Resetting UI state

Advanced Methods

Builder.createNode(settings, container, parent)

Creates a single DOM node from parsed settings.

const settings = {
    tag: 'button',
    attr: {
        class: 'btn',
        type: 'button',
        text: 'Click Me'
    }
};

const button = Builder.createNode(settings, document.body);

Low-level method - typically used internally or for custom rendering logic.

Builder.setDirectives(element, directives, parent)

Applies directives to an element.

const directives = [
    {
        directive: { callBack: (ele, value) => { /* ... */ } },
        attr: { value: 'directive-value' }
    }
];

Builder.setDirectives(element, directives, parentComponent);

Use when:

  • Manually applying directives
  • Custom rendering logic
  • Advanced framework extensions

Builder.removeNode(node)

Removes a node and cleans up all associated data.

Builder.removeNode(element);

Proper cleanup:

  • Removes element from DOM
  • Cleans up data tracking
  • Unbinds data connections
  • Removes event listeners

Builder.removeAll(element)

Removes all children from an element.

Builder.removeAll(container);

Ensures:

  • All child data is cleaned
  • Memory is freed
  • Bindings are removed

Layout Building Process

1. Parse Layout

const layout = {
    tag: 'div',
    class: 'card',
    'data-id': '123',
    children: [
        { tag: 'h3', text: 'Title' }
    ]
};

2. Create Elements

Builder creates DOM elements for each node in the layout tree.

3. Apply Attributes

All attributes, classes, data attributes, and events are applied.

4. Process Children

Children are recursively built and appended.

5. Apply Directives

Directives add behaviors and bindings.

6. Return Result

A DocumentFragment containing all elements is returned.

Component Rendering

Auto-Component Creation

Non-component objects are automatically wrapped in Jot components:

// This object layout
Builder.render({
    render() {
        return { tag: 'div', text: 'Hello' };
    }
}, container);

// Becomes this internally
const JotComponent = Jot({
    render() {
        return { tag: 'div', text: 'Hello' };
    }
});
const instance = new JotComponent();
// Then rendered

Component Detection

Builder checks isUnit === true to identify components:

// Detected as component
class MyComponent extends Component
{
    render() { /* ... */ }
}

const component = new MyComponent();
component.isUnit === true;  // ✅ Component

Data & State Handling

Automatic Temporary Components

When layouts have data or state properties, Builder creates temporary components:

const layout = {
    tag: 'div',
    data: new Data({ count: 0 }),
    children: [
        {
            onSet: ['count', (value) => ({
                tag: 'span',
                text: `Count: ${value}`
            })]
        }
    ]
};

Builder.build(layout, container);

What happens:

  1. Builder detects data or state property
  2. Creates temporary Component wrapper
  3. Passes data/state to component
  4. Renders the nested layout inside

State Integration

const layout = {
    tag: 'div',
    state: stateTracker,
    children: [
        {
            useState: ['theme', (theme) => ({
                class: `theme-${theme}`
            })]
        }
    ]
};

Builder.build(layout, container);

Render Strategies

Browser Rendering (BrowserRender)

Used in browser environments:

  • Creates real DOM elements
  • Appends to DocumentFragments
  • Handles events and bindings
  • Full directive support

Server Rendering (ServerRender)

Used in Node.js/SSR:

  • Generates HTML strings
  • No event binding (client hydration)
  • Limited directive support
  • SEO-friendly output

Detection

Builder automatically selects the correct renderer:

// Checks for window and document
const isBrowser = (typeof window !== 'undefined' && typeof document === 'object');

Common Patterns

Dynamic Content Rebuilding

class DynamicView extends Component
{
    updateContent(newData)
    {
        // Clear and rebuild
        Builder.rebuild({
            tag: 'div',
            children: newData.map(item => ({
                tag: 'div',
                class: 'item',
                text: item.name
            }))
        }, this.elem);
    }
}

Manual Layout Building

class CustomRenderer extends Component
{
    renderCustom()
    {
        const layout = this.generateLayout();
        return Builder.build(layout, this.elem, this);
    }

    generateLayout()
    {
        return {
            tag: 'section',
            children: [
                { tag: 'h1', text: 'Generated' }
            ]
        };
    }
}

Conditional Element Creation

const layout = {
    tag: 'div',
    children: [
        { tag: 'h1', text: 'Always visible' },
        showDetails && { tag: 'p', text: 'Details...' },
        showFooter && { tag: 'footer', text: 'Footer' }
    ].filter(Boolean)  // Remove falsy values
};

Builder.build(layout, container);

Fragment-Based Building

// Build without immediately appending
const fragment = Builder.build(layout);

// Manipulate fragment...

// Append when ready
container.appendChild(fragment);

Integration with Components

Inside Component Render

class MyComponent extends Component
{
    render()
    {
        // Builder is called automatically
        return {
            tag: 'div',
            children: [
                { tag: 'h1', text: 'Title' }
            ]
        };
    }
}

Manual Building

class AdvancedComponent extends Component
{
    afterSetup()
    {
        // Manual building for special cases
        const extra = Builder.build({
            tag: 'aside',
            text: 'Extra content'
        }, this.elem, this);
    }
}

Nested Components

class Parent extends Component
{
    render()
    {
        return {
            tag: 'div',
            children: [
                // Child component
                new ChildComponent({ message: 'Hello' }),

                // Or auto-component
                {
                    render: () => ({ tag: 'span', text: 'Auto' })
                }
            ]
        };
    }
}

Caching Elements

Cache Property

class Form extends Component
{
    render()
    {
        return {
            tag: 'form',
            children: [
                {
                    tag: 'input',
                    cache: 'nameInput'  // Cached as this.nameInput
                },
                {
                    tag: 'button',
                    cache: 'submitBtn'
                }
            ]
        };
    }

    afterSetup()
    {
        // Access cached elements
        console.log(this.nameInput);   // <input> element
        console.log(this.submitBtn);   // <button> element
    }
}

Performance Considerations

1. Use DocumentFragments

Builder automatically uses DocumentFragments for batch operations.

2. Minimize Rebuilds

// ✅ Good - targeted updates
this.updateSpecificElement();

// ❌ Avoid - full rebuilds
Builder.rebuild(entireLayout, this.elem);

3. Batch Operations

// ✅ Good - single build call
Builder.build(arrayOfLayouts, container);

// ❌ Avoid - multiple builds
arrayOfLayouts.forEach(layout => Builder.build(layout, container));

4. Lazy Loading

class LazyView extends Component
{
    render()
    {
        return {
            tag: 'div',
            children: [
                { tag: 'h1', text: 'Header' },
                // Lazy load heavy content
                this.showContent && this.renderHeavyContent()
            ]
        };
    }
}

Best Practices

1. Let Components Handle Rendering

// ✅ Preferred - component-based
class View extends Component
{
    render() {
        return { tag: 'div', text: 'Content' };
    }
}

// ⚠️ Only when necessary - manual Builder
Builder.build(layout, container);

2. Use Rebuild for Full Refreshes

// ✅ Good - complete refresh
Builder.rebuild(newLayout, element, parent);

// ❌ Avoid - manual clear + build
Builder.removeAll(element);
Builder.build(newLayout, element, parent);

3. Clean Up Properly

// ✅ Good - proper cleanup
Builder.removeNode(element);

// ❌ Bad - memory leak
element.remove();

4. Cache Strategically

// ✅ Good - cache elements you'll reference
{
    tag: 'input',
    cache: 'searchInput'  // Used in multiple methods
}

// ❌ Avoid - caching everything
{
    tag: 'div',
    cache: 'randomDiv'  // Never used
}

Debugging

Inspect Build Process

const layout = {
    tag: 'div',
    class: 'debug',
    children: [
        { tag: 'span', text: 'Test' }
    ]
};

const result = Builder.build(layout);
console.log('Built fragment:', result);
console.log('Children:', result.children);

Track Rendering

class DebugComponent extends Component
{
    render()
    {
        console.log('Rendering...');
        const layout = { tag: 'div', text: 'Debug' };
        console.log('Layout:', layout);
        return layout;
    }

    afterRender()
    {
        console.log('Rendered element:', this.elem);
    }
}

Common Issues

Layout Not Rendering

// ❌ Wrong - no container
Builder.build(layout);

// ✅ Correct - with container
Builder.build(layout, document.body);

Memory Leaks

// ❌ Wrong - doesn't clean up data
element.remove();

// ✅ Correct - full cleanup
Builder.removeNode(element);

Missing Directives

// ❌ Wrong - directives not applied
const ele = document.createElement('div');

// ✅ Correct - directives handled by Builder
Builder.build({
    tag: 'div',
    onSet: ['data', () => {}]  // Directive applied
}, container);

Advanced Scenarios

Custom Render Engine

class CustomRender extends BrowserRender
{
    createNode(settings, container, parent)
    {
        // Custom node creation logic
        console.log('Creating:', settings.tag);
        return super.createNode(settings, container, parent);
    }
}

Render Hooks

class HookedComponent extends Component
{
    beforeRender()
    {
        console.log('About to render');
    }

    render()
    {
        return { tag: 'div', text: 'Content' };
    }

    afterRender()
    {
        console.log('Rendered:', this.elem);
    }
}

Manual Directive Handling

const customDirectives = [
    {
        directive: {
            callBack: (ele, value, parent) => {
                ele.style.color = value;
            }
        },
        attr: { value: 'red' }
    }
];

Builder.setDirectives(element, customDirectives, parent);

Summary

Builder is the core rendering engine that:

  • ✅ Converts object layouts to DOM
  • ✅ Manages component lifecycle
  • ✅ Handles directives and bindings
  • ✅ Provides cleanup and memory management
  • ✅ Supports both browser and server rendering
  • ✅ Enables declarative UI construction

Most applications use Builder indirectly through components, but understanding Builder helps with advanced scenarios and debugging.

Clone this wiki locally