### Install Runed with npm Source: https://runed.dev/docs/getting-started This command installs the Runed library using npm. Ensure you have Node.js and npm installed on your system. This is the first step before importing Runed utilities into your project. ```bash npm install runed ``` -------------------------------- ### Log Active Element in Svelte Module Source: https://runed.dev/docs/getting-started Example of using the 'activeElement' utility from Runed in a .svelte.ts file to log the currently active element to the console. It utilizes Svelte's $effect for reactive logging. Requires the 'runed' package. ```typescript import { activeElement } from "runed"; function logActiveElement() { $effect(() => { console.log("Active element is ", activeElement.current); }); } logActiveElement(); ``` -------------------------------- ### Use activeElement in Svelte Component Source: https://runed.dev/docs/getting-started Example of using the 'activeElement' utility from Runed within a Svelte component. It demonstrates how to bind an input element and conditionally render content based on whether the input is active. Requires the 'runed' package. ```svelte {#if activeElement.current === inputElement} The input element is active! {/if} ``` -------------------------------- ### Example: Using extract to get a reactive interval in Runed.js Source: https://runed.dev/docs/utilities/extract Demonstrates the practical usage of the `extract` utility from Runed.js within a function. It shows how `extract` simplifies getting a definite numeric interval from a potentially reactive or static input, with a default fallback. ```javascript import { extract } from "runed"; /** * Triggers confetti at a given interval. * @param intervalProp Time between confetti bursts, in ms. Defaults to 100. */ function throwConfetti(intervalProp?: MaybeGetter) { const interval = $derived(extract(intervalProp, 100)); // ... } ``` -------------------------------- ### Example: Initializing Debounced with reactive or static values Source: https://runed.dev/docs/utilities/extract Illustrates how to initialize the `Debounced` utility in Runed.js. It shows examples of providing reactive getters for both the value and the debounce time, as well as using static values for the debounce time. ```javascript let search = $state(""); let debounceTime = $state(500); // with a reactive value const d1 = new Debounced( () => search, () => debounceTime ); // with a static value const d2 = new Debounced(() => search, 500); // no defined value const d3 = new Debounced(() => search); ``` -------------------------------- ### Interval Options Configuration Source: https://runed.dev/docs/utilities/use-interval Shows how to configure useInterval with options including immediate start behavior and immediate callback execution. Options control when the interval starts and whether callbacks execute immediately upon resuming. ```typescript ``` -------------------------------- ### watchOnce for single execution Source: https://runed.dev/docs/utilities/watch This example demonstrates `watchOnce`, which is used to execute a callback function only a single time when the specified sources change. It functions identically to `watch` otherwise but does not accept any options object. ```javascript watchOnce(sources, callback); ``` -------------------------------- ### Watch with lazy execution option Source: https://runed.dev/docs/utilities/watch This example demonstrates using the `options` object with `watch` to enable lazy execution. When `lazy: true` is set, the callback will not run on the initial setup but will only execute after the watched sources have changed for the first time. ```javascript watch(sources, callback, { // First run will only happen after sources change when set to true. // By default, its false. lazy: true }); ``` -------------------------------- ### FiniteStateMachine: Simple Toggle Switch Example Source: https://runed.dev/docs/utilities/finite-state-machine Illustrates a simple FiniteStateMachine for a toggle switch with two states ('on', 'off') and a single 'toggle' event. This is a fundamental example of FSM usage. ```typescript import { FiniteStateMachine } from "runed"; type MyStates = "on" | "off"; type MyEvents = "toggle"; const f = new FiniteStateMachine("off", { off: { toggle: "on" }, on: { toggle: "off" } }); ``` -------------------------------- ### FiniteStateMachine: Basic Definition with TypeScript Types Source: https://runed.dev/docs/utilities/finite-state-machine Demonstrates the basic setup of a FiniteStateMachine with strongly-typed states and events using TypeScript. It includes initial state, event transitions, and a timed event (_enter with debounce). ```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" } }); ``` -------------------------------- ### Resource Data Fetching with Svelte Source: https://runed.dev/docs/utilities/resource Demonstrates how to use the `resource` utility to fetch data based on reactive state changes. It handles loading, error states, and provides options for debouncing. This example fetches post data based on an ID and displays the results. ```typescript import { resource } from "runed"; let id = $state(1); const searchResource = resource( () => id, async (id, prevId, { data, refetching, onCleanup, signal }) => { // data: the previous value returned from the fetcher // refetching: whether the fetcher is currently refetching // or it can be the value you passed to refetch() // onCleanup: A cleanup function that will be called when the source is invalidated // and the fetcher is about to re-run // signal: AbortSignal for cancelling fetch requests const response = await fetch(`api/posts?id=${id}`, { signal }); return response.json(); }, { debounce: 300 // lazy: Skip initial fetch when true // once: Only fetch once when true // initialValue: Provides an initial value for the resource // debounce: Debounce rapid changes // throttle: Throttle rapid changes } ); // The current value of the resource searchResource.current; // Whether the resource is currently loading searchResource.loading; // Error if the fetch failed searchResource.error; // Update the resource value directly, useful for optimistic updates searchResource.mutate(); // Re-run the fetcher with current watching values searchResource.refetch(); ``` -------------------------------- ### Watch an array of reactive sources Source: https://runed.dev/docs/utilities/watch This example demonstrates watching multiple reactive sources simultaneously. An array of getter functions is passed to `watch`. The callback receives the current and previous values for all watched sources, allowing for complex state-dependent logic. ```javascript let age = $state(20); let name = $state("bob"); watch([() => age, () => name], ([age, name], [prevAge, prevName]) => { // ... }); ``` -------------------------------- ### Example: Using Previous with a reactive state in Runed.js Source: https://runed.dev/docs/utilities/extract Demonstrates how to use the `Previous` utility to track the previous value of a reactive state variable ($state) in Runed.js. This is a common pattern for observing state changes. ```javascript import { Previous } from "runed"; let count = $state(0); const previous = new Previous(() => count); ``` -------------------------------- ### Example: Simplifying setTimeout with extract utility Source: https://runed.dev/docs/utilities/extract Shows a verbose, common pattern for determining a delay value for `setTimeout` using conditional checks for function execution or direct values. This highlights the problem `extract` aims to solve. ```javascript setTimeout( /* ... */, typeof wait === "function" ? (wait() ?? 250) : (wait ?? 250) ); ``` -------------------------------- ### IsIdle Usage Example with Svelte Source: https://runed.dev/docs/utilities/is-idle Demonstrates how to use the IsIdle component in a Svelte application to display the current idle state and the time of the last user activity. It highlights the basic setup and integration with Svelte's reactive properties. ```svelte

