Repository navigation
Builder
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.
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
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
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
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
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.
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
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
Removes all children from an element.
Builder.removeAll(container);Ensures:
- All child data is cleaned
- Memory is freed
- Bindings are removed
const layout = {
tag: 'div',
class: 'card',
'data-id': '123',
children: [
{ tag: 'h3', text: 'Title' }
]
};Builder creates DOM elements for each node in the layout tree.
All attributes, classes, data attributes, and events are applied.
Children are recursively built and appended.
Directives add behaviors and bindings.
A DocumentFragment containing all elements is returned.
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 renderedBuilder checks isUnit === true to identify components:
// Detected as component
class MyComponent extends Component
{
render() { /* ... */ }
}
const component = new MyComponent();
component.isUnit === true; // ✅ ComponentWhen 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:
- Builder detects
dataorstateproperty - Creates temporary Component wrapper
- Passes data/state to component
- Renders the nested layout inside
const layout = {
tag: 'div',
state: stateTracker,
children: [
{
useState: ['theme', (theme) => ({
class: `theme-${theme}`
})]
}
]
};
Builder.build(layout, container);Used in browser environments:
- Creates real DOM elements
- Appends to DocumentFragments
- Handles events and bindings
- Full directive support
Used in Node.js/SSR:
- Generates HTML strings
- No event binding (client hydration)
- Limited directive support
- SEO-friendly output
Builder automatically selects the correct renderer:
// Checks for window and document
const isBrowser = (typeof window !== 'undefined' && typeof document === 'object');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);
}
}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' }
]
};
}
}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);// Build without immediately appending
const fragment = Builder.build(layout);
// Manipulate fragment...
// Append when ready
container.appendChild(fragment);class MyComponent extends Component
{
render()
{
// Builder is called automatically
return {
tag: 'div',
children: [
{ tag: 'h1', text: 'Title' }
]
};
}
}class AdvancedComponent extends Component
{
afterSetup()
{
// Manual building for special cases
const extra = Builder.build({
tag: 'aside',
text: 'Extra content'
}, this.elem, this);
}
}class Parent extends Component
{
render()
{
return {
tag: 'div',
children: [
// Child component
new ChildComponent({ message: 'Hello' }),
// Or auto-component
{
render: () => ({ tag: 'span', text: 'Auto' })
}
]
};
}
}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
}
}Builder automatically uses DocumentFragments for batch operations.
// ✅ Good - targeted updates
this.updateSpecificElement();
// ❌ Avoid - full rebuilds
Builder.rebuild(entireLayout, this.elem);// ✅ Good - single build call
Builder.build(arrayOfLayouts, container);
// ❌ Avoid - multiple builds
arrayOfLayouts.forEach(layout => Builder.build(layout, container));class LazyView extends Component
{
render()
{
return {
tag: 'div',
children: [
{ tag: 'h1', text: 'Header' },
// Lazy load heavy content
this.showContent && this.renderHeavyContent()
]
};
}
}// ✅ Preferred - component-based
class View extends Component
{
render() {
return { tag: 'div', text: 'Content' };
}
}
// ⚠️ Only when necessary - manual Builder
Builder.build(layout, container);// ✅ Good - complete refresh
Builder.rebuild(newLayout, element, parent);
// ❌ Avoid - manual clear + build
Builder.removeAll(element);
Builder.build(newLayout, element, parent);// ✅ Good - proper cleanup
Builder.removeNode(element);
// ❌ Bad - memory leak
element.remove();// ✅ Good - cache elements you'll reference
{
tag: 'input',
cache: 'searchInput' // Used in multiple methods
}
// ❌ Avoid - caching everything
{
tag: 'div',
cache: 'randomDiv' // Never used
}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);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);
}
}// ❌ Wrong - no container
Builder.build(layout);
// ✅ Correct - with container
Builder.build(layout, document.body);// ❌ Wrong - doesn't clean up data
element.remove();
// ✅ Correct - full cleanup
Builder.removeNode(element);// ❌ Wrong - directives not applied
const ele = document.createElement('div');
// ✅ Correct - directives handled by Builder
Builder.build({
tag: 'div',
onSet: ['data', () => {}] // Directive applied
}, container);class CustomRender extends BrowserRender
{
createNode(settings, container, parent)
{
// Custom node creation logic
console.log('Creating:', settings.tag);
return super.createNode(settings, container, parent);
}
}class HookedComponent extends Component
{
beforeRender()
{
console.log('About to render');
}
render()
{
return { tag: 'div', text: 'Content' };
}
afterRender()
{
console.log('Rendered:', this.elem);
}
}const customDirectives = [
{
directive: {
callBack: (ele, value, parent) => {
ele.style.color = value;
}
},
attr: { value: 'red' }
}
];
Builder.setDirectives(element, customDirectives, parent);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.