### Install Runed Kit Dependencies Source: https://github.com/svecosystem/runed/blob/main/packages/runed/src/lib/kit/README.md Command to install the required SvelteKit package dependency for the Runed kit utilities. ```bash npm install @sveltejs/kit ``` -------------------------------- ### Use Runed utilities in Svelte Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/getting-started.md Demonstrates how to import and utilize Runed utilities like activeElement within Svelte components and Svelte module files. These examples show integration with Svelte 5 runes such as $state and $effect. ```svelte {#if activeElement.current === inputElement} The input element is active! {/if} ``` ```typescript import { activeElement } from "runed"; function logActiveElement() { $effect(() => { console.log("Active element is ", activeElement.current); }); } logActiveElement(); ``` -------------------------------- ### Install Runed via npm Source: https://github.com/svecosystem/runed/blob/main/packages/runed/README.md This command installs the Runed package into your project using the npm package manager. It is the primary method for adding the library as a dependency. ```bash npm install runed ``` -------------------------------- ### Define reactive URL parameters with schema validation Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/use-search-params.md Demonstrates how to initialize URL parameters using different schema validation libraries. These examples show how to define default values and access reactive state. ```TypeScript (Zod) import { z } from "zod"; const productSearchSchema = z.object({ page: z.number().default(1), filter: z.string().default(""), sort: z.enum(["newest", "oldest", "price"]).default("newest") }); const params = useSearchParams(productSearchSchema); const page = $derived(params.page); const sort = $derived(params.sort); ``` ```TypeScript (Valibot) import * as v from "valibot"; const productSearchSchema = v.object({ page: v.optional(v.fallback(v.number(), 1), 1), filter: v.optional(v.fallback(v.string(), ""), ""), sort: v.optional(v.fallback(v.picklist(["newest", "oldest", "price"]), "newest"), "newest") }); const params = useSearchParams(productSearchSchema); ``` ```TypeScript (Arktype) import { type } from "arktype"; const productSearchSchema = type({ page: "number = 1", filter: 'string = ""', sort: '"newest" | "oldest" | "price" = "newest"' }); const params = useSearchParams(productSearchSchema); ``` -------------------------------- ### Context API Usage Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/context.md Demonstrates how to create, set, and get context values using the Runed Context API. ```APIDOC ## Context API Usage ### Description This section illustrates the typical workflow for using the Runed Context API to share data across your Svelte component tree. ### Creating a Context Define a context instance with a specific type and an identifier. ```ts import { Context } from "runed"; export const myTheme = new Context<"light" | "dark">("theme"); ``` ### Setting Context Values In a parent component, set the context value during initialization. ```svelte {@render children?.()} ``` **Note:** Context must be set during component initialization, not within event handlers or callbacks. ### Reading Context Values In child components, retrieve the context value using `get()` or `getOr()`. ```svelte ``` ### Type Definition ```ts class Context { /** * @param name The name of the context. Used for debugging and error messages. */ constructor(name: string) {} /** * The symbol key used internally for context retrieval. */ get key(): symbol; /** * Checks if the context has been set in a parent component. * Must be called during component initialization. */ exists(): boolean; /** * Retrieves the context value from the closest parent. * Throws an error if the context is not set. * Must be called during component initialization. */ get(): TContext; /** * Retrieves the context value or a fallback value if the context is not set. * Must be called during component initialization. */ getOr(fallback: TFallback): TContext | TFallback; /** * Sets the context value for the current component and returns it. * Must be called during component initialization. */ set(context: TContext): TContext; } ``` ``` -------------------------------- ### Implement TextareaAutosize in Svelte Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/textarea-autosize.md Shows how to initialize the TextareaAutosize utility by passing a getter for the textarea element and the reactive input value. This setup ensures the textarea automatically resizes as the user types. ```svelte ``` -------------------------------- ### Advanced Controlled onClickOutside Listener Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/on-click-outside.md Shows how to manually manage the listener state using the returned start and stop methods, useful for modal or dialog interactions. ```svelte
``` -------------------------------- ### Svelte Component Using `createSearchParamsSchema` for Dates Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/use-search-params.md A practical Svelte component example demonstrating the integration of createSearchParamsSchema for managing date parameters in URL. It includes input fields for 'eventDate' (formatted as YYYY-MM-DD) and 'createdAt' (formatted as ISO8601), updating the URL dynamically. ```svelte ``` -------------------------------- ### Stop Resize Observer with runed Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/use-resize-observer.md This example shows how to manually stop a resize observer instance created with the `useResizeObserver` utility from the 'runed' library. The `useResizeObserver` function returns an object containing a `stop` method, which, when called, disconnects the observer from its target element. ```typescript const { stop } = useResizeObserver(/* ... */); stop(); ``` -------------------------------- ### Managing Debounced State Updates Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/debounced.md This TypeScript example illustrates how to control the debounced state using methods like `cancel`, `setImmediately`, and `updateImmediately`. It shows how to prevent pending updates, force an immediate update, and wait for an update to complete. ```typescript let count = $state(0); const debounced = new Debounced(() => count, 500); count = 1; debounced.cancel(); // after a while... console.log(debounced.current); // Still 0! count = 2; console.log(debounced.current); // Still 0! debounced.setImmediately(count); console.log(debounced.current); // 2 count = 3; console.log(debounced.current); // 2 await debounced.updateImmediately(); console.log(debounced.current); // 3 ``` -------------------------------- ### Configure useInterval Options Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/use-interval.md Shows how to initialize useInterval with specific configuration options such as immediate execution, immediate callbacks, and custom tick logic. ```svelte ``` -------------------------------- ### Import Runed Kit and Core Utilities Source: https://github.com/svecosystem/runed/blob/main/packages/runed/src/lib/kit/README.md Demonstrates how to import SvelteKit-dependent utilities from the kit subpath while maintaining access to core Runed utilities. ```typescript // Import SvelteKit-dependent utilities from the kit subpath import { useSearchParams } from "runed/kit"; // Regular utilities are still available from the main export import { isMounted, useEventListener } from "runed"; ``` -------------------------------- ### Reactive Data Fetching with Runed Resource (Svelte) Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/resource.md Demonstrates how to use the 'resource' utility to fetch data reactively based on a changing ID. It includes handling loading and error states, and displaying fetched results. The 'resource' function takes a source (a reactive value or function) and an async fetcher function, with optional configuration like debouncing. ```svelte {#if searchResults.loading}
Loading...
{:else if searchResults.error}
Error: {searchResults.error.message}
{:else} {/if} ``` -------------------------------- ### Custom Serialization with Date Objects Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/persisted-state.md Provides an example of using custom serialization handlers with PersistedState to correctly persist and retrieve complex data types like Date objects. This example utilizes the 'superjson' library for serialization. Dependencies include 'runed' and 'superjson'. ```ts import superjson from "superjson"; // Example with Date objects const lastAccessed = new PersistedState("last-accessed", new Date(), { serializer: { serialize: superjson.stringify, deserialize: superjson.parse } }); ``` -------------------------------- ### Read Context Value in Child Component (Svelte) Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/context.md Illustrates how child components can read a context value using the `get()` or `getOr()` methods. `get()` throws an error if the context is not set, while `getOr()` provides a fallback value. Both methods must be called during component initialization. ```svelte ``` -------------------------------- ### Implement Reactive Interval with Controls Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/use-interval.md Demonstrates how to use the useInterval hook with a reactive delay, manual pause/resume controls, and a counter display. ```svelte