Idle: {idle.current}

Last active: {new Date(idle.lastActive).toLocaleTimeString()}

``` -------------------------------- ### SvelteKit Date Input Example (Svelte) Source: https://runed.dev/docs/utilities/use-search-params Demonstrates a practical Svelte component using `useSearchParams` and `createSearchParamsSchema` to manage date inputs. It binds two date parameters, `eventDate` (formatted as 'date') and `createdAt` (formatted as 'datetime'), to corresponding HTML input elements, updating the URL dynamically. ```svelte ``` -------------------------------- ### IsInViewport Usage and Type Definition Source: https://runed.dev/docs/utilities/is-in-viewport Demonstrates how to use the IsInViewport class to track element visibility in the viewport and shows the TypeScript type definitions. The usage example shows importing the class, creating an instance with a reactive state element, and accessing the current visibility state. The type definition shows the constructor parameters and current property access. ```typescript

Target node

Target node in viewport: {inViewport.current}

``` ```typescript import { type UseIntersectionObserverOptions } from "runed"; export type IsInViewportOptions = UseIntersectionObserverOptions; export declare class IsInViewport { constructor(node: MaybeGetter, options?: IsInViewportOptions); get current(): boolean; } ``` -------------------------------- ### AnimationFrames Usage Example with FPS Control Source: https://runed.dev/docs/utilities/animation-frames This Svelte component demonstrates how to use the AnimationFrames utility to control animation frame rates. It initializes AnimationFrames with a callback function to update frame count and delta time, and allows dynamic adjustment of the FPS limit via a slider. Dependencies include the AnimationFrames class from 'runed' and a custom Slider component. ```typescript import { AnimationFrames } from "runed"; import { Slider } from "../ui/slider"; // Check out shadcn-svelte! let frames = $state(0); let fpsLimit = $state(10); let delta = $state(0); const animation = new AnimationFrames( (args) => { frames++; delta = args.delta; }, { fpsLimit: () => fpsLimit } ); const stats = $derived( `Frames: ${frames}\nFPS: ${animation.fps.toFixed(0)}\nDelta: ${delta.toFixed(0)}ms` ); ``` -------------------------------- ### Integrating Zod Codecs into Search Parameter Schemas Source: https://runed.dev/docs/utilities/use-search-params This example demonstrates incorporating custom codecs into a Zod object schema for URL search parameters using the 'useSearchParams' hook from 'runed/kit'. It supports defaults and optional fields, transforming URL data into typed JavaScript objects. Inputs are URL params; outputs are reactive params object; assumes Svelte/RuneD environment with no noted limitations. ```typescript import { z } from "zod"; const searchSchema = z.object({ // Regular fields work as before query: z.string().default(""), page: z.coerce.number().default(1), // Unix timestamp - more compact than ISO datetime createdAfter: unixTimestampCodec.default(new Date("2024-01-01")), // Date-only format - cleaner for calendar dates birthDate: dateOnlyCodec.default(new Date("1990-01-15")), // Compact product IDs productId: compactIdCodec.optional() }); const params = useSearchParams(searchSchema); ``` -------------------------------- ### Scope Active Element Tracking to a Custom Document/Shadow Root Source: https://runed.dev/docs/utilities/active-element This example shows how to instantiate `ActiveElement` from 'runed' with a custom `document` option, allowing focus tracking to be scoped within a specific Shadow Root or Document instance. This is useful for isolated component environments. ```typescript import { ActiveElement } from "runed"; // Assuming 'shadowRoot' is a valid DocumentOrShadowRoot reference const activeElement = new ActiveElement({ document: shadowRoot }); ``` -------------------------------- ### Initializing PersistedState in Svelte Component Source: https://runed.dev/docs/utilities/persisted-state Demonstrates basic setup of PersistedState in a Svelte component with increment, decrement, and reset buttons to update and display a reactive count. Requires the 'runed' library import. Outputs reactive state updates that persist across sessions and tabs. ```svelte

