### Setup Petite-Vue Benchmarking Frame Source: https://github.com/denisfl/micra.js/blob/master/bench/frames/petite-vue/index.html Imports the adapter and setup functions, then initializes the frame after the window loads. This is the main setup for the benchmark. ```javascript import { adapter } from '../../adapters/petite-vue.adapter.js' import { setupFrame } from '../frame.js' await new Promise(r => window.addEventListener('load', r)) setupFrame(adapter) ``` -------------------------------- ### Toggle Component Integration Example Source: https://github.com/denisfl/micra.js/blob/master/tests/fixtures/components/toggle.html Example of how the toggle component is defined and started within the Micra.js application. ```javascript Micra.define("sidebar-menu", { state: { open: false }, toggle() { this.state.open = !this.state.open; }, close() { this.state.open = false; }, }); Micra.define("toggle-demo", { state: { checked: false, label: "", disabled: false }, onCreate() { this.state.label = this.prop("label", ""); this.state.checked = this.prop("checked", false); this.state.disabled = this.prop("disabled", false); }, flip() { if (this.state.disabled) return; this.state.checked = !this.state.checked; Micra.emit("toggle:changed", { label: this.state.label, checked: this.state.checked, }); }, }); Micra.start(); ``` -------------------------------- ### Quick Start: Counter Component Source: https://github.com/denisfl/micra.js/blob/master/README.md This example demonstrates a basic counter component using Micra.js. It includes state management for a count, increment/decrement functions, and displays the count reactively. Ensure the Micra.js library is included via CDN. ```html
``` -------------------------------- ### Setup Micra.js Benchmark Frame Source: https://github.com/denisfl/micra.js/blob/master/bench/frames/micra/index.html Imports the necessary adapter and setupFrame function to initialize the benchmark frame. This is the primary setup for the Micra.js benchmark environment. ```javascript import { adapter } from '../../adapters/micra.adapter.js' import { setupFrame } from '../frame.js' setupFrame(adapter) ``` -------------------------------- ### Start Micra Application Source: https://github.com/denisfl/micra.js/blob/master/bench-llm/golden/06-modal-bus.html Initializes and starts the Micra.js application, making defined components available for use. ```javascript Micra.start(); ``` -------------------------------- ### Install Micra.js via npm Source: https://github.com/denisfl/micra.js/blob/master/CLAUDE.md Use this command to install Micra.js as a dependency in your project. ```bash npm install micra.js ``` -------------------------------- ### Setup Stimulus Adapter in Bench Frame Source: https://github.com/denisfl/micra.js/blob/master/bench/frames/stimulus/index.html Imports necessary functions and sets up the Stimulus adapter for the benchmark frame. Ensure the window has loaded before proceeding. ```javascript import { adapter } from '../../adapters/stimulus.adapter.js' import { setupFrame } from '../frame.js' await new Promise(r => window.addEventListener('load', r)) setupFrame(adapter) ``` -------------------------------- ### Define and Start Counter Component Source: https://github.com/denisfl/micra.js/blob/master/bench-llm/golden/01-counter.html Defines a 'counter' component with initial state and methods to modify the count. The component is then started. ```javascript Micra.define("counter", { state: { count: 0 }, inc() { this.state.count++; }, dec() { this.state.count--; }, reset() { this.state.count = 0; }, }); Micra.start(); ``` -------------------------------- ### Setup Vanilla Bench Frame Source: https://github.com/denisfl/micra.js/blob/master/bench/frames/vanilla/index.html Imports the vanilla adapter and setupFrame function to initialize the benchmark environment. Ensure the adapter and setupFrame are correctly imported from their respective paths. ```javascript import { adapter } from '../../adapters/vanilla.adapter.js' import { setupFrame } from '../frame.js' setupFrame(adapter) ``` -------------------------------- ### Mount and Start Micra.js Applications Source: https://github.com/denisfl/micra.js/blob/master/README.md Mount a component to a specific DOM element using Micra.mount. Micra.start initializes the application from a root element or document. ```typescript Micra.mount(selector: string | HTMLElement, definition): ComponentInstance | null ``` ```typescript Micra.start(root?: Document | HTMLElement): void ``` -------------------------------- ### Benchmark Setup and Component Mounting Source: https://github.com/denisfl/micra.js/blob/master/bench/bench-legacy.html Sets up a host element for benchmarks and provides a function to mount Micra components directly, bypassing the registry. Includes helper for creating DOM elements. ```javascript function makeHost(html) { const el = document.createElement('div') el.innerHTML = html sandbox.appendChild(el) return el } function mountComponent(el, def) { // Use Micra.mount directly (bypasses registry) return Micra.mount(el, def) } ``` -------------------------------- ### Mount Components Source: https://github.com/denisfl/micra.js/blob/master/README.md Methods for mounting components to the DOM and starting the Micra application. ```APIDOC ## Mount Components ### Micra.mount **Description**: Mounts a component to a specified DOM element or selector. ### Signature ```ts Micra.mount(selector: string | HTMLElement, definition): ComponentInstance | null ``` ### Micra.start **Description**: Starts the Micra application, optionally targeting a root element. ### Signature ```ts Micra.start(root?: Document | HTMLElement): void ``` ``` -------------------------------- ### Using the Fetch Helper in Micra.js Source: https://github.com/denisfl/micra.js/blob/master/PROMPT.md Illustrates how to use the `this.fetch` helper for making GET and POST requests. It supports query parameters for GET and automatically includes CSRF tokens for POST. FetchError is thrown for non-2xx status codes. ```javascript // GET with query params → /api/users?page=2&q=ann const list = await this.fetch("/api/users", { page: 2, q: "ann" }) // POST with JSON body (auto X-CSRF-Token from await this.fetch("/api/save", { method: "POST", body: { name, email } }) // Throws FetchError on non-2xx — catch by .status: try { await this.fetch("/api/x") } catch (e) { if (e.status === 404) /* ... */ } ``` -------------------------------- ### Define and Start Micra Todo App Source: https://github.com/denisfl/micra.js/blob/master/bench-llm/golden/02-todo.html Defines a 'todo' component with state for items, draft input, and next ID. Includes methods for adding, toggling, and removing todo items. Starts the Micra application. ```javascript Micra.define("todo", { state: { items: [], draft: "", nextId: 1 }, left() { return this.state.items.filter((t) => !t.done).length; }, add() { const title = this.state.draft.trim(); if (!title) return; this.state.items = [ ...this.state.items, { id: this.state.nextId, title, done: false, }, ]; this.state.nextId = this.state.nextId + 1; this.state.draft = ""; }, toggle(e) { const id = Number(e.currentTarget.dataset.id); this.state.items = this.state.items.map((t) => t.id === id ? { ...t, done: !t.done } : t ); }, remove(e) { const id = Number(e.currentTarget.dataset.id); this.state.items = this.state.items.filter((t) => t.id !== id); }, }); Micra.start(); ``` -------------------------------- ### Initialize Alpine.js Benchmark Frame Source: https://github.com/denisfl/micra.js/blob/master/bench/frames/alpine/index.html Imports the Alpine.js adapter and setupFrame utility. Waits for the page to load and then initializes Alpine.js and the frame setup. Ensures Alpine's reactive APIs are available before proceeding. ```javascript import { adapter } from '../../adapters/alpine.adapter.js' import { setupFrame } from '../frame.js' // Wait for Alpine script to attach await new Promise(r => window.addEventListener('load', r)) // Start Alpine to make .reactive() and other API available. // The MutationObserver Alpine sets up is *inside this iframe's document* // only — it can't interfere with the parent or sibling frames. if (window.__startAlpine) window.__startAlpine() setupFrame(adapter) ``` -------------------------------- ### Micra.js Directives Examples Source: https://github.com/denisfl/micra.js/blob/master/llms.txt Examples of Micra.js directives for setting text content, HTML, conditional mounting, display toggling, attribute binding, two-way input binding, keyed list rendering, DOM refs, class toggling, and event binding. ```html data-text="name" ``` ```html data-html="content" ``` ```html data-if="count > 0" ``` ```html data-show="loaded" ``` ```html data-bind="href:url, disabled:loading" ``` ```html data-model="search" ``` ```html data-each="items" data-key="id" ``` ```html data-ref="chart" ``` ```html data-class="active:isActive" ``` ```html data-on="click:save" ``` ```html @click="increment" ``` -------------------------------- ### Define and Start Micra.js Component Source: https://github.com/denisfl/micra.js/blob/master/CLAUDE.md This is the core pattern for defining a Micra.js component with its state, methods, and lifecycle hooks. It also shows how to start the Micra.js application by scanning the DOM. ```js import * as Micra from 'micra.js' Micra.define('name', { state: { /* reactive data */ }, method() { this.state.value = 'new' }, onCreate() { /* runs after mount, refs available */ }, onDestroy() { /* cleanup */ }, }) Micra.start() // scans DOM for [data-component] and mounts all ``` -------------------------------- ### Defer Alpine.js Loading Source: https://github.com/denisfl/micra.js/blob/master/bench/frames/alpine/index.html Allows deferring the initialization of Alpine.js. The provided start function will be called later. ```javascript window.deferLoadingAlpine = (start) => { window.__startAlpine = start } ``` -------------------------------- ### Define Micra.js App with Lifecycle Hooks Source: https://github.com/denisfl/micra.js/blob/master/llms.txt Use `Micra.define` to create an application instance, specifying initial state and implementing `onCreate` for setup and `onDestroy` for cleanup. ```javascript Micra.define('app', { state: {}, onCreate() { /* mounted, refs available */ }, onDestroy() { /* cleanup */ }, }) ``` -------------------------------- ### Define and Start Micra.js Component Source: https://github.com/denisfl/micra.js/blob/master/llms.txt Defines a 'counter' component with state and an increment method, then starts the Micra.js application. This pattern is used for adding interactive elements to your HTML. ```html
``` ```javascript Micra.define('counter', { state: { count: 0 }, increment() { this.state.count++ }, }) Micra.start() ``` -------------------------------- ### Data Each Directive Example Source: https://github.com/denisfl/micra.js/blob/master/README.md The `data-each` directive is used for list rendering, iterating over an array and rendering elements for each item. It requires a `data-key` for efficient updates. This example iterates over 'items' using 'id' as the key. ```html data-each="items" data-key="id" ``` -------------------------------- ### Micra.js Core API Methods Source: https://github.com/denisfl/micra.js/blob/master/llms.txt Core API methods for registering and mounting components, tearing down components, and managing the event bus. Use these for global application setup and teardown. ```typescript // Register & mount Micra.define(name, definition) Micra.mount(selector, definition) Micra.start(root?) // scans DOM for [data-component] and mounts all // Teardown (server-driven / swap pages: htmx, Turbo, Astro) Micra.destroy(root?) // tear down a component + nested ones (mirror of start) Micra.autoCleanup() // auto-destroy components when their DOM is swapped out // Event bus Micra.on(event, handler) Micra.emit(event, payload?) Micra.off(event, handler) // DevTools Micra.instances() // ReadonlyMap of live components Micra.registry() // ReadonlyMap of registered definitions Micra.debug() // prints all live components to console ``` -------------------------------- ### Data Ref Directive Example Source: https://github.com/denisfl/micra.js/blob/master/README.md The `data-ref` directive provides a way to get a direct reference to a DOM element within the component's `this.refs` object. This example assigns the reference to 'chart'. ```html data-ref="chart" ``` -------------------------------- ### Data HTML Directive Example Source: https://github.com/denisfl/micra.js/blob/master/README.md The `data-html` directive is used to set the `innerHTML` of an element. This example shows how to bind it to a 'content' property. ```html data-html="content" ``` -------------------------------- ### Data Text Directive Example Source: https://github.com/denisfl/micra.js/blob/master/README.md The `data-text` directive is used to set the `textContent` of an element. This example shows how to bind it to a 'name' property. ```html data-text="name" ``` -------------------------------- ### Initialize and Manage Admin Theme Source: https://github.com/denisfl/micra.js/blob/master/examples/admin.html Initializes theme management by checking local storage for saved preferences ('light', 'dark', 'system') and sets up event listeners for system color scheme changes. ```javascript onCreate() { this._mql = matchMedia("(prefers-color-scheme: dark)"); let saved = null; try { saved = localStorage.getItem("admin-theme"); } catch (_) {} if (saved === "light" || saved === "dark" || saved === "system") { this.state.theme = saved; } this.applyTheme(); this._onScheme = () => { if (this.state.theme === "system") this.applyTheme(); }; this._mql.addEventListener?.("change", this._onScheme); this._k = (e) => this._onKey(e); document.addEventListener("keydown", this._k); } ``` -------------------------------- ### Data On Directive Example Source: https://github.com/denisfl/micra.js/blob/master/README.md The `data-on` directive binds DOM events to component methods. This example binds the 'click' event to the 'save' method. ```html data-on="click:save" ``` -------------------------------- ### Run Generation with Hosted Models Source: https://github.com/denisfl/micra.js/blob/master/bench-llm/README.md Run this command to generate components using hosted LLMs. API keys for services like Anthropic, OpenAI, and Gemini must be set as environment variables. ```bash export ANTHROPIC_API_KEY=... export OPENAI_API_KEY=... export GEMINI_API_KEY=... node bench-llm/run.mjs ``` -------------------------------- ### Define and Start Counter Component Source: https://github.com/denisfl/micra.js/blob/master/README.md This TypeScript code defines a 'counter' component with state and methods for incrementing, decrementing, and resetting the count. It then starts the Micra.js application. ```typescript import * as Micra from "micra.js"; Micra.define("counter", { state: { count: 0 }, increment() { this.state.count++; }, decrement() { this.state.count--; }, reset() { this.state.count = 0; }, }); Micra.start(); ``` -------------------------------- ### Shorthand Event Binding Example Source: https://github.com/denisfl/micra.js/blob/master/README.md The `@event` syntax is a shorthand for the `data-on` directive, simplifying event binding. This example binds the 'click' event to the 'increment' method. ```html @click="increment" ``` -------------------------------- ### Data Class Directive Example Source: https://github.com/denisfl/micra.js/blob/master/README.md The `data-class` directive allows toggling CSS classes additively based on a condition. This example adds the 'active' class when 'isActive' is true. ```html data-class="active:isActive" ``` -------------------------------- ### Data Bind Directive Example Source: https://github.com/denisfl/micra.js/blob/master/README.md The `data-bind` directive allows binding multiple attributes to component state or properties. This example binds 'href' to 'url' and 'disabled' to 'loading'. ```html data-bind="href:url, disabled:loading" ``` -------------------------------- ### Render 500 items with keyed list Source: https://github.com/denisfl/micra.js/blob/master/bench/bench-legacy.html Benchmarks the initial render of 500 items in a list with `data-each` and `data-key`. This test is designed to measure performance with a larger dataset. ```html
``` -------------------------------- ### Data Show Directive Example Source: https://github.com/denisfl/micra.js/blob/master/README.md The `data-show` directive toggles the `style.display` property of an element based on a boolean expression. This example shows toggling based on a 'loaded' property. ```html data-show="loaded" ``` -------------------------------- ### Data If Directive Example Source: https://github.com/denisfl/micra.js/blob/master/README.md The `data-if` directive conditionally mounts or unmounts an element from the DOM based on a given expression. This example shows mounting based on 'count > 0'. ```html data-if="count > 0" ``` -------------------------------- ### Data Model Directive Example Source: https://github.com/denisfl/micra.js/blob/master/README.md The `data-model` directive provides two-way data binding for input elements, synchronizing the input's value with a component property. This example binds to a 'search' property. ```html data-model="search" ``` -------------------------------- ### Run Generation with Local Ollama Models Source: https://github.com/denisfl/micra.js/blob/master/bench-llm/README.md Execute this command for free-path generation using local open-weights models served via Ollama. Ensure the desired model is pulled first. ```bash ollama pull qwen2.5-coder:14b node bench-llm/run.mjs --models ollama ``` -------------------------------- ### Initialize Micra in Rails Layout Source: https://github.com/denisfl/micra.js/blob/master/llms-full.txt Include this script in your `app/views/layouts/application.html.erb`'s head section to initialize Micra on page load and Turbo Drive's load event. CSRF meta tags are automatically read by Micra's fetch. ```erb <%# app/views/layouts/application.html.erb — inside %> <%= csrf_meta_tags %> <%= javascript_importmap_tags %> ``` -------------------------------- ### Render 100 items with keyed list Source: https://github.com/denisfl/micra.js/blob/master/bench/bench-legacy.html Measures the performance of rendering 100 items in a list using `data-each` with a `data-key`. Ensure `makeItems` and `mountComponent` are available in the scope. ```html
``` -------------------------------- ### Inspect Micra.js Components and Definitions Source: https://github.com/denisfl/micra.js/blob/master/PROMPT.md Use these functions to inspect the current state of Micra.js components and their definitions. `Micra.instances()` returns a map of live components, while `Micra.registry()` returns a map of all registered component definitions. `Micra.debug()` prints detailed information about live components to the console. ```javascript Micra.instances(); // Map of live components ``` ```javascript Micra.registry(); // Map of all definitions ``` ```javascript Micra.debug(); // prints all live components, their state and $el to console ``` -------------------------------- ### Create a User List with Filtering and Computed Summary in JavaScript Source: https://github.com/denisfl/micra.js/blob/master/PROMPT.md Implements a 'users' component that filters a list based on a search query and displays a summary of the results. The `filtered()` method returns the visible users, and `summary()` provides a count. Ensure the HTML includes elements for input, summary display, and item iteration. ```html

``` ```javascript Micra.define("users", { state: { query: "", users: [ /* …seeded data… */ ], }, filtered() { const q = this.state.query.toLowerCase(); if (!q) return this.state.users; return this.state.users.filter( (u) => u.name.toLowerCase().includes(q) || u.email.toLowerCase().includes(q), ); }, summary() { const n = this.filtered().length; return n + " / " + this.state.users.length + " users"; }, open(e) { const id = e.currentTarget.closest("[data-id]").dataset.id; this.emit("user:open", { id }); }, }); Micra.start(); ``` -------------------------------- ### Micra.js Directive: `data-ref` Source: https://github.com/denisfl/micra.js/blob/master/PROMPT.md Illustrates how to get a direct reference to an HTMLElement using `data-ref`, accessible via `this.refs`. ```html data-ref="canvas" ``` -------------------------------- ### Include Micra.js via CDN Source: https://github.com/denisfl/micra.js/blob/master/llms.txt Include Micra.js directly in your HTML using a CDN link. This method does not require a build step and exposes a global `Micra` object. Use `cdn.jsdelivr.net` for compatibility with AI sandboxes. ```html ``` -------------------------------- ### Get Row Identifier Source: https://github.com/denisfl/micra.js/blob/master/examples/admin.html Retrieves a unique identifier for a table row, likely based on event target properties. ```javascript rowId(e) { return } ``` -------------------------------- ### Implement Async Data Fetching with Loading and Error States in JavaScript Source: https://github.com/denisfl/micra.js/blob/master/PROMPT.md Creates a 'user-loader' component that fetches user data asynchronously, displaying 'Loading…' or an error message if the fetch fails. The `onCreate` lifecycle hook initiates the first load. Use the `fetch` method for API calls and handle potential errors. ```html

Loading…


``` ```javascript Micra.define("user-loader", { state: { loading: false, error: "", user: null }, async onCreate() { await this.load(); }, async load() { this.state.loading = true; this.state.error = ""; try { this.state.user = await this.fetch("/api/user"); } catch (e) { this.state.error = e.message; } finally { this.state.loading = false; } }, pretty() { return JSON.stringify(this.state.user, null, 2); }, }); Micra.start(); ``` -------------------------------- ### Micra.js Directive: `data-class` Source: https://github.com/denisfl/micra.js/blob/master/PROMPT.md Example of conditionally adding CSS classes to an element based on component state using `data-class`. ```html data-class="active:isActive, hidden:!loaded" ``` -------------------------------- ### Mock Backend Fetch Implementation Source: https://github.com/denisfl/micra.js/blob/master/tests/fixtures/recipes/data-resource.html This mock replaces the global fetch to simulate API responses for '/api/users'. It supports simulating success, server errors, and aborting requests based on a signal. ```javascript const USERS = [ { id: 1, name: "Ada Lovelace", role: "Admin" }, { id: 2, name: "Bob Smith", role: "Member" }, { id: 3, name: "Carol White", role: "Viewer" }, { id: 4, name: "Diego Hernandez", role: "Member" }, ]; const _origFetch = window.fetch; window.fetch = (url, opts) => { if (typeof url === "string" && url.startsWith("/api/users")) { const fail = new URL("http://x" + url).searchParams.get("fail"); return new Promise((resolve, reject) => { const t = setTimeout(() => { if (fail) { resolve(new Response("server error", { status: 500 })); } else { resolve( new Response(JSON.stringify(USERS), { status: 200, headers: { "content-type": "application/json", }, }) ); } }, 120); if (opts?.signal) { opts.signal.addEventListener("abort", () => { clearTimeout(t); const err = new Error("aborted"); err.name = "AbortError"; reject(err); }); } }); } return _origFetch(url, opts); }; ``` -------------------------------- ### Using jsDelivr for Micra.js CDN Source: https://github.com/denisfl/micra.js/blob/master/CLAUDE.md When including Micra.js via CDN, use `cdn.jsdelivr.net` instead of `unpkg.com`. This is due to Content Security Policy restrictions in some environments that block unpkg.com. ```html ``` ```html ``` -------------------------------- ### Component Registration and Mounting Source: https://github.com/denisfl/micra.js/blob/master/llms.txt Methods for defining, registering, and mounting Micra.js components. ```APIDOC ## Micra.define ### Description Registers a new component definition with a given name. ### Method `Micra.define(name, definition)` ### Parameters - **name** (string) - The name of the component. - **definition** (object) - The component's definition object. ## Micra.mount ### Description Mounts a component definition to a specified DOM selector. ### Method `Micra.mount(selector, definition)` ### Parameters - **selector** (string) - The CSS selector for the DOM element to mount to. - **definition** (object) - The component's definition object. ## Micra.start ### Description Scans the DOM for elements with the `data-component` attribute and mounts all found components. ### Method `Micra.start(root?) ### Parameters - **root** (HTMLElement, optional) - The root element to scan for components. Defaults to the document. ```