### Full SSR + Hydration Example with State Source: https://ilha.build/llms-full.txt A comprehensive example showing island definition with state management, SSR rendering with snapshot, and client-side hydration. ```typescript // server.ts import ilha, { html } from "ilha"; import { mount } from "ilha"; const Counter = ilha .state("count", 0) .on("button@click", ({ state }) => state.count(state.count() + 1)) .render( ({ state }) => html`

Count: ${state.count()}

`, ); // Server — render with snapshot const body = await Counter.hydratable( { count: 10 }, { name: "Counter", snapshot: true, skipOnMount: true }, ); // Client — hydrate in place mount({ Counter }); ``` -------------------------------- ### File-System Routing Setup Source: https://ilha.build/llms-full.txt Configuration for enabling file-system routing with Vite. ```APIDOC ## File-System Routing `@ilha/router` ships a Vite plugin that scans `src/pages/`, resolves layout and error boundary chains, and generates a ready-to-use router with zero manual route registration. ### Setup ```ts // vite.config.ts import { defineConfig } from "vite"; import { pages } from "@ilha/router/vite"; export default defineConfig({ plugins: [pages()], }); ``` Add `.ilha/` to `.gitignore`. ``` -------------------------------- ### Ilha Store Installation Source: https://ilha.build/llms-full.txt Install the @ilha/store package using your preferred package manager. ```APIDOC ## Install ``` -------------------------------- ### Install Ilha using Package Manager Source: https://ilha.build/llms-full.txt Install the Ilha framework using your preferred package manager. This command is typically run in your project's terminal. ```bash npm install ilha ``` -------------------------------- ### Full Pokemon Picker Component Example Source: https://ilha.build/llms-full.txt This example demonstrates a complete Ilha.js component that fetches and displays Pokemon data. It utilizes `.input()` for initial configuration, `.state()` for managing component data, `.onMount()` for initial data fetching, and `.effect()` for handling side effects like API requests with cancellation. ```javascript import dedent from "dedent"; import { Sandbox } from "$src/sandbox"; export const script = dedent` import "./styles.css"; import ilha, { html, mount, type } from "ilha"; const PokemonPicker = ilha .input<{ defaultPokemon: string }>() .state('pokemon', ({ defaultPokemon }) => defaultPokemon) .state('pokemonList', []) .state('pokemonData', null) .onMount(({ state }) => { const fetchList = async () => { const req = await fetch('https://pokeapi.co/api/v2/pokemon'); const list = await req.json(); state.pokemonList(list.results); }; fetchList(); }) .effect(({ state }) => { const controller = new AbortController(); const fetchPokemon = async () => { const pokemon = state.pokemon(); try { const req = await fetch( `https://pokeapi.co/api/v2/pokemon/${pokemon}`, { signal: controller.signal } ); const data = await req.json(); // Only update if this request wasn't aborted (still the latest) if (!controller.signal.aborted) { state.pokemonData(data); } } catch (err) { // Ignore abort errors if (err.name !== 'AbortError') throw err; } }; fetchPokemon(); return () => controller.abort(); }) .bind('#pokemon', 'pokemon') .render(({ state }) => { const currentPokemon = state.pokemon(); const options = state.pokemonList().map( ({ name }) => html` ` ); const card = state.pokemonData() ? html`

${state.pokemonData().name}

` : html`

Loading...