Count: {count.current}

``` -------------------------------- ### Retrieving All Pressed Keys in JavaScript Source: https://runed.dev/docs/utilities/pressed-keys Instantiate PressedKeys and access the all property to get an array of all currently pressed keys. Useful for logging or general key state inspection. Returns an array of key names; no inputs required beyond instantiation. ```javascript const keys = new PressedKeys(); console.log(keys.all); ``` -------------------------------- ### Custom Serialization for Date Objects in PersistedState Source: https://runed.dev/docs/utilities/persisted-state Example of using superjson for serializing and deserializing Date objects in PersistedState. Requires importing superjson library. Enables persistence of non-plain types like Dates across sessions. ```typescript import superjson from "superjson"; // Example with Date objects const lastAccessed = new PersistedState("last-accessed", new Date(), { serializer: { serialize: superjson.stringify, deserialize: superjson.parse } }); ``` -------------------------------- ### Detect element size changes with useResizeObserver (TypeScript) Source: https://runed.dev/docs/utilities/use-resize-observer This snippet shows how to import and apply the useResizeObserver hook from the Runed library within a Svelte component. The observer updates a reactive text value with the element's width and height, and a separate example illustrates stopping the observer via the returned stop method. Requires Runed as a dependency and works in browsers supporting ResizeObserver. ```TypeScript ``` ```TypeScript const { stop } = useResizeObserver(/* ... */); stop(); ``` -------------------------------- ### Basic watch with single reactive source Source: https://runed.dev/docs/utilities/watch This snippet demonstrates the basic usage of the `watch` function. It takes a getter function that returns a reactive source and a callback function that executes when the source changes. The callback logs the current value of the source to the console. ```javascript import { watch } from "runed"; let count = $state(0); watch(() => count, () => { console.log(count); }); ``` -------------------------------- ### TypeScript - onClickOutside Controlled Listener Source: https://runed.dev/docs/utilities/on-click-outside Shows how to use onClickOutside with a dialog element, including start and stop control methods. ```typescript import { onClickOutside } from "runed"; let dialog = $state()!; const clickOutside = onClickOutside( () => dialog, () => { dialog.close(); clickOutside.stop(); }, { immediate: false } ); function openDialog() { dialog.showModal(); clickOutside.start(); } function closeDialog() { dialog.close(); clickOutside.stop(); }
``` -------------------------------- ### watchOnce.pre for single pre-emptive execution Source: https://runed.dev/docs/utilities/watch This snippet showcases `watchOnce.pre`, which combines the functionality of `watchOnce` and `$effect.pre`. The callback is executed only once, and it runs pre-emptively before the browser paint, without accepting any options. ```javascript watchOnce.pre(sources, callback); ``` -------------------------------- ### TextareaAutosize Grow-only Behavior (TypeScript) Source: https://runed.dev/docs/utilities/textarea-autosize This example shows how to configure TextareaAutosize for grow-only behavior using the 'minHeight' style property. This ensures the textarea expands to fit content but does not shrink below its current size. ```typescript new TextareaAutosize({ element: () => el, input: () => value, styleProp: "minHeight" }); ``` -------------------------------- ### Basic useInterval Usage with Counter and Controls Source: https://runed.dev/docs/utilities/use-interval Demonstrates basic usage of useInterval with reactive delay, counter tracking, pause/resume/reset controls, and status monitoring. Includes UI elements to interact with the interval and display current state. ```typescript