Counter: {interval.counter}

Interval delay: {delay}ms

Status: {interval.isActive ? "Running" : "Paused"}

``` -------------------------------- ### Resource with Multiple Dependencies (Svelte) Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/resource.md Illustrates how to use the 'resource' utility with multiple reactive dependencies. The fetcher function receives an array of the current values of these dependencies. This is useful for scenarios where data fetching depends on several reactive sources. ```svelte ``` -------------------------------- ### Pre-render Execution with Resource.pre (Svelte) Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/resource.md Demonstrates the use of `resource.pre()` for executing data fetching during the pre-rendering phase. This is beneficial for SSR (Server-Side Rendering) scenarios where initial data needs to be fetched before the client-side hydration. ```svelte ``` -------------------------------- ### Context Class Type Definition (TypeScript) Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/context.md Provides the TypeScript type definition for the `Context` class. It outlines the constructor and methods available for managing context, including `key`, `exists`, `get`, `getOr`, and `set`. ```typescript class Context { /** * @param name The name of the context. * This is used for generating the context key and error messages. */ constructor(name: string) {} /** * The key used to get and set the context. * * It is not recommended to use this value directly. * Instead, use the methods provided by this class. */ get key(): symbol; /** * Checks whether this has been set in the context of a parent component. * * Must be called during component initialization. */ exists(): boolean; /** * Retrieves the context that belongs to the closest parent component. * * Must be called during component initialization. * * @throws An error if the context does not exist. */ get(): TContext; /** * Retrieves the context that belongs to the closest parent component, * or the given fallback value if the context does not exist. * * Must be called during component initialization. */ getOr(fallback: TFallback): TContext | TFallback; /** * Associates the given value with the current component and returns it. * * Must be called during component initialization. */ set(context: TContext): TContext; } ``` -------------------------------- ### Custom Cleanup with Resource (Svelte) Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/resource.md Shows how to implement custom cleanup logic using the 'onCleanup' function provided within the 'resource' fetcher. This is crucial for managing resources like EventSource connections, ensuring they are properly closed when the source is invalidated or the component unmounts. ```svelte ``` -------------------------------- ### Debounce Event Scheduling in TypeScript Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/finite-state-machine.md Demonstrates how to use the `debounce` method to send an event after a delay. Re-invoking `debounce` with the same event cancels the previous timer and starts a new one. This functionality can be used in various parts of the state machine, including actions and lifecycle methods. ```typescript f.send("toggle"); // turn on immediately f.debounce(5000, "toggle"); // turn off in 5000 milliseconds ``` ```typescript // schedule a toggle in five seconds f.debounce(5000, "toggle"); // ... less than 5000ms elapses ... f.debounce(5000, "toggle"); // The second call cancels the original timer, and starts a new one ``` ```typescript const f = new FiniteStateMachine("off", { off: { toggle: () => { f.debounce(5000, "toggle"); return "on"; } }, on: { toggle: "off" } }); ``` ```typescript const f = new FiniteStateMachine("off", { off: { toggle: "on" }, on: { toggle: "off", _enter: () => { f.debounce(5000, "toggle"); } } }); ``` -------------------------------- ### Create a Simple Finite State Machine for a Toggle Switch Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/finite-state-machine.md Illustrates the basic usage of FiniteStateMachine to model a simple on/off toggle switch. It defines the states and the event that triggers the transition between them. ```typescript import { FiniteStateMachine } from "runed"; type MyStates = "on" | "off"; type MyEvents = "toggle"; const f = new FiniteStateMachine("off", { off: { toggle: "on" }, on: { toggle: "off" } }); ``` -------------------------------- ### Runed Reactivity: Limitations with Nested Mutations Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/use-search-params.md Highlights the limitations of `useSearchParams` reactivity in Svelte, specifically that nested property mutations within objects or arrays do not trigger URL updates. Examples include modifying nested object properties, using array methods like `push`, or updating array item properties directly. ```svelte ``` -------------------------------- ### Utilize Lifecycle Methods for State Entry and Exit in Finite State Machine Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/finite-state-machine.md Demonstrates the use of `_enter` and `_exit` lifecycle methods in FiniteStateMachine to execute code when a state is entered or exited. These methods receive a metadata object with transition details. ```typescript import { FiniteStateMachine } from "runed"; type MyStates = "on" | "off"; type MyEvents = "toggle"; const f = new FiniteStateMachine("off", { off: { toggle: "on", _enter: (meta) => { console.log("switch is off"); }, _exit: (meta) => { console.log("switch is no longer off"); } }, on: { toggle: "off", _enter: (meta) => { console.log("switch is on"); }, _exit: (meta) => { console.log("switch is no longer on"); } } }); ``` -------------------------------- ### Configure custom document scope for ActiveElement Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/active-element.md Shows how to instantiate the ActiveElement class to track focus within a specific shadow root or custom document. ```svelte ``` -------------------------------- ### Throttle function execution with useThrottle in Svelte Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/use-throttle.md Demonstrates how to use the useThrottle hook to manage state updates based on user input. It takes a callback function and a duration provider to control the frequency of the throttled action. ```svelte
search, (v) => { search = v; throttledUpdate(); } } />