` return html` ${card} `; }); const Pokedex = ilha.render(() => html` ${PokemonPicker({ defaultPokemon: "charizard" })} `); mount({ Pokedex }); `; export const template = `
`; ``` -------------------------------- ### Example Usage - createForm Source: https://ilha.build/llms-full.txt An example demonstrating how to use the createForm function with Zod schema validation. ```APIDOC ## Example ```ts import { z } from "zod"; import { createForm, issuesToErrors } from "@ilha/form"; const form = createForm({ el: document.querySelector("form")!, schema: z.object({ email: z.string().email("Invalid email"), name: z.string().min(1, "Name is required"), }), onSubmit(values) { console.log(values.email); }, onError(issues) { console.log(issuesToErrors(issues)); }, validateOn: "input", }); const unmount = form.mount(); ``` ``` -------------------------------- ### One-time Setup with `.onMount()` Source: https://ilha.build/llms-full.txt Register a function with `.onMount()` to execute once after the island is mounted. This is ideal for initializing third-party libraries or performing DOM manipulations that only need to happen initially. ```typescript import ilha from "ilha"; const Island = ilha .onMount(({ host }) => { console.log("mounted", host); }) .render(() => `
hello
`); ``` -------------------------------- ### Vite Plugin Setup for File-System Routing Source: https://ilha.build/llms-full.txt Configure the Vite build process to use the `@ilha/router/vite` plugin for automatic route generation based on the file system. ```typescript // vite.config.ts import { defineConfig } from "vite"; import { pages } from "@ilha/router/vite"; export default defineConfig({ plugins: [pages()], }); ``` -------------------------------- ### Full SSR + Hydration Example Source: https://ilha.build/guide/island/hydratable A comprehensive example showing a stateful island component rendered with SSR and configured for client-side hydration. Note the use of `snapshot: true` for server-side state capture and `skipOnMount: true`. ```typescript // server.ts import ilha, { html } from "ilha"; import { mount } from "ilha"; const Counter = ilha .state("count", 0) .on("button@click", ({ state }) => state.count(state.count() + 1)) .render( ({ state }) => html`

Count: ${state.count()}

`, ); // Server — render with snapshot const body = await Counter.hydratable( { count: 10 }, { name: "Counter", snapshot: true, skipOnMount: true }, ); // Client — hydrate in place mount({ Counter }); ``` -------------------------------- ### Create Basic Ilha Store Source: https://ilha.build/llms-full.txt Initializes a simple global store with a count state. Demonstrates setting and getting the state. ```typescript import { createStore } from "@ilha/store"; const store = createStore({ count: 0 }); store.setState({ count: 1 }); store.getState(); // → { count: 1 } ``` -------------------------------- ### Create Ilha Store with State and Actions Source: https://ilha.build/llms-full.txt Illustrates creating a store with both initial state and a set of actions. The actions creator receives set, get, and getInitialState functions. ```typescript // State + actions const store = createStore({ count: 0 }, (set, get, getInitialState) => ({ increment() { set({ count: get().count + 1 }); }, reset() { set(getInitialState()); }, })); ``` -------------------------------- ### Server-side Rendering with Ilha Router Source: https://ilha.build/llms-full.txt Implement server-side rendering by using the router to render the HTML for a given request URL. This example shows a basic SSR setup without hydration. ```typescript import { router } from "@ilha/router"; import { homePage, aboutPage, notFound } from "./pages"; const html = router() .route("/", homePage) .route("/about", aboutPage) .route("/**", notFound) .render(request.url); return new Response(`${html}`, { headers: { "content-type": "text/html" }, }); ``` -------------------------------- ### Selector Syntax Examples Source: https://ilha.build/guide/island/on Demonstrates various ways to specify CSS selectors and event names for attaching listeners. Omit the selector to target the island host. ```typescript .on("@click", handler) // host click .on("button@click", handler) // any `, ); ``` -------------------------------- ### Ilha Store Get Initial State Source: https://ilha.build/llms-full.txt Fetches the initial state of the store as it was at creation time. This state is frozen and unaffected by subsequent updates, making it useful for reset operations. ```typescript store.getInitialState(); // → { count: 0 } ``` -------------------------------- ### Counter Component with Bind and Effect Source: https://ilha.build/llms-full.txt Example of a Counter component using Ilha's state, derived, on, bind, effect, and render methods. The effect resets the count to 0 if it exceeds 3. ```typescript import dedent from "dedent"; import { Sandbox } from "$src/sandbox"; export const script = dedent` import "./styles.css"; import ilha, { html, mount } from "ilha"; const Counter = ilha .state("count", 0) .derived("doubled", ({ state }) => state.count() * 2) .on("[data-action=increase]@click", ({ state }) => { state.count(state.count() + 1) }) .bind("#count", 'count') .effect(({ state }) => { if (state.count() > 3) { state.count(0); } }) .render( ({ state, derived }) => html`