Counter: {interval.counter}

Interval delay: {delay}ms

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

``` -------------------------------- ### Resource with Multiple Dependencies Source: https://runed.dev/docs/utilities/resource Shows how to configure the `resource` utility to watch multiple reactive dependencies. The fetcher function receives an array of the current values of these dependencies, allowing for more complex data fetching scenarios. ```typescript const results = resource([() => query, () => page], async ([query, page]) => { const res = await fetch(`/api/search?q=${query}&page=${page}`); return res.json(); }); ``` -------------------------------- ### Creating StateHistory Instance Source: https://runed.dev/docs/utilities/state-history Initializes StateHistory with a getter to track state and a setter to update it. Requires the 'runed' import and a reactive state like $state. Outputs an object with log array of snapshots and timestamps, plus undo/redo/clear methods. Limited by manual logging triggers. ```typescript import { StateHistory } from "runed"; let count = $state(0); const history = new StateHistory(() => count, (c) => (count = c)); history.log[0]; // { snapshot: 0, timestamp: ... } ``` -------------------------------- ### Resource Pre-render Execution Source: https://runed.dev/docs/utilities/resource Demonstrates how to use `resource.pre()` for pre-render execution of data fetching. This allows data to be fetched before the component is fully rendered, improving perceived performance. ```typescript const data = resource.pre( () => query, async (query) => { const res = await fetch(`/api/search?q=${query}`); return res.json(); } ); ``` -------------------------------- ### Throttled State Management with runed.dev Source: https://runed.dev/docs/utilities/throttled Demonstrates how to use the Throttled component from 'runed' to create a throttled state. It shows basic usage with an input field and displaying the throttled search query, along with how to bind to a state variable and a delay. Dependencies include the 'runed' library. ```typescript

You searched for: {throttled.current}

``` -------------------------------- ### Watch deeply nested object state with $state.snapshot Source: https://runed.dev/docs/utilities/watch This example shows how to watch for changes in a deeply nested reactive object using `$state.snapshot()`. The `watch` function monitors the snapshot of the object, and the callback logs a descriptive message when any property within the object changes. ```javascript let user = $state({ name: 'bob', age: 20 }); watch(() => $state.snapshot(user), () => { console.log(`${user.name} is ${user.age} years old`); }); ``` -------------------------------- ### watch.pre for pre-emptive effect execution Source: https://runed.dev/docs/utilities/watch This snippet introduces `watch.pre`, which functions similarly to `watch` but utilizes `$effect.pre` internally. This means the callback will execute before the browser has painted, which can be useful for certain performance-sensitive updates. ```javascript watch.pre(sources, callback); ``` -------------------------------- ### Use Debounce Function in Svelte Component Source: https://runed.dev/docs/utilities/use-debounce Demonstrates how to use the useDebounce utility function to debounce callback execution in a Svelte component. The example shows a button counter that logs count after a specified debounce duration, with additional controls to run immediately or cancel the scheduled execution. ```TypeScript/Svelte

{logged || "Press the button!"}

``` -------------------------------- ### Attach Automatically Disposed Event Listener with useEventListener Source: https://runed.dev/docs/utilities/use-event-listener This example demonstrates how to use the `useEventListener` function to attach an event listener to the document body. The listener automatically disposes when the component is unmounted or the target element changes. It's useful for global event tracking without direct DOM manipulation. ```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"}

