Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
eleva.js
https://elevajs.com
Admin
A minimalist, lightweight, pure vanilla JavaScript frontend runtime framework.
Tokens:
258,158
Snippets:
1,564
Trust Score:
5.6
Update:
8 months ago
Context
Chat
Benchmark
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Quick Start: Installing Eleva Plugins Source: https://elevajs.com/plugins A quick start example illustrating the initialization of an Eleva application and the subsequent installation of core plugins such as Attr, Store, and Router. Options can be passed during plugin installation. ```javascript import Eleva from "eleva"; import { Attr, Router, Store } from "eleva/plugins"; const app = new Eleva("MyApp"); // Install plugins as needed app.use(Attr); app.use(Store, { state: { count: 0 } }); app.use(Router, { routes: [...] }); ``` -------------------------------- ### Eleva Store Plugin: Basic Setup (JavaScript) Source: https://elevajs.com/plugins/store Provides a basic setup example for the Eleva Store plugin, demonstrating how to install it with initial state and actions for managing theme, user, and a counter. ```javascript // file: main.js import Eleva from "eleva"; import { Store } from "eleva/plugins"; const app = new Eleva("MyApp"); // Install with initial state and actions app.use(Store, { state: { theme: "light", user: null, counter: 0 }, actions: { setTheme: (state, theme) => state.theme.value = theme, setUser: (state, user) => state.user.value = user, increment: (state) => state.counter.value++, decrement: (state) => state.counter.value-- } }); ``` -------------------------------- ### Using Router Plugins: Installation and Management Source: https://elevajs.com/plugins/router/api Illustrates how to install, retrieve, and remove plugins from the router. It shows how to install a plugin with options, get a list of all installed plugins, retrieve a specific plugin by name, and remove a plugin. This enables dynamic management of router extensions. ```javascript // Install with options router.use(MyPlugin, { option1: "value1" }); // Get all plugins const plugins = router.getPlugins(); // [{ name: "my-plugin", version: "1.0.0", ... }] // Get specific plugin const myPlugin = router.getPlugin("my-plugin"); // Remove plugin router.removePlugin("my-plugin"); ``` -------------------------------- ### Attr Plugin Setup and Configuration Source: https://elevajs.com/plugins/attr This section covers the installation and basic setup of the Attr plugin, including how to use it with default options or custom configurations. ```APIDOC ## Installation ### Via Package Manager ``` # npm npm install eleva # yarn yarn add eleva # pnpm pnpm add eleva # bun bun add eleva ``` ### Via CDN ```html <!-- Core + All Plugins --> <script src="https://cdn.jsdelivr.net/npm/eleva/dist/eleva-plugins.umd.min.js"></script> <!-- Attr Plugin Only --> <script src="https://cdn.jsdelivr.net/npm/eleva/dist/plugins/attr.umd.min.js"></script> ``` ## Getting Started ### Basic Setup ```javascript import Eleva from "eleva"; import { Attr } from "eleva/plugins"; // Create app instance const app = new Eleva("MyApp"); // Install Attr plugin with default options app.use(Attr); // Or with custom configuration app.use(Attr, { enableAria: true, // Handle ARIA attributes enableData: true, // Handle data-* attributes enableBoolean: true, // Handle boolean attributes enableDynamic: true // Handle dynamic properties }); ``` ## Configuration ### Plugin Options ```javascript app.use(Attr, { enableAria: true, // Enable ARIA attribute handling enableData: true, // Enable data-* attribute handling enableBoolean: true, // Enable boolean attribute handling enableDynamic: true // Enable dynamic property detection }); ``` ### Selective Feature Enabling ```javascript // Only ARIA attributes (accessibility-focused) app.use(Attr, { enableAria: true, enableData: false, enableBoolean: false, enableDynamic: false }); // Only data attributes (data storage) app.use(Attr, { enableAria: false, enableData: true, enableBoolean: false, enableDynamic: false }); // Form handling (boolean + dynamic) app.use(Attr, { enableAria: false, enableData: false, enableBoolean: true, enableDynamic: true }); ``` ``` -------------------------------- ### Basic Eleva App Setup with Attr Plugin Source: https://elevajs.com/plugins/attr Demonstrates the basic setup of an Eleva application and how to install the Attr plugin with default or custom configuration options. ```javascript import Eleva from "eleva"; import { Attr } from "eleva/plugins"; // Create app instance const app = new Eleva("MyApp"); // Install Attr plugin with default options app.use(Attr); // Or with custom configuration app.use(Attr, { enableAria: true, // Handle ARIA attributes enableData: true, // Handle data-* attributes enableBoolean: true, // Handle boolean attributes enableDynamic: true // Handle dynamic properties }); ``` -------------------------------- ### Eleva.js Quick Start Setup Source: https://elevajs.com/index This snippet demonstrates the basic setup for an Eleva.js application. It covers importing the Eleva library, creating a new app instance, defining a simple 'Counter' component with signal-based reactivity, and mounting the component to the DOM. This showcases Eleva's core concepts of components, signals, and template rendering. ```javascript import Eleva from "eleva"; // 1. Create app const app = new Eleva("MyApp"); // 2. Define component app.component("Counter", { setup: ({ signal }) => ({ count: signal(0) }), template: (ctx) => ` <button @click="() => count.value++"> Count: ${ctx.count.value} </button> ` }); // 3. Mount app.mount(document.getElementById("app"), "Counter"); ``` -------------------------------- ### Store Plugin: State Management Example Source: https://elevajs.com/plugins Illustrates the setup and usage of the Store plugin for global state management. It includes defining initial state, actions for mutations, and configuring persistence. A component example shows how to access and dispatch actions. ```javascript app.use(Store, { state: { count: 0, user: null }, actions: { increment: (state) => state.count.value++, setUser: (state, user) => state.user.value = user }, persistence: { key: "app-state", storage: "localStorage" } }); app.component("Counter", { setup: ({ store }) => ({ count: store.state.count, increment: () => store.dispatch("increment") }), template: (ctx) => ` <button @click="increment">Count: ${ctx.count.value}</button> ` }); ``` -------------------------------- ### ElevaJS Setup Context Destructuring Source: https://elevajs.com/examples/patterns/best-practices/setup-lifecycle Illustrates how to destructure specific utilities like 'signal' from the setup context. It shows examples of destructuring only necessary parts and multiple utilities like 'signal', 'emitter', and 'props'. ```javascript // Destructure only what's needed setup: ({ signal }) => { const count = signal(0); return { count }; } // Multiple utilities setup: ({ signal, emitter, props }) => { const items = signal(props.initialItems || []); emitter.on("refresh", () => loadItems()); return { items }; } ``` -------------------------------- ### Implementing the Eleva Store Plugin Source: https://elevajs.com/plugin-system Illustrates the setup of the Eleva `Store` plugin for centralized state management. This example includes defining initial state, actions for state mutations, and configuring persistence options using localStorage. ```javascript import { Store } from 'eleva/plugins'; app.use(Store, { state: { count: 0, user: null }, actions: { increment: (state) => state.count.value++, setUser: (state, user) => state.user.value = user }, persistence: { key: "app-state", storage: "localStorage" } }); ``` -------------------------------- ### Eleva.js Setup Function with Web APIs Source: https://elevajs.com/cheatsheet Demonstrates the flexibility of the `setup` function in Eleva, allowing the use of any Web API like `fetch`, `localStorage`, `setTimeout`, and `URL`. It shows an example of fetching data and initializing state from local storage. ```javascript setup: ({ signal }) => ({ // Fetch, localStorage, setTimeout, URL, Observers, etc. data: signal(JSON.parse(localStorage.getItem('data')) || []), onMount: async () => { await fetch('/api'); } }) ``` -------------------------------- ### Set Up Eleva Plugin Project (npm) Source: https://elevajs.com/examples/custom-plugin/development Initializes a new Eleva plugin project using npm. It creates a directory, initializes the npm project, and installs Eleva and development dependencies like Vite and Vitest. ```bash # Create a new directory for your plugin mkdir eleva-simple-logger cd eleva-simple-logger # Initialize npm project npm init -y # Install Eleva as a peer dependency npm install eleva --save-peer # Install development dependencies npm install --save-dev vite vitest @types/node ``` -------------------------------- ### Set Up Eleva Router for SPA Source: https://elevajs.com/plugins/router Example of configuring the Eleva Router plugin in `main.js`. This includes creating an Eleva instance, defining routes with corresponding components, and installing the router with specified options like mode and mount point. ```javascript // File: main.js import Eleva from "eleva"; import { Router } from "eleva/plugins"; import { HomePage } from "./components/HomePage.js"; import { AboutPage } from "./components/AboutPage.js"; import { UserPage } from "./components/UserPage.js"; import { NotFoundPage } from "./components/NotFoundPage.js"; // 1. Create Eleva instance const app = new Eleva("myApp"); // 2. Define routes const routes = [ { path: "/", component: HomePage }, { path: "/about", component: AboutPage }, { path: "/users/:id", component: UserPage }, { path: "*", component: NotFoundPage } // Catch-all (conventionally last) ]; // 3. Install router plugin (starts automatically by default) const router = app.use(Router, { mode: "hash", // Use hash-based routing mount: "#app", // Mount point in HTML routes: routes }); // Router starts automatically (autoStart: true by default) // Use isReady signal to know when router is ready router.isReady.watch((ready) => { if (ready) { console.log("Router started!"); console.log("Current route:", router.currentRoute.value?.path); } }); ``` -------------------------------- ### Register and Mount Eleva Component Globally Source: https://elevajs.com/components Demonstrates global component registration using `app.component()` and then mounting the component by its registered name. It includes a basic setup with a signal for reactive state and an event listener for incrementing a counter. ```javascript const app = new Eleva("MyApp"); app.component("HelloWorld", { setup({ signal }) { const count = signal(0); return { count }; }, template: (ctx) => ` <div> <h1>Hello, Eleva!</h1> <p>Count: ${ctx.count.value}</p> <button @click="() => count.value++">Increment</button> </div> `, }); app.mount(document.getElementById("app"), "HelloWorld").then((instance) => { console.log("Component mounted:", instance); }); ``` -------------------------------- ### Eleva Store Plugin: 30-Second Setup (JavaScript) Source: https://elevajs.com/plugins/store Demonstrates a quick setup for the Eleva Store plugin, including initializing Eleva, using the Store plugin with initial state and actions, and creating a simple counter component. ```javascript import Eleva from "eleva"; import { Store } from "eleva/plugins"; const app = new Eleva("MyApp"); app.use(Store, { state: { count: 0 }, actions: { increment: (state) => state.count.value++ } }); app.component("Counter", { setup({ store }) { return { count: store.state.count, increment: () => store.dispatch("increment") }; }, template: (ctx) => ` <button @click="increment">Count: ${ctx.count.value}</button> ` }); app.mount(document.getElementById("app"), "Counter"); // Result: Button showing "Count: 0", increments on click ``` -------------------------------- ### Initialize Eleva App and Install Store Plugin (JavaScript) Source: https://elevajs.com/examples/patterns/state/project-structure Sets up the main Eleva application instance and installs the Store plugin for global state management. It defines initial state, actions for modifying state, and persistence options for user and theme data. ```javascript import Eleva from "eleva"; import { Store } from "eleva/plugins"; export const app = new Eleva("MyApp"); // Install Store plugin app.use(Store, { state: { user: null, theme: "light", notifications: [] }, actions: { setUser: (state, user) => state.user.value = user, setTheme: (state, theme) => state.theme.value = theme, addNotification: (state, msg) => { state.notifications.value = [...state.notifications.value, msg]; }, clearNotifications: (state) => state.notifications.value = [] }, persistence: { key: "app-state", include: ["user", "theme"] } }); ``` -------------------------------- ### Full Store Configuration Example (JavaScript) Source: https://elevajs.com/plugins/store/configuration Demonstrates a comprehensive configuration for the Eleva Store plugin, including initial state, actions, namespaced modules, persistence settings, DevTools enablement, and error handling. ```javascript app.use(Store, { // Initial state state: { theme: "light", language: "en", notifications: [] }, // Actions actions: { setTheme: (state, theme) => state.theme.value = theme, setLanguage: (state, lang) => state.language.value = lang, addNotification: (state, notification) => { state.notifications.value = [...state.notifications.value, { id: Date.now(), ...notification }]; }, clearNotifications: (state) => state.notifications.value = [] }, // Namespaced modules namespaces: { auth: { state: { user: null, token: null }, actions: { login: (state, payload) => { /* ... */ }, logout: (state) => { /* ... */ } } } }, // Persistence persistence: { enabled: true, key: "myapp-store", storage: "localStorage", include: ["theme", "language", "auth.token"] // Only persist these }, // DevTools devTools: process.env.NODE_ENV === "development", // Error handling onError: (error, context) => { console.error(`Store error [${context}]:`, error); // Send to error tracking service } }); ``` -------------------------------- ### Vue State Management (JavaScript) Source: https://elevajs.com/migration Example of state management using `ref` in Vue. ```javascript // Vue const count = ref(0); count.value++; ``` -------------------------------- ### Plugin Registration Tests (Vitest) Source: https://elevajs.com/examples/custom-plugin/development Tests the plugin registration mechanism of ElevaJS. It verifies that the `use` method throws an error for plugins without an `install` method, returns the result of the `install` method, and correctly passes options to the `install` method. This snippet uses Vitest. ```javascript describe('Plugin Registration', () => { it('should throw if plugin has no install method', () => { const app = new Eleva('TestApp'); const invalidPlugin = { name: 'invalid', version: '1.0.0' }; expect(() => app.use(invalidPlugin)).toThrow(); }); it('should return the install result', () => { const app = new Eleva('TestApp'); const pluginWithReturn = { name: 'returner', version: '1.0.0', install: (eleva) => ({ api: 'value' }) }; const result = app.use(pluginWithReturn); expect(result).toEqual({ api: 'value' }); }); it('should pass options to install', () => { const app = new Eleva('TestApp'); const installSpy = vi.fn(); const plugin = { name: 'spy', version: '1.0.0', install: installSpy }; app.use(plugin, { custom: 'option' }); expect(installSpy).toHaveBeenCalledWith(app, { custom: 'option' }); }); }); ``` -------------------------------- ### Alpine.js Conditional Rendering (HTML) Source: https://elevajs.com/migration Example of conditional rendering in Alpine.js using the `x-if` directive. ```html // Alpine <div x-if="isVisible">Content</div> ``` -------------------------------- ### Store - Dynamic State and Actions Setup Source: https://elevajs.com/llms-full Illustrates how to dynamically create state properties, actions, and even entire modules at runtime using the store's API. This is useful for features that are initialized or modified during the application's lifecycle. ```javascript setup: ({ store }) => ({ onMount: () => { // Create new state property at runtime store.createState("newCounter", 0); // Create new action at runtime store.createAction("incrementNew", (state) => { state.newCounter.value++; }); // Register entire module at runtime store.registerModule("analytics", { state: { pageViews: 0, events: [] }, actions: { trackView: (state) => state.analytics.pageViews.value++, trackEvent: (state, event) => { state.analytics.events.value = [ ...state.analytics.events.value, event ]; } } }); }, onUnmount: () => { // Unregister module when no longer needed store.unregisterModule("analytics"); } }) ``` -------------------------------- ### Vue Conditional Rendering (HTML) Source: https://elevajs.com/migration Example of conditional rendering in Vue using the `v-if` directive. ```html // Vue <div v-if="isVisible">Content</div> ``` -------------------------------- ### ElevaJS Quick Start: Counter Component Example Source: https://elevajs.com/plugins/store This JavaScript code demonstrates how to initialize an ElevaJS application, set up a store with state and actions, define a reactive counter component, and mount it to the DOM. It utilizes the Store plugin for state management and provides basic increment, decrement, and reset functionality. ```javascript import Eleva from "eleva"; import { Store } from "eleva/plugins"; const app = new Eleva("CounterApp"); app.use(Store, { state: { count: 0 }, actions: { increment: (state) => state.count.value++, decrement: (state) => state.count.value--, reset: (state) => state.count.value = 0, setCount: (state, value) => state.count.value = value } }); app.component("Counter", { setup({ store }) { return { count: store.state.count, increment: () => store.dispatch("increment"), decrement: () => store.dispatch("decrement"), reset: () => store.dispatch("reset") }; }, template: (ctx) => ` <div class="counter"> <h2>Count: ${ctx.count.value}</h2> <button @click="decrement">-</button> <button @click="reset">Reset</button> <button @click="increment">+</button> </div> ` }); app.mount(document.getElementById("app"), "Counter"); // Result: Interactive counter with increment, decrement, and reset ``` -------------------------------- ### React Conditional Rendering (JSX) Source: https://elevajs.com/migration Example of conditional rendering in React using logical AND operator. ```jsx // React {isVisible && <div>Content</div>} ``` -------------------------------- ### Mounting Components with Props Source: https://elevajs.com/components Explains how to pass initial data (props) when mounting a component. Note that props are static. ```APIDOC ## Mounting with Props Pass initial data when mounting. > **Important:** Props are **static by design** — they are evaluated once at mount time. To create reactive data flow between parent and child, use signals or emitters. See Props Behavior for details. ```javascript app.component("UserProfile", { setup({ props }) { return { name: props.name || "Guest", role: props.role || "User" }; }, template: (ctx) => ` <div> <h2>${ctx.name}</h2> <p>Role: ${ctx.role}</p> </div> ` }); // Mount with props app.mount(document.getElementById("app"), "UserProfile", { name: "Alice", role: "Admin" }); ``` ``` -------------------------------- ### Alpine.js State Management (HTML) Source: https://elevajs.com/migration Example of state management using `x-data` directive in Alpine.js. ```html // Alpine <div x-data="{ count: 0 }"> <button @click="count++"> </div> ``` -------------------------------- ### Eleva.js Setup and Component Mounting Source: https://elevajs.com/cheatsheet Demonstrates how to import Eleva, create an app instance, register a component, and mount it to the DOM. It shows the basic structure for initializing and running an Eleva application. ```javascript import Eleva from "eleva"; const app = new Eleva("MyApp"); app.component("Name", { setup, template, style, children }); const instance = await app.mount(document.getElementById("app"), "Name", { props }); ``` -------------------------------- ### React State Management (JavaScript) Source: https://elevajs.com/migration Example of state management using `useState` hook in React. ```javascript // React const [count, setCount] = useState(0); setCount(count + 1); ``` -------------------------------- ### Minimal Eleva Router Setup Source: https://elevajs.com/plugins/router Demonstrates the basic setup for the Eleva Router Plugin. It initializes Eleva, uses the Router plugin with specified options (mode, mount point, and routes), and automatically handles component mounting without manual intervention. ```javascript import Eleva from "eleva"; import { Router } from "eleva/plugins"; const app = new Eleva("myApp"); const router = app.use(Router, { mode: "hash", mount: "#app", routes: [ { path: "/", component: HomePage }, { path: "/users/:id", component: UserPage }, { path: "*", component: NotFoundPage } ] }); // Router starts automatically (autoStart: true by default) ``` -------------------------------- ### Alpine.js Event Handling (HTML) Source: https://elevajs.com/migration Example of handling click events in Alpine.js using the `@click` directive. ```html // Alpine <button @click="count++"> ``` -------------------------------- ### Vue Event Handling (HTML) Source: https://elevajs.com/migration Example of handling click events in Vue using the `@click` directive. ```html // Vue <button @click="count++"> ``` -------------------------------- ### jQuery State Management (JavaScript) Source: https://elevajs.com/migration Example of manual state management and DOM updates using jQuery. ```javascript // jQuery let count = 0; $('#count').text(++count); ``` -------------------------------- ### Eleva.js App Mount Example Source: https://elevajs.com/examples/apps/blog This code snippet demonstrates how to mount the main Eleva application, specifically the 'Blog' component, to a DOM element with the ID 'app'. This is a fundamental step in initializing an Eleva application. ```javascript app.mount(document.getElementById("app"), "Blog"); ``` -------------------------------- ### Component Definition Structure Source: https://elevajs.com/components Defines the structure of a component in Eleva, including setup, template, style, and children. ```APIDOC ## Component Definition Structure A component in Eleva is a plain JavaScript object with these properties: ```javascript app.component("MyComponent", { // 1. Setup - Initialize state (optional) setup({ signal, emitter, props }) { const state = signal(initialValue); return { state, /* ...other exports */ }; }, // 2. Template - Define HTML structure (required) template: (ctx) => ` <div>${ctx.state.value}</div> `, // 3. Style - Component CSS (optional, not auto-scoped) style: ` div { color: blue; } `, // 4. Children - Child component mappings (optional) children: { ".child-container": "ChildComponent" } }); ``` **Order Explanation:** * `setup` initializes data for `template` and `style`. * `template` defines the structure that `style` will apply to. * `style` applies CSS to the template's elements. * `children` maps to elements created in the template. ``` -------------------------------- ### jQuery Conditional Rendering (JavaScript) Source: https://elevajs.com/migration Example of conditional DOM manipulation using jQuery's `.show()` method. ```javascript // jQuery if (isVisible) $('#content').show(); ``` -------------------------------- ### React Event Handling (JSX) Source: https://elevajs.com/migration Example of handling click events in React using inline arrow functions. ```jsx // React <button onClick={() => setCount(c => c + 1)}> ``` -------------------------------- ### Installing Eleva.js Plugins Source: https://elevajs.com/glossary Shows how to install official Eleva.js plugins like Router and Store using the `app.use()` method. Plugins extend the framework's functionality. ```javascript import { Router, Store, Attr } from "eleva/plugins"; app.use(Router, { routes: [...] }); ``` -------------------------------- ### Install an Eleva Plugin (JavaScript) Source: https://elevajs.com/plugin-system Demonstrates how to install a plugin into an Eleva application instance using the `use` method. This method takes the plugin object and optional configuration options as arguments. ```javascript const app = new Eleva("myApp"); app.use(MyPlugin, { /* optional configuration */ }); ``` -------------------------------- ### jQuery Event Handling (JavaScript) Source: https://elevajs.com/migration Example of attaching click event listeners using jQuery's `.on()` method. ```javascript // jQuery $('button').on('click', () => count++); ``` -------------------------------- ### Global Component Registration and Mounting Source: https://elevajs.com/components Demonstrates how to register components globally and then mount them by their registered name. ```APIDOC ## Global Component Registration & Mounting Register components globally, then mount by name: ```javascript const app = new Eleva("MyApp"); app.component("HelloWorld", { setup({ signal }) { const count = signal(0); return { count }; }, template: (ctx) => ` <div> <h1>Hello, Eleva!</h1> <p>Count: ${ctx.count.value}</p> <button @click="() => count.value++">Increment</button> </div> `, }); app.mount(document.getElementById("app"), "HelloWorld").then((instance) => { console.log("Component mounted:", instance); }); ``` ``` -------------------------------- ### Dynamic Component Mounting with Setup in ElevaJS Source: https://elevajs.com/components Mounts a component dynamically, allowing for setup logic (like signals) and a custom template within the parent. This offers full control over the component's lifecycle and behavior. Use for complex dynamic component needs. ```javascript children: { ".dynamic-container": { setup: ({ signal }) => ({ userData: signal({ name: "John", role: "admin" }) }), template: (ctx) => `<user-card :user="userData.value" :editable="true"></user-card>`, children: { "user-card": "UserCard" } } } ``` -------------------------------- ### Markdown: Example README Structure for Eleva.js Plugin Source: https://elevajs.com/examples/custom-plugin/best-practices Presents a standard Markdown structure for a `README.md` file when publishing an Eleva.js plugin. It includes sections for installation, usage examples, API documentation, configuration options, and licensing, following common open-source conventions. ```markdown # eleva-my-plugin A plugin for Eleva that does X. ## Installation ```bash npm install eleva-my-plugin ``` ## Usage ```js import Eleva from 'eleva'; import MyPlugin from 'eleva-my-plugin'; const app = new Eleva('MyApp'); app.use(MyPlugin, { option: 'value' }); ``` ## Options | Option | Type | Default | Description | |--------|------|---------|-------------| | `option` | `string` | `''` | Description | ## API ### `app.myPlugin.method()` Description of method. ## License MIT ``` -------------------------------- ### Eleva App Initialization and Component Mounting Source: https://elevajs.com/core-concepts Shows the basic setup of an Eleva application. It involves creating an app instance, registering a component with a setup function and template, and then mounting that component to a specified DOM element. The mount function returns a promise that resolves with mount results, including an unmount function. ```javascript const app = new Eleva("MyApp"); // Register component app.component("Counter", { setup: ({ signal }) => ({ count: signal(0) }), template: (ctx) => `<div>${ctx.count.value}</div>` }); // Mount component const instance = await app.mount(document.getElementById("app"), "Counter"); // Unmount when done await instance.unmount(); ``` -------------------------------- ### Eleva: Complete Input and Button Component Setup Source: https://elevajs.com/examples/patterns/forms A complete Eleva application setup demonstrating an input field and a button. It uses signals for reactive state management of input and displayed values, and event binding for user interactions. The component is then mounted to the DOM. ```javascript // main.js - Complete application setup import Eleva from "eleva"; // 1. Create the application instance const app = new Eleva("FormApp"); // 2. Define the component app.component("InputDisplay", { setup({ signal }) { // Reactive state for the input value const inputValue = signal(""); // Reactive state for the displayed message const displayedValue = signal(""); // Handle input changes function handleInput(event) { inputValue.value = event.target.value; } // Handle button click - display current input value function showValue() { displayedValue.value = inputValue.value; } return { inputValue, displayedValue, handleInput, showValue }; }, template: (ctx) => ` <div class="input-display"> <input type="text" value="${ctx.inputValue.value}" @input="handleInput" placeholder="Enter some text..." /> <button type="button" @click="showValue">Show Value</button> ${ctx.displayedValue.value ? ` <p class="result"> Current value: <strong>${ctx.displayedValue.value}</strong> </p> ` : ''} </div> `, style: ` .input-display { display: flex; flex-direction: column; gap: 1rem; max-width: 300px; } .input-display input { padding: 0.5rem; border: 1px solid #ccc; border-radius: 4px; } .input-display button { padding: 0.5rem 1rem; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; } .input-display button:hover { background: #0056b3; } .result { margin: 0; padding: 0.5rem; background: #f0f0f0; border-radius: 4px; } ` }); // 3. Mount to the DOM app.mount(document.getElementById("app"), "InputDisplay"); ``` ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Input Display Example</title> </head> <body> <div id="app"></div> <script type="module" src="./main.js"></script> </body> </html> ``` -------------------------------- ### Eleva Plugin Returning an API via install() (JavaScript) Source: https://elevajs.com/examples/custom-plugin Shows how an Eleva plugin can return a specific API or instance from its `install` method, which is then directly accessible after calling `app.use()`. This pattern is useful for plugins that expose a distinct interface, like a router. ```javascript // Plugin that returns an API const RouterPlugin = { name: "router", version: "1.0.0", install(eleva, options) { const router = new Router(eleva, options); eleva.router = router; return router; // Return for direct access } }; // Usage const router = app.use(RouterPlugin, { mount: "#app", routes: [...] }); await router.start(); // The returned router instance provides direct API access ``` -------------------------------- ### Eleva JS-First Component Example Source: https://elevajs.com/migration/from-alpine Illustrates an Eleva component structured as a JavaScript object with a setup function for state and a template function for rendering. This approach is JS-first and programmatic. ```javascript const Toggle = { setup({ signal }) { const open = signal(false); return { open, toggle: () => open.value = !open.value }; }, template: (ctx) => ` <div> <button @click="toggle">Toggle</button> ${ctx.open.value ? '<div>Content</div>' : ''} </div> ` }; ``` -------------------------------- ### Eleva Store Plugin Configuration Source: https://elevajs.com/llms Demonstrates the basic setup of the Eleva Store plugin, defining initial state and actions. It also shows how to access store state and dispatch actions from within an Eleva component. ```javascript import { Store } from "eleva/plugins"; app.use(Store, { state: { count: 0, user: null }, actions: { increment: (state) => state.count.value++, setUser: (state, user) => state.user.value = user } }); // In component: access via setup({ store }) setup: ({ store }) => ({ count: store.state.count, increment: () => store.dispatch("increment") }) ```