Count: ${state.count()}

Doubled: ${derived.doubled.value}

` ); mount({ Counter }); `; export const template = `
`; ``` -------------------------------- ### createStore - State Only Source: https://ilha.build/llms-full.txt Creates a store with initial state. No actions are defined. ```APIDOC ## `createStore(initialState)` ### Description Creates a store with initial state. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **initialState** (object) - Required - The initial state for the store. ### Request Example ```ts import { createStore } from "@ilha/store"; const store = createStore({ count: 0, name: "Ada" }); ``` ### Response #### Success Response (200) - **store** (object) - The created store instance with `getState`, `setState`, `subscribe`, and `bind` methods. #### Response Example ```ts // store object with methods ``` ``` -------------------------------- ### createStore - State and Actions Source: https://ilha.build/llms-full.txt Creates a store with initial state and encapsulated actions for state mutations. ```APIDOC ## `createStore(initialState, actions?)` ### Description Creates a store. Optionally accepts an actions creator for encapsulating mutations. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **initialState** (object) - Required - The initial state for the store. - **actions** (function) - Optional - An actions creator function. ### Actions Creator Arguments The actions creator receives: | Argument | Description | | ------------------- | ----------------------------------------------------------------- | | `set(patch | fn)` | Merge a partial patch or apply an updater function | | `get()` | Read the current live state, including other actions | | `getInitialState()` | Read the frozen initial state snapshot as it was at creation time | ### Request Example ```ts import { createStore } from "@ilha/store"; const store = createStore({ count: 0 }, (set, get, getInitialState) => ({ increment() { set({ count: get().count + 1 }); }, reset() { set(getInitialState()); }, })); ``` ### Response #### Success Response (200) - **store** (object) - The created store instance with `getState`, `setState`, `subscribe`, and `bind` methods, including the defined actions. #### Response Example ```ts // store object with state and actions store.getState().increment(); ``` ``` -------------------------------- ### Ilha Store Get State Source: https://ilha.build/llms-full.txt Retrieves the current snapshot of the store's state. Returns a stable reference if the state has not changed. ```typescript store.getState(); // → { count: 5, increment: [Function], reset: [Function] } ``` -------------------------------- ### Initialize third-party libraries with .onMount() Source: https://ilha.build/guide/island/onmount Use .onMount() to hand off a DOM element to a third-party library that manages its own rendering, passing necessary input props. ```typescript declare global { interface Window { MapLibrary: any; } } // ---cut--- import ilha from "ilha"; const Map = ilha .input<{ lat: number; lng: number }>() .onMount(({ host, input }) => { // [!code highlight:4] const map = new window.MapLibrary(host, { center: [input.lat, input.lng], zoom: 12, }); return () => map.destroy(); }) .render(() => `
`); ``` -------------------------------- ### Initializing Third-Party Libraries with `.onMount()` Source: https://ilha.build/llms-full.txt Integrate external libraries within `.onMount()` by passing the island's host element and input props. Ensure to return a cleanup function to destroy the library instance on unmount. ```typescript declare global { interface Window { MapLibrary: any; } } // ---cut--- import ilha from "ilha"; const Map = ilha .input<{ lat: number; lng: number }>() .onMount(({ host, input }) => { const map = new window.MapLibrary(host, { center: [input.lat, input.lng], zoom: 12, }); return () => map.destroy(); }) .render(() => `
`); ``` -------------------------------- ### Mounting and Rendering Source: https://ilha.build/llms-full.txt Methods for mounting the router in the browser and rendering HTML on the server. ```APIDOC ## .mount(target, options?) ### Description Mounts the router into a DOM element or CSS selector. Sets up `popstate` listening and intercepts internal `` clicks automatically. Returns an `unmount` function. ### Method `mount` ### Endpoint N/A (Browser API) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Options - **hydrate** (boolean) - Optional - `false` - Preserve SSR DOM, don't wipe on first mount. - **registry** (Record) - Optional - Island registry for interactive hydration on navigation. ### Request Example ```javascript router.mount('#app', { hydrate: true, registry: islandRegistry }); ``` ### Response - **unmount** (function) - A function to unmount the router. ## .render(url) ### Description Returns a synchronous HTML string for the matched route. Renders `
` when no route matches. ### Method `render` ### Endpoint N/A (Server API) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **url** (string | URL) - The URL to render. ### Request Example ```javascript const html = router.render('/about'); ``` ### Response - **string** - HTML string for the matched route. ``` ```APIDOC ## .renderHydratable(url, registry, options?, request?) ### Description Async variant of `.render()` that outputs HTML with `data-ilha` hydration markers and serialized loader data. Use this in your SSR handler for the full hydration pipeline. ### Method `renderHydratable` ### Endpoint N/A (Server API) ### Parameters - **url** (string | URL) - The URL to render. - **registry** (Record) - The island registry. - **options** (object) - Optional - Rendering options. - **request** (Request) - Optional - The incoming request object. ### Request Example ```javascript const html = await router.renderHydratable('/profile', registry); ``` ### Response - **string** - HTML string with hydration markers. ## .renderResponse(url, registry, options?, request?) ### Description Structured-envelope variant of `.renderHydratable()` that returns a discriminated union instead of a raw string, letting your server emit proper HTTP status codes. ### Method `renderResponse` ### Endpoint N/A (Server API) ### Parameters - **url** (string | URL) - The URL to render. - **registry** (Record) - The island registry. - **options** (object) - Optional - Rendering options. - **request** (Request) - Optional - The incoming request object. ### Response - **object** - A discriminated union with `kind` property: `html`, `redirect`, or `error`. - `html`: `{ kind: "html", html: string, status?: number }` - `redirect`: `{ kind: "redirect", to: string, status: number }` - `error`: `{ kind: "error", status: number, message: string, html: string }` ### Response Example ```javascript const res = await router.renderResponse('/protected', registry); if (res.kind === 'redirect') { return Response.redirect(res.to, res.status); } if (res.kind === 'error') { return new Response(res.html, { status: res.status }); } return new Response(res.html, { headers: { 'content-type': 'text/html' } }); ``` ``` -------------------------------- ### Share State Between Islands with Context Source: https://ilha.build/guide/helpers/context Any island calling `context()` with the same key gets the same signal. Updates to the signal in one island automatically re-render other islands reading it. ```typescript import ilha, { html, context } from "ilha"; const cartCount = context("cart.count", 0); const CartButton = ilha .on("button@click", () => cartCount(cartCount() + 1)) // [!code highlight] .render(() => html` `); const CartBadge = ilha // [!code highlight] .render(() => html`${cartCount()}`); ``` -------------------------------- ### Basic Island Transition with Enter and Leave Animations Source: https://ilha.build/llms-full.txt Implement enter and leave animation callbacks for an island. The `enter` callback runs on mount, and the `leave` callback runs on unmount, awaiting the animation before teardown. ```typescript import ilha from "ilha"; const Island = ilha .transition({ enter: async (host) => { await host.animate( [ { opacity: 0, }, { opacity: 1 }, ], { duration: 300, fill: "forwards", }, ).finished; }, leave: async (host) => { await host.animate( [ { opacity: 1, }, { opacity: 0 }, ], { duration: 300, fill: "forwards", }, ).finished; }, }) .render(() => `
content
`); ``` -------------------------------- ### Accessing Route State with useRoute() Source: https://ilha.build/llms-full.txt Use `useRoute()` within Ilha components to get reactive accessors for the current route's path, parameters, search, and hash. ```typescript import ilha from "ilha"; import { useRoute } from "@ilha/router"; const MyPage = ilha.render(() => { const { path, params, search, hash } = useRoute(); return `