``` -------------------------------- ### FiniteStateMachine: Lifecycle Methods (_enter, _exit) Source: https://runed.dev/docs/utilities/finite-state-machine Demonstrates the use of special lifecycle methods (_enter, _exit) in FiniteStateMachine to execute logic when entering or exiting a state. These methods receive a metadata object. ```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"); } } }); ``` -------------------------------- ### Runed Context Class Definition (TypeScript) Source: https://runed.dev/docs/utilities/context Provides the full TypeScript definition of the Context class used by Runed, including constructor, key accessor, existence check, getters, fallback getter, and setter methods. All operations must be performed during component initialization. ```typescript class Context {\n\t/**\n\t * @param name The name of the context.\n\t * This is used for generating the context key and error messages.\n\t */\n\tconstructor(name: string) {}\n\n\t/**\n\t * The key used to get and set the context.\n\t *\n\t * It is not recommended to use this value directly.\n\t * Instead, use the methods provided by this class.\n\t */\n\tget key(): symbol;\n\n\t/**\n\t * Checks whether this has been set in the context of a parent component.\n\t *\n\t * Must be called during component initialization.\n\t */\n\texists(): boolean;\n\n\t/**\n\t * Retrieves the context that belongs to the closest parent component.\n\t *\n\t * Must be called during component initialization.\n\t *\n\t * @throws An error if the context does not exist.\n\t */\n\tget(): TContext;\n\n\t/**\n\t * Retrieves the context that belongs to the closest parent component,\n\t * or the given fallback value if the context does not exist.\n\t *\n\t * Must be called during component initialization.\n\t */\n\tgetOr(fallback: TFallback): TContext | TFallback;\n\n\t/**\n\t * Associates the given value with the current component and returns it.\n\t *\n\t * Must be called during component initialization.\n\t */\n\tset(context: TContext): TContext;\n} ``` -------------------------------- ### useGeolocation Type Definitions - TypeScript Source: https://runed.dev/docs/utilities/use-geolocation TypeScript type definitions for useGeolocation hook options and return types. Defines the configuration options including immediate startup behavior and the reactive return object with position, error, and control methods. ```typescript type UseGeolocationOptions = Partial & { /** * Whether to start the watcher immediately upon creation. * If set to `false`, the watcher will only start tracking the position when `resume()` is called. * * @defaultValue true */ immediate?: boolean; }; type UseGeolocationReturn = { readonly isSupported: boolean; readonly position: Omit; readonly error: GeolocationPositionError | null; readonly isPaused: boolean; pause: () => void; resume: () => void; }; ``` -------------------------------- ### TypeScript Resource Type Definitions Source: https://runed.dev/docs/utilities/resource Defines the types used for managing resources, including options for fetching, state representation, return values, fetcher information, and the fetcher function signature. It also details the `resource` function signature. ```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 = ( /** Current value of the source */ value: Source extends Array ? { [K in keyof Source]: Source[K]; } : Source, /** Previous value of the source */ previousValue: Source extends Array ? { [K in keyof Source]: Source[K]; } : Source | undefined, info: ResourceFetcherRefetchInfo ) => Promise; function resource< Source, RefetchInfo = unknown, Fetcher extends ResourceFetcher< Source, Awaited>, RefetchInfo > = ResourceFetcher >( source: Getter, fetcher: Fetcher, opions?: ResourceOptions>> ): ResourceReturn>, RefetchInfo>; ``` -------------------------------- ### Track Element Dimensions with ElementSize (Svelte/TypeScript) Source: https://runed.dev/docs/utilities/element-size This snippet demonstrates how to use the ElementSize utility from the 'runed' library to track the width and height of an HTML element. It initializes ElementSize with a callback that returns the target element, and then displays the reactive width and height properties. Dependencies include the 'runed' library. ```typescript import { ElementSize } from "runed"; let el = $state() as HTMLElement; const size = new ElementSize(() => el); ``` -------------------------------- ### Callback Functionality Source: https://runed.dev/docs/utilities/use-interval Demonstrates useInterval with an optional callback function that receives the current counter value on each tick. Shows how to log or process each tick. ```typescript ``` -------------------------------- ### FiniteStateMachine: Actions for Conditional Transitions Source: https://runed.dev/docs/utilities/finite-state-machine Shows how to use action functions within FiniteStateMachine transitions for conditional logic. Actions can dynamically determine the next state or prevent transitions by returning nothing. ```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"; } } } }); ``` -------------------------------- ### Throttle function execution with useThrottle Source: https://runed.dev/docs/utilities/use-throttle Implements throttling for function execution using Runed's useThrottle. Takes a function and throttle duration, returning a throttled version. Useful for limiting rapid event handlers like search input updates. Depends on Runed's useThrottle import and Solid.js reactivity. ```typescript
search, (v) => { search = v; throttledUpdate(); } } />