You searched for: {throttledSearch}

``` -------------------------------- ### Initialize PersistedState in Svelte Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/persisted-state.md Demonstrates the basic initialization of PersistedState in a Svelte component. It shows how to create a reactive counter that is persisted and synchronized across tabs. Dependencies include the 'runed' library. ```svelte

Count: {count.current}

``` -------------------------------- ### Configure watch options Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/watch.md Shows how to pass an options object to the watch function, specifically using the lazy property to defer the initial execution until a change occurs. ```ts watch(sources, callback, { // First run will only happen after sources change when set to true. // By default, its false. lazy: true }); ``` -------------------------------- ### Initialize Resource Function Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/resource.md The resource function creates a reactive data source that automatically re-fetches when the source getter changes. It accepts a source getter, a fetcher function, and optional configuration. ```typescript function resource< Source, RefetchInfo = unknown, Fetcher extends ResourceFetcher< Source, Awaited>, RefetchInfo > = ResourceFetcher >( source: Getter, fetcher: Fetcher, options?: ResourceOptions>> ): ResourceReturn>, RefetchInfo>; ``` -------------------------------- ### Configure Grow-only Behavior Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/textarea-autosize.md Demonstrates how to configure the TextareaAutosize utility to use 'minHeight' mode, allowing the textarea to expand with content without shrinking below its initial size. ```typescript new TextareaAutosize({ element: () => el, input: () => value, styleProp: "minHeight" }); ``` -------------------------------- ### Create a Context Instance (TypeScript) Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/context.md Demonstrates how to create a new `Context` instance in TypeScript. The constructor takes a string name for debugging and error messages. The generic type parameter `` ensures type safety for the context value. ```typescript import { Context } from "runed"; export const myTheme = new Context<"light" | "dark">("theme"); ``` -------------------------------- ### Configuring PersistedState Options Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/persisted-state.md Shows how to configure PersistedState with various options, including storage type ('local' or 'session'), disabling cross-tab synchronization, controlling initial connection status, and providing custom serialization handlers. Dependencies include the 'runed' library. ```ts const state = new PersistedState("user-preferences", initialValue, { // Use sessionStorage instead of localStorage (default: 'local') storage: "session", // Disable cross-tab synchronization (default: true) syncTabs: false, // Start disconnected from storage (default: true) connected: false, // Custom serialization handlers serializer: { serialize: superjson.stringify, deserialize: superjson.parse } }); ``` -------------------------------- ### Check Key States with PressedKeys Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/pressed-keys.md Demonstrates how to instantiate PressedKeys and use the has method to check for individual or combined key presses within a Svelte derived state. ```typescript const keys = new PressedKeys(); const isArrowDownPressed = $derived(keys.has("ArrowDown")); const isCtrlAPressed = $derived(keys.has("Control", "a")); ``` -------------------------------- ### Implement Dynamic State Transitions with Actions in Finite State Machine Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/finite-state-machine.md Shows how to use action functions within a FiniteStateMachine to implement conditional or dynamic state transitions. Actions can return a state name or nothing to prevent a transition, and can accept parameters. ```typescript import { FiniteStateMachine } from "runed"; type MyStates = "on" | "off" | "cooldown"; type MyEvents = "toggle"; const f = new FiniteStateMachine("off", { off: { toggle: () => { if (isTuesday) { // Switch can only turn on during Tuesdays return "on"; } // All other days, nothing is returned and state is unchanged. } }, on: { toggle: (heldMillis: number) => { // You can also dynamically return the next state! // Only turn off if switch is depressed for 3 seconds if (heldMillis > 3000) { return "off"; } } } }); ``` -------------------------------- ### Configure URL parameter behavior Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/use-search-params.md Shows how to customize the behavior of URL updates, including debouncing, history management, and parameter compression for cleaner URLs. ```TypeScript const params = useSearchParams(schema, { showDefaults: true, debounce: 300, pushHistory: false, compress: true, compressedParamName: '_compressed' }); // Usage in component ``` -------------------------------- ### Track reactive state changes with Previous Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/previous.md Demonstrates how to initialize and use the Previous utility within a Svelte component to track the history of a reactive count variable. The utility exposes a current property that holds the value from the previous reactive cycle. ```svelte
Previous: {`${previous.current}`}
``` -------------------------------- ### Track element visibility with IsInViewport Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/is-in-viewport.md Demonstrates the basic implementation of IsInViewport to track if an element is visible. It requires a getter function returning the target element and provides a reactive 'current' boolean state. ```svelte

Target node

Target node in viewport: {inViewport.current}

``` -------------------------------- ### Perform one-time detection with IsInViewport Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/is-in-viewport.md Shows how to use the 'once' option to stop observing an element after it has been seen for the first time. This is useful for triggering one-time animations or lazy loading. ```svelte
I'll fade in once when first visible, then stop observing
``` -------------------------------- ### Watch reactive sources with runed Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/watch.md Demonstrates how to use the watch function to trigger a callback when specific reactive state changes. It supports single values, deep object snapshots, and multiple source arrays. ```ts import { watch } from "runed"; // Basic usage let count = $state(0); watch(() => count, () => { console.log(count); }); // Deep object watching let user = $state({ name: 'bob', age: 20 }); watch(() => $state.snapshot(user), () => { console.log(`${user.name} is ${user.age} years old`); }); // Watching specific deep value watch(() => user.age, () => { console.log(`User is now ${user.age} years old`); }); // Watching multiple sources let age = $state(20); let name = $state("bob"); watch([() => age, () => name], ([age, name], [prevAge, prevName]) => { // Callback logic }); // Accessing current and previous values watch(() => count, (curr, prev) => { console.log(`count is ${curr}, was ${prev}`); }); ``` -------------------------------- ### Define Resource Types and Fetcher Signature Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/resource.md Defines the core TypeScript interfaces for resource management, including state tracking, fetcher parameters, and return types. These types support lazy loading, debouncing, throttling, and manual mutation of resource data. ```typescript type ResourceOptions = { /** Skip initial fetch when true */ lazy?: boolean; /** Only fetch once when true */ once?: boolean; /** Initial value for the resource */ initialValue?: Data; /** Debounce time in milliseconds */ debounce?: number; /** Throttle time in milliseconds */ throttle?: number; }; type ResourceState = { /** Current value of the resource */ current: Data | undefined; /** Whether the resource is currently loading */ loading: boolean; /** Error if the fetch failed */ error: Error | undefined; }; type ResourceReturn = ResourceState & { /** Update the resource value directly */ mutate: (value: Data) => void; /** Re-run the fetcher with current values */ refetch: (info?: RefetchInfo) => Promise; }; type ResourceFetcherRefetchInfo = { /** Previous data return from fetcher */ data: Data | undefined; /** Whether the fetcher is currently refetching or it can be the value you passed to refetch. */ refetching: RefetchInfo | boolean; /** A cleanup function that will be called when the source is invalidated and the fetcher is about to re-run */ onCleanup: (fn: () => void) => void; /** AbortSignal for cancelling fetch requests */ signal: AbortSignal; }; type ResourceFetcher = ( value: Source extends Array ? { [K in keyof Source]: Source[K] } : Source, previousValue: Source extends Array ? { [K in keyof Source]: Source[K] } : Source | undefined, info: ResourceFetcherRefetchInfo ) => Promise; ``` -------------------------------- ### Define Custom Zod Codecs for Serialization Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/use-search-params.md Shows how to create Zod codecs to handle custom bidirectional transformations between URL string representations and JavaScript types like Dates or base36 numbers. ```typescript import { z } from "zod"; const unixTimestampCodec = z.codec( z.coerce.number(), z.date(), { decode: (timestamp) => new Date(timestamp * 1000), encode: (date) => Math.floor(date.getTime() / 1000) } ); const dateOnlyCodec = z.codec( z.string(), z.date(), { decode: (str) => new Date(str + "T00:00:00.000Z"), encode: (date) => date.toISOString().split("T")[0] } ); const compactIdCodec = z.codec( z.string(), z.number(), { decode: (str) => parseInt(str, 36), encode: (num) => num.toString(36) } ); ``` -------------------------------- ### Track element dimensions reactively with ElementSize Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/element-size.md This snippet demonstrates how to use the ElementSize class to track the width and height of a textarea element. It requires an element reference provided via a getter function and exposes reactive width and height properties. ```svelte

Width: {size.width} Height: {size.height}

``` -------------------------------- ### Implement Finite State Machines Source: https://context7.com/svecosystem/runed/llms.txt FiniteStateMachine provides a strongly-typed way to manage application states, transitions, and side effects. It supports lifecycle hooks like _enter and _exit, as well as debounced events. ```typescript import { FiniteStateMachine } from "runed"; type States = "idle" | "loading" | "success" | "error"; type Events = "fetch" | "resolve" | "reject" | "reset"; const fsm = new FiniteStateMachine("idle", { idle: { fetch: "loading", _enter: () => console.log("Entered idle state") }, loading: { resolve: "success", reject: "error", _enter: () => { fsm.debounce(10000, "reject"); }, _exit: () => console.log("Left loading state") }, success: { reset: "idle", _enter: (meta) => console.log(`Success! From: ${meta.from}`) }, error: { reset: "idle", fetch: "loading" }, "*": { reset: "idle" } }); fsm.send("fetch"); console.log(fsm.current); fsm.debounce(5000, "reject"); ``` -------------------------------- ### Observe Element Resize with Svelte and runed Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/use-resize-observer.md This snippet demonstrates how to use the `useResizeObserver` hook from the 'runed' library within a Svelte component. It observes a textarea element and updates its content with the element's current width and height. The hook requires a callback returning the target element and a handler function to process resize events. ```svelte ``` -------------------------------- ### Initialize IsMounted in Svelte Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/is-mounted.md Demonstrates the basic usage of the IsMounted class from the Runed library within a Svelte component's script tag. This is the recommended and most concise way to initialize the mounted state tracker. ```svelte ``` -------------------------------- ### Initialize ScrollState in Svelte Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/scroll-state.md Demonstrates how to instantiate the ScrollState utility by binding a target element. The utility provides reactive access to scroll positions, directions, and edge arrival states. ```svelte
``` -------------------------------- ### Implement Wildcard Event Handling in Finite State Machine Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/finite-state-machine.md Explains how to use the wildcard state `*` in FiniteStateMachine to define a fallback handler for events that are not explicitly defined in the current state. This allows for global event handling. ```typescript import { FiniteStateMachine } from "runed"; type MyStates = "on" | "off"; type MyEvents = "toggle" | "emergency"; const f = new FiniteStateMachine("off", { off: { toggle: "on" }, on: { toggle: "off" }, "*": { emergency: "off" } }); // will always result in the switch turning off. f.send("emergency"); ``` -------------------------------- ### Watch Reactive Changes with Runed's watch and watchOnce Source: https://context7.com/svecosystem/runed/llms.txt The `watch` utility allows you to monitor specific reactive values and execute a callback when they change, unlike `$effect` which tracks dependencies automatically. `watchOnce` executes the callback only on the first change. Both support watching single or multiple values, deep watching objects, and lazy execution. ```ts import { watch, watchOnce } from "runed"; let count = $state(0); let name = $state("bob"); // Watch single value watch(() => count, (curr, prev) => { console.log(`count changed from ${prev} to ${curr}`); }); // Watch multiple values watch([() => count, () => name], ([count, name], [prevCount, prevName]) => { console.log(`Values: ${count}, ${name}`); }); // Deep watch an object let user = $state({ name: "bob", age: 20 }); watch(() => $state.snapshot(user), () => { console.log(`User changed: ${user.name}, ${user.age}`); }); // Lazy watch (skip first run) watch(() => count, () => console.log("Changed!"), { lazy: true }); // Watch once watchOnce(() => count, () => console.log("First change only")); // Pre-render variant watch.pre(() => count, () => console.log("Before DOM update")); ``` -------------------------------- ### Create Basic Search Params Schema with Defaults Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/use-search-params.md Defines a search parameters schema using createSearchParamsSchema, including basic types (number, string), arrays, and objects with default values. This demonstrates the fundamental usage for setting up URL parameter structures. ```typescript const productSearchSchema = createSearchParamsSchema({ // Basic types with defaults page: { type: "number", default: 1 }, filter: { type: "string", default: "" }, sort: { type: "string", default: "newest" }, // Array type with specific element type tags: { type: "array", default: ["new"], arrayType: "" // Specify string[] type }, // Object type with specific shape config: { type: "object", default: { theme: "light" }, objectType: { theme: "" } // Specify { theme: string } type } }); ``` -------------------------------- ### Track focused element with activeElement Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/active-element.md Demonstrates the basic usage of the reactive activeElement store to display the currently focused DOM element in a Svelte component. ```svelte

Currently active element: {activeElement.current?.localName ?? "No active element found"}

``` -------------------------------- ### Attach Event Listener with useEventListener Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/use-event-listener.md Demonstrates how to use the useEventListener hook to track document clicks within a class-based structure and a Svelte component. It ensures memory safety by automatically removing listeners upon component destruction. ```typescript import { useEventListener } from "runed"; export class ClickLogger { #clicks = $state(0); constructor() { useEventListener( () => document.body, "click", () => this.#clicks++ ); } get clicks() { return this.#clicks; } } ``` ```svelte

You've clicked the document {logger.clicks} {logger.clicks === 1 ? "time" : "times"}

``` -------------------------------- ### Implement AnimationFrames with FPS control in Svelte Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/animation-frames.md This snippet demonstrates how to initialize an AnimationFrames instance to track frame counts and delta time. It utilizes Svelte 5 runes to bind the animation state and FPS limits to UI components. ```svelte
{stats}

FPS limit: {fpsLimit}{fpsLimit === 0 ? " (not limited)" : ""}

(fpsLimit = value[0] ?? 0)} min={0} max={144} /> ``` -------------------------------- ### Control observer lifecycle Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/is-in-viewport.md Illustrates how to access the underlying observer instance from the IsInViewport class to manually pause, resume, or stop the observation process. ```svelte ``` -------------------------------- ### Track focus within a container using IsFocusWithin Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/is-focus-within.md This snippet demonstrates how to initialize the IsFocusWithin class by passing a getter function that returns the target container element. The 'current' property provides a reactive boolean value indicating if any descendant has focus. ```svelte

Focus within form: {focusWithinForm.current}

``` -------------------------------- ### Controlling PersistedState Connection Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/persisted-state.md Demonstrates manual control over the connection state of PersistedState using the `connected` option and `.connect()`/`.disconnect()` methods. This allows for managing when state is persisted to and read from storage. Dependencies include the 'runed' library. ```ts // Start disconnected from storage const state = new PersistedState("temp-data", initialValue, { connected: false }); // State changes are kept in memory only state.current = "new value"; // Connect to storage when ready state.connect(); // Now persists to storage // Check connection status console.log(state.connected); // true // Disconnect from storage state.disconnect(); // Removes from storage, keeps value in memory ``` -------------------------------- ### Define a Complex Finite State Machine with Actions and Lifecycle Methods Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/finite-state-machine.md Demonstrates the creation of a finite state machine with multiple states, events, conditional transitions using actions, and lifecycle methods for state entry and exit. It includes a debounce mechanism for event handling. ```typescript import { FiniteStateMachine } from "runed"; type MyStates = "disabled" | "idle" | "running"; type MyEvents = "toggleEnabled" | "start" | "stop"; const f = new FiniteStateMachine("disabled", { disabled: { toggleEnabled: "idle" }, idle: { toggleEnabled: "disabled", start: "running" }, running: { _enter: () => { f.debounce(2000, "stop"); }, stop: "idle", toggleEnabled: "disabled" } }); ``` -------------------------------- ### Track document visibility with IsDocumentVisible Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/is-document-visible.md This snippet demonstrates how to instantiate the IsDocumentVisible class to reactively track the visibility state of the document. It exposes a 'current' property that returns a boolean indicating if the document is visible. ```svelte

Document visible: {visible.current ? "Yes" : "No"}

``` -------------------------------- ### Apply Date Formats Using `dateFormats` Option Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/use-search-params.md Shows an alternative method for defining date formats using the `dateFormats` option, which can be used with various validation libraries including createSearchParamsSchema. This approach centralizes date format configuration. ```typescript // Works with Zod, Valibot, Arktype, or createSearchParamsSchema const params = useSearchParams(zodSchema, { dateFormats: { birthDate: "date", // YYYY-MM-DD createdAt: "datetime" // ISO8601 } }); ``` -------------------------------- ### Persisting Complex Objects with PersistedState Source: https://github.com/svecosystem/runed/blob/main/sites/docs/src/content/utilities/persisted-state.md Illustrates how PersistedState handles different types of data, including arrays, plain objects, and custom class instances. It highlights that only plain structures are deeply reactive for automatic persistence. Dependencies include the 'runed' library. ```ts const persistedArray = new PersistedState("foo", ["a", "b"]); persistedArray.current.push("c"); // This will persist the change const persistedObject = new PersistedState("bar", { name: "Bob" }); persistedObject.current.name = "JG"; // This will persist the change class Person { name: string; constructor(name: string) { this.name = name; } } const persistedComplexObject = new PersistedState("baz", new Person("Bob")); persistedComplexObject.current.name = "JG"; // This will NOT persist the change persistedComplexObject.current = new Person("JG"); // This will persist the change ```