Architecture Guide

Huchi Component Engine

Build rich, stateful, and reactive web interfaces using native ES6 classes, template literals, and a messaging bus—without JSX transpilers, complex state hooks, or build tooling.

Why Huchi Components? (React Paradigm Comparison)

Modern frontend frameworks require heavy build setups, virtual DOM engines, and steep learning curves. Huchi OS gives you component-driven development natively in the browser:

Feature React / Vue Huchi OS Component Engine
Build Requirements Node.js, Vite, Webpack, Babel, JSX transpilers Zero build step. Runs directly in evergreen browsers.
Templating JSX / Custom Template Directives Native ES6 Template Literals (_ui_html getter).
State Management useState, useReducer, Redux, Zustand Native class property this.state + this.setState().
Inter-Component Messaging Prop Drilling, React Context, Event Emitters Integrated Page Bus via x.request(), x.handle(), and x.emit().
Memory Management Manual useEffect return functions Automatic Sandbox Teardown: dump() purges listeners on DOM removal.

Anatomy of a Huchi Component

Every component extends the base Component class and consists of three foundational layers:

Production Code Examples

1. Stateful Dashboard Component (AppMenu.js)

Demonstrates state initialization, conditional HTML rendering based on roles and network connectivity, and state updates via async data fetching:

import { Component } from "../HuchiOS/Component.js";
import { getTenantHeader } from "../Utils/inc.js";

export default class AppMenu extends Component {
    constructor(path) {
        super(path);
        // Initializing Component State
        this.state = {
            installedSlugs: this.defaults("active"),
            catalog: this.defaults("catalogue"),
            role: 'STAFF',
            isOffline: window.appState?.state?.isOffline || false
        };
    }

    // Reactive Template Literal View
    get _ui_html() {
        const { installedSlugs, catalog, role, isOffline } = this.state;
        const isPrivileged = ["OWNER", "ADMIN"].includes(role);
        const activeApps = catalog.filter(item => installedSlugs.includes(item.slug));

        return `
            <main class="max-w-4xl mx-auto px-4 py-6 space-y-8">
                ${isOffline ? `
                    <div class="bg-amber-500/10 border border-amber-500/20 p-4 rounded-2xl">
                        <p class="text-xs text-amber-400">Offline Storage Engine Active</p>
                    </div>
                ` : ''}

                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                    ${activeApps.map(app => `
                        <a href="/${app.path}/dashboard" class="bg-slate-950 border border-slate-800 p-5 rounded-2xl">
                            <h3 class="text-xs font-black text-white uppercase">${app.name}</h3>
                            <p class="text-[10px] text-slate-400">${app.description}</p>
                        </a>
                    `).join('')}
                </div>
            </main>
        `;
    }

    defaults(key) {
        if (key === 'active') return ["sales-invoicing", "ledger-accounting"];
        return [
            { name: "Ledger & Accounting", slug: "ledger-accounting", path: "accounting", description: "Double-entry ledgers." },
            { name: "Sales & Invoicing", slug: "sales-invoicing", path: "sales", description: "Invoicing and pipeline tracking." }
        ];
    }

    module() {
        return (box) => ({
            init: async (component) => {
                // Fetch dynamic catalog manifests
                const data = await window.read('apps-manifest', 'tenant-manifest', getTenantHeader());
                
                if (data?.data) {
                    // Update internal state and trigger re-render
                    component.state.installedSlugs = data.data.active || component.defaults("active");
                    component.state.catalog = data.data.catalogue || component.defaults("catalogue");
                    component.render();
                }
            },
            dump: () => {
                // Teardown logic called automatically on DOM removal
            }
        });
    }
}

2. System Modal Controller (Modal.js)

Shows how a component handles system requests across the Page Bus (x.handle), injects dynamic child content using x.manualSwap(), and controls modal visibility:

import { Component } from "../HuchiOS/Component.js";