You searched for: {throttledSearch}

``` -------------------------------- ### Define Product Search Schema with Zod Source: https://runed.dev/docs/utilities/use-search-params Defines a Zod schema for validating product search parameters, including pagination, filtering, and sorting options. It sets default values and specifies the type for each parameter. ```typescript import { z } from "zod"; // Version 3.24.0+ export const productSearchSchema = z.object({ page: z.coerce.number().default(1), filter: z.string().default(""), sort: z.enum(["newest", "oldest", "price"]) }); ``` -------------------------------- ### Schema with createSearchParamsSchema Source: https://runed.dev/docs/utilities/use-search-params Creates a lightweight schema for `useSearchParams` without external dependencies. Supports basic types, arrays, and objects with default values. Not suitable for complex validation. ```javascript 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 } }); ``` -------------------------------- ### Schema with Options Source: https://runed.dev/docs/utilities/use-search-params Configures `useSearchParams` with options for debouncing, history management, and compression. Useful for controlling URL update behavior and reducing URL length. Requires a schema definition. ```javascript // Show default values in URL, debounce updates by 300ms, // don't create new history entries, and compress params const params = useSearchParams(schema, { showDefaults: true, debounce: 300, pushHistory: false, compress: true, compressedParamName: '_compressed' // Custom name to avoid conflicts }); // Great for binding to input fields (updates URL without cluttering history) // Resulting URL will be something like: /?_compressed=N4IgDgTg9g... ``` -------------------------------- ### Watch callback with current and previous values Source: https://runed.dev/docs/utilities/watch This snippet shows how the callback function in `watch` receives both the current and previous values of the watched sources. This is useful for comparing state changes and implementing logic based on transitions. ```javascript let count = $state(0); watch(() => count, (curr, prev) => { console.log(`count is ${curr}, was ${prev}`); }); ``` -------------------------------- ### IsMounted Component Usage (Svelte) Source: https://runed.dev/docs/utilities/is-mounted Demonstrates how to use the IsMounted component from the 'runed' library in a Svelte component. This component helps track the mounted state of the component it's used within. ```svelte ``` -------------------------------- ### Basic Schema with Valibot Source: https://runed.dev/docs/utilities/use-search-params Defines a search params schema using Valibot for type validation and default values. `useSearchParams` integrates with Valibot for robust data handling. ```javascript 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); ``` -------------------------------- ### IsMounted Alternative using onMount (Svelte) Source: https://runed.dev/docs/utilities/is-mounted Shows an alternative implementation for tracking component mounted state in Svelte using the built-in 'onMount' lifecycle function. This provides a similar functionality to the IsMounted component. ```svelte ``` -------------------------------- ### Real-World Svelte Implementation of Event Search with Codecs Source: https://runed.dev/docs/utilities/use-search-params This Svelte component uses custom Zod codecs in a schema for event search parameters, integrating with 'useSearchParams' from 'runed/kit'. It handles date inputs reactively, producing cleaner URLs. Dependencies include 'zod' and 'runed/kit'; inputs are form values; outputs are typed params for app logic; limited to browser environment. ```typescript ``` -------------------------------- ### Wildcard Handlers in Runed Source: https://runed.dev/docs/utilities/finite-state-machine This snippet demonstrates the use of wildcard handlers (`*`) in a Runed FiniteStateMachine. The wildcard state acts as a fallback, handling events not explicitly defined in other states. This ensures events are processed even if the state machine isn't fully configured. ```typescript import { FiniteStateMachine } from "runed"; interface MyStates = "on" | "off"; interface 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"); ``` -------------------------------- ### Interface for Search Parameter Options Source: https://runed.dev/docs/utilities/use-search-params Defines configuration options for managing search parameters. It allows control over showing default values, debouncing URL updates, managing browser history, compressing data, and customizing date formats. ```typescript interface SearchParamsOptions { /** * If true, parameters set to their default values will be shown in the URL. * If false, parameters with default values will be omitted from the URL. * @default false */ showDefaults?: boolean; /** * The number of milliseconds to delay URL updates when parameters change. * This helps avoid cluttering browser history when values change rapidly * (like during typing in an input field). * @default 0 (no debounce) */ debounce?: number; /** * Controls whether URL updates create new browser history entries. * If true (default), each update adds a new entry to the browser history. * If false, updates replace the current URL without creating new history entries. * @default true */ pushHistory?: boolean; /** * Enable lz-string compression for all parameters. * When true, all parameters are compressed into a single parameter in the URL. * This helps reduce URL length and provides basic parameter obfuscation. * @default false */ compress?: boolean; /** * The name of the parameter used to store compressed data when compression is enabled. * You can customize this to avoid conflicts with your schema parameters. * For example, if your schema already uses '_data', you might want to use '_compressed' or another unique name. * @default '_data' */ compressedParamName?: string; /** * Controls whether to update the URL when parameters change. * If true (default), changes to parameters will update the URL. * If false, parameters will only be stored in memory without updating the URL. * Note: When false, compress option will be ignored. * @default true */ updateURL?: boolean; /** * If true, the page will not scroll to the top when the URL is updated. * This is useful if you want to maintain the user's scroll position during parameter changes. * @default false */ noScroll?: boolean; /** * Specifies which date fields should use date-only format (YYYY-MM-DD) instead of full ISO8601 datetime. * * Map field names to their desired format: * - 'date': Serializes as YYYY-MM-DD (e.g., "2025-10-21") * - 'datetime': Serializes as full ISO8601 (e.g., "2025-10-21T18:18:14.196Z") * * Example: * { dateFormats: { birthDate: 'date', createdAt: 'datetime' } } * * @default undefined (all dates use datetime format) */ dateFormats?: Record; } ``` -------------------------------- ### Using Previous Utility in Svelte with TypeScript Source: https://runed.dev/docs/utilities/previous This snippet shows importing and instantiating the Previous utility to track the prior value of a reactive count state. It includes a button to increment the count and displays both current and previous values. Requires the 'runed' library; outputs reactive previous value for UI updates, with initial undefined state. ```svelte
Previous: {`${previous.current}`}
``` -------------------------------- ### useGeolocation Svelte Component - Svelte/TypeScript Source: https://runed.dev/docs/utilities/use-geolocation Svelte component demonstrating reactive geolocation usage. Imports the hook, displays current position coordinates, timestamp, error state, and provides pause/resume controls. Shows how to handle supported state and display geolocation data reactively. ```svelte
Coords: {JSON.stringify(location.position.coords, null, 2)}
Located at: {location.position.timestamp}
Error: {JSON.stringify(location.error, null, 2)}
Is Supported: {location.isSupported}
``` -------------------------------- ### Initialize ScrollState with an Element Source: https://runed.dev/docs/utilities/scroll-state Demonstrates how to initialize the ScrollState utility with a specific HTML element as the scroll container. It shows how to bind the element and access reactive properties like scroll position and direction. ```typescript import { ScrollState } from "runed"; let el = $state(); const scroll = new ScrollState({ element: () => el }); ``` -------------------------------- ### Basic Schema with Zod Source: https://runed.dev/docs/utilities/use-search-params Defines a search params schema using Zod for type validation and default values. Accesses parameters reactively using `$derived`. Suitable for complex validation needs. ```javascript 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); // Access parameters directly const page = $derived(params.page); // number (defaults to 1) const sort = $derived(params.sort); // 'newest' | 'oldest' | 'price' ``` -------------------------------- ### Register cleanup function with onCleanup Source: https://runed.dev/docs/utilities/on-cleanup Demonstrates how to use onCleanup to register a cleanup function that executes when the component is destroyed or an effect is disposed. It can replace onDestroy and is useful for resource cleanup. ```TypeScript import { onCleanup } from "runed"; // can act as a replacement for `onDestroy` onCleanup(() => { console.log("Component is being cleaned up!"); }); // can be used within a root effect to call a cleanup function when the root effect is disposed $effect.root(() => { onCleanup(() => { console.log("Root effect is being cleaned up!"); }); }); ``` ```TypeScript function onCleanup(cb: () => void): void; ```