User: ${params().id}

`; }); ``` -------------------------------- ### Handler Context Example Source: https://ilha.build/guide/island/on Illustrates accessing the event target and value within an input event handler. The handler receives a context object including state, event, and target. ```typescript import ilha from "ilha"; const Island = ilha .state("value", "") .on("input@input", ({ state, event }) => { state.value((event.target as HTMLInputElement).value); }) .render(({ state }) => ``); ``` -------------------------------- ### Directory Structure and Mapping Source: https://ilha.build/llms-full.txt Explains the file-system routing conventions and how filenames map to URL patterns. ```APIDOC ### Directory Structure ``` src/pages/ +layout.ts ← root layout (wraps all pages) +error.ts ← root error boundary index.ts → / about.ts → /about (auth)/ ← route group — invisible in the URL +layout.ts ← layout scoped to (auth) pages only sign-in.ts → /sign-in sign-up.ts → /sign-up user/ +layout.ts ← nested layout (wraps user/* only) +error.ts ← nested error boundary [id].ts → /user/:id [id]/ settings.ts → /user/:id/settings [...slug].ts → /**:slug ``` ### Filename → Pattern Mapping | File | Pattern | | ------------------- | ----------- | | `index.ts` | `/` | | `about.ts` | `/about` | | `[id].ts` | `/:id` | | `user/[id].ts` | `/user/:id` | | `[...slug].ts` | `/**:slug` | | `(auth)/sign-in.ts` | `/sign-in` | ### Route Groups Folders wrapped in parentheses — `(name)` — organise files without contributing a URL segment. Use them for shared layouts, co-located pages, or logical grouping with no effect on the URL. ### Layouts A `+layout.ts` wraps every page in its directory and all subdirectories. Layouts compose inside-out — nearest layout is innermost. ```ts twoslash // src/pages/+layout.ts import { defineLayout } from "@ilha/router"; import ilha, { html } from "ilha"; export default defineLayout((children) => ilha.render( () => html`
${children}
`, ), ); ``` ``` -------------------------------- ### Ilha Island with Store Subscription Source: https://ilha.build/llms-full.txt Demonstrates the standard pattern of subscribing to a store slice within an Ilha island's `.effect()` and driving a local signal from it. The `.effect()` cleanup return ensures proper cleanup on unmount. ```typescript import { createStore } from "@ilha/store"; import ilha, { html } from "ilha"; export const cartStore = createStore({ items: [] as string[] }, (set, get) => ({ add(item: string) { set({ items: [...get().items, item] }); }, remove(item: string) { set({ items: get().items.filter((i) => i !== item) }); }, })); export const CartIsland = ilha .state("items", cartStore.getState().items) .effect(({ state }) => { return cartStore.subscribe( (s) => s.items, (items) => state.items(items) ); }) .render( ({ state }) => html` `, ); ``` -------------------------------- ### store.getInitialState() Source: https://ilha.build/llms-full.txt Retrieves the frozen initial state of the store as it was at creation time. ```APIDOC ## `store.getInitialState()` ### Description Returns the frozen initial state as it was at construction time. Not affected by subsequent `setState` calls. Useful for reset actions. ### Parameters None ### Request Example ```ts const initialState = store.getInitialState(); console.log(initialState.count); // e.g., 0 ``` ### Response #### Success Response (200) - **initialState** (object) - The frozen initial state of the store. #### Response Example ```ts { "count": 0, "name": "Ada" } ``` ``` -------------------------------- ### Scoped CSS Rule Example Source: https://ilha.build/guide/island/css Illustrates how Ilha wraps styles in a `@scope` rule. This rule constrains styles to the island host and excludes nested islands, using low specificity selectors. ```css @scope (:scope) to ([data-ilha]) { .title { font-weight: 700; } button { background: teal; color: white; } } ``` -------------------------------- ### Navigation Helpers Source: https://ilha.build/llms-full.txt Functions for programmatic navigation and prefetching. ```APIDOC ## `navigate(to, options?)` ### Description Programmatically navigate to a path. Updates the URL, history stack, and all reactive signals. Duplicate navigations are no-ops. ### Method `navigate` ### Parameters - **to** (string) - The path to navigate to. - **options** (object) - Optional - Navigation options. - **replace** (boolean) - If true, replaces the current history entry instead of pushing a new one. ### Request Example ```javascript import { navigate } from '@ilha/router'; navigate('/about'); navigate('/about', { replace: true }); // replaces instead of pushing ``` ## `prefetch(pathWithSearch)` ### Description Prefetches loader data for a path in the background. The result is cached and consumed on the next navigation, making the transition feel instant. ### Method `prefetch` ### Parameters - **pathWithSearch** (string) - The path to prefetch, including the search query. ### Request Example ```javascript prefetch('/user/42'); prefetch('/dashboard?tab=overview'); ``` ### Note `RouterLink` calls this automatically on `mouseenter` for links with the `data-prefetch` attribute. ``` -------------------------------- ### Variable: context() Source: https://ilha.build/llms-full.txt Creates a context signal with a given key and initial value. ```APIDOC ## Variable: context() ### Type Parameters - **T**: The type of the value stored in the context signal. ### Parameters - **key** (string) - The unique key for the context. - **initial** (T) - The initial value for the context signal. ### Returns `ContextSignal` - A signal accessor for the context value. ``` -------------------------------- ### Client-side Hydration with Ilha Router Source: https://ilha.build/llms-full.txt The .hydrate() method is the recommended client entry point for mounting the router and enabling hydration. It can optionally take root element and target selector options. ```typescript pageRouter.hydrate(registry); ``` ```typescript pageRouter.hydrate(registry, { root: document.getElementById("root"), target: "#app", }); ``` -------------------------------- ### Accessing the raw string value Source: https://ilha.build/guide/helpers/html The `html`` template returns a `RawHtml` object. Access its `.value` property to get the plain string representation, though ilha typically unwraps this automatically at render boundaries. ```typescript import { html } from "ilha"; const result = html`

