`
});
```
--------------------------------
### Eleva Setup Context Example
Source: https://github.com/tarekraafat/eleva/blob/master/docs/core-concepts.md
Demonstrates the usage of the setup context in Eleva components. The setup function receives utilities like `signal`, `emitter`, and `props`, which can be used to initialize component state and return values for the template.
```javascript
const MyComponent = {
setup: ({ signal, emitter, props }) => {
const counter = signal(0);
return { counter };
},
template: (ctx) => `
Counter: ${ctx.counter.value}
`,
};
```
--------------------------------
### Eleva Event Handler Examples
Source: https://github.com/tarekraafat/eleva/blob/master/docs/faq.md
Provides examples of correctly implementing event handlers in Eleva. It shows how to avoid the `ctx.` prefix, ensure functions are returned from `setup`, and use arrow functions for inline handlers with arguments.
```javascript
// Incorrect: @click="ctx.handleClick"
// Correct: @click="handleClick"
// Inline handler with arguments:
// @click="() => count.value++"
```
--------------------------------
### Eleva ES Module Example
Source: https://github.com/tarekraafat/eleva/blob/master/README.md
Demonstrates how to use Eleva with ES modules, including importing the library, creating an instance, defining a component with setup and template, and mounting it to the DOM. This example utilizes reactive signals for state management.
```javascript
// Import Eleva (using ES modules)
import Eleva from "eleva";
// Create a new Eleva instance
const app = new Eleva("MyApp");
// Define a component
app.component("HelloWorld", {
// The setup method is optional; if omitted, an empty state is used.
setup({ signal }) {
const count = signal(0);
return {
count,
onMount: ({ container, context }) => {
console.log('Component mounted!');
}
};
},
template: (ctx) => `
Hello, Eleva! 👋
Count: ${ctx.count.value}
`
});
// Mount the component and handle the Promise
app.mount(document.getElementById("app"), "HelloWorld")
.then(instance => {
console.log("Component mounted:", instance);
// Later...
// instance.unmount();
});
```
--------------------------------
### Installing Multiple Eleva Plugins
Source: https://github.com/tarekraafat/eleva/blob/master/docs/plugin-system.md
Provides an example of how to install multiple built-in Eleva plugins (Attr, Store, Router) onto an Eleva application instance.
```javascript
import Eleva from 'eleva';
import { Attr, Router, Store } from 'eleva/plugins';
const app = new Eleva("MyApp");
// Install plugins
app.use(Attr);
app.use(Store, { state: {} });
app.use(Router, { routes: [] });
```
--------------------------------
### Eleva: Dynamic Component Mounting Example
Source: https://github.com/tarekraafat/eleva/blob/master/docs/components.md
Demonstrates 'Dynamic' component mounting in Eleva, allowing for components to be defined inline with their own setup and template logic. This provides full control over component behavior and lifecycle, suitable for complex or context-dependent components.
```javascript
children: {
".dynamic-container": {
setup: ({ signal }) => ({
userData: signal({ name: "John", role: "admin" })
}),
template: (ctx) => ``,
children: { "user-card": "UserCard" }
}
}
```
--------------------------------
### Eleva.js Setup Return - Minimal Public API
Source: https://github.com/tarekraafat/eleva/blob/master/docs/examples/patterns/best-practices/setup-lifecycle.md
Illustrates the principle of returning only the necessary properties from the setup function to the template. It contrasts an example returning too much (internal variables and helper functions) with a 'better' example that only exposes what the template requires.
```javascript
// Avoid: Returning everything
setup: ({ signal }) => {
const count = signal(0);
const internalCache = new Map(); // Not needed in template
const helperFn = () => { /* ... */ }; // Only used internally
function increment() {
helperFn();
count.value++;
internalCache.set(count.value, Date.now());
}
return { count, increment, internalCache, helperFn }; // Too much!
}
// Better: Return only template-facing API
setup: ({ signal }) => {
const count = signal(0);
const internalCache = new Map();
const helperFn = () => { /* ... */ };
function increment() {
helperFn();
count.value++;
internalCache.set(count.value, Date.now());
}
return { count, increment }; // Only what template needs
}
```
--------------------------------
### Eleva Quick Start Counter Example
Source: https://github.com/tarekraafat/eleva/blob/master/docs/plugins/store/index.md
A quick start example demonstrating a functional counter component using Eleva. It includes state management for a count and actions to increment, decrement, reset, and set the count.
```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) => `
Count: ${ctx.count.value}
`
});
app.mount(document.getElementById("app"), "Counter");
// Result: Interactive counter with increment, decrement, and reset
```
--------------------------------
### Set Up Eleva Plugin Project (Bash)
Source: https://github.com/tarekraafat/eleva/blob/master/docs/examples/custom-plugin/development.md
Initializes a new project directory for an Eleva.js plugin, sets up npm, and installs necessary Eleva and development dependencies like Vite and Vitest.
```bash
mkdir eleva-simple-logger
cd eleva-simple-logger
npm init -y
npm install eleva --save-peer
npm install --save-dev vite vitest @types/node
```
--------------------------------
### Eleva Plugin API Example
Source: https://github.com/tarekraafat/eleva/blob/master/docs/faq.md
Demonstrates the structure of a custom Eleva plugin. Plugins are objects with an `install` method that receives the Eleva instance and options, allowing for extension of Eleva's functionality.
```javascript
const myPlugin = {
install(eleva, options) {
eleva.prototype.myCustomMethod = function() {
console.log('Custom method called!');
};
}
};
app.use(myPlugin);
```
--------------------------------
### Minimal Router Setup with Eleva.js
Source: https://github.com/tarekraafat/eleva/blob/master/docs/plugins/router/index.md
Demonstrates the basic setup for the Eleva.js Router plugin. It initializes Eleva, uses the Router plugin with specified options (mode, mount point, and routes), and automatically starts the router. Manual mounting of the app is not required when using this plugin.
```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)
```
--------------------------------
### Simple Eleva Project Structure Example
Source: https://github.com/tarekraafat/eleva/blob/master/docs/llms-full.txt
Illustrates a basic project structure for a small Eleva application. This setup is suitable for widgets, prototypes, or applications without complex routing, organizing code into logical directories like `src`, `components`, and `utils`.
```bash
my-eleva-app/
├── index.html
├── src/
│ ├── main.js # App initialization
│ ├── app.js # Eleva instance
│ ├── components/
│ │ ├── Counter.js # Component with inline style
│ │ ├── Header.js
│ │ └── index.js # Component exports
│ ├── utils/
│ │ └── helpers.js
│ └── styles/
│ └── main.css # Global styles only
└── package.json
```
--------------------------------
### Migration Guides
Source: https://github.com/tarekraafat/eleva/blob/master/docs/index.md
Guides to help migrate projects from other popular frameworks like React, Vue, and Alpine.js to Eleva.
```APIDOC
### Migration Guides
| From | Guide |
|---|---|
| React | [Migration Guide →](./migration/from-react.md) |
| Vue | [Migration Guide →](./migration/from-vue.md) |
| Alpine.js | [Migration Guide →](./migration/from-alpine.md) |
```
--------------------------------
### Full Eleva Store Configuration Example
Source: https://github.com/tarekraafat/eleva/blob/master/docs/plugins/store/configuration.md
This JavaScript snippet demonstrates a comprehensive configuration for the Eleva Store plugin. It includes initial state, action definitions, namespaced modules, persistence settings, DevTools enablement, and an error handling callback. This example showcases how to integrate various features of the Store plugin for a complete application setup.
```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
}
});
```
--------------------------------
### Safe Component Setup and Template Usage (JavaScript)
Source: https://github.com/tarekraafat/eleva/blob/master/docs/architecture.md
Illustrates safe patterns for defining components in Eleva. This includes setting up signals, using template expressions for dynamic data display, and handling events securely. These examples assume templates are developer-authored.
```javascript
// SAFE: Developer-authored template with dynamic data
app.component("UserGreeting", {
setup: ({ signal }) => {
const userName = signal("Alice");
return { userName };
},
template: (ctx) => `
Hello, ${ctx.userName.value}
`
});
// SAFE: Displaying user content (data, not template)
app.component("Comment", {
setup: ({ props }) => ({
// User content is DATA, safely interpolated as text
content: props.content
}),
template: (ctx) => `
${ctx.content}
`
});
// SAFE: Event handlers defined by developer
app.component("Button", {
setup: ({ signal }) => {
const handleClick = () => console.log("Clicked");
return { handleClick };
},
template: (ctx) => `
`
});
```
--------------------------------
### Installation Methods
Source: https://github.com/tarekraafat/eleva/blob/master/docs/index.md
Various methods to install and integrate Eleva into your project, including npm, CDN, and ESM imports.
```APIDOC
## Installation
### npm
```bash
npm install eleva
```
### CDN (jsDelivr)
```html
```
### CDN (unpkg)
```html
```
### ESM Import
```javascript
import Eleva from "eleva";
```
### Plugin Import
```javascript
import { Router, Store } from "eleva/plugins";
```
```
--------------------------------
### ES Modules Setup for Eleva Application
Source: https://github.com/tarekraafat/eleva/blob/master/docs/llms-full.txt
Illustrates setting up an Eleva application using ES Modules, which is a standard way to import and export JavaScript modules. This example shows how to import Eleva, define a root component, and mount it to a specified DOM element.
```javascript
// main.js
import Eleva from "eleva";
const app = new Eleva("MyApp");
app.component("App", {
setup: ({ signal }) => {
const message = signal("Hello, Eleva!");
return { message };
},
template: (ctx) => `
${ctx.message.value}
`
});
app.mount(document.getElementById("app"), "App");
```
--------------------------------
### Examples & Patterns
Source: https://github.com/tarekraafat/eleva/blob/master/docs/index.md
Resources for learning Eleva through examples and common patterns for state management, forms, lists, and async data.
```APIDOC
### Examples & Patterns
| Resource | Description |
|---|---|
| **[Examples](./examples/index.md)** | Real-world examples and tutorials |
| **[State Patterns](./examples/patterns/state/index.md)** | State management patterns |
| **[Form Patterns](./examples/patterns/forms.md)** | Form handling patterns |
| **[List Patterns](./examples/patterns/lists/index.md)** | List rendering patterns |
| **[Async Patterns](./examples/patterns/async-data/index.md)** | Async data fetching patterns |
```
--------------------------------
### Eleva App Mount Example
Source: https://github.com/tarekraafat/eleva/blob/master/docs/examples/apps/blog.md
This JavaScript code demonstrates how to mount the main 'Blog' application to the DOM element with the ID 'app' using the Eleva framework. It's the entry point for initializing the application.
```javascript
app.mount(document.getElementById("app"), "Blog");
```
--------------------------------
### Eleva Core Framework Only
Source: https://github.com/tarekraafat/eleva/blob/master/README.md
Illustrates how to import and initialize only the core Eleva framework for a lightweight setup. This approach is beneficial for minimizing bundle size when advanced features are not immediately required.
```javascript
import Eleva from 'eleva';
const app = new Eleva("myApp");
// Core framework only - ~6KB minified
```
--------------------------------
### Implement State Management in Eleva Plugin (JavaScript)
Source: https://github.com/tarekraafat/eleva/blob/master/docs/examples/custom-plugin/development.md
Adds a simple state management system to the Eleva instance within a plugin's install method. It provides methods to set and get key-value pairs in a shared state map and emits an event on state updates.
```js
install(eleva) {
eleva.store = {
state: new Map(),
set(key, value) {
this.state.set(key, value);
eleva.emitter.emit('store:update', { key, value });
},
get(key) {
return this.state.get(key);
}
};
}
```
--------------------------------
### Initialization: x-init vs. setup()
Source: https://github.com/tarekraafat/eleva/blob/master/docs/migration/from-alpine.md
Compares how Alpine.js and Eleva.js handle component initialization. Alpine uses the `x-init` directive for setup logic, often involving asynchronous operations like data fetching. Eleva achieves similar results using the `setup()` function, which runs when the component is mounted, also supporting asynchronous operations.
```html
`
};
```
--------------------------------
### Passing Props from Parent to Child in Eleva
Source: https://github.com/tarekraafat/eleva/blob/master/docs/components.md
Demonstrates how parent components pass data and event handlers to child components using `:prop` attributes. The child component receives these props via its `setup` function and uses them in its template. This example shows passing primitive values, objects, and functions.
```javascript
app.component("ProductList", {
setup: ({ signal }) => {
const products = signal([
{ id: 1, name: "Widget", price: 29.99 },
{ id: 2, name: "Gadget", price: 49.99 }
]);
function handleSelect(product) {
console.log("Selected:", product);
}
return { products, handleSelect };
},
template: (ctx) => `
`
});
```
--------------------------------
### Minimal Eleva.js Setup
Source: https://github.com/tarekraafat/eleva/blob/master/README.md
This snippet demonstrates the minimal setup for an Eleva.js application. It shows how to create a new Eleva app instance, define a simple counter component with reactive state using `signal`, and mount the component to the DOM. Dependencies include the 'eleva' package.
```javascript
import Eleva from "eleva";
const app = new Eleva("MyApp");
app.component("Counter", {
setup: ({ signal }) => ({ count: signal(0) }),
template: (ctx) => ``
});
app.mount(document.getElementById("app"), "Counter");
```
--------------------------------
### Start Eleva Development Server
Source: https://github.com/tarekraafat/eleva/blob/master/CONTRIBUTING.md
Starts the development server for the Eleva project, allowing for local testing and development. This command is typically used after installing dependencies.
```bash
npm run dev
```
--------------------------------
### Eleva Store Plugin Initialization and Usage (JavaScript)
Source: https://github.com/tarekraafat/eleva/blob/master/README.md
Demonstrates how to install and configure the Eleva Store plugin, define initial state and actions, and use the store within components. It also shows how to dynamically register modules, create individual state properties and actions, and subscribe to store changes. This snippet is essential for understanding the core functionality of the Store plugin.
```javascript
import Eleva from 'eleva';
import { Store } from 'eleva/plugins';
const app = new Eleva("myApp");
// Install store with configuration
app.use(Store, {
state: {
theme: "light",
counter: 0,
user: {
name: "John Doe",
email: "john@example.com"
}
},
actions: {
increment: (state) => state.counter.value++,
decrement: (state) => state.counter.value--,
toggleTheme: (state) => {
state.theme.value = state.theme.value === "light" ? "dark" : "light";
},
updateUser: (state, updates) => {
state.user.value = { ...state.user.value, ...updates };
}
},
// Optional: Namespaced modules
namespaces: {
auth: {
state: { token: null, isLoggedIn: false },
actions: {
login: (state, token) => {
state.auth.token.value = token;
state.auth.isLoggedIn.value = true;
},
logout: (state) => {
state.auth.token.value = null;
state.auth.isLoggedIn.value = false;
}
}
}
},
// Optional: State persistence
persistence: {
enabled: true,
key: "myApp-store",
storage: "localStorage", // or "sessionStorage"
include: ["theme", "user"] // Only persist specific keys
}
});
// Use store in components
app.component("Counter", {
setup({ store }) {
return {
count: store.state.counter,
theme: store.state.theme,
increment: () => store.dispatch("increment"),
decrement: () => store.dispatch("decrement")
};
},
template: (ctx) => `
Counter: ${ctx.count.value}
`
});
// Create state and actions at runtime
app.component("TodoManager", {
setup({ store }) {
// Register new module dynamically
store.registerModule("todos", {
state: { items: [], filter: "all" },
actions: {
addTodo: (state, text) => {
state.todos.items.value = [...state.todos.items.value, {
id: Date.now(),
text,
completed: false
}];
},
toggleTodo: (state, id) => {
const todo = state.todos.items.value.find(t => t.id === id);
if (todo) todo.completed = !todo.completed;
}
}
});
// Create individual state properties
const notification = store.createState("notification", null);
// Create individual actions
store.createAction("showNotification", (state, message) => {
state.notification.value = message;
setTimeout(() => state.notification.value = null, 3000);
});
return {
todos: store.state.todos.items,
notification,
addTodo: (text) => store.dispatch("todos.addTodo", text),
notify: (msg) => store.dispatch("showNotification", msg)
};
}
});
// Subscribe to store changes
const unsubscribe = app.store.subscribe((mutation, state) => {
console.log('Store updated:', mutation.type, state);
});
// Access store globally
console.log(app.store.getState()); // Get current state values
app.dispatch("increment"); // Dispatch actions globally
```
--------------------------------
### Eleva Installation Methods
Source: https://github.com/tarekraafat/eleva/blob/master/docs/index.md
Provides various methods for installing the Eleva framework. Includes package manager commands for npm and CDN links for direct script inclusion, as well as ESM and plugin import statements.
```bash
npm install eleva
```
```html
```
```html
```
```javascript
import Eleva from "eleva"
```
```javascript
import { Router, Store } from "eleva/plugins"
```
--------------------------------
### Test Plugin Registration - JavaScript
Source: https://github.com/tarekraafat/eleva/blob/master/docs/examples/custom-plugin/development.md
Tests the plugin registration process in Eleva, verifying that it throws an error for plugins lacking an 'install' method, returns the result of the 'install' method, and correctly passes options to the 'install' method. This ensures the plugin system handles various registration scenarios as expected.
```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' });
});
});
```
--------------------------------
### Extend Eleva Setup Context with Plugin
Source: https://github.com/tarekraafat/eleva/blob/master/docs/plugin-system.md
This JavaScript snippet shows a plugin pattern for extending the setup context in Eleva. The `install` method wraps the original `mount` function to inject custom utilities into the component's props before mounting.
```javascript
install(eleva) {
const originalMount = eleva.mount.bind(eleva);
eleva.mount = async (container, compName, props) => {
// Inject custom utilities into setup context
const enhancedProps = {
...props,
myUtility: () => { /* ... */ }
};
return originalMount(container, compName, enhancedProps);
};
}
```
--------------------------------
### Native JavaScript in Setup Function (JavaScript)
Source: https://github.com/tarekraafat/eleva/blob/master/docs/core-concepts.md
Demonstrates using native JavaScript APIs within the `setup` function of an Eleva component. This includes examples of Fetch API, localStorage, timers, URL manipulation, regular expressions, and Web APIs like IntersectionObserver.
```javascript
setup: ({ signal }) => {
const data = signal(null);
const loading = signal(true);
// Fetch API
const loadData = async () => {
const res = await fetch('/api/data');
data.value = await res.json();
};
// localStorage
const theme = signal(localStorage.getItem('theme') || 'light');
const saveTheme = (t) => {
theme.value = t;
localStorage.setItem('theme', t);
};
// setTimeout / setInterval
let timer = null;
const startTimer = () => {
timer = setInterval(() => { /* ... */ }, 1000);
};
// URL / URLSearchParams
const params = new URLSearchParams(window.location.search);
const query = signal(params.get('q') || '');
// Regular expressions
const isValidEmail = (email) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
// Web APIs (IntersectionObserver, ResizeObserver, etc.)
let observer = null;
return {
data, loading, theme, query,
loadData, saveTheme, startTimer, isValidEmail,
onMount: () => {
loadData();
observer = new IntersectionObserver(/* ... */);
},
onUnmount: () => {
clearInterval(timer);
observer?.disconnect();
}
};
}
```
--------------------------------
### Vuex/Pinia vs. Eleva Store Implementation
Source: https://github.com/tarekraafat/eleva/blob/master/docs/migration/from-vue.md
Illustrates the state management patterns of Pinia and Eleva, covering state definition, getters/computed properties, actions/dispatches, and component integration.
```javascript
// stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
user: null
}),
getters: {
doubleCount: (state) => state.count * 2
},
actions: {
increment() {
this.count++;
},
async fetchUser(id) {
this.user = await api.getUser(id);
}
}
});
// In component
import { useCounterStore } from '@/stores/counter';
const store = useCounterStore();
store.increment();
console.log(store.doubleCount);
```
```javascript
import Eleva from "eleva";
import { Store } from "eleva/plugins";
const app = new Eleva("App");
app.use(Store, {
state: {
count: 0,
user: null
},
actions: {
increment: (state) => state.count.value++,
fetchUser: async (state, id) => {
state.user.value = await api.getUser(id);
}
}
});
// In component
const Counter = {
setup({ store }) {
// Computed equivalent
const doubleCount = () => store.state.count.value * 2;
return {
count: store.state.count,
doubleCount,
increment: () => store.dispatch("increment"),
fetchUser: (id) => store.dispatch("fetchUser", id)
};
},
template: (ctx) => `
Count: ${ctx.count.value}
Double: ${ctx.doubleCount()}
`
};
```
--------------------------------
### Get All Plugins - JavaScript
Source: https://github.com/tarekraafat/eleva/blob/master/docs/plugins/router/api.md
Retrieves an array of all currently installed router plugins. This is useful for inspecting the router's configuration and active plugins.
```javascript
const plugins = router.getPlugins();
console.log('Installed plugins:', plugins);
```
--------------------------------
### Setup Eleva.js Application
Source: https://github.com/tarekraafat/eleva/blob/master/docs/cheatsheet.md
Demonstrates how to import Eleva.js, create a new application instance, register a component, and mount it to the DOM. This is the initial setup required for any Eleva.js 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 });
```
--------------------------------
### Basic Eleva App Setup with Attr Plugin
Source: https://github.com/tarekraafat/eleva/blob/master/docs/plugins/attr/index.md
Demonstrates the initial setup of an Eleva application instance and the installation of the Attr plugin. The plugin can be used with default options or with custom configurations to enable specific attribute handling features like ARIA, data, boolean, and dynamic properties.
```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
});
```
--------------------------------
### Setup Return Value: Exporting Only Necessary Values in JavaScript
Source: https://github.com/tarekraafat/eleva/blob/master/docs/best-practices.md
Demonstrates how to optimize the return value of a setup function by exporting only the values that the template needs. This avoids exposing internal implementation details and reduces the bundle size. It contrasts an 'everything' approach with a 'template-facing API' approach.
```javascript
setup: ({ signal }) => {
const count = signal(0);
const internalCache = new Map(); // Not needed in template
const helperFn = () => { /* ... */ }; // Only used internally
return { count, increment, internalCache, helperFn }; // Too much!
}
// Better: Return only template-facing API
setup: ({ signal }) => {
const count = signal(0);
const internalCache = new Map();
const helperFn = () => { /* ... */ };
function increment() {
helperFn();
count.value++;
internalCache.set(count.value, Date.now());
}
return { count, increment }; // Only what template needs
}
```
--------------------------------
### Compose Multiple Plugins in Eleva (JavaScript)
Source: https://github.com/tarekraafat/eleva/blob/master/docs/examples/custom-plugin/development.md
Defines a composed plugin that utilizes other plugins (Logger and Store) during its installation. This demonstrates how to structure plugins that depend on or extend the functionality of other plugins.
```js
const ComposedPlugin = {
name: "composed",
version: "1.0.0",
install(eleva, options) {
// Use other plugins
eleva.use(Logger, options.logger);
eleva.use(Store, options.store);
}
};
```
--------------------------------
### LIFO Uninstall Order Example (JavaScript)
Source: https://github.com/tarekraafat/eleva/blob/master/docs/plugin-system.md
Demonstrates the correct Last-In, First-Out (LIFO) order for uninstalling plugins to maintain the integrity of method wrapping. Incorrect order can break the wrapper chain.
```javascript
// Installation order
app.use(PluginA); // Wraps mount first
app.use(PluginB); // Wraps mount second (wraps PluginA's wrapper)
// Uninstall in reverse order
PluginB.uninstall(app); // Unwrap second layer first
PluginA.uninstall(app); // Unwrap first layer last
```
--------------------------------
### Create and Mount Eleva Application Instance
Source: https://context7.com/tarekraafat/eleva/llms.txt
Demonstrates how to create a new Eleva application instance, register a component with its setup, template, and style, and then mount the component to a DOM element. It also shows how to unmount the component later.
```javascript
import Eleva from "eleva";
// Create an application instance
const app = new Eleva("MyApp");
// Register a component
app.component("Counter", {
setup({ signal }) {
const count = signal(0);
const increment = () => count.value++;
return { count, increment };
},
template: (ctx) => `
Count: ${ctx.count.value}
`,
style: `
button { padding: 8px 16px; cursor: pointer; }
p { font-size: 1.5rem; }
`
});
// Mount to DOM
const instance = await app.mount(document.getElementById("app"), "Counter");
// Later: unmount the component
await instance.unmount();
```
--------------------------------
### Eleva Plugin Usage Example (JavaScript)
Source: https://github.com/tarekraafat/eleva/blob/master/docs/examples/custom-plugin/best-practices.md
Demonstrates how to install and use a custom Eleva plugin within a JavaScript application. It shows the import process and how to integrate the plugin with the Eleva application instance.
```javascript
import Eleva from 'eleva';
import MyPlugin from 'eleva-my-plugin';
const app = new Eleva('MyApp');
app.use(MyPlugin, { option: 'value' });
```
--------------------------------
### Bun Test Configuration Example
Source: https://github.com/tarekraafat/eleva/blob/master/test/README.md
Example `bunfig.toml` file demonstrating test configuration options. This includes setting up preload scripts, test timeouts, and coverage settings.
```toml
[test]
preload = ["./test/setup.ts"]
timeout = 30000
coverage = true
coverageDir = "./test/coverage"
```
--------------------------------
### Add a New Component Type via Plugin
Source: https://github.com/tarekraafat/eleva/blob/master/docs/plugin-system.md
Demonstrates how a plugin can introduce new component types to Eleva. The `install` function uses `eleva.component()` to register a new component with its template and setup logic.
```javascript
install(eleva) {
eleva.component("enhanced-component", {
template: (ctx) => `...`,
setup: (ctx) => ({ /* ... */ })
});
}
```
--------------------------------
### Eleva UMD Example
Source: https://github.com/tarekraafat/eleva/blob/master/README.md
Shows how to integrate Eleva using a UMD (Universal Module Definition) script tag, making the Eleva global available for use. This example is suitable for environments where module bundlers are not used.
```html
Eleva Example
```
--------------------------------
### Eleva: Variable-Based Component Mounting Example
Source: https://github.com/tarekraafat/eleva/blob/master/docs/components.md
Explains 'Variable-Based' component mounting in Eleva, where components are referenced from variables. This approach is useful for components defined dynamically or stored in variables, avoiding the need for global registration.
```javascript
const UserCard = {
setup: (ctx) => ({ /* setup logic */ }),
template: (ctx) => `
`,
children: {
".user-card-container": UserCard, // Mount from variable
},
});
```
--------------------------------
### Minimal HTML Setup with CDN
Source: https://github.com/tarekraafat/eleva/blob/master/docs/llms-full.txt
Demonstrates how to set up a basic Eleva application using a Content Delivery Network (CDN) directly within an HTML file. This includes initializing the Eleva app, defining a simple counter component with signals and event handling, and mounting it to the DOM.
```html
My Eleva App
```
--------------------------------
### Eleva: Direct Component Mounting Example
Source: https://github.com/tarekraafat/eleva/blob/master/docs/components.md
Illustrates the 'Direct' type of children mounting in Eleva, where a component is mounted directly using its tag name. This method is suitable for simple component composition and offers the best performance.
```javascript
children: {
"user-card": "UserCard" // Direct mounting without container
}
```