### Install HellaJS Packages and Vite Plugin
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/learn/quick-start.mdx
Installs the core HellaJS packages (@hellajs/core, @hellajs/dom) and the Vite plugin (vite-plugin-hellajs) required for HellaJS development within a Vite project.
```bash
cd my-hella-app
npm install @hellajs/core @hellajs/dom
npm install -D vite-plugin-hellajs
```
--------------------------------
### HellaJS Local Development Setup
Source: https://github.com/omilli/hellajs-docs/blob/master/GEMINI.md
Outlines the command-line steps required to set up and run the HellaJS documentation locally. This includes navigating to the docs directory, installing dependencies, and starting the development server.
```bash
cd docs
bun install
bun dev
```
--------------------------------
### Start Vite Development Server
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/learn/quick-start.mdx
Command to start the Vite development server, allowing you to see the HellaJS application in action during development. The app typically runs at http://localhost:5173.
```bash
npm run dev
```
--------------------------------
### Configure Vite with HellaJS Plugin
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/learn/quick-start.mdx
Demonstrates how to configure the Vite build process by adding the vite-plugin-hellajs to the `vite.config.js` file, enabling HellaJS features.
```javascript
// vite.config.js
import { defineConfig } from 'vite';
import viteHellaJS from 'vite-plugin-hellajs';
export default defineConfig({
plugins: [viteHellaJS()],
});
```
--------------------------------
### Scaffold Vite Project with npm
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/learn/quick-start.mdx
Creates a new Vite project using npm, specifically templated for vanilla JavaScript, as the first step in setting up a HellaJS application.
```bash
npm create vite@latest my-hella-app -- --template vanilla
```
--------------------------------
### Complete Vite Project Setup with HellaJS
Source: https://github.com/omilli/hellajs-docs/blob/master/public/llms.txt
Steps to create a new Vite project with TypeScript, install HellaJS core packages, and the Vite plugin.
```bash
# Create project
npm create vite@latest my-hella-app -- --template vanilla-ts
# Install HellaJS
cd my-hella-app
npm install @hellajs/core @hellajs/dom @hellajs/store @hellajs/resource @hellajs/router @hellajs/css
# Install Vite plugin
npm install -D vite-plugin-hellajs
# Optional: Install testing tools
npm install -D vitest @vitest/ui jsdom @testing-library/jest-dom
```
--------------------------------
### Install HellaJS Packages
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/learn/tutorials/todo-app.mdx
Installs the necessary HellaJS core, DOM, and store packages, along with the Vite plugin and Tailwind CSS for project setup.
```bash
cd todo-app
npm install @hellajs/core @hellajs/dom @hellajs/store
npm install -D vite-plugin-hellajs @tailwindcss/vite@next
```
--------------------------------
### Create Basic HellaJS App Component
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/learn/quick-start.mdx
Provides the core JavaScript/JSX code for a simple HellaJS application, demonstrating the use of signals for state management and mounting a component to the DOM using HellaJS.
```jsx
// main.js
import { signal } from "@hellajs/core";
import { mount } from "@hellajs/dom";
const App = () => {
const count = signal(0);
return (
<>
Hello, HellaJS!
>
);
};
mount(App, '#app');
```
--------------------------------
### HellaJS Development Workflow Example
Source: https://github.com/omilli/hellajs-docs/blob/master/public/llms.txt
Example of a main application file using HellaJS signals and DOM mounting within a Vite project.
```javascript
// main.tsx
import { signal } from '@hellajs/core';
import { mount } from '@hellajs/dom';
import './style.css';
const App = () => {
const count = signal(0);
return (
HellaJS + Vite
);
};
mount(App, '#app');
// Hot module replacement support
if (import.meta.hot) {
import.meta.hot.accept();
}
```
--------------------------------
### Install @hellajs/store
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/reference/index.mdx
This snippet shows how to install the @hellajs/store package using npm.
```bash
npm install @hellajs/store
```
--------------------------------
### Install @hellajs/resource
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/reference/index.mdx
Installs the @hellajs/resource package, which enables reactive data fetching with integrated caching, loading state management, and error handling.
```bash
npm install @hellajs/resource
```
--------------------------------
### Install @hellajs/core
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/reference/index.mdx
Installs the core HellaJS package, which provides reactive primitives like signals, computed values, and effects for building reactive applications.
```bash
npm install @hellajs/core
```
--------------------------------
### SolidJS onMount and onCleanup for Lifecycle Management
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/learn/migrating/solid.mdx
Demonstrates SolidJS's component-scoped lifecycle hooks `onMount` and `onCleanup`. This example uses `onMount` to start a timer and `onCleanup` to clear it.
```jsx
function Timer() {
const [count, setCount] = createSignal(0);
onMount(() => {
const interval = setInterval(() => {
setCount(prev => prev + 1);
}, 1000);
onCleanup(() => clearInterval(interval));
});
return
Timer: {count()}
;
}
```
--------------------------------
### Install Vite Plugin for HellaJS
Source: https://github.com/omilli/hellajs-docs/blob/master/public/llms.txt
Installs the Vite plugin for HellaJS using npm. This plugin is recommended for Vite projects.
```bash
npm install --save-dev vite-plugin-hellajs
```
--------------------------------
### Install @hellajs/dom
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/reference/index.mdx
Installs the @hellajs/dom package, which provides utilities for rendering reactive components and managing DOM interactions with lifecycle support.
```bash
npm install @hellajs/dom
```
--------------------------------
### Basic HellaJS Router Setup
Source: https://github.com/omilli/hellajs-docs/blob/master/public/llms.txt
Demonstrates a basic setup for the HellaJS router, including importing necessary functions, defining a signal for view management, configuring routes for different paths, and rendering components based on the current route. It also shows how to use the navigate function for programmatic navigation.
```jsx
import { signal } from '@hellajs/core';
import { router, navigate, route } from '@hellajs/router';
const currentView = signal(null);
router({
routes: {
'/': () => currentView(),
'/about': () => currentView(),
'/users/:id': (params) => currentView(),
'/search': (params, query) => currentView()
},
notFound: () => currentView()
});
const App = () => (
{currentView}
);
```
--------------------------------
### Install HellaJS Packages
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/learn/tutorials/counter-app.mdx
Installs the necessary HellaJS core and DOM packages, along with Vite plugins for HellaJS and Tailwind CSS, for a new Vite project.
```bash
npm create vite@latest counter-app -- --template vanilla
cd counter-app
npm install @hellajs/core @hellajs/dom
npm install -D vite-plugin-hellajs @tailwindcss/vite@next
```
--------------------------------
### HellaJS API: Router Setup (MDX)
Source: https://github.com/omilli/hellajs-docs/blob/master/GEMINI.md
Documentation for setting up the `Router` component in HellaJS to manage application routing.
```MDX
import { Router } from 'hellajs';
# Router Setup
Configure your application's router.
```javascript
{/* Define routes here */}
```
```
--------------------------------
### Install @hellajs/router
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/reference/index.mdx
Installs the @hellajs/router package, designed for client-side routing in single-page applications, featuring reactive navigation state management.
```bash
npm install @hellajs/router
```
--------------------------------
### Install Vite HellaJS Plugin
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/plugins/vite.mdx
Installs the Vite plugin for HellaJS as a development dependency using npm.
```bash
npm install --save-dev vite-plugin-hellajs
```
--------------------------------
### Install Babel Plugin
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/plugins/babel.mdx
Installs the babel-plugin-hellajs package as a development dependency using npm.
```bash
npm install --save-dev babel-plugin-hellajs
```
--------------------------------
### Configure TypeScript for HellaJS DOM Types
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/learn/quick-start.mdx
Shows how to update the `tsconfig.json` file to include type definitions for HellaJS DOM, specifically adding '@hellajs/dom' to the 'types' array in compilerOptions for TypeScript projects.
```json
{
"compilerOptions": {
//...
"jsx": "preserve",
"types": ["@hellajs/dom"]
//...
}
}
```
--------------------------------
### Install Rollup Plugin for HellaJS
Source: https://github.com/omilli/hellajs-docs/blob/master/public/llms.txt
Installs the Rollup plugin for HellaJS using npm. This plugin is used for bundling projects with Rollup.
```bash
npm install --save-dev rollup-plugin-hellajs
```
--------------------------------
### Install @hellajs/css
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/reference/index.mdx
Installs the @hellajs/css package, a type-safe CSS-in-JS solution that offers reactive styling and automatic vendor prefixing for web applications.
```bash
npm install @hellajs/css
```
--------------------------------
### Run HellaJS Development Server
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/learn/tutorials/todo-app.mdx
This command starts the development server for your HellaJS application. It allows you to see your changes live and typically runs on a local host address.
```bash
npm run dev
```
--------------------------------
### HellaJS Todo App Tutorial (MDX)
Source: https://github.com/omilli/hellajs-docs/blob/master/GEMINI.md
This tutorial guides users through creating a Todo list application with HellaJS, showcasing state management and UI updates.
```MDX
import { signal } from 'hellajs';
# Todo App Tutorial
Manage your todos.
```javascript
const todos = signal([]);
const newTodo = signal('');
function addTodo() {
todos.value = [...todos.value, { id: Date.now(), text: newTodo.value }];
newTodo.value = '';
}
```
```
--------------------------------
### Component Functions Example
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/reference/dom/mount.mdx
Highlights that HellaJS components are plain functions returning HellaNodes, requiring no special classes or syntax. This example shows a simple Greeting component.
```jsx
const Greeting = (props) =>
Hello, {props.name}!
;
const App = () => ;
mount(App);
```
--------------------------------
### MDX Code Demonstration Component
Source: https://github.com/omilli/hellajs-docs/blob/master/GEMINI.md
The 'CodeExample.mdx' component is designed to display code snippets within Markdown files, allowing for syntax highlighting and interactive examples.
```MDX
import { CodeBlock } from '@astrojs/mdx';
## Example Usage
```javascript
console.log('Hello, HellaJS!');
```
```
--------------------------------
### Reactive Context Example
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/reference/dom/mount.mdx
Illustrates how `mount` establishes a reactive root, enabling automatic DOM updates when signal values change. The example shows a simple counter where the displayed count updates reactively.
```jsx
const count = signal(0);
const App = () =>
Count: {count}
;
mount(App, '#app'); // DOM updates automatically when count changes
```
--------------------------------
### Render HellaJS Migration Guides
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/learn/index.mdx
Renders a grid of cards for HellaJS migration guides using the `migrationCards` data. It maps over the array to create individual links, each displaying a framework icon and its name. The cards are styled with Tailwind CSS for a clean, clickable appearance.
```astro
```
--------------------------------
### Fragment Support Example
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/reference/dom/mount.mdx
Illustrates how to render multiple top-level elements without a wrapper div using fragments (`<>...>`). This allows for more flexible DOM structures.
```jsx
const App = () => (
<>
HeaderMain content
>
);
```
--------------------------------
### TypeScript Component Example
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/reference/dom/mount.mdx
Demonstrates how to create and mount a HellaJS component using TypeScript. Components are functions returning HellaNodes, and props can be typed for better correctness.
```typescript
import { type HellaNode } from '@hellajs/dom';
interface MyComponentProps {
message: string;
}
// A component is just a function that returns a HellaNode
const MyComponent = (props: MyComponentProps): HellaNode => {
return
{props.message}
;
};
mount(() => );
```
--------------------------------
### HellaJS Migration from React (MDX)
Source: https://github.com/omilli/hellajs-docs/blob/master/GEMINI.md
This MDX file provides guidance and code examples for migrating applications from React to HellaJS.
```MDX
# Migrating from React
Key differences and migration steps.
**React:** `useState`
**HellaJS:** `signal`
```javascript
// React example
// const [count, setCount] = React.useState(0);
// HellaJS equivalent
// import { signal } from 'hellajs';
// const count = signal(0);
```
```
--------------------------------
### Configure Vitest for HellaJS
Source: https://github.com/omilli/hellajs-docs/blob/master/public/llms.txt
Sets up Vitest with the vite-plugin-hellajs plugin for testing HellaJS applications. It specifies the testing environment as 'jsdom' and includes a setup file for global imports and mocks.
```javascript
// vitest.config.js
import { defineConfig } from 'vitest/config';
import viteHellaJS from 'vite-plugin-hellajs';
export default defineConfig({
plugins: [viteHellaJS()],
test: {
environment: 'jsdom',
setupFiles: ['./src/test-setup.js']
}
});
// src/test-setup.js
import '@testing-library/jest-dom';
// Mock DOM APIs if needed
global.ResizeObserver = class ResizeObserver {
observe() {}
unobserve() {}
disconnect() {}
};
```
--------------------------------
### Route Information Example (Flat and Nested)
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/reference/router/route.mdx
Illustrates how to extract path, params, and query from the `route` signal for both flat and nested routing structures, including parameter inheritance.
```typescript
// For URL: /users/123?sort=name&page=2 (flat route)
const { path, params, query } = route();
// path: "/users/123?sort=name&page=2"
// params: { id: "123" }
// query: { sort: "name", page: "2" }
// For URL: /admin/users/123/edit (nested route with inheritance)
// Router config: /admin -> /users -> /:id -> /edit
const { path, params, query } = route();
// path: "/admin/users/123/edit"
// params: { id: "123" } (inherited from parent route)
// query: {}
```
--------------------------------
### Svelte Component Props Example
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/learn/migrating/svelte.mdx
Illustrates how to define and use component props in Svelte. It shows the `export let` syntax for declaring props and how to pass them during component usage.
```svelte
{displayName}
{#if showEmail}
{user.email}
{/if}
```
--------------------------------
### Vue Template Syntax Example
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/learn/migrating/vue.mdx
Demonstrates Vue 3's template syntax using directives like v-if, v-for, and event binding with @click. It includes a script setup block for component logic.
```vue
{{ title }}
{{ message }}
No message
{{ item.name }}
```
--------------------------------
### Basic Usage of @hellajs/store
Source: https://github.com/omilli/hellajs-docs/blob/master/public/llms.txt
Demonstrates the fundamental usage of the @hellajs/store library, showing how to create a store with initial data, access properties using getter syntax, and update properties using setter syntax for reactive updates.
```javascript
import { store } from '@hellajs/store';
const user = store({
name: 'John',
email: 'john@example.com',
preferences: {
theme: 'dark',
language: 'en'
}
});
// Each property is reactive
console.log(user.name()); // 'John'
user.name('Jane'); // Only name-dependent code updates
// Nested properties are also reactive
console.log(user.preferences.theme()); // 'dark'
user.preferences.theme('light'); // Only theme-dependent code updates
```
--------------------------------
### Install Rollup Plugin
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/plugins/rollup.mdx
Installs the Rollup plugin for HellaJS as a development dependency using npm.
```bash
npm install --save-dev rollup-plugin-hellajs
```
--------------------------------
### JavaScript: Basic mount usage example
Source: https://github.com/omilli/hellajs-docs/blob/master/public/llms.txt
Demonstrates the basic usage of the `mount` function in JavaScript to render a simple `App` component to the DOM. The component displays a counter and a button to increment it, mounting to the default '#app' selector.
```javascript
import { mount } from '@hellajs/dom';
const App = () => {
const count = signal(0);
return (
Count: {count}
);
};
mount(App, '#app'); // Defaults to '#app' if selector not provided
```
--------------------------------
### HellaJS Migration Guides Cards
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/learn/index.mdx
Defines an array of objects, each representing a migration guide from another framework to HellaJS. Each object includes a link, an icon name, icon color, and the framework's title (e.g., React, Vue, Svelte). This data is used to display links to tailored migration guides.
```javascript
export const migrationCards = [
{
href: "/learn/migrating/react",
icon: "simple-icons:react",
iconColor: "text-[#61DAFB]",
title: "React"
},
{
href: "/learn/migrating/vue",
icon: "simple-icons:vuedotjs",
iconColor: "text-[#4FC08D]",
title: "Vue"
},
{
href: "/learn/migrating/svelte",
icon: "simple-icons:svelte",
iconColor: "text-[#FF3E00]",
title: "Svelte"
},
{
href: "/learn/migrating/solid",
icon: "simple-icons:solid",
iconColor: "text-[#2C4F7C]",
title: "Solid"
},
{
href: "/learn/migrating/angular",
icon: "simple-icons:angular",
iconColor: "text-[#DD0031]",
title: "Angular"
}
];
```
--------------------------------
### HellaJS Router Navigation Methods
Source: https://github.com/omilli/hellajs-docs/blob/master/public/llms.txt
Provides examples of using the `navigate` function in HellaJS router for programmatic navigation. It covers basic navigation, navigation with query parameters, and navigation with both parameters and query parameters.
```javascript
// Basic navigation
navigate('/users/123');
// With query parameters
navigate('/search', {}, { q: 'hello', page: '2' });
// With parameters and query
navigate('/users/:id/posts', { id: '123' }, { sort: 'date' });
```
--------------------------------
### Install Babel Plugin for HellaJS
Source: https://github.com/omilli/hellajs-docs/blob/master/public/llms.txt
Installs the Babel plugin for HellaJS using npm. This plugin is used for transforming JSX syntax.
```bash
npm install --save-dev babel-plugin-hellajs
```
--------------------------------
### HellaJS Basic Router Usage
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/reference/router/router.mdx
Provides a foundational example of setting up client-side routing with HellaJS. It showcases defining static, dynamic, and wildcard routes, along with handling query parameters. This snippet also includes imports for HellaJS signals.
```typescript
import { router } from "@hellajs/router";
import { signal } from "@hellajs/core";
const currentView = signal('Loading...');
const appData = signal({});
router({
routes: {
// Static route
"/": (params, query) => {
currentView('HomePage');
return { page: 'home' };
},
// Dynamic route with a parameter
"/users/:id": (params, query) => {
currentView(`UserProfile: ${params.id}`);
return {
page: 'userProfile',
userId: params.id,
user: loadUser(params.id)
};
},
// Wildcard route
"/files/*": (params, query) => {
const filePath = params['*'];
currentView(`FileViewer: ${filePath}`);
return {
page: 'fileViewer',
filePath,
content: loadFile(filePath)
};
},
// Route with query parameters
"/search": (params, query) => {
currentView(`SearchResults: ${query.q}`);
return {
page: 'search',
term: query.q,
results: performSearch(query.q)
};
}
}
});
```
--------------------------------
### Store Methods: Set, Update, and Cleanup
Source: https://github.com/omilli/hellajs-docs/blob/master/public/llms.txt
Illustrates the various methods available on a @hellajs/store instance, including `set` for complete state replacement, `update` for partial deep merging, and `cleanup` for memory management.
```javascript
// Individual property access
user.name(); // getter
user.name('Jane'); // setter
// Complete replacement
user.set({
name: 'Alice',
email: 'alice@example.com',
preferences: { theme: 'light', language: 'es' }
});
// Partial deep merge
user.update({
preferences: { theme: 'dark' } // Merges with existing preferences
});
// Cleanup (important for memory management)
user.cleanup();
```
--------------------------------
### JavaScript Memory Management Example
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/reference/css/css.mdx
Provides an example of how reference counting works for memory management, including creating, sharing, and removing styles.
```javascript
const styles = { color: 'blue' };
// Create a style (ref count = 1)
const buttonStyle = css(styles);
// Identical objects share rules and increment reference count (ref count = 2)
const sameStyle = css(styles);
// Remove a reference (ref count = 1)
cssRemove(styles);
// Remove the last reference (ref count = 0, CSS rule removed from DOM)
cssRemove(styles);
```
--------------------------------
### HellaJS Counter App Tutorial (MDX)
Source: https://github.com/omilli/hellajs-docs/blob/master/GEMINI.md
A step-by-step tutorial demonstrating how to build a simple counter application using HellaJS core concepts like signals and effects.
```MDX
import { signal, effect } from 'hellajs';
# Counter App Tutorial
Let's build a counter.
```javascript
const count = signal(0);
effect(() => {
console.log('Count changed:', count.value);
});
function increment() {
count.value++;
}
```
```
--------------------------------
### HellaJS Effect Cleanup Function Example
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/reference/core/effect.mdx
Provides an example of managing resources within a HellaJS effect, such as an interval, and demonstrates how to call the returned cleanup function.
```typescript
const cleanup = effect(() => {
const interval = setInterval(() => console.log('tick'), 1000);
// Note: Effect functions cannot return cleanup - manage resources manually
});
// Call cleanup when no longer needed
cleanup();
```
--------------------------------
### Basic resource Usage
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/reference/resource/resource.mdx
Illustrates the basic usage of the `resource` function, including creating a resource, observing its reactive state using `effect`, and initiating data fetching with `.fetch()`. It highlights that data fetching is not automatic upon creation.
```javascript
import { resource } from '@hellajs/resource';
import { effect } from '@hellajs/core';
// 1. Create the resource
const usersResource = resource (() =>
fetch('https://api.example.com/users').then(r => r.json())
);
// 2. Use its reactive state
effect(() => {
console.log(`Status: ${usersResource.status()}`);
if (usersResource.data()) {
console.log('Users:', usersResource.data().length);
}
});
// 3. Start fetching
usersResource.fetch();
```
--------------------------------
### Render HellaJS Tutorial Cards
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/learn/index.mdx
Renders a grid of cards for HellaJS tutorials using the `tutorialCards` data. It maps over the array to create individual cards, each displaying an icon, title, description, and a 'Start Tutorial' button linking to the respective tutorial. Tailwind CSS is used for styling.
```astro
```
--------------------------------
### Key-Based Optimization Example
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/reference/dom/foreach.mdx
Provides an example of key-based optimization in JSX using forEach. It highlights the use of a stable `id` property from data items for efficient tracking and updating of DOM nodes.
```jsx
const items = signal([
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
]);
{forEach(items, (item) =>
{item.name}
// Uses item.id for tracking
)}
```
--------------------------------
### HellaJS Tutorial Cards
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/learn/index.mdx
Defines an array of objects, each representing a tutorial for HellaJS. Each object includes an icon, title, description, a link to the tutorial, and button text. This data is used to display interactive tutorials like the Counter App and Todo App.
```javascript
export const tutorialCards = [
{
icon: "ph:list-numbers",
title: "Counter App",
description: "Build an interactive counter to learn reactive fundamentals, event handling, and component structure.",
href: "/learn/tutorials/counter-app",
buttonText: "Start Tutorial",
},
{
icon: "ph:check-square",
title: "Todo App",
description: "Create a full-featured todo application exploring state management, data persistence, and complex interactions.",
href: "/learn/tutorials/todo-app",
buttonText: "Start Tutorial",
}
];
```
--------------------------------
### HellaJS Signal for Reactive State
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/learn/migrating/vue.mdx
Shows how to use HellaJS `signal` to create reactive state that automatically updates dependent DOM elements. This example mirrors the Vue example with a greeting and a counter.
```jsx
const App = () => {
const name = signal('World');
const count = signal(0);
return (
Hello, {name}!
Count: {count}
name(e.target.value)} />
);
};
```
--------------------------------
### HellaJS Store Basic Usage with Reactivity
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/reference/store/store.mdx
Illustrates basic usage of the HellaJS store by creating a store with a plain JavaScript object and demonstrating how to access and update properties using signal functions within an effect.
```javascript
import { store } from '@hellajs/store';
import { effect } from '@hellajs/core';
const user = store({
name: 'John Doe',
address: {
city: 'New York',
},
});
effect(() => {
console.log(`${user.name()} lives in ${user.address.city()}`);
});
// Logs: "John Doe lives in New York"
// Update a top-level property
user.name('Jane Doe');
// Logs: "Jane Doe lives in New York"
// Update a nested property
user.address.city('San Francisco');
// Logs: "Jane Doe lives in San Francisco"
```
--------------------------------
### Basic Routing Setup
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/learn/concepts/routing.mdx
Sets up client-side routing with a configuration object mapping URL patterns to handler functions. It includes a fallback for undefined routes. Dependencies include '@hellajs/router' and '@hellajs/core' for signals.
```jsx
import { router, navigate } from '@hellajs/router';
import { signal } from '@hellajs/core';
const currentView = signal('Loading...');
const renderView = (content) => { currentView(content); };
router({
routes: {
'/': () => renderView('Home'),
'/about': () => renderView('About'),
'/todos': () => renderView('TodoList'),
'/todos/:id': (params, query) => renderView(`TodoDetail: ${params.id}`)
},
notFound: () => renderView('404 Not Found')
});
```
--------------------------------
### Client-Side Routing with @hellajs/router
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/reference/index.mdx
Demonstrates setting up client-side routing using @hellajs/router, including defining routes, handling route parameters, implementing route guards, and programmatic navigation.
```typescript
import { mount } from '@hellajs/dom';
import { router, navigate } from '@hellajs/router';
mount(<>Loading...>);
router({
routes: {
'/': () => mount(),
'/users/:id': (params) => mount(),
'/settings': {
before: () => checkAuth(), // Guard route with authentication
handler: () => mount()
}
},
notFound: () => mount()
});
// Programmatic navigation
navigate('/users/123');
navigate('/settings');
```
--------------------------------
### JSX Automatic Cleanup Example
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/reference/css/cssremove.mdx
Explains HellaJS's automatic cleanup feature where styles are removed when their reference count reaches zero. This example shows multiple components using the same style and how cleanup occurs.
```jsx
const styles = {
color: 'blue',
fontSize: '16px'
};
// Multiple components using the same style
const style1 = css(styles); // ref count: 1
const style2 = css(styles); // ref count: 2
const style3 = css(styles); // ref count: 3
// Components cleanup as they unmount
cssRemove(styles); // ref count: 2 (rule stays in DOM)
cssRemove(styles); // ref count: 1 (rule stays in DOM)
cssRemove(styles); // ref count: 0 (rule removed from DOM)
```
--------------------------------
### JSX Usage: Fresh State Guarantee Example
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/reference/css/cssreset.mdx
Provides a practical example of how cssReset ensures a fresh state by demonstrating the creation and reuse of styles before and after a reset. It highlights how counters and caches are cleared, leading to predictable style generation.
```jsx
// Build up system state
css({ color: 'red' }); // Creates .c1
css({ color: 'blue' }); // Creates .c2
css({ color: 'red' }); // Reuses .c1 (ref count: 2)
cssReset(); // Complete system cleanup
// Fresh start - all counters and caches cleared
css({ color: 'red' }); // Creates .c1 again (fresh)
css({ color: 'blue' }); // Creates .c2 again (fresh)
```
--------------------------------
### Parameter Validation Examples in TypeScript
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/reference/router/navigate.mdx
Demonstrates correct and incorrect usage of parameter substitution in HellaJS navigation, showing how invalid or missing keys result in malformed URLs. Includes a best practice example of validating parameters before navigation.
```typescript
// ✅ Correct parameter key
navigate('/users/:id', { id: '123' });
// Results in: /users/123
// ❌ Wrong key, param not substituted - creates malformed URL
navigate('/users/:id', { userId: '123' });
// Results in: /users/:id (malformed - :id remains in URL)
// ❌ Missing required parameter - creates malformed URL
navigate('/users/:id/posts/:postId', { id: '123' });
// Results in: /users/123/posts/:postId (malformed - :postId remains)
// ✅ Best practice: validate parameters before navigation
const navigateToUser = (userId) => {
if (!userId) {
console.error('User ID is required');
return;
}
navigate('/users/:id', { id: userId });
};
```
--------------------------------
### UserProfile: Fetch User Data with Lifecycle Hooks
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/learn/concepts/resources.mdx
Demonstrates fetching user data using `resource`, setting initial data, and handling success/error callbacks. It also shows how to switch users and invalidate the cache.
```jsx
const UserProfile = () => {
const userId = signal(1);
const user = resource(
id => fetch(`/api/users/${id}`).then(r => r.json()),
{
key: () => userId(),
initialData: { name: 'Loading...', email: '' }, // Shown immediately
onSuccess: (userData) => {
console.log('User loaded:', userData.name);
// Could trigger analytics, notifications, etc.
},
onError: (error) => {
console.error('Failed to load user:', error);
// Could trigger error reporting
}
}
);
user.request();
return (
{user.data().name}
{user.data().email}
{user.loading() &&
Updating...
}
{user.error() && (
Failed to load user data
)}
Status: {user.status()}.
);
};
```
--------------------------------
### App Component Composition Example in JSX
Source: https://github.com/omilli/hellajs-docs/blob/master/public/llms.txt
Demonstrates the usage of Card and Modal components within an App component. It shows how to compose components and manage modal visibility using HellaJS signals.
```jsx
// Usage
const App = () => {
const showModal = signal(false);
return (
Welcome to our application!
showModal(false)}
title="Confirmation"
>
Are you sure you want to proceed?
);
};
```
--------------------------------
### HellaJS Advanced JSX Binding Examples
Source: https://github.com/omilli/hellajs-docs/blob/master/public/llms.txt
Provides comprehensive examples of advanced reactive bindings in HellaJS JSX, demonstrating simple bindings, conditional rendering, derived values, complex expressions, array operations, and template literals within a component structure.
```jsx
const App = () => {
const count = signal(0);
const user = signal({ name: 'John', role: 'admin' });
const todos = signal([]);
return (
{/* Template literals */}
{`${user().name} - Todo App (${todos().length})`}
);
};
```
--------------------------------
### Parameter Inheritance Example
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/learn/concepts/routing.mdx
Illustrates how child routes automatically inherit parameters from their parent routes, simplifying data access in nested components.
```typescript
router({
routes: {
'/users/:userId': {
children: {
'/profile': (params, query) => {
// params = { userId: '123' }
// Child inherits parent parameters automatically
return showUserProfile(params.userId);
}
}
}
}
});
```
--------------------------------
### Create and Refetch Todo List with Resource
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/learn/concepts/resources.mdx
Illustrates creating a resource for a todo list using an async function. It shows how to manually trigger the initial fetch, add new todos, and refetch the list after a mutation. The resource handles loading and error states for the todo data.
```javascript
import { resource, forEach } from 'hellajs';
const TodoApp = () => {
const todos = resource(() =>
fetch('/api/todos').then(r => r.json())
);
// Manually trigger the initial fetch
todos.request();
const addTodo = async (text) => {
await fetch('/api/todos', {
method: 'POST',
body: JSON.stringify({ text }),
headers: { 'Content-Type': 'application/json' }
});
todos.request(); // Refetch after mutation
};
return (
{todos.loading() &&
Loading todos...
}
{todos.error() &&
Error loading todos
}
{todos.data() && (
{forEach(todos.data, todo => (
{todo.text}
))}
)}
);
};
```
--------------------------------
### Event Handling Example
Source: https://github.com/omilli/hellajs-docs/blob/master/src/pages/reference/dom/mount.mdx
Shows standard event handling in HellaJS using `on` prefixed props, such as `onClick`, for attaching event listeners to elements.
```jsx
const App = () => (
);
```
--------------------------------
### Advanced Store Patterns: Persistence
Source: https://github.com/omilli/hellajs-docs/blob/master/public/llms.txt
Shows how to create a persistent store using @hellajs/store by integrating with `localStorage`. It includes logic for loading initial data from storage and automatically saving changes using an `effect`.
```javascript
// Store with persistence
const createPersistedStore = (key, initialData) => {
// Load from localStorage
const saved = localStorage.getItem(key);
const data = saved ? JSON.parse(saved) : initialData;
const storeInstance = store(data);
// Auto-save to localStorage
effect(() => {
localStorage.setItem(key, JSON.stringify(storeInstance.computed()));
});
return storeInstance;
};
const persistedSettings = createPersistedStore('app-settings', {
theme: 'light',
language: 'en',
notifications: true
});
```