hello

`; result.value; // → "

hello

" ``` -------------------------------- ### Schema-based Input Declaration with Zod Source: https://ilha.build/guide/island/input Use `.input(schema)` with a validator like Zod to get TypeScript inference, runtime validation, coercion, and default values. This is recommended for islands needing robust data handling. ```typescript import ilha from "ilha"; import { z } from "zod"; const Greeting = ilha .input(z.object({ name: z.string().default("World") })) // [!code highlight] .render(({ input }) => `

Hello, ${input.name}!

`); Greeting.toString({ name: "ilha" }); // →

Hello, ilha!

Greeting.toString(); // →

Hello, World!

``` -------------------------------- ### Create and Mount Ilha Form Source: https://ilha.build/llms-full.txt Demonstrates creating a form instance with Zod schema validation, defining submit and error handlers, and mounting the form to a DOM element. The form validates on input. ```typescript import { z } from "zod"; import { createForm, issuesToErrors } from "@ilha/form"; const form = createForm({ el: document.querySelector("form")!, schema: z.object({ email: z.string().email("Invalid email"), name: z.string().min(1, "Name is required"), }), onSubmit(values) { console.log(values.email); }, onError(issues) { console.log(issuesToErrors(issues)); }, validateOn: "input", }); const unmount = form.mount(); ``` -------------------------------- ### Effect with cleanup function Source: https://ilha.build/llms-full.txt Implement cleanup logic in an effect by returning a function. This function runs before the effect re-runs or when the island unmounts, preventing issues like stale timers or subscriptions. This example uses setInterval and clearInterval. ```typescript import ilha from "ilha"; const Island = ilha .state("delay", 1000) .effect(({ state }) => { const id = setInterval(() => { console.log("tick"); }, state.delay()); return () => clearInterval(id); // [!code highlight] }) .render(({ state }) => `