export default class Modal extends Component {
    get _ui_html() {
        return `
            <div class="huchi-modal-card relative bg-white w-full max-w-xl rounded-[2.5rem] shadow-2xl flex flex-col">
                <button type="button" class="huchi-modal-close-trigger absolute top-6 right-6" title="Dismiss">
                    <i class="fa-solid fa-xmark"></i>
                </button>
                <div id="modal-content" class="p-8"></div>
            </div>
        `;
    }

    module() { 
        return (x) => {
            let modalRoot = x.mod();
            let container = x.id("modal-content");

            const showModal = (config) => {
                const { content, callback, size = 'xl' } = config;
                
                // Securely swap child HTML content into the modal container
                x.manualSwap(container.node(), content);
                modalRoot.removeClass("hidden").addClass("flex modal-visible");
                
                if (typeof callback === "function") {
                    callback(modalRoot.node(), container.node());
                }
            };

            const hideModal = () => {
                modalRoot.removeClass("flex modal-visible").addClass("hidden");
                x.manualSwap(container.node(), "");
            };

            return {
                init: () => {
                    // Register system-wide request handlers on the Page Bus
                    x.handle("SYSTEM_MODAL_OPEN", showModal);
                    x.handle("SYSTEM_MODAL_CLOSE", hideModal);
                    
                    const closeTrigger = modalRoot.node().querySelector('.huchi-modal-close-trigger');
                    if (closeTrigger) {
                        closeTrigger.addEventListener('click', () => hideModal());
                    }
                }               
            };
        };
    }
}

3. Global Dialogue Service (Dialogue.js)

Demonstrates converting a component into a global system service (e.g., window.confirmDialogue) that communicates with other components by dispatching system requests:

import { Component } from "../HuchiOS/Component.js";
import { dom } from "../HuchiOS/Utils.js";

export default class Dialogue extends Component {
    module() {
        return (x) => {
            const openDialogue = (body, onConfirm, onCancel) => {
                // Dispatch request over the Page Bus to trigger the Modal component
                x.request("SYSTEM_MODAL_OPEN", {
                    size: 'md',
                    content: `
                        <div class="huchi-dialogue flex flex-col">
                            <div class="dialogue-body">${body}</div>
                            <div class="mt-6 flex justify-end gap-2">
                                <button type="button" class="btn-cancel">Cancel</button>
                                <button type="button" class="btn-confirm">Confirm</button>
                            </div>
                        </div>
                    `,
                    callback: (modalParent, modalBody) => {
                        const bodyWrapper = dom(modalBody);
                        
                        bodyWrapper.select('.btn-confirm').on('click', async (e) => {
                            x.stop(e);
                            if (typeof onConfirm === "function") await onConfirm(bodyWrapper);
                            x.request("SYSTEM_MODAL_CLOSE");
                        });

                        bodyWrapper.select('.btn-cancel').on('click', (e) => {
                            x.stop(e);
                            if (typeof onCancel === "function") onCancel(bodyWrapper);
                            x.request("SYSTEM_MODAL_CLOSE");
                        });
                    }
                });
            };

            return {
                init: () => {
                    // Expose clean global window helpers
                    window.confirmDialogue = (body, onConfirm, onCancel) => {
                        openDialogue(body, onConfirm, onCancel);
                    };
                }
            };
        };
    }
}

API Quick Reference

Base Component Methods

Method / Property Type Description
this.state Object Local state store. Changes trigger updates when using setState() or render().
setState(newState) Method Shallowly merges new state properties and calls render().
render() Method Updates existing DOM nodes matching [data-x-mod] or returns a new Tag.
get _ui_html Getter Returns HTML template string interpolated with local component state.

SandBox Lifecycle Helpers (Inside module())

Method Parameters Description
x.handle(key, fn) key: String, fn: Function Registers a request handler on the Page Bus.
x.request(key, data) key: String, data: Any Invokes a registered request handler and returns its result.
x.emit(msg, data) msg: String, 0data: Any Emits an asynchronous message across the Page Bus.
x.on(msg, fn) msg: String, fn: Function Subscribes to an event on the Page Bus; automatically cleaned up on dump.
x.manualSwap(node, html) node: HTMLElement, html: String Safely swaps container contents and clears child module references.
x.mod() none Returns a wrapped Dom instance of the component's root node.