Interval: ${state.delay()}ms

`); ``` -------------------------------- ### MountOptions Interface Source: https://ilha.build/llms-full.txt Options for mounting an island component. ```APIDOC ## Interface: MountOptions Options for mounting an island. ### Properties - `lazy?` (boolean): Optional. If true, the island will be mounted lazily. - `root?` (Element): Optional. The root element for intersection observer when lazy mounting. ``` -------------------------------- ### Declare Asynchronous Derived Values in Ilha Source: https://ilha.build/llms-full.txt Use `.derived()` to declare computed values that depend on state or input. This example shows an async derived value fetching user data, with checks for loading and error states. ```typescript import ilha, { html } from "ilha"; const UserCard = ilha .state("userId", 1) // [!code highlight:4] .derived("user", async ({ state, signal }) => { const res = await fetch(`/api/users/${state.userId()}`, { signal }); return res.json(); }) .render(({ derived }) => { if (derived.user.loading) return `

Loading…

`; if (derived.user.error) return `

Error: ${derived.user.error.message}

`; return `

${derived.user.value.name}

`; }); ``` -------------------------------- ### Form Options Source: https://ilha.build/llms-full.txt Configuration options for creating and managing a form instance. ```APIDOC ## Form Options ### Parameters #### `el` (HTMLFormElement) - Required The form element to bind. #### `schema` (StandardSchemaV1) - Required Any Standard Schema compatible validator such as Zod, Valibot, or ArkType. #### `onSubmit` ((values, event) => void) - Required Called with typed schema output after a valid submit. #### `onError` ((issues, event) => void) - Optional Called when submit validation fails. #### `validateOn` ("submit" | "change" | "input") - Optional Controls automatic validation; defaults to "submit". #### `defaultValues` (Record) - Optional Initial DOM values applied on `mount()` and tracked across re-renders. ``` -------------------------------- ### Get Form Values and Validate Source: https://ilha.build/llms-full.txt Use form.values() to synchronously read current form values with FormData, validate them, and return a discriminated union. This method never throws validation failures and works even before mounting the form. ```typescript const result = form.values(); if (result.ok) { console.log(result.data); } else { console.log(result.issues); } ``` -------------------------------- ### Mount Islands with Basic Registry Source: https://ilha.build/llms-full.txt Use the `mount` function to activate islands by providing a registry mapping island names to their constructors. This is the recommended approach for SSR and hydration. ```ts import { mount } from "ilha"; import { Counter, Card } from "./islands"; mount({ Counter, Card }); ``` -------------------------------- ### Multiple independent effects Source: https://ilha.build/llms-full.txt Chain multiple .effect() calls to register several independent reactive side effects. Each effect tracks its own dependencies and runs separately, allowing for distinct reactive behaviors. This example updates the document title and body background color. ```typescript import ilha from "ilha"; const Island = ilha .state("title", "Hello") .state("color", "teal") .effect(({ state }) => { document.title = state.title(); }) .effect(({ state }) => { document.body.style.backgroundColor = state.color(); }) .render(({ state }) => `

${state.title()}

`); ``` -------------------------------- ### mount() Function Source: https://ilha.build/api/variables/mount This snippet details the mount() function, its parameters, and return type. ```APIDOC ## mount() ### Description Registers and mounts islands using the provided registry and options. ### Method `const mount: (registry, options) => MountResult = mountAll` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### registry - **registry** (IslandRegistry) - The registry containing islands to mount. #### options - **options** (MountOptions) - Optional configuration for mounting islands. Defaults to `{}`. ### Returns - **MountResult** - An object containing information about the mounted islands. ``` -------------------------------- ### Ilha.js Counter Component with Two-Way Binding Source: https://ilha.build/tutorial/counter/bind This example demonstrates a counter component using Ilha.js. It utilizes .bind() for two-way synchronization between the 'count' state and an input field, while also updating the 'doubled' derived state and handling an increase action via a button click. ```javascript import dedent from "dedent"; import { Sandbox } from "$src/sandbox"; export const script = dedent` import "./styles.css"; import ilha, { html, mount } from "ilha"; const Counter = ilha .state("count", 0) .derived("doubled", ({ state }) => state.count() * 2) .on("[data-action=increase]@click", ({ state }) => { state.count(state.count() + 1) }) .bind("#count", 'count') .render( ({ state, derived }) => html`

Count: ${state.count()}

Doubled: ${derived.doubled.value}

` ); mount({ Counter }); `; export const template = `
`; ``` -------------------------------- ### Utility Variables Source: https://ilha.build/llms-full.txt Provides access to core Ilha utilities like context, CSS, HTML, and mounting functions. ```APIDOC ## Utility Variables Ilha provides several top-level utility variables for common tasks: * **`context`**: Function to create and manage reactive context. * **`css`**: Utility for CSS-related operations. * **`default`**: Default export or configuration. * **`from`**: Function for data transformation or sourcing. * **`html`**: Utility for generating or manipulating HTML. * **`mount`**: Function to mount island components. * **`raw`**: Utility for handling raw data or content. ``` -------------------------------- ### Ilha.js Counter Component with Effect Source: https://ilha.build/tutorial/counter/effect This example demonstrates a counter component using Ilha.js. It includes state management, derived state, event handling, DOM binding, and an effect that resets the count if it exceeds 3. The effect runs automatically after each state update to enforce this constraint. ```javascript import dedent from "dedent"; import { Sandbox } from "$src/sandbox"; export const script = dedent` import "./styles.css"; import ilha, { html, mount } from "ilha"; const Counter = ilha .state("count", 0) .derived("doubled", ({ state }) => state.count() * 2) .on("[data-action=increase]@click", ({ state }) => { state.count(state.count() + 1) }) .bind("#count", 'count') .effect(({ state }) => { if (state.count() > 3) { state.count(0); } }) .render( ({ state, derived }) => html`

Count: ${state.count()}

Doubled: ${derived.doubled.value}

` ); mount({ Counter }); `; export const template = `
`; ``` -------------------------------- ### Import ilha Core and Helpers Source: https://ilha.build/llms-full.txt Import the default export for the builder chain and named exports for utility functions like html, raw, css, mount, from, and context. ```typescript import ilha, { html, raw, css, mount, from, context } from "ilha"; ``` -------------------------------- ### Combining Enter and Leave Transitions for a Drawer Source: https://ilha.build/llms-full.txt Define both `enter` and `leave` transitions for an island, such as a drawer. Callbacks are optional; only one needs to be defined if the other is not required. ```typescript import ilha from "ilha"; const Drawer = ilha .transition({ enter: async (host) => { await host.animate([{ transform: "translateX(-100%)" }, { transform: "translateX(0)" }], { duration: 250, easing: "ease-out", }).finished; }, leave: async (host) => { await host.animate([{ transform: "translateX(0)" }, { transform: "translateX(-100%)" }], { duration: 250, easing: "ease-in", }).finished; }, }) .render(() => `
content
`); ``` -------------------------------- ### Create and Use a Global Context Signal Source: https://ilha.build/guide/helpers/context Import `context` from 'ilha' to create a named signal. The second argument is the initial value. Read the value with `signal()` and write with `signal(newValue)`. ```typescript import { context } from "ilha"; const theme = context("app.theme", "light"); theme(); // → "light" (read) theme("dark"); // → sets to "dark" (write) ``` -------------------------------- ### Configure Ilha Router Pages Source: https://ilha.build/llms-full.txt Configure the Ilha router to generate routes from a specified directory. Uses default values if not provided. ```typescript import { pages } from "@ilha/router/vite"; // ---cut--- pages({ dir: "src/pages", // default generated: ".ilha/routes.ts", // default }); ``` -------------------------------- ### Island Rendering with Different Return Types Source: https://ilha.build/guide/island/render Demonstrates returning plain strings, `html`` tagged templates for safe interpolation, and `raw()` for trusted markup within `html``. ```typescript import ilha, { html, raw } from "ilha"; // Plain string — no escaping const A = ilha.render(() => `

hello

`); // html`` — safe interpolation with auto-escaping const B = ilha.render(({ state }) => html`

${state}

`); // raw() — trusted markup inside html`` const C = ilha.render(() => html`
${raw("trusted")}
`); ```