# Tempo Documentation This file is generated from the Tempo documentation site. # Tempo | [![npm @tempots/dom](https://img.shields.io/npm/v/@tempots/dom?label=@tempots/dom)](https://www.npmjs.com/package/@tempots/dom) | [![npm @tempots/std](https://img.shields.io/npm/v/@tempots/std?label=@tempots/std)](https://www.npmjs.com/package/@tempots/std) | [![npm @tempots/ui](https://img.shields.io/npm/v/@tempots/ui?label=@tempots/ui)](https://www.npmjs.com/package/@tempots/ui) | [![codecov](https://codecov.io/gh/fponticelli/tempots/branch/main/graph/badge.svg)](https://codecov.io/gh/fponticelli/tempots) | [![CI](https://github.com/fponticelli/tempots/workflows/CI/badge.svg)](https://github.com/fponticelli/tempots/actions) | | --- | --- | --- | --- | --- | > A new UI Framework for the web ## Why Choose Tempo? - Simple TypeScript functions - Predictable rendering without surprises - Zero dependencies - No hidden complexities - Directly updates the DOM (no virtual DOM) - Fine-grained control when required - Lightweight and efficient To get started, see the [Quick Start](#quick-start) guide. ## Documentation - [Quick Start](#quick-start): Get started with Tempo in a few simple steps - [Installation](#installation): Install Tempo using npm or yarn - [How It Works](#how-does-it-work): Learn how Tempo works under the hood - [Renderables](#renderables): The building blocks of Tempo applications - [Signals](#signals): Reactive state management - [Build your own Renderables](#build-your-own-renderables): Create reusable components - [Providers](#providers): Dependency injection and context sharing - [Examples & Best Practices](#examples-patterns): Common patterns and best practices - [Troubleshooting & FAQ](#troubleshooting-faq): Common issues and solutions ## Libraries Tempo provides a set of libraries to help you build your applications: - [@tempots/dom](#tempotsdom): The core UI framework - [@tempots/std](#tempotsstd): A [standard library](#standard-library) with utility functions and types - [@tempots/ui](#tempotsui): A collection of [reusable UI components](#ui-components) ## Demos See Tempo in action with these demo applications: - [Hackers News PWA](https://tempo-ts.com/demo/hnpwa.html): A Hacker News reader - [7GUIs](https://tempo-ts.com/demo/7guis.html): Implementation of the 7GUIs benchmark - [TodoMVC](https://tempo-ts.com/demo/todomvc.html): The classic TodoMVC example - [Counter Demo](https://tempo-ts.com/demo/counter.html): A simple counter application ## LLM-Friendly Documentation This documentation is available in LLM-optimized formats following the [llms.txt](https://llmstxt.org/) convention: - [`llms.txt`](/llms.txt) — Documentation index for AI tools - [`llms-full.txt`](/llms-full.txt) — Complete documentation in a single file --- # Quick Start Tempo can be used for fully fledged single-page applications or simple widgets. Either way, it is easy to get started: 1. Define a template or component 2. Render it to the DOM at a specific location ## Hello World A classic “Hello World” example:```ts import { html, render } from '@tempots/dom' // Define a template or renderable const HelloWorld = html.h1('Hello World') // Render it to the DOM render(HelloWorld, document.body) ``` The `render()` call returns a function that can be used to remove the rendered template from the DOM: ```ts // Render it to the DOM const remove = render(HelloWorld, document.body) // Remove it from the DOM after 1 second setTimeout(() => { console.log('Removing HelloWorld') remove() }, 1000) ``` ## Add state and interactivity State in Tempo is managed through signals. Signals are reactive and can be used to update the DOM (or anything else) when they change. A `Signal` is a readonly object that can be observed but not updated. A `Prop` is a writable object that can be updated. A `Computed` is a readonly object that is derived from other signals. Here is an example of a simple counter: ```ts import { html, on, render, prop } from '@tempots/dom' // Define a writeable signal const count = prop(0) // Define a template const Counter = html.div( html.h1(count.map(v => `count: ${v}`)), // ✨ Auto-disposed html.div( html.button(on.click(() => count.value++), '+'), html.button(on.click(() => count.value--), '-'), ) ) // Render it to the DOM render(Counter, document.body) ``` The `count` signal is updated by mutating the `count.value` that computes a new value based on the current value. `count` can also be set directly by calling `count.set()` or update with a function with `count.update(v => v+1)`. What about ``count.map(v => `count: ${v}`)``? This is a `Computed` signal that is derived from the `count` signal. It will update whenever `count` changes. The `map()` function is a helper function that maps the value of the signal to a new value. Events are handled by using the functions associated to the `on` object. The `on.click()` function creates an event listener for the `click` event. ### Automatic Memory Management **Important:** Signals created within renderables (like `count` and `count.map(...)` above) are automatically tracked and disposed when the component is removed from the DOM. This means: - ✅ No manual cleanup needed - ✅ No memory leaks - ✅ Works with all signal types: `prop()`, `signal()`, `computed()` - ✅ Works with derived signals: `.map()`, `.filter()`, `.flatMap()`, etc. Tempo automatically creates a disposal scope for each renderable and tracks all signals created within it. When the renderable is removed from the DOM, all tracked signals are automatically disposed. Note that differently from other frameworks, Tempo does not make a distinction between children nodes, attributes, properties, or event handlers. Everything satisfies the same `Renderable` type and `Renderable`s can be nested in any component that accept children. This brings a lot of flexibility and simplicity to the API. One example is that you can use the `Portal` component not just to render the content of a selected element but also change/add to its attributes, classes and event handlers. ## Next Steps - [Installation](#installation) - Learn more about [how Tempo works](#how-does-it-work) - [Renderables](#renderables), the building blocks of Tempo applications - [Signals](#signals), the reactive core of Tempo - [Learn more about Building your own Renderables](#build-your-own-renderables) - [Render](#render), the function to apply Renderables to the DOM --- # Installation Tempo is available as a package on npm. You can install it using npm or yarn:```bash # npm npm install @tempots/dom # yarn yarn add @tempots/dom ``` Tempo is written in TypeScript so types are generated and included in the package. You can use Tempo with or without TypeScript. If you are using TypeScript, you will get full type checking and autocompletion. `@tempots/dom` doesn't have any dependency. If you use `@tempots/ui` you will also need to install `@tempots/dom` and `@tempots/std` as they are peer dependencies. ## Additional Packages Tempo provides additional packages for specific use cases: | Package | Purpose | |---------|---------| | `@tempots/std` | Standard library with utilities and common patterns | | `@tempots/ui` | Pre-built UI components | | `@tempots/server` | Server-side rendering to strings and streams | | `@tempots/client` | Client-side hydration and islands architecture | | `@tempots/vite` | Vite plugin for SSG with automatic route discovery | ### For SSR/SSG Projects If you're building a server-rendered or static site, install the SSR packages: ```bash npm install @tempots/dom @tempots/server @tempots/client @tempots/vite ``` See [SSR & Headless Rendering](#ssr-headless-rendering) for detailed documentation. ## Next Steps - [How does Tempo work?](#how-does-it-work) - [Learn more about Renderables](#renderables) - [Learn more about Signals](#signals) - [Learn more about Building your own Renderables](#build-your-own-renderables) - [SSR & Headless Rendering](#ssr-headless-rendering) - [Explore Examples & Best Practices](#examples-patterns) - [Learn more about render](#render) --- # How Does It Work? ## Renderable The core of Tempo is the `Renderable` type. A `Renderable` is a function with the following signature:```ts type Renderable = (context: DOMContext) => Clear type Clear = (removeTree: boolean) => void ``` The `Renderable` function takes a `DOMContext` object, which provides access to the DOM and other utilities. The function returns a `Clear` function that removes the rendered template from the DOM. This simple signature offers flexibility and ease of use. For instance, consider the `Fragment` component, which can have multiple children but doesn’t contribute to the DOM itself. It’s used to group multiple renderables together. Here’s its implementation: ```ts export const Fragment = (...children: TNode[]): Renderable => (ctx: DOMContext) => { const clears = children.map(child => renderableOfTNode(child)(ctx)) return (removeTree: boolean) => { clears.forEach(clear => clear(removeTree)) } } ``` In Tempo, you often pass a `TNode` (short for Tempo Node) to existing renderables. A `TNode` is a union type that includes commonly used types in Tempo: `Renderable`, `Signal`, `Prop`, `Computed`, `string`, `undefined`, `null`, or an `Array`. The `renderableOfTNode` function helps convert a `TNode` to a `Renderable`. Using `TNode` makes the API more flexible and allows for a more declarative syntax. ```ts html.div('Hello World') // equivalent to html.div(TextNode('Hello World')) ``` ### Clear The `Clear` function removes the rendered template from the DOM. Its argument, `removeTree`, indicates whether to remove side effects, such as clearing an interval or timeout, and all DOM modifications (`true`) or only side effects (`false`). ### TNode A `TNode` is treated differently based on its type: - string or `Value` (alias for `Signal | string`): Treated as a text node. - `undefined` or `null`: Ignored. - `Renderable`: Left unmodified. - `Renderable[]`: Gets wrapped into a `Fragment`. ## DOMContext The `DOMContext` object, passed to the Renderable function, provides access to the DOM and other utilities. It has the following properties: - `element`: The Element instance associated with this context. - `reference`: An optional Node instance serving as a reference for this context. - `document`: The Document instance associated with this context. The reference node, `TextNode` with an empty string, acts as a placeholder when elements are added or removed between siblings. It’s useful for `Renderables` like `ForEach` or `When`, which need to track element positions in the DOM. Additionally, `DOMContext` contains a collection of providers for shared state between Renderables, avoiding prop drilling and keeping the API clean. The `isFirstLevel` property, still experimental, marks nodes for server-side rendering and hydration. ## Next Steps - [Learn more about Renderables](#renderables) - [Learn more about Signals](#signals) - [Learn more about Building your own Renderables](#build-your-own-renderables) - [Explore the Standard Library](#standard-library) - [Discover UI Components](#ui-components) - [Learn more about render](#render) --- # Renderables Renderables or components are the building blocks of Tempo applications. They are the templates that are rendered to the DOM. Tempo provides a set of functions to create and manipulate renderables. The Renderable functions use the convention of starting with a capital letter. This is to differentiate them from regular functions and to make it easier to identify them in the code. The notable exception is for basic html/svg elements, which are lowercase. ## HTML/SVG, text and Attributes To create HTML or SVG elements, use the `html` and `svg` objects. Each of them contains the full list of available tags as functions. For example, to create a `div` element, use `html.div()`. To create a `circle` element, use `svg.circle()`. These functions take an arbitrary number of `TNode` arguments. A `TNode` can be a string, a `Signal`, a `Renderable`, a `Renderable[]` or `null`/`undefined`. To create text nodes, you can just pass a `string` or a `Signal` where a `TNode` is expected. Alternatively you can be explicit and use the `TextNode()` function. ```ts const titleSignal = signal('Hello, World!') html.div( 'Hello, World!', // <-- this is a text node titleSignal, // <-- this is a signal that automatically updates a text node html.span('This is a span'), TextNode('This is also a text node') ) ``` To create DOM attributes and properties use the `attr` object. It contains functions for all the standard attributes and properties. For example, to set the `id` attribute, use `attr.id('my-id')`. ```ts html.img( attr.id('my-id'), attr.src('https://example.com/image.jpg'), attr.title(titleSignal) ) ``` You will have noticed that text nodes and attribute values accept both literal values (ex. `'Hello, World!'`) and signals (ex. `titleSignal`). This is because the arguments are typed as `Value` which is a union of `T` and `Signal`. `Value` also happens to be part of the `TNode` union. ### attr.class The `class` attribute is special in the sense that can be used multiple times in the same element. ```ts const classSignal = signal('class3 class4') html.div(attr.class('class1 class2'), attr.class(classSignal)) ``` A class attribute can be a string or a signal that emits a string. The string can contain multiple classes separated by spaces. ### Other attributes and elements There are helper objects to create arbitrary data-attributes, math/svg elements and attributes, and style attributes. ```ts html.div( dataAttr.mydata('myvalue'), math.math( mathAttr.display('inline'), math.mfrac(math.msup(math.mi('π'), math.mn('2')), math.mn('6')) ), svg.svg(svg.circle(svgAttr.cx(50), svgAttr.cy(50), svgAttr.r(40))), style.color('red') ) ``` ## Events Similar to attributes, events can be set using the `on` object. The `on` object contains functions for all the standard events. For example, to set the `click` event, use `on.click(fn)`. It is fine to use `signal.value` or `signal.get()` to get the value of a signal in an event handler. ### emit helpers Tempo provides a set of functions to simplify event handling by extracting values from DOM events: | Helper | Description | | --------------------------------- | ---------------------------------------------- | | `emitValue(fn)` | Extract string value from input/textarea | | `emitValueAsNumber(fn)` | Extract numeric value (uses `valueAsNumber`) | | `emitValueAsDate(fn)` | Extract Date from date input | | `emitValueAsNullableDate(fn)` | Extract Date or null from date input | | `emitValueAsDateTime(fn)` | Extract Date from datetime-local input | | `emitValueAsNullableDateTime(fn)` | Extract Date or null from datetime-local input | | `emitChecked(fn)` | Extract boolean from checkbox/radio | | `emitTarget(fn)` | Get the target element directly | ```ts const name = prop('') const age = prop(0) const birthDate = prop(null) const isSubscribed = prop(false) html.form( // Text input - use prop.set directly as callback html.input( attr.type('text'), attr.value(name), on.input(emitValue(name.set)) ), // Number input - use filter for validation html.input( attr.type('number'), attr.value(age.map(String)), on.input( emitValueAsNumber(v => { if (!isNaN(v)) age.set(v) }) ) ), // Date input - prop.set works directly html.input( attr.type('date'), on.change(emitValueAsNullableDate(birthDate.set)) ), // Checkbox - prop.set works directly html.input( attr.type('checkbox'), attr.checked(isSubscribed), on.change(emitChecked(isSubscribed.set)) ), // Direct element access html.input( on.focus( emitTarget((input: HTMLInputElement) => { input.select() // Select all text on focus }) ) ) ) ``` **Emit Options:** All emit helpers accept an optional second argument for event control: ```ts type EmitOptions = { preventDefault?: boolean stopPropagation?: boolean stopImmediatePropagation?: boolean } // Example: prevent form submission on.submit( emitTarget( () => { console.log('Form submitted') }, { preventDefault: true } ) ) ``` ## input elements When using `input` elements it is very common you want to specify the type of the input. Tempo provides a set of functions to create `input` elements with the correct type. For example, to create a `number` input, use `input.number()`. ## bind Tempo provides functions to bind `Props` to input elements. For example, to bind a `string` prop to an `input` element, use `BindText`. Other bind functions include `BindNumber`, `BindDate`, `BindDateTime`, and `BindChecked`. These set a bidirectional binding between the prop and the input element. ```ts import { prop, input, BindText, BindNumber, BindDate, BindDateTime, BindChecked } from '@tempots/dom' // Text binding - syncs input value with prop const email = prop('') input.text(BindText(email)) // Number binding - parses input as number const age = prop(0) input.number(BindNumber(age)) // Date binding - syncs with date input const birthDate = prop(new Date()) input.date(BindDate(birthDate)) // DateTime binding - syncs with datetime-local input const appointmentTime = prop(new Date()) input['datetime-local'](BindDateTime(appointmentTime)) // Checkbox binding - syncs checked state const isSubscribed = prop(false) input.checkbox(BindChecked(isSubscribed)) ``` ## Conditionals Tempo has a set of functions to create conditional renderables. For example, to render a `div` element only if a condition is met, use `When` (or `Unless` for its negation). ```ts const showSignal = signal(true) When(showSignal, () => html.div('This is visible')) ``` A second argument can be passed to `When` to specify a renderable to show when the condition is false. An interesting aspect of conditionals in Tempo, is that there is no DOM rebuilding unless the branch is changed. ### Ensure In TypeScript it is common to work with values that can be `null` or `undefined`. To render a value only if it is not `null` or `undefined`, use `Ensure`. ```ts const valueSignal = signal('Hello, World!') Ensure(valueSignal, v => html.div(v.map(text => `This is visible: ${text}`))) ``` Unlike `When`, `Ensure` takes a function that returns a renderable. This function is called with a new signal that is guaranteed to be not `null` or `undefined`. ### OneOf `OneOf` helpers allow matching a signal and rendering a branch based on its value. Several variations exist depending on what you want to match. ```ts const status = signal<{ loading: true } | { error: string }>({ loading: true }) OneOf(status, { loading: () => html.div('Loading...'), error: e => html.div('Error:', e), }) ``` #### OneOfValue ```ts const mode = signal<'view' | 'edit'>('view') OneOfValue(mode, { view: () => html.div('Viewing'), edit: () => html.div('Editing'), }) ``` #### OneOfTuple ```ts const pair = signal(['A', 1] as ['A' | 'B', number]) OneOfTuple(pair, { A: n => html.div('A:', n.map(String)), B: n => html.div('B:', n.map(String)), }) ``` #### OneOfField ```ts type State = | { state: 'loading' } | { state: 'error'; message: string } | { state: 'ready'; content: string } const state = signal({ state: 'loading' }) OneOfField(state, 'state', { loading: () => html.div('Loading...'), error: s => html.div('Error:', s.$.message), ready: s => html.div('Ready:', s.$.content), }) ``` #### OneOfKind ```ts type MyType = { kind: 'A'; text: string } | { kind: 'B'; value: number } const valueSignal = signal({ kind: 'A', text: 'Hello, World!' }) OneOfKind(valueSignal, { A: v => html.div('A:', v.$.text), B: v => html.div('B:', v.$.value.map(String)), }) ``` #### OneOfType ```ts type Msg = { type: 'inc'; value: number } | { type: 'dec'; value: number } const msg = signal({ type: 'inc', value: 1 }) OneOfType(msg, { inc: m => html.div('Inc', m.$.value.map(String)), dec: m => html.div('Dec', m.$.value.map(String)), }) ``` ## Loops Of course you can also render lists of elements. Tempo provides a set of functions to create loops. For example, to render a list of `div` elements, use `ForEach`. ```ts const itemsSignal = signal(['Item 1', 'Item 2', 'Item 3']) ForEach(itemsSignal, (item, position) => html.div(position.$.counter.map(String), ': ', item) ) ``` The renderable function takes two arguments. The first is a signal that represent an element of the list. The second is a signal that represents the position of the element in the list. The position signal has a `counter` field that is the 1-based index of the element in the list as well as a `isFirst`, `isLast` and `index`. `ForEach` accepts an optional third argument to render a separator between elements. You can wrap your loop in a `NotEmpty` renderable if you want to ensure that the list is not empty. This is useful in the case of structures like `UL` or `OL` where an empty list would not be desired. ```ts const itemsSignal = signal(['Item 1', 'Item 2', 'Item 3']) NotEmpty( itemsSignal, items => html.ul(ForEach(items, item => html.li(item))), () => 'No items' ) ``` `Repeat` takes a signal that represents the number of times to repeat the renderable. It is useful when you want to repeat a renderable a fixed number of times. ```ts const countSignal = signal(3) Repeat(countSignal, pos => html.div(`${pos.counter} of `, pos.$.total.map(String)) ) ``` `counter` is a fixed value so it is not wrapped in a signal but `total` is a signal as it can vary when `countSignal` changes. If you know ahead of time the number and content of the elements, you can use a regular loop to create an array of renderables. ```ts const items = ['Item 1', 'Item 2', 'Item 3'] html.div(items.map((item, index) => html.div(String(index), ': ', item))) ``` ## Lifecycle For more advanced use cases, Tempo provides a set of functions to handle the lifecycle of a renderable. For example, to run a function when a renderable is mounted, use `WithElement`. This will take a callback function that will be called with the HTML DOM Element just mounted. Similarly `WithCtx` will take a callback function that will be called with the current `DOMContext`, and `WithBrowserCtx` for browser-specific contexts. ```ts html.div( // element is the DIV Element just mounted WithElement(element => { console.log('Mounted', element) }) ) ``` Whenever you want to cleanup resources when a renderable is unmounted, use `OnDispose`. ```ts html.div( WithElement(element => { const listener = () => console.log('Clicked') element.addEventListener('click', listener) return OnDispose((removeTree, ctx) => { if (removeTree) { element.removeEventListener('click', listener) } }) }) ) ``` ## Fragment/Empty You can use `Fragment` where a single renderable is expected but you want to render multiple components. Similarly, you can use `Empty` to fill a slot with nothing. ## Providers To simplify the structure of a larger project, it is often useful to use a Provide/Use pattern. In a high-level component, you can provide a value (or function, or signal, or anything really) that is consumed by a lower-level component. You can use `Provide` to provide a single value (or a record or a function), and `Use` to consume it. A provider is a simple object that knows how to provide a context value and how to identify itself. ```ts const Preferences = { mark: makeProviderMark>('Preferences'), create: () => { const preferences = signal({ theme: 'bubbly' }) // the implementation, it must return an object with return { value: preferences, dispose: preferences.dispose } }, } ``` The provider can be made available this way: ```ts const MyComponent = Provide( Preferences, {}, // options (can be empty) () => html.div(...) ) ``` And it can be used this way: ```ts Use(Preferences, value => html.div(value.$.theme)) ``` If you want to `set` and/or `use` multiple providers at once, you can use `WithProvider`. ```ts WithProvider(({ set, use }) => { set(Preferences, {}) const preferences = use(Preferences) return html.div(preferences.$.theme) }) ``` ## Asynchronous Operations Tempo provides two renderables for handling async operations: `Async` and `Task`. ### Async vs Task - **`Async(promise, options)`** - Wraps an existing Promise. The promise starts executing immediately when created. - **`Task(fn, options)`** - Wraps a function that returns a Promise. The function is called when the component renders (lazy execution). ```ts import { Async, Task } from '@tempots/dom' // Async: promise executes immediately when this line runs const immediateLoad = Async( fetch('/api/data').then(r => r.json()), { pending: () => html.div('Loading...'), then: data => html.div('Data: ', JSON.stringify(data)), error: err => html.div('Error: ', String(err)) } ) // Task: fetch only happens when the component renders const lazyLoad = Task( () => fetch('/api/data').then(r => r.json()), { pending: () => html.div('Loading...'), then: data => html.div('Data: ', JSON.stringify(data)), error: err => html.div('Error: ', String(err)) } ) // Shorthand: just pass a function for the success case const simpleTask = Task( () => fetch('/api/data').then(r => r.json()), data => html.div('Data: ', JSON.stringify(data)) ) ``` ### Using Signals for Reactive Data More often you'll want to combine `Signal`s with `Promise` for reactive data fetching: ```ts const dataSignal = Signal.ofPromise( fetch('https://api.example.com/data').then(res => res.text()), null // initial value before the promise resolves ) html.div(Ensure(dataSignal, data => html.div(data), html.div('Loading...'))) ``` When you need to refetch based on changing parameters, use `mapAsync`: ```ts const idSignal = signal(1) const dataSignal = idSignal.mapAsync( async id => { const res = await fetch(`https://api.example.com/data/${id}`) return res.text() }, null // default value before the promise resolves ) // dataSignal automatically refetches when idSignal changes ``` ## Portal A `Portal` is a way to render a renderable in a different part of the DOM. This is useful when you want to render a modal, a tooltip or you want to make changes to the `head` element. The `HTMLTitle` renderable defined in the `@tempots/ui` package is a good example of this. ```ts export const HTMLTitle = (title: Value) => Portal('head > title', attr.innerText(title)) ``` ## Next Steps - [Learn more about Signals](#signals) - [Learn more about Building your own Renderables](#build-your-own-renderables) - [Learn more about Providers](#providers) - [Discover UI Components](#ui-components) - [Explore Examples & Best Practices](#examples-patterns) - [Learn more about render](#render) --- # Signals Signals are the reactive data stores. They are used to manage state and notify state changes. ## Create signals There are three types of signals: `Signal`, `Prop`, and `Computed`. A `Signal` is a readonly object that can be observed but not updated. A `Prop` is a writable object that can be updated. A `Computed` is a readonly object that is derived from other signals. To create a signal, use the `signal()`, `prop()`, and `computed()` (or `computedOf`) functions.```tsx // create a signal that cannot be updated const s = signal(0) // create a signal that can be updated const p = prop(0) p.value = 1 console.log(p.value) // 1 // create a computed signal from a single dependency const c1 = computed(() => s.value * 2, [s]) // for multiple signals, prefer computedOf - cleaner syntax with type-safe values const c2 = computedOf(s, p)((sVal, pVal) => sVal + pVal) ``` When you create a Computed signal, you need to provide a function that returns the value of the signal. The function will be called whenever the dependency signals in the second argument change. There is no magic here, if you don't provide the dependency signals, the computed signal will not update. Signals can also be created from promises using the `Signal.ofPromise()` static method. ```ts const userSignal = Signal.ofPromise( fetch('/api/user').then(r => r.json()), null, // initial value before promise resolves error => ({ error: String(error) }) // optional error recovery function ) ``` The first argument is a promise that resolves to the value of the signal. The second argument is the initial value used until the promise resolves. An optional third argument is an error recovery function. ## Read signals Once you have a signal, you can read its value using the `value` property (or `get()` function). You generally don't access the `value` property directly unless you are referring it within an event handler or a computed signal. Since signals are reactive, you can listen to changes using the `on()` method. The method returns a function that you can call to stop listening to changes. This is how tempo monitors changes and updates the DOM. When you add a callback to a signal, the callback is called immediately with the current value of the signal. ## Modify props You can update a prop using the `set()` method or using the `value` setter. They both take a new value and update the signal. You can also update a prop using the `update()` method. The method takes a function that receives the current value and returns the new value. ```ts const p = prop(0) p.set(1) p.value = 2 p.update(v => v + 1) ``` ## Effects You can also create side effects using the `effect()` function. The function takes a function that performs the side effect and an array of signals that the side effect depends on. The function is called immediately and whenever the dependency signals change. The function returns a function that you can call to stop the side effect. ## Transform signals You can transform signals using the `map()`, `filter()`, `flatMap()`, and other functions. These functions create a new signal that is derived from the original signal. ```ts const count = prop(0) const doubled = count.map(x => x * 2) // ✨ Auto-disposed const positive = count.filter(x => x > 0) // ✨ Auto-disposed ``` **Automatic Disposal:** All derived signals (created with `.map()`, `.filter()`, `.flatMap()`, etc.) are automatically tracked and disposed when used within renderables. No manual cleanup needed! Since you will often work with signals of objects, you might find the `$` property useful. `$` is an object that contains signals for each property of the object. This makes it easy to work with signals of objects. ```ts const prop = prop({ name: 'John', age: 30 }) console.log(prop.$.name.value) // John ``` The `at()` function is equivalent to `$` and it takes the key as an argument. ## Automatic Memory Management When you create signals within a renderable, Tempo automatically tracks them and disposes them when the component is removed from the DOM. This applies to: - **Signal creation**: `prop()`, `signal()`, `computed()`, `computedOf()` - **Signal transformations**: `.map()`, `.filter()`, `.flatMap()`, `.filterMap()`, etc. - **Effects**: `effect()` functions ```ts import { html, prop, render } from '@tempots/dom' const MyComponent = () => { const count = prop(0) // ✨ Auto-disposed const doubled = count.map(x => x * 2) // ✨ Auto-disposed return html.div('Count: ', count, ' Doubled: ', doubled) } const clear = render(MyComponent(), document.body) // Later: clear() will automatically dispose count and doubled ``` ### Long-Lived Signals If you need to create a signal that outlives the current component scope, use `untracked()`: ```ts import { untracked, prop } from '@tempots/dom' const globalState = untracked(() => prop(0)) // Not auto-disposed // Remember to dispose manually when done: globalState.dispose() ``` ## Signal Methods Reference ### Listening Methods | Method | Description | | ------------------------------ | --------------------------------------------------------------------------------------------- | | `on(listener, options?)` | Listen to value changes. Called immediately with current value. Returns unsubscribe function. | | `onChange(listener, options?)` | Like `on()` but skips the initial call - only fires on actual changes. | | `hasListeners()` | Returns `true` if the signal has any registered listeners. | **Listener Options:** ```ts type ListenerOptions = { skipInitial?: boolean // Don't call immediately with current value once?: boolean // Unsubscribe after first call abortSignal?: AbortSignal // Cancel via AbortController } ``` ### Transformation Methods | Method | Description | | -------------------------------------- | ------------------------------------------------------------ | | `map(fn, equals?)` | Transform values to a new type. Returns a Computed signal. | | `flatMap(fn, equals?)` | Map then flatten nested signals. | | `filter(predicate, startValue?)` | Only emit values matching predicate. | | `filterMap(fn, startValue, equals?)` | Map + filter in one operation. Skips null/undefined results. | | `mapMaybe(fn, alt)` | Map with fallback for null/undefined results. | | `mapAsync(fn, alt, recover?, equals?)` | Async transformation with abort support. | | `tap(fn)` | Execute side effect without modifying value. | ```ts const count = prop(5) // Transform to different types const doubled = count.map(n => n * 2) const message = count.map(n => `Count is ${n}`) // Filter values const positive = count.filter(n => n > 0) // Async transformation const userData = userId.mapAsync( async (id, { abortSignal }) => { const res = await fetch(`/api/users/${id}`, { signal: abortSignal }) return res.json() }, null // initial value ) // Side effects without modifying const logged = count.tap(n => console.log('Value:', n)) ``` ### Object Access Methods | Method | Description | | --------- | -------------------------------------------------------------------------------------------------------- | | `at(key)` | Get a signal for a specific property of the value. | | `$` | Proxy object providing signals for all properties. `signal.$.name` is equivalent to `signal.at('name')`. | ### Disposal Methods | Method | Description | | --------------------- | ----------------------------------------------- | | `dispose()` | Dispose the signal and release all resources. | | `isDisposed()` | Returns `true` if the signal has been disposed. | | `onDispose(listener)` | Register a callback to run when disposed. | ### Prop-Specific Methods | Method | Description | | --------------- | -------------------------------------------------------- | | `set(value)` | Set a new value. | | `update(fn)` | Update value using a function: `prop.update(v => v + 1)` | | `reducer(fn)` | Create a reducer function with effects. | | `iso(get, set)` | Create a bidirectional transformation (isomorphism). | | `atProp(key)` | Get a writable Prop for a specific property. | ```ts const user = prop({ name: 'John', age: 30 }) // Get writable access to nested property const nameProp = user.atProp('name') nameProp.value = 'Jane' // Updates user.value.name ``` ### Static Methods | Method | Description | | ---------------------------------------------------- | ------------------------------- | | `Signal.ofPromise(promise, init, recover?, equals?)` | Create signal from a Promise. | | `Signal.is(value)` | Check if a value is a Signal. | | `Prop.is(value)` | Check if a value is a Prop. | | `Computed.is(value)` | Check if a value is a Computed. | ## Storage Utilities Tempo provides utilities for persisting signals to browser storage with automatic synchronization across tabs. ### localStorageProp Creates a Prop backed by localStorage: ```ts import { localStorageProp } from '@tempots/dom' const theme = localStorageProp({ key: 'app-theme', defaultValue: 'light', }) // Value persists across page reloads theme.value = 'dark' ``` ### sessionStorageProp Creates a Prop backed by sessionStorage (cleared when browser closes): ```ts import { sessionStorageProp } from '@tempots/dom' const formData = sessionStorageProp({ key: 'checkout-form', defaultValue: { email: '', address: '' }, }) ``` ### storedProp Options Both `localStorageProp` and `sessionStorageProp` accept these options: ```ts type StorageOptions = { key: Value // Storage key (can be reactive) defaultValue: T | (() => T) // Default when not in storage serialize?: (v: T) => string // Custom serialization (default: JSON.stringify) deserialize?: (v: string) => T // Custom deserialization (default: JSON.parse) equals?: (a: T, b: T) => boolean // Equality function syncTabs?: boolean // Sync across browser tabs (default: true) onKeyChange?: 'load' | 'migrate' | 'keep' // Behavior when key changes } ``` ### syncProp For cross-tab synchronization of any Prop: ```ts import { syncProp, prop } from '@tempots/dom' // Create a synchronized prop const sharedState = syncProp({ key: 'shared-state', prop: prop({ count: 0 }), }) // Changes in one tab automatically appear in other tabs sharedState.value = { count: 1 } ``` ## Next Steps - [Learn more about Building your own Renderables](#build-your-own-renderables) - [Explore the Standard Library](#standard-library) - [Troubleshooting & FAQ](#troubleshooting-faq) - [Learn more about render](#render) --- # Build your own Renderables or Components A reusable Renderable or Component can be exported as either a constant value or a function.```ts const Logo = html.div( attr.class('logo'), html.img(attr.src('logo.png')) ) ``` In this example, `Logo` is a reusable component. The content of the component remains the same; it doesn’t change. However, it is still reusable because it doesn’t generate a new DOM unless it is `render`ed. It can be applied multiple times in different locations, making it versatile across applications. Using a capitalized name for your component is a common convention to indicate that it is a component. You can create a component that is still constant and reusable but has dynamic content. ```ts const UserView = Async( fetchUser(), (user) => html.div(user.name) ) ``` The rendered content of the component is dynamic and depends on the result of the `fetchUser()` promise but the promise is executed only once for any instantiation of the component. ## Options More commonly, you'll see components that take a set of options as argument. In this case the component is a function that returns a `Renderable`. Tempo uses "options" instead of "props" to avoid confusion with the `prop()` signal type. ```ts const UserView = (user: User) => html.div(user.name) ``` This is a valid component but it is not often what you want in the context of Tempo because it does not allow to update the DOM when the options change. Each application of this component will result in a DOM state that will not change unless the component is re-rendered. To address this, you want to use `Signal`s instead. ```ts const UserView = (user: Signal) => html.div(user.$.name) ``` Now, any time the `user` signal changes, the DOM will be updated. Notice that the `$` property is used to access the value of a field wrapped in the signal. It is convenient and type-safe. The equivalent method is `user.at('name')`. To get the best of both worlds, you can use `Value`. ```ts const UserView = (user: Value) => html.div( Value.map(user, ({ name }) => name) ) ``` `Value` is a union type that can be either a `Signal` or a `T`. It is a convenient way to work with signals and values in the same way. `Value.map` is used to map a `Value` to a new `Value`. Most Renderables in Tempo accept `Value` instead of `Signal` or `T`. If you want to create components that take multiple arguments or options, you can shape them the way you want. ## Next Steps - [Discover UI Components](#ui-components) - [Explore Examples & Best Practices](#examples-patterns) - [Learn more about render](#render) --- # Providers Providers in Tempo offer a powerful dependency injection system that allows you to share state, services, and functionality across your application without prop drilling. This pattern is similar to React's Context API or Angular's dependency injection system, but with Tempo's functional approach. ## Core Concepts The provider system in Tempo consists of several key components: 1. **Provider Mark**: A unique identifier for a provider 2. **Provider**: An object that knows how to create and dispose of a value 3. **Provide**: A renderable that makes a provider available to its children 4. **Use**: A renderable that consumes a provider's value 5. **WithProvider**: A more flexible API for working with multiple providers ## Creating a Provider A provider is an object with two properties: - `mark`: A unique identifier created with `makeProviderMark` - `create`: A function that creates the provider's value and returns an object with: - `value`: The actual value to be provided - `dispose`: A cleanup function called when the provider is no longer needed - `onUse` (optional): A function called when the provider is used Here's how to create a simple provider:```typescript import { makeProviderMark, signal, Signal, Provider } from '@tempots/dom' // Define the type for our preferences interface Preferences { theme: 'light' | 'dark' fontSize: number } // Create a provider for preferences const PreferencesProvider: Provider> = { // Create a unique mark with the correct type mark: makeProviderMark>('Preferences'), // Create function returns the value and cleanup create: () => { // Create a signal to hold the preferences const preferences = signal({ theme: 'light', fontSize: 16 }) // Return the value and cleanup function return { value: preferences, dispose: () => preferences.dispose() } } } ``` ## Providing Values Once you have a provider, you can make it available to child components using the `Provide` renderable: ```typescript import { html, Provide } from '@tempots/dom' // Make the preferences available to all children const App = () => Provide( PreferencesProvider, // The provider to use {}, // Options (if any) () => html.div( // Child components that can access the provider html.h1('My App'), SettingsPanel(), MainContent() ) ) ``` The `Provide` function takes three arguments: 1. The provider object 2. Options to pass to the provider's `create` function (can be empty `{}`) 3. A function that returns the child components ## Consuming Provider Values To use a provider's value, use the `Use` renderable: ```typescript import { html, Use } from '@tempots/dom' const ThemeToggle = () => Use( PreferencesProvider, // The provider to use preferences => html.div( // Function that receives the provider value html.button( on.click(() => { // Toggle the theme preferences.update(prefs => ({ ...prefs, theme: prefs.theme === 'light' ? 'dark' : 'light' })) }), 'Toggle Theme: ', preferences.$.theme // Access theme property using $ shorthand ) ) ) ``` The `Use` function takes two arguments: 1. The provider to consume 2. A function that receives the provider's value and returns a renderable ## Using Multiple Providers If you need to use multiple providers, you can use `UseMany`: ```typescript import { html, UseMany } from '@tempots/dom' const SettingsPanel = () => UseMany( PreferencesProvider, UserProvider )( (preferences, user) => html.div( html.h2('Settings for ', user.$.name), html.div('Theme: ', preferences.$.theme), html.div('Font Size: ', preferences.$.fontSize.map(String)) ) ) ``` ## Advanced Usage with WithProvider For more complex scenarios, you can use `WithProvider` which gives you direct access to both `set` and `use` functions: ```typescript import { html, WithProvider } from '@tempots/dom' const AdvancedComponent = () => WithProvider(({ set, use }) => { // Set up multiple providers set(PreferencesProvider, {}) set(UserProvider, { userId: 123 }) // Use the providers const preferences = use(PreferencesProvider) const user = use(UserProvider) // Return a renderable using the providers return html.div( html.h2(`Hello, ${user.$.name}`), html.div(`Your theme is: ${preferences.$.theme}`) ) }) ``` ## Provider with Options Providers can accept options when they're created: ```typescript // Provider that accepts options const ThemeProvider: Provider, { initialTheme: string }> = { mark: makeProviderMark>('Theme'), create: (options = { initialTheme: 'light' }) => { const theme = signal(options.initialTheme) return { value: theme, dispose: () => theme.dispose() } } } // Using the provider with options const App = () => Provide( ThemeProvider, { initialTheme: 'dark' }, // Pass options here () => html.div( // ... ) ) ``` ## Real-World Example: Theme Provider Here's a complete example of a theme provider that detects the user's system preferences: ```typescript import { makeProviderMark, signal, Signal, Provider, html, Provide, Use, attr, on } from '@tempots/dom' // Define theme types type Theme = 'light' | 'dark' // Create the theme provider const ThemeProvider: Provider> = { mark: makeProviderMark>('Theme'), create: () => { // Detect system preference const prefersDark = window.matchMedia('(prefers-color-scheme: dark)') const theme = signal(prefersDark.matches ? 'dark' : 'light') // Listen for system preference changes const handler = (e: MediaQueryListEvent) => { theme.value = e.matches ? 'dark' : 'light' } prefersDark.addEventListener('change', handler) return { value: theme, dispose: () => { prefersDark.removeEventListener('change', handler) theme.dispose() } } } } // App component that provides the theme const App = () => Provide( ThemeProvider, {}, () => html.div( // Apply theme class to body Use( ThemeProvider, theme => html.body( attr.class(theme.map(t => `theme-${t}`)), html.h1('Themed App'), ThemeToggle(), Content() ) ) ) ) // Theme toggle button const ThemeToggle = () => Use( ThemeProvider, theme => html.button( on.click(() => { theme.value = theme.value === 'light' ? 'dark' : 'light' }), 'Toggle Theme: ', theme.map(t => t === 'light' ? '🌞' : '🌙') ) ) // Content that uses the theme const Content = () => Use( ThemeProvider, theme => html.div( attr.class('content'), html.p(`Current theme: ${theme.value}`) ) ) ``` ## Next Steps - [Learn more about Building your own Renderables](#build-your-own-renderables) - [Explore Examples & Best Practices](#examples-patterns) - [Learn more about render](#render) --- # Standard Library (@tempots/std) The `@tempots/std` package is a comprehensive standard library for TypeScript that provides utility functions and types commonly used in web applications. This package serves as a natural complement to the Tempo libraries but can be used independently in any TypeScript project. ## Installation```bash # npm npm install @tempots/std # yarn yarn add @tempots/std # pnpm pnpm add @tempots/std ``` ## Features The library provides utility functions organized into several modules: ### Array Operations ```typescript import { filterMapArray, uniqueByPrimitive, range, chunk, partition, groupBy, } from '@tempots/std' // Filter and map in one pass const numbers = [1, 2, 3, 4, 5] const evenDoubled = filterMapArray(numbers, n => n % 2 === 0 ? n * 2 : undefined ) // [4, 8] // Generate a range of numbers const oneToFive = range(5, 1) // [1, 2, 3, 4, 5] // Get unique values by a key extractor const users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 1, name: 'Clone' }, ] const uniqueUsers = uniqueByPrimitive(users, user => user.id) // [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }] // Chunk an array into groups const chunked = chunk([1, 2, 3, 4, 5], 2) // [[1, 2], [3, 4], [5]] // Partition by predicate const [evens, odds] = partition(numbers, n => n % 2 === 0) // [[2, 4], [1, 3, 5]] ``` ### String Utilities ```typescript import { capitalizeWords, ellipsis } from '@tempots/std' // or import { capitalizeWords, ellipsis } from '@tempots/std/string' // Capitalize words const capitalized = capitalizeWords('hello world') // 'Hello World' // Truncate text with ellipsis (uses unicode ellipsis character) const truncated = ellipsis('This is a long text', 10) // 'This is a…' ``` ### Result Type The `Result` type provides a way to handle operations that might fail: ```typescript import { Result } from '@tempots/std' // or import { Result } from '@tempots/std/result' // Create a success result const success = Result.success(42) // Create a failure result const failure = Result.failure(new Error('Something went wrong')) // Match on a result const value = Result.match( success, value => `Success: ${value}`, error => `Error: ${error.message}` ) // 'Success: 42' ``` ### AsyncResult Type Similar to `Result`, but for asynchronous operations with loading states: ```typescript import { AsyncResult } from '@tempots/std' // Create from a promise const asyncResult = await AsyncResult.ofPromise( fetch('https://api.example.com/data').then(r => r.json()) ) // Handle the result with pattern matching AsyncResult.match(asyncResult, { success: data => console.log('Data:', data), failure: error => console.error('Error:', error), loading: () => console.log('Loading...'), notAsked: () => console.log('Not started'), }) ``` ### Validation Type The `Validation` type is useful for form validation and data checking. It represents either a valid state or an invalid state with an error: ```typescript import { Validation } from '@tempots/std' // Define validation rules const validateEmail = (email: string): Validation => { if (!email.includes('@')) { return Validation.invalid('Email must contain @') } if (email.length < 5) { return Validation.invalid('Email too short') } return Validation.valid } const validateAge = (age: number): Validation => { if (age < 0) return Validation.invalid('Age cannot be negative') if (age > 150) return Validation.invalid('Age seems unrealistic') return Validation.valid } // Use validation const emailResult = validateEmail('user@example.com') // Pattern matching Validation.match( emailResult, () => console.log('Email is valid!'), error => console.log('Invalid:', error) ) // Type guards if (Validation.isValid(emailResult)) { console.log('Proceed with valid email') } if (Validation.isInvalid(emailResult)) { console.log('Error:', emailResult.error) } // Execute side effects conditionally Validation.whenValid(emailResult, () => { submitForm() }) Validation.whenInvalid(emailResult, error => { showError(error) }) // Convert to Result type for further processing const result = Validation.toResult(emailResult, 'user@example.com') ``` **Form Validation Example with Tempo:** ```typescript import { html, prop } from '@tempots/dom' import { Validation } from '@tempots/std' const email = prop('') const emailError = email.map(value => { const validation = validateEmail(value) return Validation.isInvalid(validation) ? validation.error : null }) html.form( html.input( attr.type('email'), attr.value(email), on.input(emitValue(email.set)) // Use prop.set directly ), Ensure(emailError, error => html.span(attr.class('error'), error)) ) ``` ## Available Modules The library is organized into the following modules: - `array` - Array manipulation utilities (filterMapArray, uniqueByPrimitive, range, chunk, partition, groupBy, etc.) - `async-result` - Asynchronous result handling with loading states - `bigint` - BigInt utilities - `boolean` - Boolean utilities - `date` - Date manipulation utilities - `deferred` - Promise deferral utilities - `domain` - Domain-specific types (Maybe, Nothing, Compare, etc.) - `equal` - Deep equality comparison - `function` - Function composition and manipulation - `iterator` - Iterator utilities (take, skip, filter, map, reduce, find, etc.) - `json` - JSON utilities - `map` - Map utilities (mapFromEntries, mapFilter, mapMerge, mapGroupBy, etc.) - `number` - Number utilities - `object` - Object manipulation - `promise` - Promise utilities - `random` - Random value generation - `regexp` - Regular expression utilities - `result` - Result type for error handling - `set` - Set utilities (setUnion, setIntersection, setDifference, etc.) - `string` - String manipulation utilities (80+ functions) - `timer` - Timing utilities (delayed, interval, throttle, debounce) - `union` - Union type utilities - `url` - URL/path utilities (parseUrl, buildUrl, joinPaths, etc.) - `validation` - Data validation utilities ## Next Steps - [Learn more about the UI components library](#ui-components) - [Learn more about render](#render) --- # UI Components (@tempots/ui) The `@tempots/ui` package is a collection of reusable UI components and renderables built on top of `@tempots/dom` to accelerate development with Tempo. This package provides higher-level abstractions for common UI patterns and components. ## Installation```bash # npm npm install @tempots/dom @tempots/std @tempots/ui # yarn yarn add @tempots/dom @tempots/std @tempots/ui # pnpm pnpm add @tempots/dom @tempots/std @tempots/ui ``` Note: `@tempots/dom` and `@tempots/std` are peer dependencies and must be installed alongside `@tempots/ui`. ## Features ### UI Components The library provides a set of reusable UI components: #### AutoFocus and AutoSelect ```typescript import { html, render } from '@tempots/dom' import { AutoFocus, AutoSelect } from '@tempots/ui' // Create an input that automatically gets focus const focusedInput = html.input( AutoFocus(), // Automatically focus this input when rendered AutoSelect() // Automatically select all text when focused ) // Render it to the DOM render(focusedInput, document.body) ``` #### InViewport Detect when an element is in the viewport: ```typescript import { html, render } from '@tempots/dom' import { InViewport } from '@tempots/ui' // Create an element that detects when it's in the viewport const lazyLoadedContent = InViewport( { mode: 'partial', once: false }, // mode: 'partial' | 'full', once?: boolean (isVisible) => isVisible.map(v => v ? html.div('Content is visible!') : html.div('Loading...')) ) // Render it to the DOM render(lazyLoadedContent, document.body) ``` #### HTMLTitle Set the document title: ```typescript import { html, render, prop } from '@tempots/dom' import { HTMLTitle } from '@tempots/ui' // Create a title that updates when the signal changes const title = prop('Welcome to my app') const app = html.div( HTMLTitle(title), html.h1(title) ) // Render it to the DOM render(app, document.body) // Update the title title.value = 'New page title' ``` #### Router Client-side routing with `RootRouter` and `ChildRouter`: ```typescript import { html, render, Provide, Use } from '@tempots/dom' import { RootRouter, ChildRouter, Location, NavigationService } from '@tempots/ui' // Define routes - handlers receive a Signal const app = Provide(Location, {}, () => RootRouter({ '/': () => html.div('Home page'), '/about': () => html.div('About page'), '/users/:id': (info) => html.div('User ID: ', info.$.params.$.id), '/admin/*': () => AdminRoutes(), '*': () => html.div('404 - Not found') }) ) // Nested routes with ChildRouter const AdminRoutes = () => ChildRouter({ '/users': () => html.div('Admin Users'), '/settings': () => html.div('Admin Settings'), '*': () => html.div('Admin 404') }) // Render it to the DOM render(app, document.body) // Navigate programmatically using NavigationService NavigationService.navigate('/about') ``` #### Query Handle async data loading with loading/error states: ```typescript import { html, prop, render } from '@tempots/dom' import { Query } from '@tempots/ui' // Create a query that loads data from an API const userId = prop(1) const userQueryView = Query({ request: userId, load: async ({ request, abortSignal }) => { const response = await fetch(`https://api.example.com/user/${request}`, { signal: abortSignal }) if (!response.ok) throw new Error('Failed to load user') return response.json() }, convertError: error => error instanceof Error ? error.message : String(error), pending: ({ previous, reload }) => html.div('Loading...'), failure: ({ error, reload }) => html.div( error.map(message => `Error: ${message}`), html.button(on.click(reload), 'Retry') ), success: ({ value, reload }) => html.div( value.map(u => `Hello, ${u.name}!`), html.button(on.click(reload), 'Refresh') ), }) // Render it to the DOM render(userQueryView, document.body) // Trigger a reload by changing the request value userId.value = 2 ``` ## Available Components The library includes the following components and utilities: ### Input & Focus - `AutoFocus` - Automatically focus an element - `AutoSelect` - Automatically select text in an input - `SelectOnFocus` - Select all text when an input is focused ### Viewport & Layout - `InViewport` - Detect when an element is in the viewport - `WhenInViewport` - Conditional rendering based on viewport visibility - `WindowSize` - Track window dimensions - `ElementRect` - Track element size and position - `PopOver` - Create popup/popover elements - `HiddenWhenEmpty` - Hide an element when its content is empty ### Routing - `RootRouter` - Root-level client-side routing - `ChildRouter` - Nested routing for sub-routes - `Location` - Provider for reactive location state - `NavigationService` - Programmatic navigation utilities - `Anchor` - Navigation-aware anchor element ### Async Operations - `Query` - Async data loading with loading/error states - `Mutation` - Handle async mutations (POST/PUT operations) - `AsyncResultView` - Display async operation results - `ResultView` - Display success/failure results ### Events & Interaction - `OnClickOutside` - Detect clicks outside an element - `OnKeyPressed` - Handle keyboard events with modifier support - `OnEnterKey` - Handle Enter key press - `OnEscapeKey` - Handle Escape key press ### Utilities - `HTMLTitle` - Set the document title - `Appearance` - Detect and react to light/dark mode - `classes` - Conditional CSS class binding - `Ticker` / `ticker` - Counter/timer signal utilities - `makeRelativeTime` - Human-readable relative time formatting ## Next Steps - [Learn more about render](#render) - Check out the [demos](https://tempo-ts.com/demo/counter.html) to see these components in action --- # SSR & Headless Rendering Tempo provides comprehensive support for server-side rendering (SSR), static site generation (SSG), and client-side hydration through dedicated packages: | Package | Purpose | |---------|---------| | `@tempots/server` | Server-side rendering to strings and streams | | `@tempots/client` | Client-side hydration and islands architecture | | `@tempots/vite` | Vite plugin for SSG with automatic route discovery | ## Why SSR/SSG? - **SEO optimization** - Pre-render pages for search engine crawlers - **Performance** - Send pre-rendered HTML for faster initial page loads - **Static hosting** - Deploy to CDNs without a server - **Progressive enhancement** - Pages work before JavaScript loads ## @tempots/server The server package provides functions to render Tempo components to HTML strings or streams. ### Installation```bash npm install @tempots/server ``` ### renderToString Renders a component to an HTML string: ```typescript import { renderToString } from '@tempots/server' import { html } from '@tempots/dom' const App = () => html.div( html.h1('Hello, World!'), html.p('Rendered on the server.') ) const htmlString = await renderToString(App(), { url: 'https://example.com/page', generatePlaceholders: true, // Enable hydration markers }) ``` ### renderToStream Renders to a Node.js Readable stream for streaming SSR: ```typescript import { renderToStream } from '@tempots/server' app.get('/', (req, res) => { const stream = renderToStream(App(), { url: req.url, onShellReady: () => res.write(''), onAllReady: () => res.end(), }) stream.pipe(res) }) ``` ### createRenderer High-level convenience function for SSR entry points: ```typescript // entry-server.ts import { createRenderer } from '@tempots/server' import { App } from './App' export const { render, renderStream } = createRenderer( (options) => App(options), { hydrate: true, getData: async (url) => { // Fetch data for this URL return { user: await fetchUser() } } } ) ``` ## @tempots/client The client package provides hydration and islands architecture support. ### Installation ```bash npm install @tempots/client ``` ### hydrate Hydrates server-rendered HTML with client-side interactivity: ```typescript import { hydrate } from '@tempots/client' import { App } from './App' // Server-rendered HTML is already in the DOM const cleanup = hydrate(App(), document.getElementById('app')!) ``` ### startClient High-level client initialization with islands support: ```typescript import { startClient } from '@tempots/client' import { App } from './App' import { Counter, TodoList } from './islands' startClient({ app: () => App(), islands: { Counter, TodoList }, container: '#app', debug: true, }) ``` ### Islands Architecture Islands allow you to hydrate only interactive components while keeping the rest static: ```typescript // Define an island component import { html, prop, on } from '@tempots/dom' export const Counter = (options: unknown) => { const { initial = 0 } = (options ?? {}) as { initial?: number } const count = prop(initial) return html.div( html.button(on.click(() => count.update(n => n - 1)), '-'), html.span(count.map(String)), html.button(on.click(() => count.update(n => n + 1)), '+'), ) } // Mark islands in your SSR template import { islandMarker, attr } from '@tempots/dom' const CounterIsland = (initial: number) => html.div( ...islandMarker('Counter', { initial }, 'visible').map( ({ name, value }) => attr[name](value) ), // Static placeholder content html.span(String(initial)) ) ``` Hydration strategies: - `"immediate"` - Hydrate as soon as possible - `"idle"` - Hydrate when browser is idle - `"visible"` - Hydrate when scrolled into view - `{ media: "(min-width: 768px)" }` - Hydrate when media query matches ## @tempots/vite The Vite plugin provides SSG with automatic route discovery. ### Installation ```bash npm install @tempots/vite ``` ### Configuration ```typescript // vite.config.ts import { defineConfig } from 'vite' import { tempo } from '@tempots/vite' export default defineConfig({ plugins: [ tempo({ mode: 'ssg', // or 'ssr', 'islands', 'hybrid' routes: 'crawl', // Auto-discover routes (default) seedRoutes: ['/'], // Starting points for crawling ssrEntry: 'src/entry-server.ts', container: '#app', hydrate: true, }) ] }) ``` ### Route Discovery By default, the plugin crawls your site starting from `/` and discovers all internal links: ```typescript // Explicit routes tempo({ routes: ['/', '/about', '/contact'], }) // Dynamic routes tempo({ routes: async () => { const posts = await fetchBlogPosts() return ['/', ...posts.map(p => `/blog/${p.slug}`)] }, }) // Crawl with multiple entry points tempo({ routes: 'crawl', seedRoutes: ['/', '/docs', '/api'], }) ``` ### Project Structure ``` my-app/ ├── src/ │ ├── App.ts # Main app component │ ├── entry-client.ts # Client entry (hydration) │ └── entry-server.ts # Server entry (rendering) ├── index.html # HTML template └── vite.config.ts # Vite configuration ``` ### Entry Files **entry-server.ts:** ```typescript import { renderToString } from '@tempots/server' import { App } from './App' export async function render(url: string): Promise { return renderToString(App(), { url, generatePlaceholders: true, }) } ``` **entry-client.ts:** ```typescript import { render } from '@tempots/dom' import { App } from './App' render(App(), document.getElementById('app')!) ``` ## Low-Level API: runHeadless For advanced use cases, you can use the low-level headless rendering API: ```typescript import { runHeadless, html } from '@tempots/dom' const App = () => html.div( html.h1('Hello, World!'), html.p('Headless rendered') ) const { root, clear, currentURL } = runHeadless(() => App(), { startUrl: 'https://example.com', selector: 'body', }) // Get HTML output const htmlOutput = root.contentToHTML(true) // true = include placeholders // Clean up clear() ``` ## Context-Aware Rendering Conditionally render based on environment: ```typescript import { html, WithBrowserCtx, WithHeadlessCtx } from '@tempots/dom' const App = () => html.div( // Only in browser WithBrowserCtx(() => html.div('Window width: ', window.innerWidth.toString()) ), // Only in headless/SSR WithHeadlessCtx(() => html.div('Server-rendered placeholder') ), // Both environments html.p('Universal content') ) ``` ## Next Steps - [Quick Start](#quick-start) - Get started with Tempo - [Renderables](#renderables) - Learn about the building blocks - [Signals](#signals) - Reactive state management - [Examples](#examples-patterns) - Common patterns and best practices --- # Examples & Patterns This page provides practical examples and patterns for common scenarios when building applications with Tempo. ## Form Handling ### Complete Form with Validation```typescript import { html, prop, computedOf, render, Ensure, attr, on, emitValue } from '@tempots/dom' import type { Prop, Signal } from '@tempots/dom' import { Validation } from '@tempots/std' // Validation functions const validateEmail = (value: string): Validation => { if (!value) return Validation.valid // Don't show error when empty if (!value.includes('@')) return Validation.invalid('Invalid email format') return Validation.valid } const validatePassword = (value: string): Validation => { if (!value) return Validation.valid // Don't show error when empty if (value.length < 8) return Validation.invalid('At least 8 characters') if (!/[A-Z]/.test(value)) return Validation.invalid('Needs uppercase letter') if (!/[0-9]/.test(value)) return Validation.invalid('Needs a number') return Validation.valid } // Form component with real-time validation const RegistrationForm = () => { const name = prop('') const email = prop('') const password = prop('') // Real-time validation errors (derived from field values) const emailError = email.map(v => { const result = validateEmail(v) return Validation.isInvalid(result) ? result.error : null }) const passwordError = password.map(v => { const result = validatePassword(v) return Validation.isInvalid(result) ? result.error : null }) // Check if form can be submitted const canSubmit = computedOf(name, email, password)((n, e, p) => n.trim().length > 0 && Validation.isValid(validateEmail(e)) && Validation.isValid(validatePassword(p)) ) const handleSubmit = () => { console.log('Form submitted:', { name: name.value, email: email.value }) } return html.form( on.submit(e => { e.preventDefault(); handleSubmit() }), FormField('Name', name), FormField('Email', email, emailError, 'email'), FormField('Password', password, passwordError, 'password'), html.button( attr.type('submit'), attr.disabled(canSubmit.map(v => !v)), 'Register' ) ) } // Reusable form field component const FormField = ( label: string, value: Prop, error?: Signal, type: string = 'text' ) => html.div( attr.class('form-field'), html.label(label), html.input( attr.type(type), attr.value(value), on.input(emitValue(value.set)), error ? attr.class(error.map(e => e ? 'error' : '')) : null ), error ? Ensure(error, err => html.span(attr.class('error-message'), err)) : null ) ``` ## Data Fetching with Query ### Basic Query Usage ```typescript import { html, prop, render, attr, on, emitValue, Ensure } from '@tempots/dom' import { Query } from '@tempots/ui' interface User { id: number name: string email: string } const UserProfile = () => { const userId = prop(1) return html.div( // User selector html.select( on.change(emitValue(v => userId.value = parseInt(v))), html.option(attr.value('1'), 'User 1'), html.option(attr.value('2'), 'User 2'), html.option(attr.value('3'), 'User 3') ), // Query with loading/error states Query({ request: userId, load: async ({ request, abortSignal }) => { const res = await fetch(`/api/users/${request}`, { signal: abortSignal }) if (!res.ok) throw new Error('Failed to load user') return res.json() }, convertError: e => e instanceof Error ? e.message : 'Unknown error', pending: ({ previous }) => html.div( 'Loading...', // Show previous data while loading Ensure(previous, user => html.div( attr.class('stale'), 'Previous: ', user.$.name )) ), failure: ({ error, reload }) => html.div( html.p('Error: ', error), html.button(on.click(reload), 'Retry') ), success: ({ value, reload }) => html.div( html.h2(value.$.name), html.p(value.$.email), html.button(on.click(reload), 'Refresh') ) }) ) } ``` ### Mutation for POST/PUT Operations ```typescript import { html, prop, attr, on, emitValue } from '@tempots/dom' import { Mutation } from '@tempots/ui' interface User { id: number name: string email: string } const CreateUserForm = () => { const name = prop('') const email = prop('') return html.div( Mutation<{ name: string; email: string }, User, string>({ mutate: async ({ request, abortSignal }) => { const res = await fetch('/api/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(request), signal: abortSignal }) if (!res.ok) throw new Error('Failed to create user') return res.json() }, convertError: e => e instanceof Error ? e.message : 'Unknown error', idle: ({ trigger }) => html.form( on.submit(e => { e.preventDefault() trigger({ name: name.value, email: email.value }) }), html.input( attr.placeholder('Name'), attr.value(name), on.input(emitValue(name.set)) ), html.input( attr.type('email'), attr.placeholder('Email'), attr.value(email), on.input(emitValue(email.set)) ), html.button(attr.type('submit'), 'Create User') ), pending: () => html.div('Creating user...'), failure: ({ error, reset }) => html.div( html.p('Error: ', error), html.button(on.click(reset), 'Try Again') ), success: ({ value, reset }) => html.div( html.p('User created: ', value.$.name), html.button(on.click(reset), 'Create Another') ) }) ) } ``` ## Router with Authentication ### Protected Routes ```typescript import { html, prop, Provide, Use, makeProviderMark, When, Fragment, attr, on, emitValue } from '@tempots/dom' import type { Signal, TNode } from '@tempots/dom' import { RootRouter, ChildRouter, Location, NavigationService, Anchor } from '@tempots/ui' interface User { id: number name: string email: string } // Auth provider const Auth = { mark: makeProviderMark>('Auth'), create: () => { const user = prop(null) return { value: user, dispose: user.dispose } } } // Protected route wrapper const ProtectedRoute = (content: () => TNode) => Use(Auth, user => When( user.map(u => u !== null), content, () => { // Redirect to login NavigationService.navigate('/login') return html.div('Redirecting to login...') } ) ) // App with routing const App = () => Provide(Auth, {}, () => Provide(Location, {}, () => html.div( Navigation(), RootRouter({ '/': () => html.div('Home - Public'), '/login': () => LoginPage(), '/dashboard': () => ProtectedRoute(() => Dashboard()), '/dashboard/*': () => ProtectedRoute(() => DashboardRoutes()), '*': () => html.div('404 - Not Found') }) ) ) ) // Nested dashboard routes const DashboardRoutes = () => ChildRouter({ '/profile': () => html.div('Profile Page'), '/settings': () => html.div('Settings Page'), '*': () => html.div('Dashboard Home') }) // Navigation component const Navigation = () => Use(Auth, user => html.nav( Anchor('/', 'Home'), When( user.map(u => u === null), () => Anchor('/login', 'Login'), () => Fragment( Anchor('/dashboard', 'Dashboard'), html.button( on.click(() => user.value = null), 'Logout' ) ) ) ) ) // Login page const LoginPage = () => Use(Auth, user => { const email = prop('') const password = prop('') const handleLogin = async () => { // Simulate login user.value = { id: 1, name: 'John', email: email.value } NavigationService.navigate('/dashboard') } return html.form( on.submit(e => { e.preventDefault(); handleLogin() }), html.h1('Login'), html.input( attr.type('email'), attr.placeholder('Email'), on.input(emitValue(email.set)) ), html.input( attr.type('password'), attr.placeholder('Password'), on.input(emitValue(password.set)) ), html.button(attr.type('submit'), 'Login') ) }) ``` ## Keyboard Shortcuts ### Global Keyboard Handler ```typescript import { html, prop, attr, on, emitValue, When } from '@tempots/dom' import { OnKeyPressed, OnEnterKey, OnEscapeKey } from '@tempots/ui' const KeyboardShortcutsDemo = () => { const isModalOpen = prop(false) const searchQuery = prop('') return html.div( // Global keyboard shortcuts OnKeyPressed({ key: 'k', ctrl: true, handler: () => { // Ctrl+K to open search document.querySelector('#search')?.focus() } }), OnKeyPressed({ key: 's', ctrl: true, handler: (e) => { e.preventDefault() console.log('Save triggered!') } }), // Search input with keyboard handling html.div( html.input( attr.id('search'), attr.placeholder('Search... (Ctrl+K)'), attr.value(searchQuery), on.input(emitValue(searchQuery.set)), OnEnterKey(() => { console.log('Searching for:', searchQuery.value) }), OnEscapeKey(() => { searchQuery.value = '' document.querySelector('#search')?.blur() }) ) ), // Modal with escape to close html.button( on.click(() => isModalOpen.value = true), 'Open Modal (Esc to close)' ), When(isModalOpen, () => html.div( attr.class('modal'), OnEscapeKey(() => isModalOpen.value = false), html.div( attr.class('modal-content'), html.h2('Modal Title'), html.p('Press Escape to close this modal'), html.button( on.click(() => isModalOpen.value = false), 'Close' ) ) ) ) ) } ``` ### Input with Key Modifiers ```typescript const TextEditor = () => { const text = prop('') const history = prop([]) const saveToHistory = () => { history.update(h => [...h, text.value]) } const undo = () => { history.update(h => { if (h.length === 0) return h const prev = h[h.length - 1] text.value = prev ?? '' return h.slice(0, -1) }) } return html.div( html.textarea( attr.value(text), on.input(emitValue(text.set)), // Ctrl+S to save OnKeyPressed({ key: 's', ctrl: true, handler: e => { e.preventDefault() saveToHistory() console.log('Saved!') } }), // Ctrl+Z to undo OnKeyPressed({ key: 'z', ctrl: true, handler: e => { e.preventDefault() undo() } }) ), html.div( 'History: ', history.map(h => h.length.toString()), ' saves' ) ) } ``` ## Click Outside Detection ```typescript import { html, prop, attr, on, When } from '@tempots/dom' import { OnClickOutside } from '@tempots/ui' const Dropdown = () => { const isOpen = prop(false) return html.div( attr.class('dropdown'), html.button( on.click(() => isOpen.update(v => !v)), 'Toggle Dropdown' ), When(isOpen, () => html.div( attr.class('dropdown-menu'), OnClickOutside(() => isOpen.value = false), html.ul( html.li('Option 1'), html.li('Option 2'), html.li('Option 3') ) ) ) ) } ``` ## Viewport Detection ```typescript import { html, attr, When } from '@tempots/dom' import { InViewport, WhenInViewport } from '@tempots/ui' const LazyLoadedSection = () => html.div( // Load content when element comes into view InViewport( { mode: 'partial', once: true }, isVisible => When(isVisible, () => html.div( attr.class('loaded'), 'Content loaded when scrolled into view!' ), () => html.div( attr.class('placeholder'), 'Scroll to load...' ) ) ) ) // Or use the convenience wrapper const AnimatedOnScroll = () => html.div( WhenInViewport( { mode: 'full' }, () => html.div( attr.class('animate-in'), 'This animates when fully visible' ) ) ) ``` ## Next Steps - [Learn about Signals](#signals) - [Explore UI Components](#ui-components) - [Server-Side Rendering](#ssr-headless-rendering) - [Troubleshooting](#troubleshooting-faq) --- # Render Rendering is the final act of applying `Renderable`s to the DOM. When defining renderables, nothing in the DOM is changed or updated, not until those renderables are applied using either `render()` or `renderWithContext()`. Both functions return a `cancel` function that can be used to undo the modifications described in the applied renderables. ## render() A rendering function that takes two mandatory arguments, a `Renderable` that describes the change to apply to the DOM and a parent node (either as an instance or as a CSS selector) where to apply those changes. Optionally you can pass an object with the following options: * a `document` instance to be used during the rendering. This is only necessary in special context, like rendering in a non-browser context when using a string selector for `parent`. * the `clear` option indicates if the rendering operation should also remove the contents that were potentially generated by the SSR component. * the `disposeWithParent` option indicates if the rendering operation should be automatically disposed when the parent node is removed from the DOM.```ts function render( node: Renderable, parent: Node | string, { doc, clear, disposeWithParent = true }: { doc?: Document clear?: boolean disposeWithParent?: boolean } = {} ): () => void ``` ## renderWithContext() `renderWithContext()` is a more atomic operation that requires an already instantiated `DOMContext`. Like `render` it returns a `cancel` function. ```ts function renderWithContext(node: Renderable, ctx: DOMContext): () => void ``` ## Next Steps Check out these resources: - [Explore Examples & Best Practices](#examples-patterns) - [Troubleshooting & FAQ](#troubleshooting-faq) - [Standard Library](#standard-library) - [UI Components](#ui-components) Or explore the API documentation for the Tempo libraries: - [@tempots/dom](#tempotsdom) - [@tempots/std](#tempotsstd) - [@tempots/ui](#tempotsui) --- # Troubleshooting & FAQ This page addresses common issues and questions that may arise when working with Tempo. ## Common Mistakes ### Renderables should not be payloads to signals The following is an anti-pattern.```typescript function Counter() { const p = prop(1); // DON'T! return p.map((value) => html.div(String(value))); } ``` This is how it should work: ```typescript function Counter() { const p = prop(1); // DO! return html.div(p.map(String)); } ``` In the rare case where a signal should really contain a Renderable, the `MapSignal` component is the way to go. The reason to avoid it is that the entire sub-tree DOM is re-rendered when the `prop` changes which is potentially inefficient. ```typescript function Counter() { const p = prop(1); // Correct but inefficient return MapSignal(p, (value) => html.div(String(value))); } ``` ## Frequently Asked Questions ### How does Tempo compare to React, Vue, or Angular? Tempo is a lightweight UI framework that takes a different approach: - **No Virtual DOM**: Tempo directly updates the DOM, which can be more efficient for many use cases. - **Fully Typed**: Built from the ground up with TypeScript for excellent type safety. - **Zero Dependencies**: Tempo has no external dependencies, making it lightweight. - **Functional Approach**: Uses plain functions rather than classes or JSX. - **Fine-Grained Reactivity**: Uses signals for precise updates rather than re-rendering components. ### Can I use Tempo with existing libraries? Yes! Tempo can be integrated with most JavaScript libraries. Since Tempo directly manipulates the DOM, you can use it alongside other libraries that do the same. You can: 1. Use the `WithElement` renderable to get a reference to a DOM element 2. Initialize third-party libraries with that element 3. Clean up resources with `OnDispose` ```typescript import { html, WithElement, OnDispose } from '@tempots/dom' import SomeThirdPartyLib from 'some-third-party-lib' const ThirdPartyComponent = () => html.div( WithElement(element => { // Initialize the third-party library const instance = new SomeThirdPartyLib(element) // Return a cleanup function return OnDispose(() => { instance.destroy() }) }) ) ``` The other way around is also possible. You can use Tempo to create renderables that can be used in other libraries. Just get access to a parent node and use `render` to render Tempo content. The function returned by `render` can be used to dispose of the rendered content. ```ts import { render } from '@tempots/dom' const cancel = render( html.div('Hello World'), document.getElementById('root') ) // later cancel() ``` ### Does Tempo support Server-Side Rendering (SSR)? Tempo has experimental support for server-side rendering. The `DOMContext` includes an `isFirstLevel` property that can be used to mark nodes for server-side rendering and hydration. However, this feature is still under development. ## Common Issues ### Signals not updating the UI If your signals are changing but the UI isn't updating, check: 1. **Signal Dependencies**: For computed signals, make sure you've included all dependencies in the dependency array. ```typescript // Incorrect - missing dependency // This still works but it only updates on variations of signal1 const computed = computed(() => signal1.value + signal2.value, [signal1]) // Correct const computed = computed(() => signal1.value + signal2.value, [signal1, signal2]) ``` 2. **Signal Equality**: Signals use reference equality by default. For objects, you might need to provide a custom equality function. ```typescript // Custom equality function for objects const userSignal = signal( { name: 'John', age: 30 }, (a, b) => a.name === b.name && a.age === b.age ) ``` 3. **Immutable Updates**: When updating objects or arrays in props, make sure to create new references. ```typescript // Incorrect - mutating the array const items = prop([1, 2, 3]) items.value.push(4) // UI won't update! // Correct - creating a new array items.value = [...items.value, 4] ``` ### Memory Leaks If your application is experiencing memory leaks, check: 1. **Cleanup Functions**: Make sure you're properly cleaning up resources with `OnDispose`. ```typescript WithElement(element => { const interval = setInterval(() => { // Do something }, 1000) return OnDispose(() => { clearInterval(interval) }) }) ``` 2. **Signal Listeners**: When working outside the renderable context, if you manually add listeners to signals, make sure to remove them. ```typescript const clear = signal.on(value => { // Do something with value }) // Later, when no longer needed clear() ``` If a Signal is disposed, it will automatically remove all listeners and you don't need to call `clear`. Within renderables, the scope is automatically tracked and signals are automatically disposed. The exception to that is if you define a signal in an async context where the scope cannot be automatically tracked. In this case you will have to manually dispose the signal. 3. **Event Listeners**: If you manually add DOM event listeners, make sure to remove them. ```typescript WithElement(element => { const handler = () => console.log('Clicked') element.addEventListener('click', handler) return OnDispose(() => { element.removeEventListener('click', handler) }) }) ``` ### TypeScript Errors If you're encountering TypeScript errors: 1. **Check TypeScript Version**: Tempo requires TypeScript 4.7 or later. 2. **Import Types**: Make sure you're importing types correctly. ```typescript // Import types import { Renderable, Signal, Prop } from '@tempots/dom' ``` 3. **Generic Type Parameters**: Make sure you're providing the correct type parameters. ```typescript // Specify the type parameter const userSignal = signal(null) ``` ## Next Steps - [Learn more about Signals](#signals) - [Explore Examples & Best Practices](#examples-patterns) - [Check out the Demos](https://tempo-ts.com/demo/hnpwa.html) --- # @tempots/dom Tempo DOM is a lightweight UI Framework for building web applications. It has no dependencies and it is built with [TypeScript](https://www.typescriptlang.org/). To install use:```bash # npm npm install @tempots/dom # yarn yarn add @tempots/dom ``` For more information, see the [Tempo documentation](/). --- # @tempots/server Tempo Server provides server-side rendering (SSR) utilities for Tempo applications. Render your Tempo components to HTML strings or streams for faster initial page loads and better SEO. ## Installation```bash npm install @tempots/server ``` ## Features - **renderToString** - Render components to HTML strings - **renderToStream** - Stream rendered HTML for faster time-to-first-byte - **createRenderer** - High-level convenience function for SSR entry points - Hydration placeholder generation for client-side rehydration ## Quick Example ```typescript import { renderToString } from '@tempots/server' import { html } from '@tempots/dom' const App = () => html.div( html.h1('Hello, SSR!'), html.p('Rendered on the server.') ) const htmlString = await renderToString(App(), { url: 'https://example.com/page', generatePlaceholders: true, }) ``` For complete documentation, see [SSR & Headless Rendering](#ssr-headless-rendering). --- # @tempots/client Tempo Client provides client-side hydration utilities for Tempo SSR applications. Hydrate server-rendered HTML to make it interactive, or use the islands architecture to selectively hydrate only interactive components. ## Installation```bash npm install @tempots/client ``` ## Features - **hydrate** - Hydrate server-rendered HTML with client-side interactivity - **startClient** - High-level client initialization with islands support - **Islands Architecture** - Hydrate only interactive components while keeping the rest static - Multiple hydration strategies: immediate, idle, visible, and media query-based ## Quick Example ```typescript import { startClient } from '@tempots/client' import { App } from './App' import { Counter, TodoList } from './islands' startClient({ app: () => App(), islands: { Counter, TodoList }, container: '#app', }) ``` ## Islands Architecture Islands allow selective hydration of interactive components: ```typescript import { islandMarker, attr, html } from '@tempots/dom' const CounterIsland = (initial: number) => html.div( ...islandMarker('Counter', { initial }, 'visible').map( ({ name, value }) => attr[name](value) ), html.span(String(initial)) // Static placeholder ) ``` Hydration strategies: - `"immediate"` - Hydrate as soon as possible - `"idle"` - Hydrate when browser is idle - `"visible"` - Hydrate when scrolled into view - `{ media: "(min-width: 768px)" }` - Hydrate when media query matches For complete documentation, see [SSR & Headless Rendering](#ssr-headless-rendering). --- # Tempo Standard Library (@tempots/std) A comprehensive standard library for TypeScript that provides utility functions and types commonly used in web applications. This package serves as a natural complement to the Tempo libraries but can be used independently in any TypeScript project. ## Overview The Tempo Standard Library fills the gaps in JavaScript's standard library with a collection of well-tested, type-safe utility functions. It follows functional programming principles and provides consistent APIs across all modules. ## Key Features - **Zero Dependencies**: Lightweight with no external dependencies - **Type Safe**: Full TypeScript support with comprehensive type definitions - **Functional**: Immutable operations and functional programming patterns - **Modular**: Import only what you need for optimal bundle size - **Well Tested**: Comprehensive test coverage for reliability - **Consistent APIs**: Uniform naming and parameter conventions ## Module Categories ### Data Manipulation - **array**: Array operations (map, filter, reduce, unique, etc.) - **object**: Object manipulation and transformation utilities - **string**: String processing and formatting functions ### Async Operations - **promise**: Promise utilities and helpers - **deferred**: Promise deferral and cancellation - **async-result**: Asynchronous result handling with error management ### Type Safety - **result**: Result type for error handling without exceptions - **validation**: Data validation and type checking utilities - **domain**: Common domain types and type guards ### Utilities - **function**: Function composition and manipulation - **timer**: Timing utilities and delays - **equal**: Deep equality comparison functions - **json**: JSON parsing and serialization helpers ### Numeric Operations - **number**: Number utilities and mathematical operations - **bigint**: BigInt manipulation functions ## Design Principles ### Functional Programming All functions are pure and side-effect free where possible:```typescript // Pure function - doesn't modify input const doubled = mapArray([1, 2, 3], x => x * 2) // [2, 4, 6] // Immutable operations const filtered = filterArray(numbers, x => x > 5) ``` ### Type Safety Comprehensive TypeScript support with generic types: ```typescript // Type-safe array operations const strings: string[] = ['a', 'b', 'c'] const lengths: number[] = mapArray(strings, s => s.length) // Result type for error handling const result: Result = parseNumber('42') ``` ### Consistent APIs Uniform parameter ordering and naming conventions: ```typescript // Data first, function second pattern mapArray(array, fn) filterArray(array, predicate) foldLeftArray(array, reducer, initial) ``` ## Usage Patterns ### Error Handling with Result Type ```typescript import { Result, success, failure } from '@tempots/std/result' function divide(a: number, b: number): Result { if (b === 0) { return failure('Division by zero') } return success(a / b) } const result = divide(10, 2) result.match({ success: value => console.log(`Result: ${value}`), failure: error => console.error(`Error: ${error}`) }) ``` ### Array Processing ```typescript import { mapArray, filterArray, foldLeftArray } from '@tempots/std/array' const numbers = [1, 2, 3, 4, 5] const evenSquares = mapArray( filterArray(numbers, n => n % 2 === 0), n => n * n ) // [4, 16] const sum = foldLeftArray(numbers, (acc, n) => acc + n, 0) // 15 ``` ### Async Operations ```typescript import { deferred } from '@tempots/std/deferred' import { delayed } from '@tempots/std/timer' // Create a deferred promise const { promise, resolve, reject } = deferred() // Delay execution const cancel = delayed(() => resolve('Done!'), 1000) // Use the promise promise.then(value => console.log(value)) ``` ## Integration with Tempo While @tempots/std can be used independently, it integrates seamlessly with Tempo: ```typescript import { prop, computed } from '@tempots/dom' import { mapArray, filterArray } from '@tempots/std' const items = prop([1, 2, 3, 4, 5]) const evenItems = computed(() => filterArray(items.value, n => n % 2 === 0) ) const doubled = computed(() => mapArray(evenItems.value, n => n * 2) ) ``` ## Performance Considerations - **Tree Shaking**: Import specific functions to minimize bundle size - **Immutability**: Functions create new objects rather than mutating inputs - **Lazy Evaluation**: Some operations support lazy evaluation patterns - **Memory Efficiency**: Optimized algorithms for common operations ## Best Practices 1. **Import Specifically**: Import only the functions you need ```typescript import { mapArray } from '@tempots/std/array' // Instead of: import { mapArray } from '@tempots/std' ``` 2. **Use Result Types**: Prefer Result types over throwing exceptions ```typescript // Good function parseNumber(str: string): Result // Avoid function parseNumber(str: string): number // throws on error ``` 3. **Compose Functions**: Build complex operations from simple functions ```typescript const processData = (data: string[]) => mapArray( filterArray(data, s => s.length > 0), s => s.toUpperCase() ) ``` ## Contributing See the main [CONTRIBUTING.md](../../CONTRIBUTING.md) for development setup and guidelines. ## Documentation For detailed API documentation, see the [Tempo Documentation Site](https://tempo-ts.com/library/tempots-std.html). --- # @tempots/vite Tempo Vite is a Vite plugin for building Tempo applications with SSR, SSG, or islands architecture. It provides automatic route discovery, static site generation, and seamless integration with Vite's build system. ## Installation```bash npm install @tempots/vite ``` ## Features - **SSG Mode** - Static site generation with pre-rendered HTML - **SSR Mode** - Server-side rendering for dynamic content - **Islands Mode** - Selective hydration of interactive components - **Route Crawling** - Automatic route discovery by crawling internal links - Seamless Vite integration ## Quick Example ```typescript // vite.config.ts import { defineConfig } from 'vite' import { tempo } from '@tempots/vite' export default defineConfig({ plugins: [ tempo({ mode: 'ssg', ssrEntry: 'src/entry-server.ts', routes: 'crawl', // Auto-discover routes hydrate: true, }) ] }) ``` ## Route Discovery ```typescript // Explicit routes tempo({ routes: ['/', '/about', '/contact'] }) // Dynamic routes tempo({ routes: async () => { const posts = await fetchBlogPosts() return ['/', ...posts.map(p => `/blog/${p.slug}`)] } }) // Crawl with seed routes (default) tempo({ routes: 'crawl', seedRoutes: ['/', '/docs'], }) ``` For complete documentation, see [SSR & Headless Rendering](#ssr-headless-rendering). --- # Tempo UI (@tempots/ui) A collection of reusable UI components and renderables built on top of @tempots/dom to accelerate development with Tempo. This package provides higher-level abstractions for common UI patterns and components. ## Overview Tempo UI bridges the gap between the low-level DOM manipulation of @tempots/dom and the high-level components needed for real applications. It provides a curated set of components, utilities, and patterns that solve common UI development challenges. ## Key Features - **Component Library**: Pre-built components for common UI patterns - **Routing System**: Client-side routing with URL synchronization - **Query Management**: Async data loading with loading/error states - **Form Utilities**: Enhanced form controls and input handling - **Accessibility**: Built-in accessibility features and ARIA support - **Performance**: Optimized components with minimal overhead - **Type Safety**: Full TypeScript support with comprehensive types ## Component Categories ### Input Enhancement - **AutoFocus**: Automatically focus elements when rendered - **AutoSelect**: Automatically select text in inputs - **SelectOnFocus**: Select text when input receives focus ### Layout & Visibility - **InViewport**: Detect when elements enter/exit the viewport - **HiddenWhenEmpty**: Hide elements when they have no content - **PopOver**: Create popup and popover elements - **Size**: Responsive size utilities ### Navigation & Routing - **Router**: Client-side routing system - **Location**: Navigation and location utilities - **Anchor**: Enhanced anchor link handling ### Data Loading - **Query**: Async data loading with loading/error states - **AsyncResultView**: Display async operation results - **ResultView**: Display success/failure results ### Utilities - **HTMLTitle**: Dynamic document title management - **Appearance**: Theme and appearance utilities - **Ticker**: Time-based updates and animations ## Design Philosophy ### Composition Over Configuration Components are designed to be composed together rather than configured with many options:```typescript // Compose multiple behaviors html.input( AutoFocus(), AutoSelect(), SelectOnFocus(), attr.placeholder('Enter text...') ) ``` ### Minimal API Surface Each component has a focused, minimal API that does one thing well: ```typescript // Simple, focused APIs const AutoFocus = (delay: number = 10): Renderable const InViewport = (options: IntersectionObserverInit, render: (isVisible: Signal) => TNode): Renderable ``` ### Framework Integration Components integrate seamlessly with Tempo's reactive system: ```typescript // Reactive integration const isVisible = prop(false) InViewport({}, visible => { isVisible.set(visible.value) return html.div('Content is visible!') }) ``` ## Routing System ### Basic Routing ```typescript import { Router, Location } from '@tempots/ui' const AppRouter = Router({ '/': () => html.div('Home Page'), '/about': () => html.div('About Page'), '/users/:id': (info) => { const userId = info.$.params.$.id return html.div('User Profile: ', userId) }, '*': () => html.div('404 - Not Found') }) render(AppRouter, document.body) ``` ### Programmatic Navigation ```typescript // Navigate to different routes Location.navigate('/about') Location.navigate('/users/123') // Access current location Use(Location, location => { return html.div('Current path: ', location.$.pathname) }) ``` ### Route Parameters ```typescript // Extract route parameters '/users/:id/posts/:postId': (info) => { const userId = info.$.params.$.id const postId = info.$.params.$.postId return UserPost({ userId, postId }) } ``` ## Query Management ### Basic Query Loading ```typescript import { Query } from '@tempots/ui' const userQuery = Query({ load: () => fetch('/api/user').then(r => r.json()), loading: () => html.div('Loading user...'), error: (err) => html.div('Error: ', err.message), success: (user) => html.div( html.h2(user.name), html.p(user.email) ) }) ``` ### Advanced Query Patterns ```typescript // Query with dependencies const userPosts = Query({ load: async () => { const user = await fetchUser() const posts = await fetchUserPosts(user.id) return { user, posts } }, loading: () => SkeletonLoader(), error: (err) => ErrorMessage({ error: err }), success: ({ user, posts }) => UserPostsList({ user, posts }) }) ``` ## Form Enhancement ### Input Focus Management ```typescript import { AutoFocus, AutoSelect, SelectOnFocus } from '@tempots/ui' function LoginForm() { const username = prop('') const password = prop('') return html.form( html.input( AutoFocus(), // Focus on render SelectOnFocus(), // Select text on focus attr.placeholder('Username'), attr.value(username), on.input(e => username.set(e.target.value)) ), html.input( attr.type('password'), attr.placeholder('Password'), attr.value(password), on.input(e => password.set(e.target.value)) ) ) } ``` ### Form Validation ```typescript // Combine with @tempots/std for validation import { Result, success, failure } from '@tempots/std' const validateEmail = (email: string): Result => { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ return emailRegex.test(email) ? success(email) : failure('Invalid email format') } const emailInput = prop('') const emailValidation = emailInput.map(validateEmail) ``` ## Viewport Detection ### Lazy Loading ```typescript import { InViewport } from '@tempots/ui' const LazyImage = ({ src, alt }: { src: string, alt: string }) => InViewport( { threshold: 0.1 }, isVisible => isVisible.value ? html.img(attr.src(src), attr.alt(alt)) : html.div(attr.class('placeholder'), 'Loading...') ) ``` ### Infinite Scrolling ```typescript const InfiniteList = ({ items, loadMore }: { items: Signal, loadMore: () => void }) => html.div( ForEach(items, item => ItemComponent(item)), InViewport( { threshold: 1.0 }, isVisible => { if (isVisible.value) loadMore() return html.div('Loading more...') } ) ) ``` ## Performance Considerations - **Lazy Loading**: Components only render when needed - **Event Cleanup**: Automatic cleanup of event listeners and observers - **Memory Management**: Proper disposal of resources and subscriptions - **Bundle Size**: Tree-shakeable components for optimal bundle size ## Integration Patterns ### With @tempots/dom ```typescript // Enhance basic DOM elements html.input( AutoFocus(), attr.value(signal), on.input(handler) ) ``` ### With @tempots/std ```typescript // Use std utilities for data processing import { mapArray, filterArray } from '@tempots/std' const processedItems = computed(() => mapArray( filterArray(items.value, item => item.visible), item => ({ ...item, processed: true }) ) ) ``` ## Best Practices 1. **Compose Components**: Build complex UI by composing simple components 2. **Use Signals**: Leverage reactive signals for dynamic behavior 3. **Handle Errors**: Always provide error states for async operations 4. **Accessibility**: Use semantic HTML and ARIA attributes 5. **Performance**: Use lazy loading and viewport detection for large lists ## Contributing See the main [CONTRIBUTING.md](../../CONTRIBUTING.md) for development setup and guidelines. ## Documentation For detailed API documentation, see the [Tempo Documentation Site](https://tempo-ts.com/library/tempots-ui.html). --- # tempots-dom api index [Home](#tempots-ui-api-index) ## tempots-dom: API Reference ## tempots-dom: Packages | Package | Description | | --- | --- | | [@tempots/dom](#dom) | | --- ## dom._isfragment: \_isFragment() function **Signature:**```typescript _isFragment: (node: Node) => node is DocumentFragment ```## dom._isfragment: Parameters | Parameter | Type | Description | | --- | --- | --- | | node | Node | | **Returns:** node is DocumentFragment --- ## dom.aria: aria variable An object that provides a convenient way to create mountable attributes for ARIA properties. The type of the value is inferred from the attribute name. **Signature:**```typescript aria: { activedescendant: (value: SplitNValue) => Renderable; atomic: (value: SplitNValue) => Renderable; autocomplete: (value: SplitNValue<"none" | "inline" | "list" | "both">) => Renderable; braillelabel: (value: SplitNValue) => Renderable; brailleroledescription: (value: SplitNValue) => Renderable; busy: (value: SplitNValue) => Renderable; checked: (value: SplitNValue) => Renderable; colcount: (value: SplitNValue) => Renderable; colindex: (value: SplitNValue) => Renderable; colindextext: (value: SplitNValue) => Renderable; colspan: (value: SplitNValue) => Renderable; controls: (value: SplitNValue) => Renderable; current: (value: SplitNValue) => Renderable; describedby: (value: SplitNValue) => Renderable; description: (value: SplitNValue) => Renderable; details: (value: SplitNValue) => Renderable; disabled: (value: SplitNValue) => Renderable; dropeffect: (value: SplitNValue<"none" | "copy" | "execute" | "link" | "move" | "popup">) => Renderable; errormessage: (value: SplitNValue) => Renderable; expanded: (value: SplitNValue) => Renderable; flowto: (value: SplitNValue) => Renderable; grabbed: (value: SplitNValue) => Renderable; haspopup: (value: SplitNValue) => Renderable; hidden: (value: SplitNValue) => Renderable; invalid: (value: SplitNValue) => Renderable; keyshortcuts: (value: SplitNValue) => Renderable; label: (value: SplitNValue) => Renderable; labelledby: (value: SplitNValue) => Renderable; level: (value: SplitNValue) => Renderable; live: (value: SplitNValue<"off" | "assertive" | "polite">) => Renderable; modal: (value: SplitNValue) => Renderable; multiline: (value: SplitNValue) => Renderable; multiselectable: (value: SplitNValue) => Renderable; orientation: (value: SplitNValue<"undefined" | "horizontal" | "vertical">) => Renderable; owns: (value: SplitNValue) => Renderable; placeholder: (value: SplitNValue) => Renderable; posinset: (value: SplitNValue) => Renderable; pressed: (value: SplitNValue) => Renderable; readonly: (value: SplitNValue) => Renderable; relevant: (value: SplitNValue) => Renderable; required: (value: SplitNValue) => Renderable; roledescription: (value: SplitNValue) => Renderable; rowcount: (value: SplitNValue) => Renderable; rowindex: (value: SplitNValue) => Renderable; rowindextext: (value: SplitNValue) => Renderable; rowspan: (value: SplitNValue) => Renderable; selected: (value: SplitNValue) => Renderable; setsize: (value: SplitNValue) => Renderable; sort: (value: SplitNValue<"none" | "ascending" | "descending" | "other">) => Renderable; valuemax: (value: SplitNValue) => Renderable; valuemin: (value: SplitNValue) => Renderable; valuenow: (value: SplitNValue) => Renderable; valuetext: (value: SplitNValue) => Renderable; } ``` ## dom.aria: Example ```ts const button = html.button( aria.label('Click me!'), // maps to the `aria-label` attribute // maps to the `aria-pressed` attribute where pressed is a `Signal` aria.pressed(pressed) ) ``` --- ## dom.ariaattributes: AriaAttributes type Represents a collection of ARIA attributes and their corresponding types. **Signature:**```typescript export type AriaAttributes = { activedescendant: string; atomic: boolean; autocomplete: 'none' | 'inline' | 'list' | 'both'; braillelabel: string; brailleroledescription: string; busy: boolean; checked: boolean | 'mixed'; colcount: number; colindex: number; colindextext: string; colspan: number; controls: string; current: 'page' | 'step' | 'location' | 'date' | 'time' | 'true' | 'false' | string; describedby: string; description: string; details: string; disabled: boolean; dropeffect: 'none' | 'copy' | 'execute' | 'link' | 'move' | 'popup'; errormessage: string; expanded: boolean | 'undefined'; flowto: string; grabbed: boolean; haspopup: boolean | 'false' | 'true' | 'menu' | 'listbox' | 'tree' | 'grid' | 'dialog'; hidden: boolean | 'undefined'; invalid: boolean | 'false' | 'true' | 'grammar' | 'spelling'; keyshortcuts: string; label: string; labelledby: string; level: number; live: 'off' | 'assertive' | 'polite'; modal: boolean; multiline: boolean; multiselectable: boolean; orientation: 'horizontal' | 'vertical' | 'undefined'; owns: string; placeholder: string; posinset: number; pressed: boolean | 'mixed' | 'undefined'; readonly: boolean; relevant: 'additions' | 'removals' | 'text' | 'all' | string; required: boolean; roledescription: string; rowcount: number; rowindex: number; rowindextext: string; rowspan: number; selected: boolean | 'undefined'; setsize: number; sort: 'none' | 'ascending' | 'descending' | 'other'; valuemax: number; valuemin: number; valuenow: number; valuetext: string; }; ``` --- ## dom.async: Async() function Creates a renderable asynchronous task that wraps a promise. **Signature:**```typescript Async: (promise: Promise, options: AsyncOptions | ((value: T) => TNode)) => Renderable ```## dom.async: Parameters | Parameter | Type | Description | | --- | --- | --- | | promise | Promise<T> | The promise to wrap. | | options | [AsyncOptions](#dom-asyncoptions)<T> \\| ((value: T) => [TNode](#dom-tnode)) | The options for the asynchronous task. | **Returns:** [Renderable](#dom-renderable) The renderable asynchronous task. --- ## dom.asyncoptions: AsyncOptions type Options for the `Async` component. **Signature:**```typescript export type AsyncOptions = { pending?: () => TNode; then: (value: T) => TNode; error?: (error: unknown) => TNode; }; ``` **References:** [TNode](#dom-tnode) --- ## dom.attr_2: Attr\_2() function Creates a renderable for an HTML attribute with the specified name and value. This is the functional equivalent of using `attr[name](value)` with a dynamic attribute name. The `class` attribute is special and can be used multiple times on the same element. Multiple class values will be merged together. **Signature:**```typescript Attr: (name: string, value: unknown) => Renderable ```## dom.attr_2: Parameters | Parameter | Type | Description | | --- | --- | --- | | name | string | The name of the attribute. | | value | unknown | The value of the attribute (can be a literal or Signal). | **Returns:** [Renderable](#dom-renderable) A renderable that sets the attribute. ## dom.attr_2: Example```ts const button = html.button( Attr('type', 'button'), Attr('disabled', disabledSignal), // Multiple class attributes Attr('class', 'btn btn-primary'), Attr('class', 'active'), // Both classes will be applied // ... ) ``` --- ## dom.attr: attr variable The `attr` object allows to create any HTML attribute. Either a literal value or `Signal` can be passed as a value. The type of the value is inferred from the attribute name. **Signature:**```typescript attr: { accept: (value: SplitNValue) => Renderable; 'accept-charset': (value: SplitNValue) => Renderable; accesskey: (value: SplitNValue) => Renderable; action: (value: SplitNValue) => Renderable; align: (value: SplitNValue) => Renderable; allow: (value: SplitNValue) => Renderable; allowfullscreen: (value: SplitNValue) => Renderable; allowpaymentrequest: (value: SplitNValue) => Renderable; alt: (value: SplitNValue) => Renderable; as: (value: SplitNValue) => Renderable; async: (value: SplitNValue) => Renderable; autocapitalize: (value: SplitNValue<"none" | "off" | "on" | "sentences" | "words" | "characters">) => Renderable; autocomplete: (value: SplitNValue) => Renderable; autofocus: (value: SplitNValue) => Renderable; autoplay: (value: SplitNValue) => Renderable; bgcolor: (value: SplitNValue) => Renderable; border: (value: SplitNValue) => Renderable; capture: (value: SplitNValue) => Renderable; charset: (value: SplitNValue) => Renderable; checked: (value: SplitNValue) => Renderable; cite: (value: SplitNValue) => Renderable; class: (value: SplitNValue) => Renderable; color: (value: SplitNValue) => Renderable; cols: (value: SplitNValue) => Renderable; colspan: (value: SplitNValue) => Renderable; content: (value: SplitNValue) => Renderable; contenteditable: (value: SplitNValue) => Renderable; controls: (value: SplitNValue) => Renderable; coords: (value: SplitNValue) => Renderable; crossorigin: (value: SplitNValue<"" | "anonymous" | "use-credentials">) => Renderable; data: (value: SplitNValue) => Renderable; datetime: (value: SplitNValue) => Renderable; decoding: (value: SplitNValue<"sync" | "async" | "auto">) => Renderable; default: (value: SplitNValue) => Renderable; defer: (value: SplitNValue) => Renderable; dir: (value: SplitNValue<"auto" | "ltr" | "rtl">) => Renderable; dirname: (value: SplitNValue) => Renderable; disabled: (value: SplitNValue) => Renderable; download: (value: SplitNValue) => Renderable; draggable: (value: SplitNValue) => Renderable; dropzone: (value: SplitNValue) => Renderable; enctype: (value: SplitNValue) => Renderable; enterkeyhint: (value: SplitNValue<"enter" | "done" | "go" | "next" | "previous" | "search" | "send">) => Renderable; for: (value: SplitNValue) => Renderable; form: (value: SplitNValue) => Renderable; formaction: (value: SplitNValue) => Renderable; formenctype: (value: SplitNValue) => Renderable; formmethod: (value: SplitNValue) => Renderable; formnovalidate: (value: SplitNValue) => Renderable; formtarget: (value: SplitNValue) => Renderable; headers: (value: SplitNValue) => Renderable; height: (value: SplitNValue) => Renderable; hidden: (value: SplitNValue) => Renderable; high: (value: SplitNValue) => Renderable; href: (value: SplitNValue) => Renderable; hreflang: (value: SplitNValue) => Renderable; 'http-equiv': (value: SplitNValue) => Renderable; icon: (value: SplitNValue) => Renderable; id: (value: SplitNValue) => Renderable; imagesizes: (value: SplitNValue) => Renderable; imagesrcset: (value: SplitNValue) => Renderable; inputmode: (value: SplitNValue<"none" | "text" | "search" | "decimal" | "numeric" | "tel" | "email" | "url">) => Renderable; integrity: (value: SplitNValue) => Renderable; is: (value: SplitNValue) => Renderable; ismap: (value: SplitNValue) => Renderable; itemid: (value: SplitNValue) => Renderable; itemprop: (value: SplitNValue) => Renderable; itemref: (value: SplitNValue) => Renderable; itemscope: (value: SplitNValue) => Renderable; itemtype: (value: SplitNValue) => Renderable; keytype: (value: SplitNValue) => Renderable; kind: (value: SplitNValue) => Renderable; label: (value: SplitNValue) => Renderable; lang: (value: SplitNValue) => Renderable; language: (value: SplitNValue) => Renderable; list: (value: SplitNValue) => Renderable; loading: (value: SplitNValue<"eager" | "lazy">) => Renderable; loop: (value: SplitNValue) => Renderable; low: (value: SplitNValue) => Renderable; manifest: (value: SplitNValue) => Renderable; max: (value: SplitNValue) => Renderable; maxlength: (value: SplitNValue) => Renderable; media: (value: SplitNValue) => Renderable; method: (value: SplitNValue) => Renderable; min: (value: SplitNValue) => Renderable; minlength: (value: SplitNValue) => Renderable; multiple: (value: SplitNValue) => Renderable; muted: (value: SplitNValue) => Renderable; name: (value: SplitNValue) => Renderable; nonce: (value: SplitNValue) => Renderable; novalidate: (value: SplitNValue) => Renderable; open: (value: SplitNValue) => Renderable; optimum: (value: SplitNValue) => Renderable; part: (value: SplitNValue) => Renderable; pattern: (value: SplitNValue) => Renderable; ping: (value: SplitNValue) => Renderable; placeholder: (value: SplitNValue) => Renderable; playsinline: (value: SplitNValue) => Renderable; popover: (value: SplitNValue<"" | "auto" | "manual">) => Renderable; popovertarget: (value: SplitNValue) => Renderable; popovertargetaction: (value: SplitNValue<"hide" | "show" | "toggle">) => Renderable; poster: (value: SplitNValue) => Renderable; preload: (value: SplitNValue) => Renderable; property: (value: SplitNValue) => Renderable; radiogroup: (value: SplitNValue) => Renderable; readonly: (value: SplitNValue) => Renderable; referrerpolicy: (value: SplitNValue<"no-referrer" | "no-referrer-when-downgrade" | "origin" | "origin-when-cross-origin" | "same-origin" | "strict-origin" | "strict-origin-when-cross-origin" | "unsafe-url">) => Renderable; rel: (value: SplitNValue) => Renderable; required: (value: SplitNValue) => Renderable; reversed: (value: SplitNValue) => Renderable; role: (value: SplitNValue) => Renderable; rows: (value: SplitNValue) => Renderable; rowspan: (value: SplitNValue) => Renderable; sandbox: (value: SplitNValue) => Renderable; scope: (value: SplitNValue) => Renderable; scoped: (value: SplitNValue) => Renderable; seamless: (value: SplitNValue) => Renderable; selected: (value: SplitNValue) => Renderable; shape: (value: SplitNValue) => Renderable; size: (value: SplitNValue) => Renderable; sizes: (value: SplitNValue) => Renderable; slot: (value: SplitNValue) => Renderable; span: (value: SplitNValue) => Renderable; spellcheck: (value: SplitNValue) => Renderable; src: (value: SplitNValue) => Renderable; srcdoc: (value: SplitNValue) => Renderable; srclang: (value: SplitNValue) => Renderable; srcset: (value: SplitNValue) => Renderable; start: (value: SplitNValue) => Renderable; step: (value: SplitNValue) => Renderable; style: (value: SplitNValue) => Renderable; tabindex: (value: SplitNValue) => Renderable; target: (value: SplitNValue) => Renderable; title: (value: SplitNValue) => Renderable; translate: (value: SplitNValue<"yes" | "no">) => Renderable; type: (value: SplitNValue) => Renderable; usemap: (value: SplitNValue) => Renderable; value: (value: SplitNValue) => Renderable; valueAsNumber: (value: SplitNValue) => Renderable; valueAsDate: (value: SplitNValue) => Renderable; width: (value: SplitNValue) => Renderable; wrap: (value: SplitNValue) => Renderable; textContent: (value: SplitNValue) => Renderable; innerText: (value: SplitNValue) => Renderable; innerHTML: (value: SplitNValue) => Renderable; outerHTML: (value: SplitNValue) => Renderable; } ``` ## dom.attr: Example ```ts const button = html.button( attr.type('button'), attr.disabled(disabled), // where disabled is a `Signal` // ... ) ``` --- ## dom.bindchecked: BindChecked() function Binds a `boolean` property to the checked value of an input element. The binding is two-way. **Signature:**```typescript BindChecked: (prop: Prop) => Renderable ```## dom.bindchecked: Parameters | Parameter | Type | Description | | --- | --- | --- | | prop | Prop<boolean> | The `boolean` property to bind. | **Returns:** [Renderable](#dom-renderable) A Renderable. --- ## dom.binddate: BindDate() function Binds a `Date` property to an input element. The binding is two-way. Changes to the input element will update the property but will only be affected by day changes and ignore time changes. **Signature:**```typescript BindDate: (prop: Prop, handler?: keyof typeof on) => Renderable ```## dom.binddate: Parameters | Parameter | Type | Description | | --- | --- | --- | | prop | Prop<Date> | The `Date` property to bind. | | handler | keyof typeof [on](#dom-on) | _(Optional)_ The event handler to use (default: 'input'). | **Returns:** [Renderable](#dom-renderable) A Renderable. --- ## dom.binddatetime: BindDateTime() function Binds a `Date` property to an input element. The binding is two-way. **Signature:**```typescript BindDateTime: (prop: Prop, handler?: keyof typeof on) => Renderable ```## dom.binddatetime: Parameters | Parameter | Type | Description | | --- | --- | --- | | prop | Prop<Date> | The `Date` property to bind. | | handler | keyof typeof [on](#dom-on) | _(Optional)_ The event handler to use (default: 'input'). | **Returns:** [Renderable](#dom-renderable) A Renderable. --- ## dom.bindnumber: BindNumber() function Binds a `number` property to an input element. The binding is two-way. **Signature:**```typescript BindNumber: (prop: Prop, handler?: keyof typeof on) => Renderable ```## dom.bindnumber: Parameters | Parameter | Type | Description | | --- | --- | --- | | prop | Prop<number> | The `number` property to bind. | | handler | keyof typeof [on](#dom-on) | _(Optional)_ The event handler to use (default: 'input'). | **Returns:** [Renderable](#dom-renderable) A Renderable. --- ## dom.bindtext: BindText() function Binds a `string` property to an input element. The binding is two-way. **Signature:**```typescript BindText: (prop: Prop, handler?: keyof typeof on) => Renderable ```## dom.bindtext: Parameters | Parameter | Type | Description | | --- | --- | --- | | prop | Prop<string> | The `string` property to bind. | | handler | keyof typeof [on](#dom-on) | _(Optional)_ The event handler to use (default: 'input'). | **Returns:** [Renderable](#dom-renderable) A Renderable. --- ## dom.browsercontext._constructor_: BrowserContext.(constructor) Constructs a new `DOMContext` instance. **Signature:**```typescript constructor( document: Document, element: HTMLElement, reference: Node | undefined, providers: Providers); ```## dom.browsercontext._constructor_: Parameters | Parameter | Type | Description | | --- | --- | --- | | document | Document | The `Document` instance associated with this context. | | element | HTMLElement | The `Element` instance associated with this context. | | reference | Node \\| undefined | An optional `Node` instance that serves as a reference for this context. | | providers | [Providers](#dom-providers) | The `Providers` instance associated with this context. | --- ## dom.browsercontext.addclasses: BrowserContext.addClasses property Adds classes to the element. **Signature:**```typescript readonly addClasses: (tokens: string[]) => void; ``` --- ## dom.browsercontext.appendorinsert: BrowserContext.appendOrInsert property Appends or inserts a child node to the element, depending on whether a reference node is provided. **Signature:**```typescript readonly appendOrInsert: (child: Node) => void; ``` --- ## dom.browsercontext.clear: BrowserContext.clear property **Signature:**```typescript readonly clear: (removeTree: boolean) => void; ``` --- ## dom.browsercontext.createelement: BrowserContext.createElement property Creates a new DOM element (eg: HTML or SVG) with the specified tag name and namespace. **Signature:**```typescript readonly createElement: (tagName: string, namespace: string | undefined) => HTMLElement; ``` --- ## dom.browsercontext.createtext: BrowserContext.createText property Creates a new text node with the specified text content. **Signature:**```typescript readonly createText: (text: string) => Text; ``` --- ## dom.browsercontext.document: BrowserContext.document property The `Document` instance associated with this context. **Signature:**```typescript readonly document: Document; ``` --- ## dom.browsercontext.element: BrowserContext.element property The `Element` instance associated with this context. **Signature:**```typescript readonly element: HTMLElement; ``` --- ## dom.browsercontext.getclasses: BrowserContext.getClasses property Gets the classes of the element. **Signature:**```typescript readonly getClasses: () => string[]; ``` --- ## dom.browsercontext.getprovider: BrowserContext.getProvider property Retrieves a provider for the given provider mark. **Signature:**```typescript readonly getProvider: (mark: ProviderMark) => { value: T; onUse: (() => void) | undefined; }; ``` --- ## dom.browsercontext.getstyle: BrowserContext.getStyle property Gets the style of the element. **Signature:**```typescript readonly getStyle: (name: string) => string; ``` --- ## dom.browsercontext.gettext: BrowserContext.getText property Gets the text content of the current element or text node. **Signature:**```typescript readonly getText: () => string; ``` --- ## dom.browsercontext.getwindow: BrowserContext.getWindow property **Signature:**```typescript readonly getWindow: () => Window & typeof globalThis; ``` --- ## dom.browsercontext.isbrowser: BrowserContext.isBrowser property Returns `true` if the context is a browser context. **Signature:**```typescript readonly isBrowser: () => this is BrowserContext; ``` --- ## dom.browsercontext.isbrowserdom: BrowserContext.isBrowserDOM property > Warning: This API is now obsolete. > > Use `isBrowser()` instead. > Returns `true` if the context is a browser DOM context. **Signature:**```typescript readonly isBrowserDOM: () => this is BrowserContext; ``` --- ## dom.browsercontext.isheadless: BrowserContext.isHeadless property Returns `true` if the context is a headless context. **Signature:**```typescript readonly isHeadless: () => this is HeadlessContext; ``` --- ## dom.browsercontext.isheadlessdom: BrowserContext.isHeadlessDOM property Returns `true` if the context is a headless DOM context. **Signature:**```typescript readonly isHeadlessDOM: () => this is HeadlessContext; ``` --- ## dom.browsercontext.makeaccessors: BrowserContext.makeAccessors property **Signature:**```typescript readonly makeAccessors: (name: string) => { get: () => any; set: (value: unknown) => void; }; ``` --- ## dom.browsercontext.makechildelement: BrowserContext.makeChildElement property Creates a new child element and appends it to the current element, returning a new context. This method creates a new DOM element with the specified tag name and namespace, appends it to the current element, and returns a new DOMContext focused on the newly created child element. This is the primary method for building DOM trees. **Signature:**```typescript readonly makeChildElement: (tagName: string, namespace: string | undefined) => DOMContext; ``` ## dom.browsercontext.makechildelement: Example ```typescript // Create HTML elements const divCtx = ctx.makeChildElement('div', undefined) const spanCtx = divCtx.makeChildElement('span', undefined) // Create SVG elements const svgCtx = ctx.makeChildElement('svg', 'http://www.w3.org/2000/svg') const circleCtx = svgCtx.makeChildElement('circle', 'http://www.w3.org/2000/svg') ``` --- ## dom.browsercontext.makechildtext: BrowserContext.makeChildText property Creates a new text node with the specified text content and appends it to the current element. **Signature:**```typescript readonly makeChildText: (text: string) => DOMContext; ``` --- ## dom.browsercontext.makeportal: BrowserContext.makePortal property Creates a portal to render content in a different part of the DOM tree. Portals allow you to render child components into a DOM node that exists outside the parent component's DOM hierarchy. This is useful for modals, tooltips, dropdowns, and other UI elements that need to break out of their container's styling or z-index context. **Signature:**```typescript readonly makePortal: (selector: string | HTMLElement) => DOMContext; ``` ## dom.browsercontext.makeportal: Example 1 ```typescript // Portal to a modal container const modalCtx = ctx.makePortal('#modal-root') const modal = modalCtx.makeChildElement('div', undefined) // Add modal content modal.makeChildText('This renders in #modal-root') ``` ## dom.browsercontext.makeportal: Example 2 ```typescript // Portal to an existing element reference const tooltipContainer = document.getElementById('tooltip-container')! const tooltipCtx = ctx.makePortal(tooltipContainer) // Render tooltip content const tooltip = tooltipCtx.makeChildElement('div', undefined) tooltip.addClasses(['tooltip', 'tooltip-top']) ``` ## dom.browsercontext.makeportal: Example 3 ```typescript // Portal for dropdown menu const dropdownCtx = ctx.makePortal('body') // Render at body level const dropdown = dropdownCtx.makeChildElement('div', undefined) dropdown.addClasses(['dropdown-menu']) dropdown.setStyle('position', 'absolute') dropdown.setStyle('top', '100px') dropdown.setStyle('left', '50px') ``` --- ## dom.browsercontext.makeref: BrowserContext.makeRef property Creates a new `DOMContext` with a reference to a newly created text node. The text node is appended or inserted to the current `DOMContext`. The new `DOMContext` with the reference is returned. **Signature:**```typescript readonly makeRef: () => DOMContext; ``` --- ## dom.browsercontext: BrowserContext class Browser implementation of DOMContext for real DOM manipulation in web browsers. BrowserContext provides a comprehensive API for creating, manipulating, and managing DOM elements in a browser environment. It handles element creation, text nodes, event listeners, styling, and provider management while maintaining immutability through context chaining. The context uses a reference system to track insertion points within sibling elements, allowing precise control over where new elements are inserted in the DOM tree. **Signature:**```typescript export declare class BrowserContext implements DOMContext ``` **Implements:** [DOMContext](#dom-domcontext) ## dom.browsercontext: Example 1 ```typescript // Create a context for the document body const ctx = BrowserContext.of(document.body, undefined, {}) // Create child elements const divCtx = ctx.makeChildElement('div', undefined) const textCtx = divCtx.makeChildText('Hello, World!') // Add event listeners divCtx.on('click', (event, ctx) => { console.log('Div clicked!', event.target) }) ``` ## dom.browsercontext: Example 2 ```typescript // Working with providers const themeProvider = makeProviderMark('theme') const ctxWithProvider = ctx.setProvider(themeProvider, 'dark', undefined) // Later retrieve the provider const { value: theme } = ctxWithProvider.getProvider(themeProvider) ``` ## dom.browsercontext: Example 3 ```typescript // Portal to different DOM location const modalCtx = ctx.makePortal('#modal-root') const modalContent = modalCtx.makeChildElement('div', undefined) ```## dom.browsercontext: Constructors | Constructor | Modifiers | Description | | --- | --- | --- | | [(constructor)(document, element, reference, providers)](#dom-browsercontext-constructor) | | Constructs a new `DOMContext` instance. | ## dom.browsercontext: Properties | Property | Modifiers | Type | Description | | --- | --- | --- | --- | | [addClasses](#dom-browsercontext-addclasses) | `readonly` | (tokens: string\[\]) => void | Adds classes to the element. | | [appendOrInsert](#dom-browsercontext-appendorinsert) | `readonly` | (child: Node) => void | Appends or inserts a child node to the element, depending on whether a reference node is provided. | | [clear](#dom-browsercontext-clear) | `readonly` | (removeTree: boolean) => void | | | [createElement](#dom-browsercontext-createelement) | `readonly` | (tagName: string, namespace: string \\| undefined) => HTMLElement | Creates a new DOM element (eg: HTML or SVG) with the specified tag name and namespace. | | [createText](#dom-browsercontext-createtext) | `readonly` | (text: string) => Text | Creates a new text node with the specified text content. | | [document](#dom-browsercontext-document) | `readonly` | Document | The `Document` instance associated with this context. | | [element](#dom-browsercontext-element) | `readonly` | HTMLElement | The `Element` instance associated with this context. | | [getClasses](#dom-browsercontext-getclasses) | `readonly` | () => string\[\] | Gets the classes of the element. | | [getProvider](#dom-browsercontext-getprovider) | `readonly` | <T>(mark: ProviderMark<T>) => { value: T; onUse: (() => void) \\| undefined; } | Retrieves a provider for the given provider mark. | | [getStyle](#dom-browsercontext-getstyle) | `readonly` | (name: string) => string | Gets the style of the element. | | [getText](#dom-browsercontext-gettext) | `readonly` | () => string | Gets the text content of the current element or text node. | | [getWindow](#dom-browsercontext-getwindow) | `readonly` | () => Window & typeof globalThis | | | [isBrowser](#dom-browsercontext-isbrowser) | `readonly` | () => this is [BrowserContext](#dom-browsercontext) | Returns `true` if the context is a browser context. | | [isBrowserDOM](#dom-browsercontext-isbrowserdom) | `readonly` | () => this is [BrowserContext](#dom-browsercontext) | Returns `true` if the context is a browser DOM context. | | [isHeadless](#dom-browsercontext-isheadless) | `readonly` | () => this is [HeadlessContext](#dom-headlesscontext) | Returns `true` if the context is a headless context. | | [isHeadlessDOM](#dom-browsercontext-isheadlessdom) | `readonly` | () => this is [HeadlessContext](#dom-headlesscontext) | Returns `true` if the context is a headless DOM context. | | [makeAccessors](#dom-browsercontext-makeaccessors) | `readonly` | (name: string) => { get: () => any; set: (value: unknown) => void; } | | | [makeChildElement](#dom-browsercontext-makechildelement) | `readonly` | (tagName: string, namespace: string \\| undefined) => [DOMContext](#dom-domcontext) | Creates a new child element and appends it to the current element, returning a new context. This method creates a new DOM element with the specified tag name and namespace, appends it to the current element, and returns a new DOMContext focused on the newly created child element. This is the primary method for building DOM trees. | | [makeChildText](#dom-browsercontext-makechildtext) | `readonly` | (text: string) => [DOMContext](#dom-domcontext) | Creates a new text node with the specified text content and appends it to the current element. | | [makePortal](#dom-browsercontext-makeportal) | `readonly` | (selector: string \\| HTMLElement) => [DOMContext](#dom-domcontext) | Creates a portal to render content in a different part of the DOM tree. Portals allow you to render child components into a DOM node that exists outside the parent component's DOM hierarchy. This is useful for modals, tooltips, dropdowns, and other UI elements that need to break out of their container's styling or z-index context. | | [makeRef](#dom-browsercontext-makeref) | `readonly` | () => [DOMContext](#dom-domcontext) | Creates a new `DOMContext` with a reference to a newly created text node. The text node is appended or inserted to the current `DOMContext`. The new `DOMContext` with the reference is returned. | | [on](#dom-browsercontext-on) | `readonly` | <E>(event: string, listener: (event: E, ctx: [BrowserContext](#dom-browsercontext)) => void, options?: [HandlerOptions](#dom-handleroptions)) => Clear | Adds an event listener to the element. | | [providers](#dom-browsercontext-providers) | `readonly` | [Providers](#dom-providers) | The `Providers` instance associated with this context. | | [reference](#dom-browsercontext-reference) | `readonly` | Node \\| undefined | An optional `Node` instance that serves as a reference for this context. | | [removeClasses](#dom-browsercontext-removeclasses) | `readonly` | (tokens: string\[\]) => void | Removes classes from the element. | | [setProvider](#dom-browsercontext-setprovider) | `readonly` | <T>(mark: ProviderMark<T>, value: T, onUse: undefined \\| (() => void)) => [DOMContext](#dom-domcontext) | Sets a provider for the given provider mark. | | [setStyle](#dom-browsercontext-setstyle) | `readonly` | (name: string, value: string) => void | Sets the style of the element. | | [setText](#dom-browsercontext-settext) | `readonly` | (text: string) => void | Sets the text content of the current element. | | [withElement](#dom-browsercontext-withelement) | `readonly` | (element: HTMLElement) => [BrowserContext](#dom-browsercontext) | Creates a new `DOMContext` instance with the provided `element`. | | [withReference](#dom-browsercontext-withreference) | `readonly` | (reference: Text \\| undefined) => [DOMContext](#dom-domcontext) | Creates a new `DOMContext` instance with the specified reference. | ## dom.browsercontext: Methods | Method | Modifiers | Description | | --- | --- | --- | | [of(element, ref, providers)](#dom-browsercontext-of) | `static` | Creates a new `DOMContext` instance for the given `Element` and optional reference `Node`. | --- ## dom.browsercontext.of: BrowserContext.of() method Creates a new `DOMContext` instance for the given `Element` and optional reference `Node`. **Signature:**```typescript static of(element: HTMLElement, ref: Node | undefined, providers: Providers): DOMContext; ```## dom.browsercontext.of: Parameters | Parameter | Type | Description | | --- | --- | --- | | element | HTMLElement | The `HTMLElement` to create the `DOMContext` for. | | ref | Node \\| undefined | A reference `Node` to associate with the `DOMContext` or undefined . | | providers | [Providers](#dom-providers) | The providers to associate with the `DOMContext`. | **Returns:** [DOMContext](#dom-domcontext) A new `DOMContext` instance. --- ## dom.browsercontext.on: BrowserContext.on property Adds an event listener to the element. **Signature:**```typescript readonly on: (event: string, listener: (event: E, ctx: BrowserContext) => void, options?: HandlerOptions) => Clear; ``` --- ## dom.browsercontext.providers: BrowserContext.providers property The `Providers` instance associated with this context. **Signature:**```typescript readonly providers: Providers; ``` --- ## dom.browsercontext.reference: BrowserContext.reference property An optional `Node` instance that serves as a reference for this context. **Signature:**```typescript readonly reference: Node | undefined; ``` --- ## dom.browsercontext.removeclasses: BrowserContext.removeClasses property Removes classes from the element. **Signature:**```typescript readonly removeClasses: (tokens: string[]) => void; ``` --- ## dom.browsercontext.setprovider: BrowserContext.setProvider property Sets a provider for the given provider mark. **Signature:**```typescript readonly setProvider: (mark: ProviderMark, value: T, onUse: undefined | (() => void)) => DOMContext; ``` --- ## dom.browsercontext.setstyle: BrowserContext.setStyle property Sets the style of the element. **Signature:**```typescript readonly setStyle: (name: string, value: string) => void; ``` --- ## dom.browsercontext.settext: BrowserContext.setText property Sets the text content of the current element. **Signature:**```typescript readonly setText: (text: string) => void; ``` --- ## dom.browsercontext.withelement: BrowserContext.withElement property Creates a new `DOMContext` instance with the provided `element`. **Signature:**```typescript readonly withElement: (element: HTMLElement) => BrowserContext; ``` --- ## dom.browsercontext.withreference: BrowserContext.withReference property Creates a new `DOMContext` instance with the specified reference. **Signature:**```typescript readonly withReference: (reference: Text | undefined) => DOMContext; ``` --- ## dom.class_placeholder_attr: CLASS\_PLACEHOLDER\_ATTR variable **Signature:**```typescript CLASS_PLACEHOLDER_ATTR = "data-tts-class" ``` --- ## dom.conjunction: Conjunction() function Creates a Renderable that returns the appropriate separator based on the element position. **Signature:**```typescript Conjunction: (separator: () => TNode, options?: ConjunctionOptions) => (pos: Signal) => Renderable ```## dom.conjunction: Parameters | Parameter | Type | Description | | --- | --- | --- | | separator | () => [TNode](#dom-tnode) | The default separator to use. | | options | [ConjunctionOptions](#dom-conjunctionoptions) | _(Optional)_ The options for configuring the conjunction. | **Returns:** (pos: Signal<ElementPosition>) => [Renderable](#dom-renderable) A function that returns the appropriate separator based on the element position. --- ## dom.conjunctionoptions: ConjunctionOptions type Options for configuring a conjunction. **Signature:**```typescript export type ConjunctionOptions = { lastSeparator?: () => TNode; firstSeparator?: () => TNode; }; ``` **References:** [TNode](#dom-tnode) --- ## dom.cssstyles: CSSStyles type Represents a subset of CSS styles. It is a type that excludes certain properties from the `CSSStyleDeclaration` type. **Signature:**```typescript export type CSSStyles = Omit; ``` **References:** [ExcludeFromStyle](#dom-excludefromstyle) --- ## dom.dataattr: dataAttr variable The `data` object allows to create any `data-` attributes. Either a literal value or `Signal` can be passed as a value. **Signature:** ```typescript dataAttr: { [x: string]: (value: Value) => Renderable; } ``` ## dom.dataattr: Example ```ts const button = html.button( dataAttr.myinfo('something'), // maps to the `data-myinfo` attribute ) ``` --- ## dom.disposecallback: DisposeCallback type **Signature:**```typescript export type DisposeCallback = (removeTree: boolean, ctx: DOMContext) => void; ``` **References:** [DOMContext](#dom-domcontext) --- ## dom.dom_renderable_type: DOM\_RENDERABLE\_TYPE variable Symbol to brand DOM renderables and prevent mixing with other contexts **Signature:**```typescript DOM_RENDERABLE_TYPE: unique symbol ``` --- ## dom.domcontext.addclasses: DOMContext.addClasses() method Adds classes to the element. **Signature:**```typescript addClasses(tokens: string[]): void; ```## dom.domcontext.addclasses: Parameters | Parameter | Type | Description | | --- | --- | --- | | tokens | string\[\] | The class names to add. | **Returns:** void --- ## dom.domcontext.clear: DOMContext.clear() method **Signature:**```typescript clear(removeTree: boolean): void; ```## dom.domcontext.clear: Parameters | Parameter | Type | Description | | --- | --- | --- | | removeTree | boolean | | **Returns:** void --- ## dom.domcontext.getclasses: DOMContext.getClasses() method Gets the classes of the element. **Signature:**```typescript getClasses(): string[]; ``` **Returns:** string\[\] The classes of the element. --- ## dom.domcontext.getprovider: DOMContext.getProvider() method Retrieves a provider for the given provider mark. **Signature:**```typescript getProvider(mark: ProviderMark): { value: T; onUse?: () => void; }; ```## dom.domcontext.getprovider: Parameters | Parameter | Type | Description | | --- | --- | --- | | mark | ProviderMark<T> | The provider mark to retrieve the provider for. | **Returns:** { value: T; onUse?: () => void; } The provider for the given mark. ## dom.domcontext.getprovider: Exceptions Throws `ProviderNotFoundError` if the provider for the given mark is not found. --- ## dom.domcontext.getstyle: DOMContext.getStyle() method Gets the style of the element. **Signature:**```typescript getStyle(name: string): string; ```## dom.domcontext.getstyle: Parameters | Parameter | Type | Description | | --- | --- | --- | | name | string | The name of the style to get. | **Returns:** string The value of the style. --- ## dom.domcontext.gettext: DOMContext.getText() method Gets the text content of the current element or text node. **Signature:**```typescript getText(): string; ``` **Returns:** string The text content of the current element or text node. --- ## dom.domcontext.isbrowser: DOMContext.isBrowser() method Returns `true` if the context is a browser DOM context. **Signature:**```typescript isBrowser(): this is BrowserContext; ``` **Returns:** this is [BrowserContext](#dom-browsercontext) `true` if the context is a browser DOM context. --- ## dom.domcontext.isbrowserdom: DOMContext.isBrowserDOM() method > Warning: This API is now obsolete. > > Use `isBrowser()` instead. > Returns `true` if the context is a browser DOM context. **Signature:**```typescript isBrowserDOM(): this is BrowserContext; ``` **Returns:** this is [BrowserContext](#dom-browsercontext) `true` if the context is a browser DOM context. --- ## dom.domcontext.isheadless: DOMContext.isHeadless() method Returns `true` if the context is a headless context. **Signature:**```typescript isHeadless(): this is HeadlessContext; ``` **Returns:** this is [HeadlessContext](#dom-headlesscontext) `true` if the context is a headless context. --- ## dom.domcontext.isheadlessdom: DOMContext.isHeadlessDOM() method Returns `true` if the context is a headless DOM context. **Signature:**```typescript isHeadlessDOM(): this is HeadlessContext; ``` **Returns:** this is [HeadlessContext](#dom-headlesscontext) `true` if the context is a headless DOM context. --- ## dom.domcontext.makeaccessors: DOMContext.makeAccessors() method Returns an object with methods to get and set the value of a property or attribute. **Signature:**```typescript makeAccessors(name: string): { get(): unknown; set(value: unknown): void; }; ```## dom.domcontext.makeaccessors: Parameters | Parameter | Type | Description | | --- | --- | --- | | name | string | The name of the property to create accessors for. | **Returns:** { get(): unknown; set(value: unknown): void; } An object with methods to get and set the value of the property. --- ## dom.domcontext.makechildelement: DOMContext.makeChildElement() method Creates a new DOM element (eg: HTML or SVG) with the specified tag name and namespace and appends it to the current element. **Signature:**```typescript makeChildElement(tagName: string, namespace: string | undefined): DOMContext; ```## dom.domcontext.makechildelement: Parameters | Parameter | Type | Description | | --- | --- | --- | | tagName | string | The tag name of the element to create. | | namespace | string \\| undefined | The namespace URI to create the element in, or `undefined` to create a standard HTML element. | **Returns:** [DOMContext](#dom-domcontext) The newly created element. --- ## dom.domcontext.makechildtext: DOMContext.makeChildText() method Creates a new text node with the specified text content and appends it to the current element. **Signature:**```typescript makeChildText(text: string): DOMContext; ```## dom.domcontext.makechildtext: Parameters | Parameter | Type | Description | | --- | --- | --- | | text | string | The text content for the new text node. | **Returns:** [DOMContext](#dom-domcontext) A new `DOMContext` with a reference to the new text node. --- ## dom.domcontext.makeportal: DOMContext.makePortal() method Creates a new `DOMContext` instance with a reference to a DOM element selected by the provided `selector`. **Signature:**```typescript makePortal(selector: string | HTMLElement): DOMContext; ```## dom.domcontext.makeportal: Parameters | Parameter | Type | Description | | --- | --- | --- | | selector | string \\| HTMLElement | The CSS selector for the target DOM element. | **Returns:** [DOMContext](#dom-domcontext) A new `DOMContext` instance with a reference to the selected DOM element. --- ## dom.domcontext.makeref: DOMContext.makeRef() method Creates a new `DOMContext` with a reference to a newly created text node. The text node is appended or inserted to the current `DOMContext`. The new `DOMContext` with the reference is returned. **Signature:**```typescript makeRef(): DOMContext; ``` **Returns:** [DOMContext](#dom-domcontext) --- ## dom.domcontext: DOMContext interface `DOMContext` is an immutable class that represents the context of a DOM element. It provides methods and properties to manipulate and interact with the DOM element. A reference in a DOMContext is to mark a position within a set of siblings. It is used to insert new elements before the reference. **Signature:**```typescript export interface DOMContext ```## dom.domcontext: Methods | Method | Description | | --- | --- | | [addClasses(tokens)](#dom-domcontext-addclasses) | Adds classes to the element. | | [clear(removeTree)](#dom-domcontext-clear) | | | [getClasses()](#dom-domcontext-getclasses) | Gets the classes of the element. | | [getProvider(mark)](#dom-domcontext-getprovider) | Retrieves a provider for the given provider mark. | | [getStyle(name)](#dom-domcontext-getstyle) | Gets the style of the element. | | [getText()](#dom-domcontext-gettext) | Gets the text content of the current element or text node. | | [isBrowser()](#dom-domcontext-isbrowser) | Returns `true` if the context is a browser DOM context. | | [isBrowserDOM()](#dom-domcontext-isbrowserdom) | Returns `true` if the context is a browser DOM context. | | [isHeadless()](#dom-domcontext-isheadless) | Returns `true` if the context is a headless context. | | [isHeadlessDOM()](#dom-domcontext-isheadlessdom) | Returns `true` if the context is a headless DOM context. | | [makeAccessors(name)](#dom-domcontext-makeaccessors) | Returns an object with methods to get and set the value of a property or attribute. | | [makeChildElement(tagName, namespace)](#dom-domcontext-makechildelement) | Creates a new DOM element (eg: HTML or SVG) with the specified tag name and namespace and appends it to the current element. | | [makeChildText(text)](#dom-domcontext-makechildtext) | Creates a new text node with the specified text content and appends it to the current element. | | [makePortal(selector)](#dom-domcontext-makeportal) | Creates a new `DOMContext` instance with a reference to a DOM element selected by the provided `selector`. | | [makeRef()](#dom-domcontext-makeref) | Creates a new `DOMContext` with a reference to a newly created text node. The text node is appended or inserted to the current `DOMContext`. The new `DOMContext` with the reference is returned. | | [on(event, listener, options)](#dom-domcontext-on) | Adds an event listener to the element. | | [removeClasses(tokens)](#dom-domcontext-removeclasses) | Removes classes from the element. | | [setProvider(mark, value, onUse)](#dom-domcontext-setprovider) | Sets a provider for the given provider mark. | | [setStyle(name, value)](#dom-domcontext-setstyle) | Sets the style of the element. | | [setText(text)](#dom-domcontext-settext) | Sets the text content of the current element. | --- ## dom.domcontext.on: DOMContext.on() method Adds an event listener to the element. **Signature:**```typescript on(event: string, listener: (event: E, ctx: DOMContext) => void, options?: HandlerOptions): Clear; ```## dom.domcontext.on: Parameters | Parameter | Type | Description | | --- | --- | --- | | event | string | The event to listen for. | | listener | (event: E, ctx: [DOMContext](#dom-domcontext)) => void | The listener to call when the event occurs. | | options | [HandlerOptions](#dom-handleroptions) | _(Optional)_ The options for the event listener. | **Returns:** Clear A function to remove the event listener. --- ## dom.domcontext.removeclasses: DOMContext.removeClasses() method Removes classes from the element. **Signature:**```typescript removeClasses(tokens: string[]): void; ```## dom.domcontext.removeclasses: Parameters | Parameter | Type | Description | | --- | --- | --- | | tokens | string\[\] | The class names to remove. | **Returns:** void --- ## dom.domcontext.setprovider: DOMContext.setProvider() method Sets a provider for the given provider mark. **Signature:**```typescript setProvider(mark: ProviderMark, value: T, onUse: undefined | (() => void)): DOMContext; ```## dom.domcontext.setprovider: Parameters | Parameter | Type | Description | | --- | --- | --- | | mark | ProviderMark<T> | The provider mark to set the provider for. | | value | T | The provider to set for the given mark. | | onUse | undefined \\| (() => void) | | **Returns:** [DOMContext](#dom-domcontext) --- ## dom.domcontext.setstyle: DOMContext.setStyle() method Sets the style of the element. **Signature:**```typescript setStyle(name: string, value: string): void; ```## dom.domcontext.setstyle: Parameters | Parameter | Type | Description | | --- | --- | --- | | name | string | The name of the style to set. | | value | string | The value of the style to set. | **Returns:** void --- ## dom.domcontext.settext: DOMContext.setText() method Sets the text content of the current element. **Signature:**```typescript setText(text: string): void; ```## dom.domcontext.settext: Parameters | Parameter | Type | Description | | --- | --- | --- | | text | string | The text content to set. | **Returns:** void --- ## dom.domnode: DOMNode() function Creates a renderable DOM node. **Signature:**```typescript DOMNode: (node: Node) => Renderable ```## dom.domnode: Parameters | Parameter | Type | Description | | --- | --- | --- | | node | Node | The DOM node to render. | **Returns:** [Renderable](#dom-renderable)<[BrowserContext](#dom-browsercontext)> A renderable object that can be used to remove the rendered node from the DOM. --- ## dom.el: El() function Creates a Renderable that represents an HTML element. **Signature:**```typescript El: (tagName: string, ...children: TNode[]) => Renderable ```## dom.el: Parameters | Parameter | Type | Description | | --- | --- | --- | | tagName | string | The tag name of the HTML element. | | children | [TNode](#dom-tnode)\[\] | The child nodes of the HTML element. | **Returns:** [Renderable](#dom-renderable) A renderable object that creates and appends the HTML element to the DOM. --- ## dom.elns: ElNS() function Creates a renderable object that represents an element in the DOM with a specified namespace. **Signature:**```typescript ElNS: (tagName: string, namespace: string, ...children: TNode[]) => Renderable ```## dom.elns: Parameters | Parameter | Type | Description | | --- | --- | --- | | tagName | string | The name of the HTML tag for the element. | | namespace | string | The namespace of the element. | | children | [TNode](#dom-tnode)\[\] | The child nodes of the element. | **Returns:** [Renderable](#dom-renderable) A renderable object that creates and appends the element to the DOM. --- ## dom.emit: emit() function Creates an event handler that calls the provided function with the event as an argument. **Signature:**```typescript emit: (fn: (event: Event) => void, options?: EmitOptions) => (event: Event) => void ```## dom.emit: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn | (event: Event) => void | The function to call when the event is triggered. | | options | [EmitOptions](#dom-emitoptions) | _(Optional)_ | **Returns:** (event: Event) => void An event handler function that can be used with event listeners. --- ## dom.emitchecked: emitChecked() function Creates an event handler that extracts and emits the checked state from a checkbox or radio input. This utility simplifies handling checkbox and radio button state changes by automatically extracting the `checked` property from the target element. **Signature:**```typescript emitChecked: (fn: (checked: boolean, event: Event) => void, options?: EmitOptions) => (event: Event) => void ```## dom.emitchecked: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn | (checked: boolean, event: Event) => void | Callback function that receives the input element's checked state | | options | [EmitOptions](#dom-emitoptions) | _(Optional)_ | **Returns:** (event: Event) => void Event handler function that can be used with event listeners ## dom.emitchecked: Example 1```typescript const isEnabled = prop(false) html.input( attr.type('checkbox'), attr.checked(isEnabled), on.change(emitChecked(checked => isEnabled.value = checked)) ) ``` ## dom.emitchecked: Example 2 ```typescript // With radio buttons const selectedOption = prop('') html.div( html.label( html.input( attr.type('radio'), attr.name('option'), attr.value('A'), on.change(emitChecked(checked => { if (checked) selectedOption.value = 'A' })) ), 'Option A' ), html.label( html.input( attr.type('radio'), attr.name('option'), attr.value('B'), on.change(emitChecked(checked => { if (checked) selectedOption.value = 'B' })) ), 'Option B' ) ) ``` --- ## dom.emitoptions: EmitOptions type Options for event handlers. **Signature:**```typescript export type EmitOptions = { preventDefault?: boolean; stopPropagation?: boolean; stopImmediatePropagation?: boolean; }; ``` --- ## dom.emittarget: emitTarget() function Creates an event handler that extracts and emits the target element from an event. **Signature:**```typescript emitTarget: (fn: (element: EL, event: Event) => void, options?: EmitOptions) => (event: Event) => void ```## dom.emittarget: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn | (element: EL, event: Event) => void | Callback function that receives the target element | | options | [EmitOptions](#dom-emitoptions) | _(Optional)_ | **Returns:** (event: Event) => void Event handler function that can be used with event listeners ## dom.emittarget: Example```typescript html.input( on.input(emitTarget((input) => { console.log('Input value:', input.value) })) ) ``` --- ## dom.emitvalue: emitValue() function Creates an event handler that extracts and emits the string value from an input element. This utility simplifies handling input events by automatically extracting the value from the target element and passing it to your callback function. **Signature:**```typescript emitValue: (fn: (text: string, event: Event) => void, options?: EmitOptions) => (event: Event) => void ```## dom.emitvalue: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn | (text: string, event: Event) => void | Callback function that receives the input element's string value | | options | [EmitOptions](#dom-emitoptions) | _(Optional)_ | **Returns:** (event: Event) => void Event handler function that can be used with event listeners ## dom.emitvalue: Example 1```typescript const name = prop('') html.input( attr.value(name), on.input(emitValue(value => name.value = value)) ) ``` ## dom.emitvalue: Example 2 ```typescript // With textarea const description = prop('') html.textarea( attr.value(description), on.input(emitValue(value => { description.value = value console.log('Description updated:', value) })) ) ``` --- ## dom.emitvalueasdate: emitValueAsDate() function Converts the value of an HTML input element to a Date object and emits it using the provided callback function. **Signature:**```typescript emitValueAsDate: (fn: (date: Date, event: Event) => void, options?: EmitOptions) => (event: Event) => void ```## dom.emitvalueasdate: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn | (date: Date, event: Event) => void | The callback function to be called with the converted Date object. | | options | [EmitOptions](#dom-emitoptions) | _(Optional)_ | **Returns:** (event: Event) => void A function that can be used as an event handler for input events. --- ## dom.emitvalueasdatetime: emitValueAsDateTime() function Emits the value of an HTMLInputElement as a Date object. **Signature:**```typescript emitValueAsDateTime: (fn: (date: Date, event: Event) => void, options?: EmitOptions) => (event: Event) => void ```## dom.emitvalueasdatetime: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn | (date: Date, event: Event) => void | The callback function to be called with the emitted Date object. | | options | [EmitOptions](#dom-emitoptions) | _(Optional)_ | **Returns:** (event: Event) => void The event handler function. --- ## dom.emitvalueasnullabledate: emitValueAsNullableDate() function Converts the value of an HTML input element to a Date object or null and emits it using the provided callback function. **Signature:**```typescript emitValueAsNullableDate: (fn: (date: Date | null, event: Event) => void, options?: EmitOptions) => (event: Event) => void ```## dom.emitvalueasnullabledate: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn | (date: Date \\| null, event: Event) => void | The callback function to be called with the converted Date object or null. | | options | [EmitOptions](#dom-emitoptions) | _(Optional)_ | **Returns:** (event: Event) => void A function that can be used as an event handler for input events. --- ## dom.emitvalueasnullabledatetime: emitValueAsNullableDateTime() function Emits the value of an HTMLInputElement as a Date object or null. **Signature:**```typescript emitValueAsNullableDateTime: (fn: (date: Date | null, event: Event) => void, options?: EmitOptions) => (event: Event) => void ```## dom.emitvalueasnullabledatetime: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn | (date: Date \\| null, event: Event) => void | The callback function to be called with the emitted Date object or null. | | options | [EmitOptions](#dom-emitoptions) | _(Optional)_ | **Returns:** (event: Event) => void The event handler function. --- ## dom.emitvalueasnumber: emitValueAsNumber() function Creates an event handler that extracts and emits the numeric value from an input element. This utility automatically converts the input's value to a number using the browser's built-in `valueAsNumber` property, which handles number inputs correctly and returns `NaN` for invalid numeric values. **Signature:**```typescript emitValueAsNumber: (fn: (num: number, event: Event) => void, options?: EmitOptions) => (event: Event) => void ```## dom.emitvalueasnumber: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn | (num: number, event: Event) => void | Callback function that receives the input element's numeric value (may be NaN) | | options | [EmitOptions](#dom-emitoptions) | _(Optional)_ | **Returns:** (event: Event) => void Event handler function that can be used with event listeners ## dom.emitvalueasnumber: Example 1```typescript const age = prop(0) html.input( attr.type('number'), attr.value(age.map(String)), on.input(emitValueAsNumber(value => { if (!isNaN(value)) { age.value = value } })) ) ``` ## dom.emitvalueasnumber: Example 2 ```typescript // With range input const volume = prop(50) html.input( attr.type('range'), attr.min('0'), attr.max('100'), attr.value(volume.map(String)), on.input(emitValueAsNumber(value => volume.value = value)) ) ``` --- ## dom.empty: Empty variable Represents an empty renderable object. **Signature:**```typescript Empty: Renderable ``` --- ## dom.ensure: Ensure() function Conditionally renders content based on whether a value is non-null/non-undefined. This function provides a type-safe way to handle nullable values in your UI. It only renders the `then` content when the value is not null or undefined, and optionally renders alternative content when the value is null/undefined. **Signature:**```typescript Ensure: (value: NillifyValue, then: (value: Signal>) => TNode, otherwise?: () => TNode) => Renderable ```## dom.ensure: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | [NillifyValue](#dom-nillifyvalue)<T> | A signal or literal value that may be null or undefined | | then | (value: Signal<[NonNillable](#dom-nonnillable)<T>>) => [TNode](#dom-tnode) | Function that receives a signal of the non-nullable value and returns content to render | | otherwise | () => [TNode](#dom-tnode) | _(Optional)_ Optional function that returns content to render when value is null/undefined | **Returns:** [Renderable](#dom-renderable) A renderable that conditionally displays content based on the value's nullability ## dom.ensure: Example 1```typescript // With a signal that might be null const user = prop(null) Ensure(user, (userSignal) => html.div('Welcome, ', userSignal.map(u => u.name)), () => html.div('Please log in') ) ``` ## dom.ensure: Example 2 ```typescript // With a literal value const maybeData = getData() // returns string | null Ensure(maybeData, (dataSignal) => html.div('Data: ', dataSignal), () => html.div('No data available') ) ``` --- ## dom.ensureall: EnsureAll() function Conditionally renders content only when ALL provided values are non-null/non-undefined. This function is useful when you need multiple values to be present before rendering content. It waits for all values to be non-null/non-undefined before calling the callback function. If any value becomes null/undefined, it will render the `otherwise` content instead. **Signature:**```typescript EnsureAll: []>(...signals: { [K in keyof T]: NillifyValue; }) => (callback: (...values: { [K in keyof T]: Signal ? U : never>>; }) => TNode, otherwise?: () => TNode) => Renderable ```## dom.ensureall: Parameters | Parameter | Type | Description | | --- | --- | --- | | signals | { \[K in keyof T\]: [NillifyValue](#dom-nillifyvalue)<T\[K\]>; } | Variable number of values (signals or literals) that may be null/undefined | **Returns:** (callback: (...values: { \[K in keyof T\]: Signal<[NonNillable](#dom-nonnillable)<T\[K\] extends Value<infer U> ? U : never>>; }) => [TNode](#dom-tnode), otherwise?: () => [TNode](#dom-tnode)) => [Renderable](#dom-renderable) A function that takes a callback and optional otherwise function, returning a renderable ## dom.ensureall: Example 1```typescript const user = prop(null) const profile = prop(null) const settings = prop(null) EnsureAll(user, profile, settings)( (userSignal, profileSignal, settingsSignal) => html.div( html.h1('Dashboard'), html.div('User: ', userSignal.map(u => u.name)), html.div('Profile: ', profileSignal.map(p => p.bio)), html.div('Theme: ', settingsSignal.map(s => s.theme)) ), () => html.div('Loading user data...') ) ``` ## dom.ensureall: Example 2 ```typescript // Mix of signals and literal values const apiData = prop(null) const staticConfig = { theme: 'dark' } EnsureAll(apiData, staticConfig)( (dataSignal, configSignal) => html.div( 'Data loaded with theme: ', configSignal.map(c => c.theme) ), () => html.div('Waiting for data...') ) ``` --- ## dom.excludefromstyle: ExcludeFromStyle type Represents a set of properties or values that are excluded from the CSSStyleDeclaration interface. **Signature:**```typescript export type ExcludeFromStyle = 'getPropertyPriority' | 'getPropertyValue' | 'item' | 'removeProperty' | 'setProperty' | 'parentRule' | 'length' | 'name' | number | typeof Symbol.iterator; ``` --- ## dom.foreach: ForEach() function Efficiently renders a dynamic list of items from an array signal. This function creates a reactive list that automatically updates when the source array changes. Each item in the array gets its own signal that tracks changes to that specific item. The list efficiently handles additions, removals, and modifications to the array. **Signature:**```typescript ForEach: (value: Value, item: (value: Signal, position: ElementPosition) => TNode, separator?: (pos: ElementPosition) => TNode) => Renderable ```## dom.foreach: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | Value<T\[\]> | A signal or literal array to iterate over | | item | (value: Signal<T>, position: ElementPosition) => [TNode](#dom-tnode) | Function that renders each item, receives the item signal and position info | | separator | (pos: ElementPosition) => [TNode](#dom-tnode) | _(Optional)_ Optional function that renders content between items | **Returns:** [Renderable](#dom-renderable) A renderable that displays the dynamic list ## dom.foreach: Example 1```typescript const todos = prop([ { id: 1, text: 'Learn Tempo', done: false }, { id: 2, text: 'Build an app', done: false } ]) ForEach(todos, (todoSignal, position) => html.div( html.input( attr.type('checkbox'), attr.checked(todoSignal.map(t => t.done)) ), html.span(todoSignal.map(t => t.text)), html.small(`Item ${position.index + 1}`) ) ) ``` ## dom.foreach: Example 2 ```typescript // With separators between items const items = prop(['apple', 'banana', 'cherry']) ForEach(items, (itemSignal) => html.span(itemSignal), () => html.span(', ') // Separator between items ) // Renders: apple, banana, cherry ``` ## dom.foreach: Example 3 ```typescript // Using position information const numbers = prop([10, 20, 30]) ForEach(numbers, (numberSignal, position) => html.div( `Position ${position.index}: `, numberSignal, position.isFirst ? ' (first)' : '', position.isLast ? ' (last)' : '' ) ) ``` --- ## dom.fragment: Fragment() function Creates a fragment renderable that represents a collection of child renderables. The Fragment itself does not render any DOM elements. Instead, it renders the child renderables in the given DOM context. It can be used any time a single Renderable/TNode is expected, but multiple renderables are needed. **Signature:**```typescript Fragment: (...children: TNode[]) => Renderable ```## dom.fragment: Parameters | Parameter | Type | Description | | --- | --- | --- | | children | [TNode](#dom-tnode)<T>\[\] | The child renderables to include in the fragment. | **Returns:** [Renderable](#dom-renderable)<T> A renderable object that renders the child renderables in the given DOM context. --- ## dom.getwindow: getWindow() function **Signature:**```typescript getWindow: () => Window | undefined ``` **Returns:** Window \| undefined --- ## dom.globalprobe: GlobalProbe variable **Signature:**```typescript GlobalProbe: Provider<() => void, ProbeOptions> ``` --- ## dom.handleroptions: HandlerOptions type Options for event listeners. **Signature:**```typescript export type HandlerOptions = { once?: boolean; signal?: AbortSignal; passive?: boolean; capture?: boolean; }; ``` --- ## dom.headlessadapter._constructor_: HeadlessAdapter.(constructor) Constructs a new instance of the `HeadlessAdapter` class **Signature:**```typescript constructor({ select, getAttribute, setAttribute, getClass, setClass, getStyles, setStyles, appendHTML, getInnerHTML, setInnerHTML, getInnerText, setInnerText, }: { select: (selector: string) => EL[]; getAttribute: (el: EL, attr: string) => string | null; setAttribute: (el: EL, attr: string, value: string | null) => void; getClass: (el: EL) => string | null; setClass: (el: EL, cls: string | null) => void; getStyles: (el: EL) => Record; setStyles: (el: EL, styles: Record) => void; appendHTML: (el: EL, html: string) => void; getInnerHTML: (el: EL) => string | null; setInnerHTML: (el: EL, html: string) => void; getInnerText: (el: EL) => string | null; setInnerText: (el: EL, text: string) => void; }); ```## dom.headlessadapter._constructor_: Parameters | Parameter | Type | Description | | --- | --- | --- | | { select, getAttribute, setAttribute, getClass, setClass, getStyles, setStyles, appendHTML, getInnerHTML, setInnerHTML, getInnerText, setInnerText, } | { select: (selector: string) => EL\[\]; getAttribute: (el: EL, attr: string) => string \\| null; setAttribute: (el: EL, attr: string, value: string \\| null) => void; getClass: (el: EL) => string \\| null; setClass: (el: EL, cls: string \\| null) => void; getStyles: (el: EL) => Record<string, string>; setStyles: (el: EL, styles: Record<string, string>) => void; appendHTML: (el: EL, html: string) => void; getInnerHTML: (el: EL) => string \\| null; setInnerHTML: (el: EL, html: string) => void; getInnerText: (el: EL) => string \\| null; setInnerText: (el: EL, text: string) => void; } | | --- ## dom.headlessadapter.appendhtml: HeadlessAdapter.appendHTML property Appends HTML to an element. **Signature:**```typescript readonly appendHTML: (el: EL, html: string) => void; ``` --- ## dom.headlessadapter.getattribute: HeadlessAdapter.getAttribute property Gets the value of an attribute from an element. **Signature:**```typescript readonly getAttribute: (el: EL, attr: string) => string | null; ``` --- ## dom.headlessadapter.getclass: HeadlessAdapter.getClass property Gets the class of an element. **Signature:**```typescript readonly getClass: (el: EL) => string | null; ``` --- ## dom.headlessadapter.getinnerhtml: HeadlessAdapter.getInnerHTML property Gets the inner HTML of an element. **Signature:**```typescript readonly getInnerHTML: (el: EL) => string | null; ``` --- ## dom.headlessadapter.getinnertext: HeadlessAdapter.getInnerText property Gets the inner text of an element. **Signature:**```typescript readonly getInnerText: (el: EL) => string | null; ``` --- ## dom.headlessadapter.getstyles: HeadlessAdapter.getStyles property Gets the styles of an element. **Signature:**```typescript readonly getStyles: (el: EL) => Record; ``` --- ## dom.headlessadapter: HeadlessAdapter class Represents an adapter for headless rendering environments. This class provides methods to interact with elements in a headless context. This class is used to adapt the HeadlesContext to whatever you want to use to render your final HTML. You can use libraries like cheerio to render your HTML. For cheerio an adapter could look like this:```ts const renderWithCheerio = (html: string, root: HeadlessPortal) => { const $ = cheerio.load(html) const adapter = new HeadlessAdapter>({ select: (selector: string): cheerio.Cheerio[] => [$(selector)], getAttribute: (el, name: string) => el.attr(name) ?? null, setAttribute: (el, name: string, value: string | null) => { if (value === null) { el.removeAttr(name) } else { el.attr(name, value) } }, getClass: el => el.attr('class') ?? '', setClass: (el, value: string | null) => { if (value === null) { el.removeAttr('class') } else { el.attr('class', value) } }, getStyles: el => el.attr('style') ?? {}, setStyles: (el, value: Record) => { if (Object.keys(value).length === 0) { el.removeAttr('style') } else { el.css(value) } }, appendHTML: (el, html) => el.append(html), getInnerHTML: el => el.html() ?? '', setInnerHTML: (el, html) => el.html(html), getInnerText: el => el.text() ?? '', setInnerText: (el, text) => el.text(text), }) adapter.setFromRoot(root, true) return $.html() } ``` This function will return the rendered HTML as a string. **Signature:** ```typescript export declare class HeadlessAdapter ```## dom.headlessadapter: Constructors | Constructor | Modifiers | Description | | --- | --- | --- | | [(constructor)({ select, getAttribute, setAttribute, getClass, setClass, getStyles, setStyles, appendHTML, getInnerHTML, setInnerHTML, getInnerText, setInnerText, })](#dom-headlessadapter-constructor) | | Constructs a new instance of the `HeadlessAdapter` class | ## dom.headlessadapter: Properties | Property | Modifiers | Type | Description | | --- | --- | --- | --- | | [appendHTML](#dom-headlessadapter-appendhtml) | `readonly` | (el: EL, html: string) => void | Appends HTML to an element. | | [getAttribute](#dom-headlessadapter-getattribute) | `readonly` | (el: EL, attr: string) => string \\| null | Gets the value of an attribute from an element. | | [getClass](#dom-headlessadapter-getclass) | `readonly` | (el: EL) => string \\| null | Gets the class of an element. | | [getInnerHTML](#dom-headlessadapter-getinnerhtml) | `readonly` | (el: EL) => string \\| null | Gets the inner HTML of an element. | | [getInnerText](#dom-headlessadapter-getinnertext) | `readonly` | (el: EL) => string \\| null | Gets the inner text of an element. | | [getStyles](#dom-headlessadapter-getstyles) | `readonly` | (el: EL) => Record<string, string> | Gets the styles of an element. | | [select](#dom-headlessadapter-select) | `readonly` | (selector: string) => EL\[\] | Selects elements from the headless environment. | | [setAttribute](#dom-headlessadapter-setattribute) | `readonly` | (el: EL, attr: string, value: string \\| null) => void | Sets the value of an attribute on an element. | | [setClass](#dom-headlessadapter-setclass) | `readonly` | (el: EL, cls: string \\| null) => void | Sets the class of an element. | | [setFromRoot](#dom-headlessadapter-setfromroot) | `readonly` | (root: [HeadlessPortal](#dom-headlessportal), setPlaceholders: boolean) => void | Sets the content of the root element from a HeadlessPortal. Generally this will be the same instance that is returned by `runHeadless`. | | [setInnerHTML](#dom-headlessadapter-setinnerhtml) | `readonly` | (el: EL, html: string) => void | Sets the inner HTML of an element. | | [setInnerText](#dom-headlessadapter-setinnertext) | `readonly` | (el: EL, text: string) => void | Sets the inner text of an element. | | [setStyles](#dom-headlessadapter-setstyles) | `readonly` | (el: EL, styles: Record<string, string>) => void | Sets the styles of an element. | --- ## dom.headlessadapter.select: HeadlessAdapter.select property Selects elements from the headless environment. **Signature:**```typescript readonly select: (selector: string) => EL[]; ``` --- ## dom.headlessadapter.setattribute: HeadlessAdapter.setAttribute property Sets the value of an attribute on an element. **Signature:**```typescript readonly setAttribute: (el: EL, attr: string, value: string | null) => void; ``` --- ## dom.headlessadapter.setclass: HeadlessAdapter.setClass property Sets the class of an element. **Signature:**```typescript readonly setClass: (el: EL, cls: string | null) => void; ``` --- ## dom.headlessadapter.setfromroot: HeadlessAdapter.setFromRoot property Sets the content of the root element from a HeadlessPortal. Generally this will be the same instance that is returned by `runHeadless`. **Signature:**```typescript readonly setFromRoot: (root: HeadlessPortal, setPlaceholders: boolean) => void; ``` --- ## dom.headlessadapter.setinnerhtml: HeadlessAdapter.setInnerHTML property Sets the inner HTML of an element. **Signature:**```typescript readonly setInnerHTML: (el: EL, html: string) => void; ``` --- ## dom.headlessadapter.setinnertext: HeadlessAdapter.setInnerText property Sets the inner text of an element. **Signature:**```typescript readonly setInnerText: (el: EL, text: string) => void; ``` --- ## dom.headlessadapter.setstyles: HeadlessAdapter.setStyles property Sets the styles of an element. **Signature:**```typescript readonly setStyles: (el: EL, styles: Record) => void; ``` --- ## dom.headlesscontainer.currenturl: HeadlessContainer.currentURL property **Signature:**```typescript currentURL: Prop; ``` --- ## dom.headlesscontainer: HeadlessContainer interface **Signature:**```typescript export interface HeadlessContainer ```## dom.headlesscontainer: Properties | Property | Modifiers | Type | Description | | --- | --- | --- | --- | | [currentURL](#dom-headlesscontainer-currenturl) | | Prop<string> | | --- ## dom.headlesscontext._constructor_: HeadlessContext.(constructor) Constructs a new instance of the `HeadlessContext` class **Signature:**```typescript constructor(element: HeadlessBase, reference: HeadlessNode | undefined, container: HeadlessContainer, providers: Providers); ```## dom.headlesscontext._constructor_: Parameters | Parameter | Type | Description | | --- | --- | --- | | element | HeadlessBase | | | reference | [HeadlessNode](#dom-headlessnode) \\| undefined | | | container | [HeadlessContainer](#dom-headlesscontainer) | | | providers | [Providers](#dom-providers) | | --- ## dom.headlesscontext.addclasses: HeadlessContext.addClasses property **Signature:**```typescript readonly addClasses: (tokens: string[]) => void; ``` --- ## dom.headlesscontext.appendorinsert: HeadlessContext.appendOrInsert property **Signature:**```typescript readonly appendOrInsert: (element: HeadlessNode) => void; ``` --- ## dom.headlesscontext.clear: HeadlessContext.clear property **Signature:**```typescript readonly clear: (removeTree: boolean) => void; ``` --- ## dom.headlesscontext.container: HeadlessContext.container property **Signature:**```typescript readonly container: HeadlessContainer; ``` --- ## dom.headlesscontext.element: HeadlessContext.element property **Signature:**```typescript readonly element: HeadlessBase; ``` --- ## dom.headlesscontext.getclasses: HeadlessContext.getClasses property **Signature:**```typescript readonly getClasses: () => string[]; ``` --- ## dom.headlesscontext.getprovider: HeadlessContext.getProvider property **Signature:**```typescript readonly getProvider: (mark: ProviderMark) => { value: T; onUse: (() => void) | undefined; }; ``` --- ## dom.headlesscontext.getstyle: HeadlessContext.getStyle property **Signature:**```typescript readonly getStyle: (name: string) => string; ``` --- ## dom.headlesscontext.gettext: HeadlessContext.getText property **Signature:**```typescript readonly getText: () => string; ``` --- ## dom.headlesscontext.isbrowser: HeadlessContext.isBrowser property **Signature:**```typescript readonly isBrowser: () => this is BrowserContext; ``` --- ## dom.headlesscontext.isbrowserdom: HeadlessContext.isBrowserDOM property **Signature:**```typescript readonly isBrowserDOM: () => this is BrowserContext; ``` --- ## dom.headlesscontext.isheadless: HeadlessContext.isHeadless property **Signature:**```typescript readonly isHeadless: () => this is HeadlessContext; ``` --- ## dom.headlesscontext.isheadlessdom: HeadlessContext.isHeadlessDOM property **Signature:**```typescript readonly isHeadlessDOM: () => this is HeadlessContext; ``` --- ## dom.headlesscontext.makeaccessors: HeadlessContext.makeAccessors property **Signature:**```typescript readonly makeAccessors: (name: string) => { get(): unknown; set(value: unknown): void; }; ``` --- ## dom.headlesscontext.makechildelement: HeadlessContext.makeChildElement property **Signature:**```typescript readonly makeChildElement: (tagName: string, namespace: string | undefined) => DOMContext; ``` --- ## dom.headlesscontext.makechildtext: HeadlessContext.makeChildText property **Signature:**```typescript readonly makeChildText: (text: string) => DOMContext; ``` --- ## dom.headlesscontext.makeportal: HeadlessContext.makePortal property **Signature:**```typescript readonly makePortal: (selector: string | HTMLElement) => DOMContext; ``` --- ## dom.headlesscontext.makeref: HeadlessContext.makeRef property **Signature:**```typescript readonly makeRef: () => DOMContext; ``` --- ## dom.headlesscontext: HeadlessContext class **Signature:**```typescript export declare class HeadlessContext implements DOMContext ```**Implements:** [DOMContext](#dom-domcontext) ## dom.headlesscontext: Constructors | Constructor | Modifiers | Description | | --- | --- | --- | | [(constructor)(element, reference, container, providers)](#dom-headlesscontext-constructor) | | Constructs a new instance of the `HeadlessContext` class | ## dom.headlesscontext: Properties | Property | Modifiers | Type | Description | | --- | --- | --- | --- | | [addClasses](#dom-headlesscontext-addclasses) | `readonly` | (tokens: string\[\]) => void | | | [appendOrInsert](#dom-headlesscontext-appendorinsert) | `readonly` | (element: [HeadlessNode](#dom-headlessnode)) => void | | | [clear](#dom-headlesscontext-clear) | `readonly` | (removeTree: boolean) => void | | | [container](#dom-headlesscontext-container) | `readonly` | [HeadlessContainer](#dom-headlesscontainer) | | | [element](#dom-headlesscontext-element) | `readonly` | HeadlessBase | | | [getClasses](#dom-headlesscontext-getclasses) | `readonly` | () => string\[\] | | | [getProvider](#dom-headlesscontext-getprovider) | `readonly` | <T>(mark: ProviderMark<T>) => { value: T; onUse: (() => void) \\| undefined; } | | | [getStyle](#dom-headlesscontext-getstyle) | `readonly` | (name: string) => string | | | [getText](#dom-headlesscontext-gettext) | `readonly` | () => string | | | [isBrowser](#dom-headlesscontext-isbrowser) | `readonly` | () => this is [BrowserContext](#dom-browsercontext) | | | [isBrowserDOM](#dom-headlesscontext-isbrowserdom) | `readonly` | () => this is [BrowserContext](#dom-browsercontext) | | | [isHeadless](#dom-headlesscontext-isheadless) | `readonly` | () => this is [HeadlessContext](#dom-headlesscontext) | | | [isHeadlessDOM](#dom-headlesscontext-isheadlessdom) | `readonly` | () => this is [HeadlessContext](#dom-headlesscontext) | | | [makeAccessors](#dom-headlesscontext-makeaccessors) | `readonly` | (name: string) => { get(): unknown; set(value: unknown): void; } | | | [makeChildElement](#dom-headlesscontext-makechildelement) | `readonly` | (tagName: string, namespace: string \\| undefined) => [DOMContext](#dom-domcontext) | | | [makeChildText](#dom-headlesscontext-makechildtext) | `readonly` | (text: string) => [DOMContext](#dom-domcontext) | | | [makePortal](#dom-headlesscontext-makeportal) | `readonly` | (selector: string \\| HTMLElement) => [DOMContext](#dom-domcontext) | | | [makeRef](#dom-headlesscontext-makeref) | `readonly` | () => [DOMContext](#dom-domcontext) | | | [on](#dom-headlesscontext-on) | `readonly` | <E>(event: string, listener: (event: E, ctx: [HeadlessContext](#dom-headlesscontext)) => void) => Clear | | | [providers](#dom-headlesscontext-providers) | `readonly` | [Providers](#dom-providers) | | | [reference](#dom-headlesscontext-reference) | `readonly` | [HeadlessNode](#dom-headlessnode) \\| undefined | | | [removeClasses](#dom-headlesscontext-removeclasses) | `readonly` | (tokens: string\[\]) => void | | | [setProvider](#dom-headlesscontext-setprovider) | `readonly` | <T>(mark: ProviderMark<T>, value: T, onUse: undefined \\| (() => void)) => [DOMContext](#dom-domcontext) | Sets a provider for the given provider mark. | | [setStyle](#dom-headlesscontext-setstyle) | `readonly` | (name: string, value: string) => void | | | [setText](#dom-headlesscontext-settext) | `readonly` | (text: string) => void | | --- ## dom.headlesscontext.on: HeadlessContext.on property **Signature:**```typescript readonly on: (event: string, listener: (event: E, ctx: HeadlessContext) => void) => Clear; ``` --- ## dom.headlesscontext.providers: HeadlessContext.providers property **Signature:**```typescript readonly providers: Providers; ``` --- ## dom.headlesscontext.reference: HeadlessContext.reference property **Signature:**```typescript readonly reference: HeadlessNode | undefined; ``` --- ## dom.headlesscontext.removeclasses: HeadlessContext.removeClasses property **Signature:**```typescript readonly removeClasses: (tokens: string[]) => void; ``` --- ## dom.headlesscontext.setprovider: HeadlessContext.setProvider property Sets a provider for the given provider mark. **Signature:**```typescript readonly setProvider: (mark: ProviderMark, value: T, onUse: undefined | (() => void)) => DOMContext; ``` --- ## dom.headlesscontext.setstyle: HeadlessContext.setStyle property **Signature:**```typescript readonly setStyle: (name: string, value: string) => void; ``` --- ## dom.headlesscontext.settext: HeadlessContext.setText property **Signature:**```typescript readonly setText: (text: string) => void; ``` --- ## dom.headlesselement._constructor_: HeadlessElement.(constructor) Constructs a new instance of the `HeadlessElement` class **Signature:**```typescript constructor(tagName: string, namespace: string | undefined, parent: HeadlessBase | undefined); ```## dom.headlesselement._constructor_: Parameters | Parameter | Type | Description | | --- | --- | --- | | tagName | string | | | namespace | string \\| undefined | | | parent | HeadlessBase \\| undefined | | --- ## dom.headlesselement.isportal: HeadlessElement.isPortal property **Signature:**```typescript readonly isPortal: () => this is HeadlessPortal; ``` --- ## dom.headlesselement: HeadlessElement class **Signature:**```typescript export declare class HeadlessElement extends HeadlessBase ```**Extends:** HeadlessBase ## dom.headlesselement: Constructors | Constructor | Modifiers | Description | | --- | --- | --- | | [(constructor)(tagName, namespace, parent)](#dom-headlesselement-constructor) | | Constructs a new instance of the `HeadlessElement` class | ## dom.headlesselement: Properties | Property | Modifiers | Type | Description | | --- | --- | --- | --- | | [isPortal](#dom-headlesselement-isportal) | `readonly` | () => this is [HeadlessPortal](#dom-headlessportal) | | | [namespace](#dom-headlesselement-namespace) | `readonly` | string \\| undefined | | | [tagName](#dom-headlesselement-tagname) | `readonly` | string | | | [toHTML](#dom-headlesselement-tohtml) | `readonly` | (generatePlaceholders?: boolean) => string | | ## dom.headlesselement: Methods | Method | Modifiers | Description | | --- | --- | --- | | [toHTMLStream(options)](#dom-headlesselement-tohtmlstream) | | Generates HTML output as an async stream of string chunks. Yields the opening tag, then each child's content, then the closing tag. | --- ## dom.headlesselement.namespace: HeadlessElement.namespace property **Signature:**```typescript readonly namespace: string | undefined; ``` --- ## dom.headlesselement.tagname: HeadlessElement.tagName property **Signature:**```typescript readonly tagName: string; ``` --- ## dom.headlesselement.tohtml: HeadlessElement.toHTML property **Signature:**```typescript readonly toHTML: (generatePlaceholders?: boolean) => string; ``` --- ## dom.headlesselement.tohtmlstream: HeadlessElement.toHTMLStream() method Generates HTML output as an async stream of string chunks. Yields the opening tag, then each child's content, then the closing tag. **Signature:**```typescript toHTMLStream(options?: StreamOptions): AsyncGenerator; ```## dom.headlesselement.tohtmlstream: Parameters | Parameter | Type | Description | | --- | --- | --- | | options | [StreamOptions](#dom-streamoptions) | _(Optional)_ Options for streaming output. String chunks of HTML content. | **Returns:** AsyncGenerator<string> --- ## dom.headlessnode: HeadlessNode type **Signature:**```typescript export type HeadlessNode = HeadlessElement | HeadlessPortal | HeadlessText; ``` **References:** [HeadlessElement](#dom-headlesselement), [HeadlessPortal](#dom-headlessportal), [HeadlessText](#dom-headlesstext) --- ## dom.headlessoptions: HeadlessOptions type Options for running a headless environment. **Signature:**```typescript export type HeadlessOptions = { startUrl?: Value; selector: string; providers?: Providers; }; ``` **References:** [Providers](#dom-providers) --- ## dom.headlessportal._constructor_: HeadlessPortal.(constructor) Constructs a new instance of the `HeadlessPortal` class **Signature:**```typescript constructor(selector: string | HTMLElement, parent: HeadlessBase | undefined); ```## dom.headlessportal._constructor_: Parameters | Parameter | Type | Description | | --- | --- | --- | | selector | string \\| HTMLElement | | | parent | HeadlessBase \\| undefined | | --- ## dom.headlessportal.contenttohtml: HeadlessPortal.contentToHTML property **Signature:**```typescript readonly contentToHTML: (generatePlaceholders?: boolean) => string; ``` --- ## dom.headlessportal.contenttohtmlstream: HeadlessPortal.contentToHTMLStream() method Streams the portal's content HTML. Unlike toHTMLStream, this yields the actual content for rendering at the target location. **Signature:**```typescript contentToHTMLStream(options?: StreamOptions): AsyncGenerator; ```## dom.headlessportal.contenttohtmlstream: Parameters | Parameter | Type | Description | | --- | --- | --- | | options | [StreamOptions](#dom-streamoptions) | _(Optional)_ Options for streaming output. String chunks of the portal's content. | **Returns:** AsyncGenerator<string> --- ## dom.headlessportal.isportal: HeadlessPortal.isPortal property **Signature:**```typescript readonly isPortal: () => this is HeadlessPortal; ``` --- ## dom.headlessportal: HeadlessPortal class **Signature:**```typescript export declare class HeadlessPortal extends HeadlessBase ```**Extends:** HeadlessBase ## dom.headlessportal: Constructors | Constructor | Modifiers | Description | | --- | --- | --- | | [(constructor)(selector, parent)](#dom-headlessportal-constructor) | | Constructs a new instance of the `HeadlessPortal` class | ## dom.headlessportal: Properties | Property | Modifiers | Type | Description | | --- | --- | --- | --- | | [contentToHTML](#dom-headlessportal-contenttohtml) | `readonly` | (generatePlaceholders?: boolean) => string | | | [isPortal](#dom-headlessportal-isportal) | `readonly` | () => this is [HeadlessPortal](#dom-headlessportal) | | | [selector](#dom-headlessportal-selector) | `readonly` | string \\| HTMLElement | | | [toHTML](#dom-headlessportal-tohtml) | `readonly` | () => string | | ## dom.headlessportal: Methods | Method | Modifiers | Description | | --- | --- | --- | | [contentToHTMLStream(options)](#dom-headlessportal-contenttohtmlstream) | | Streams the portal's content HTML. Unlike toHTMLStream, this yields the actual content for rendering at the target location. | | [toHTMLStream(options)](#dom-headlessportal-tohtmlstream) | | Portals don't render inline - they render at their target selector. This method yields nothing for the inline position. | --- ## dom.headlessportal.selector: HeadlessPortal.selector property **Signature:**```typescript readonly selector: string | HTMLElement; ``` --- ## dom.headlessportal.tohtml: HeadlessPortal.toHTML property **Signature:**```typescript readonly toHTML: () => string; ``` --- ## dom.headlessportal.tohtmlstream: HeadlessPortal.toHTMLStream() method Portals don't render inline - they render at their target selector. This method yields nothing for the inline position. **Signature:**```typescript toHTMLStream(options?: StreamOptions): AsyncGenerator; ```## dom.headlessportal.tohtmlstream: Parameters | Parameter | Type | Description | | --- | --- | --- | | options | [StreamOptions](#dom-streamoptions) | _(Optional)_ | **Returns:** AsyncGenerator<string> --- ## dom.headlesstext._constructor_: HeadlessText.(constructor) Constructs a new instance of the `HeadlessText` class **Signature:**```typescript constructor(text: string); ```## dom.headlesstext._constructor_: Parameters | Parameter | Type | Description | | --- | --- | --- | | text | string | | --- ## dom.headlesstext.gettext: HeadlessText.getText property **Signature:**```typescript readonly getText: () => string; ``` --- ## dom.headlesstext.id: HeadlessText.id property **Signature:**```typescript readonly id: string; ``` --- ## dom.headlesstext.iselement: HeadlessText.isElement property **Signature:**```typescript readonly isElement: () => this is HeadlessElement; ``` --- ## dom.headlesstext.istext: HeadlessText.isText property **Signature:**```typescript readonly isText: () => this is HeadlessText; ``` --- ## dom.headlesstext: HeadlessText class **Signature:**```typescript export declare class HeadlessText ```## dom.headlesstext: Constructors | Constructor | Modifiers | Description | | --- | --- | --- | | [(constructor)(text)](#dom-headlesstext-constructor) | | Constructs a new instance of the `HeadlessText` class | ## dom.headlesstext: Properties | Property | Modifiers | Type | Description | | --- | --- | --- | --- | | [getText](#dom-headlesstext-gettext) | `readonly` | () => string | | | [id](#dom-headlesstext-id) | `readonly` | string | | | [isElement](#dom-headlesstext-iselement) | `readonly` | () => this is [HeadlessElement](#dom-headlesselement) | | | [isText](#dom-headlesstext-istext) | `readonly` | () => this is [HeadlessText](#dom-headlesstext) | | | [text](#dom-headlesstext-text) | | string | | | [toHTML](#dom-headlesstext-tohtml) | `readonly` | () => string | | ## dom.headlesstext: Methods | Method | Modifiers | Description | | --- | --- | --- | | [toHTMLStream(options)](#dom-headlesstext-tohtmlstream) | | Streams the text content as a single chunk. | --- ## dom.headlesstext.text: HeadlessText.text property **Signature:**```typescript text: string; ``` --- ## dom.headlesstext.tohtml: HeadlessText.toHTML property **Signature:**```typescript readonly toHTML: () => string; ``` --- ## dom.headlesstext.tohtmlstream: HeadlessText.toHTMLStream() method Streams the text content as a single chunk. **Signature:**```typescript toHTMLStream(options?: StreamOptions): AsyncGenerator; ```## dom.headlesstext.tohtmlstream: Parameters | Parameter | Type | Description | | --- | --- | --- | | options | [StreamOptions](#dom-streamoptions) | _(Optional)_ Options (unused for text nodes, kept for API consistency). The text content. | **Returns:** AsyncGenerator<string> --- ## dom.html: html variable A convenience object to create Renderables for HTML elements. **Signature:**```typescript html: { a: (...children: TNode[]) => Renderable; abbr: (...children: TNode[]) => Renderable; address: (...children: TNode[]) => Renderable; area: (...children: TNode[]) => Renderable; article: (...children: TNode[]) => Renderable; aside: (...children: TNode[]) => Renderable; audio: (...children: TNode[]) => Renderable; b: (...children: TNode[]) => Renderable; base: (...children: TNode[]) => Renderable; bdi: (...children: TNode[]) => Renderable; bdo: (...children: TNode[]) => Renderable; blockquote: (...children: TNode[]) => Renderable; body: (...children: TNode[]) => Renderable; br: (...children: TNode[]) => Renderable; button: (...children: TNode[]) => Renderable; canvas: (...children: TNode[]) => Renderable; caption: (...children: TNode[]) => Renderable; cite: (...children: TNode[]) => Renderable; code: (...children: TNode[]) => Renderable; col: (...children: TNode[]) => Renderable; colgroup: (...children: TNode[]) => Renderable; data: (...children: TNode[]) => Renderable; datalist: (...children: TNode[]) => Renderable; dd: (...children: TNode[]) => Renderable; del: (...children: TNode[]) => Renderable; details: (...children: TNode[]) => Renderable; dfn: (...children: TNode[]) => Renderable; dialog: (...children: TNode[]) => Renderable; div: (...children: TNode[]) => Renderable; dl: (...children: TNode[]) => Renderable; dt: (...children: TNode[]) => Renderable; em: (...children: TNode[]) => Renderable; embed: (...children: TNode[]) => Renderable; fencedframe: (...children: TNode[]) => Renderable; fieldset: (...children: TNode[]) => Renderable; figcaption: (...children: TNode[]) => Renderable; figure: (...children: TNode[]) => Renderable; footer: (...children: TNode[]) => Renderable; form: (...children: TNode[]) => Renderable; h1: (...children: TNode[]) => Renderable; h2: (...children: TNode[]) => Renderable; h3: (...children: TNode[]) => Renderable; h4: (...children: TNode[]) => Renderable; h5: (...children: TNode[]) => Renderable; h6: (...children: TNode[]) => Renderable; head: (...children: TNode[]) => Renderable; header: (...children: TNode[]) => Renderable; hgroup: (...children: TNode[]) => Renderable; hr: (...children: TNode[]) => Renderable; html: (...children: TNode[]) => Renderable; i: (...children: TNode[]) => Renderable; iframe: (...children: TNode[]) => Renderable; img: (...children: TNode[]) => Renderable; input: (...children: TNode[]) => Renderable; ins: (...children: TNode[]) => Renderable; kbd: (...children: TNode[]) => Renderable; label: (...children: TNode[]) => Renderable; legend: (...children: TNode[]) => Renderable; li: (...children: TNode[]) => Renderable; link: (...children: TNode[]) => Renderable; main: (...children: TNode[]) => Renderable; map: (...children: TNode[]) => Renderable; mark: (...children: TNode[]) => Renderable; menu: (...children: TNode[]) => Renderable; meta: (...children: TNode[]) => Renderable; meter: (...children: TNode[]) => Renderable; nav: (...children: TNode[]) => Renderable; noscript: (...children: TNode[]) => Renderable; object: (...children: TNode[]) => Renderable; ol: (...children: TNode[]) => Renderable; optgroup: (...children: TNode[]) => Renderable; option: (...children: TNode[]) => Renderable; output: (...children: TNode[]) => Renderable; p: (...children: TNode[]) => Renderable; param: (...children: TNode[]) => Renderable; picture: (...children: TNode[]) => Renderable; portal: (...children: TNode[]) => Renderable; pre: (...children: TNode[]) => Renderable; progress: (...children: TNode[]) => Renderable; q: (...children: TNode[]) => Renderable; rp: (...children: TNode[]) => Renderable; rt: (...children: TNode[]) => Renderable; ruby: (...children: TNode[]) => Renderable; s: (...children: TNode[]) => Renderable; samp: (...children: TNode[]) => Renderable; script: (...children: TNode[]) => Renderable; search: (...children: TNode[]) => Renderable; section: (...children: TNode[]) => Renderable; select: (...children: TNode[]) => Renderable; slot: (...children: TNode[]) => Renderable; small: (...children: TNode[]) => Renderable; source: (...children: TNode[]) => Renderable; span: (...children: TNode[]) => Renderable; strong: (...children: TNode[]) => Renderable; style: (...children: TNode[]) => Renderable; sub: (...children: TNode[]) => Renderable; summary: (...children: TNode[]) => Renderable; sup: (...children: TNode[]) => Renderable; table: (...children: TNode[]) => Renderable; tbody: (...children: TNode[]) => Renderable; td: (...children: TNode[]) => Renderable; template: (...children: TNode[]) => Renderable; textarea: (...children: TNode[]) => Renderable; tfoot: (...children: TNode[]) => Renderable; th: (...children: TNode[]) => Renderable; thead: (...children: TNode[]) => Renderable; time: (...children: TNode[]) => Renderable; title: (...children: TNode[]) => Renderable; tr: (...children: TNode[]) => Renderable; track: (...children: TNode[]) => Renderable; u: (...children: TNode[]) => Renderable; ul: (...children: TNode[]) => Renderable; var: (...children: TNode[]) => Renderable; video: (...children: TNode[]) => Renderable; wbr: (...children: TNode[]) => Renderable; } ``` --- ## dom.htmlattributes: HTMLAttributes type Represents the HTML attributes that can be used in an HTML element. \*\*Security Warning:\*\* Some properties like `innerHTML` and `outerHTML` can introduce Cross-Site Scripting (XSS) vulnerabilities if used with untrusted user input. Always sanitize user-provided content before using these properties. **Signature:**```typescript export type HTMLAttributes = { accept: string; 'accept-charset': string; accesskey: string; action: string; align: string; allow: string; allowfullscreen: boolean; allowpaymentrequest: boolean; alt: string; as: string; async: boolean; autocapitalize: 'off' | 'none' | 'on' | 'sentences' | 'words' | 'characters'; autocomplete: string; autofocus: boolean; autoplay: boolean; bgcolor: string; border: string; capture: boolean | 'user' | 'environment'; charset: string; checked: boolean; cite: string; class: string; color: string; cols: number; colspan: number; content: string; contenteditable: boolean | 'true' | 'false' | 'plaintext-only'; controls: string; coords: string; crossorigin: 'anonymous' | 'use-credentials' | ''; data: string; datetime: string; decoding: 'sync' | 'async' | 'auto'; default: string; defer: string; dir: 'ltr' | 'rtl' | 'auto'; dirname: string; disabled: boolean; download: string; draggable: boolean | 'true' | 'false'; dropzone: string; enctype: string; enterkeyhint: 'enter' | 'done' | 'go' | 'next' | 'previous' | 'search' | 'send'; for: string; form: string; formaction: string; formenctype: string; formmethod: string; formnovalidate: boolean; formtarget: string; headers: string; height: string; hidden: 'until-found' | 'hidden' | '' | boolean; high: string; href: string; hreflang: string; 'http-equiv': string; icon: string; id: string; imagesizes: string; imagesrcset: string; inputmode: 'none' | 'text' | 'decimal' | 'numeric' | 'tel' | 'search' | 'email' | 'url'; integrity: string; is: string; ismap: string; itemid: string; itemprop: string; itemref: string; itemscope: boolean; itemtype: string; keytype: string; kind: string; label: string; lang: string; language: string; list: string; loading: 'eager' | 'lazy'; loop: string; low: string; manifest: string; max: number; maxlength: number; media: string; method: string; min: number; minlength: number; multiple: boolean; muted: boolean; name: string; nonce: string; novalidate: string; open: string; optimum: string; part: string; pattern: string; ping: string; placeholder: string; playsinline: boolean; popover: 'auto' | 'manual' | ''; popovertarget: string; popovertargetaction: 'hide' | 'show' | 'toggle'; poster: string; preload: string; property: string; radiogroup: string; readonly: boolean; referrerpolicy: 'no-referrer' | 'no-referrer-when-downgrade' | 'origin' | 'origin-when-cross-origin' | 'same-origin' | 'strict-origin' | 'strict-origin-when-cross-origin' | 'unsafe-url'; rel: string; required: string; reversed: string; role: string; rows: number; rowspan: number; sandbox: string; scope: string; scoped: string; seamless: string; selected: boolean; shape: string; size: number; sizes: string; slot: string; span: string; spellcheck: boolean | 'true' | 'false'; src: string; srcdoc: string; srclang: string; srcset: string; start: string; step: number; style: string; tabindex: number; target: string; title: string; translate: 'yes' | 'no'; type: string; usemap: string; value: string; valueAsNumber: number; valueAsDate: Date; width: string; wrap: string; textContent: string; innerText: string; innerHTML: string; outerHTML: string; }; ``` --- ## dom.htmlevents: HTMLEvents type Represents a mapping of HTML event names to their corresponding event types. **Signature:**```typescript export type HTMLEvents = { abort: Event; afterprint: Event; animationcancel: AnimationEvent; animationend: AnimationEvent; animationiteration: AnimationEvent; animationstart: AnimationEvent; auxclick: MouseEvent; beforeinput: InputEvent; beforeprint: Event; beforeunload: BeforeUnloadEvent; blur: FocusEvent; cancel: Event; canplay: Event; canplaythrough: Event; change: Event; click: MouseEvent; close: Event; compositionend: CompositionEvent; compositionstart: CompositionEvent; compositionupdate: CompositionEvent; contextmenu: MouseEvent; copy: ClipboardEvent; cuechange: Event; cut: ClipboardEvent; dblclick: MouseEvent; drag: DragEvent; dragend: DragEvent; dragenter: DragEvent; dragexit: Event; dragleave: DragEvent; dragover: DragEvent; dragstart: DragEvent; drop: DragEvent; durationchange: Event; emptied: Event; ended: Event; error: ErrorEvent; focus: FocusEvent; focusin: FocusEvent; focusout: FocusEvent; formdata: FormDataEvent; fullscreenchange: Event; fullscreenerror: Event; gotpointercapture: PointerEvent; hashchange: HashChangeEvent; input: Event; invalid: Event; keydown: KeyboardEvent; keypress: KeyboardEvent; keyup: KeyboardEvent; languagechange: Event; load: Event; loadeddata: Event; loadedmetadata: Event; loadend: ProgressEvent; loadstart: ProgressEvent; lostpointercapture: PointerEvent; message: MessageEvent; messageerror: MessageEvent; mousedown: MouseEvent; mouseenter: MouseEvent; mouseleave: MouseEvent; mousemove: MouseEvent; mouseout: MouseEvent; mouseover: MouseEvent; mouseup: MouseEvent; offline: Event; online: Event; orientationchange: Event; pagehide: PageTransitionEvent; pageshow: PageTransitionEvent; paste: ClipboardEvent; pause: Event; play: Event; playing: Event; pointercancel: PointerEvent; pointerdown: PointerEvent; pointerenter: PointerEvent; pointerleave: PointerEvent; pointerlockchange: Event; pointerlockerror: Event; pointermove: PointerEvent; pointerout: PointerEvent; pointerover: PointerEvent; pointerrawupdate: PointerEvent; pointerup: PointerEvent; popstate: PopStateEvent; progress: ProgressEvent; ratechange: Event; readystatechange: Event; rejectionhandled: PromiseRejectionEvent; reset: Event; resize: UIEvent; scroll: Event; scrollend: Event; securitypolicyviolation: SecurityPolicyViolationEvent; seeked: Event; seeking: Event; select: Event; selectionchange: Event; selectstart: Event; slotchange: Event; stalled: Event; storage: StorageEvent; submit: SubmitEvent; suspend: Event; timeupdate: Event; toggle: Event; touchcancel: TouchEvent; touchend: TouchEvent; touchmove: TouchEvent; touchstart: TouchEvent; transitioncancel: TransitionEvent; transitionend: TransitionEvent; transitionrun: TransitionEvent; transitionstart: TransitionEvent; unhandledrejection: PromiseRejectionEvent; unload: Event; visibilitychange: Event; volumechange: Event; waiting: Event; wheel: WheelEvent; }; ``` --- ## dom.htmltags: HTMLTags type Represents a mapping of HTML tag names to their corresponding element types. **Signature:**```typescript export type HTMLTags = { a: HTMLAnchorElement; abbr: HTMLElement; address: HTMLElement; area: HTMLAreaElement; article: HTMLElement; aside: HTMLElement; audio: HTMLAudioElement; b: HTMLElement; base: HTMLBaseElement; bdi: HTMLElement; bdo: HTMLElement; blockquote: HTMLQuoteElement; body: HTMLBodyElement; br: HTMLBRElement; button: HTMLButtonElement; canvas: HTMLCanvasElement; caption: HTMLTableCaptionElement; cite: HTMLElement; code: HTMLElement; col: HTMLTableColElement; colgroup: HTMLTableColElement; data: HTMLDataElement; datalist: HTMLDataListElement; dd: HTMLElement; del: HTMLModElement; details: HTMLDetailsElement; dfn: HTMLElement; dialog: HTMLDialogElement; div: HTMLDivElement; dl: HTMLDListElement; dt: HTMLElement; em: HTMLElement; embed: HTMLEmbedElement; fencedframe: HTMLElement; fieldset: HTMLFieldSetElement; figcaption: HTMLElement; figure: HTMLElement; footer: HTMLElement; form: HTMLFormElement; h1: HTMLHeadingElement; h2: HTMLHeadingElement; h3: HTMLHeadingElement; h4: HTMLHeadingElement; h5: HTMLHeadingElement; h6: HTMLHeadingElement; head: HTMLHeadElement; header: HTMLElement; hgroup: HTMLElement; hr: HTMLHRElement; html: HTMLHtmlElement; i: HTMLElement; iframe: HTMLIFrameElement; img: HTMLImageElement; input: HTMLInputElement; ins: HTMLModElement; kbd: HTMLElement; label: HTMLLabelElement; legend: HTMLLegendElement; li: HTMLLIElement; link: HTMLLinkElement; main: HTMLElement; map: HTMLMapElement; mark: HTMLElement; menu: HTMLMenuElement; meta: HTMLMetaElement; meter: HTMLMeterElement; nav: HTMLElement; noscript: HTMLElement; object: HTMLObjectElement; ol: HTMLOListElement; optgroup: HTMLOptGroupElement; option: HTMLOptionElement; output: HTMLOutputElement; p: HTMLParagraphElement; param: HTMLParamElement; picture: HTMLPictureElement; portal: HTMLElement; pre: HTMLPreElement; progress: HTMLProgressElement; q: HTMLQuoteElement; rp: HTMLElement; rt: HTMLElement; ruby: HTMLElement; s: HTMLElement; samp: HTMLElement; script: HTMLScriptElement; search: HTMLElement; section: HTMLElement; select: HTMLSelectElement; slot: HTMLSlotElement; small: HTMLElement; source: HTMLSourceElement; span: HTMLSpanElement; strong: HTMLElement; style: HTMLStyleElement; sub: HTMLElement; summary: HTMLElement; sup: HTMLElement; table: HTMLTableElement; tbody: HTMLTableSectionElement; td: HTMLTableCellElement; template: HTMLTemplateElement; textarea: HTMLTextAreaElement; tfoot: HTMLTableSectionElement; th: HTMLTableCellElement; thead: HTMLTableSectionElement; time: HTMLTimeElement; title: HTMLTitleElement; tr: HTMLTableRowElement; track: HTMLTrackElement; u: HTMLElement; ul: HTMLUListElement; var: HTMLElement; video: HTMLVideoElement; wbr: HTMLElement; }; ``` --- ## dom.hydration_id_attr: HYDRATION\_ID\_ATTR variable Attribute name for hydration IDs. Used to match server-rendered elements with client-side renderables during hydration. **Signature:**```typescript HYDRATION_ID_ATTR = "data-tempo-id" ``` --- ## dom.id: Id type **Signature:**```typescript export type Id = {} & { [P in keyof T]: T[P]; }; ``` --- ## dom.iframe: IFrame() function Creates an iframe element and optionally renders content into its document. When children are provided, they are rendered into the iframe's contentDocument. This allows you to create isolated DOM contexts with their own styles and scripts. **Signature:**```typescript export declare function IFrame({ src, name, width, height, sandbox, allow, referrerpolicy, loading, iframeChild, onLoad, }?: IFrameOptions, ...children: TNode[]): import('..').Renderable; ```## dom.iframe: Parameters | Parameter | Type | Description | | --- | --- | --- | | { src, name, width, height, sandbox, allow, referrerpolicy, loading, iframeChild, onLoad, } | [IFrameOptions](#dom-iframeoptions) | _(Optional)_ | | children | [TNode](#dom-tnode)\[\] | Optional content to render inside the iframe's document | **Returns:** import('..').[Renderable](#dom-renderable) A renderable that creates and manages the iframe ## dom.iframe: Example 1```typescript // Simple iframe with src IFrame({ src: 'https://example.com', width: 800, height: 600 }) ``` ## dom.iframe: Example 2 ```typescript // Iframe with rendered content IFrame( { width: 800, height: 600 }, html.div( html.style('body { font-family: sans-serif; }'), html.h1('Hello from iframe!'), html.p('This content is rendered inside the iframe') ) ) ``` ## dom.iframe: Example 3 ```typescript // Iframe with onLoad callback IFrame( { width: 800, height: 600, onLoad: (iframe, doc) => { console.log('Iframe loaded:', doc.title) } }, html.div('Content') ) ``` --- ## dom.iframeoptions.allow: IFrameOptions.allow property The allow attribute for the iframe. **Signature:**```typescript allow?: Value; ``` --- ## dom.iframeoptions.height: IFrameOptions.height property The height of the iframe. **Signature:**```typescript height?: SplitValue; ``` --- ## dom.iframeoptions.iframechild: IFrameOptions.iframeChild property Content to attach directly to the iframe's element, not the document body. **Signature:**```typescript iframeChild?: TNode; ``` --- ## dom.iframeoptions.loading: IFrameOptions.loading property The loading attribute for the iframe. **Signature:**```typescript loading?: Value<'eager' | 'lazy'>; ``` --- ## dom.iframeoptions: IFrameOptions interface **Signature:**```typescript export interface IFrameOptions ```## dom.iframeoptions: Properties | Property | Modifiers | Type | Description | | --- | --- | --- | --- | | [allow?](#dom-iframeoptions-allow) | | Value<string> | _(Optional)_ The allow attribute for the iframe. | | [height?](#dom-iframeoptions-height) | | [SplitValue](#dom-splitvalue)<string \\| number> | _(Optional)_ The height of the iframe. | | [iframeChild?](#dom-iframeoptions-iframechild) | | [TNode](#dom-tnode) | _(Optional)_ Content to attach directly to the iframe's element, not the document body. | | [loading?](#dom-iframeoptions-loading) | | Value<'eager' \\| 'lazy'> | _(Optional)_ The loading attribute for the iframe. | | [name?](#dom-iframeoptions-name) | | Value<string> | _(Optional)_ The name of the iframe. | | [onLoad?](#dom-iframeoptions-onload) | | (iframe: HTMLIFrameElement) => void | _(Optional)_ Callback function that is called when the iframe is loaded. Receives the iframe element and its contentDocument. | | [referrerpolicy?](#dom-iframeoptions-referrerpolicy) | | Value<[ReferrerPolicy](#dom-referrerpolicy2)> | _(Optional)_ The referrerpolicy attribute for the iframe. | | [sandbox?](#dom-iframeoptions-sandbox) | | Value<string> | _(Optional)_ The sandbox attribute for the iframe. | | [src?](#dom-iframeoptions-src) | | Value<string> | _(Optional)_ The URL of the page to embed in the iframe. | | [width?](#dom-iframeoptions-width) | | [SplitValue](#dom-splitvalue)<string \\| number> | _(Optional)_ The width of the iframe. | --- ## dom.iframeoptions.name: IFrameOptions.name property The name of the iframe. **Signature:**```typescript name?: Value; ``` --- ## dom.iframeoptions.onload: IFrameOptions.onLoad property Callback function that is called when the iframe is loaded. Receives the iframe element and its contentDocument. **Signature:**```typescript onLoad?: (iframe: HTMLIFrameElement) => void; ``` --- ## dom.iframeoptions.referrerpolicy: IFrameOptions.referrerpolicy property The referrerpolicy attribute for the iframe. **Signature:**```typescript referrerpolicy?: Value; ``` --- ## dom.iframeoptions.sandbox: IFrameOptions.sandbox property The sandbox attribute for the iframe. **Signature:**```typescript sandbox?: Value; ``` --- ## dom.iframeoptions.src: IFrameOptions.src property The URL of the page to embed in the iframe. **Signature:**```typescript src?: Value; ``` --- ## dom.iframeoptions.width: IFrameOptions.width property The width of the iframe. **Signature:**```typescript width?: SplitValue; ``` --- ## dom.input: input variable A convenience object to create Renderables for HTMLInput elements. It automatically creates an attribute with the specified type **Signature:**```typescript input: { number: (...children: TNode[]) => Renderable; date: (...children: TNode[]) => Renderable; time: (...children: TNode[]) => Renderable; text: (...children: TNode[]) => Renderable; color: (...children: TNode[]) => Renderable; search: (...children: TNode[]) => Renderable; hidden: (...children: TNode[]) => Renderable; tel: (...children: TNode[]) => Renderable; email: (...children: TNode[]) => Renderable; url: (...children: TNode[]) => Renderable; checkbox: (...children: TNode[]) => Renderable; radio: (...children: TNode[]) => Renderable; file: (...children: TNode[]) => Renderable; password: (...children: TNode[]) => Renderable; button: (...children: TNode[]) => Renderable; submit: (...children: TNode[]) => Renderable; reset: (...children: TNode[]) => Renderable; range: (...children: TNode[]) => Renderable; image: (...children: TNode[]) => Renderable; month: (...children: TNode[]) => Renderable; week: (...children: TNode[]) => Renderable; "datetime-local": (...children: TNode[]) => Renderable; } ``` ## dom.input: Example ```ts input.text() // equivalent to html.input(attr.type('text')) ``` --- ## dom.inputtypes: InputTypes type Represents the possible input types for HTML input elements. **Signature:**```typescript export type InputTypes = 'text' | 'number' | 'checkbox' | 'radio' | 'file' | 'password' | 'button' | 'submit' | 'reset' | 'date' | 'range' | 'color' | 'hidden' | 'image' | 'month' | 'time' | 'week' | 'email' | 'tel' | 'url' | 'search' | 'datetime-local'; ``` --- ## dom.makeprobe: makeProbe() function **Signature:**```typescript makeProbe: (identifier: symbol) => Provider<() => void, ProbeOptions> ```## dom.makeprobe: Parameters | Parameter | Type | Description | | --- | --- | --- | | identifier | symbol | | **Returns:** [Provider](#dom-provider)<() => void, [ProbeOptions](#dom-probeoptions)> --- ## dom.mapsignal: MapSignal() function Maps the values emitted by a signal to a renderable function and returns a new renderable function. While it is tempting to use MapSignal for its simplicity, it is important to remember that the renderable function returned by MapSignal will be re-rendered every time the signal emits a new value. In other contexts link `Ensure` or `OneOf`, the renderable function is only re-rendered when the signal changes to a state that requires a different renderable function. **Signature:**```typescript MapSignal: (value: Value, fn: (value: T) => TNode) => Renderable ```## dom.mapsignal: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | Value<T> | | | fn | (value: T) => [TNode](#dom-tnode) | The function to map the signal values to a renderable/TNode. | **Returns:** [Renderable](#dom-renderable) - A new renderable function that represents the mapped signal. --- ## dom.math: math variable A convenience object to create Renderables for MATH elements. **Signature:**```typescript math: { 'annotation-xml': (...children: TNode[]) => Renderable; annotation: (...children: TNode[]) => Renderable; maction: (...children: TNode[]) => Renderable; maligngroup: (...children: TNode[]) => Renderable; malignmark: (...children: TNode[]) => Renderable; math: (...children: TNode[]) => Renderable; menclose: (...children: TNode[]) => Renderable; merror: (...children: TNode[]) => Renderable; mfenced: (...children: TNode[]) => Renderable; mfrac: (...children: TNode[]) => Renderable; mglyph: (...children: TNode[]) => Renderable; mi: (...children: TNode[]) => Renderable; mlabeledtr: (...children: TNode[]) => Renderable; mlongdiv: (...children: TNode[]) => Renderable; mmultiscripts: (...children: TNode[]) => Renderable; mn: (...children: TNode[]) => Renderable; mo: (...children: TNode[]) => Renderable; mover: (...children: TNode[]) => Renderable; mpadded: (...children: TNode[]) => Renderable; mphantom: (...children: TNode[]) => Renderable; mprescripts: (...children: TNode[]) => Renderable; mroot: (...children: TNode[]) => Renderable; mrow: (...children: TNode[]) => Renderable; ms: (...children: TNode[]) => Renderable; mscarries: (...children: TNode[]) => Renderable; mscarry: (...children: TNode[]) => Renderable; msgroup: (...children: TNode[]) => Renderable; msline: (...children: TNode[]) => Renderable; mspace: (...children: TNode[]) => Renderable; msqrt: (...children: TNode[]) => Renderable; msrow: (...children: TNode[]) => Renderable; mstack: (...children: TNode[]) => Renderable; mstyle: (...children: TNode[]) => Renderable; msub: (...children: TNode[]) => Renderable; msubsup: (...children: TNode[]) => Renderable; msup: (...children: TNode[]) => Renderable; mtable: (...children: TNode[]) => Renderable; mtd: (...children: TNode[]) => Renderable; mtext: (...children: TNode[]) => Renderable; mtr: (...children: TNode[]) => Renderable; munder: (...children: TNode[]) => Renderable; munderover: (...children: TNode[]) => Renderable; none: (...children: TNode[]) => Renderable; semantics: (...children: TNode[]) => Renderable; } ``` --- ## dom.mathattr: mathAttr variable An object that provides attribute functions for MathML tags. **Signature:**```typescript mathAttr: { accent: (value: SplitNValue) => Renderable; accentunder: (value: SplitNValue) => Renderable; actiontype: (value: SplitNValue<"statusline" | "tooltip" | "input">) => Renderable; align: (value: SplitNValue<"left" | "right" | "center">) => Renderable; altimg: (value: SplitNValue) => Renderable; altimgheight: (value: SplitNValue) => Renderable; altimgvalign: (value: SplitNValue) => Renderable; altimgwidth: (value: SplitNValue) => Renderable; alttext: (value: SplitNValue) => Renderable; background: (value: SplitNValue) => Renderable; base: (value: SplitNValue) => Renderable; bevelled: (value: SplitNValue) => Renderable; charalign: (value: SplitNValue<"left" | "right" | "center">) => Renderable; class: (value: SplitNValue) => Renderable; close: (value: SplitNValue) => Renderable; color: (value: SplitNValue) => Renderable; columnalign: (value: SplitNValue) => Renderable; columnlines: (value: SplitNValue) => Renderable; columnspacing: (value: SplitNValue) => Renderable; columnspan: (value: SplitNValue) => Renderable; columnwidth: (value: SplitNValue) => Renderable; crossout: (value: SplitNValue) => Renderable; decimalpoint: (value: SplitNValue) => Renderable; definitionurl: (value: SplitNValue) => Renderable; denomalign: (value: SplitNValue<"left" | "right" | "center">) => Renderable; depth: (value: SplitNValue) => Renderable; dir: (value: SplitNValue<"ltr" | "rtl">) => Renderable; display: (value: SplitNValue<"inline" | "block">) => Renderable; displaystyle: (value: SplitNValue) => Renderable; edge: (value: SplitNValue<"left" | "right">) => Renderable; encoding: (value: SplitNValue) => Renderable; equalcolumns: (value: SplitNValue) => Renderable; equalrows: (value: SplitNValue) => Renderable; fence: (value: SplitNValue) => Renderable; fontfamily: (value: SplitNValue) => Renderable; fontsize: (value: SplitNValue) => Renderable; fontstyle: (value: SplitNValue<"normal" | "italic">) => Renderable; fontweight: (value: SplitNValue<"normal" | "bold">) => Renderable; form: (value: SplitNValue<"prefix" | "infix" | "postfix">) => Renderable; frame: (value: SplitNValue) => Renderable; groupalign: (value: SplitNValue) => Renderable; height: (value: SplitNValue) => Renderable; href: (value: SplitNValue) => Renderable; id: (value: SplitNValue) => Renderable; indentalign: (value: SplitNValue<"left" | "right" | "auto" | "center" | "id">) => Renderable; indentalignfirst: (value: SplitNValue<"left" | "right" | "auto" | "center" | "id" | "indentaling">) => Renderable; indentalignlast: (value: SplitNValue<"left" | "right" | "auto" | "center" | "id" | "indentaling">) => Renderable; indentshift: (value: SplitNValue) => Renderable; indentshiftfirst: (value: SplitNValue) => Renderable; indentshiftlast: (value: SplitNValue) => Renderable; indenttarget: (value: SplitNValue) => Renderable; infixlinebreakstyle: (value: SplitNValue<"before" | "after" | "duplicate">) => Renderable; intent: (value: SplitNValue) => Renderable; largeop: (value: SplitNValue) => Renderable; leftoverhang: (value: SplitNValue) => Renderable; length: (value: SplitNValue) => Renderable; linebreak: (value: SplitNValue<"auto" | "newline" | "nobreak" | "goodbreak" | "badbreak">) => Renderable; linebreakmultchar: (value: SplitNValue) => Renderable; linebreakstyle: (value: SplitNValue<"before" | "after" | "duplicate" | "infixlinebreakstyle">) => Renderable; lineleading: (value: SplitNValue) => Renderable; linethickness: (value: SplitNValue) => Renderable; location: (value: SplitNValue) => Renderable; longdivstyle: (value: SplitNValue<"lefttop" | "stackedrightright" | "mediumstackedrightright" | "shortstackedrightright" | "righttop">) => Renderable; lquote: (value: SplitNValue) => Renderable; lspace: (value: SplitNValue) => Renderable; mathbackground: (value: SplitNValue) => Renderable; mathcolor: (value: SplitNValue) => Renderable; mathdepth: (value: SplitNValue) => Renderable; mathsize: (value: SplitNValue) => Renderable; mathvariant: (value: SplitNValue<"normal" | "italic" | "bold" | "bold-italic" | "double-struck" | "bold-fraktur" | "script" | "bold-script" | "fraktur" | "sans-serif" | "bold-sans-serif" | "sans-serif-italic" | "sans-serif-bold-italic" | "monospace" | "initial" | "tailed" | "looped" | "stretched">) => Renderable; maxsize: (value: SplitNValue) => Renderable; maxwidth: (value: SplitNValue) => Renderable; minlabelspacing: (value: SplitNValue) => Renderable; minsize: (value: SplitNValue) => Renderable; movablelimits: (value: SplitNValue) => Renderable; mslinethickness: (value: SplitNValue) => Renderable; notation: (value: SplitNValue) => Renderable; numalign: (value: SplitNValue<"left" | "right" | "center">) => Renderable; open: (value: SplitNValue) => Renderable; other: (value: SplitNValue) => Renderable; overflow: (value: SplitNValue<"scale" | "linebreak" | "scroll" | "elide" | "truncate">) => Renderable; position: (value: SplitNValue) => Renderable; rightoverhang: (value: SplitNValue) => Renderable; rowalign: (value: SplitNValue) => Renderable; rowlines: (value: SplitNValue) => Renderable; rowspacing: (value: SplitNValue) => Renderable; rowspan: (value: SplitNValue) => Renderable; rquote: (value: SplitNValue) => Renderable; rspace: (value: SplitNValue) => Renderable; scriptlevel: (value: SplitNValue) => Renderable; scriptminsize: (value: SplitNValue) => Renderable; scriptsizemultiplier: (value: SplitNValue) => Renderable; selection: (value: SplitNValue) => Renderable; separator: (value: SplitNValue) => Renderable; separators: (value: SplitNValue) => Renderable; shift: (value: SplitNValue) => Renderable; side: (value: SplitNValue<"left" | "right" | "leftoverlap" | "rightoverlap">) => Renderable; stackalign: (value: SplitNValue<"left" | "right" | "center" | "decimalpoint">) => Renderable; stretchy: (value: SplitNValue) => Renderable; style: (value: SplitNValue) => Renderable; subscriptshift: (value: SplitNValue) => Renderable; superscriptshift: (value: SplitNValue) => Renderable; symmetric: (value: SplitNValue) => Renderable; type: (value: SplitNValue) => Renderable; valign: (value: SplitNValue<"bottom" | "top" | "center" | "baseline" | "axis">) => Renderable; voffset: (value: SplitNValue) => Renderable; width: (value: SplitNValue) => Renderable; xlink: (value: SplitNValue) => Renderable; xmlns: (value: SplitNValue) => Renderable; xref: (value: SplitNValue) => Renderable; } ``` ## dom.mathattr: Example ```ts const math = html.math( mathAttr.mathvariant('bold'), mathAttr.mathsize(size), // where size is a `Signal` // ... ) ``` --- ## dom.mathel: MathEl() function Creates a Renderable that represents a MathML element. **Signature:**```typescript MathEl: (tagName: string, ...children: TNode[]) => Renderable ```## dom.mathel: Parameters | Parameter | Type | Description | | --- | --- | --- | | tagName | string | The tag name of the MathML element. | | children | [TNode](#dom-tnode)\[\] | The child nodes of the MathML element. | **Returns:** [Renderable](#dom-renderable) A renderable function that creates and appends the MathML element to the DOM. --- ## dom.mathmlattributes: MathMLAttributes type Represents the attributes used in MathML elements. **Signature:**```typescript export type MathMLAttributes = { accent: boolean | string; accentunder: boolean | string; actiontype: 'statusline' | 'tooltip' | 'input'; align: 'left' | 'center' | 'right'; altimg: string; altimgheight: string; altimgvalign: string; altimgwidth: string; alttext: string; background: string; base: string; bevelled: boolean | string; charalign: 'left' | 'center' | 'right'; class: string; close: string; color: string; columnalign: string; columnlines: string; columnspacing: string; columnspan: number | string; columnwidth: string; crossout: string; decimalpoint: string; definitionurl: string; denomalign: 'left' | 'center' | 'right'; depth: string; dir: 'ltr' | 'rtl'; display: 'block' | 'inline'; displaystyle: boolean | string; edge: 'left' | 'right'; encoding: string; equalcolumns: boolean | string; equalrows: boolean | string; fence: boolean | string; fontfamily: string; fontsize: string; fontstyle: 'normal' | 'italic'; fontweight: 'normal' | 'bold'; form: 'prefix' | 'infix' | 'postfix'; frame: string; groupalign: string; height: string; href: string; id: string; indentalign: 'left' | 'center' | 'right' | 'auto' | 'id'; indentalignfirst: 'left' | 'center' | 'right' | 'auto' | 'id' | 'indentaling'; indentalignlast: 'left' | 'center' | 'right' | 'auto' | 'id' | 'indentaling'; indentshift: string; indentshiftfirst: string; indentshiftlast: string; indenttarget: string; infixlinebreakstyle: 'before' | 'after' | 'duplicate'; intent: string; largeop: boolean | string; leftoverhang: string; length: string; linebreak: 'auto' | 'newline' | 'nobreak' | 'goodbreak' | 'badbreak'; linebreakmultchar: string; linebreakstyle: 'before' | 'after' | 'duplicate' | 'infixlinebreakstyle'; lineleading: string; linethickness: string; location: string; longdivstyle: 'lefttop' | 'stackedrightright' | 'mediumstackedrightright' | 'shortstackedrightright' | 'righttop'; lquote: string; lspace: string; mathbackground: string; mathcolor: string; mathdepth: string; mathsize: string; mathvariant: 'normal' | 'bold' | 'italic' | 'bold-italic' | 'double-struck' | 'bold-fraktur' | 'script' | 'bold-script' | 'fraktur' | 'sans-serif' | 'bold-sans-serif' | 'sans-serif-italic' | 'sans-serif-bold-italic' | 'monospace' | 'initial' | 'tailed' | 'looped' | 'stretched'; maxsize: string; maxwidth: string; minlabelspacing: string; minsize: string; movablelimits: boolean | string; mslinethickness: string; notation: string; numalign: 'left' | 'center' | 'right'; open: string; other: string; overflow: 'linebreak' | 'scroll' | 'elide' | 'truncate' | 'scale'; position: string; rightoverhang: string; rowalign: string; rowlines: string; rowspacing: string; rowspan: number | string; rquote: string; rspace: string; scriptlevel: string; scriptminsize: string; scriptsizemultiplier: string; selection: string; separator: boolean | string; separators: string; shift: string; side: 'left' | 'leftoverlap' | 'right' | 'rightoverlap'; stackalign: 'left' | 'center' | 'right' | 'decimalpoint'; stretchy: boolean | string; style: string; subscriptshift: string; superscriptshift: string; symmetric: boolean | string; type: string; valign: 'top' | 'bottom' | 'center' | 'baseline' | 'axis'; voffset: string; width: string; xlink: string; xmlns: string; xref: string; }; ``` --- ## dom.mathmltags: MathMLTags type Represents a collection of MathML tags. **Signature:**```typescript export type MathMLTags = { 'annotation-xml': MathMLElement; annotation: MathMLElement; maction: MathMLElement; maligngroup: MathMLElement; malignmark: MathMLElement; math: MathMLElement; menclose: MathMLElement; merror: MathMLElement; mfenced: MathMLElement; mfrac: MathMLElement; mglyph: MathMLElement; mi: MathMLElement; mlabeledtr: MathMLElement; mlongdiv: MathMLElement; mmultiscripts: MathMLElement; mn: MathMLElement; mo: MathMLElement; mover: MathMLElement; mpadded: MathMLElement; mphantom: MathMLElement; mprescripts: MathMLElement; mroot: MathMLElement; mrow: MathMLElement; ms: MathMLElement; mscarries: MathMLElement; mscarry: MathMLElement; msgroup: MathMLElement; msline: MathMLElement; mspace: MathMLElement; msqrt: MathMLElement; msrow: MathMLElement; mstack: MathMLElement; mstyle: MathMLElement; msub: MathMLElement; msubsup: MathMLElement; msup: MathMLElement; mtable: MathMLElement; mtd: MathMLElement; mtext: MathMLElement; mtr: MathMLElement; munder: MathMLElement; munderover: MathMLElement; none: MathMLElement; semantics: MathMLElement; }; ``` --- ## dom package ## dom: Classes | Class | Description | | --- | --- | | [BrowserContext](#dom-browsercontext) | Browser implementation of DOMContext for real DOM manipulation in web browsers. BrowserContext provides a comprehensive API for creating, manipulating, and managing DOM elements in a browser environment. It handles element creation, text nodes, event listeners, styling, and provider management while maintaining immutability through context chaining. The context uses a reference system to track insertion points within sibling elements, allowing precise control over where new elements are inserted in the DOM tree. | | [HeadlessAdapter](#dom-headlessadapter) | Represents an adapter for headless rendering environments. This class provides methods to interact with elements in a headless context. This class is used to adapt the HeadlesContext to whatever you want to use to render your final HTML. You can use libraries like cheerio to render your HTML. For cheerio an adapter could look like this: |```ts const renderWithCheerio = (html: string, root: HeadlessPortal) => { const $ = cheerio.load(html) const adapter = new HeadlessAdapter>({ select: (selector: string): cheerio.Cheerio[] => [$(selector)], getAttribute: (el, name: string) => el.attr(name) ?? null, setAttribute: (el, name: string, value: string | null) => { if (value === null) { el.removeAttr(name) } else { el.attr(name, value) } }, getClass: el => el.attr('class') ?? '', setClass: (el, value: string | null) => { if (value === null) { el.removeAttr('class') } else { el.attr('class', value) } }, getStyles: el => el.attr('style') ?? {}, setStyles: (el, value: Record) => { if (Object.keys(value).length === 0) { el.removeAttr('style') } else { el.css(value) } }, appendHTML: (el, html) => el.append(html), getInnerHTML: el => el.html() ?? '', setInnerHTML: (el, html) => el.html(html), getInnerText: el => el.text() ?? '', setInnerText: (el, text) => el.text(text), }) adapter.setFromRoot(root, true) return $.html() } ```This function will return the rendered HTML as a string. [HeadlessContext](#dom-headlesscontext) [HeadlessElement](#dom-headlesselement) [HeadlessPortal](#dom-headlessportal) [HeadlessText](#dom-headlesstext) [ProviderNotFoundError](#dom-providernotfounderror) Error thrown when a provider is not found. [RenderingError](#dom-renderingerror) Represents an error that occurs during rendering. ## dom: Functions | Function | Description | | --- | --- | | [\_isFragment(node)](#dom-isfragment) | | | [Aria(name, value)](#dom-aria) | Creates a renderable for an ARIA attribute with the specified name and value. This is the functional equivalent of using `aria[name](value)` with a dynamic attribute name. | | [Async(promise, options)](#dom-async) | Creates a renderable asynchronous task that wraps a promise. | | [Attr\_2(name, value)](#dom-attr2) | Creates a renderable for an HTML attribute with the specified name and value. This is the functional equivalent of using `attr[name](value)` with a dynamic attribute name. The `class` attribute is special and can be used multiple times on the same element. Multiple class values will be merged together. | | [BindChecked(prop)](#dom-bindchecked) | Binds a `boolean` property to the checked value of an input element. The binding is two-way. | | [BindDate(prop, handler)](#dom-binddate) | Binds a `Date` property to an input element. The binding is two-way. Changes to the input element will update the property but will only be affected by day changes and ignore time changes. | | [BindDateTime(prop, handler)](#dom-binddatetime) | Binds a `Date` property to an input element. The binding is two-way. | | [BindNumber(prop, handler)](#dom-bindnumber) | Binds a `number` property to an input element. The binding is two-way. | | [BindText(prop, handler)](#dom-bindtext) | Binds a `string` property to an input element. The binding is two-way. | | [Conjunction(separator, options)](#dom-conjunction) | Creates a Renderable that returns the appropriate separator based on the element position. | | [DataAttr(name, value)](#dom-dataattr) | Creates a renderable for a data attribute with the specified name and value. This is the functional equivalent of using `dataAttr[name](value)` with a dynamic attribute name. | | [DOMNode(node)](#dom-domnode) | Creates a renderable DOM node. | | [El(tagName, children)](#dom-el) | Creates a Renderable that represents an HTML element. | | [ElNS(tagName, namespace, children)](#dom-elns) | Creates a renderable object that represents an element in the DOM with a specified namespace. | | [emit(fn, options)](#dom-emit) | Creates an event handler that calls the provided function with the event as an argument. | | [emitChecked(fn, options)](#dom-emitchecked) | Creates an event handler that extracts and emits the checked state from a checkbox or radio input. This utility simplifies handling checkbox and radio button state changes by automatically extracting the `checked` property from the target element. | | [emitTarget(fn, options)](#dom-emittarget) | Creates an event handler that extracts and emits the target element from an event. | | [emitValue(fn, options)](#dom-emitvalue) | Creates an event handler that extracts and emits the string value from an input element. This utility simplifies handling input events by automatically extracting the value from the target element and passing it to your callback function. | | [emitValueAsDate(fn, options)](#dom-emitvalueasdate) | Converts the value of an HTML input element to a Date object and emits it using the provided callback function. | | [emitValueAsDateTime(fn, options)](#dom-emitvalueasdatetime) | Emits the value of an HTMLInputElement as a Date object. | | [emitValueAsNullableDate(fn, options)](#dom-emitvalueasnullabledate) | Converts the value of an HTML input element to a Date object or null and emits it using the provided callback function. | | [emitValueAsNullableDateTime(fn, options)](#dom-emitvalueasnullabledatetime) | Emits the value of an HTMLInputElement as a Date object or null. | | [emitValueAsNumber(fn, options)](#dom-emitvalueasnumber) | Creates an event handler that extracts and emits the numeric value from an input element. This utility automatically converts the input's value to a number using the browser's built-in `valueAsNumber` property, which handles number inputs correctly and returns `NaN` for invalid numeric values. | | [Ensure(value, then, otherwise)](#dom-ensure) | Conditionally renders content based on whether a value is non-null/non-undefined. This function provides a type-safe way to handle nullable values in your UI. It only renders the `then` content when the value is not null or undefined, and optionally renders alternative content when the value is null/undefined. | | [EnsureAll(signals)](#dom-ensureall) | Conditionally renders content only when ALL provided values are non-null/non-undefined. This function is useful when you need multiple values to be present before rendering content. It waits for all values to be non-null/non-undefined before calling the callback function. If any value becomes null/undefined, it will render the `otherwise` content instead. | | [ForEach(value, item, separator)](#dom-foreach) | Efficiently renders a dynamic list of items from an array signal. This function creates a reactive list that automatically updates when the source array changes. Each item in the array gets its own signal that tracks changes to that specific item. The list efficiently handles additions, removals, and modifications to the array. | | [Fragment(children)](#dom-fragment) | Creates a fragment renderable that represents a collection of child renderables. The Fragment itself does not render any DOM elements. Instead, it renders the child renderables in the given DOM context. It can be used any time a single Renderable/TNode is expected, but multiple renderables are needed. | | [getWindow()](#dom-getwindow) | | | [IFrame({ src, name, width, height, sandbox, allow, referrerpolicy, loading, iframeChild, onLoad, }, children)](#dom-iframe) | Creates an iframe element and optionally renders content into its document. When children are provided, they are rendered into the iframe's contentDocument. This allows you to create isolated DOM contexts with their own styles and scripts. | | [makeProbe(identifier)](#dom-makeprobe) | | | [MapSignal(value, fn)](#dom-mapsignal) | Maps the values emitted by a signal to a renderable function and returns a new renderable function. While it is tempting to use MapSignal for its simplicity, it is important to remember that the renderable function returned by MapSignal will be re-rendered every time the signal emits a new value. In other contexts link `Ensure` or `OneOf`, the renderable function is only re-rendered when the signal changes to a state that requires a different renderable function. | | [MathAttr(name, value)](#dom-mathattr) | Creates a renderable for a MathML attribute with the specified name and value. This is the functional equivalent of using `mathAttr[name](value)`. | | [MathEl(tagName, children)](#dom-mathel) | Creates a Renderable that represents a MathML element. | | [NotEmpty(value, display, whenEmpty)](#dom-notempty) | Returns a renderable component that displays the given `display` component when the `signal` contains a non-empty array, and the `whenEmpty` component otherwise. | | [OnChecked(fn)](#dom-onchecked) | **_(ALPHA)_** Attaches an event handler to the 'click' event that triggers when a checkbox is checked or unchecked. | | [OnDispose(fns)](#dom-ondispose) | Creates a renderable object that will be called when the component is unmounted. | | [OneOf(match, cases)](#dom-oneof) | Creates a renderable function that renders different components based on the value of a signal. The signal value should be an object with a single key that matches one of the keys in the `cases` object. | | [OneOfField(match, field, cases)](#dom-oneoffield) | Creates a renderable that renders different components based on the value of the specified field. | | [OneOfKind(match, cases)](#dom-oneofkind) | Creates a renderable field that matches the value of the `kind` property in the provided `match` signal. It uses the `cases` object to determine the appropriate field to render based on the value of `kind`. | | [OneOfTuple(match, cases)](#dom-oneoftuple) | Creates a tuple-based one-of component that matches a signal value with a set of cases. The signal value should be a tuple with the first element being the key to match against. | | [OneOfType(match, cases)](#dom-oneoftype) | Creates a field that renders one of the provided cases based on the value of the `type` property. It uses the `cases` object to determine the appropriate field to render based on the value of `type`. | | [OneOfValue(match, cases)](#dom-oneofvalue) | Creates a renderable value that represents one of the provided cases based on the given match signal. The match signal should emit a value that matches one of the keys in the `cases` object. | | [Portal(selector, node)](#dom-portal) | Renders the given `node` into a DOM element selected by the provided `selector`. Throws an error if the element cannot be found. | | [Provide(provider, options, child)](#dom-provide) | Makes a provider available to all child components in the component tree. This function creates a provider context that child components can access using `Use`. The provider is automatically disposed when the component is unmounted. | | [render(node, parent, { doc, clear, disposeWithParent, providers })](#dom-render) | Renders a `Renderable` node into a specified parent element or selector. | | [renderableOfTNode(child)](#dom-renderableoftnode) | Converts a TNode into a Renderable. | | [renderWithContext(renderable, ctx)](#dom-renderwithcontext) | Renders the given `renderable` with the provided `ctx` DOM context. Creates a DisposalScope for automatic signal disposal. All signals created during the renderable execution are tracked and disposed when the clear function is called. | | [Repeat(times, element, separator)](#dom-repeat) | Renders content a specified number of times, with each iteration receiving position information. This function is useful for generating repeated UI elements based on a count rather than an array. Each iteration receives an `ElementPosition` object that provides the current index and position information relative to the total count. | | [restoreTempoPlaceholders()](#dom-restoretempoplaceholders) | Restores all placeholders in the DOM. This function is useful when the HTML is rendered on the server and then hydrated on the client. It restores the original content that was replaced with placeholders during the initial render. When you render on the server side, make sure to call `HeadlessAdapter.setFromRoot` with the result of `runHeadless` and the second parameter `setPlaceholders` to `true`. | | [runHeadless(makeRenderable, { startUrl, selector, providers, })](#dom-runheadless) | Runs a renderable function in a headless environment. | | [ShadowRoot\_2({ mode, delegatesFocus, slotAssignment, clonable, serializable, }, children)](#dom-shadowroot2) | | | [SVGAttr(name, value)](#dom-svgattr) | Creates a renderable for an SVG attribute with the specified name and value. This is the functional equivalent of using `svgAttr[name](value)` with a dynamic attribute name. | | [SVGEl(tagName, children)](#dom-svgel) | Creates a Renderable that represents an SVG element. | | [Task(task, options)](#dom-task) | Represents a renderable task that can be executed asynchronously. | | [TextNode(value)](#dom-textnode) | Creates a renderable text node. | | [Unless(condition, then, otherwise)](#dom-unless) | Lazily renders content when a condition is false. | | [Use(provider, child)](#dom-use) | Consumes a provider value and makes it available to a child component. This function looks up a provider in the component tree and passes its value to the child function. The provider must have been made available by a parent component using `Provide`. | | [UseMany(providers)](#dom-usemany) | Consumes multiple providers and makes their values available to a child component. This function is a convenience wrapper for consuming multiple providers at once. It's equivalent to nesting multiple `Use` calls but provides a cleaner API when you need access to several providers simultaneously. | | [When(condition, then, otherwise)](#dom-when) | Lazily renders content based on a boolean condition. | | [WithBrowserCtx(fn)](#dom-withbrowserctx) | Returns a renderable object that executes the given function with the current DOMContext as argument. The given function can return a TNode or void. If you need to perform some actions when the Renderable is disposed, you can use `OnDispose` as the return value. | | [WithCtx(fn)](#dom-withctx) | Returns a renderable object that executes the given function with the current DOMContext as argument. The given function can return a TNode or void. If you need to perform some actions when the Renderable is disposed, you can use `OnDispose` as the return value. | | [WithElement(fn)](#dom-withelement) | Executes a callback function when the parent element is mounted in the DOM. The given function can return a TNode or void. Any returned TNode will be appended to the element argument. If you need to perform some actions when the Renderable is disposed, you can use `OnDispose` as the return value. | | [WithHeadlessCtx(fn)](#dom-withheadlessctx) | Returns a renderable object that executes the given function with the current DOMContext as argument. | | [WithProvider(fn)](#dom-withprovider) | Returns a renderable object that executes the given function with the current DOMContext as argument. The given function can return a TNode or void. If you need to perform some actions when the Renderable is disposed, you can use `OnDispose` as the return value. | | [WithScope(fn)](#dom-withscope) | Creates a renderable that provides explicit access to a DisposalScope. This is useful when you need to create signals in async contexts (like setTimeout, fetch callbacks, event handlers) where automatic scope tracking doesn't work. | ## dom: Interfaces | Interface | Description | | --- | --- | | [DOMContext](#dom-domcontext) | `DOMContext` is an immutable class that represents the context of a DOM element. It provides methods and properties to manipulate and interact with the DOM element. A reference in a DOMContext is to mark a position within a set of siblings. It is used to insert new elements before the reference. | | [HeadlessContainer](#dom-headlesscontainer) | | | [IFrameOptions](#dom-iframeoptions) | | | [ShadowRootOptions](#dom-shadowrootoptions) | | | [StreamOptions](#dom-streamoptions) | Options for streaming HTML output. | ## dom: Variables | Variable | Description | | --- | --- | | [aria](#dom-aria) | An object that provides a convenient way to create mountable attributes for ARIA properties. The type of the value is inferred from the attribute name. | | [attr](#dom-attr) | The `attr` object allows to create any HTML attribute. Either a literal value or `Signal` can be passed as a value. The type of the value is inferred from the attribute name. | | [CLASS\_PLACEHOLDER\_ATTR](#dom-classplaceholderattr) | | | [dataAttr](#dom-dataattr) | The `data` object allows to create any `data-` attributes. Either a literal value or `Signal` can be passed as a value. | | [DOM\_RENDERABLE\_TYPE](#dom-domrenderabletype) | Symbol to brand DOM renderables and prevent mixing with other contexts | | [Empty](#dom-empty) | Represents an empty renderable object. | | [GlobalProbe](#dom-globalprobe) | | | [html](#dom-html) | A convenience object to create Renderables for HTML elements. | | [HYDRATION\_ID\_ATTR](#dom-hydrationidattr) | Attribute name for hydration IDs. Used to match server-rendered elements with client-side renderables during hydration. | | [input](#dom-input) | A convenience object to create Renderables for HTMLInput elements. It automatically creates an attribute with the specified type | | [math](#dom-math) | A convenience object to create Renderables for MATH elements. | | [mathAttr](#dom-mathattr) | An object that provides attribute functions for MathML tags. | | [on](#dom-on) | Provides type-safe event handlers for all HTML events. The `on` object is a proxy that provides access to all standard HTML events with proper TypeScript typing. Each event handler receives the native event object and the DOM context. | | [style](#dom-style) | A collection of functions to create style renderables. | | [svg](#dom-svg) | A convenience object to create Renderables for SVG elements. | | [svgAttr](#dom-svgattr) | An object that provides a convenient way to create mountable attributes for SVG elements. | ## dom: Type Aliases | Type Alias | Description | | --- | --- | | [AriaAttributes](#dom-ariaattributes) | Represents a collection of ARIA attributes and their corresponding types. | | [AsyncOptions](#dom-asyncoptions) | Options for the `Async` component. | | [ConjunctionOptions](#dom-conjunctionoptions) | Options for configuring a conjunction. | | [CSSStyles](#dom-cssstyles) | Represents a subset of CSS styles. It is a type that excludes certain properties from the `CSSStyleDeclaration` type. | | [DisposeCallback](#dom-disposecallback) | | | [EmitOptions](#dom-emitoptions) | Options for event handlers. | | [ExcludeFromStyle](#dom-excludefromstyle) | Represents a set of properties or values that are excluded from the CSSStyleDeclaration interface. | | [HandlerOptions](#dom-handleroptions) | Options for event listeners. | | [HeadlessNode](#dom-headlessnode) | | | [HeadlessOptions](#dom-headlessoptions) | Options for running a headless environment. | | [HTMLAttributes](#dom-htmlattributes) | Represents the HTML attributes that can be used in an HTML element. \*\*Security Warning:\*\* Some properties like `innerHTML` and `outerHTML` can introduce Cross-Site Scripting (XSS) vulnerabilities if used with untrusted user input. Always sanitize user-provided content before using these properties. | | [HTMLEvents](#dom-htmlevents) | Represents a mapping of HTML event names to their corresponding event types. | | [HTMLTags](#dom-htmltags) | Represents a mapping of HTML tag names to their corresponding element types. | | [Id](#dom-id) | | | [InputTypes](#dom-inputtypes) | Represents the possible input types for HTML input elements. | | [MathMLAttributes](#dom-mathmlattributes) | Represents the attributes used in MathML elements. | | [MathMLTags](#dom-mathmltags) | Represents a collection of MathML tags. | | [Merge](#dom-merge) | | | [NillifyValue](#dom-nillifyvalue) | | | [NonNillable](#dom-nonnillable) | | | [NValue](#dom-nvalue) | Represents a nullable value or a signal of a nullable value. | | [ObjectToUnion](#dom-objecttounion) | Converts an object to a union of its keys. | | [OneOfFieldOptions](#dom-oneoffieldoptions) | Represents the options for a one-of field. | | [OneOfKindOptions](#dom-oneofkindoptions) | The options for a one-of kind field. | | [OneOfOptions](#dom-oneofoptions) | Represents a set of options for a one-of type. | | [OneOfTupleOptions](#dom-oneoftupleoptions) | Represents a mapping of keys to functions that accept a value of type `Signal` and return a `TNode`. | | [OneOfTypeOptions](#dom-oneoftypeoptions) | Represents a mapping of types to rendering functions. | | [OneOfValueOptions](#dom-oneofvalueoptions) | Represents a set of options for a one-of value. | | [ProbeOptions](#dom-probeoptions) | | | [ProbeResolution](#dom-proberesolution) | | | [Provider](#dom-provider) | Represents a provider for a specific type `T`. | | [ProviderOptions](#dom-provideroptions) | Represents an object with provider options. | | [Providers](#dom-providers) | Represents a collection of providers. The keys of the record are ProviderMark types, and the values are of unknown type. | | [ReferrerPolicy\_2](#dom-referrerpolicy2) | | | [Renderable](#dom-renderable) | A renderable object that can render content into the DOM. Renderables are the fundamental building blocks of Tempo applications. They are objects with a `render()` method that receives a DOMContext and returns a cleanup function, and a `type` symbol for runtime type checking. This is a specialized version of the core Renderable type for DOM contexts. | | [RenderOptions](#dom-renderoptions) | Options for rendering. | | [Size](#dom-size) | Represents the size of an object with width and height. | | [SplitNValue](#dom-splitnvalue) | | | [SplitValue](#dom-splitvalue) | | | [StyleOptions](#dom-styleoptions) | | | [SVGAttributes](#dom-svgattributes) | Represents the attributes that can be used in SVG elements. | | [SVGTags](#dom-svgtags) | Represents a mapping of SVG tag names to their corresponding SVG element types. | | [TaskOptions](#dom-taskoptions) | Represents the options for a task. | | [TNode](#dom-tnode) | A flexible type representing any content that can be rendered in Tempo. TNode (Template Node) is the union type that encompasses all possible content that can be rendered in a Tempo application. This includes components, text, signals, arrays of content, and null/undefined values for conditional rendering. | | [ToProviderTypes](#dom-toprovidertypes) | Converts an array of `Provider` types `T` into an array of their corresponding types. | | [WithDispose](#dom-withdispose) | | --- ## dom.merge: Merge type **Signature:**```typescript export type Merge = Id; ``` **References:** [Id](#dom-id) --- ## dom.nillifyvalue: NillifyValue type **Signature:**```typescript export type NillifyValue = Value | Value | Value; ``` --- ## dom.nonnillable: NonNillable type **Signature:**```typescript export type NonNillable = Merge; ``` **References:** [Merge](#dom-merge) --- ## dom.notempty: NotEmpty() function Returns a renderable component that displays the given `display` component when the `signal` contains a non-empty array, and the `whenEmpty` component otherwise. **Signature:**```typescript NotEmpty: (value: Value, display: (value: Signal) => Renderable, whenEmpty?: () => Renderable) => Renderable ```## dom.notempty: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | Value<T\[\]> | The signal or literal containing the array. | | display | (value: Signal<T\[\]>) => [Renderable](#dom-renderable) | The component to display when the array is non-empty. | | whenEmpty | () => [Renderable](#dom-renderable) | _(Optional)_ The component to display when the array is empty. | **Returns:** [Renderable](#dom-renderable) - The renderable component. --- ## dom.nvalue: NValue type Represents a nullable value or a signal of a nullable value. **Signature:**```typescript export type NValue = Value> | ReadSignal | ReadSignal | ReadSignal | ReadSignal | null | undefined; ``` --- ## dom.objecttounion: ObjectToUnion type Converts an object to a union of its keys. **Signature:**```typescript export type ObjectToUnion = { [K in keyof T]: { [P in K]: T[K]; }; }[keyof T]; ``` --- ## dom.on: on variable Provides type-safe event handlers for all HTML events. The `on` object is a proxy that provides access to all standard HTML events with proper TypeScript typing. Each event handler receives the native event object and the DOM context. **Signature:**```typescript on: { abort: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; afterprint: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; animationcancel: (handler: (event: AnimationEvent, ctx: DOMContext) => void) => Renderable; animationend: (handler: (event: AnimationEvent, ctx: DOMContext) => void) => Renderable; animationiteration: (handler: (event: AnimationEvent, ctx: DOMContext) => void) => Renderable; animationstart: (handler: (event: AnimationEvent, ctx: DOMContext) => void) => Renderable; auxclick: (handler: (event: MouseEvent, ctx: DOMContext) => void) => Renderable; beforeinput: (handler: (event: InputEvent, ctx: DOMContext) => void) => Renderable; beforeprint: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; beforeunload: (handler: (event: BeforeUnloadEvent, ctx: DOMContext) => void) => Renderable; blur: (handler: (event: FocusEvent, ctx: DOMContext) => void) => Renderable; cancel: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; canplay: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; canplaythrough: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; change: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; click: (handler: (event: MouseEvent, ctx: DOMContext) => void) => Renderable; close: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; compositionend: (handler: (event: CompositionEvent, ctx: DOMContext) => void) => Renderable; compositionstart: (handler: (event: CompositionEvent, ctx: DOMContext) => void) => Renderable; compositionupdate: (handler: (event: CompositionEvent, ctx: DOMContext) => void) => Renderable; contextmenu: (handler: (event: MouseEvent, ctx: DOMContext) => void) => Renderable; copy: (handler: (event: ClipboardEvent, ctx: DOMContext) => void) => Renderable; cuechange: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; cut: (handler: (event: ClipboardEvent, ctx: DOMContext) => void) => Renderable; dblclick: (handler: (event: MouseEvent, ctx: DOMContext) => void) => Renderable; drag: (handler: (event: DragEvent, ctx: DOMContext) => void) => Renderable; dragend: (handler: (event: DragEvent, ctx: DOMContext) => void) => Renderable; dragenter: (handler: (event: DragEvent, ctx: DOMContext) => void) => Renderable; dragexit: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; dragleave: (handler: (event: DragEvent, ctx: DOMContext) => void) => Renderable; dragover: (handler: (event: DragEvent, ctx: DOMContext) => void) => Renderable; dragstart: (handler: (event: DragEvent, ctx: DOMContext) => void) => Renderable; drop: (handler: (event: DragEvent, ctx: DOMContext) => void) => Renderable; durationchange: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; emptied: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; ended: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; error: (handler: (event: ErrorEvent, ctx: DOMContext) => void) => Renderable; focus: (handler: (event: FocusEvent, ctx: DOMContext) => void) => Renderable; focusin: (handler: (event: FocusEvent, ctx: DOMContext) => void) => Renderable; focusout: (handler: (event: FocusEvent, ctx: DOMContext) => void) => Renderable; formdata: (handler: (event: FormDataEvent, ctx: DOMContext) => void) => Renderable; fullscreenchange: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; fullscreenerror: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; gotpointercapture: (handler: (event: PointerEvent, ctx: DOMContext) => void) => Renderable; hashchange: (handler: (event: HashChangeEvent, ctx: DOMContext) => void) => Renderable; input: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; invalid: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; keydown: (handler: (event: KeyboardEvent, ctx: DOMContext) => void) => Renderable; keypress: (handler: (event: KeyboardEvent, ctx: DOMContext) => void) => Renderable; keyup: (handler: (event: KeyboardEvent, ctx: DOMContext) => void) => Renderable; languagechange: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; load: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; loadeddata: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; loadedmetadata: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; loadend: (handler: (event: ProgressEvent, ctx: DOMContext) => void) => Renderable; loadstart: (handler: (event: ProgressEvent, ctx: DOMContext) => void) => Renderable; lostpointercapture: (handler: (event: PointerEvent, ctx: DOMContext) => void) => Renderable; message: (handler: (event: MessageEvent, ctx: DOMContext) => void) => Renderable; messageerror: (handler: (event: MessageEvent, ctx: DOMContext) => void) => Renderable; mousedown: (handler: (event: MouseEvent, ctx: DOMContext) => void) => Renderable; mouseenter: (handler: (event: MouseEvent, ctx: DOMContext) => void) => Renderable; mouseleave: (handler: (event: MouseEvent, ctx: DOMContext) => void) => Renderable; mousemove: (handler: (event: MouseEvent, ctx: DOMContext) => void) => Renderable; mouseout: (handler: (event: MouseEvent, ctx: DOMContext) => void) => Renderable; mouseover: (handler: (event: MouseEvent, ctx: DOMContext) => void) => Renderable; mouseup: (handler: (event: MouseEvent, ctx: DOMContext) => void) => Renderable; offline: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; online: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; orientationchange: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; pagehide: (handler: (event: PageTransitionEvent, ctx: DOMContext) => void) => Renderable; pageshow: (handler: (event: PageTransitionEvent, ctx: DOMContext) => void) => Renderable; paste: (handler: (event: ClipboardEvent, ctx: DOMContext) => void) => Renderable; pause: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; play: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; playing: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; pointercancel: (handler: (event: PointerEvent, ctx: DOMContext) => void) => Renderable; pointerdown: (handler: (event: PointerEvent, ctx: DOMContext) => void) => Renderable; pointerenter: (handler: (event: PointerEvent, ctx: DOMContext) => void) => Renderable; pointerleave: (handler: (event: PointerEvent, ctx: DOMContext) => void) => Renderable; pointerlockchange: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; pointerlockerror: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; pointermove: (handler: (event: PointerEvent, ctx: DOMContext) => void) => Renderable; pointerout: (handler: (event: PointerEvent, ctx: DOMContext) => void) => Renderable; pointerover: (handler: (event: PointerEvent, ctx: DOMContext) => void) => Renderable; pointerrawupdate: (handler: (event: PointerEvent, ctx: DOMContext) => void) => Renderable; pointerup: (handler: (event: PointerEvent, ctx: DOMContext) => void) => Renderable; popstate: (handler: (event: PopStateEvent, ctx: DOMContext) => void) => Renderable; progress: (handler: (event: ProgressEvent, ctx: DOMContext) => void) => Renderable; ratechange: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; readystatechange: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; rejectionhandled: (handler: (event: PromiseRejectionEvent, ctx: DOMContext) => void) => Renderable; reset: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; resize: (handler: (event: UIEvent, ctx: DOMContext) => void) => Renderable; scroll: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; scrollend: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; securitypolicyviolation: (handler: (event: SecurityPolicyViolationEvent, ctx: DOMContext) => void) => Renderable; seeked: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; seeking: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; select: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; selectionchange: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; selectstart: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; slotchange: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; stalled: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; storage: (handler: (event: StorageEvent, ctx: DOMContext) => void) => Renderable; submit: (handler: (event: SubmitEvent, ctx: DOMContext) => void) => Renderable; suspend: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; timeupdate: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; toggle: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; touchcancel: (handler: (event: TouchEvent, ctx: DOMContext) => void) => Renderable; touchend: (handler: (event: TouchEvent, ctx: DOMContext) => void) => Renderable; touchmove: (handler: (event: TouchEvent, ctx: DOMContext) => void) => Renderable; touchstart: (handler: (event: TouchEvent, ctx: DOMContext) => void) => Renderable; transitioncancel: (handler: (event: TransitionEvent, ctx: DOMContext) => void) => Renderable; transitionend: (handler: (event: TransitionEvent, ctx: DOMContext) => void) => Renderable; transitionrun: (handler: (event: TransitionEvent, ctx: DOMContext) => void) => Renderable; transitionstart: (handler: (event: TransitionEvent, ctx: DOMContext) => void) => Renderable; unhandledrejection: (handler: (event: PromiseRejectionEvent, ctx: DOMContext) => void) => Renderable; unload: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; visibilitychange: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; volumechange: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; waiting: (handler: (event: Event, ctx: DOMContext) => void) => Renderable; wheel: (handler: (event: WheelEvent, ctx: DOMContext) => void) => Renderable; } ``` ## dom.on: Example 1 ```typescript // Basic click handler html.button( on.click((event, ctx) => { console.log('Button clicked!', event.target) }), 'Click me' ) ``` ## dom.on: Example 2 ```typescript // Input event with value extraction const text = prop('') html.input( attr.value(text), on.input((event) => { text.value = (event.target as HTMLInputElement).value }) ) ``` ## dom.on: Example 3 ```typescript // Multiple event handlers on same element html.div( on.mouseenter(() => console.log('Mouse entered')), on.mouseleave(() => console.log('Mouse left')), on.click(() => console.log('Clicked')), 'Hover and click me' ) ``` ## dom.on: Example 4 ```typescript // Keyboard event handling html.input( on.keydown((event) => { if (event.key === 'Enter') { console.log('Enter pressed!') event.preventDefault() } }) ) ``` --- ## dom.onchecked: OnChecked() function > This API is provided as an alpha preview for developers and may change based on feedback that we receive. Do not use this API in a production environment. > Attaches an event handler to the 'click' event that triggers when a checkbox is checked or unchecked. **Signature:**```typescript OnChecked: (fn: (event: boolean, ctx: DOMContext) => void) => Renderable ```## dom.onchecked: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn | (event: boolean, ctx: [DOMContext](#dom-domcontext)) => void | The callback function to be executed when the checkbox is clicked. | **Returns:** [Renderable](#dom-renderable) --- ## dom.ondispose: OnDispose() function Creates a renderable object that will be called when the component is unmounted. **Signature:**```typescript OnDispose: (...fns: (DisposeCallback | WithDispose)[]) => Renderable ```## dom.ondispose: Parameters | Parameter | Type | Description | | --- | --- | --- | | fns | ([DisposeCallback](#dom-disposecallback) \\| [WithDispose](#dom-withdispose))\[\] | The function(s) to be called when the component is unmounted. | **Returns:** [Renderable](#dom-renderable) A renderable object that takes a DOMContext and returns a function that takes a boolean indicating whether to remove the tree. --- ## dom.oneof: OneOf() function Creates a renderable function that renders different components based on the value of a signal. The signal value should be an object with a single key that matches one of the keys in the `cases` object. **Signature:**```typescript OneOf: >(match: Value, cases: OneOfOptions) => Renderable ```## dom.oneof: Parameters | Parameter | Type | Description | | --- | --- | --- | | match | Value<T> | The signal or value to match against. | | cases | [OneOfOptions](#dom-oneofoptions)<T> | An object containing the different cases to render based on the signal value. | **Returns:** [Renderable](#dom-renderable) A renderable function that renders the appropriate component based on the signal value. --- ## dom.oneoffield: OneOfField() function Creates a renderable that renders different components based on the value of the specified field. **Signature:**```typescript OneOfField: (match: Value, field: K, cases: OneOfFieldOptions) => Renderable ```## dom.oneoffield: Parameters | Parameter | Type | Description | | --- | --- | --- | | match | Value<T> | The signal or value that emits the object containing the one-of field. | | field | K | The key of the one-of field. | | cases | [OneOfFieldOptions](#dom-oneoffieldoptions)<T, K> | The options for the different cases of rendering based on the one-of field value. | **Returns:** [Renderable](#dom-renderable) - The renderable field representing the one-of field. --- ## dom.oneoffieldoptions: OneOfFieldOptions type Represents the options for a one-of field. **Signature:**```typescript export type OneOfFieldOptions = { [KK in T[K]]: (value: Signal) => TNode; }; ``` **References:** [TNode](#dom-tnode) --- ## dom.oneofkind: OneOfKind() function Creates a renderable field that matches the value of the `kind` property in the provided `match` signal. It uses the `cases` object to determine the appropriate field to render based on the value of `kind`. **Signature:**```typescript OneOfKind: (match: Value, cases: OneOfKindOptions) => Renderable ```## dom.oneofkind: Parameters | Parameter | Type | Description | | --- | --- | --- | | match | Value<T> | The signal containing the object to match against. | | cases | [OneOfKindOptions](#dom-oneofkindoptions)<T> | The object containing the cases to match against. | **Returns:** [Renderable](#dom-renderable) - The renderable field that matches the value of `kind`. --- ## dom.oneofkindoptions: OneOfKindOptions type The options for a one-of kind field. **Signature:**```typescript export type OneOfKindOptions = { [KK in T['kind']]: (value: Signal) => TNode; }; ``` **References:** [TNode](#dom-tnode) --- ## dom.oneofoptions: OneOfOptions type Represents a set of options for a one-of type. **Signature:**```typescript export type OneOfOptions> = { [KK in keyof T]: (value: Signal) => TNode; }; ``` **References:** [TNode](#dom-tnode) --- ## dom.oneoftuple: OneOfTuple() function Creates a tuple-based one-of component that matches a signal value with a set of cases. The signal value should be a tuple with the first element being the key to match against. **Signature:**```typescript OneOfTuple: (match: Value<[T, V]>, cases: OneOfTupleOptions) => Renderable ```## dom.oneoftuple: Parameters | Parameter | Type | Description | | --- | --- | --- | | match | Value<\[T, V\]> | The signal containing the value to match. | | cases | [OneOfTupleOptions](#dom-oneoftupleoptions)<T, V> | The options for the one-of component. | **Returns:** [Renderable](#dom-renderable) The result of matching the signal value with the cases. --- ## dom.oneoftupleoptions: OneOfTupleOptions type Represents a mapping of keys to functions that accept a value of type `Signal` and return a `TNode`. **Signature:** ```typescript export type OneOfTupleOptions = { [KK in T]: (value: Signal) => TNode; }; ``` **References:** [TNode](#dom-tnode) --- ## dom.oneoftype: OneOfType() function Creates a field that renders one of the provided cases based on the value of the `type` property. It uses the `cases` object to determine the appropriate field to render based on the value of `type`. **Signature:**```typescript OneOfType: (match: Value, cases: OneOfTypeOptions) => Renderable ```## dom.oneoftype: Parameters | Parameter | Type | Description | | --- | --- | --- | | match | Value<T> | The signal that contains the object with the `type` property. | | cases | [OneOfTypeOptions](#dom-oneoftypeoptions)<T> | The options for rendering each case based on the `type` property. | **Returns:** [Renderable](#dom-renderable) - The rendered field. --- ## dom.oneoftypeoptions: OneOfTypeOptions type Represents a mapping of types to rendering functions. **Signature:**```typescript export type OneOfTypeOptions = { [KK in T['type']]: (value: Signal) => TNode; }; ``` **References:** [TNode](#dom-tnode) --- ## dom.oneofvalue: OneOfValue() function Creates a renderable value that represents one of the provided cases based on the given match signal. The match signal should emit a value that matches one of the keys in the `cases` object. **Signature:**```typescript OneOfValue: (match: Value, cases: OneOfValueOptions) => Renderable ```## dom.oneofvalue: Parameters | Parameter | Type | Description | | --- | --- | --- | | match | Value<T> | The match signal. | | cases | [OneOfValueOptions](#dom-oneofvalueoptions)<T> | The options for the one-of value. | **Returns:** [Renderable](#dom-renderable) - The renderable value representing one of the cases. --- ## dom.oneofvalueoptions: OneOfValueOptions type Represents a set of options for a one-of value. **Signature:**```typescript export type OneOfValueOptions = { [KK in T]: () => TNode; }; ``` **References:** [TNode](#dom-tnode) --- ## dom.portal: Portal() function Renders the given `node` into a DOM element selected by the provided `selector`. Throws an error if the element cannot be found. **Signature:**```typescript Portal: (selector: string | HTMLElement, node: TNode) => Renderable ```## dom.portal: Parameters | Parameter | Type | Description | | --- | --- | --- | | selector | string \\| HTMLElement | The CSS selector for the target DOM element. | | node | [TNode](#dom-tnode) | The node to be rendered. | **Returns:** [Renderable](#dom-renderable) The result of rendering the `node` into the selected DOM element. --- ## dom.probeoptions: ProbeOptions type **Signature:**```typescript export type ProbeOptions = { callback?: (resolution: ProbeResolution) => void; timeout?: number; }; ``` **References:** [ProbeResolution](#dom-proberesolution) --- ## dom.proberesolution: ProbeResolution type **Signature:**```typescript export type ProbeResolution = 'resolved' | 'timeout' | 'disposed'; ``` --- ## dom.provide: Provide() function Makes a provider available to all child components in the component tree. This function creates a provider context that child components can access using `Use`. The provider is automatically disposed when the component is unmounted. **Signature:**```typescript Provide: (provider: Provider, options: O, child: () => TNode) => Renderable ```## dom.provide: Parameters | Parameter | Type | Description | | --- | --- | --- | | provider | [Provider](#dom-provider)<T, O> | The provider definition containing mark and create function | | options | O | Options to pass to the provider's create function | | child | () => [TNode](#dom-tnode) | Function that returns the child components that can access the provider | **Returns:** [Renderable](#dom-renderable) A renderable that provides the value to its children ## dom.provide: Example 1```typescript // Create a theme provider const ThemeProvider: Provider> = { mark: makeProviderMark>('Theme'), create: () => { const theme = prop('light') return { value: theme, dispose: () => theme.dispose() } } } // Provide the theme to child components const App = () => Provide( ThemeProvider, {}, // options () => html.div( html.h1('My App'), ThemeToggle(), // Can access the theme MainContent() // Can also access the theme ) ) ``` ## dom.provide: Example 2 ```typescript // Provider with options const ConfigProvider: Provider = { mark: makeProviderMark('Config'), create: (options) => { const config = new Config(options.apiUrl) return { value: config, dispose: () => config.cleanup() } } } // Provide with specific options Provide( ConfigProvider, { apiUrl: 'https://api.example.com' }, () => AppContent() ) ``` --- ## dom.provider: Provider type Represents a provider for a specific type `T`. **Signature:**```typescript export type Provider = { mark: ProviderMark; create: (options: O | undefined, ctx: DOMContext) => { value: T; dispose: () => void; onUse?: () => void; }; }; ``` **References:** [DOMContext](#dom-domcontext) --- ## dom.providernotfounderror._constructor_: ProviderNotFoundError.(constructor) Constructs a new instance of the `ProviderNotFoundError` class **Signature:**```typescript constructor(mark: ProviderMark); ```## dom.providernotfounderror._constructor_: Parameters | Parameter | Type | Description | | --- | --- | --- | | mark | ProviderMark<unknown> | | --- ## dom.providernotfounderror: ProviderNotFoundError class Error thrown when a provider is not found. **Signature:**```typescript export declare class ProviderNotFoundError extends Error ```**Extends:** Error ## dom.providernotfounderror: Constructors | Constructor | Modifiers | Description | | --- | --- | --- | | [(constructor)(mark)](#dom-providernotfounderror-constructor) | | Constructs a new instance of the `ProviderNotFoundError` class | --- ## dom.provideroptions: ProviderOptions type Represents an object with provider options. **Signature:**```typescript export type ProviderOptions = { use: (provider: Provider) => T; set: (provider: Provider, options?: O) => void; }; ``` **References:** [Provider](#dom-provider) --- ## dom.providers: Providers type Represents a collection of providers. The keys of the record are ProviderMark types, and the values are of unknown type. **Signature:**```typescript export type Providers = Record, [ unknown, undefined | (() => void) ]>; ``` --- ## dom.referrerpolicy_2: ReferrerPolicy\_2 type **Signature:**```typescript export type ReferrerPolicy = 'no-referrer' | 'no-referrer-when-downgrade' | 'origin' | 'origin-when-cross-origin' | 'same-origin' | 'strict-origin' | 'strict-origin-when-cross-origin' | 'unsafe-url'; ``` --- ## dom.render: render() function Renders a `Renderable` node into a specified parent element or selector. **Signature:**```typescript render: (node: Renderable, parent: Node | string, { doc, clear, disposeWithParent, providers }?: RenderOptions) => () => void ```## dom.render: Parameters | Parameter | Type | Description | | --- | --- | --- | | node | [Renderable](#dom-renderable) | The `Renderable` node to render. | | parent | Node \\| string | The parent element or selector where the node should be rendered. | | { doc, clear, disposeWithParent, providers } | [RenderOptions](#dom-renderoptions) | _(Optional)_ | **Returns:** () => void The result of rendering the `Renderable` node. ## dom.render: Exceptions Throws a `RenderingError` if the parent element cannot be found by the provided selector. --- ## dom.renderable: Renderable type A renderable object that can render content into the DOM. Renderables are the fundamental building blocks of Tempo applications. They are objects with a `render()` method that receives a DOMContext and returns a cleanup function, and a `type` symbol for runtime type checking. This is a specialized version of the core Renderable type for DOM contexts. **Signature:**```typescript export type Renderable = CoreRenderable; ``` **References:** [DOMContext](#dom-domcontext), [DOM\_RENDERABLE\_TYPE](#dom-domrenderabletype) ## dom.renderable: Example 1 ```typescript // Simple renderable that creates a div const MyComponent: Renderable = { type: DOM_RENDERABLE_TYPE, render: (ctx) => { const divCtx = ctx.makeChildElement('div', undefined) divCtx.makeChildText('Hello, World!') // Return cleanup function return (removeTree) => { if (removeTree) { // Cleanup logic here } } } } ``` ## dom.renderable: Example 2 ```typescript // Renderable with event listeners const Button: Renderable = { type: DOM_RENDERABLE_TYPE, render: (ctx) => { const buttonCtx = ctx.makeChildElement('button', undefined) buttonCtx.makeChildText('Click me') const clearClick = buttonCtx.on('click', () => { console.log('Button clicked!') }) return (removeTree) => { clearClick(removeTree) } } } ``` --- ## dom.renderableoftnode: renderableOfTNode() function Converts a TNode into a Renderable. **Signature:**```typescript renderableOfTNode: (child: TNode) => Renderable ```## dom.renderableoftnode: Parameters | Parameter | Type | Description | | --- | --- | --- | | child | [TNode](#dom-tnode)<T> | The TNode to convert. | **Returns:** [Renderable](#dom-renderable)<T> The corresponding Renderable. --- ## dom.renderingerror._constructor_: RenderingError.(constructor) Constructs a new instance of the `RenderingError` class **Signature:**```typescript constructor(message: string); ```## dom.renderingerror._constructor_: Parameters | Parameter | Type | Description | | --- | --- | --- | | message | string | | --- ## dom.renderingerror: RenderingError class Represents an error that occurs during rendering. **Signature:**```typescript export declare class RenderingError extends Error ```**Extends:** Error ## dom.renderingerror: Constructors | Constructor | Modifiers | Description | | --- | --- | --- | | [(constructor)(message)](#dom-renderingerror-constructor) | | Constructs a new instance of the `RenderingError` class | --- ## dom.renderoptions: RenderOptions type Options for rendering. **Signature:**```typescript export type RenderOptions = { doc?: Document; clear?: boolean; disposeWithParent?: boolean; providers?: Providers; }; ``` **References:** [Providers](#dom-providers) --- ## dom.renderwithcontext: renderWithContext() function Renders the given `renderable` with the provided `ctx` DOM context. Creates a DisposalScope for automatic signal disposal. All signals created during the renderable execution are tracked and disposed when the clear function is called. **Signature:**```typescript renderWithContext: (renderable: Renderable, ctx: DOMContext) => (removeTree?: boolean) => void ```## dom.renderwithcontext: Parameters | Parameter | Type | Description | | --- | --- | --- | | renderable | [Renderable](#dom-renderable) | The renderable node to be rendered. | | ctx | [DOMContext](#dom-domcontext) | The DOM context to be used for rendering. | **Returns:** (removeTree?: boolean) => void A function that can be called to clear the rendered node. --- ## dom.repeat: Repeat() function Renders content a specified number of times, with each iteration receiving position information. This function is useful for generating repeated UI elements based on a count rather than an array. Each iteration receives an `ElementPosition` object that provides the current index and position information relative to the total count. **Signature:**```typescript Repeat: (times: Value, element: (index: ElementPosition) => TNode, separator?: (pos: ElementPosition) => TNode) => Renderable ```## dom.repeat: Parameters | Parameter | Type | Description | | --- | --- | --- | | times | Value<number> | A signal or number representing how many times to repeat the content | | element | (index: ElementPosition) => [TNode](#dom-tnode) | Function that returns content for each iteration, receives position information | | separator | (pos: ElementPosition) => [TNode](#dom-tnode) | _(Optional)_ Optional function that returns content to place between iterations | **Returns:** [Renderable](#dom-renderable) A renderable that displays the repeated content ## dom.repeat: Example 1```typescript // Create a simple numbered list const count = prop(5) Repeat(count, (position) => html.div( `Item ${position.index + 1} of ${position.total.value}`, position.isFirst ? ' (first)' : '', position.isLast ? ' (last)' : '' ) ) ``` ## dom.repeat: Example 2 ```typescript // Create a star rating component const rating = prop(3) const maxStars = 5 Repeat(maxStars, (position) => html.span( attr.class(position.index < rating.value ? 'star-filled' : 'star-empty'), '★' ) ) ``` ## dom.repeat: Example 3 ```typescript // With separators between items Repeat(3, (position) => html.span(`Item ${position.index}`), () => html.span(' | ') // Separator ) // Renders: Item 0 | Item 1 | Item 2 ``` ## dom.repeat: Example 4 ```typescript // Dynamic count that updates the UI const itemCount = prop(2) html.div( html.button( on.click(() => itemCount.value++), 'Add Item' ), Repeat(itemCount, (position) => html.div(`Dynamic item ${position.index + 1}`) ) ) ``` --- ## dom.restoretempoplaceholders: restoreTempoPlaceholders() function Restores all placeholders in the DOM. This function is useful when the HTML is rendered on the server and then hydrated on the client. It restores the original content that was replaced with placeholders during the initial render. When you render on the server side, make sure to call `HeadlessAdapter.setFromRoot` with the result of `runHeadless` and the second parameter `setPlaceholders` to `true`. **Signature:**```typescript restoreTempoPlaceholders: () => void ``` **Returns:** void --- ## dom.runheadless: runHeadless() function Runs a renderable function in a headless environment. **Signature:**```typescript runHeadless: (makeRenderable: () => Renderable, { startUrl, selector, providers, }?: HeadlessOptions) => { clear: (removeTree?: boolean) => void; root: HeadlessPortal; currentURL: import('@tempots/core').Prop; } ```## dom.runheadless: Parameters | Parameter | Type | Description | | --- | --- | --- | | makeRenderable | () => [Renderable](#dom-renderable) | A function that returns a Renderable to be rendered in the headless environment. | | { startUrl, selector, providers, } | [HeadlessOptions](#dom-headlessoptions) | _(Optional)_ | **Returns:** { clear: (removeTree?: boolean) => void; root: [HeadlessPortal](#dom-headlessportal); currentURL: import('@tempots/core').Prop<string>; } An object containing the clear function, root element, and current URL Signal of the headless environment. --- ## dom.shadowroot_2: ShadowRoot\_2() function **Signature:**```typescript export declare function ShadowRoot({ mode, delegatesFocus, slotAssignment, clonable, serializable, }: ShadowRootOptions, ...children: TNode[]): import('..').Renderable; ```## dom.shadowroot_2: Parameters | Parameter | Type | Description | | --- | --- | --- | | { mode, delegatesFocus, slotAssignment, clonable, serializable, } | [ShadowRootOptions](#dom-shadowrootoptions) | | | children | [TNode](#dom-tnode)\[\] | | **Returns:** import('..').[Renderable](#dom-renderable) --- ## dom.shadowrootoptions.clonable: ShadowRootOptions.clonable property **Signature:**```typescript clonable?: boolean; ``` --- ## dom.shadowrootoptions.delegatesfocus: ShadowRootOptions.delegatesFocus property **Signature:**```typescript delegatesFocus?: boolean; ``` --- ## dom.shadowrootoptions: ShadowRootOptions interface **Signature:**```typescript export interface ShadowRootOptions ```## dom.shadowrootoptions: Properties | Property | Modifiers | Type | Description | | --- | --- | --- | --- | | [clonable?](#dom-shadowrootoptions-clonable) | | boolean | _(Optional)_ | | [delegatesFocus?](#dom-shadowrootoptions-delegatesfocus) | | boolean | _(Optional)_ | | [mode](#dom-shadowrootoptions-mode) | | 'open' \\| 'closed' | | | [serializable?](#dom-shadowrootoptions-serializable) | | boolean | _(Optional)_ | | [slotAssignment?](#dom-shadowrootoptions-slotassignment) | | 'named' \\| 'manual' | _(Optional)_ | --- ## dom.shadowrootoptions.mode: ShadowRootOptions.mode property **Signature:**```typescript mode: 'open' | 'closed'; ``` --- ## dom.shadowrootoptions.serializable: ShadowRootOptions.serializable property **Signature:**```typescript serializable?: boolean; ``` --- ## dom.shadowrootoptions.slotassignment: ShadowRootOptions.slotAssignment property **Signature:**```typescript slotAssignment?: 'named' | 'manual'; ``` --- ## dom.size: Size type Represents the size of an object with width and height. **Signature:**```typescript export type Size = { readonly width: number; readonly height: number; }; ``` --- ## dom.splitnvalue: SplitNValue type **Signature:**```typescript export type SplitNValue = (T extends unknown ? TupleToUnion[]> : never) | NValue; ``` **References:** [NValue](#dom-nvalue) --- ## dom.splitvalue: SplitValue type **Signature:**```typescript export type SplitValue = (T extends unknown ? TupleToUnion[]> : never) | Value; ``` --- ## dom.streamoptions.generateplaceholders: StreamOptions.generatePlaceholders property Whether to generate placeholder attributes for hydration. **Signature:**```typescript generatePlaceholders?: boolean; ``` --- ## dom.streamoptions: StreamOptions interface Options for streaming HTML output. **Signature:**```typescript export interface StreamOptions ```## dom.streamoptions: Properties | Property | Modifiers | Type | Description | | --- | --- | --- | --- | | [generatePlaceholders?](#dom-streamoptions-generateplaceholders) | | boolean | _(Optional)_ Whether to generate placeholder attributes for hydration. | --- ## dom.style: style variable A collection of functions to create style renderables. **Signature:**```typescript style: { page: (value: NValue) => Renderable; grid: (value: NValue) => Renderable; all: (value: NValue) => Renderable; accentColor: (value: NValue) => Renderable; alignContent: (value: NValue) => Renderable; alignItems: (value: NValue) => Renderable; alignSelf: (value: NValue) => Renderable; alignmentBaseline: (value: NValue) => Renderable; animation: (value: NValue) => Renderable; animationComposition: (value: NValue) => Renderable; animationDelay: (value: NValue) => Renderable; animationDirection: (value: NValue) => Renderable; animationDuration: (value: NValue) => Renderable; animationFillMode: (value: NValue) => Renderable; animationIterationCount: (value: NValue) => Renderable; animationName: (value: NValue) => Renderable; animationPlayState: (value: NValue) => Renderable; animationTimingFunction: (value: NValue) => Renderable; appearance: (value: NValue) => Renderable; aspectRatio: (value: NValue) => Renderable; backdropFilter: (value: NValue) => Renderable; backfaceVisibility: (value: NValue) => Renderable; background: (value: NValue) => Renderable; backgroundAttachment: (value: NValue) => Renderable; backgroundBlendMode: (value: NValue) => Renderable; backgroundClip: (value: NValue) => Renderable; backgroundColor: (value: NValue) => Renderable; backgroundImage: (value: NValue) => Renderable; backgroundOrigin: (value: NValue) => Renderable; backgroundPosition: (value: NValue) => Renderable; backgroundPositionX: (value: NValue) => Renderable; backgroundPositionY: (value: NValue) => Renderable; backgroundRepeat: (value: NValue) => Renderable; backgroundSize: (value: NValue) => Renderable; baselineShift: (value: NValue) => Renderable; baselineSource: (value: NValue) => Renderable; blockSize: (value: NValue) => Renderable; border: (value: NValue) => Renderable; borderBlock: (value: NValue) => Renderable; borderBlockColor: (value: NValue) => Renderable; borderBlockEnd: (value: NValue) => Renderable; borderBlockEndColor: (value: NValue) => Renderable; borderBlockEndStyle: (value: NValue) => Renderable; borderBlockEndWidth: (value: NValue) => Renderable; borderBlockStart: (value: NValue) => Renderable; borderBlockStartColor: (value: NValue) => Renderable; borderBlockStartStyle: (value: NValue) => Renderable; borderBlockStartWidth: (value: NValue) => Renderable; borderBlockStyle: (value: NValue) => Renderable; borderBlockWidth: (value: NValue) => Renderable; borderBottom: (value: NValue) => Renderable; borderBottomColor: (value: NValue) => Renderable; borderBottomLeftRadius: (value: NValue) => Renderable; borderBottomRightRadius: (value: NValue) => Renderable; borderBottomStyle: (value: NValue) => Renderable; borderBottomWidth: (value: NValue) => Renderable; borderCollapse: (value: NValue) => Renderable; borderColor: (value: NValue) => Renderable; borderEndEndRadius: (value: NValue) => Renderable; borderEndStartRadius: (value: NValue) => Renderable; borderImage: (value: NValue) => Renderable; borderImageOutset: (value: NValue) => Renderable; borderImageRepeat: (value: NValue) => Renderable; borderImageSlice: (value: NValue) => Renderable; borderImageSource: (value: NValue) => Renderable; borderImageWidth: (value: NValue) => Renderable; borderInline: (value: NValue) => Renderable; borderInlineColor: (value: NValue) => Renderable; borderInlineEnd: (value: NValue) => Renderable; borderInlineEndColor: (value: NValue) => Renderable; borderInlineEndStyle: (value: NValue) => Renderable; borderInlineEndWidth: (value: NValue) => Renderable; borderInlineStart: (value: NValue) => Renderable; borderInlineStartColor: (value: NValue) => Renderable; borderInlineStartStyle: (value: NValue) => Renderable; borderInlineStartWidth: (value: NValue) => Renderable; borderInlineStyle: (value: NValue) => Renderable; borderInlineWidth: (value: NValue) => Renderable; borderLeft: (value: NValue) => Renderable; borderLeftColor: (value: NValue) => Renderable; borderLeftStyle: (value: NValue) => Renderable; borderLeftWidth: (value: NValue) => Renderable; borderRadius: (value: NValue) => Renderable; borderRight: (value: NValue) => Renderable; borderRightColor: (value: NValue) => Renderable; borderRightStyle: (value: NValue) => Renderable; borderRightWidth: (value: NValue) => Renderable; borderSpacing: (value: NValue) => Renderable; borderStartEndRadius: (value: NValue) => Renderable; borderStartStartRadius: (value: NValue) => Renderable; borderStyle: (value: NValue) => Renderable; borderTop: (value: NValue) => Renderable; borderTopColor: (value: NValue) => Renderable; borderTopLeftRadius: (value: NValue) => Renderable; borderTopRightRadius: (value: NValue) => Renderable; borderTopStyle: (value: NValue) => Renderable; borderTopWidth: (value: NValue) => Renderable; borderWidth: (value: NValue) => Renderable; bottom: (value: NValue) => Renderable; boxDecorationBreak: (value: NValue) => Renderable; boxShadow: (value: NValue) => Renderable; boxSizing: (value: NValue) => Renderable; breakAfter: (value: NValue) => Renderable; breakBefore: (value: NValue) => Renderable; breakInside: (value: NValue) => Renderable; captionSide: (value: NValue) => Renderable; caretColor: (value: NValue) => Renderable; clear: (value: NValue) => Renderable; clip: (value: NValue) => Renderable; clipPath: (value: NValue) => Renderable; clipRule: (value: NValue) => Renderable; color: (value: NValue) => Renderable; colorInterpolation: (value: NValue) => Renderable; colorInterpolationFilters: (value: NValue) => Renderable; colorScheme: (value: NValue) => Renderable; columnCount: (value: NValue) => Renderable; columnFill: (value: NValue) => Renderable; columnGap: (value: NValue) => Renderable; columnRule: (value: NValue) => Renderable; columnRuleColor: (value: NValue) => Renderable; columnRuleStyle: (value: NValue) => Renderable; columnRuleWidth: (value: NValue) => Renderable; columnSpan: (value: NValue) => Renderable; columnWidth: (value: NValue) => Renderable; columns: (value: NValue) => Renderable; contain: (value: NValue) => Renderable; containIntrinsicBlockSize: (value: NValue) => Renderable; containIntrinsicHeight: (value: NValue) => Renderable; containIntrinsicInlineSize: (value: NValue) => Renderable; containIntrinsicSize: (value: NValue) => Renderable; containIntrinsicWidth: (value: NValue) => Renderable; container: (value: NValue) => Renderable; containerName: (value: NValue) => Renderable; containerType: (value: NValue) => Renderable; content: (value: NValue) => Renderable; contentVisibility: (value: NValue) => Renderable; counterIncrement: (value: NValue) => Renderable; counterReset: (value: NValue) => Renderable; counterSet: (value: NValue) => Renderable; cssFloat: (value: NValue) => Renderable; cssText: (value: NValue) => Renderable; cursor: (value: NValue) => Renderable; cx: (value: NValue) => Renderable; cy: (value: NValue) => Renderable; d: (value: NValue) => Renderable; direction: (value: NValue) => Renderable; display: (value: NValue) => Renderable; dominantBaseline: (value: NValue) => Renderable; emptyCells: (value: NValue) => Renderable; fill: (value: NValue) => Renderable; fillOpacity: (value: NValue) => Renderable; fillRule: (value: NValue) => Renderable; filter: (value: NValue) => Renderable; flex: (value: NValue) => Renderable; flexBasis: (value: NValue) => Renderable; flexDirection: (value: NValue) => Renderable; flexFlow: (value: NValue) => Renderable; flexGrow: (value: NValue) => Renderable; flexShrink: (value: NValue) => Renderable; flexWrap: (value: NValue) => Renderable; float: (value: NValue) => Renderable; floodColor: (value: NValue) => Renderable; floodOpacity: (value: NValue) => Renderable; font: (value: NValue) => Renderable; fontFamily: (value: NValue) => Renderable; fontFeatureSettings: (value: NValue) => Renderable; fontKerning: (value: NValue) => Renderable; fontOpticalSizing: (value: NValue) => Renderable; fontPalette: (value: NValue) => Renderable; fontSize: (value: NValue) => Renderable; fontSizeAdjust: (value: NValue) => Renderable; fontStretch: (value: NValue) => Renderable; fontStyle: (value: NValue) => Renderable; fontSynthesis: (value: NValue) => Renderable; fontSynthesisSmallCaps: (value: NValue) => Renderable; fontSynthesisStyle: (value: NValue) => Renderable; fontSynthesisWeight: (value: NValue) => Renderable; fontVariant: (value: NValue) => Renderable; fontVariantAlternates: (value: NValue) => Renderable; fontVariantCaps: (value: NValue) => Renderable; fontVariantEastAsian: (value: NValue) => Renderable; fontVariantLigatures: (value: NValue) => Renderable; fontVariantNumeric: (value: NValue) => Renderable; fontVariantPosition: (value: NValue) => Renderable; fontVariationSettings: (value: NValue) => Renderable; fontWeight: (value: NValue) => Renderable; forcedColorAdjust: (value: NValue) => Renderable; gap: (value: NValue) => Renderable; gridArea: (value: NValue) => Renderable; gridAutoColumns: (value: NValue) => Renderable; gridAutoFlow: (value: NValue) => Renderable; gridAutoRows: (value: NValue) => Renderable; gridColumn: (value: NValue) => Renderable; gridColumnEnd: (value: NValue) => Renderable; gridColumnGap: (value: NValue) => Renderable; gridColumnStart: (value: NValue) => Renderable; gridGap: (value: NValue) => Renderable; gridRow: (value: NValue) => Renderable; gridRowEnd: (value: NValue) => Renderable; gridRowGap: (value: NValue) => Renderable; gridRowStart: (value: NValue) => Renderable; gridTemplate: (value: NValue) => Renderable; gridTemplateAreas: (value: NValue) => Renderable; gridTemplateColumns: (value: NValue) => Renderable; gridTemplateRows: (value: NValue) => Renderable; height: (value: NValue) => Renderable; hyphenateCharacter: (value: NValue) => Renderable; hyphenateLimitChars: (value: NValue) => Renderable; hyphens: (value: NValue) => Renderable; imageOrientation: (value: NValue) => Renderable; imageRendering: (value: NValue) => Renderable; inlineSize: (value: NValue) => Renderable; inset: (value: NValue) => Renderable; insetBlock: (value: NValue) => Renderable; insetBlockEnd: (value: NValue) => Renderable; insetBlockStart: (value: NValue) => Renderable; insetInline: (value: NValue) => Renderable; insetInlineEnd: (value: NValue) => Renderable; insetInlineStart: (value: NValue) => Renderable; isolation: (value: NValue) => Renderable; justifyContent: (value: NValue) => Renderable; justifyItems: (value: NValue) => Renderable; justifySelf: (value: NValue) => Renderable; left: (value: NValue) => Renderable; letterSpacing: (value: NValue) => Renderable; lightingColor: (value: NValue) => Renderable; lineBreak: (value: NValue) => Renderable; lineHeight: (value: NValue) => Renderable; listStyle: (value: NValue) => Renderable; listStyleImage: (value: NValue) => Renderable; listStylePosition: (value: NValue) => Renderable; listStyleType: (value: NValue) => Renderable; margin: (value: NValue) => Renderable; marginBlock: (value: NValue) => Renderable; marginBlockEnd: (value: NValue) => Renderable; marginBlockStart: (value: NValue) => Renderable; marginBottom: (value: NValue) => Renderable; marginInline: (value: NValue) => Renderable; marginInlineEnd: (value: NValue) => Renderable; marginInlineStart: (value: NValue) => Renderable; marginLeft: (value: NValue) => Renderable; marginRight: (value: NValue) => Renderable; marginTop: (value: NValue) => Renderable; marker: (value: NValue) => Renderable; markerEnd: (value: NValue) => Renderable; markerMid: (value: NValue) => Renderable; markerStart: (value: NValue) => Renderable; mask: (value: NValue) => Renderable; maskClip: (value: NValue) => Renderable; maskComposite: (value: NValue) => Renderable; maskImage: (value: NValue) => Renderable; maskMode: (value: NValue) => Renderable; maskOrigin: (value: NValue) => Renderable; maskPosition: (value: NValue) => Renderable; maskRepeat: (value: NValue) => Renderable; maskSize: (value: NValue) => Renderable; maskType: (value: NValue) => Renderable; mathDepth: (value: NValue) => Renderable; mathStyle: (value: NValue) => Renderable; maxBlockSize: (value: NValue) => Renderable; maxHeight: (value: NValue) => Renderable; maxInlineSize: (value: NValue) => Renderable; maxWidth: (value: NValue) => Renderable; minBlockSize: (value: NValue) => Renderable; minHeight: (value: NValue) => Renderable; minInlineSize: (value: NValue) => Renderable; minWidth: (value: NValue) => Renderable; mixBlendMode: (value: NValue) => Renderable; objectFit: (value: NValue) => Renderable; objectPosition: (value: NValue) => Renderable; offset: (value: NValue) => Renderable; offsetAnchor: (value: NValue) => Renderable; offsetDistance: (value: NValue) => Renderable; offsetPath: (value: NValue) => Renderable; offsetPosition: (value: NValue) => Renderable; offsetRotate: (value: NValue) => Renderable; opacity: (value: NValue) => Renderable; order: (value: NValue) => Renderable; orphans: (value: NValue) => Renderable; outline: (value: NValue) => Renderable; outlineColor: (value: NValue) => Renderable; outlineOffset: (value: NValue) => Renderable; outlineStyle: (value: NValue) => Renderable; outlineWidth: (value: NValue) => Renderable; overflow: (value: NValue) => Renderable; overflowAnchor: (value: NValue) => Renderable; overflowBlock: (value: NValue) => Renderable; overflowClipMargin: (value: NValue) => Renderable; overflowInline: (value: NValue) => Renderable; overflowWrap: (value: NValue) => Renderable; overflowX: (value: NValue) => Renderable; overflowY: (value: NValue) => Renderable; overscrollBehavior: (value: NValue) => Renderable; overscrollBehaviorBlock: (value: NValue) => Renderable; overscrollBehaviorInline: (value: NValue) => Renderable; overscrollBehaviorX: (value: NValue) => Renderable; overscrollBehaviorY: (value: NValue) => Renderable; padding: (value: NValue) => Renderable; paddingBlock: (value: NValue) => Renderable; paddingBlockEnd: (value: NValue) => Renderable; paddingBlockStart: (value: NValue) => Renderable; paddingBottom: (value: NValue) => Renderable; paddingInline: (value: NValue) => Renderable; paddingInlineEnd: (value: NValue) => Renderable; paddingInlineStart: (value: NValue) => Renderable; paddingLeft: (value: NValue) => Renderable; paddingRight: (value: NValue) => Renderable; paddingTop: (value: NValue) => Renderable; pageBreakAfter: (value: NValue) => Renderable; pageBreakBefore: (value: NValue) => Renderable; pageBreakInside: (value: NValue) => Renderable; paintOrder: (value: NValue) => Renderable; perspective: (value: NValue) => Renderable; perspectiveOrigin: (value: NValue) => Renderable; placeContent: (value: NValue) => Renderable; placeItems: (value: NValue) => Renderable; placeSelf: (value: NValue) => Renderable; pointerEvents: (value: NValue) => Renderable; position: (value: NValue) => Renderable; printColorAdjust: (value: NValue) => Renderable; quotes: (value: NValue) => Renderable; r: (value: NValue) => Renderable; resize: (value: NValue) => Renderable; right: (value: NValue) => Renderable; rotate: (value: NValue) => Renderable; rowGap: (value: NValue) => Renderable; rubyAlign: (value: NValue) => Renderable; rubyPosition: (value: NValue) => Renderable; rx: (value: NValue) => Renderable; ry: (value: NValue) => Renderable; scale: (value: NValue) => Renderable; scrollBehavior: (value: NValue) => Renderable; scrollMargin: (value: NValue) => Renderable; scrollMarginBlock: (value: NValue) => Renderable; scrollMarginBlockEnd: (value: NValue) => Renderable; scrollMarginBlockStart: (value: NValue) => Renderable; scrollMarginBottom: (value: NValue) => Renderable; scrollMarginInline: (value: NValue) => Renderable; scrollMarginInlineEnd: (value: NValue) => Renderable; scrollMarginInlineStart: (value: NValue) => Renderable; scrollMarginLeft: (value: NValue) => Renderable; scrollMarginRight: (value: NValue) => Renderable; scrollMarginTop: (value: NValue) => Renderable; scrollPadding: (value: NValue) => Renderable; scrollPaddingBlock: (value: NValue) => Renderable; scrollPaddingBlockEnd: (value: NValue) => Renderable; scrollPaddingBlockStart: (value: NValue) => Renderable; scrollPaddingBottom: (value: NValue) => Renderable; scrollPaddingInline: (value: NValue) => Renderable; scrollPaddingInlineEnd: (value: NValue) => Renderable; scrollPaddingInlineStart: (value: NValue) => Renderable; scrollPaddingLeft: (value: NValue) => Renderable; scrollPaddingRight: (value: NValue) => Renderable; scrollPaddingTop: (value: NValue) => Renderable; scrollSnapAlign: (value: NValue) => Renderable; scrollSnapStop: (value: NValue) => Renderable; scrollSnapType: (value: NValue) => Renderable; scrollbarColor: (value: NValue) => Renderable; scrollbarGutter: (value: NValue) => Renderable; scrollbarWidth: (value: NValue) => Renderable; shapeImageThreshold: (value: NValue) => Renderable; shapeMargin: (value: NValue) => Renderable; shapeOutside: (value: NValue) => Renderable; shapeRendering: (value: NValue) => Renderable; stopColor: (value: NValue) => Renderable; stopOpacity: (value: NValue) => Renderable; stroke: (value: NValue) => Renderable; strokeDasharray: (value: NValue) => Renderable; strokeDashoffset: (value: NValue) => Renderable; strokeLinecap: (value: NValue) => Renderable; strokeLinejoin: (value: NValue) => Renderable; strokeMiterlimit: (value: NValue) => Renderable; strokeOpacity: (value: NValue) => Renderable; strokeWidth: (value: NValue) => Renderable; tabSize: (value: NValue) => Renderable; tableLayout: (value: NValue) => Renderable; textAlign: (value: NValue) => Renderable; textAlignLast: (value: NValue) => Renderable; textAnchor: (value: NValue) => Renderable; textBox: (value: NValue) => Renderable; textBoxEdge: (value: NValue) => Renderable; textBoxTrim: (value: NValue) => Renderable; textCombineUpright: (value: NValue) => Renderable; textDecoration: (value: NValue) => Renderable; textDecorationColor: (value: NValue) => Renderable; textDecorationLine: (value: NValue) => Renderable; textDecorationSkipInk: (value: NValue) => Renderable; textDecorationStyle: (value: NValue) => Renderable; textDecorationThickness: (value: NValue) => Renderable; textEmphasis: (value: NValue) => Renderable; textEmphasisColor: (value: NValue) => Renderable; textEmphasisPosition: (value: NValue) => Renderable; textEmphasisStyle: (value: NValue) => Renderable; textIndent: (value: NValue) => Renderable; textOrientation: (value: NValue) => Renderable; textOverflow: (value: NValue) => Renderable; textRendering: (value: NValue) => Renderable; textShadow: (value: NValue) => Renderable; textTransform: (value: NValue) => Renderable; textUnderlineOffset: (value: NValue) => Renderable; textUnderlinePosition: (value: NValue) => Renderable; textWrap: (value: NValue) => Renderable; textWrapMode: (value: NValue) => Renderable; textWrapStyle: (value: NValue) => Renderable; top: (value: NValue) => Renderable; touchAction: (value: NValue) => Renderable; transform: (value: NValue) => Renderable; transformBox: (value: NValue) => Renderable; transformOrigin: (value: NValue) => Renderable; transformStyle: (value: NValue) => Renderable; transition: (value: NValue) => Renderable; transitionBehavior: (value: NValue) => Renderable; transitionDelay: (value: NValue) => Renderable; transitionDuration: (value: NValue) => Renderable; transitionProperty: (value: NValue) => Renderable; transitionTimingFunction: (value: NValue) => Renderable; translate: (value: NValue) => Renderable; unicodeBidi: (value: NValue) => Renderable; userSelect: (value: NValue) => Renderable; vectorEffect: (value: NValue) => Renderable; verticalAlign: (value: NValue) => Renderable; viewTransitionClass: (value: NValue) => Renderable; viewTransitionName: (value: NValue) => Renderable; visibility: (value: NValue) => Renderable; webkitAlignContent: (value: NValue) => Renderable; webkitAlignItems: (value: NValue) => Renderable; webkitAlignSelf: (value: NValue) => Renderable; webkitAnimation: (value: NValue) => Renderable; webkitAnimationDelay: (value: NValue) => Renderable; webkitAnimationDirection: (value: NValue) => Renderable; webkitAnimationDuration: (value: NValue) => Renderable; webkitAnimationFillMode: (value: NValue) => Renderable; webkitAnimationIterationCount: (value: NValue) => Renderable; webkitAnimationName: (value: NValue) => Renderable; webkitAnimationPlayState: (value: NValue) => Renderable; webkitAnimationTimingFunction: (value: NValue) => Renderable; webkitAppearance: (value: NValue) => Renderable; webkitBackfaceVisibility: (value: NValue) => Renderable; webkitBackgroundClip: (value: NValue) => Renderable; webkitBackgroundOrigin: (value: NValue) => Renderable; webkitBackgroundSize: (value: NValue) => Renderable; webkitBorderBottomLeftRadius: (value: NValue) => Renderable; webkitBorderBottomRightRadius: (value: NValue) => Renderable; webkitBorderRadius: (value: NValue) => Renderable; webkitBorderTopLeftRadius: (value: NValue) => Renderable; webkitBorderTopRightRadius: (value: NValue) => Renderable; webkitBoxAlign: (value: NValue) => Renderable; webkitBoxFlex: (value: NValue) => Renderable; webkitBoxOrdinalGroup: (value: NValue) => Renderable; webkitBoxOrient: (value: NValue) => Renderable; webkitBoxPack: (value: NValue) => Renderable; webkitBoxShadow: (value: NValue) => Renderable; webkitBoxSizing: (value: NValue) => Renderable; webkitFilter: (value: NValue) => Renderable; webkitFlex: (value: NValue) => Renderable; webkitFlexBasis: (value: NValue) => Renderable; webkitFlexDirection: (value: NValue) => Renderable; webkitFlexFlow: (value: NValue) => Renderable; webkitFlexGrow: (value: NValue) => Renderable; webkitFlexShrink: (value: NValue) => Renderable; webkitFlexWrap: (value: NValue) => Renderable; webkitJustifyContent: (value: NValue) => Renderable; webkitLineClamp: (value: NValue) => Renderable; webkitMask: (value: NValue) => Renderable; webkitMaskBoxImage: (value: NValue) => Renderable; webkitMaskBoxImageOutset: (value: NValue) => Renderable; webkitMaskBoxImageRepeat: (value: NValue) => Renderable; webkitMaskBoxImageSlice: (value: NValue) => Renderable; webkitMaskBoxImageSource: (value: NValue) => Renderable; webkitMaskBoxImageWidth: (value: NValue) => Renderable; webkitMaskClip: (value: NValue) => Renderable; webkitMaskComposite: (value: NValue) => Renderable; webkitMaskImage: (value: NValue) => Renderable; webkitMaskOrigin: (value: NValue) => Renderable; webkitMaskPosition: (value: NValue) => Renderable; webkitMaskRepeat: (value: NValue) => Renderable; webkitMaskSize: (value: NValue) => Renderable; webkitOrder: (value: NValue) => Renderable; webkitPerspective: (value: NValue) => Renderable; webkitPerspectiveOrigin: (value: NValue) => Renderable; webkitTextFillColor: (value: NValue) => Renderable; webkitTextSizeAdjust: (value: NValue) => Renderable; webkitTextStroke: (value: NValue) => Renderable; webkitTextStrokeColor: (value: NValue) => Renderable; webkitTextStrokeWidth: (value: NValue) => Renderable; webkitTransform: (value: NValue) => Renderable; webkitTransformOrigin: (value: NValue) => Renderable; webkitTransformStyle: (value: NValue) => Renderable; webkitTransition: (value: NValue) => Renderable; webkitTransitionDelay: (value: NValue) => Renderable; webkitTransitionDuration: (value: NValue) => Renderable; webkitTransitionProperty: (value: NValue) => Renderable; webkitTransitionTimingFunction: (value: NValue) => Renderable; webkitUserSelect: (value: NValue) => Renderable; whiteSpace: (value: NValue) => Renderable; whiteSpaceCollapse: (value: NValue) => Renderable; widows: (value: NValue) => Renderable; width: (value: NValue) => Renderable; willChange: (value: NValue) => Renderable; wordBreak: (value: NValue) => Renderable; wordSpacing: (value: NValue) => Renderable; wordWrap: (value: NValue) => Renderable; writingMode: (value: NValue) => Renderable; x: (value: NValue) => Renderable; y: (value: NValue) => Renderable; zIndex: (value: NValue) => Renderable; zoom: (value: NValue) => Renderable; variable: (name: `--${string}`, value: NValue) => Renderable; } ``` --- ## dom.styleoptions: StyleOptions type **Signature:**```typescript export type StyleOptions = Merge<{ [AN in keyof CSSStyles]: (value: NValue) => Renderable; }, { variable: (name: `--${string}`, value: NValue) => Renderable; }>; ``` **References:** [Merge](#dom-merge), [CSSStyles](#dom-cssstyles), [NValue](#dom-nvalue), [Renderable](#dom-renderable) --- ## dom.svg: svg variable A convenience object to create Renderables for SVG elements. **Signature:**```typescript svg: { a: (...children: TNode[]) => Renderable; animate: (...children: TNode[]) => Renderable; animateMotion: (...children: TNode[]) => Renderable; animateTransform: (...children: TNode[]) => Renderable; circle: (...children: TNode[]) => Renderable; clipPath: (...children: TNode[]) => Renderable; defs: (...children: TNode[]) => Renderable; desc: (...children: TNode[]) => Renderable; ellipse: (...children: TNode[]) => Renderable; feBlend: (...children: TNode[]) => Renderable; feColorMatrix: (...children: TNode[]) => Renderable; feComponentTransfer: (...children: TNode[]) => Renderable; feComposite: (...children: TNode[]) => Renderable; feConvolveMatrix: (...children: TNode[]) => Renderable; feDiffuseLighting: (...children: TNode[]) => Renderable; feDisplacementMap: (...children: TNode[]) => Renderable; feDistantLight: (...children: TNode[]) => Renderable; feDropShadow: (...children: TNode[]) => Renderable; feFlood: (...children: TNode[]) => Renderable; feFuncA: (...children: TNode[]) => Renderable; feFuncB: (...children: TNode[]) => Renderable; feFuncG: (...children: TNode[]) => Renderable; feFuncR: (...children: TNode[]) => Renderable; feGaussianBlur: (...children: TNode[]) => Renderable; feImage: (...children: TNode[]) => Renderable; feMerge: (...children: TNode[]) => Renderable; feMergeNode: (...children: TNode[]) => Renderable; feMorphology: (...children: TNode[]) => Renderable; feOffset: (...children: TNode[]) => Renderable; fePointLight: (...children: TNode[]) => Renderable; feSpecularLighting: (...children: TNode[]) => Renderable; feSpotLight: (...children: TNode[]) => Renderable; feTile: (...children: TNode[]) => Renderable; feTurbulence: (...children: TNode[]) => Renderable; filter: (...children: TNode[]) => Renderable; foreignObject: (...children: TNode[]) => Renderable; g: (...children: TNode[]) => Renderable; image: (...children: TNode[]) => Renderable; line: (...children: TNode[]) => Renderable; linearGradient: (...children: TNode[]) => Renderable; marker: (...children: TNode[]) => Renderable; mask: (...children: TNode[]) => Renderable; metadata: (...children: TNode[]) => Renderable; mpath: (...children: TNode[]) => Renderable; path: (...children: TNode[]) => Renderable; pattern: (...children: TNode[]) => Renderable; polygon: (...children: TNode[]) => Renderable; polyline: (...children: TNode[]) => Renderable; radialGradient: (...children: TNode[]) => Renderable; rect: (...children: TNode[]) => Renderable; script: (...children: TNode[]) => Renderable; set: (...children: TNode[]) => Renderable; stop: (...children: TNode[]) => Renderable; style: (...children: TNode[]) => Renderable; svg: (...children: TNode[]) => Renderable; switch: (...children: TNode[]) => Renderable; symbol: (...children: TNode[]) => Renderable; text: (...children: TNode[]) => Renderable; textPath: (...children: TNode[]) => Renderable; title: (...children: TNode[]) => Renderable; tspan: (...children: TNode[]) => Renderable; use: (...children: TNode[]) => Renderable; view: (...children: TNode[]) => Renderable; } ``` --- ## dom.svgattr: svgAttr variable An object that provides a convenient way to create mountable attributes for SVG elements. **Signature:**```typescript svgAttr: { 'accent-height': (value: SplitNValue) => Renderable; accumulate: (value: SplitNValue<"none" | "sum">) => Renderable; additive: (value: SplitNValue<"sum" | "replace">) => Renderable; 'alignment-baseline': (value: SplitNValue<"auto" | "baseline" | "before-edge" | "text-before-edge" | "middle" | "central" | "after-edge" | "text-after-edge" | "ideographic" | "alphabetic" | "hanging" | "mathematical" | "inherit">) => Renderable; 'allow-reorder': (value: SplitNValue<"yes" | "no">) => Renderable; alphabetic: (value: SplitNValue) => Renderable; amplitude: (value: SplitNValue) => Renderable; 'arabic-form': (value: SplitNValue<"initial" | "medial" | "terminal" | "isolated">) => Renderable; ascent: (value: SplitNValue) => Renderable; attributeName: (value: SplitNValue) => Renderable; attributeType: (value: SplitNValue<"auto" | "CSS" | "XML">) => Renderable; autoReverse: (value: SplitNValue) => Renderable; azimuth: (value: SplitNValue) => Renderable; baseFrequency: (value: SplitNValue) => Renderable; baseProfile: (value: SplitNValue) => Renderable; 'baseline-shift': (value: SplitNValue) => Renderable; bbox: (value: SplitNValue) => Renderable; begin: (value: SplitNValue) => Renderable; bias: (value: SplitNValue) => Renderable; by: (value: SplitNValue) => Renderable; calcMode: (value: SplitNValue<"discrete" | "linear" | "paced" | "spline">) => Renderable; 'cap-height': (value: SplitNValue) => Renderable; class: (value: SplitNValue) => Renderable; clip: (value: SplitNValue) => Renderable; 'clip-path': (value: SplitNValue) => Renderable; clipPathUnits: (value: SplitNValue<"userSpaceOnUse" | "objectBoundingBox">) => Renderable; clipRule: (value: SplitNValue<"inherit" | "nonzero" | "evenodd">) => Renderable; 'color-interpolation': (value: SplitNValue<"auto" | "inherit" | "sRGB" | "linearRGB">) => Renderable; 'color-interpolation-filters': (value: SplitNValue<"auto" | "inherit" | "sRGB" | "linearRGB">) => Renderable; 'color-profile': (value: SplitNValue) => Renderable; 'color-rendering': (value: SplitNValue<"auto" | "inherit" | "optimizeSpeed" | "optimizeQuality">) => Renderable; contentScriptType: (value: SplitNValue) => Renderable; contentStyleType: (value: SplitNValue) => Renderable; crossorigin: (value: SplitNValue<"anonymous" | "use-credentials">) => Renderable; cursor: (value: SplitNValue) => Renderable; cx: (value: SplitNValue) => Renderable; cy: (value: SplitNValue) => Renderable; d: (value: SplitNValue) => Renderable; decelerate: (value: SplitNValue) => Renderable; descent: (value: SplitNValue) => Renderable; diffuseConstant: (value: SplitNValue) => Renderable; direction: (value: SplitNValue<"ltr" | "rtl" | "inherit">) => Renderable; display: (value: SplitNValue) => Renderable; divisor: (value: SplitNValue) => Renderable; 'dominant-baseline': (value: SplitNValue<"auto" | "middle" | "central" | "ideographic" | "alphabetic" | "hanging" | "mathematical" | "inherit" | "text-bottom" | "text-top">) => Renderable; dur: (value: SplitNValue) => Renderable; dx: (value: SplitNValue) => Renderable; dy: (value: SplitNValue) => Renderable; edgeMode: (value: SplitNValue<"none" | "duplicate" | "wrap">) => Renderable; elevation: (value: SplitNValue) => Renderable; 'enable-background': (value: SplitNValue) => Renderable; end: (value: SplitNValue) => Renderable; exponent: (value: SplitNValue) => Renderable; externalResourcesRequired: (value: SplitNValue) => Renderable; fill: (value: SplitNValue) => Renderable; 'fill-opacity': (value: SplitNValue) => Renderable; 'fill-rule': (value: SplitNValue<"inherit" | "nonzero" | "evenodd">) => Renderable; filter: (value: SplitNValue) => Renderable; filterRes: (value: SplitNValue) => Renderable; filterUnits: (value: SplitNValue<"userSpaceOnUse" | "objectBoundingBox">) => Renderable; 'flood-color': (value: SplitNValue) => Renderable; 'flood-opacity': (value: SplitNValue) => Renderable; focusable: (value: SplitNValue) => Renderable; 'font-family': (value: SplitNValue) => Renderable; 'font-size': (value: SplitNValue) => Renderable; 'font-size-adjust': (value: SplitNValue) => Renderable; 'font-stretch': (value: SplitNValue) => Renderable; 'font-style': (value: SplitNValue<"normal" | "italic" | "inherit" | "oblique">) => Renderable; 'font-variant': (value: SplitNValue) => Renderable; 'font-weight': (value: SplitNValue) => Renderable; format: (value: SplitNValue) => Renderable; fr: (value: SplitNValue) => Renderable; from: (value: SplitNValue) => Renderable; fx: (value: SplitNValue) => Renderable; fy: (value: SplitNValue) => Renderable; g1: (value: SplitNValue) => Renderable; g2: (value: SplitNValue) => Renderable; 'glyph-name': (value: SplitNValue) => Renderable; 'glyph-orientation-horizontal': (value: SplitNValue) => Renderable; 'glyph-orientation-vertical': (value: SplitNValue) => Renderable; glyphRef: (value: SplitNValue) => Renderable; gradientTransform: (value: SplitNValue) => Renderable; gradientUnits: (value: SplitNValue<"userSpaceOnUse" | "objectBoundingBox">) => Renderable; hanging: (value: SplitNValue) => Renderable; height: (value: SplitNValue) => Renderable; 'horiz-adv-x': (value: SplitNValue) => Renderable; 'horiz-origin-x': (value: SplitNValue) => Renderable; 'horiz-origin-y': (value: SplitNValue) => Renderable; href: (value: SplitNValue) => Renderable; id: (value: SplitNValue) => Renderable; ideographic: (value: SplitNValue) => Renderable; 'image-rendering': (value: SplitNValue<"auto" | "inherit" | "optimizeSpeed" | "optimizeQuality">) => Renderable; in: (value: SplitNValue) => Renderable; in2: (value: SplitNValue) => Renderable; intercept: (value: SplitNValue) => Renderable; k: (value: SplitNValue) => Renderable; k1: (value: SplitNValue) => Renderable; k2: (value: SplitNValue) => Renderable; k3: (value: SplitNValue) => Renderable; k4: (value: SplitNValue) => Renderable; kernelMatrix: (value: SplitNValue) => Renderable; kernelUnitLength: (value: SplitNValue) => Renderable; kerning: (value: SplitNValue) => Renderable; keyPoints: (value: SplitNValue) => Renderable; keySplines: (value: SplitNValue) => Renderable; keyTimes: (value: SplitNValue) => Renderable; lang: (value: SplitNValue) => Renderable; lengthAdjust: (value: SplitNValue<"spacing" | "spacingAndGlyphs">) => Renderable; 'letter-spacing': (value: SplitNValue) => Renderable; 'lighting-color': (value: SplitNValue) => Renderable; limitingConeAngle: (value: SplitNValue) => Renderable; local: (value: SplitNValue) => Renderable; 'marker-end': (value: SplitNValue) => Renderable; markerHeight: (value: SplitNValue) => Renderable; 'marker-mid': (value: SplitNValue) => Renderable; 'marker-start': (value: SplitNValue) => Renderable; markerUnits: (value: SplitNValue<"strokeWidth" | "userSpaceOnUse">) => Renderable; markerWidth: (value: SplitNValue) => Renderable; mask: (value: SplitNValue) => Renderable; maskContentUnits: (value: SplitNValue<"userSpaceOnUse" | "objectBoundingBox">) => Renderable; maskUnits: (value: SplitNValue<"userSpaceOnUse" | "objectBoundingBox">) => Renderable; mathematical: (value: SplitNValue) => Renderable; max: (value: SplitNValue) => Renderable; media: (value: SplitNValue) => Renderable; method: (value: SplitNValue<"align" | "stretch">) => Renderable; min: (value: SplitNValue) => Renderable; mode: (value: SplitNValue<"normal" | "multiply" | "screen" | "darken" | "lighten">) => Renderable; name: (value: SplitNValue) => Renderable; numOctaves: (value: SplitNValue) => Renderable; offset: (value: SplitNValue) => Renderable; opacity: (value: SplitNValue) => Renderable; operator: (value: SplitNValue<"over" | "in" | "out" | "atop" | "xor" | "lighter" | "arithmetic">) => Renderable; order: (value: SplitNValue) => Renderable; orient: (value: SplitNValue) => Renderable; orientation: (value: SplitNValue<"h" | "v">) => Renderable; origin: (value: SplitNValue) => Renderable; overflow: (value: SplitNValue<"auto" | "hidden" | "scroll" | "inherit" | "visible">) => Renderable; 'overline-position': (value: SplitNValue) => Renderable; 'overline-thickness': (value: SplitNValue) => Renderable; 'paint-order': (value: SplitNValue) => Renderable; 'panose-1': (value: SplitNValue) => Renderable; path: (value: SplitNValue) => Renderable; pathLength: (value: SplitNValue) => Renderable; patternContentUnits: (value: SplitNValue<"userSpaceOnUse" | "objectBoundingBox">) => Renderable; patternTransform: (value: SplitNValue) => Renderable; patternUnits: (value: SplitNValue<"userSpaceOnUse" | "objectBoundingBox">) => Renderable; 'pointer-events': (value: SplitNValue<"none" | "all" | "fill" | "stroke" | "inherit" | "visible" | "bounding-box" | "visiblePainted" | "visibleFill" | "visibleStroke" | "painted">) => Renderable; points: (value: SplitNValue) => Renderable; pointsAtX: (value: SplitNValue) => Renderable; pointsAtY: (value: SplitNValue) => Renderable; pointsAtZ: (value: SplitNValue) => Renderable; preserveAlpha: (value: SplitNValue) => Renderable; preserveAspectRatio: (value: SplitNValue) => Renderable; primitiveUnits: (value: SplitNValue<"userSpaceOnUse" | "objectBoundingBox">) => Renderable; r: (value: SplitNValue) => Renderable; radius: (value: SplitNValue) => Renderable; refX: (value: SplitNValue) => Renderable; refY: (value: SplitNValue) => Renderable; 'rendering-intent': (value: SplitNValue<"auto" | "inherit" | "perceptual" | "relative-colorimetric" | "saturation" | "absolute-colorimetric">) => Renderable; repeatCount: (value: SplitNValue) => Renderable; repeatDur: (value: SplitNValue) => Renderable; requiredExtensions: (value: SplitNValue) => Renderable; requiredFeatures: (value: SplitNValue) => Renderable; restart: (value: SplitNValue<"always" | "whenNotActive" | "never">) => Renderable; result: (value: SplitNValue) => Renderable; role: (value: SplitNValue) => Renderable; rotate: (value: SplitNValue) => Renderable; rx: (value: SplitNValue) => Renderable; ry: (value: SplitNValue) => Renderable; scale: (value: SplitNValue) => Renderable; seed: (value: SplitNValue) => Renderable; 'shape-rendering': (value: SplitNValue<"auto" | "inherit" | "optimizeSpeed" | "crispEdges" | "geometricPrecision">) => Renderable; side: (value: SplitNValue<"left" | "right">) => Renderable; slope: (value: SplitNValue) => Renderable; spacing: (value: SplitNValue<"auto" | "exact">) => Renderable; specularConstant: (value: SplitNValue) => Renderable; specularExponent: (value: SplitNValue) => Renderable; speed: (value: SplitNValue) => Renderable; spreadMethod: (value: SplitNValue<"pad" | "reflect" | "repeat">) => Renderable; startOffset: (value: SplitNValue) => Renderable; stdDeviation: (value: SplitNValue) => Renderable; stemh: (value: SplitNValue) => Renderable; stemv: (value: SplitNValue) => Renderable; stitchTiles: (value: SplitNValue<"noStitch" | "stitch">) => Renderable; 'stop-color': (value: SplitNValue) => Renderable; 'stop-opacity': (value: SplitNValue) => Renderable; 'strikethrough-position': (value: SplitNValue) => Renderable; 'strikethrough-thickness': (value: SplitNValue) => Renderable; string: (value: SplitNValue) => Renderable; stroke: (value: SplitNValue) => Renderable; 'stroke-dasharray': (value: SplitNValue) => Renderable; 'stroke-dashoffset': (value: SplitNValue) => Renderable; 'stroke-linecap': (value: SplitNValue<"inherit" | "butt" | "round" | "square">) => Renderable; 'stroke-linejoin': (value: SplitNValue<"inherit" | "round" | "miter" | "bevel">) => Renderable; 'stroke-miterlimit': (value: SplitNValue) => Renderable; 'stroke-opacity': (value: SplitNValue) => Renderable; 'stroke-width': (value: SplitNValue) => Renderable; style: (value: SplitNValue) => Renderable; surfaceScale: (value: SplitNValue) => Renderable; systemLanguage: (value: SplitNValue) => Renderable; tabindex: (value: SplitNValue) => Renderable; tableValues: (value: SplitNValue) => Renderable; target: (value: SplitNValue) => Renderable; targetX: (value: SplitNValue) => Renderable; targetY: (value: SplitNValue) => Renderable; 'text-anchor': (value: SplitNValue<"middle" | "inherit" | "start" | "end">) => Renderable; 'text-decoration': (value: SplitNValue<"none" | "inherit" | "underline" | "overline" | "line-through" | "blink">) => Renderable; textLength: (value: SplitNValue) => Renderable; 'text-rendering': (value: SplitNValue<"auto" | "inherit" | "optimizeSpeed" | "geometricPrecision" | "optimizeLegibility">) => Renderable; title: (value: SplitNValue) => Renderable; to: (value: SplitNValue) => Renderable; transform: (value: SplitNValue) => Renderable; 'transform-origin': (value: SplitNValue) => Renderable; type: (value: SplitNValue) => Renderable; u1: (value: SplitNValue) => Renderable; u2: (value: SplitNValue) => Renderable; 'underline-position': (value: SplitNValue) => Renderable; 'underline-thickness': (value: SplitNValue) => Renderable; unicode: (value: SplitNValue) => Renderable; 'unicode-bidi': (value: SplitNValue<"normal" | "inherit" | "embed" | "isolate" | "bidi-override" | "isolate-override" | "plaintext">) => Renderable; 'unicode-range': (value: SplitNValue) => Renderable; 'units-per-em': (value: SplitNValue) => Renderable; 'v-alphabetic': (value: SplitNValue) => Renderable; values: (value: SplitNValue) => Renderable; 'vector-effect': (value: SplitNValue<"none" | "non-scaling-stroke" | "non-scaling-size" | "non-rotation" | "fixed-position">) => Renderable; version: (value: SplitNValue) => Renderable; 'vert-adv-y': (value: SplitNValue) => Renderable; 'vert-origin-x': (value: SplitNValue) => Renderable; 'vert-origin-y': (value: SplitNValue) => Renderable; 'v-hanging': (value: SplitNValue) => Renderable; 'v-ideographic': (value: SplitNValue) => Renderable; viewBox: (value: SplitNValue) => Renderable; viewTarget: (value: SplitNValue) => Renderable; visibility: (value: SplitNValue<"hidden" | "inherit" | "visible" | "collapse">) => Renderable; 'v-mathematical': (value: SplitNValue) => Renderable; width: (value: SplitNValue) => Renderable; widths: (value: SplitNValue) => Renderable; 'word-spacing': (value: SplitNValue) => Renderable; 'writing-mode': (value: SplitNValue<"inherit" | "lr-tb" | "rl-tb" | "tb-rl" | "lr" | "rl" | "tb">) => Renderable; x1: (value: SplitNValue) => Renderable; x2: (value: SplitNValue) => Renderable; x: (value: SplitNValue) => Renderable; xChannelSelector: (value: SplitNValue<"R" | "G" | "B" | "A">) => Renderable; 'x-height': (value: SplitNValue) => Renderable; 'xlink:actuate': (value: SplitNValue<"none" | "other" | "onLoad" | "onRequest">) => Renderable; 'xlink:arcrole': (value: SplitNValue) => Renderable; 'xlink:href': (value: SplitNValue) => Renderable; 'xlink:role': (value: SplitNValue) => Renderable; 'xlink:show': (value: SplitNValue<"none" | "other" | "replace" | "embed" | "new">) => Renderable; 'xlink:title': (value: SplitNValue) => Renderable; 'xlink:type': (value: SplitNValue<"none" | "simple" | "extended" | "locator" | "arc" | "resource" | "title">) => Renderable; xlinkActuate: (value: SplitNValue<"none" | "other" | "onLoad" | "onRequest">) => Renderable; xlinkArcrole: (value: SplitNValue) => Renderable; xlinkHref: (value: SplitNValue) => Renderable; xlinkRole: (value: SplitNValue) => Renderable; xlinkShow: (value: SplitNValue<"none" | "other" | "replace" | "embed" | "new">) => Renderable; xlinkTitle: (value: SplitNValue) => Renderable; xlinkType: (value: SplitNValue<"none" | "simple" | "extended" | "locator" | "arc" | "resource" | "title">) => Renderable; 'xml:base': (value: SplitNValue) => Renderable; 'xml:lang': (value: SplitNValue) => Renderable; 'xml:space': (value: SplitNValue<"default" | "preserve">) => Renderable; xmlBase: (value: SplitNValue) => Renderable; xmlLang: (value: SplitNValue) => Renderable; xmlns: (value: SplitNValue) => Renderable; 'xmlns:xlink': (value: SplitNValue) => Renderable; xmlnsXlink: (value: SplitNValue) => Renderable; xmlSpace: (value: SplitNValue<"default" | "preserve">) => Renderable; y1: (value: SplitNValue) => Renderable; y2: (value: SplitNValue) => Renderable; y: (value: SplitNValue) => Renderable; yChannelSelector: (value: SplitNValue<"R" | "G" | "B" | "A">) => Renderable; z: (value: SplitNValue) => Renderable; zoomAndPan: (value: SplitNValue<"disable" | "magnify">) => Renderable; } ``` ## dom.svgattr: Example ```ts const svg = html.svg( svgAttr.width(100), svgAttr.height(height), // where height is a `Signal` // ... ) ``` --- ## dom.svgattributes: SVGAttributes type Represents the attributes that can be used in SVG elements. **Signature:**```typescript export type SVGAttributes = { 'accent-height': number | string; accumulate: 'none' | 'sum'; additive: 'replace' | 'sum'; 'alignment-baseline': 'auto' | 'baseline' | 'before-edge' | 'text-before-edge' | 'middle' | 'central' | 'after-edge' | 'text-after-edge' | 'ideographic' | 'alphabetic' | 'hanging' | 'mathematical' | 'inherit'; 'allow-reorder': 'no' | 'yes'; alphabetic: number | string; amplitude: number | string; 'arabic-form': 'initial' | 'medial' | 'terminal' | 'isolated'; ascent: number | string; attributeName: string; attributeType: 'CSS' | 'XML' | 'auto'; autoReverse: boolean | string; azimuth: number | string; baseFrequency: number | string; baseProfile: string; 'baseline-shift': number | string; bbox: string; begin: string; bias: number | string; by: string; calcMode: 'discrete' | 'linear' | 'paced' | 'spline'; 'cap-height': number | string; class: string; clip: string; 'clip-path': string; clipPathUnits: 'userSpaceOnUse' | 'objectBoundingBox'; clipRule: 'nonzero' | 'evenodd' | 'inherit'; 'color-interpolation': 'auto' | 'sRGB' | 'linearRGB' | 'inherit'; 'color-interpolation-filters': 'auto' | 'sRGB' | 'linearRGB' | 'inherit'; 'color-profile': string; 'color-rendering': 'auto' | 'optimizeSpeed' | 'optimizeQuality' | 'inherit'; contentScriptType: string; contentStyleType: string; crossorigin: 'anonymous' | 'use-credentials'; cursor: string; cx: number | string; cy: number | string; d: string; decelerate: number | string; descent: number | string; diffuseConstant: number | string; direction: 'ltr' | 'rtl' | 'inherit'; display: string; divisor: number | string; 'dominant-baseline': 'auto' | 'text-bottom' | 'alphabetic' | 'ideographic' | 'middle' | 'central' | 'mathematical' | 'hanging' | 'text-top' | 'inherit'; dur: string; dx: number | string; dy: number | string; edgeMode: 'duplicate' | 'wrap' | 'none'; elevation: number | string; 'enable-background': string; end: string; exponent: number | string; externalResourcesRequired: boolean | string; fill: string; 'fill-opacity': number | string; 'fill-rule': 'nonzero' | 'evenodd' | 'inherit'; filter: string; filterRes: string; filterUnits: 'userSpaceOnUse' | 'objectBoundingBox'; 'flood-color': string; 'flood-opacity': number | string; focusable: boolean | 'auto' | string; 'font-family': string; 'font-size': number | string; 'font-size-adjust': number | string; 'font-stretch': string; 'font-style': 'normal' | 'italic' | 'oblique' | 'inherit'; 'font-variant': string; 'font-weight': string; format: string; fr: number | string; from: string; fx: number | string; fy: number | string; g1: string; g2: string; 'glyph-name': string; 'glyph-orientation-horizontal': number | string; 'glyph-orientation-vertical': number | string; glyphRef: string; gradientTransform: string; gradientUnits: 'userSpaceOnUse' | 'objectBoundingBox'; hanging: number | string; height: number | string; 'horiz-adv-x': number | string; 'horiz-origin-x': number | string; 'horiz-origin-y': number | string; href: string; id: string; ideographic: number | string; 'image-rendering': 'auto' | 'optimizeSpeed' | 'optimizeQuality' | 'inherit'; in: string; in2: string; intercept: number | string; k: number | string; k1: number | string; k2: number | string; k3: number | string; k4: number | string; kernelMatrix: string; kernelUnitLength: number | string; kerning: number | string; keyPoints: string; keySplines: string; keyTimes: string; lang: string; lengthAdjust: 'spacing' | 'spacingAndGlyphs'; 'letter-spacing': number | string; 'lighting-color': string; limitingConeAngle: number | string; local: string; 'marker-end': string; markerHeight: number | string; 'marker-mid': string; 'marker-start': string; markerUnits: 'userSpaceOnUse' | 'strokeWidth'; markerWidth: number | string; mask: string; maskContentUnits: 'userSpaceOnUse' | 'objectBoundingBox'; maskUnits: 'userSpaceOnUse' | 'objectBoundingBox'; mathematical: number | string; max: string; media: string; method: 'align' | 'stretch'; min: string; mode: 'normal' | 'multiply' | 'screen' | 'darken' | 'lighten'; name: string; numOctaves: number | string; offset: number | string; opacity: number | string; operator: 'over' | 'in' | 'out' | 'atop' | 'xor' | 'lighter' | 'arithmetic'; order: number | string; orient: 'auto' | 'auto-start-reverse' | number | string; orientation: 'h' | 'v'; origin: string; overflow: 'visible' | 'hidden' | 'scroll' | 'auto' | 'inherit'; 'overline-position': number | string; 'overline-thickness': number | string; 'paint-order': string; 'panose-1': string; path: string; pathLength: number | string; patternContentUnits: 'userSpaceOnUse' | 'objectBoundingBox'; patternTransform: string; patternUnits: 'userSpaceOnUse' | 'objectBoundingBox'; 'pointer-events': 'bounding-box' | 'visiblePainted' | 'visibleFill' | 'visibleStroke' | 'visible' | 'painted' | 'fill' | 'stroke' | 'all' | 'none' | 'inherit'; points: string; pointsAtX: number | string; pointsAtY: number | string; pointsAtZ: number | string; preserveAlpha: boolean | string; preserveAspectRatio: string; primitiveUnits: 'userSpaceOnUse' | 'objectBoundingBox'; r: number | string; radius: number | string; refX: number | string; refY: number | string; 'rendering-intent': 'auto' | 'perceptual' | 'relative-colorimetric' | 'saturation' | 'absolute-colorimetric' | 'inherit'; repeatCount: number | string; repeatDur: string; requiredExtensions: string; requiredFeatures: string; restart: 'always' | 'whenNotActive' | 'never'; result: string; role: string; rotate: number | string; rx: number | string; ry: number | string; scale: number | string; seed: number | string; 'shape-rendering': 'auto' | 'optimizeSpeed' | 'crispEdges' | 'geometricPrecision' | 'inherit'; side: 'left' | 'right'; slope: number | string; spacing: 'auto' | 'exact'; specularConstant: number | string; specularExponent: number | string; speed: number | string; spreadMethod: 'pad' | 'reflect' | 'repeat'; startOffset: number | string; stdDeviation: number | string; stemh: number | string; stemv: number | string; stitchTiles: 'noStitch' | 'stitch'; 'stop-color': string; 'stop-opacity': number | string; 'strikethrough-position': number | string; 'strikethrough-thickness': number | string; string: string; stroke: string; 'stroke-dasharray': string; 'stroke-dashoffset': number | string; 'stroke-linecap': 'butt' | 'round' | 'square' | 'inherit'; 'stroke-linejoin': 'miter' | 'round' | 'bevel' | 'inherit'; 'stroke-miterlimit': number | string; 'stroke-opacity': number | string; 'stroke-width': number | string; style: string; surfaceScale: number | string; systemLanguage: string; tabindex: number | string; tableValues: string; target: string; targetX: number | string; targetY: number | string; 'text-anchor': 'start' | 'middle' | 'end' | 'inherit'; 'text-decoration': 'none' | 'underline' | 'overline' | 'line-through' | 'blink' | 'inherit'; textLength: number | string; 'text-rendering': 'auto' | 'optimizeSpeed' | 'optimizeLegibility' | 'geometricPrecision' | 'inherit'; title: string; to: string; transform: string; 'transform-origin': string; type: string; u1: string; u2: string; 'underline-position': number | string; 'underline-thickness': number | string; unicode: string; 'unicode-bidi': 'normal' | 'embed' | 'isolate' | 'bidi-override' | 'isolate-override' | 'plaintext' | 'inherit'; 'unicode-range': string; 'units-per-em': number | string; 'v-alphabetic': number | string; values: string; 'vector-effect': 'none' | 'non-scaling-stroke' | 'non-scaling-size' | 'non-rotation' | 'fixed-position'; version: string; 'vert-adv-y': number | string; 'vert-origin-x': number | string; 'vert-origin-y': number | string; 'v-hanging': number | string; 'v-ideographic': number | string; viewBox: string; viewTarget: string; visibility: 'visible' | 'hidden' | 'collapse' | 'inherit'; 'v-mathematical': number | string; width: number | string; widths: string; 'word-spacing': number | string; 'writing-mode': 'lr-tb' | 'rl-tb' | 'tb-rl' | 'lr' | 'rl' | 'tb' | 'inherit'; x1: number | string; x2: number | string; x: number | string; xChannelSelector: 'R' | 'G' | 'B' | 'A'; 'x-height': number | string; 'xlink:actuate': 'onLoad' | 'onRequest' | 'other' | 'none'; 'xlink:arcrole': string; 'xlink:href': string; 'xlink:role': string; 'xlink:show': 'new' | 'replace' | 'embed' | 'other' | 'none'; 'xlink:title': string; 'xlink:type': 'simple' | 'extended' | 'locator' | 'arc' | 'resource' | 'title' | 'none'; xlinkActuate: 'onLoad' | 'onRequest' | 'other' | 'none'; xlinkArcrole: string; xlinkHref: string; xlinkRole: string; xlinkShow: 'new' | 'replace' | 'embed' | 'other' | 'none'; xlinkTitle: string; xlinkType: 'simple' | 'extended' | 'locator' | 'arc' | 'resource' | 'title' | 'none'; 'xml:base': string; 'xml:lang': string; 'xml:space': 'default' | 'preserve'; xmlBase: string; xmlLang: string; xmlns: string; 'xmlns:xlink': string; xmlnsXlink: string; xmlSpace: 'default' | 'preserve'; y1: number | string; y2: number | string; y: number | string; yChannelSelector: 'R' | 'G' | 'B' | 'A'; z: number | string; zoomAndPan: 'disable' | 'magnify'; }; ``` --- ## dom.svgel: SVGEl() function Creates a Renderable that represents an SVG element. **Signature:**```typescript SVGEl: (tagName: string, ...children: TNode[]) => Renderable ```## dom.svgel: Parameters | Parameter | Type | Description | | --- | --- | --- | | tagName | string | The tag name of the SVG element. | | children | [TNode](#dom-tnode)\[\] | The child nodes of the SVG element. | **Returns:** [Renderable](#dom-renderable) A renderable function that creates and appends the SVG element to the DOM. --- ## dom.svgtags: SVGTags type Represents a mapping of SVG tag names to their corresponding SVG element types. **Signature:**```typescript export type SVGTags = { a: SVGAElement; animate: SVGAnimateElement; animateMotion: SVGAnimateMotionElement; animateTransform: SVGAnimateTransformElement; circle: SVGCircleElement; clipPath: SVGClipPathElement; defs: SVGDefsElement; desc: SVGDescElement; ellipse: SVGEllipseElement; feBlend: SVGFEBlendElement; feColorMatrix: SVGFEColorMatrixElement; feComponentTransfer: SVGFEComponentTransferElement; feComposite: SVGFECompositeElement; feConvolveMatrix: SVGFEConvolveMatrixElement; feDiffuseLighting: SVGFEDiffuseLightingElement; feDisplacementMap: SVGFEDisplacementMapElement; feDistantLight: SVGFEDistantLightElement; feDropShadow: SVGFEDropShadowElement; feFlood: SVGFEFloodElement; feFuncA: SVGFEFuncAElement; feFuncB: SVGFEFuncBElement; feFuncG: SVGFEFuncGElement; feFuncR: SVGFEFuncRElement; feGaussianBlur: SVGFEGaussianBlurElement; feImage: SVGFEImageElement; feMerge: SVGFEMergeElement; feMergeNode: SVGFEMergeNodeElement; feMorphology: SVGFEMorphologyElement; feOffset: SVGFEOffsetElement; fePointLight: SVGFEPointLightElement; feSpecularLighting: SVGFESpecularLightingElement; feSpotLight: SVGFESpotLightElement; feTile: SVGFETileElement; feTurbulence: SVGFETurbulenceElement; filter: SVGFilterElement; foreignObject: SVGForeignObjectElement; g: SVGGElement; image: SVGImageElement; line: SVGLineElement; linearGradient: SVGLinearGradientElement; marker: SVGMarkerElement; mask: SVGMaskElement; metadata: SVGMetadataElement; mpath: SVGMPathElement; path: SVGPathElement; pattern: SVGPatternElement; polygon: SVGPolygonElement; polyline: SVGPolylineElement; radialGradient: SVGRadialGradientElement; rect: SVGRectElement; script: SVGScriptElement; set: SVGSetElement; stop: SVGStopElement; style: SVGStyleElement; svg: SVGSVGElement; switch: SVGSwitchElement; symbol: SVGSymbolElement; text: SVGTextElement; textPath: SVGTextPathElement; title: SVGTitleElement; tspan: SVGTSpanElement; use: SVGUseElement; view: SVGViewElement; }; ``` --- ## dom.task: Task() function Represents a renderable task that can be executed asynchronously. **Signature:**```typescript Task: (task: () => Promise, options: TaskOptions | ((value: T) => TNode)) => Renderable ```## dom.task: Parameters | Parameter | Type | Description | | --- | --- | --- | | task | () => Promise<T> | The asynchronous task to be executed. | | options | [TaskOptions](#dom-taskoptions)<T> \\| ((value: T) => [TNode](#dom-tnode)) | The options for the task or a function that transforms the task result into a renderable node. | **Returns:** [Renderable](#dom-renderable) - A renderable object that renders the task and returns a cleanup function. --- ## dom.taskoptions: TaskOptions type Represents the options for a task. **Signature:**```typescript export type TaskOptions = { pending?: () => TNode; then: (value: T) => TNode; error?: (error: unknown) => TNode; }; ``` **References:** [TNode](#dom-tnode) --- ## dom.textnode: TextNode() function Creates a renderable text node. **Signature:**```typescript TextNode: (value: Value) => Renderable ```## dom.textnode: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | Value<string> | The value of the text node. | **Returns:** [Renderable](#dom-renderable) A renderable text node. --- ## dom.tnode: TNode type A flexible type representing any content that can be rendered in Tempo. TNode (Template Node) is the union type that encompasses all possible content that can be rendered in a Tempo application. This includes components, text, signals, arrays of content, and null/undefined values for conditional rendering. **Signature:**```typescript export type TNode = Renderable | string | ReadSignal | undefined | null | Renderable[]; ``` **References:** [DOMContext](#dom-domcontext), [Renderable](#dom-renderable) ## dom.tnode: Example 1 ```typescript // All of these are valid TNode values: // Renderable component const component: TNode = MyComponent() // Static text const text: TNode = 'Hello, World!' // Signal text const dynamicText: TNode = userNameSignal // Array of content const list: TNode = [ html.div('Item 1'), html.div('Item 2'), html.div('Item 3') ] // Conditional content const conditional: TNode = isVisible.value ? html.div('Visible') : null ``` ## dom.tnode: Example 2 ```typescript // Function that accepts any renderable content function Container(children: TNode): Renderable { return html.div( attr.class('container'), children // Can be any TNode type ) } // Usage with different TNode types Container('Simple text') Container(MyComponent()) Container([html.p('Paragraph 1'), html.p('Paragraph 2')]) Container(isLoading.value ? 'Loading...' : null) ``` ## dom.tnode: Example 3 ```typescript // Building complex content with TNode const buildContent = (items: string[]): TNode => { if (items.length === 0) { return html.div('No items found') } return items.map(item => html.div(item)) } ``` --- ## dom.toprovidertypes: ToProviderTypes type Converts an array of `Provider` types `T` into an array of their corresponding types. **Signature:**```typescript export type ToProviderTypes = T extends [] ? [] : T extends [Provider] ? [K] : T extends [Provider, ...infer R] ? [K, ...ToProviderTypes] : never; ``` **References:** [Provider](#dom-provider), [ToProviderTypes](#dom-toprovidertypes) --- ## dom.unless: Unless() function Lazily renders content when a condition is false. **Signature:**```typescript Unless: (condition: Value, then: () => TNode, otherwise?: () => TNode) => Renderable ```## dom.unless: Parameters | Parameter | Type | Description | | --- | --- | --- | | condition | Value<boolean> | The condition to evaluate | | then | () => [TNode](#dom-tnode) | Function returning content to render if condition is false | | otherwise | () => [TNode](#dom-tnode) | _(Optional)_ Optional function returning content to render if condition is true | **Returns:** [Renderable](#dom-renderable) Renderable content --- ## dom.use: Use() function Consumes a provider value and makes it available to a child component. This function looks up a provider in the component tree and passes its value to the child function. The provider must have been made available by a parent component using `Provide`. **Signature:**```typescript Use: (provider: Provider, child: (provider: T) => TNode) => Renderable ```## dom.use: Parameters | Parameter | Type | Description | | --- | --- | --- | | provider | [Provider](#dom-provider)<T> | The provider to consume (must be available in parent components) | | child | (provider: T) => [TNode](#dom-tnode) | Function that receives the provider value and returns content to render | **Returns:** [Renderable](#dom-renderable) A renderable that consumes the provider and renders the child content ## dom.use: Exceptions {ProviderNotFoundError} When the provider is not found in the component tree ## dom.use: Example 1```typescript // Use a theme provider const ThemeToggle = () => Use( ThemeProvider, (theme) => html.button( on.click(() => { theme.value = theme.value === 'light' ? 'dark' : 'light' }), 'Current theme: ', theme ) ) ``` ## dom.use: Example 2 ```typescript // Use multiple properties from a provider const UserProfile = () => Use( UserProvider, (user) => html.div( html.h2('Welcome, ', user.map(u => u.name)), html.p('Email: ', user.map(u => u.email)), html.p('Role: ', user.map(u => u.role)) ) ) ``` ## dom.use: Example 3 ```typescript // Use provider in conditional rendering const ConditionalContent = () => Use( AuthProvider, (auth) => auth.map(a => a.isLoggedIn) ? html.div('Welcome back!') : html.div('Please log in') ) ``` --- ## dom.usemany: UseMany() function Consumes multiple providers and makes their values available to a child component. This function is a convenience wrapper for consuming multiple providers at once. It's equivalent to nesting multiple `Use` calls but provides a cleaner API when you need access to several providers simultaneously. **Signature:**```typescript UseMany: []>(...providers: T) => (child: (...values: ToProviderTypes) => TNode) => Renderable ```## dom.usemany: Parameters | Parameter | Type | Description | | --- | --- | --- | | providers | T | Variable number of providers to consume | **Returns:** (child: (...values: [ToProviderTypes](#dom-toprovidertypes)<T>) => [TNode](#dom-tnode)) => [Renderable](#dom-renderable) Function that takes a child function and returns a renderable ## dom.usemany: Exceptions {ProviderNotFoundError} When any of the providers is not found in the component tree ## dom.usemany: Example 1```typescript // Use multiple providers together const Dashboard = () => UseMany( UserProvider, ThemeProvider, ConfigProvider )( (user, theme, config) => html.div( attr.class(theme.map(t => `theme-${t}`)), html.h1('Dashboard for ', user.map(u => u.name)), html.p('API URL: ', config.map(c => c.apiUrl)), html.p('Current theme: ', theme) ) ) ``` ## dom.usemany: Example 2 ```typescript // Equivalent to nested Use calls const Dashboard = () => Use(UserProvider, user => Use(ThemeProvider, theme => Use(ConfigProvider, config => html.div( // Same content as above ) ) ) ) ``` ## dom.usemany: Example 3 ```typescript // Type-safe access to multiple providers const SettingsPanel = () => UseMany( PreferencesProvider, UserProvider )( (preferences, user) => html.div( html.h2('Settings for ', user.map(u => u.name)), html.label( 'Theme: ', html.select( attr.value(preferences.map(p => p.theme)), on.change(emitValue(value => { preferences.update(p => ({ ...p, theme: value })) })), html.option(attr.value('light'), 'Light'), html.option(attr.value('dark'), 'Dark') ) ) ) ) ``` --- ## dom.when: When() function Lazily renders content based on a boolean condition. **Signature:**```typescript When: (condition: Value, then: () => TNode, otherwise?: () => TNode) => Renderable ```## dom.when: Parameters | Parameter | Type | Description | | --- | --- | --- | | condition | Value<boolean> | The condition to evaluate | | then | () => [TNode](#dom-tnode) | Function returning content to render if condition is true | | otherwise | () => [TNode](#dom-tnode) | _(Optional)_ Optional function returning content to render if condition is false | **Returns:** [Renderable](#dom-renderable) Renderable content --- ## dom.withbrowserctx: WithBrowserCtx() function Returns a renderable object that executes the given function with the current DOMContext as argument. The given function can return a TNode or void. If you need to perform some actions when the Renderable is disposed, you can use `OnDispose` as the return value. **Signature:**```typescript WithBrowserCtx: (fn: (ctx: BrowserContext) => TNode | void) => Renderable ```## dom.withbrowserctx: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn | (ctx: [BrowserContext](#dom-browsercontext)) => [TNode](#dom-tnode) \\| void | The function to be executed with the DOMContext argument. | **Returns:** [Renderable](#dom-renderable) A Clear function that can be used to clean up any resources associated with the execution. --- ## dom.withctx: WithCtx() function Returns a renderable object that executes the given function with the current DOMContext as argument. The given function can return a TNode or void. If you need to perform some actions when the Renderable is disposed, you can use `OnDispose` as the return value. **Signature:**```typescript WithCtx: (fn: (ctx: DOMContext) => TNode | void) => Renderable ```## dom.withctx: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn | (ctx: [DOMContext](#dom-domcontext)) => [TNode](#dom-tnode) \\| void | The function to be executed with the DOMContext argument. | **Returns:** [Renderable](#dom-renderable) A Clear function that can be used to clean up any resources associated with the execution. --- ## dom.withdispose: WithDispose type **Signature:**```typescript export type WithDispose = { dispose: DisposeCallback; }; ``` **References:** [DisposeCallback](#dom-disposecallback) --- ## dom.withelement: WithElement() function Executes a callback function when the parent element is mounted in the DOM. The given function can return a TNode or void. Any returned TNode will be appended to the element argument. If you need to perform some actions when the Renderable is disposed, you can use `OnDispose` as the return value. **Signature:**```typescript WithElement: (fn: (element: T) => TNode | void) => Renderable ```## dom.withelement: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn | (element: T) => [TNode](#dom-tnode) \\| void | The callback function to be executed. | **Returns:** [Renderable](#dom-renderable) - The renderable function. --- ## dom.withheadlessctx: WithHeadlessCtx() function Returns a renderable object that executes the given function with the current DOMContext as argument. **Signature:**```typescript WithHeadlessCtx: (fn: (ctx: HeadlessContext) => TNode | void) => Renderable ```## dom.withheadlessctx: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn | (ctx: [HeadlessContext](#dom-headlesscontext)) => [TNode](#dom-tnode) \\| void | The function to be executed with the DOMContext argument. | **Returns:** [Renderable](#dom-renderable) A Clear function that can be used to clean up any resources associated with the execution. --- ## dom.withprovider: WithProvider() function Returns a renderable object that executes the given function with the current DOMContext as argument. The given function can return a TNode or void. If you need to perform some actions when the Renderable is disposed, you can use `OnDispose` as the return value. **Signature:**```typescript WithProvider: (fn: (opts: ProviderOptions) => TNode | void) => Renderable ```## dom.withprovider: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn | (opts: [ProviderOptions](#dom-provideroptions)) => [TNode](#dom-tnode) \\| void | The function to be executed with the DOMContext argument. | **Returns:** [Renderable](#dom-renderable) A Clear function that can be used to clean up any resources associated with the execution. --- ## dom.withscope: WithScope() function Creates a renderable that provides explicit access to a DisposalScope. This is useful when you need to create signals in async contexts (like setTimeout, fetch callbacks, event handlers) where automatic scope tracking doesn't work. **Signature:**```typescript WithScope: (fn: (scope: DisposalScope) => TNode) => Renderable ```## dom.withscope: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn | (scope: DisposalScope) => [TNode](#dom-tnode) | Function that receives the scope and returns content to render | **Returns:** [Renderable](#dom-renderable) A renderable that manages the scope lifecycle ## dom.withscope: Example 1```typescript // Using scope in async context WithScope(scope => { setTimeout(() => { const signal = scope.prop(42) // signal will be disposed when component unmounts }, 1000) return html.div('Loading...') }) ``` ## dom.withscope: Example 2 ```typescript // Using scope with fetch WithScope(scope => { fetch('/api/data').then(response => { const data = scope.prop(response.data) // data will be disposed when component unmounts }) return html.div('Fetching...') }) ``` --- # tempots-std api index [Home](#tempots-ui-api-index) ## tempots-std: API Reference ## tempots-std: Packages | Package | Description | | --- | --- | | [@tempots/std](#std) | | --- ## std.adddays: addDays() function Adds the specified number of days to a date. This function creates a new Date object with the specified number of days added. Negative values subtract days. **Signature:**```typescript addDays: (date: Date, days: number) => Date ```## std.adddays: Parameters | Parameter | Type | Description | | --- | --- | --- | | date | Date | The base date | | days | number | Number of days to add (can be negative) | **Returns:** Date A new Date object with days added ## std.adddays: Example```typescript const date = new Date('2023-01-15') const future = addDays(date, 7) // Result: 2023-01-22 const past = addDays(date, -3) // Result: 2023-01-12 ``` --- ## std.addhours: addHours() function Adds the specified number of hours to a date. This function creates a new Date object with the specified number of hours added. Negative values subtract hours. **Signature:**```typescript addHours: (date: Date, hours: number) => Date ```## std.addhours: Parameters | Parameter | Type | Description | | --- | --- | --- | | date | Date | The base date | | hours | number | Number of hours to add (can be negative) | **Returns:** Date A new Date object with hours added ## std.addhours: Example```typescript const date = new Date('2023-01-15T10:00:00') const future = addHours(date, 5) // Result: 2023-01-15T15:00:00 const past = addHours(date, -2) // Result: 2023-01-15T08:00:00 ``` --- ## std.addminutes: addMinutes() function Adds the specified number of minutes to a date. This function creates a new Date object with the specified number of minutes added. Negative values subtract minutes. **Signature:**```typescript addMinutes: (date: Date, minutes: number) => Date ```## std.addminutes: Parameters | Parameter | Type | Description | | --- | --- | --- | | date | Date | The base date | | minutes | number | Number of minutes to add (can be negative) | **Returns:** Date A new Date object with minutes added ## std.addminutes: Example```typescript const date = new Date('2023-01-15T10:30:00') const future = addMinutes(date, 45) // Result: 2023-01-15T11:15:00 const past = addMinutes(date, -15) // Result: 2023-01-15T10:15:00 ``` --- ## std.angledifference: angleDifference() function Calculates the minimum difference between two angles in degrees. **Signature:**```typescript angleDifference: (a: number, b: number, turn?: number) => number ```## std.angledifference: Parameters | Parameter | Type | Description | | --- | --- | --- | | a | number | The first angle in degrees. | | b | number | The second angle in degrees. | | turn | number | _(Optional)_ The total number of degrees in a full turn. Default is 360.0. | **Returns:** number The difference between the two angles. ## std.angledifference: Example```ts angleDifference(0, 90) // returns 90 angleDifference(90, 0) // returns -90 angleDifference(0, 270) // returns -90 angleDifference(270, 0) // returns 90 ``` --- ## std.applyarraydiffoperations: applyArrayDiffOperations() function Applies a series of operations to an array and returns the modified array. **Signature:**```typescript applyArrayDiffOperations: (operations: ArrayDiffOperations, start: T[]) => T[] ```## std.applyarraydiffoperations: Parameters | Parameter | Type | Description | | --- | --- | --- | | operations | [ArrayDiffOperations](#std-arraydiffoperations)<T> | The operations to apply. | | start | T\[\] | The initial array. | **Returns:** T\[\] The modified array after applying the operations. --- ## std.arearraysequal: areArraysEqual() function Checks if two arrays are equal based on a custom equality function. **Signature:**```typescript areArraysEqual: (a: T[], b: T[], equals: (a: T, b: T) => boolean) => boolean ```## std.arearraysequal: Parameters | Parameter | Type | Description | | --- | --- | --- | | a | T\[\] | The first array. | | b | T\[\] | The second array. | | equals | (a: T, b: T) => boolean | The custom equality function to compare elements. | **Returns:** boolean Returns `true` if the arrays are equal, `false` otherwise. --- ## std.argsafter: ArgsAfter type **Signature:**```typescript export type ArgsAfter> = Args extends [...After, ...infer Rest] ? Rest : never; ``` **References:** [ArgsSubset](#std-argssubset) --- ## std.argssubset: ArgsSubset type **Signature:**```typescript export type ArgsSubset = T extends [] ? [] : T extends [infer A, ...infer Rest] ? [A] | [A, ...ArgsSubset] : never; ``` **References:** [ArgsSubset](#std-argssubset) --- ## std.arraydiffoperations: ArrayDiffOperations type Represents the different operations that can be performed on an array. **Signature:**```typescript export type ArrayDiffOperations = { removals: Array<{ at: number; qt: number; }>; swaps: Array<{ from: number; to: number; }>; inserts: Array<{ at: number; values: T[]; }>; }; ``` --- ## std.arrayhasvalues: arrayHasValues() function Checks if an array has values. **Signature:**```typescript arrayHasValues: (arr: T[]) => arr is [T, ...T[]] ```## std.arrayhasvalues: Parameters | Parameter | Type | Description | | --- | --- | --- | | arr | T\[\] | The array to check. | **Returns:** arr is \[T, ...T\[\]\] `true` if the array has values, `false` otherwise. --- ## std.arrayhead: arrayHead() function Returns the first element of an array, or `undefined` if the array is empty. **Signature:**```typescript arrayHead: (arr: A[]) => Maybe ```## std.arrayhead: Parameters | Parameter | Type | Description | | --- | --- | --- | | arr | A\[\] | The input array. | **Returns:** [Maybe](#std-maybe)<A> The first element of the array, or `undefined` if the array is empty. --- ## std.arraytail: arrayTail() function Returns a new array containing all elements of the input array except for the first element. **Signature:**```typescript arrayTail: (arr: A[]) => A[] ```## std.arraytail: Parameters | Parameter | Type | Description | | --- | --- | --- | | arr | A\[\] | The input array. | **Returns:** A\[\] A new array containing all elements of the input array except for the first element. --- ## std.asyncfailure: AsyncFailure type Represents a failure result. **Signature:**```typescript export type AsyncFailure = { readonly type: 'AsyncFailure'; readonly error: E; }; ``` --- ## std.asyncresult: AsyncResult variable A set of utility functions for working with `AsyncResult`. **Signature:**```typescript AsyncResult: { notAsked: { type: "NotAsked"; }; loading(previousValue?: Maybe): AsyncResult; success(value: V): AsyncResult; failure(error: E): AsyncResult; isSuccess(r: AsyncResult): r is AsyncSuccess; isFailure(r: AsyncResult): r is AsyncFailure; isNotAsked(r: AsyncResult): r is NotAsked; isLoading(r: AsyncResult): r is Loading; getOrElse(r: AsyncResult, alt: V): V; getOrElseLazy(r: AsyncResult, altf: () => V): V; getOrNull(r: AsyncResult): V | null; getOrUndefined(r: AsyncResult): Maybe; getUnsafe: (r: AsyncResult) => V; match: (r: AsyncResult, { success, failure, loading, notAsked, }: { success: (value: V1) => V2; failure: (error: E) => V2; loading: (previousValue?: V1) => V2; notAsked: () => V2; }) => V2; effect: (r: AsyncResult, handlers: { success?: (value: V) => void; failure?: (error: E) => void; loading?: (previousValue?: V) => void; notAsked?: () => void; else?: () => void; }) => AsyncResult; whenSuccess: (r: AsyncResult, apply: (v: V) => void) => AsyncResult; whenFailure: (r: AsyncResult, apply: (e: E) => void) => AsyncResult; equals: (r1: AsyncResult, r2: AsyncResult, options?: { valueEquals: (v1: V, v2: V) => boolean; errorEquals: (e1: E, e2: E) => boolean; }) => boolean; all: (results: AsyncResult[]) => AsyncResult; ofPromise: (p: Promise) => Promise>; map: (result: AsyncResult, fn: (value: V) => U) => AsyncResult; flatMap: (result: AsyncResult, fn: (value: V) => AsyncResult) => AsyncResult; mapError: (result: AsyncResult, fn: (error: E) => F) => AsyncResult; flatMapError: (result: AsyncResult, fn: (error: E) => AsyncResult) => AsyncResult; toResult: (result: AsyncResult) => import('./result').Result | undefined; isSettled(r: AsyncResult): r is Settled; recover: (result: AsyncResult, fn: (error: E) => V) => AsyncResult; ap: (resultFn: AsyncResult<(v: V) => U, E>, resultVal: AsyncResult) => AsyncResult; map2: (r1: AsyncResult, r2: AsyncResult, fn: (v1: V1, v2: V2) => U) => AsyncResult; map3: (r1: AsyncResult, r2: AsyncResult, r3: AsyncResult, fn: (v1: V1, v2: V2, v3: V3) => U) => AsyncResult; } ``` --- ## std.asyncsuccess: AsyncSuccess type Represents a successful result. **Signature:**```typescript export type AsyncSuccess = { readonly type: 'AsyncSuccess'; readonly value: V; }; ``` --- ## std.biabs: biAbs() function Returns the absolute value of a bigint. **Signature:**```typescript biAbs: (x: bigint) => bigint ```## std.biabs: Parameters | Parameter | Type | Description | | --- | --- | --- | | x | bigint | The bigint to compute the absolute value of. | **Returns:** bigint The absolute value of `x`. --- ## std.biceildiv: biCeilDiv() function Calculates the ceiling division of two BigInt numbers. **Signature:**```typescript biCeilDiv: (x: bigint, y: bigint) => bigint ```## std.biceildiv: Parameters | Parameter | Type | Description | | --- | --- | --- | | x | bigint | The dividend. | | y | bigint | The divisor. | **Returns:** bigint The result of dividing `x` by `y`, rounded up to the nearest whole number. --- ## std.bicompare: biCompare() function Compares two BigInt values and returns a number indicating their relative order. **Signature:**```typescript biCompare: (x: bigint, y: bigint) => number ```## std.bicompare: Parameters | Parameter | Type | Description | | --- | --- | --- | | x | bigint | The first BigInt value to compare. | | y | bigint | The second BigInt value to compare. | **Returns:** number A negative number if `x` is less than `y`, a positive number if `x` is greater than `y`, or zero if `x` is equal to `y`. --- ## std.bifloordiv: biFloorDiv() function Divides two BigInt numbers and returns the largest integer less than or equal to the quotient. **Signature:**```typescript biFloorDiv: (x: bigint, y: bigint) => bigint ```## std.bifloordiv: Parameters | Parameter | Type | Description | | --- | --- | --- | | x | bigint | The dividend. | | y | bigint | The divisor. | **Returns:** bigint The largest integer less than or equal to the quotient of `x` divided by `y`. --- ## std.bigcd: biGcd() function Calculates the greatest common divisor (GCD) of two BigInt numbers. **Signature:**```typescript biGcd: (x: bigint, y: bigint) => bigint ```## std.bigcd: Parameters | Parameter | Type | Description | | --- | --- | --- | | x | bigint | The first BigInt number. | | y | bigint | The second BigInt number. | **Returns:** bigint The GCD of `x` and `y`. --- ## std.biiseven: biIsEven() function Checks if a given bigint is even. **Signature:**```typescript biIsEven: (x: bigint) => boolean ```## std.biiseven: Parameters | Parameter | Type | Description | | --- | --- | --- | | x | bigint | The bigint to check. | **Returns:** boolean `true` if the bigint is even, `false` otherwise. --- ## std.biisnegative: biIsNegative() function Checks if a given bigint is negative. **Signature:**```typescript biIsNegative: (x: bigint) => boolean ```## std.biisnegative: Parameters | Parameter | Type | Description | | --- | --- | --- | | x | bigint | The bigint to check. | **Returns:** boolean `true` if the bigint is negative, `false` otherwise. --- ## std.biisodd: biIsOdd() function Checks if a given bigint is odd. **Signature:**```typescript biIsOdd: (x: bigint) => boolean ```## std.biisodd: Parameters | Parameter | Type | Description | | --- | --- | --- | | x | bigint | The bigint to check. | **Returns:** boolean `true` if the bigint is odd, `false` otherwise. --- ## std.biisone: biIsOne() function Checks if a given bigint is equal to 1n. **Signature:**```typescript biIsOne: (x: bigint) => boolean ```## std.biisone: Parameters | Parameter | Type | Description | | --- | --- | --- | | x | bigint | The bigint to check. | **Returns:** boolean `true` if the bigint is equal to 1n, `false` otherwise. --- ## std.biispositive: biIsPositive() function Checks if a bigint is positive. **Signature:**```typescript biIsPositive: (x: bigint) => boolean ```## std.biispositive: Parameters | Parameter | Type | Description | | --- | --- | --- | | x | bigint | The bigint to check. | **Returns:** boolean `true` if the bigint is positive, `false` otherwise. --- ## std.biisprime: biIsPrime() function Checks if a given number is prime. **Signature:**```typescript biIsPrime: (x: bigint) => boolean ```## std.biisprime: Parameters | Parameter | Type | Description | | --- | --- | --- | | x | bigint | The number to check for primality. | **Returns:** boolean `true` if the number is prime, `false` otherwise. --- ## std.biiszero: biIsZero() function Checks if a given bigint is zero. **Signature:**```typescript biIsZero: (x: bigint) => boolean ```## std.biiszero: Parameters | Parameter | Type | Description | | --- | --- | --- | | x | bigint | The bigint to check. | **Returns:** boolean `true` if the bigint is zero, `false` otherwise. --- ## std.bilcm: biLcm() function Calculates the least common multiple (LCM) of two BigInt numbers. **Signature:**```typescript biLcm: (x: bigint, y: bigint) => bigint ```## std.bilcm: Parameters | Parameter | Type | Description | | --- | --- | --- | | x | bigint | The first BigInt number. | | y | bigint | The second BigInt number. | **Returns:** bigint The least common multiple of `x` and `y`. --- ## std.bimax: biMax() function Returns the maximum of two BigInt values. **Signature:**```typescript biMax: (x: bigint, y: bigint) => bigint ```## std.bimax: Parameters | Parameter | Type | Description | | --- | --- | --- | | x | bigint | The first BigInt value. | | y | bigint | The second BigInt value. | **Returns:** bigint The maximum of the two BigInt values. --- ## std.bimin: biMin() function Returns the minimum of two BigInt values. **Signature:**```typescript biMin: (x: bigint, y: bigint) => bigint ```## std.bimin: Parameters | Parameter | Type | Description | | --- | --- | --- | | x | bigint | The first BigInt value. | | y | bigint | The second BigInt value. | **Returns:** bigint The smaller of the two BigInt values. --- ## std.binextprime: biNextPrime() function Finds the next prime number greater than the given number. **Signature:**```typescript biNextPrime: (x: bigint) => bigint ```## std.binextprime: Parameters | Parameter | Type | Description | | --- | --- | --- | | x | bigint | The starting number. | **Returns:** bigint The next prime number greater than `x`. --- ## std.bipow: biPow() function Calculates the power of a bigint number. **Signature:**```typescript biPow: (x: bigint, y: bigint) => bigint ```## std.bipow: Parameters | Parameter | Type | Description | | --- | --- | --- | | x | bigint | The base number. | | y | bigint | The exponent. | **Returns:** bigint The result of raising `x` to the power of `y`. ## std.bipow: Exceptions Throws `ArgumentError` if the exponent `y` is negative. --- ## std.biprevprime: biPrevPrime() function Returns the previous prime number less than the given number. Throws an error if there is no previous prime. **Signature:**```typescript biPrevPrime: (x: bigint) => bigint ```## std.biprevprime: Parameters | Parameter | Type | Description | | --- | --- | --- | | x | bigint | The number to find the previous prime for. | **Returns:** bigint The previous prime number less than `x`. ## std.biprevprime: Exceptions Throws `ArgumentError` if there is no previous prime. --- ## std.booleantoint: booleanToInt() function Converts a boolean to an integer value (`true` => `1`, `false` => `0`). **Signature:**```typescript booleanToInt: (v: boolean) => number ```## std.booleantoint: Parameters | Parameter | Type | Description | | --- | --- | --- | | v | boolean | The boolean value. | **Returns:** number The integer value. --- ## std.buildarray: buildArray() function Generates an array of values by applying a function to each index. This function provides a more semantic alternative to `Array.from({ length }, (_, i) => f(i))` with better readability and intent expression. It's particularly useful for creating arrays with computed values based on their position. **Signature:**```typescript buildArray: (length: number, f: (index: number) => A) => A[] ```## std.buildarray: Parameters | Parameter | Type | Description | | --- | --- | --- | | length | number | The length of the resulting array. | | f | (index: number) => A | The function to apply to each index. It takes the index as a parameter and returns the corresponding value. | **Returns:** A\[\] An array of values generated by applying the function to each index. ## std.buildarray: Example```typescript // Create an array of squares const squares = buildArray(5, i => i * i) // Result: [0, 1, 4, 9, 16] // Create an array of objects with IDs const items = buildArray(3, i => ({ id: i, name: `Item ${i}` })) // Result: [{ id: 0, name: 'Item 0' }, { id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }] ``` --- ## std.buildurl: buildUrl() function Builds a URL from a base URL and query parameters. This function safely constructs URLs with query parameters, handling encoding and existing parameters properly. **Signature:**```typescript buildUrl: (base: string, params?: Record) => string ```## std.buildurl: Parameters | Parameter | Type | Description | | --- | --- | --- | | base | string | The base URL | | params | Record<string, string> | _(Optional)_ Query parameters to add | **Returns:** string The constructed URL string ## std.buildurl: Example```typescript const url = buildUrl('https://api.example.com/users', { page: '1', limit: '10', search: 'john doe' }) // Result: 'https://api.example.com/users?page=1&limit=10&search=john%20doe' ``` --- ## std.canceloptions: CancelOptions interface Options for cancelling a throttled function. **Signature:**```typescript export interface CancelOptions ```## std.canceloptions: Properties | Property | Modifiers | Type | Description | | --- | --- | --- | --- | | [upcomingOnly?](#std-canceloptions-upcomingonly) | | boolean | _(Optional)_ If true, only prevents future scheduled executions. If false, also prevents all future executions even after new calls. false | --- ## std.canceloptions.upcomingonly: CancelOptions.upcomingOnly property If true, only prevents future scheduled executions. If false, also prevents all future executions even after new calls. false **Signature:**```typescript upcomingOnly?: boolean; ``` --- ## std.canonicalizenewlines: canonicalizeNewlines() function Replaces occurrances of `\r\n`, `\n\r`, `\r` with `\n` **Signature:**```typescript canonicalizeNewlines: (value: string) => string ```## std.canonicalizenewlines: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to normalize. | **Returns:** string The string with normalized line endings. --- ## std.canparseboolean: canParseBoolean() function Returns `true` if the passed value can be parsed as a boolean. The following values are considered parsable: - `'true'` / `'false'` - `'0'` / `'1'` - `'on'` / `'off'` The comparison is case insensitive. **Signature:**```typescript canParseBoolean: (v: string) => boolean ```## std.canparseboolean: Parameters | Parameter | Type | Description | | --- | --- | --- | | v | string | The value to check. | **Returns:** boolean `true` if the value can be parsed; otherwise, `false`. --- ## std.capitalize: capitalize() function `capitalize` returns a string with the first character convert to upper case. **Signature:**```typescript capitalize: (s: string) => string ```## std.capitalize: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to capitalize. | **Returns:** string The capitalized string. --- ## std.capitalizewords: capitalizeWords() function Capitalize the first letter of every word in `value`. If `whiteSpaceOnly` is set to `true` the process is limited to whitespace separated words. **Signature:**```typescript capitalizeWords: (value: string, whiteSpaceOnly?: boolean) => string ```## std.capitalizewords: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to capitalize. | | whiteSpaceOnly | boolean | _(Optional)_ If `true`, only whitespace separated words will be capitalized. | **Returns:** string The string with the first letter of each word capitalized. --- ## std.ceilto: ceilTo() function Rounds a number up to the specified number of decimals. **Signature:**```typescript ceilTo: (v: number, decimals: number) => number ```## std.ceilto: Parameters | Parameter | Type | Description | | --- | --- | --- | | v | number | The number to round up. | | decimals | number | The number of decimals to round up to. | **Returns:** number The rounded up number. ## std.ceilto: Example```ts ceilTo(1.234, 2) // returns 1.24 ceilTo(1.234, 1) // returns 1.3 ceilTo(1.234, 0) // returns 2 ``` --- ## std.chain: chain() function Chains multiple iterables into a single iterable. This function creates a new iterable that yields all elements from the input iterables in sequence. **Signature:**```typescript chain: (...iterables: Iterable[]) => Iterable ```## std.chain: Parameters | Parameter | Type | Description | | --- | --- | --- | | iterables | Iterable<T>\[\] | The iterables to chain | **Returns:** Iterable<T> An iterable that yields all elements in sequence ## std.chain: Example```typescript const first = [1, 2, 3] const second = [4, 5, 6] const third = [7, 8, 9] const chained = [...chain(first, second, third)] // [1, 2, 3, 4, 5, 6, 7, 8, 9] // Works with different iterable types const mixed = [...chain([1, 2], new Set([3, 4]), 'ab')] // [1, 2, 3, 4, 'a', 'b'] ``` --- ## std.chunk: chunk() function Splits an array into chunks of the specified size. This function divides an array into smaller arrays of a fixed size. The last chunk may contain fewer elements if the array length is not evenly divisible by the chunk size. **Signature:**```typescript chunk: (array: readonly T[], size: number) => T[][] ```## std.chunk: Parameters | Parameter | Type | Description | | --- | --- | --- | | array | readonly T\[\] | The array to chunk | | size | number | The size of each chunk (must be positive) | **Returns:** T\[\]\[\] An array of chunks ## std.chunk: Example```typescript const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] const chunks = chunk(numbers, 3) // Result: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] const uneven = chunk([1, 2, 3, 4, 5], 2) // Result: [[1, 2], [3, 4], [5]] ``` --- ## std.chunkstring: chunkString() function Returns an array of `string` whose elements are equally long (using `len`). If the string `s` is not exactly divisible by `len` the last element of the array will be shorter. **Signature:**```typescript chunkString: (s: string, len: number) => string[] ```## std.chunkstring: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to chunk. | | len | number | The length of each chunk. | **Returns:** string\[\] An array of chunks. --- ## std.clamp: clamp() function `clamp` restricts a value within the specified range. **Signature:**```typescript clamp: (value: number, min: number, max: number) => number ```## std.clamp: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | number | The value to clamp. | | min | number | The minimum value. | | max | number | The maximum value. | **Returns:** number The clamped value. ## std.clamp: Example```ts clamp(1.3, 0, 1) // returns 1 clamp(0.8, 0, 1) // returns 0.8 clamp(-0.5, 0, 1) // returns 0.0 ``` --- ## std.clampint: clampInt() function Clamps a number to a specified range and returns an integer value. **Signature:**```typescript clampInt: (value: number, min: number, max: number) => number ```## std.clampint: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | number | The number to clamp. | | min | number | The minimum value of the range. | | max | number | The maximum value of the range. | **Returns:** number The clamped integer value. ## std.clampint: Example```ts clampInt(5, 0, 10) // returns 5 clampInt(15, 0, 10) // returns 10 clampInt(-5, 0, 10) // returns 0 ``` --- ## std.clampsym: clampSym() function Like clamp but you only pass one argument (`max`) that is used as the upper limit and the opposite (additive inverse or `-max`) as the lower limit. **Signature:**```typescript clampSym: (v: number, max: number) => number ```## std.clampsym: Parameters | Parameter | Type | Description | | --- | --- | --- | | v | number | The value to clamp. | | max | number | The maximum value. | **Returns:** number The clamped value. ## std.clampsym: Example```ts clampSym(5, 10) // returns 5 clampSym(15, 10) // returns 10 clampSym(-5, 10) // returns -5 clampSym(-15, 10) // returns -10 ``` --- ## std.collapsetext: collapseText() function It cleans up all the whitespaces in the passed `value`. `collapse` does the following: - remove trailing/leading whitespaces - within the string, it collapses seqeunces of whitespaces into a single space character For whitespaces in this description, it is intended to be anything that is matched by the regular expression `\s`. **Signature:**```typescript collapseText: (value: string) => string ```## std.collapsetext: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to collapse. | **Returns:** string The string with all whitespaces collapsed. --- ## std.compare: Compare type Represents a function that compares two values of type T and returns a number. The returned number indicates the relative order of the two values: - A negative number if `a` is less than `b`. - Zero if `a` is equal to `b`. - A positive number if `a` is greater than `b`. **Signature:**```typescript export type Compare = (a: T, b: T) => number; ``` --- ## std.comparearrays: compareArrays() function Compares two arrays based on their lengths and element values. **Signature:**```typescript compareArrays: (a: A[], b: A[], comparef: Compare, shorterFirst?: boolean) => number ```## std.comparearrays: Parameters | Parameter | Type | Description | | --- | --- | --- | | a | A\[\] | The first array to compare. | | b | A\[\] | The second array to compare. | | comparef | [Compare](#std-compare)<A> | The compare function to use for comparing the elements of the arrays. | | shorterFirst | boolean | _(Optional)_ Specifies whether shorter arrays should be considered smaller. Defaults to true. | **Returns:** number A compare function that can be used to compare arrays. --- ## std.comparebooleans: compareBooleans() function Returns a comparison value (`Int`) from two boolean values. **Signature:**```typescript compareBooleans: (a: boolean, b: boolean) => number ```## std.comparebooleans: Parameters | Parameter | Type | Description | | --- | --- | --- | | a | boolean | The first boolean value. | | b | boolean | The second boolean value. | **Returns:** number A comparison value. --- ## std.comparecaseinsensitive: compareCaseInsensitive() function Compares two strings ignoring their case. **Signature:**```typescript compareCaseInsensitive: (a: string | null | undefined, b: string | null | undefined) => number ```## std.comparecaseinsensitive: Parameters | Parameter | Type | Description | | --- | --- | --- | | a | string \\| null \\| undefined | The first string to compare. | | b | string \\| null \\| undefined | The second string to compare. | **Returns:** number A negative number if `a` is less than `b`, zero if they are equal, or a positive number if `a` is greater than `b`. --- ## std.comparedates: compareDates() function Compares two dates. **Signature:**```typescript compareDates: (a: Date, b: Date) => number ```## std.comparedates: Parameters | Parameter | Type | Description | | --- | --- | --- | | a | Date | The first date | | b | Date | The second date | **Returns:** number A negative number if `a` is less than `b`, zero if they are equal, or a positive number if `a` is greater than `b`. --- ## std.comparenumbers: compareNumbers() function It returns the comparison value (an integer number) between two `float` values. **Signature:**```typescript compareNumbers: (a: number, b: number) => number ```## std.comparenumbers: Parameters | Parameter | Type | Description | | --- | --- | --- | | a | number | The first value to compare. | | b | number | The second value to compare. | **Returns:** number A number indicating the relative order of the two values. ## std.comparenumbers: Example```ts compare(5, 10) // returns -1 compare(10, 5) // returns 1 compare(5, 5) // returns 0 ``` --- ## std.comparestrings: compareStrings() function It compares to string and it returns a negative number if `a` is inferior to `b`, zero if they are the same, or otherwise a positive non-sero number. **Signature:**```typescript compareStrings: (a: string, b: string) => number ```## std.comparestrings: Parameters | Parameter | Type | Description | | --- | --- | --- | | a | string | The first string to compare. | | b | string | The second string to compare. | **Returns:** number A negative number if `a` is less than `b`, zero if they are equal, or a positive number if `a` is greater than `b`. --- ## std.compose_1: compose() function **Signature:**```typescript export declare function compose(fn1: (...args: TArgs) => R1): (...args: TArgs) => R1; ```## std.compose_1: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn1 | (...args: TArgs) => R1 | | **Returns:** (...args: TArgs) => R1 --- ## std.compose_2: compose() function **Signature:**```typescript export declare function compose(fn2: (arg: R1) => R2, fn1: (...args: TArgs) => R1): (...args: TArgs) => R2; ```## std.compose_2: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn2 | (arg: R1) => R2 | | | fn1 | (...args: TArgs) => R1 | | **Returns:** (...args: TArgs) => R2 --- ## std.compose_3: compose() function **Signature:**```typescript export declare function compose(fn3: (arg: R2) => R3, fn2: (arg: R1) => R2, fn1: (...args: TArgs) => R1): (...args: TArgs) => R3; ```## std.compose_3: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn3 | (arg: R2) => R3 | | | fn2 | (arg: R1) => R2 | | | fn1 | (...args: TArgs) => R1 | | **Returns:** (...args: TArgs) => R3 --- ## std.compose_4: compose() function **Signature:**```typescript export declare function compose(fn4: (arg: R3) => R4, fn3: (arg: R2) => R3, fn2: (arg: R1) => R2, fn1: (...args: TArgs) => R1): (...args: TArgs) => R4; ```## std.compose_4: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn4 | (arg: R3) => R4 | | | fn3 | (arg: R2) => R3 | | | fn2 | (arg: R1) => R2 | | | fn1 | (...args: TArgs) => R1 | | **Returns:** (...args: TArgs) => R4 --- ## std.compose: compose() function Composes functions from right to left. This function creates a new function that applies the given functions in right-to-left order. The rightmost function can accept multiple arguments, while the others must be unary. **Signature:**```typescript export declare function compose(): (arg: T) => T; ``` **Returns:** <T>(arg: T) => T A new function that applies all functions in right-to-left order ## std.compose: Example ```typescript const add = (a: number, b: number) => a + b const double = (x: number) => x * 2 const square = (x: number) => x * x const composed = compose(square, double, add) const result = composed(2, 3) // square(double(add(2, 3))) = square(double(5)) = square(10) = 100 ``` --- ## std.containsalltext: containsAllText() function `containsAllText` returns `true` if `s` contains all of the strings in `tests` **Signature:**```typescript containsAllText: (s: string, tests: string[]) => boolean ```## std.containsalltext: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to search in. | | tests | string\[\] | The strings to search for. | **Returns:** boolean `true` if `s` contains all of the strings in `tests`, `false` otherwise. --- ## std.containsalltextcaseinsensitive: containsAllTextCaseInsensitive() function `containsAllTextCaseInsensitive` returns `true` if `s` contains all of the strings in `tests` regardless of the text case **Signature:**```typescript containsAllTextCaseInsensitive: (s: string, tests: string[]) => boolean ```## std.containsalltextcaseinsensitive: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to search in. | | tests | string\[\] | The strings to search for. | **Returns:** boolean `true` if `s` contains all of the strings in `tests` (case-insensitive), `false` otherwise. --- ## std.containsanytext: containsAnyText() function `containsAnyText` returns `true` if `s` contains any of the strings in `tests` **Signature:**```typescript containsAnyText: (s: string, tests: string[]) => boolean ```## std.containsanytext: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to search in. | | tests | string\[\] | The strings to search for. | **Returns:** boolean `true` if `s` contains any of the strings in `tests`, `false` otherwise. --- ## std.containsanytextcaseinsensitive: containsAnyTextCaseInsensitive() function `containsAnyTextCaseInsensitive` returns `true` if `s` contains any of the strings in `tests` regardless of the text case **Signature:**```typescript containsAnyTextCaseInsensitive: (s: string, tests: string[]) => boolean ```## std.containsanytextcaseinsensitive: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to search in. | | tests | string\[\] | The strings to search for. | **Returns:** boolean `true` if `s` contains any of the strings in `tests` (case-insensitive), `false` otherwise. --- ## std.countstringoccurrences: countStringOccurrences() function Return the number of occurrences of `test` in `s`. **Signature:**```typescript countStringOccurrences: (s: string, test: string) => number ```## std.countstringoccurrences: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to search in. | | test | string | The string to search for. | **Returns:** number The number of occurrences of `test` in `s`. --- ## std.curryleft: curryLeft() function Curries a function from left to right. **Signature:**```typescript curryLeft: (f: (a: A, ...rest: Rest) => Ret) => (a: A) => (...rest: Rest) => Ret ```## std.curryleft: Parameters | Parameter | Type | Description | | --- | --- | --- | | f | (a: A, ...rest: Rest) => Ret | The function to curry. | **Returns:** (a: A) => (...rest: Rest) => Ret A curried function. --- ## std.dasherize: dasherize() function `dasherize` replaces all the occurrances of `_` with `-` **Signature:**```typescript dasherize: (s: string) => string ```## std.dasherize: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to dasherize. | **Returns:** string The dasherized string. --- ## std.debounce: debounce() function Debounce execution of a function. Debouncing, unlike throttling, guarantees that a function is only executed a single time, either at the very beginning of a series of calls, or at the very end. **Signature:**```typescript export declare function debounce any>(delay: number, callback: F, { atBegin }?: DebounceOptions): ThrottledFunction, This>; ```## std.debounce: Parameters | Parameter | Type | Description | | --- | --- | --- | | delay | number | A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful. | | callback | F | A function to be executed after delay milliseconds. The `this` context and all arguments are passed through, as-is, to `callback` when the debounced-function is executed. | | { atBegin } | [DebounceOptions](#std-debounceoptions) | _(Optional)_ | **Returns:** [ThrottledFunction](#std-throttledfunction)<Parameters<F>, This> {Function} A new, debounced function. --- ## std.debounceoptions: DebounceOptions type Options for debouncing a function. **Signature:**```typescript export type DebounceOptions = { atBegin?: boolean; }; ``` --- ## std.decodebase64: decodeBase64() function Decodes a base64 encoded string. **Signature:**```typescript decodeBase64: (s: string) => string ```## std.decodebase64: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The base64 encoded string to decode. | **Returns:** string The decoded string. ## std.decodebase64: Exceptions Throws a `MissingImplementationError` if no implementation is found for base64 decoding. --- ## std.deepclone: deepClone() function Creates a deep clone of an object. This function recursively clones objects, arrays, and primitive values. It handles Date objects specially and avoids infinite recursion. **Signature:**```typescript deepClone: (obj: T) => T ```## std.deepclone: Parameters | Parameter | Type | Description | | --- | --- | --- | | obj | T | The object to clone | **Returns:** T A deep clone of the object ## std.deepclone: Example```typescript const original = { name: 'Alice', settings: { theme: 'dark', notifications: true }, tags: ['user', 'admin'] } const cloned = deepClone(original) cloned.settings.theme = 'light' // Original remains unchanged ``` --- ## std.deepequal: deepEqual() function Checks if two values are equal by comparing their contents. **Signature:**```typescript deepEqual: (a: A, b: A) => boolean ```## std.deepequal: Parameters | Parameter | Type | Description | | --- | --- | --- | | a | A | The first value to compare. | | b | A | The second value to compare. | **Returns:** boolean `true` if the values are deeply equal, `false` otherwise. --- ## std.deferred: deferred() function Creates a deferred object. A deferred object is a promise that can be resolved or rejected. **Signature:**```typescript deferred: () => { promise: Promise; resolve: (value: T) => void; reject: (reason?: unknown) => void; } ``` **Returns:** { promise: Promise<T>; resolve: (value: T) => void; reject: (reason?: unknown) => void; } A deferred object. ## std.deferred: Example ```ts const { promise, resolve, reject } = deferred() promise.then((value) => { console.warn(value) }) resolve(42) ``` --- ## std.delayed: delayed() function Delays the execution of a function by the given number of milliseconds. **Signature:**```typescript delayed: (fn: () => (() => void) | void, ms: number) => () => void ```## std.delayed: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn | () => (() => void) \\| void | The function to delay. The function can optionally return a callback that will be invoked when the delay is cancelled. | | ms | number | The number of milliseconds to delay the function. | **Returns:** () => void A function that, when called, will cancel the delay and prevent the original function from being executed. ## std.delayed: Example```ts // Delay a function for 1 second const cancel = delayed(() => console.warn('Hello!'), 1000); // Cancel the delayed execution if needed cancel(); ``` --- ## std.delayedanimationframe: delayedAnimationFrame() function Delays the execution of a function using requestAnimationFrame. **Signature:**```typescript delayedAnimationFrame: (callback: (time: DOMHighResTimeStamp) => void) => () => void ```## std.delayedanimationframe: Parameters | Parameter | Type | Description | | --- | --- | --- | | callback | (time: DOMHighResTimeStamp) => void | The function to delay. | **Returns:** () => void A function that, when called, will cancel the delay and prevent the original function from being executed. --- ## std.deletefirstfromstring: deleteFirstFromString() function If present, it removes the first occurrence of `toremove` from `value`. **Signature:**```typescript deleteFirstFromString: (value: string, toremove: string) => string ```## std.deletefirstfromstring: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to remove the text from. | | toremove | string | The text to remove from `value`. | **Returns:** string The string with the text removed. --- ## std.deletestringafter: deleteStringAfter() function If present, it removes the `toremove` text from the end of `value`. **Signature:**```typescript deleteStringAfter: (value: string, toremove: string) => string ```## std.deletestringafter: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to remove the text from. | | toremove | string | The text to remove from the end of `value`. | **Returns:** string The string with the text removed. --- ## std.deletestringbefore: deleteStringBefore() function If present, it removes the `toremove` text from the beginning of `value`. **Signature:**```typescript deleteStringBefore: (value: string, toremove: string) => string ```## std.deletestringbefore: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to remove the text from. | | toremove | string | The text to remove from the beginning of `value`. | **Returns:** string The string with the text removed. --- ## std.deletesubstring: deleteSubstring() function If present, it removes all the occurrences of `toremove` from `value`. **Signature:**```typescript deleteSubstring: (value: string, toremove: string) => string ```## std.deletesubstring: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to remove the occurrences from. | | toremove | string | The string to remove from `value`. | **Returns:** string The string with all occurrences of `toremove` removed. --- ## std.diffindays: diffInDays() function Calculates the difference in days between two dates. Returns a positive number if dateB is after dateA, negative if before. The calculation ignores time components and focuses on calendar days. **Signature:**```typescript diffInDays: (dateA: Date, dateB: Date) => number ```## std.diffindays: Parameters | Parameter | Type | Description | | --- | --- | --- | | dateA | Date | The first date | | dateB | Date | The second date | **Returns:** number The difference in days (dateB - dateA) ## std.diffindays: Example```typescript const dateA = new Date('2023-01-15') const dateB = new Date('2023-01-20') const diff = diffInDays(dateA, dateB) // Result: 5 const diffReverse = diffInDays(dateB, dateA) // Result: -5 ``` --- ## std.diffinhours: diffInHours() function Calculates the difference in hours between two dates. Returns a positive number if dateB is after dateA, negative if before. The result includes fractional hours for precise calculations. **Signature:**```typescript diffInHours: (dateA: Date, dateB: Date) => number ```## std.diffinhours: Parameters | Parameter | Type | Description | | --- | --- | --- | | dateA | Date | The first date | | dateB | Date | The second date | **Returns:** number The difference in hours (dateB - dateA) ## std.diffinhours: Example```typescript const dateA = new Date('2023-01-15T10:00:00') const dateB = new Date('2023-01-15T15:30:00') const diff = diffInHours(dateA, dateB) // Result: 5.5 ``` --- ## std.drop: Drop type **Signature:**```typescript export type Drop = I['length'] extends N ? T : T extends [infer _, ...infer R] ? Drop : []; ``` **References:** [Drop](#std-drop) --- ## std.ellipsis: ellipsis() function `ellipsis` truncates `s` at len `maxlen` replaces the last characters with the content of `symbol`. **Signature:**```typescript ellipsis: (s: string, maxlen?: number, symbol?: string) => string ```## std.ellipsis: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to truncate. | | maxlen | number | _(Optional)_ The maximum length of the string. | | symbol | string | _(Optional)_ The symbol to replace the truncated characters with. | **Returns:** string The truncated string. ## std.ellipsis: Example```ts ellipsis('tempo is a nice library', 9) // returns 'tempo is …' ``` --- ## std.ellipsismiddle: ellipsisMiddle() function Same as `ellipsis` but puts the symbol in the middle of the string and not to the end. **Signature:**```typescript ellipsisMiddle: (s: string, maxlen?: number, symbol?: string) => string ```## std.ellipsismiddle: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to truncate. | | maxlen | number | _(Optional)_ The maximum length of the string. | | symbol | string | _(Optional)_ The symbol to replace the truncated characters with. | **Returns:** string The truncated string. ## std.ellipsismiddle: Example```ts ellipsisMiddle('tempo is a nice library', 18) // returns 'tempo is … library' ``` --- ## std.encodebase64: encodeBase64() function Encodes a string to base64. **Signature:**```typescript encodeBase64: (s: string) => string ```## std.encodebase64: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to encode. | **Returns:** string The base64 encoded string. ## std.encodebase64: Exceptions Throws `MissingImplementationError` if no implementation is found for base64 encoding. --- ## std.endofday: endOfDay() function Returns a new Date representing the end of the day (23:59:59.999). This is useful for date range queries where you need the last millisecond of a given day. **Signature:**```typescript endOfDay: (date: Date) => Date ```## std.endofday: Parameters | Parameter | Type | Description | | --- | --- | --- | | date | Date | The input date | **Returns:** Date A new Date set to the end of the day ## std.endofday: Example```typescript const date = new Date('2023-01-15T14:30:45.123') const end = endOfDay(date) // Result: 2023-01-15T23:59:59.999 ``` --- ## std.endofweek: endOfWeek() function Returns a new Date representing the end of the week (Sunday 23:59:59.999). This follows the ISO 8601 standard where Sunday is the last day of the week. Useful for weekly reports and date grouping. **Signature:**```typescript endOfWeek: (date: Date) => Date ```## std.endofweek: Parameters | Parameter | Type | Description | | --- | --- | --- | | date | Date | The input date | **Returns:** Date A new Date set to the end of the week ## std.endofweek: Example```typescript const date = new Date('2023-01-18') // Wednesday const end = endOfWeek(date) // Result: 2023-01-22T23:59:59.999 (Sunday) ``` --- ## std.epsilon: EPSILON variable Constant value employed to see if two `number` values are very close. **Signature:**```typescript EPSILON = 1e-9 ``` --- ## std.every: every() function Tests whether all elements in an iterable satisfy the predicate. This function returns true if the predicate returns true for all elements, or false otherwise. It short-circuits on the first false result. **Signature:**```typescript every: (iterable: Iterable, predicate: (item: T) => boolean) => boolean ```## std.every: Parameters | Parameter | Type | Description | | --- | --- | --- | | iterable | Iterable<T> | The iterable to test | | predicate | (item: T) => boolean | Function that tests each element | **Returns:** boolean true if all elements satisfy the predicate, false otherwise ## std.every: Example```typescript const numbers = [2, 4, 6, 8] const allEven = every(numbers, n => n % 2 === 0) // true const users = [{ age: 25 }, { age: 30 }, { age: 17 }] const allAdults = every(users, user => user.age >= 18) // false ``` --- ## std.failure: Failure type Represents a failure result. **Signature:**```typescript export type Failure = { readonly type: 'Failure'; readonly error: E; }; ``` --- ## std.fillarray: fillArray() function Creates a new array with the specified length and fills it with the provided value. This function provides a more semantic alternative to `Array(length).fill(value)` or `new Array(length).fill(value)` with better type inference and clearer intent. It's particularly useful when you need arrays of non-primitive values or when working with functional programming patterns. **Signature:**```typescript fillArray: (length: number, value: A) => A[] ```## std.fillarray: Parameters | Parameter | Type | Description | | --- | --- | --- | | length | number | The length of the new array. | | value | A | The value to fill the array with. | **Returns:** A\[\] A new array filled with the specified value. ## std.fillarray: Example```typescript // Create an array of default objects const defaultUsers = fillArray(3, { name: '', active: false }) // Result: [{ name: '', active: false }, { name: '', active: false }, { name: '', active: false }] // Create an array of empty arrays const matrix = fillArray(3, [] as number[]) // Result: [[], [], []] // Create an array of functions const handlers = fillArray(5, () => console.log('handler')) // Result: [function, function, function, function, function] ``` --- ## std.filter: filter() function Filters an iterable, yielding only elements that satisfy the predicate. This function creates a new iterable that yields only elements for which the predicate returns true. It's lazy and memory-efficient. **Signature:**```typescript filter: (iterable: Iterable, predicate: (item: T) => boolean) => Iterable ```## std.filter: Parameters | Parameter | Type | Description | | --- | --- | --- | | iterable | Iterable<T> | The iterable to filter | | predicate | (item: T) => boolean | Function that tests each element | **Returns:** Iterable<T> An iterable that yields filtered elements ## std.filter: Example```typescript const numbers = [1, 2, 3, 4, 5, 6] const evens = [...filter(numbers, n => n % 2 === 0)] // [2, 4, 6] // Chain with other operations const result = take(filter(largeDataset, isValid), 100) ``` --- ## std.filtercharcodes: filterCharcodes() function Same as `filterCharcodes` but `predicate` operates on integer char codes instead of string characters. **Signature:**```typescript filterCharcodes: (s: string, predicate: (n: number) => boolean) => string ```## std.filtercharcodes: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to filter. | | predicate | (n: number) => boolean | The function to apply to each character code in the string. | **Returns:** string The filtered string. --- ## std.filterchars: filterChars() function `filterString` applies `predicate` character by character to `s` and it returns a filtered version of the string. **Signature:**```typescript filterChars: (s: string, predicate: (s: string) => boolean) => string ```## std.filterchars: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to filter. | | predicate | (s: string) => boolean | The function to apply to each character in the string. | **Returns:** string The filtered string. --- ## std.filtermaparray: filterMapArray() function Applies a mapping function to each element of an array and returns a new array containing the mapped values, excluding any `null` or `undefined` values. **Signature:**```typescript filterMapArray: (arr: A[], f: (a: A, index: number) => Maybe) => B[] ```## std.filtermaparray: Parameters | Parameter | Type | Description | | --- | --- | --- | | arr | A\[\] | The input array. | | f | (a: A, index: number) => [Maybe](#std-maybe)<B> | The mapping function to apply to each element. | **Returns:** B\[\] The new array containing the mapped values. --- ## std.filternullsfromarray: filterNullsFromArray() function Filters out null and undefined values from an array. **Signature:**```typescript filterNullsFromArray: (arr: Array) => T[] ```## std.filternullsfromarray: Parameters | Parameter | Type | Description | | --- | --- | --- | | arr | Array<T \\| [Nothing](#std-nothing)> | The array to filter. | **Returns:** T\[\] The filtered array. --- ## std.filtertuple: FilterTuple type Filters out elements from a tuple that are equal to the specified type. **Signature:**```typescript export type FilterTuple = T extends [] ? [] : T extends [infer H, ...infer R] ? N extends H ? FilterTuple : [H, ...FilterTuple] : T; ``` **References:** [FilterTuple](#std-filtertuple) --- ## std.find: find() function Finds the first element in an iterable that satisfies the predicate. This function returns the first element for which the predicate returns true, or undefined if no such element is found. **Signature:**```typescript find: (iterable: Iterable, predicate: (item: T) => boolean) => T | undefined ```## std.find: Parameters | Parameter | Type | Description | | --- | --- | --- | | iterable | Iterable<T> | The iterable to search | | predicate | (item: T) => boolean | Function that tests each element | **Returns:** T \| undefined The first matching element, or undefined if none found ## std.find: Example```typescript const numbers = [1, 3, 5, 8, 9, 12] const firstEven = find(numbers, n => n % 2 === 0) // 8 const users = [{ name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }] const adult = find(users, user => user.age >= 18) // { name: 'Alice', age: 25 } ``` --- ## std.firstargument: FirstArgument type Extracts the first argument type from a function type. **Signature:**```typescript export type FirstArgument = F extends Fun1 ? A : never; ``` **References:** [Fun1](#std-fun1) --- ## std.flip: flip() function Reverses the order of all arguments of a function. This function creates a new function that calls the original function with all arguments in reverse order. This is useful for creating more readable function compositions or when you need to change the argument order for currying or partial application. **Signature:**```typescript export declare function flip(fn: (...args: TArgs) => R): (...args: Reverse) => R; ```## std.flip: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn | (...args: TArgs) => R | The function to flip | **Returns:** (...args: [Reverse](#std-reverse)<TArgs>) => R A new function with all arguments reversed ## std.flip: Example```typescript const divide = (a: number, b: number) => a / b const flippedDivide = flip(divide) divide(10, 2) // 5 flippedDivide(2, 10) // 5 (same result, but arguments are reversed) // Works with any number of arguments const subtract = (a: number, b: number, c: number) => a - b - c const flippedSubtract = flip(subtract) subtract(10, 3, 2) // 5 (10 - 3 - 2) flippedSubtract(2, 3, 10) // 5 (10 - 3 - 2, arguments reversed) ``` --- ## std.floorto: floorTo() function Rounds a number down to the specified number of decimals. **Signature:**```typescript floorTo: (v: number, decimals: number) => number ```## std.floorto: Parameters | Parameter | Type | Description | | --- | --- | --- | | v | number | The number to round down. | | decimals | number | The number of decimals to round down to. | **Returns:** number The rounded down number. ## std.floorto: Example```ts floorTo(1.234, 2) // returns 1.23 floorTo(1.234, 1) // returns 1.2 floorTo(1.234, 0) // returns 1 ``` --- ## std.fun0: Fun0 type Represents a function that takes no arguments and returns a value of type `R`. **Signature:**```typescript export type Fun0 = () => R; ``` --- ## std.fun1: Fun1 type Represents a function that takes one argument of type `A` and returns a value of type `R`. **Signature:**```typescript export type Fun1 = (a: A) => R; ``` --- ## std.fun2: Fun2 type Represents a function that takes two arguments of types `A` and `B`, and returns a value of type `R`. **Signature:**```typescript export type Fun2 = (a: A, b: B) => R; ``` --- ## std.fun3: Fun3 type Represents a function that takes three arguments of types A, B, and C, and returns a value of type R. **Signature:**```typescript export type Fun3 = (a: A, b: B, c: C) => R; ``` --- ## std.fun4: Fun4 type Represents a function that takes four arguments of types A, B, C, and D, and returns a value of type R. **Signature:**```typescript export type Fun4 = (a: A, b: B, c: C, d: D) => R; ``` --- ## std.fun5: Fun5 type Represents a function that takes five arguments of types A, B, C, D, and E, and returns a value of type R. **Signature:**```typescript export type Fun5 = (a: A, b: B, c: C, d: D, e: E) => R; ``` --- ## std.fun6: Fun6 type Represents a function that takes six arguments of types A, B, C, D, E, F and returns a value of type R. **Signature:**```typescript export type Fun6 = (a: A, b: B, c: C, d: D, e: E, f: F) => R; ``` --- ## std.getbasename: getBaseName() function Extracts the base name (file name without extension) from a path. This function returns the file name without its extension. **Signature:**```typescript getBaseName: (path: string) => string ```## std.getbasename: Parameters | Parameter | Type | Description | | --- | --- | --- | | path | string | The path to extract base name from | **Returns:** string The base name without extension ## std.getbasename: Example```typescript getBaseName('/path/to/file.txt') // 'file' getBaseName('image.jpeg') // 'image' getBaseName('README') // 'README' getBaseName('.hidden') // '.hidden' getBaseName('file.tar.gz') // 'file.tar' ``` --- ## std.getfileextension: getFileExtension() function Extracts the file extension from a path. This function returns the file extension including the dot, or an empty string if no extension is found. **Signature:**```typescript getFileExtension: (path: string) => string ```## std.getfileextension: Parameters | Parameter | Type | Description | | --- | --- | --- | | path | string | The path to extract extension from | **Returns:** string The file extension including the dot, or empty string ## std.getfileextension: Example```typescript getFileExtension('/path/to/file.txt') // '.txt' getFileExtension('image.jpeg') // '.jpeg' getFileExtension('README') // '' getFileExtension('.hidden') // '' getFileExtension('file.tar.gz') // '.gz' ``` --- ## std.getfilename: getFileName() function Extracts the file name from a path. This function returns the last segment of a path, which is typically the file name. **Signature:**```typescript getFileName: (path: string) => string ```## std.getfilename: Parameters | Parameter | Type | Description | | --- | --- | --- | | path | string | The path to extract file name from | **Returns:** string The file name ## std.getfilename: Example```typescript getFileName('/path/to/file.txt') // 'file.txt' getFileName('file.txt') // 'file.txt' getFileName('/path/to/directory/') // '' getFileName('/path/to/directory') // 'directory' ``` --- ## std.getqueryparams: getQueryParams() function Extracts query parameters from a URL as an object. This function parses the query string and returns all parameters as a plain object with string values. **Signature:**```typescript getQueryParams: (url: string) => Record ```## std.getqueryparams: Parameters | Parameter | Type | Description | | --- | --- | --- | | url | string | The URL to extract parameters from | **Returns:** Record<string, string> An object containing all query parameters ## std.getqueryparams: Example```typescript const params = getQueryParams('https://example.com/path?name=john&age=30&active=true') // Result: { name: 'john', age: '30', active: 'true' } const empty = getQueryParams('https://example.com/path') // Result: {} ``` --- ## std.groupby: groupBy() function Groups array elements by a key function. This function creates an object where keys are the result of the key function and values are arrays of elements that produced that key. **Signature:**```typescript groupBy: (array: readonly T[], keyFn: (item: T) => K) => Record ```## std.groupby: Parameters | Parameter | Type | Description | | --- | --- | --- | | array | readonly T\[\] | The array to group | | keyFn | (item: T) => K | Function that extracts the grouping key from each element | **Returns:** Record<K, T\[\]> An object with grouped elements ## std.groupby: Example```typescript const users = [ { name: 'Alice', department: 'Engineering' }, { name: 'Bob', department: 'Engineering' }, { name: 'Carol', department: 'Marketing' } ] const byDepartment = groupBy(users, user => user.department) // Result: { // Engineering: [{ name: 'Alice', ... }, { name: 'Bob', ... }], // Marketing: [{ name: 'Carol', ... }] // } ``` --- ## std.humanize: humanize() function Works the same as `underscore` but also replaces underscores with whitespaces. **Signature:**```typescript humanize: (s: string) => string ```## std.humanize: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to convert. | **Returns:** string The converted string. --- ## std.id: Id type Represents an identity type that preserves the properties of the original type. **Signature:**```typescript export type Id = {} & { [P in keyof T]: T[P]; }; ``` --- ## std.identity: identity() function Returns the input value as is. **Signature:**```typescript identity: (v: T) => T ```## std.identity: Parameters | Parameter | Type | Description | | --- | --- | --- | | v | T | The value to be returned. | **Returns:** T The input value. --- ## std.ifemptystring: ifEmptyString() function `ifEmpty` returns `value` if it is neither `null` or empty, otherwise it returns `alt` **Signature:**```typescript ifEmptyString: (value: string, alt: string) => string ```## std.ifemptystring: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to check. | | alt | string | The alternative value to return if `value` is `null` or empty. | **Returns:** string The original string if it is not `null` or empty, otherwise the alternative value. --- ## std.indexkey: IndexKey type Represents a key type that can be used to index any object. **Signature:**```typescript export type IndexKey = keyof any; ``` --- ## std.interpolate: interpolate() function `interpolate` returns a value between `a` and `b` for any value of `t` (normally between 0 and 1). **Signature:**```typescript interpolate: (a: number, b: number, t: number) => number ```## std.interpolate: Parameters | Parameter | Type | Description | | --- | --- | --- | | a | number | The first value. | | b | number | The second value. | | t | number | The interpolation value. | **Returns:** number The interpolated value. ## std.interpolate: Example```ts interpolate(0, 10, 0.5) // returns 5 interpolate(0, 10, 0.25) // returns 2.5 interpolate(0, 10, 0.75) // returns 7.5 ``` --- ## std.interpolateangle: interpolateAngle() function Interpolates values in a polar coordinate system looking for the narrowest delta angle. It can be either clock-wise or counter-clock-wise. **Signature:**```typescript interpolateAngle: (a: number, b: number, t: number, turn?: number) => number ```## std.interpolateangle: Parameters | Parameter | Type | Description | | --- | --- | --- | | a | number | The first angle in degrees. | | b | number | The second angle in degrees. | | t | number | The interpolation value. | | turn | number | _(Optional)_ The total number of degrees in a full turn. Default is 360.0. | **Returns:** number The interpolated angle. ## std.interpolateangle: Example```ts interpolateAngle(0, 90, 0.5) // returns 45 interpolateAngle(0, 270, 0.5) // returns 315 interpolateAngle(0, 90, 0.25) // returns 22.5 interpolateAngle(0, 270, 0.25) // returns 337.5 ``` --- ## std.interpolateangleccw: interpolateAngleCCW() function Interpolates values in a polar coordinate system always in counter-clock-wise direction. **Signature:**```typescript interpolateAngleCCW: (a: number, b: number, t: number, turn?: number) => number ```## std.interpolateangleccw: Parameters | Parameter | Type | Description | | --- | --- | --- | | a | number | The first angle in degrees. | | b | number | The second angle in degrees. | | t | number | The interpolation value. | | turn | number | _(Optional)_ The total number of degrees in a full turn. Default is 360.0. | **Returns:** number The interpolated angle. ## std.interpolateangleccw: Example```ts interpolateAngleCCW(0, 90, 0.5) // returns 45 interpolateAngleCCW(0, 270, 0.5) // returns 315 interpolateAngleCCW(0, 90, 0.25) // returns 22.5 interpolateAngleCCW(0, 270, 0.25) // returns 337.5 ``` --- ## std.interpolateanglecw: interpolateAngleCW() function Interpolates values in a polar coordinate system always in clock-wise direction. **Signature:**```typescript interpolateAngleCW: (a: number, b: number, t: number, turn?: number) => number ```## std.interpolateanglecw: Parameters | Parameter | Type | Description | | --- | --- | --- | | a | number | The first angle in degrees. | | b | number | The second angle in degrees. | | t | number | The interpolation value. | | turn | number | _(Optional)_ The total number of degrees in a full turn. Default is 360.0. | **Returns:** number The interpolated angle. ## std.interpolateanglecw: Example```ts interpolateAngleCW(0, 90, 0.5) // returns 45 interpolateAngleCW(0, 270, 0.5) // returns 315 interpolateAngleCW(0, 90, 0.25) // returns 22.5 interpolateAngleCW(0, 270, 0.25) // returns 337.5 ``` --- ## std.interpolatewidestangle: interpolateWidestAngle() function Interpolates values in a polar coordinate system looking for the shortest delta angle. Note: Despite the name "widest", this function actually uses the shortest angle difference, identical to `interpolateAngle`. The name is misleading for historical reasons. **Signature:**```typescript interpolateWidestAngle: (a: number, b: number, t: number, turn?: number) => number ```## std.interpolatewidestangle: Parameters | Parameter | Type | Description | | --- | --- | --- | | a | number | The first angle in degrees. | | b | number | The second angle in degrees. | | t | number | The interpolation value. | | turn | number | _(Optional)_ The total number of degrees in a full turn. Default is 360.0. | **Returns:** number The interpolated angle. ## std.interpolatewidestangle: Example```ts interpolateWidestAngle(0, 90, 0.5) // returns 45 (using shortest path) interpolateWidestAngle(0, 270, 0.5) // returns 315 (using shortest path) interpolateWidestAngle(0, 90, 0.25) // returns 22.5 (using shortest path) interpolateWidestAngle(0, 270, 0.25) // returns 337.5 (using shortest path) ``` --- ## std.interval: interval() function Executes a function repeatedly at a fixed interval. **Signature:**```typescript interval: (fn: () => void, ms: number) => () => void ```## std.interval: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn | () => void | The function to execute periodically. The function can optionally return a callback that will be invoked when the delay is cancelled. | | ms | number | The number of milliseconds between each execution. | **Returns:** () => void A function that, when called, will cancel the interval and stop future executions. ## std.interval: Example```ts // Execute a function every 2 seconds const stop = interval(() => console.warn('Tick'), 2000); // Stop the interval after some time setTimeout(() => stop(), 10000); ``` --- ## std.intervalanimationframe: intervalAnimationFrame() function Executes a function repeatedly using requestAnimationFrame. **Signature:**```typescript intervalAnimationFrame: (callback: (time: DOMHighResTimeStamp) => void) => () => void ```## std.intervalanimationframe: Parameters | Parameter | Type | Description | | --- | --- | --- | | callback | (time: DOMHighResTimeStamp) => void | The function to execute periodically. | **Returns:** () => void A function that, when called, will cancel the interval and stop future executions. --- ## std.invalid: Invalid type Represents an invalid value with an associated error. **Signature:**```typescript export type Invalid = { readonly type: 'invalid'; readonly error: E; }; ``` --- ## std.isalpha: isAlpha() function Checks if `s` contains only (and at least one) alphabetical characters. **Signature:**```typescript isAlpha: (s: string) => boolean ```## std.isalpha: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to check. | **Returns:** boolean `true` if the string contains only alphabetical characters, `false` otherwise. --- ## std.isalphanum: isAlphaNum() function `isAlphaNum` returns `true` if the string only contains alpha-numeric characters. **Signature:**```typescript isAlphaNum: (value: string) => boolean ```## std.isalphanum: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to check. | **Returns:** boolean `true` if the string contains only alpha-numeric characters, `false` otherwise. --- ## std.isarrayempty: isArrayEmpty() function Checks if an array is empty. **Signature:**```typescript isArrayEmpty: (arr: T[]) => arr is [] ```## std.isarrayempty: Parameters | Parameter | Type | Description | | --- | --- | --- | | arr | T\[\] | The array to check. | **Returns:** arr is \[\] `true` if the array is empty, `false` otherwise. --- ## std.isbreakingwhitespace: isBreakingWhitespace() function Checks if a string contains any breaking whitespace characters. **Signature:**```typescript isBreakingWhitespace: (value: string) => boolean ```## std.isbreakingwhitespace: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to check. | **Returns:** boolean `true` if the string contains breaking whitespace characters, `false` otherwise. --- ## std.isdigitsonly: isDigitsOnly() function `isDigitsOnly` returns `true` if the string only contains digits. **Signature:**```typescript isDigitsOnly: (value: string) => boolean ```## std.isdigitsonly: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to check. | **Returns:** boolean `true` if the string contains only digits, `false` otherwise. --- ## std.isemptyobject: isEmptyObject() function Checks if an object is empty. An object is considered empty if it has no own enumerable properties. **Signature:**```typescript isEmptyObject: (obj: object) => boolean ```## std.isemptyobject: Parameters | Parameter | Type | Description | | --- | --- | --- | | obj | object | The object to check. | **Returns:** boolean `true` if the object is empty, `false` otherwise. --- ## std.isemptystring: isEmptyString() function `isEmpty` returns true if either `value` is null or is an empty string. **Signature:**```typescript isEmptyString: (value: string) => boolean ```## std.isemptystring: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to check. | **Returns:** boolean `true` if the string is `null` or empty, `false` otherwise. --- ## std.isjson: isJSON() function Checks if the value is a valid JSON value with comprehensive validation. This function provides thorough validation that goes beyond basic type checking by recursively validating nested objects and arrays to ensure the entire structure can be safely serialized to JSON. **Signature:**```typescript isJSON: (value: JSONValue) => value is JSONValue ```## std.isjson: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | [JSONValue](#std-jsonvalue) | The value to check. | **Returns:** value is [JSONValue](#std-jsonvalue) `true` if the value is a completely valid JSON value; otherwise, `false`. ## std.isjson: Example```typescript isJSON('hello') // true isJSON(42) // true isJSON(true) // true isJSON(null) // true isJSON({ name: 'Alice', age: 30 }) // true isJSON([1, 2, { nested: true }]) // true isJSON(undefined) // false isJSON(() => {}) // false isJSON({ func: () => {} }) // false (contains non-JSON value) ``` --- ## std.isjsonarray: isJSONArray() function Checks if the value is a JSON array with recursive validation. This function provides more thorough validation than `Array.isArray()` by recursively checking that all elements in the array are valid JSON values. This is essential for ensuring data can be safely serialized to JSON. **Signature:**```typescript isJSONArray: (value: JSONValue) => value is JSONArray ```## std.isjsonarray: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | [JSONValue](#std-jsonvalue) | The value to check. | **Returns:** value is [JSONArray](#std-jsonarray) `true` if the value is a JSON array with all valid JSON elements; otherwise, `false`. ## std.isjsonarray: Example```typescript isJSONArray([1, 2, 3]) // true isJSONArray(['hello', 'world']) // true isJSONArray([1, 'hello', true, null]) // true isJSONArray([1, 2, undefined]) // false (undefined is not JSON-serializable) isJSONArray([1, 2, () => {}]) // false (functions are not JSON-serializable) ``` --- ## std.isjsonobject: isJSONObject() function Checks if the value is a JSON object. **Signature:**```typescript isJSONObject: (value: JSONValue) => value is JSONObject ```## std.isjsonobject: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | [JSONValue](#std-jsonvalue) | The value to check. | **Returns:** value is [JSONObject](#std-jsonobject) `true` if the value is a JSON object; otherwise, `false`. --- ## std.isjsonprimitive: isJSONPrimitive() function Checks if the value is a JSON primitive. **Signature:**```typescript isJSONPrimitive: (value: JSONValue) => value is JSONPrimitive ```## std.isjsonprimitive: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | [JSONValue](#std-jsonvalue) | The value to check. | **Returns:** value is [JSONPrimitive](#std-jsonprimitive) `true` if the value is a JSON primitive; otherwise, `false`. --- ## std.islowercase: isLowerCase() function Returns `true` if the value string is composed of only lower cased characters or case neutral characters. **Signature:**```typescript isLowerCase: (value: string) => boolean ```## std.islowercase: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to check. | **Returns:** boolean `true` if the string contains only lower case characters, `false` otherwise. --- ## std.isobject: isObject() function Checks if the given value is an object. **Signature:**```typescript isObject: (obj: unknown) => obj is Record ```## std.isobject: Parameters | Parameter | Type | Description | | --- | --- | --- | | obj | unknown | The value to check. | **Returns:** obj is Record<[IndexKey](#std-indexkey), unknown> `true` if the value is an object, `false` otherwise. --- ## std.issameday: isSameDay() function Checks if two dates represent the same calendar day. This comparison ignores time components and only compares the date parts. Useful for date-based filtering and grouping. **Signature:**```typescript isSameDay: (dateA: Date, dateB: Date) => boolean ```## std.issameday: Parameters | Parameter | Type | Description | | --- | --- | --- | | dateA | Date | The first date | | dateB | Date | The second date | **Returns:** boolean true if both dates represent the same calendar day ## std.issameday: Example```typescript const date1 = new Date('2023-01-15T10:30:00') const date2 = new Date('2023-01-15T18:45:00') const date3 = new Date('2023-01-16T10:30:00') isSameDay(date1, date2) // true isSameDay(date1, date3) // false ``` --- ## std.issamehour: isSameHour() function Checks if two dates represent the same hour. This comparison ignores date and minute components and only compares the hour parts. Useful for time-based filtering and grouping. **Signature:**```typescript isSameHour: (dateA: Date, dateB: Date) => boolean ```## std.issamehour: Parameters | Parameter | Type | Description | | --- | --- | --- | | dateA | Date | The first date | | dateB | Date | The second date | **Returns:** boolean true if both dates represent the same hour ## std.issamehour: Example```typescript const date1 = new Date('2023-01-15T10:30:00') const date2 = new Date('2023-01-15T10:45:00') const date3 = new Date('2023-01-16T10:30:00') isSameHour(date1, date2) // true isSameHour(date1, date3) // false ``` --- ## std.issameminute: isSameMinute() function Checks if two dates represent the same minute. This comparison ignores date, hour, and second components and only compares the minute parts. Useful for time-based filtering and grouping. **Signature:**```typescript isSameMinute: (dateA: Date, dateB: Date) => boolean ```## std.issameminute: Parameters | Parameter | Type | Description | | --- | --- | --- | | dateA | Date | The first date | | dateB | Date | The second date | **Returns:** boolean true if both dates represent the same minute ## std.issameminute: Example```typescript const date1 = new Date('2023-01-15T10:30:00') const date2 = new Date('2023-01-15T10:30:45') const date3 = new Date('2023-01-16T10:30:00') isSameMinute(date1, date2) // true isSameMinute(date1, date3) // false ``` --- ## std.issamemonth: isSameMonth() function Checks if two dates represent the same calendar month. This comparison ignores the day and time components and only compares the month and year parts. Useful for monthly reports and date grouping. **Signature:**```typescript isSameMonth: (dateA: Date, dateB: Date) => boolean ```## std.issamemonth: Parameters | Parameter | Type | Description | | --- | --- | --- | | dateA | Date | The first date | | dateB | Date | The second date | **Returns:** boolean true if both dates represent the same calendar month ## std.issamemonth: Example```typescript const date1 = new Date('2023-01-15') // January const date2 = new Date('2023-02-15') // February const date3 = new Date('2024-01-15') // January of next year isSameMonth(date1, date2) // false isSameMonth(date1, date3) // true ``` --- ## std.issamesecond: isSameSecond() function Checks if two dates represent the same second. This comparison ignores date, hour, and minute components and only compares the second parts. Useful for time-based filtering and grouping. **Signature:**```typescript isSameSecond: (dateA: Date, dateB: Date) => boolean ```## std.issamesecond: Parameters | Parameter | Type | Description | | --- | --- | --- | | dateA | Date | The first date | | dateB | Date | The second date | **Returns:** boolean true if both dates represent the same second ## std.issamesecond: Example```typescript const date1 = new Date('2023-01-15T10:30:00') const date2 = new Date('2023-01-15T10:30:00') const date3 = new Date('2023-01-16T10:30:00') isSameSecond(date1, date2) // true isSameSecond(date1, date3) // false ``` --- ## std.issameweek: isSameWeek() function Checks if two dates represent the same calendar week. This comparison uses the ISO 8601 week definition, where weeks start on Monday. Useful for weekly reports and date grouping. **Signature:**```typescript isSameWeek: (dateA: Date, dateB: Date) => boolean ```## std.issameweek: Parameters | Parameter | Type | Description | | --- | --- | --- | | dateA | Date | The first date | | dateB | Date | The second date | **Returns:** boolean true if both dates represent the same calendar week ## std.issameweek: Example```typescript const date1 = new Date('2023-01-15') // Monday const date2 = new Date('2023-01-16') // Tuesday const date3 = new Date('2023-01-22') // Monday of next week isSameWeek(date1, date2) // true isSameWeek(date1, date3) // false ``` --- ## std.issameyear: isSameYear() function Checks if two dates represent the same calendar year. This comparison ignores the month and day components and only compares the year part. Useful for yearly reports and date grouping. **Signature:**```typescript isSameYear: (dateA: Date, dateB: Date) => boolean ```## std.issameyear: Parameters | Parameter | Type | Description | | --- | --- | --- | | dateA | Date | The first date | | dateB | Date | The second date | **Returns:** boolean true if both dates represent the same calendar year ## std.issameyear: Example```typescript const date1 = new Date('2023-01-15') // January const date2 = new Date('2023-02-15') // February const date3 = new Date('2024-01-15') // January of next year isSameYear(date1, date2) // true isSameYear(date1, date3) // false ``` --- ## std.isspaceat: isSpaceAt() function Checks if the character at the specified position in a string is a whitespace character. **Signature:**```typescript isSpaceAt: (s: string, pos: number) => boolean ```## std.isspaceat: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The input string. | | pos | number | The position of the character to check. | **Returns:** boolean A boolean indicating whether the character at the specified position is a whitespace character. --- ## std.isunion: IsUnion type **Signature:**```typescript export type IsUnion = T extends any ? [U] extends [T] ? false : true : never; ``` --- ## std.isuppercase: isUpperCase() function Returns `true` if the value string is composed of only upper cased characters or case neutral characters. **Signature:**```typescript isUpperCase: (value: string) => boolean ```## std.isuppercase: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to check. | **Returns:** boolean `true` if the string contains only upper case characters, `false` otherwise. --- ## std.isvaliddate: isValidDate() function Checks if a value is a valid Date object. This function checks both that the value is a Date instance and that it represents a valid date (not NaN). **Signature:**```typescript isValidDate: (date: unknown) => date is Date ```## std.isvaliddate: Parameters | Parameter | Type | Description | | --- | --- | --- | | date | unknown | The value to check | **Returns:** date is Date true if the value is a valid Date, false otherwise ## std.isvaliddate: Example```typescript isValidDate(new Date()) // true isValidDate(new Date('2023-01-15')) // true isValidDate(new Date('invalid')) // false isValidDate('2023-01-15') // false isValidDate(null) // false ``` --- ## std.isvalidurl: isValidUrl() function Checks if a string is a valid URL. This function validates URLs more safely than using the URL constructor directly, as it doesn't throw exceptions. **Signature:**```typescript isValidUrl: (url: string) => boolean ```## std.isvalidurl: Parameters | Parameter | Type | Description | | --- | --- | --- | | url | string | The string to validate | **Returns:** boolean true if the string is a valid URL, false otherwise ## std.isvalidurl: Example```typescript isValidUrl('https://example.com') // true isValidUrl('http://localhost:3000/path') // true isValidUrl('ftp://files.example.com') // true isValidUrl('not-a-url') // false isValidUrl('') // false ``` --- ## std.isweekend: isWeekend() function Checks if a date falls on a weekend (Saturday or Sunday). This is useful for business logic that needs to handle weekends differently, such as scheduling or date calculations. **Signature:**```typescript isWeekend: (date: Date) => boolean ```## std.isweekend: Parameters | Parameter | Type | Description | | --- | --- | --- | | date | Date | The date to check | **Returns:** boolean true if the date is a Saturday or Sunday ## std.isweekend: Example```typescript const saturday = new Date('2023-01-14') // Saturday const monday = new Date('2023-01-16') // Monday isWeekend(saturday) // true isWeekend(monday) // false ``` --- ## std.joinarraywithconjunction: joinArrayWithConjunction() function Joins an array of values into a string using a conjunction and separator. **Signature:**```typescript joinArrayWithConjunction: (arr: A[], conjunction?: string, separator?: string) => string ```## std.joinarraywithconjunction: Parameters | Parameter | Type | Description | | --- | --- | --- | | arr | A\[\] | The array of values to join. | | conjunction | string | _(Optional)_ The conjunction to use between the second-to-last and last value. Default is ' and '. | | separator | string | _(Optional)_ The separator to use between each value. Default is ', '. | **Returns:** string The joined string. --- ## std.joinpaths: joinPaths() function Joins multiple path segments into a single path. This function properly handles leading and trailing slashes, ensuring a clean path without double slashes or missing separators. **Signature:**```typescript joinPaths: (...paths: string[]) => string ```## std.joinpaths: Parameters | Parameter | Type | Description | | --- | --- | --- | | paths | string\[\] | Path segments to join | **Returns:** string The joined path ## std.joinpaths: Example```typescript const path = joinPaths('api', 'v1', 'users', '123') // Result: 'api/v1/users/123' const withSlashes = joinPaths('/api/', '/v1/', 'users/') // Result: '/api/v1/users/' const empty = joinPaths('', 'path', '', 'file') // Result: 'path/file' ``` --- ## std.jsonarray: JSONArray type Represents an array of JSON values. **Signature:**```typescript export type JSONArray = JSONValue[]; ``` **References:** [JSONValue](#std-jsonvalue) --- ## std.jsonobject: JSONObject interface Represents a JSON object. **Signature:**```typescript export interface JSONObject ``` --- ## std.jsonprimitive: JSONPrimitive type Represents a JSON primitive value. It can be a string, boolean, number, or Nothing (null or undefined). **Signature:**```typescript export type JSONPrimitive = string | boolean | number | Nothing; ``` **References:** [Nothing](#std-nothing) --- ## std.jsonvalue: JSONValue type Represents a JSON value, which can be a primitive, an object, or an array. **Signature:**```typescript export type JSONValue = JSONPrimitive | JSONObject | JSONArray; ``` **References:** [JSONPrimitive](#std-jsonprimitive), [JSONObject](#std-jsonobject), [JSONArray](#std-jsonarray) --- ## std.jsquote: jsQuote() function Quotes a string for use in JavaScript code. If the string contains a newline character, it will be quoted using backticks. Otherwise, it will be quoted using single quotes (`'`) or double quotes (`"`) based on the `prefer` parameter. **Signature:**```typescript jsQuote: (s: string, prefer?: string) => string ```## std.jsquote: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to be quoted. | | prefer | string | _(Optional)_ The preferred quote character. Defaults to single quote (`'`). | **Returns:** string The quoted string. --- ## std.loading: Loading type Represents a loading state in an asynchronous result. **Signature:**```typescript export type Loading = { readonly type: 'Loading'; readonly previousValue?: V; }; ``` --- ## std.looseequal: looseEqual() function Checks if two values are loosely equal. **Signature:**```typescript looseEqual: (a: T, b: T) => boolean ```## std.looseequal: Parameters | Parameter | Type | Description | | --- | --- | --- | | a | T | The first value to compare. | | b | T | The second value to compare. | **Returns:** boolean `true` if the values are loosely equal, `false` otherwise. --- ## std.lowercasefirst: lowerCaseFirst() function Convert first letter in `value` to lower case. **Signature:**```typescript lowerCaseFirst: (value: string) => string ```## std.lowercasefirst: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to convert. | **Returns:** string The string with the first letter in lower case. --- ## std.lpad: lpad() function Pads a string on the left with a specified character until it reaches a specified length. If the string is already longer than the specified length, it is returned as is. **Signature:**```typescript lpad: (s: string, char: string, length: number) => string ```## std.lpad: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to pad. | | char | string | The character to use for padding. | | length | number | The desired length of the padded string. | **Returns:** string The padded string. --- ## std.map: map() function Maps an iterable, transforming each element with the mapper function. This function creates a new iterable that yields transformed elements. It's lazy and memory-efficient, processing elements on-demand. **Signature:**```typescript map: (iterable: Iterable, mapper: (item: T) => U) => Iterable ```## std.map: Parameters | Parameter | Type | Description | | --- | --- | --- | | iterable | Iterable<T> | The iterable to map | | mapper | (item: T) => U | Function that transforms each element | **Returns:** Iterable<U> An iterable that yields transformed elements ## std.map: Example```typescript const numbers = [1, 2, 3, 4, 5] const doubled = [...map(numbers, n => n * 2)] // [2, 4, 6, 8, 10] const users = [{ name: 'Alice' }, { name: 'Bob' }] const names = [...map(users, user => user.name)] // ['Alice', 'Bob'] ``` --- ## std.mapchars: mapChars() function It maps a string character by character using `callback`. **Signature:**```typescript mapChars: (callback: (c: string) => T, value: string) => T[] ```## std.mapchars: Parameters | Parameter | Type | Description | | --- | --- | --- | | callback | (c: string) => T | The function to apply to each character in the string. | | value | string | The string to map. | **Returns:** T\[\] An array of the mapped characters. --- ## std.mapentries: mapEntries() function Gets all entries from a Map as an array of key-value pairs. This provides a convenient way to get Map entries as an array for further processing or serialization. **Signature:**```typescript mapEntries: (map: Map) => [K, V][] ```## std.mapentries: Parameters | Parameter | Type | Description | | --- | --- | --- | | map | Map<K, V> | The Map to extract entries from | **Returns:** \[K, V\]\[\] An array of all key-value pairs in the Map ## std.mapentries: Example```typescript const map = new Map([['a', 1], ['b', 2], ['c', 3]]) const entries = mapEntries(map) // Result: [['a', 1], ['b', 2], ['c', 3]] ``` --- ## std.mapfilter: mapFilter() function Creates a new Map containing only entries that satisfy the predicate. This provides a functional approach to filtering Maps, similar to Array.prototype.filter but for Map objects. **Signature:**```typescript mapFilter: (map: Map, predicate: (value: V, key: K) => boolean) => Map ```## std.mapfilter: Parameters | Parameter | Type | Description | | --- | --- | --- | | map | Map<K, V> | The Map to filter | | predicate | (value: V, key: K) => boolean | Function that tests each entry | **Returns:** Map<K, V> A new Map with entries that satisfy the predicate ## std.mapfilter: Example```typescript const map = new Map([['a', 1], ['b', 2], ['c', 3], ['d', 4]]) const evenValues = mapFilter(map, (value) => value % 2 === 0) // Result: Map { 'b' => 2, 'd' => 4 } ``` --- ## std.mapfromentries: mapFromEntries() function Creates a Map from an array of key-value pairs. This function provides better type inference than the Map constructor when working with typed key-value pairs. **Signature:**```typescript mapFromEntries: (entries: readonly [K, V][]) => Map ```## std.mapfromentries: Parameters | Parameter | Type | Description | | --- | --- | --- | | entries | readonly \[K, V\]\[\] | Array of key-value pairs | **Returns:** Map<K, V> A new Map containing the entries ## std.mapfromentries: Example```typescript const entries: [string, number][] = [['a', 1], ['b', 2], ['c', 3]] const map = mapFromEntries(entries) // Result: Map { 'a' => 1, 'b' => 2, 'c' => 3 } ``` --- ## std.mapgroupby: mapGroupBy() function Groups an array of items by a key function into a Map. This is more flexible than object-based grouping as it supports any key type, not just strings and symbols. **Signature:**```typescript mapGroupBy: (array: readonly T[], keyFn: (item: T) => K) => Map ```## std.mapgroupby: Parameters | Parameter | Type | Description | | --- | --- | --- | | array | readonly T\[\] | Array of items to group | | keyFn | (item: T) => K | Function that extracts the grouping key from each item | **Returns:** Map<K, T\[\]> A Map where keys are group identifiers and values are arrays of items ## std.mapgroupby: Example```typescript const users = [ { name: 'Alice', department: 'Engineering' }, { name: 'Bob', department: 'Engineering' }, { name: 'Carol', department: 'Marketing' } ] const byDepartment = mapGroupBy(users, user => user.department) // Result: Map { // 'Engineering' => [{ name: 'Alice', ... }, { name: 'Bob', ... }], // 'Marketing' => [{ name: 'Carol', ... }] // } ``` --- ## std.mapisempty: mapIsEmpty() function Checks if a Map is empty. This provides a semantic way to check for empty Maps, making code more readable than checking size === 0. **Signature:**```typescript mapIsEmpty: (map: Map) => boolean ```## std.mapisempty: Parameters | Parameter | Type | Description | | --- | --- | --- | | map | Map<K, V> | The Map to check | **Returns:** boolean true if the Map has no entries, false otherwise ## std.mapisempty: Example```typescript const emptyMap = new Map() const nonEmptyMap = new Map([['a', 1]]) mapIsEmpty(emptyMap) // true mapIsEmpty(nonEmptyMap) // false ``` --- ## std.mapkeys: mapKeys() function Gets all keys from a Map as an array. This provides a convenient way to get Map keys as an array for further processing with array methods. **Signature:**```typescript mapKeys: (map: Map) => K[] ```## std.mapkeys: Parameters | Parameter | Type | Description | | --- | --- | --- | | map | Map<K, V> | The Map to extract keys from | **Returns:** K\[\] An array of all keys in the Map ## std.mapkeys: Example```typescript const map = new Map([['a', 1], ['b', 2], ['c', 3]]) const keys = mapKeys(map) // Result: ['a', 'b', 'c'] ``` --- ## std.mapmap: mapMap() function Creates a new Map with values transformed by the mapper function. This provides a functional approach to transforming Map values, similar to Array.prototype.map but for Map objects. **Signature:**```typescript mapMap: (map: Map, mapper: (value: V, key: K) => U) => Map ```## std.mapmap: Parameters | Parameter | Type | Description | | --- | --- | --- | | map | Map<K, V> | The Map to transform | | mapper | (value: V, key: K) => U | Function that transforms each value | **Returns:** Map<K, U> A new Map with transformed values ## std.mapmap: Example```typescript const map = new Map([['a', 1], ['b', 2], ['c', 3]]) const doubled = mapMap(map, (value) => value * 2) // Result: Map { 'a' => 2, 'b' => 4, 'c' => 6 } ``` --- ## std.mapmerge: mapMerge() function Merges multiple Maps into a single Map. Later Maps take precedence over earlier ones for duplicate keys. This is useful for combining configuration objects or merging data. **Signature:**```typescript mapMerge: (...maps: Map[]) => Map ```## std.mapmerge: Parameters | Parameter | Type | Description | | --- | --- | --- | | maps | Map<K, V>\[\] | Maps to merge | **Returns:** Map<K, V> A new Map containing all entries from input Maps ## std.mapmerge: Example```typescript const map1 = new Map([['a', 1], ['b', 2]]) const map2 = new Map([['b', 3], ['c', 4]]) const merged = mapMerge(map1, map2) // Result: Map { 'a' => 1, 'b' => 3, 'c' => 4 } ``` --- ## std.mapregexp: mapRegExp() function Map the function `f` on each occurance matched by the pattern. **Signature:**```typescript mapRegExp: (subject: string, pattern: RegExp, f: (...s: string[]) => string) => string ```## std.mapregexp: Parameters | Parameter | Type | Description | | --- | --- | --- | | subject | string | The string to search. | | pattern | RegExp | The pattern to match. | | f | (...s: string\[\]) => string | The function to apply to each match. | **Returns:** string --- ## std.maptoobject: mapToObject() function Converts a Map with string keys to a plain object. This is useful for serialization or when you need to work with APIs that expect plain objects instead of Maps. **Signature:**```typescript mapToObject: (map: Map) => Record ```## std.maptoobject: Parameters | Parameter | Type | Description | | --- | --- | --- | | map | Map<string, V> | The Map to convert | **Returns:** Record<string, V> A plain object with the same key-value pairs ## std.maptoobject: Example```typescript const map = new Map([['name', 'Alice'], ['age', '30']]) const obj = mapToObject(map) // Result: { name: 'Alice', age: '30' } ``` --- ## std.mapvalues: mapValues() function Gets all values from a Map as an array. This provides a convenient way to get Map values as an array for further processing with array methods. **Signature:**```typescript mapValues: (map: Map) => V[] ```## std.mapvalues: Parameters | Parameter | Type | Description | | --- | --- | --- | | map | Map<K, V> | The Map to extract values from | **Returns:** V\[\] An array of all values in the Map ## std.mapvalues: Example```typescript const map = new Map([['a', 1], ['b', 2], ['c', 3]]) const values = mapValues(map) // Result: [1, 2, 3] ``` --- ## std.maybe: Maybe type Represents a type that can either hold a value of type T or be undefined. **Signature:**```typescript export type Maybe = T | undefined; ``` --- ## std package ## std: Functions | Function | Description | | --- | --- | | [addDays(date, days)](#std-adddays) | Adds the specified number of days to a date. This function creates a new Date object with the specified number of days added. Negative values subtract days. | | [addHours(date, hours)](#std-addhours) | Adds the specified number of hours to a date. This function creates a new Date object with the specified number of hours added. Negative values subtract hours. | | [addMinutes(date, minutes)](#std-addminutes) | Adds the specified number of minutes to a date. This function creates a new Date object with the specified number of minutes added. Negative values subtract minutes. | | [angleDifference(a, b, turn)](#std-angledifference) | Calculates the minimum difference between two angles in degrees. | | [applyArrayDiffOperations(operations, start)](#std-applyarraydiffoperations) | Applies a series of operations to an array and returns the modified array. | | [areArraysEqual(a, b, equals)](#std-arearraysequal) | Checks if two arrays are equal based on a custom equality function. | | [arrayDiffOperations(from, to, getKey)](#std-arraydiffoperations) | Calculates the difference operations between two arrays based on a key function. | | [arrayHasValues(arr)](#std-arrayhasvalues) | Checks if an array has values. | | [arrayHead(arr)](#std-arrayhead) | Returns the first element of an array, or `undefined` if the array is empty. | | [arrayTail(arr)](#std-arraytail) | Returns a new array containing all elements of the input array except for the first element. | | [biAbs(x)](#std-biabs) | Returns the absolute value of a bigint. | | [biCeilDiv(x, y)](#std-biceildiv) | Calculates the ceiling division of two BigInt numbers. | | [biCompare(x, y)](#std-bicompare) | Compares two BigInt values and returns a number indicating their relative order. | | [biFloorDiv(x, y)](#std-bifloordiv) | Divides two BigInt numbers and returns the largest integer less than or equal to the quotient. | | [biGcd(x, y)](#std-bigcd) | Calculates the greatest common divisor (GCD) of two BigInt numbers. | | [biIsEven(x)](#std-biiseven) | Checks if a given bigint is even. | | [biIsNegative(x)](#std-biisnegative) | Checks if a given bigint is negative. | | [biIsOdd(x)](#std-biisodd) | Checks if a given bigint is odd. | | [biIsOne(x)](#std-biisone) | Checks if a given bigint is equal to 1n. | | [biIsPositive(x)](#std-biispositive) | Checks if a bigint is positive. | | [biIsPrime(x)](#std-biisprime) | Checks if a given number is prime. | | [biIsZero(x)](#std-biiszero) | Checks if a given bigint is zero. | | [biLcm(x, y)](#std-bilcm) | Calculates the least common multiple (LCM) of two BigInt numbers. | | [biMax(x, y)](#std-bimax) | Returns the maximum of two BigInt values. | | [biMin(x, y)](#std-bimin) | Returns the minimum of two BigInt values. | | [biNextPrime(x)](#std-binextprime) | Finds the next prime number greater than the given number. | | [biPow(x, y)](#std-bipow) | Calculates the power of a bigint number. | | [biPrevPrime(x)](#std-biprevprime) | Returns the previous prime number less than the given number. Throws an error if there is no previous prime. | | [booleanToInt(v)](#std-booleantoint) | Converts a boolean to an integer value (`true` => `1`, `false` => `0`). | | [buildArray(length, f)](#std-buildarray) | Generates an array of values by applying a function to each index. This function provides a more semantic alternative to `Array.from({ length }, (_, i) => f(i))` with better readability and intent expression. It's particularly useful for creating arrays with computed values based on their position. | | [buildUrl(base, params)](#std-buildurl) | Builds a URL from a base URL and query parameters. This function safely constructs URLs with query parameters, handling encoding and existing parameters properly. | | [canonicalizeNewlines(value)](#std-canonicalizenewlines) | Replaces occurrances of `\r\n`, `\n\r`, `\r` with `\n` | | [canParseBoolean(v)](#std-canparseboolean) | Returns `true` if the passed value can be parsed as a boolean. The following values are considered parsable: - `'true'` / `'false'` - `'0'` / `'1'` - `'on'` / `'off'` The comparison is case insensitive. | | [capitalize(s)](#std-capitalize) | `capitalize` returns a string with the first character convert to upper case. | | [capitalizeWords(value, whiteSpaceOnly)](#std-capitalizewords) | Capitalize the first letter of every word in `value`. If `whiteSpaceOnly` is set to `true` the process is limited to whitespace separated words. | | [ceilTo(v, decimals)](#std-ceilto) | Rounds a number up to the specified number of decimals. | | [chain(iterables)](#std-chain) | Chains multiple iterables into a single iterable. This function creates a new iterable that yields all elements from the input iterables in sequence. | | [chunk(array, size)](#std-chunk) | Splits an array into chunks of the specified size. This function divides an array into smaller arrays of a fixed size. The last chunk may contain fewer elements if the array length is not evenly divisible by the chunk size. | | [chunkString(s, len)](#std-chunkstring) | Returns an array of `string` whose elements are equally long (using `len`). If the string `s` is not exactly divisible by `len` the last element of the array will be shorter. | | [clamp(value, min, max)](#std-clamp) | `clamp` restricts a value within the specified range. | | [clampInt(value, min, max)](#std-clampint) | Clamps a number to a specified range and returns an integer value. | | [clampSym(v, max)](#std-clampsym) | Like clamp but you only pass one argument (`max`) that is used as the upper limit and the opposite (additive inverse or `-max`) as the lower limit. | | [collapseText(value)](#std-collapsetext) | It cleans up all the whitespaces in the passed `value`. `collapse` does the following: - remove trailing/leading whitespaces - within the string, it collapses seqeunces of whitespaces into a single space character For whitespaces in this description, it is intended to be anything that is matched by the regular expression `\s`. | | [compareArrays(a, b, comparef, shorterFirst)](#std-comparearrays) | Compares two arrays based on their lengths and element values. | | [compareBooleans(a, b)](#std-comparebooleans) | Returns a comparison value (`Int`) from two boolean values. | | [compareCaseInsensitive(a, b)](#std-comparecaseinsensitive) | Compares two strings ignoring their case. | | [compareDates(a, b)](#std-comparedates) | Compares two dates. | | [compareNumbers(a, b)](#std-comparenumbers) | It returns the comparison value (an integer number) between two `float` values. | | [compareStrings(a, b)](#std-comparestrings) | It compares to string and it returns a negative number if `a` is inferior to `b`, zero if they are the same, or otherwise a positive non-sero number. | | [compose()](#std-compose) | Composes functions from right to left. This function creates a new function that applies the given functions in right-to-left order. The rightmost function can accept multiple arguments, while the others must be unary. | | [compose(fn1)](#std-compose1) | | | [compose(fn2, fn1)](#std-compose2) | | | [compose(fn3, fn2, fn1)](#std-compose3) | | | [compose(fn4, fn3, fn2, fn1)](#std-compose4) | | | [containsAllText(s, tests)](#std-containsalltext) | `containsAllText` returns `true` if `s` contains all of the strings in `tests` | | [containsAllTextCaseInsensitive(s, tests)](#std-containsalltextcaseinsensitive) | `containsAllTextCaseInsensitive` returns `true` if `s` contains all of the strings in `tests` regardless of the text case | | [containsAnyText(s, tests)](#std-containsanytext) | `containsAnyText` returns `true` if `s` contains any of the strings in `tests` | | [containsAnyTextCaseInsensitive(s, tests)](#std-containsanytextcaseinsensitive) | `containsAnyTextCaseInsensitive` returns `true` if `s` contains any of the strings in `tests` regardless of the text case | | [countStringOccurrences(s, test)](#std-countstringoccurrences) | Return the number of occurrences of `test` in `s`. | | [curryLeft(f)](#std-curryleft) | Curries a function from left to right. | | [dasherize(s)](#std-dasherize) | `dasherize` replaces all the occurrances of `_` with `-` | | [debounce(delay, callback, { atBegin })](#std-debounce) | Debounce execution of a function. Debouncing, unlike throttling, guarantees that a function is only executed a single time, either at the very beginning of a series of calls, or at the very end. | | [decodeBase64(s)](#std-decodebase64) | Decodes a base64 encoded string. | | [deepClone(obj)](#std-deepclone) | Creates a deep clone of an object. This function recursively clones objects, arrays, and primitive values. It handles Date objects specially and avoids infinite recursion. | | [deepEqual(a, b)](#std-deepequal) | Checks if two values are equal by comparing their contents. | | [deferred()](#std-deferred) | Creates a deferred object. A deferred object is a promise that can be resolved or rejected. | | [delayed(fn, ms)](#std-delayed) | Delays the execution of a function by the given number of milliseconds. | | [delayedAnimationFrame(callback)](#std-delayedanimationframe) | Delays the execution of a function using requestAnimationFrame. | | [deleteFirstFromString(value, toremove)](#std-deletefirstfromstring) | If present, it removes the first occurrence of `toremove` from `value`. | | [deleteStringAfter(value, toremove)](#std-deletestringafter) | If present, it removes the `toremove` text from the end of `value`. | | [deleteStringBefore(value, toremove)](#std-deletestringbefore) | If present, it removes the `toremove` text from the beginning of `value`. | | [deleteSubstring(value, toremove)](#std-deletesubstring) | If present, it removes all the occurrences of `toremove` from `value`. | | [diffInDays(dateA, dateB)](#std-diffindays) | Calculates the difference in days between two dates. Returns a positive number if dateB is after dateA, negative if before. The calculation ignores time components and focuses on calendar days. | | [diffInHours(dateA, dateB)](#std-diffinhours) | Calculates the difference in hours between two dates. Returns a positive number if dateB is after dateA, negative if before. The result includes fractional hours for precise calculations. | | [ellipsis(s, maxlen, symbol)](#std-ellipsis) | `ellipsis` truncates `s` at len `maxlen` replaces the last characters with the content of `symbol`. | | [ellipsisMiddle(s, maxlen, symbol)](#std-ellipsismiddle) | Same as `ellipsis` but puts the symbol in the middle of the string and not to the end. | | [encodeBase64(s)](#std-encodebase64) | Encodes a string to base64. | | [endOfDay(date)](#std-endofday) | Returns a new Date representing the end of the day (23:59:59.999). This is useful for date range queries where you need the last millisecond of a given day. | | [endOfWeek(date)](#std-endofweek) | Returns a new Date representing the end of the week (Sunday 23:59:59.999). This follows the ISO 8601 standard where Sunday is the last day of the week. Useful for weekly reports and date grouping. | | [every(iterable, predicate)](#std-every) | Tests whether all elements in an iterable satisfy the predicate. This function returns true if the predicate returns true for all elements, or false otherwise. It short-circuits on the first false result. | | [fillArray(length, value)](#std-fillarray) | Creates a new array with the specified length and fills it with the provided value. This function provides a more semantic alternative to `Array(length).fill(value)` or `new Array(length).fill(value)` with better type inference and clearer intent. It's particularly useful when you need arrays of non-primitive values or when working with functional programming patterns. | | [filter(iterable, predicate)](#std-filter) | Filters an iterable, yielding only elements that satisfy the predicate. This function creates a new iterable that yields only elements for which the predicate returns true. It's lazy and memory-efficient. | | [filterCharcodes(s, predicate)](#std-filtercharcodes) | Same as `filterCharcodes` but `predicate` operates on integer char codes instead of string characters. | | [filterChars(s, predicate)](#std-filterchars) | `filterString` applies `predicate` character by character to `s` and it returns a filtered version of the string. | | [filterMapArray(arr, f)](#std-filtermaparray) | Applies a mapping function to each element of an array and returns a new array containing the mapped values, excluding any `null` or `undefined` values. | | [filterNullsFromArray(arr)](#std-filternullsfromarray) | Filters out null and undefined values from an array. | | [find(iterable, predicate)](#std-find) | Finds the first element in an iterable that satisfies the predicate. This function returns the first element for which the predicate returns true, or undefined if no such element is found. | | [flip(fn)](#std-flip) | Reverses the order of all arguments of a function. This function creates a new function that calls the original function with all arguments in reverse order. This is useful for creating more readable function compositions or when you need to change the argument order for currying or partial application. | | [floorTo(v, decimals)](#std-floorto) | Rounds a number down to the specified number of decimals. | | [getBaseName(path)](#std-getbasename) | Extracts the base name (file name without extension) from a path. This function returns the file name without its extension. | | [getFileExtension(path)](#std-getfileextension) | Extracts the file extension from a path. This function returns the file extension including the dot, or an empty string if no extension is found. | | [getFileName(path)](#std-getfilename) | Extracts the file name from a path. This function returns the last segment of a path, which is typically the file name. | | [getQueryParams(url)](#std-getqueryparams) | Extracts query parameters from a URL as an object. This function parses the query string and returns all parameters as a plain object with string values. | | [groupBy(array, keyFn)](#std-groupby) | Groups array elements by a key function. This function creates an object where keys are the result of the key function and values are arrays of elements that produced that key. | | [humanize(s)](#std-humanize) | Works the same as `underscore` but also replaces underscores with whitespaces. | | [identity(v)](#std-identity) | Returns the input value as is. | | [ifEmptyString(value, alt)](#std-ifemptystring) | `ifEmpty` returns `value` if it is neither `null` or empty, otherwise it returns `alt` | | [interpolate(a, b, t)](#std-interpolate) | `interpolate` returns a value between `a` and `b` for any value of `t` (normally between 0 and 1). | | [interpolateAngle(a, b, t, turn)](#std-interpolateangle) | Interpolates values in a polar coordinate system looking for the narrowest delta angle. It can be either clock-wise or counter-clock-wise. | | [interpolateAngleCCW(a, b, t, turn)](#std-interpolateangleccw) | Interpolates values in a polar coordinate system always in counter-clock-wise direction. | | [interpolateAngleCW(a, b, t, turn)](#std-interpolateanglecw) | Interpolates values in a polar coordinate system always in clock-wise direction. | | [interpolateWidestAngle(a, b, t, turn)](#std-interpolatewidestangle) | Interpolates values in a polar coordinate system looking for the shortest delta angle. Note: Despite the name "widest", this function actually uses the shortest angle difference, identical to `interpolateAngle`. The name is misleading for historical reasons. | | [interval(fn, ms)](#std-interval) | Executes a function repeatedly at a fixed interval. | | [intervalAnimationFrame(callback)](#std-intervalanimationframe) | Executes a function repeatedly using requestAnimationFrame. | | [isAlpha(s)](#std-isalpha) | Checks if `s` contains only (and at least one) alphabetical characters. | | [isAlphaNum(value)](#std-isalphanum) | `isAlphaNum` returns `true` if the string only contains alpha-numeric characters. | | [isArrayEmpty(arr)](#std-isarrayempty) | Checks if an array is empty. | | [isBreakingWhitespace(value)](#std-isbreakingwhitespace) | Checks if a string contains any breaking whitespace characters. | | [isDigitsOnly(value)](#std-isdigitsonly) | `isDigitsOnly` returns `true` if the string only contains digits. | | [isEmptyObject(obj)](#std-isemptyobject) | Checks if an object is empty. An object is considered empty if it has no own enumerable properties. | | [isEmptyString(value)](#std-isemptystring) | `isEmpty` returns true if either `value` is null or is an empty string. | | [isJSON(value)](#std-isjson) | Checks if the value is a valid JSON value with comprehensive validation. This function provides thorough validation that goes beyond basic type checking by recursively validating nested objects and arrays to ensure the entire structure can be safely serialized to JSON. | | [isJSONArray(value)](#std-isjsonarray) | Checks if the value is a JSON array with recursive validation. This function provides more thorough validation than `Array.isArray()` by recursively checking that all elements in the array are valid JSON values. This is essential for ensuring data can be safely serialized to JSON. | | [isJSONObject(value)](#std-isjsonobject) | Checks if the value is a JSON object. | | [isJSONPrimitive(value)](#std-isjsonprimitive) | Checks if the value is a JSON primitive. | | [isLowerCase(value)](#std-islowercase) | Returns `true` if the value string is composed of only lower cased characters or case neutral characters. | | [isObject(obj)](#std-isobject) | Checks if the given value is an object. | | [isSameDay(dateA, dateB)](#std-issameday) | Checks if two dates represent the same calendar day. This comparison ignores time components and only compares the date parts. Useful for date-based filtering and grouping. | | [isSameHour(dateA, dateB)](#std-issamehour) | Checks if two dates represent the same hour. This comparison ignores date and minute components and only compares the hour parts. Useful for time-based filtering and grouping. | | [isSameMinute(dateA, dateB)](#std-issameminute) | Checks if two dates represent the same minute. This comparison ignores date, hour, and second components and only compares the minute parts. Useful for time-based filtering and grouping. | | [isSameMonth(dateA, dateB)](#std-issamemonth) | Checks if two dates represent the same calendar month. This comparison ignores the day and time components and only compares the month and year parts. Useful for monthly reports and date grouping. | | [isSameSecond(dateA, dateB)](#std-issamesecond) | Checks if two dates represent the same second. This comparison ignores date, hour, and minute components and only compares the second parts. Useful for time-based filtering and grouping. | | [isSameWeek(dateA, dateB)](#std-issameweek) | Checks if two dates represent the same calendar week. This comparison uses the ISO 8601 week definition, where weeks start on Monday. Useful for weekly reports and date grouping. | | [isSameYear(dateA, dateB)](#std-issameyear) | Checks if two dates represent the same calendar year. This comparison ignores the month and day components and only compares the year part. Useful for yearly reports and date grouping. | | [isSpaceAt(s, pos)](#std-isspaceat) | Checks if the character at the specified position in a string is a whitespace character. | | [isUpperCase(value)](#std-isuppercase) | Returns `true` if the value string is composed of only upper cased characters or case neutral characters. | | [isValidDate(date)](#std-isvaliddate) | Checks if a value is a valid Date object. This function checks both that the value is a Date instance and that it represents a valid date (not NaN). | | [isValidUrl(url)](#std-isvalidurl) | Checks if a string is a valid URL. This function validates URLs more safely than using the URL constructor directly, as it doesn't throw exceptions. | | [isWeekend(date)](#std-isweekend) | Checks if a date falls on a weekend (Saturday or Sunday). This is useful for business logic that needs to handle weekends differently, such as scheduling or date calculations. | | [joinArrayWithConjunction(arr, conjunction, separator)](#std-joinarraywithconjunction) | Joins an array of values into a string using a conjunction and separator. | | [joinPaths(paths)](#std-joinpaths) | Joins multiple path segments into a single path. This function properly handles leading and trailing slashes, ensuring a clean path without double slashes or missing separators. | | [jsQuote(s, prefer)](#std-jsquote) | Quotes a string for use in JavaScript code. If the string contains a newline character, it will be quoted using backticks. Otherwise, it will be quoted using single quotes (`'`) or double quotes (`"`) based on the `prefer` parameter. | | [looseEqual(a, b)](#std-looseequal) | Checks if two values are loosely equal. | | [lowerCaseFirst(value)](#std-lowercasefirst) | Convert first letter in `value` to lower case. | | [lpad(s, char, length)](#std-lpad) | Pads a string on the left with a specified character until it reaches a specified length. If the string is already longer than the specified length, it is returned as is. | | [map(iterable, mapper)](#std-map) | Maps an iterable, transforming each element with the mapper function. This function creates a new iterable that yields transformed elements. It's lazy and memory-efficient, processing elements on-demand. | | [mapChars(callback, value)](#std-mapchars) | It maps a string character by character using `callback`. | | [mapEntries(map)](#std-mapentries) | Gets all entries from a Map as an array of key-value pairs. This provides a convenient way to get Map entries as an array for further processing or serialization. | | [mapFilter(map, predicate)](#std-mapfilter) | Creates a new Map containing only entries that satisfy the predicate. This provides a functional approach to filtering Maps, similar to Array.prototype.filter but for Map objects. | | [mapFromEntries(entries)](#std-mapfromentries) | Creates a Map from an array of key-value pairs. This function provides better type inference than the Map constructor when working with typed key-value pairs. | | [mapGroupBy(array, keyFn)](#std-mapgroupby) | Groups an array of items by a key function into a Map. This is more flexible than object-based grouping as it supports any key type, not just strings and symbols. | | [mapIsEmpty(map)](#std-mapisempty) | Checks if a Map is empty. This provides a semantic way to check for empty Maps, making code more readable than checking size === 0. | | [mapKeys(map)](#std-mapkeys) | Gets all keys from a Map as an array. This provides a convenient way to get Map keys as an array for further processing with array methods. | | [mapMap(map, mapper)](#std-mapmap) | Creates a new Map with values transformed by the mapper function. This provides a functional approach to transforming Map values, similar to Array.prototype.map but for Map objects. | | [mapMerge(maps)](#std-mapmerge) | Merges multiple Maps into a single Map. Later Maps take precedence over earlier ones for duplicate keys. This is useful for combining configuration objects or merging data. | | [mapRegExp(subject, pattern, f)](#std-mapregexp) | Map the function `f` on each occurance matched by the pattern. | | [mapToObject(map)](#std-maptoobject) | Converts a Map with string keys to a plain object. This is useful for serialization or when you need to work with APIs that expect plain objects instead of Maps. | | [mapValues(map)](#std-mapvalues) | Gets all values from a Map as an array. This provides a convenient way to get Map values as an array for further processing with array methods. | | [memoize(f)](#std-memoize) | Memoizes the result of a function and returns a new function that caches the result. The cached result is returned if available, otherwise the original function is called and the result is cached for future invocations. | | [mergeObjects(a, b)](#std-mergeobjects) | Merges two objects together. | | [nearEqual(a, b, tollerance)](#std-nearequal) | number numbers can sometime introduce tiny errors even for simple operations. `nearEqual` compares two floats using a tiny tollerance (last optional argument). By default it is defined as `EPSILON`. | | [nearEqualAngles(a, b, turn, tollerance)](#std-nearequalangles) | number numbers can sometime introduce tiny errors even for simple operations. `nearEqualAngles` compares two angles (default is 360deg) using a tiny tollerance (last optional argument). By default the tollerance is defined as `EPSILON`. | | [nearZero(n, tollerance)](#std-nearzero) | `nearZero` finds if the passed number is zero or very close to it. By default `EPSILON` is used as the tollerance value. | | [negate(predicate)](#std-negate) | Creates a negated version of a predicate function. This function returns a new predicate that returns the opposite boolean result of the original predicate. | | [normalizePath(path)](#std-normalizepath) | Normalizes a path by removing redundant segments. This function resolves '..' and '.' segments in paths, similar to path.normalize in Node.js but for web contexts. | | [objectEntries(obj)](#std-objectentries) | Returns an array of entries (key-value pairs) from the given object with proper type inference. This function provides better type safety than `Object.entries()` by returning `[keyof T, T[keyof T]][]` instead of `[string, unknown][]`, preserving both key and value types for type-safe destructuring and iteration. | | [objectFromEntries(entries)](#std-objectfromentries) | Creates an object from an array of entries with proper type inference. This function provides better type safety than `Object.fromEntries()` by accepting properly typed entries and returning a typed object instead of `{ [k: string]: unknown }`. | | [objectKeys(obj)](#std-objectkeys) | Returns an array of keys from the given object with proper type inference. This function provides better type safety than `Object.keys()` by returning `Array` instead of `string[]`, ensuring type correctness when working with the keys in TypeScript. | | [objectValues(obj)](#std-objectvalues) | Returns an array of values from the given object with proper type inference. This function provides better type safety than `Object.values()` by returning `Array` instead of `unknown[]`, preserving the union type of all possible values in the object. | | [omit(obj, keys)](#std-omit) | Creates a new object with all keys except the specified ones from the source object. This function provides type-safe property exclusion, ensuring that only valid keys can be omitted and the result type reflects the remaining properties. | | [once(fn)](#std-once) | Ensures a function is called at most once. Subsequent calls return the result of the first call without executing the function again. | | [parseBoolean(v)](#std-parseboolean) | Returns `true`/`false` if the passed value can be parsed. The following values are considered parsable: - `'true'` / `'false'` - `'0'` / `'1'` - `'on'` / `'off'` | | [parseJSON(value)](#std-parsejson) | Parses a JSON string into a JSON value. | | [parseUrl(url)](#std-parseurl) | Safely parses a URL string into a URL object. This function provides better error handling than the URL constructor by returning null for invalid URLs instead of throwing. | | [partial(fn, prefixArgs)](#std-partial) | Creates a partially applied function. This function allows you to fix some arguments of a function, returning a new function that accepts the remaining arguments. | | [partition(array, predicate)](#std-partition) | Partitions an array into two arrays based on a predicate. This function splits an array into two parts: elements that satisfy the predicate and elements that don't. The order of elements is preserved. | | [pick(obj, keys)](#std-pick) | Creates a new object with only the specified keys from the source object. This function provides type-safe property selection, ensuring that only valid keys can be picked and the result type reflects the selected properties. | | [pipe(value, f1)](#std-pipe) | Pipes a value through a series of functions from left to right. This function applies the given functions to a value in left-to-right order, passing the result of each function to the next. | | [pipe(value, f1, f2)](#std-pipe1) | | | [pipe(value, f1, f2, f3)](#std-pipe2) | | | [pipe(value, f1, f2, f3, f4)](#std-pipe3) | | | [pipe(value, fns)](#std-pipe4) | | | [quote(s, quoteChar)](#std-quote) | Returns a quoted version of the input string. | | [randomBytes(length)](#std-randombytes) | Generates random bytes as a Uint8Array. This function creates an array of random bytes, useful for cryptographic operations or when you need raw random data. | | [randomChoice(array)](#std-randomchoice) | Selects a random element from an array. This function provides a convenient way to pick a random item from an array, handling the index calculation automatically. | | [randomChoices(array, count)](#std-randomchoices) | Selects multiple random elements from an array without replacement. This function picks a specified number of unique elements from an array. The order of selected elements is randomized. | | [randomFloat(min, max, inclusive)](#std-randomfloat) | Generates a random floating-point number between min and max. This function provides a convenient way to generate random floats within a specific range, with optional exclusion of the maximum value. | | [randomHex(length)](#std-randomhex) | Generates a random hexadecimal string of specified length. This function creates a random string using hexadecimal characters (0-9, a-f). Useful for generating tokens, IDs, or other random identifiers. | | [randomInt(min, max)](#std-randomint) | Generates a random integer between min and max (inclusive). This function provides a more convenient API than manually scaling Math.random() and handles the common case of generating integers within a specific range. | | [randomStringSequence(alphabet, length)](#std-randomstringsequence) | Returns a random sampling of the specified length from the seed string. | | [randomStringSequenceBase64(length)](#std-randomstringsequencebase64) | Like `randomSequence`, but automatically uses the base64 sequence as the seed string. | | [randomSubString(value, length)](#std-randomsubstring) | Returns a random substring from the `value` argument. The length of such value is by default `1`. | | [randomUuid()](#std-randomuuid) | Generates a random UUID v4 string. This function creates a UUID (Universally Unique Identifier) using random numbers. While not cryptographically secure, it's suitable for most application needs. | | [range(length, startAt)](#std-range) | Generates an array of consecutive numbers in a specified range. This function provides a more intuitive API than `Array.from({ length }, (_, i) => startAt + i)` for creating numeric sequences. It's commonly needed for iterations, indexing, and mathematical operations. | | [rankArray(array, compare, incrementDuplicates)](#std-rankarray) | Assigns ranks to the elements in the array based on the provided compare function. The ranks are assigned in ascending order, with the lowest value receiving a rank of 0. If there are duplicate values, the rank of the duplicates can be incremented or not based on the `incrementDuplicates` parameter. | | [reduce(iterable, reducer, initial)](#std-reduce) | Reduces an iterable to a single value using the reducer function. This function processes all elements in the iterable, accumulating a result using the reducer function and initial value. | | [removeAllFromArray(arr, item)](#std-removeallfromarray) | Removes all occurrences of an item from an array. | | [removeAllFromArrayByPredicate(arr, predicate)](#std-removeallfromarraybypredicate) | Removes all occurrences in an array that satisfy the given predicate. | | [removeObjectFields(ob, fields)](#std-removeobjectfields) | Removes specified fields from an object and returns a new object without those fields. | | [removeOneFromArray(arr, item)](#std-removeonefromarray) | Removes the first occurrence of an item from an array. | | [removeOneFromArrayByPredicate(arr, predicate)](#std-removeonefromarraybypredicate) | Removes the first occurrence in an array that satisfy the given predicate. | | [removeQueryParam(url, key)](#std-removequeryparam) | Removes a query parameter from a URL. This function removes a specific query parameter from a URL, preserving all other parameters and URL components. | | [reverseString(s)](#std-reversestring) | Returns a new string whose characters are in reverse order. | | [root(base, index)](#std-root) | Computes the nth root (`index`) of `base`. | | [roundTo(f, decimals)](#std-roundto) | Rounds a number to the specified number of decimals. | | [rpad(s, char, length)](#std-rpad) | Pads a string on the right with a specified character until it reaches a specified length. If the string is already longer than the specified length, it is returned as is. | | [sameObjectKeys(a, b)](#std-sameobjectkeys) | Checks if two objects have the same keys. | | [seedRandom(seed)](#std-seedrandom) | Creates a seeded random number generator. This function returns a deterministic random number generator that produces the same sequence of numbers for the same seed. Useful for testing or when reproducible randomness is needed. | | [setDifference(setA, setB)](#std-setdifference) | Creates the difference between two Sets. The difference contains elements that are in the first Set but not in the second. This is equivalent to the mathematical difference operation (A - B). | | [setFilter(set, predicate)](#std-setfilter) | Creates a new Set containing only elements that satisfy the predicate. This provides a functional approach to filtering Sets, similar to Array.prototype.filter but for Set objects. | | [setFromArray(array)](#std-setfromarray) | Creates a Set from an array, removing duplicates. This provides a semantic way to deduplicate arrays using Sets. | | [setIntersection(setA, setB)](#std-setintersection) | Creates the intersection of two Sets. The intersection contains only elements that appear in both Sets. This is equivalent to the mathematical intersection operation (A ∩ B). | | [setIsEmpty(set)](#std-setisempty) | Checks if a Set is empty. This provides a semantic way to check for empty Sets, making code more readable than checking size === 0. | | [setIsSubset(subset, superset)](#std-setissubset) | Checks if one Set is a subset of another. A Set is a subset if all of its elements are contained in the other Set. An empty Set is considered a subset of any Set. | | [setIsSuperset(superset, subset)](#std-setissuperset) | Checks if one Set is a superset of another. A Set is a superset if it contains all elements of the other Set. This is the inverse of the subset relationship. | | [setMap(set, mapper)](#std-setmap) | Creates a new Set with elements transformed by the mapper function. This provides a functional approach to transforming Set elements, similar to Array.prototype.map but for Set objects. | | [setQueryParam(url, key, value)](#std-setqueryparam) | Sets a query parameter in a URL. This function adds or updates a single query parameter in a URL, preserving all other parameters and URL components. | | [setSymmetricDifference(setA, setB)](#std-setsymmetricdifference) | Creates the symmetric difference between two Sets. The symmetric difference contains elements that are in either Set but not in both. This is equivalent to (A - B) ∪ (B - A) or (A ∪ B) - (A ∩ B). | | [setToArray(set)](#std-settoarray) | Converts a Set to an array. This provides a convenient way to convert Sets to arrays for further processing with array methods. | | [setUnion(sets)](#std-setunion) | Creates the union of multiple Sets. The union contains all unique elements that appear in any of the input Sets. This is equivalent to the mathematical union operation (A ∪ B ∪ C...). | | [shuffle(array)](#std-shuffle) | Shuffles an array in place using the Fisher-Yates algorithm. This function randomly reorders the elements of an array, modifying the original array. Each permutation is equally likely. | | [shuffled(array)](#std-shuffled) | Returns a shuffled copy of an array without modifying the original. This function creates a new array with the same elements as the input but in random order, leaving the original array unchanged. | | [skip(iterable, count)](#std-skip) | Skips the first n elements and returns an iterable of the remaining elements. This function creates a new iterable that yields all elements after skipping the specified number of initial elements. | | [sleep(ms, { abortSignal })](#std-sleep) | Sleep for a given number of milliseconds. | | [smartQuote(s, prefer)](#std-smartquote) | Converts a string in a quoted string. | | [some(iterable, predicate)](#std-some) | Tests whether at least one element in an iterable satisfies the predicate. This function returns true if the predicate returns true for any element, or false if no elements satisfy the predicate. It short-circuits on the first true result. | | [splitStringOnce(s, separator)](#std-splitstringonce) | It only splits on the first occurrance of separator. | | [splitStringOnFirst(s, find)](#std-splitstringonfirst) | Splits a string into two parts based on the first occurrence of a specified substring. If the substring is found, returns an array with two elements: the part of the string before the substring and the part after the substring. If the substring is not found, returns an array with a single element: the original string. | | [splitStringOnLast(s, find)](#std-splitstringonlast) | Splits a string into two parts at the last occurrence of a specified substring. If the substring is found, the function returns an array with two elements: the part of the string before the substring and the part after the substring. If the substring is not found, the function returns an array with a single element, which is the original string. | | [startOfDay(date)](#std-startofday) | Returns a new Date representing the start of the day (00:00:00.000). This is useful for date comparisons and range queries where you need to normalize dates to the beginning of the day. | | [startOfWeek(date)](#std-startofweek) | Returns a new Date representing the start of the week (Monday 00:00:00.000). This follows the ISO 8601 standard where Monday is the first day of the week. Useful for weekly reports and date grouping. | | [strictEqual(a, b)](#std-strictequal) | Checks if two values are strictly equal. | | [stringEndsWithAny(s, values)](#std-stringendswithany) | Returns `true` if `s` ends with any of the values in `values`. | | [stringHasContent(value)](#std-stringhascontent) | Returns `true` if `value` is not `null` and contains at least one character. | | [stringHashCode(value, seed)](#std-stringhashcode) | Calculates the hash code for a given string. | | [stringsDifferAtIndex(a, b)](#std-stringsdifferatindex) | Compares strings `a` and `b` and returns the position where they differ. If the strings are equal, it returns `-1`. | | [stringStartsWithAny(s, values)](#std-stringstartswithany) | Returns `true` if `s` starts with any of the values in `values`. | | [stringToCharcodes(s)](#std-stringtocharcodes) | It transforms a string into an `Array` of char codes in integer format. | | [substringAfter(value, searchFor)](#std-substringafter) | `substringAfter` searches for the first occurrance of `searchFor` and returns the text after that. If `searchFor` is not found, an empty string is returned. | | [substringAfterLast(value, searchFor)](#std-substringafterlast) | `substringAfterLast` searches for the last occurrance of `searchFor` and returns the text after that. If `searchFor` is not found, an empty string is returned. | | [substringBefore(value, searchFor)](#std-substringbefore) | `substringBefore` searches for the first occurrance of `searchFor` and returns the text before that. If `searchFor` is not found, an empty string is returned. | | [substringBeforeLast(value, searchFor)](#std-substringbeforelast) | `substringBeforeLast` searches for the last occurrance of `searchFor` and returns the text before that. If `searchFor` is not found, an empty string is returned. | | [surroundString(s, left, right)](#std-surroundstring) | Surrounds a string with the contents of `left` and `right`. If `right` is omitted, `left` will be used on both sides | | [take(iterable, count)](#std-take) | Takes the first n elements from an iterable. This function creates a new array containing the first n elements from the iterable. It's useful for limiting results or sampling data. | | [textContainsCaseInsensitive(s, test)](#std-textcontainscaseinsensitive) | `textContainsCaseInsensitive` returns `true` if `s` contains one or more occurrences of `test` regardless of the text case. | | [textEndsWithAnyCaseInsensitive(s, values)](#std-textendswithanycaseinsensitive) | Compares a string `s` with many `values` and see if one of them matches its end ignoring their case. | | [textEndsWithCaseInsensitive(s, end)](#std-textendswithcaseinsensitive) | Checks if a string ends with another string in a case-insensitive manner. | | [textStartsWithAnyCaseInsensitive(s, values)](#std-textstartswithanycaseinsensitive) | Compares a string `s` with many `values` and see if one of them matches its beginning ignoring their case. | | [textStartsWithCaseInsensitive(s, start)](#std-textstartswithcaseinsensitive) | Checks if a string starts with another string in a case-insensitive manner. | | [textToLines(s)](#std-texttolines) | Returns an array of `string` split by line breaks. | | [throttle(delay, callback, options)](#std-throttle) | Creates a throttled version of a function that limits how often the function can be called. | | [toArray(iterable)](#std-toarray) | Converts an iterable to an array. This function creates a new array containing all elements from the iterable. It's equivalent to \[...iterable\] but more explicit in intent. | | [toHex(num, length)](#std-tohex) | Converts a number to its hexadecimal representation. | | [trimChars(value, charlist)](#std-trimchars) | `trimChars` removes from the beginning and the end of the string any character that is present in `charlist`. | | [trimCharsLeft(value, charlist)](#std-trimcharsleft) | `trimCharsLeft` removes from the beginning of the string any character that is present in `charlist`. | | [trimCharsRight(value, charlist)](#std-trimcharsright) | `trimCharsRight` removes from the end of the string any character that is present in `charlist`. | | [trimStringSlice(value, index, length)](#std-trimstringslice) | Removes a slice from `index` to `index + length` from `value`. | | [underscore(s)](#std-underscore) | `underscore` finds UpperCase characters and turns them into LowerCase and prepends them with a whtiespace. Sequences of more than one UpperCase character are left untouched. | | [uniqueByPrimitive(values, predicate)](#std-uniquebyprimitive) | Removes duplicate objects from an array based on a key extraction function. This function removes duplicates from arrays of objects by extracting a primitive key from each object and using that key to determine uniqueness. When duplicates are found, the first occurrence is kept. | | [upperCaseFirst(value)](#std-uppercasefirst) | Convert first letter in `value` to upper case. | | [widestAngleDifference(a, b, turn)](#std-widestangledifference) | Calculates the minimum difference between two angles in degrees. Note: Despite the name "widest", this function actually calculates the shortest angle difference, identical to `angleDifference`. The name is misleading for historical reasons. | | [wrap(v, min, max)](#std-wrap) | Passed two boundaries values (`min`, `max`), `wrap` ensures that the passed value `v` will be included in the boundaries. If the value exceeds `max`, the value is reduced by `min` repeatedely until it falls within the range. Similar and inverted treatment is performed if the value is below `min`. | | [wrapCircular(v, max)](#std-wrapcircular) | Similar to `wrap`, it works for numbers between 0 and `max`. | | [wrapColumns(s, columns, indent, newline)](#std-wrapcolumns) | `wrapColumns` splits a long string into lines that are at most `columns` long. Individual words whose length exceeds `columns` are not split. | | [wrapLine(s, columns, indent, newline)](#std-wrapline) | Wraps a string into multiple lines based on the specified number of columns, indentation, and newline character. | | [xorBoolean(a, b)](#std-xorboolean) | Returns `true` when arguments are different. | ## std: Interfaces | Interface | Description | | --- | --- | | [CancelOptions](#std-canceloptions) | Options for cancelling a throttled function. | | [JSONObject](#std-jsonobject) | Represents a JSON object. | | [ThrottledFunction](#std-throttledfunction) | Represents a throttled function with a cancel method. | | [ThrottleOptions](#std-throttleoptions) | Configuration options for throttle function. | ## std: Variables | Variable | Description | | --- | --- | | [AsyncResult](#std-asyncresult) | A set of utility functions for working with `AsyncResult`. | | [EPSILON](#std-epsilon) | Constant value employed to see if two `number` values are very close. | | [Result](#std-result) | Utility functions for working with `Result` types. | | [Validation](#std-validation) | Utility functions for working with `Validation` types. | ## std: Type Aliases | Type Alias | Description | | --- | --- | | [ArgsAfter](#std-argsafter) | | | [ArgsSubset](#std-argssubset) | | | [ArrayDiffOperations](#std-arraydiffoperations) | Represents the different operations that can be performed on an array. | | [AsyncFailure](#std-asyncfailure) | Represents a failure result. | | [AsyncResult](#std-asyncresult) | Represents the result of an asynchronous operation that can be in one of the following states: - `NotAsked`: The operation has not been requested yet. - `Loading`: The operation is currently in progress. - `Success`: The operation has completed successfully and contains a value of type `V`. - `Failure`: The operation has completed with an error and contains an error of type `E`. | | [AsyncSuccess](#std-asyncsuccess) | Represents a successful result. | | [Compare](#std-compare) | Represents a function that compares two values of type T and returns a number. The returned number indicates the relative order of the two values: - A negative number if `a` is less than `b`. - Zero if `a` is equal to `b`. - A positive number if `a` is greater than `b`. | | [DebounceOptions](#std-debounceoptions) | Options for debouncing a function. | | [Drop](#std-drop) | | | [Failure](#std-failure) | Represents a failure result. | | [FilterTuple](#std-filtertuple) | Filters out elements from a tuple that are equal to the specified type. | | [FirstArgument](#std-firstargument) | Extracts the first argument type from a function type. | | [Fun0](#std-fun0) | Represents a function that takes no arguments and returns a value of type `R`. | | [Fun1](#std-fun1) | Represents a function that takes one argument of type `A` and returns a value of type `R`. | | [Fun2](#std-fun2) | Represents a function that takes two arguments of types `A` and `B`, and returns a value of type `R`. | | [Fun3](#std-fun3) | Represents a function that takes three arguments of types A, B, and C, and returns a value of type R. | | [Fun4](#std-fun4) | Represents a function that takes four arguments of types A, B, C, and D, and returns a value of type R. | | [Fun5](#std-fun5) | Represents a function that takes five arguments of types A, B, C, D, and E, and returns a value of type R. | | [Fun6](#std-fun6) | Represents a function that takes six arguments of types A, B, C, D, E, F and returns a value of type R. | | [Id](#std-id) | Represents an identity type that preserves the properties of the original type. | | [IndexKey](#std-indexkey) | Represents a key type that can be used to index any object. | | [Invalid](#std-invalid) | Represents an invalid value with an associated error. | | [IsUnion](#std-isunion) | | | [JSONArray](#std-jsonarray) | Represents an array of JSON values. | | [JSONPrimitive](#std-jsonprimitive) | Represents a JSON primitive value. It can be a string, boolean, number, or Nothing (null or undefined). | | [JSONValue](#std-jsonvalue) | Represents a JSON value, which can be a primitive, an object, or an array. | | [Loading](#std-loading) | Represents a loading state in an asynchronous result. | | [Maybe](#std-maybe) | Represents a type that can either hold a value of type T or be undefined. | | [Merge](#std-merge) | Represents the type resulting from merging two types `A` and `B`. The resulting type is the intersection of `A` and `B`. | | [NonLoading](#std-nonloading) | Represents a state in an asynchronous result that is not loading. | | [NotAsked](#std-notasked) | Represents the state when a result has not been requested yet. | | [Nothing](#std-nothing) | Represents a value that can be either `undefined` or `null`. | | [PartialBy](#std-partialby) | Creates a new type by making the specified key `K` of `T` optional. | | [Primitive](#std-primitive) | Represents a primitive value that can be of type string, boolean, number, null, or undefined. | | [PromiseResult](#std-promiseresult) | Represents a promise that resolves to a `Result` type. | | [PromiseValidation](#std-promisevalidation) | Represents a promise that resolves to a `Validation` object. | | [RequiredBy](#std-requiredby) | Creates a new type by making the specified key `K` of `T` required. | | [Result](#std-result) | Represents a result that can either be a success or a failure. | | [Reverse](#std-reverse) | | | [Settled](#std-settled) | Represents a settled state in an asynchronous result. | | [SplitLiteral](#std-splitliteral) | Splits a string literal type `T` by a specified delimiter `SplitBy`. Returns a tuple containing the split parts of the string. | | [SplitLiteralToUnion](#std-splitliteraltounion) | Converts a string literal type `T` into a union type by splitting it using the specified delimiter `SplitBy`. | | [Success](#std-success) | Represents a successful result. | | [TupleToUnion](#std-tupletounion) | Converts a tuple type to a union type. | | [Valid](#std-valid) | Represents a valid result. | | [Validation](#std-validation) | Represents a type that can either be `Valid` or `Invalid`. | --- ## std.memoize: memoize() function Memoizes the result of a function and returns a new function that caches the result. The cached result is returned if available, otherwise the original function is called and the result is cached for future invocations. **Signature:**```typescript memoize: (f: () => NonNullable) => (() => NonNullable) ```## std.memoize: Parameters | Parameter | Type | Description | | --- | --- | --- | | f | () => NonNullable<T> | The function to memoize. | **Returns:** (() => NonNullable<T>) A new function that caches the result of the original function. --- ## std.merge: Merge type Represents the type resulting from merging two types `A` and `B`. The resulting type is the intersection of `A` and `B`. **Signature:**```typescript export type Merge = Id; ``` **References:** [Id](#std-id) --- ## std.mergeobjects: mergeObjects() function Merges two objects together. **Signature:**```typescript mergeObjects: , B extends Record>(a: A, b: B) => Merge ```## std.mergeobjects: Parameters | Parameter | Type | Description | | --- | --- | --- | | a | A | The first object to merge. | | b | B | The second object to merge. | **Returns:** [Merge](#std-merge)<A, B> The merged object. --- ## std.nearequal: nearEqual() function number numbers can sometime introduce tiny errors even for simple operations. `nearEqual` compares two floats using a tiny tollerance (last optional argument). By default it is defined as `EPSILON`. **Signature:**```typescript nearEqual: (a: number, b: number, tollerance?: number) => boolean ```## std.nearequal: Parameters | Parameter | Type | Description | | --- | --- | --- | | a | number | The first number to compare. | | b | number | The second number to compare. | | tollerance | number | _(Optional)_ The tollerance value. Default is `EPSILON`. | **Returns:** boolean `true` if the numbers are very close, `false` otherwise. ## std.nearequal: Example```ts nearEqual(5, 5.000000000000001) // returns true nearEqual(5, 5.000000000001) // returns false nearEqual(5, 5.000000000001, 1e-9) // returns true ``` --- ## std.nearequalangles: nearEqualAngles() function number numbers can sometime introduce tiny errors even for simple operations. `nearEqualAngles` compares two angles (default is 360deg) using a tiny tollerance (last optional argument). By default the tollerance is defined as `EPSILON`. **Signature:**```typescript nearEqualAngles: (a: number, b: number, turn?: number, tollerance?: number) => boolean ```## std.nearequalangles: Parameters | Parameter | Type | Description | | --- | --- | --- | | a | number | The first angle in degrees. | | b | number | The second angle in degrees. | | turn | number | _(Optional)_ The total number of degrees in a full turn. Default is 360.0. | | tollerance | number | _(Optional)_ The tollerance value. Default is `EPSILON`. | **Returns:** boolean `true` if the angles are very close, `false` otherwise. ## std.nearequalangles: Example```ts nearEqualAngles(0, 360) // returns true nearEqualAngles(0, 361) // returns false nearEqualAngles(0, 360.000000000001) // returns true nearEqualAngles(0, 361, 360, 1) // returns true ``` --- ## std.nearzero: nearZero() function `nearZero` finds if the passed number is zero or very close to it. By default `EPSILON` is used as the tollerance value. **Signature:**```typescript nearZero: (n: number, tollerance?: number) => boolean ```## std.nearzero: Parameters | Parameter | Type | Description | | --- | --- | --- | | n | number | The number to check. | | tollerance | number | _(Optional)_ The tollerance value. Default is `EPSILON`. | **Returns:** boolean `true` if the number is zero or very close to it, `false` otherwise. ## std.nearzero: Example```ts nearZero(0.000000000000001) // returns true nearZero(0.000000001) // returns false nearZero(0.000000001, 1e-9) // returns true ``` --- ## std.negate: negate() function Creates a negated version of a predicate function. This function returns a new predicate that returns the opposite boolean result of the original predicate. **Signature:**```typescript negate: (predicate: (...args: Args) => boolean) => ((...args: Args) => boolean) ```## std.negate: Parameters | Parameter | Type | Description | | --- | --- | --- | | predicate | (...args: Args) => boolean | The predicate function to negate | **Returns:** ((...args: Args) => boolean) A new predicate that returns the opposite result ## std.negate: Example```typescript const isEven = (n: number) => n % 2 === 0 const isOdd = negate(isEven) isEven(4) // true isOdd(4) // false isOdd(3) // true ``` --- ## std.nonloading: NonLoading type Represents a state in an asynchronous result that is not loading. **Signature:**```typescript export type NonLoading = NotAsked | Settled; ``` **References:** [NotAsked](#std-notasked), [Settled](#std-settled) --- ## std.normalizepath: normalizePath() function Normalizes a path by removing redundant segments. This function resolves '..' and '.' segments in paths, similar to path.normalize in Node.js but for web contexts. **Signature:**```typescript normalizePath: (path: string) => string ```## std.normalizepath: Parameters | Parameter | Type | Description | | --- | --- | --- | | path | string | The path to normalize | **Returns:** string The normalized path ## std.normalizepath: Example```typescript const path = normalizePath('/api/../users/./123/../456') // Result: '/users/456' const relative = normalizePath('../../parent/child') // Result: '../../parent/child' ``` --- ## std.notasked: NotAsked type Represents the state when a result has not been requested yet. **Signature:**```typescript export type NotAsked = { readonly type: 'NotAsked'; }; ``` --- ## std.nothing: Nothing type Represents a value that can be either `undefined` or `null`. **Signature:**```typescript export type Nothing = undefined | null; ``` --- ## std.objectentries: objectEntries() function Returns an array of entries (key-value pairs) from the given object with proper type inference. This function provides better type safety than `Object.entries()` by returning `[keyof T, T[keyof T]][]` instead of `[string, unknown][]`, preserving both key and value types for type-safe destructuring and iteration. **Signature:**```typescript objectEntries: (obj: T) => [keyof T, T[keyof T]][] ```## std.objectentries: Parameters | Parameter | Type | Description | | --- | --- | --- | | obj | T | The object from which to extract entries. | **Returns:** \[keyof T, T\[keyof T\]\]\[\] An array of tuples with proper typing, where each tuple contains a key and its corresponding value. ## std.objectentries: Example```typescript const user = { id: 1, name: 'Alice', active: true } const entries = objectEntries(user) // Type: Array<['id' | 'name' | 'active', number | string | boolean]> // Result: [['id', 1], ['name', 'Alice'], ['active', true]] // Type-safe destructuring entries.forEach(([key, value]) => { // TypeScript knows key is 'id' | 'name' | 'active' // TypeScript knows value is number | string | boolean console.log(`${key}: ${value}`) }) ``` --- ## std.objectfromentries: objectFromEntries() function Creates an object from an array of entries with proper type inference. This function provides better type safety than `Object.fromEntries()` by accepting properly typed entries and returning a typed object instead of `{ [k: string]: unknown }`. **Signature:**```typescript objectFromEntries: (entries: [keyof T, T[keyof T]][]) => T ```## std.objectfromentries: Parameters | Parameter | Type | Description | | --- | --- | --- | | entries | \[keyof T, T\[keyof T\]\]\[\] | The array of entries to create an object from. | **Returns:** T The created object with proper typing. ## std.objectfromentries: Example```typescript const entries: [string, number][] = [['a', 1], ['b', 2], ['c', 3]] const obj = objectFromEntries(entries) // Type: { [x: string]: number } // Result: { a: 1, b: 2, c: 3 } // Works with union types const mixedEntries: Array<['id' | 'name', number | string]> = [ ['id', 123], ['name', 'Alice'] ] const user = objectFromEntries(mixedEntries) // Type: { [x: string]: number | string } ``` --- ## std.objectkeys: objectKeys() function Returns an array of keys from the given object with proper type inference. This function provides better type safety than `Object.keys()` by returning `Array` instead of `string[]`, ensuring type correctness when working with the keys in TypeScript. **Signature:** ```typescript objectKeys: (obj: T) => Array ```## std.objectkeys: Parameters | Parameter | Type | Description | | --- | --- | --- | | obj | T | The object from which to extract keys. | **Returns:** Array<keyof T> An array of keys from the object with proper typing. ## std.objectkeys: Example```typescript const user = { id: 1, name: 'Alice', active: true } const keys = objectKeys(user) // Type: Array<'id' | 'name' | 'active'> // Result: ['id', 'name', 'active'] // Type-safe iteration keys.forEach(key => { console.log(user[key]) // TypeScript knows this is valid }) ``` --- ## std.objectvalues: objectValues() function Returns an array of values from the given object with proper type inference. This function provides better type safety than `Object.values()` by returning `Array` instead of `unknown[]`, preserving the union type of all possible values in the object. **Signature:** ```typescript objectValues: (obj: T) => Array ```## std.objectvalues: Parameters | Parameter | Type | Description | | --- | --- | --- | | obj | T | The object from which to extract values. | **Returns:** Array<T\[keyof T\]> An array of values from the object with proper typing. ## std.objectvalues: Example```typescript const user = { id: 1, name: 'Alice', active: true } const values = objectValues(user) // Type: Array // Result: [1, 'Alice', true] // Type-safe processing values.forEach(value => { // TypeScript knows value can be number | string | boolean if (typeof value === 'string') { console.log(value.toUpperCase()) } }) ``` --- ## std.omit: omit() function Creates a new object with all keys except the specified ones from the source object. This function provides type-safe property exclusion, ensuring that only valid keys can be omitted and the result type reflects the remaining properties. **Signature:**```typescript omit: (obj: T, keys: readonly K[]) => Omit ```## std.omit: Parameters | Parameter | Type | Description | | --- | --- | --- | | obj | T | The source object | | keys | readonly K\[\] | Array of keys to omit | **Returns:** Omit<T, K> A new object without the specified keys ## std.omit: Example```typescript const user = { id: 1, name: 'Alice', email: 'alice@example.com', password: 'secret' } const publicUser = omit(user, ['password']) // Result: { id: 1, name: 'Alice', email: 'alice@example.com' } // Type: Omit ``` --- ## std.once: once() function Ensures a function is called at most once. Subsequent calls return the result of the first call without executing the function again. **Signature:**```typescript once: (fn: (...args: Args) => Return) => ((...args: Args) => Return) ```## std.once: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn | (...args: Args) => Return | The function to wrap | **Returns:** ((...args: Args) => Return) A new function that can only be called once ## std.once: Example```typescript let counter = 0 const increment = once(() => ++counter) increment() // 1 increment() // 1 (same result, function not called again) increment() // 1 ``` --- ## std.parseboolean: parseBoolean() function Returns `true`/`false` if the passed value can be parsed. The following values are considered parsable: - `'true'` / `'false'` - `'0'` / `'1'` - `'on'` / `'off'` **Signature:**```typescript parseBoolean: (v: string) => boolean ```## std.parseboolean: Parameters | Parameter | Type | Description | | --- | --- | --- | | v | string | The value to parse. | **Returns:** boolean The parsed boolean value. --- ## std.parsejson: parseJSON() function Parses a JSON string into a JSON value. **Signature:**```typescript parseJSON: (value: string) => Result ```## std.parsejson: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The JSON string to parse. | **Returns:** [Result](#std-result)<[JSONValue](#std-jsonvalue), Error> A result containing the parsed JSON value or an error if parsing fails. --- ## std.parseurl: parseUrl() function Safely parses a URL string into a URL object. This function provides better error handling than the URL constructor by returning null for invalid URLs instead of throwing. **Signature:**```typescript parseUrl: (url: string) => URL | null ```## std.parseurl: Parameters | Parameter | Type | Description | | --- | --- | --- | | url | string | The URL string to parse | **Returns:** URL \| null A URL object if valid, null otherwise ## std.parseurl: Example```typescript const url = parseUrl('https://example.com/path?param=value') // Result: URL object const invalid = parseUrl('not-a-url') // Result: null ``` --- ## std.partial: partial() function Creates a partially applied function. This function allows you to fix some arguments of a function, returning a new function that accepts the remaining arguments. **Signature:**```typescript export declare function partial(fn: (...args: [...PrefixArgs, ...RestArgs]) => Return, ...prefixArgs: PrefixArgs): (...rest: RestArgs) => Return; ```## std.partial: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn | (...args: \[...PrefixArgs, ...RestArgs\]) => Return | The function to partially apply | | prefixArgs | PrefixArgs | | **Returns:** (...rest: RestArgs) => Return A new function that accepts the remaining arguments ## std.partial: Example```typescript const add = (a: number, b: number, c: number) => a + b + c const add5And10 = partial(add, 5, 10) const result = add5And10(3) // 5 + 10 + 3 = 18 ``` --- ## std.partialby: PartialBy type Creates a new type by making the specified key `K` of `T` optional. **Signature:**```typescript export type PartialBy = Merge, Partial>>; ``` **References:** [Merge](#std-merge) --- ## std.partition: partition() function Partitions an array into two arrays based on a predicate. This function splits an array into two parts: elements that satisfy the predicate and elements that don't. The order of elements is preserved. **Signature:**```typescript partition: (array: readonly T[], predicate: (item: T) => boolean) => [T[], T[]] ```## std.partition: Parameters | Parameter | Type | Description | | --- | --- | --- | | array | readonly T\[\] | The array to partition | | predicate | (item: T) => boolean | Function that tests each element | **Returns:** \[T\[\], T\[\]\] A tuple containing \[matching elements, non-matching elements\] ## std.partition: Example```typescript const numbers = [1, 2, 3, 4, 5, 6] const [evens, odds] = partition(numbers, n => n % 2 === 0) // evens: [2, 4, 6] // odds: [1, 3, 5] ``` --- ## std.pick: pick() function Creates a new object with only the specified keys from the source object. This function provides type-safe property selection, ensuring that only valid keys can be picked and the result type reflects the selected properties. **Signature:**```typescript pick: (obj: T, keys: readonly K[]) => Pick ```## std.pick: Parameters | Parameter | Type | Description | | --- | --- | --- | | obj | T | The source object | | keys | readonly K\[\] | Array of keys to pick | **Returns:** Pick<T, K> A new object containing only the specified keys ## std.pick: Example```typescript const user = { id: 1, name: 'Alice', email: 'alice@example.com', password: 'secret' } const publicUser = pick(user, ['id', 'name', 'email']) // Result: { id: 1, name: 'Alice', email: 'alice@example.com' } // Type: Pick ``` --- ## std.pipe_1: pipe() function **Signature:**```typescript export declare function pipe(value: A, f1: (a: A) => B, f2: (b: B) => C): C; ```## std.pipe_1: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | A | | | f1 | (a: A) => B | | | f2 | (b: B) => C | | **Returns:** C --- ## std.pipe_2: pipe() function **Signature:**```typescript export declare function pipe(value: A, f1: (a: A) => B, f2: (b: B) => C, f3: (c: C) => D): D; ```## std.pipe_2: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | A | | | f1 | (a: A) => B | | | f2 | (b: B) => C | | | f3 | (c: C) => D | | **Returns:** D --- ## std.pipe_3: pipe() function **Signature:**```typescript export declare function pipe(value: A, f1: (a: A) => B, f2: (b: B) => C, f3: (c: C) => D, f4: (d: D) => E): E; ```## std.pipe_3: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | A | | | f1 | (a: A) => B | | | f2 | (b: B) => C | | | f3 | (c: C) => D | | | f4 | (d: D) => E | | **Returns:** E --- ## std.pipe_4: pipe() function **Signature:**```typescript export declare function pipe(value: T, ...fns: Array<(arg: unknown) => unknown>): unknown; ```## std.pipe_4: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | T | | | fns | Array<(arg: unknown) => unknown> | | **Returns:** unknown --- ## std.pipe: pipe() function Pipes a value through a series of functions from left to right. This function applies the given functions to a value in left-to-right order, passing the result of each function to the next. **Signature:**```typescript export declare function pipe(value: A, f1: (a: A) => B): B; ```## std.pipe: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | A | The initial value | | f1 | (a: A) => B | | **Returns:** B The final result after applying all functions ## std.pipe: Example```typescript const add5 = (x: number) => x + 5 const double = (x: number) => x * 2 const square = (x: number) => x * x const result = pipe(3, add5, double, square) // square(double(add5(3))) = square(double(8)) = square(16) = 256 ``` --- ## std.primitive: Primitive type Represents a primitive value that can be of type string, boolean, number, null, or undefined. **Signature:**```typescript export type Primitive = string | boolean | number | null | undefined; ``` --- ## std.promiseresult: PromiseResult type Represents a promise that resolves to a `Result` type. **Signature:**```typescript export type PromiseResult = PromiseLike>; ``` **References:** [Result](#std-result) --- ## std.promisevalidation: PromiseValidation type Represents a promise that resolves to a `Validation` object. **Signature:**```typescript export type PromiseValidation = PromiseLike>; ``` **References:** [Validation](#std-validation) --- ## std.quote: quote() function Returns a quoted version of the input string. **Signature:**```typescript quote: (s: string, quoteChar?: string) => string ```## std.quote: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The input string to be quoted. | | quoteChar | string | _(Optional)_ The character used for quoting. Defaults to single quote ('). | **Returns:** string The quoted string. --- ## std.randombytes: randomBytes() function Generates random bytes as a Uint8Array. This function creates an array of random bytes, useful for cryptographic operations or when you need raw random data. **Signature:**```typescript randomBytes: (length: number) => Uint8Array ```## std.randombytes: Parameters | Parameter | Type | Description | | --- | --- | --- | | length | number | The number of bytes to generate | **Returns:** Uint8Array A Uint8Array containing random bytes ## std.randombytes: Example```typescript const key = randomBytes(32) // 32 random bytes const salt = randomBytes(16) // 16 random bytes for salt ``` --- ## std.randomchoice: randomChoice() function Selects a random element from an array. This function provides a convenient way to pick a random item from an array, handling the index calculation automatically. **Signature:**```typescript randomChoice: (array: readonly T[]) => T ```## std.randomchoice: Parameters | Parameter | Type | Description | | --- | --- | --- | | array | readonly T\[\] | The array to choose from | **Returns:** T A random element from the array ## std.randomchoice: Exceptions Error if the array is empty ## std.randomchoice: Example```typescript const colors = ['red', 'green', 'blue', 'yellow'] const randomColor = randomChoice(colors) // One of the colors const users = [{ name: 'Alice' }, { name: 'Bob' }] const randomUser = randomChoice(users) // One of the users ``` --- ## std.randomchoices: randomChoices() function Selects multiple random elements from an array without replacement. This function picks a specified number of unique elements from an array. The order of selected elements is randomized. **Signature:**```typescript randomChoices: (array: readonly T[], count: number) => T[] ```## std.randomchoices: Parameters | Parameter | Type | Description | | --- | --- | --- | | array | readonly T\[\] | The array to choose from | | count | number | The number of elements to select | **Returns:** T\[\] An array of randomly selected elements ## std.randomchoices: Exceptions Error if count is greater than array length or if array is empty ## std.randomchoices: Example```typescript const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] const sample = randomChoices(numbers, 3) // e.g., [7, 2, 9] const team = randomChoices(allPlayers, 5) // Pick 5 random players ``` --- ## std.randomfloat: randomFloat() function Generates a random floating-point number between min and max. This function provides a convenient way to generate random floats within a specific range, with optional exclusion of the maximum value. **Signature:**```typescript randomFloat: (min: number, max: number, inclusive?: boolean) => number ```## std.randomfloat: Parameters | Parameter | Type | Description | | --- | --- | --- | | min | number | The minimum value (inclusive) | | max | number | The maximum value (exclusive by default) | | inclusive | boolean | _(Optional)_ Whether to include the maximum value (default: false) | **Returns:** number A random float between min and max ## std.randomfloat: Example```typescript const temperature = randomFloat(-10.0, 35.0) // Random temperature const percentage = randomFloat(0, 100) // Random percentage ``` --- ## std.randomhex: randomHex() function Generates a random hexadecimal string of specified length. This function creates a random string using hexadecimal characters (0-9, a-f). Useful for generating tokens, IDs, or other random identifiers. **Signature:**```typescript randomHex: (length: number) => string ```## std.randomhex: Parameters | Parameter | Type | Description | | --- | --- | --- | | length | number | The length of the hex string to generate | **Returns:** string A random hexadecimal string ## std.randomhex: Example```typescript const token = randomHex(16) // e.g., "a1b2c3d4e5f67890" const color = '#' + randomHex(6) // Random hex color ``` --- ## std.randomint: randomInt() function Generates a random integer between min and max (inclusive). This function provides a more convenient API than manually scaling Math.random() and handles the common case of generating integers within a specific range. **Signature:**```typescript randomInt: (min: number, max: number) => number ```## std.randomint: Parameters | Parameter | Type | Description | | --- | --- | --- | | min | number | The minimum value (inclusive) | | max | number | The maximum value (inclusive) | **Returns:** number A random integer between min and max ## std.randomint: Example```typescript const dice = randomInt(1, 6) // 1, 2, 3, 4, 5, or 6 const index = randomInt(0, array.length - 1) // Valid array index ``` --- ## std.randomstringsequence: randomStringSequence() function Returns a random sampling of the specified length from the seed string. **Signature:**```typescript randomStringSequence: (alphabet: string, length: number) => string ```## std.randomstringsequence: Parameters | Parameter | Type | Description | | --- | --- | --- | | alphabet | string | The seed string to sample from. | | length | number | The length of the random string to generate. | **Returns:** string The random string. --- ## std.randomstringsequencebase64: randomStringSequenceBase64() function Like `randomSequence`, but automatically uses the base64 sequence as the seed string. **Signature:**```typescript randomStringSequenceBase64: (length: number) => string ```## std.randomstringsequencebase64: Parameters | Parameter | Type | Description | | --- | --- | --- | | length | number | The length of the random string to generate. | **Returns:** string The random string. --- ## std.randomsubstring: randomSubString() function Returns a random substring from the `value` argument. The length of such value is by default `1`. **Signature:**```typescript randomSubString: (value: string, length?: number) => string ```## std.randomsubstring: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to extract the random substring from. | | length | number | _(Optional)_ The length of the random substring to extract. | **Returns:** string The random substring. --- ## std.randomuuid: randomUuid() function Generates a random UUID v4 string. This function creates a UUID (Universally Unique Identifier) using random numbers. While not cryptographically secure, it's suitable for most application needs. **Signature:**```typescript randomUuid: () => string ``` **Returns:** string A random UUID v4 string ## std.randomuuid: Example ```typescript const id = randomUuid() // e.g., "f47ac10b-58cc-4372-a567-0e02b2c3d479" const sessionId = randomUuid() ``` --- ## std.range: range() function Generates an array of consecutive numbers in a specified range. This function provides a more intuitive API than `Array.from({ length }, (_, i) => startAt + i)` for creating numeric sequences. It's commonly needed for iterations, indexing, and mathematical operations. **Signature:**```typescript range: (length: number, startAt?: number) => number[] ```## std.range: Parameters | Parameter | Type | Description | | --- | --- | --- | | length | number | The length of the array to generate. | | startAt | number | _(Optional)_ The starting value of the range. Default is 0. | **Returns:** number\[\] An array of numbers in the specified range. ## std.range: Example```typescript // Create a range from 0 to 4 const zeroToFour = range(5) // Result: [0, 1, 2, 3, 4] // Create a range from 10 to 14 const tenToFourteen = range(5, 10) // Result: [10, 11, 12, 13, 14] // Use for creating test data const testIds = range(100, 1000) // Result: [1000, 1001, 1002, ..., 1099] ``` --- ## std.rankarray: rankArray() function Assigns ranks to the elements in the array based on the provided compare function. The ranks are assigned in ascending order, with the lowest value receiving a rank of 0. If there are duplicate values, the rank of the duplicates can be incremented or not based on the `incrementDuplicates` parameter. **Signature:**```typescript rankArray: (array: T[], compare: (a: T, b: T) => number, incrementDuplicates?: boolean) => number[] ```## std.rankarray: Parameters | Parameter | Type | Description | | --- | --- | --- | | array | T\[\] | The array to rank. | | compare | (a: T, b: T) => number | The compare function used to determine the order of elements. | | incrementDuplicates | boolean | _(Optional)_ Whether to increment the rank of duplicate values. | **Returns:** number\[\] An array of ranks corresponding to the elements in the input array. --- ## std.reduce: reduce() function Reduces an iterable to a single value using the reducer function. This function processes all elements in the iterable, accumulating a result using the reducer function and initial value. **Signature:**```typescript reduce: (iterable: Iterable, reducer: (acc: U, item: T) => U, initial: U) => U ```## std.reduce: Parameters | Parameter | Type | Description | | --- | --- | --- | | iterable | Iterable<T> | The iterable to reduce | | reducer | (acc: U, item: T) => U | Function that combines accumulator with each element | | initial | U | Initial value for the accumulator | **Returns:** U The final accumulated value ## std.reduce: Example```typescript const numbers = [1, 2, 3, 4, 5] const sum = reduce(numbers, (acc, n) => acc + n, 0) // 15 const words = ['hello', 'world', 'foo', 'bar'] const longest = reduce(words, (acc, word) => word.length > acc.length ? word : acc, '') ``` --- ## std.removeallfromarray: removeAllFromArray() function Removes all occurrences of an item from an array. **Signature:**```typescript removeAllFromArray: (arr: A[], item: A) => boolean ```## std.removeallfromarray: Parameters | Parameter | Type | Description | | --- | --- | --- | | arr | A\[\] | The array from which to remove the item. | | item | A | The item to remove from the array. | **Returns:** boolean `true` if at least one occurrence was found and removed, `false` otherwise. --- ## std.removeallfromarraybypredicate: removeAllFromArrayByPredicate() function Removes all occurrences in an array that satisfy the given predicate. **Signature:**```typescript removeAllFromArrayByPredicate: (arr: A[], predicate: (a: A) => boolean) => boolean ```## std.removeallfromarraybypredicate: Parameters | Parameter | Type | Description | | --- | --- | --- | | arr | A\[\] | The array from which elements will be removed. | | predicate | (a: A) => boolean | The predicate function used to determine which elements to remove. | **Returns:** boolean `true` if at least one element was removed, `false` otherwise. --- ## std.removeobjectfields: removeObjectFields() function Removes specified fields from an object and returns a new object without those fields. **Signature:**```typescript removeObjectFields: >(ob: T, ...fields: F) => Omit> ```## std.removeobjectfields: Parameters | Parameter | Type | Description | | --- | --- | --- | | ob | T | The object from which fields will be removed. | | fields | F | The fields to be removed from the object. | **Returns:** Omit<T, [TupleToUnion](#std-tupletounion)<F>> A new object without the specified fields. --- ## std.removeonefromarray: removeOneFromArray() function Removes the first occurrence of an item from an array. **Signature:**```typescript removeOneFromArray: (arr: A[], item: A) => boolean ```## std.removeonefromarray: Parameters | Parameter | Type | Description | | --- | --- | --- | | arr | A\[\] | The array from which to remove the item. | | item | A | The item to remove from the array. | **Returns:** boolean `true` if the item was found and removed, `false` otherwise. --- ## std.removeonefromarraybypredicate: removeOneFromArrayByPredicate() function Removes the first occurrence in an array that satisfy the given predicate. **Signature:**```typescript removeOneFromArrayByPredicate: (arr: A[], predicate: (a: A) => boolean) => boolean ```## std.removeonefromarraybypredicate: Parameters | Parameter | Type | Description | | --- | --- | --- | | arr | A\[\] | The array from which elements will be removed. | | predicate | (a: A) => boolean | The predicate function used to determine which elements to remove. | **Returns:** boolean `true` if at least one element was removed, `false` otherwise. --- ## std.removequeryparam: removeQueryParam() function Removes a query parameter from a URL. This function removes a specific query parameter from a URL, preserving all other parameters and URL components. **Signature:**```typescript removeQueryParam: (url: string, key: string) => string ```## std.removequeryparam: Parameters | Parameter | Type | Description | | --- | --- | --- | | url | string | The base URL | | key | string | The parameter key to remove | **Returns:** string The URL with the parameter removed ## std.removequeryparam: Example```typescript const url = removeQueryParam('https://example.com/path?keep=this&remove=that', 'remove') // Result: 'https://example.com/path?keep=this' ``` --- ## std.requiredby: RequiredBy type Creates a new type by making the specified key `K` of `T` required. **Signature:**```typescript export type RequiredBy = Merge, Required>>; ``` **References:** [Merge](#std-merge) --- ## std.result: Result variable Utility functions for working with `Result` types. **Signature:**```typescript Result: { success(value: V): Result; failure(error: E): Result; map: (r: Result, f: (value: V1) => V2) => Result; flatMap: (r: Result, f: (value: V1) => Result) => Result; toAsync(r: Result): AsyncResult; toValidation(r: Result): Validation; isSuccess(r: Result): r is Success; isFailure(r: Result): r is Failure; getOrElse(r: Result, alt: V): V; getOrElseLazy(r: Result, altf: () => V): V; getOrNull(r: Result): V | null; getOrUndefined(r: Result): Maybe; getUnsafe: (r: Result) => V; match: (r: Result, success: (value: V1) => V2, failure: (error: E) => V2) => V2; effect: (r: Result, handlers: { success?: (value: V) => void; failure?: (error: E) => void; else?: () => void; }) => Result; whenSuccess: (r: Result, apply: (v: V) => void) => Result; whenFailure: (r: Result, apply: (e: E) => void) => Result; combine: (r1: Result, r2: Result, combineV: (v1: V, v2: V) => V, combineE: (e1: E, e2: E) => E) => Result; equals: (r1: Result, r2: Result, options?: { valueEquals: (v1: V, v2: V) => boolean; errorEquals: (e1: E, e2: E) => boolean; }) => boolean; all: (results: Result[]) => Result; mapError: (r: Result, f: (error: E) => F) => Result; flatMapError: (r: Result, f: (error: E) => Result) => Result; recover: (r: Result, f: (error: E) => V) => Result; ap: (resultFn: Result<(v: V) => U, E>, resultVal: Result) => Result; map2: (r1: Result, r2: Result, f: (v1: V1, v2: V2) => U) => Result; map3: (r1: Result, r2: Result, r3: Result, f: (v1: V1, v2: V2, v3: V3) => U) => Result; ofPromise: (p: Promise) => Promise>; swap: (r: Result) => Result; fromNullable: (value: V | null | undefined, error: E) => Result; fromNullableLazy: (value: V | null | undefined, errorFn: () => E) => Result; tryCatch: (f: () => V) => Result; } ``` --- ## std.reverse: Reverse type **Signature:**```typescript export type Reverse = T extends [infer A, ...infer Rest] ? [...Reverse, A] : []; ``` **References:** [Reverse](#std-reverse) --- ## std.reversestring: reverseString() function Returns a new string whose characters are in reverse order. **Signature:**```typescript reverseString: (s: string) => string ```## std.reversestring: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to reverse. | **Returns:** string The reversed string. --- ## std.root: root() function Computes the nth root (`index`) of `base`. **Signature:**```typescript root: (base: number, index: number) => number ```## std.root: Parameters | Parameter | Type | Description | | --- | --- | --- | | base | number | The base number. | | index | number | The index of the root. | **Returns:** number The nth root of the base number. ## std.root: Example```ts root(8, 3) // returns 2 root(27, 3) // returns 3 root(16, 4) // returns 2 ``` --- ## std.roundto: roundTo() function Rounds a number to the specified number of decimals. **Signature:**```typescript roundTo: (f: number, decimals: number) => number ```## std.roundto: Parameters | Parameter | Type | Description | | --- | --- | --- | | f | number | The number to round. | | decimals | number | The number of decimals to round to. | **Returns:** number The rounded number. ## std.roundto: Example```ts roundTo(1.234, 2) // returns 1.23 roundTo(1.234, 1) // returns 1.2 roundTo(1.234, 0) // returns 1 ``` --- ## std.rpad: rpad() function Pads a string on the right with a specified character until it reaches a specified length. If the string is already longer than the specified length, it is returned as is. **Signature:**```typescript rpad: (s: string, char: string, length: number) => string ```## std.rpad: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to pad. | | char | string | The character to use for padding. | | length | number | The desired length of the padded string. | **Returns:** string The padded string. --- ## std.sameobjectkeys: sameObjectKeys() function Checks if two objects have the same keys. **Signature:**```typescript sameObjectKeys: (a: T, b: T) => boolean ```## std.sameobjectkeys: Parameters | Parameter | Type | Description | | --- | --- | --- | | a | T | The first object. | | b | T | The second object. | **Returns:** boolean `true` if both objects have the same keys, `false` otherwise. --- ## std.seedrandom: seedRandom() function Creates a seeded random number generator. This function returns a deterministic random number generator that produces the same sequence of numbers for the same seed. Useful for testing or when reproducible randomness is needed. **Signature:**```typescript seedRandom: (seed: string) => (() => number) ```## std.seedrandom: Parameters | Parameter | Type | Description | | --- | --- | --- | | seed | string | The seed string for the random number generator | **Returns:** (() => number) A function that generates seeded random numbers between 0 and 1 ## std.seedrandom: Example```typescript const rng = seedRandom('my-seed') const num1 = rng() // Always the same for this seed const num2 = rng() // Next number in sequence // Create another generator with same seed const rng2 = seedRandom('my-seed') const same1 = rng2() // Same as num1 ``` --- ## std.setdifference: setDifference() function Creates the difference between two Sets. The difference contains elements that are in the first Set but not in the second. This is equivalent to the mathematical difference operation (A - B). **Signature:**```typescript setDifference: (setA: Set, setB: Set) => Set ```## std.setdifference: Parameters | Parameter | Type | Description | | --- | --- | --- | | setA | Set<T> | Set to subtract from | | setB | Set<T> | Set to subtract | **Returns:** Set<T> A new Set containing elements in setA but not in setB ## std.setdifference: Example```typescript const setA = new Set([1, 2, 3, 4]) const setB = new Set([3, 4, 5, 6]) const difference = setDifference(setA, setB) // Result: Set { 1, 2 } ``` --- ## std.setfilter: setFilter() function Creates a new Set containing only elements that satisfy the predicate. This provides a functional approach to filtering Sets, similar to Array.prototype.filter but for Set objects. **Signature:**```typescript setFilter: (set: Set, predicate: (value: T) => boolean) => Set ```## std.setfilter: Parameters | Parameter | Type | Description | | --- | --- | --- | | set | Set<T> | The Set to filter | | predicate | (value: T) => boolean | Function that tests each element | **Returns:** Set<T> A new Set with elements that satisfy the predicate ## std.setfilter: Example```typescript const numbers = new Set([1, 2, 3, 4, 5, 6]) const evenNumbers = setFilter(numbers, n => n % 2 === 0) // Result: Set { 2, 4, 6 } ``` --- ## std.setfromarray: setFromArray() function Creates a Set from an array, removing duplicates. This provides a semantic way to deduplicate arrays using Sets. **Signature:**```typescript setFromArray: (array: readonly T[]) => Set ```## std.setfromarray: Parameters | Parameter | Type | Description | | --- | --- | --- | | array | readonly T\[\] | The array to convert | **Returns:** Set<T> A new Set containing unique elements from the array ## std.setfromarray: Example```typescript const array = [1, 2, 2, 3, 3, 3, 4] const set = setFromArray(array) // Result: Set { 1, 2, 3, 4 } ``` --- ## std.setintersection: setIntersection() function Creates the intersection of two Sets. The intersection contains only elements that appear in both Sets. This is equivalent to the mathematical intersection operation (A ∩ B). **Signature:**```typescript setIntersection: (setA: Set, setB: Set) => Set ```## std.setintersection: Parameters | Parameter | Type | Description | | --- | --- | --- | | setA | Set<T> | First Set | | setB | Set<T> | Second Set | **Returns:** Set<T> A new Set containing elements present in both input Sets ## std.setintersection: Example```typescript const setA = new Set([1, 2, 3, 4]) const setB = new Set([3, 4, 5, 6]) const intersection = setIntersection(setA, setB) // Result: Set { 3, 4 } ``` --- ## std.setisempty: setIsEmpty() function Checks if a Set is empty. This provides a semantic way to check for empty Sets, making code more readable than checking size === 0. **Signature:**```typescript setIsEmpty: (set: Set) => boolean ```## std.setisempty: Parameters | Parameter | Type | Description | | --- | --- | --- | | set | Set<T> | The Set to check | **Returns:** boolean true if the Set has no elements, false otherwise ## std.setisempty: Example```typescript const emptySet = new Set() const nonEmptySet = new Set([1, 2, 3]) setIsEmpty(emptySet) // true setIsEmpty(nonEmptySet) // false ``` --- ## std.setissubset: setIsSubset() function Checks if one Set is a subset of another. A Set is a subset if all of its elements are contained in the other Set. An empty Set is considered a subset of any Set. **Signature:**```typescript setIsSubset: (subset: Set, superset: Set) => boolean ```## std.setissubset: Parameters | Parameter | Type | Description | | --- | --- | --- | | subset | Set<T> | Set to check if it's a subset | | superset | Set<T> | Set to check against | **Returns:** boolean true if subset is a subset of superset, false otherwise ## std.setissubset: Example```typescript const subset = new Set([1, 2]) const superset = new Set([1, 2, 3, 4]) const notSubset = new Set([1, 5]) setIsSubset(subset, superset) // true setIsSubset(notSubset, superset) // false setIsSubset(new Set(), superset) // true (empty set) ``` --- ## std.setissuperset: setIsSuperset() function Checks if one Set is a superset of another. A Set is a superset if it contains all elements of the other Set. This is the inverse of the subset relationship. **Signature:**```typescript setIsSuperset: (superset: Set, subset: Set) => boolean ```## std.setissuperset: Parameters | Parameter | Type | Description | | --- | --- | --- | | superset | Set<T> | Set to check if it's a superset | | subset | Set<T> | Set to check against | **Returns:** boolean true if superset is a superset of subset, false otherwise ## std.setissuperset: Example```typescript const superset = new Set([1, 2, 3, 4]) const subset = new Set([1, 2]) const notSubset = new Set([1, 5]) setIsSuperset(superset, subset) // true setIsSuperset(superset, notSubset) // false ``` --- ## std.setmap: setMap() function Creates a new Set with elements transformed by the mapper function. This provides a functional approach to transforming Set elements, similar to Array.prototype.map but for Set objects. **Signature:**```typescript setMap: (set: Set, mapper: (value: T) => U) => Set ```## std.setmap: Parameters | Parameter | Type | Description | | --- | --- | --- | | set | Set<T> | The Set to transform | | mapper | (value: T) => U | Function that transforms each element | **Returns:** Set<U> A new Set with transformed elements ## std.setmap: Example```typescript const numbers = new Set([1, 2, 3]) const doubled = setMap(numbers, n => n * 2) // Result: Set { 2, 4, 6 } ``` --- ## std.setqueryparam: setQueryParam() function Sets a query parameter in a URL. This function adds or updates a single query parameter in a URL, preserving all other parameters and URL components. **Signature:**```typescript setQueryParam: (url: string, key: string, value: string) => string ```## std.setqueryparam: Parameters | Parameter | Type | Description | | --- | --- | --- | | url | string | The base URL | | key | string | The parameter key | | value | string | The parameter value | **Returns:** string The URL with the parameter set ## std.setqueryparam: Example```typescript const url = setQueryParam('https://example.com/path?existing=value', 'new', 'param') // Result: 'https://example.com/path?existing=value&new=param' const updated = setQueryParam('https://example.com/path?existing=old', 'existing', 'new') // Result: 'https://example.com/path?existing=new' ``` --- ## std.setsymmetricdifference: setSymmetricDifference() function Creates the symmetric difference between two Sets. The symmetric difference contains elements that are in either Set but not in both. This is equivalent to (A - B) ∪ (B - A) or (A ∪ B) - (A ∩ B). **Signature:**```typescript setSymmetricDifference: (setA: Set, setB: Set) => Set ```## std.setsymmetricdifference: Parameters | Parameter | Type | Description | | --- | --- | --- | | setA | Set<T> | First Set | | setB | Set<T> | Second Set | **Returns:** Set<T> A new Set containing elements in either Set but not both ## std.setsymmetricdifference: Example```typescript const setA = new Set([1, 2, 3, 4]) const setB = new Set([3, 4, 5, 6]) const symDiff = setSymmetricDifference(setA, setB) // Result: Set { 1, 2, 5, 6 } ``` --- ## std.settled: Settled type Represents a settled state in an asynchronous result. **Signature:**```typescript export type Settled = AsyncSuccess | AsyncFailure; ``` **References:** [AsyncSuccess](#std-asyncsuccess), [AsyncFailure](#std-asyncfailure) --- ## std.settoarray: setToArray() function Converts a Set to an array. This provides a convenient way to convert Sets to arrays for further processing with array methods. **Signature:**```typescript setToArray: (set: Set) => T[] ```## std.settoarray: Parameters | Parameter | Type | Description | | --- | --- | --- | | set | Set<T> | The Set to convert | **Returns:** T\[\] An array containing all elements from the Set ## std.settoarray: Example```typescript const set = new Set([3, 1, 4, 1, 5]) // Note: duplicates are removed const array = setToArray(set) // Result: [3, 1, 4, 5] ``` --- ## std.setunion: setUnion() function Creates the union of multiple Sets. The union contains all unique elements that appear in any of the input Sets. This is equivalent to the mathematical union operation (A ∪ B ∪ C...). **Signature:**```typescript setUnion: (...sets: Set[]) => Set ```## std.setunion: Parameters | Parameter | Type | Description | | --- | --- | --- | | sets | Set<T>\[\] | Sets to union | **Returns:** Set<T> A new Set containing all unique elements from input Sets ## std.setunion: Example```typescript const setA = new Set([1, 2, 3]) const setB = new Set([3, 4, 5]) const setC = new Set([5, 6, 7]) const union = setUnion(setA, setB, setC) // Result: Set { 1, 2, 3, 4, 5, 6, 7 } ``` --- ## std.shuffle: shuffle() function Shuffles an array in place using the Fisher-Yates algorithm. This function randomly reorders the elements of an array, modifying the original array. Each permutation is equally likely. **Signature:**```typescript shuffle: (array: T[]) => T[] ```## std.shuffle: Parameters | Parameter | Type | Description | | --- | --- | --- | | array | T\[\] | The array to shuffle (modified in place) | **Returns:** T\[\] The same array reference (for chaining) ## std.shuffle: Example```typescript const deck = ['A', 'K', 'Q', 'J', '10', '9', '8', '7'] shuffle(deck) // deck is now randomly ordered const playlist = [...songs] shuffle(playlist) // Randomize playlist order ``` --- ## std.shuffled: shuffled() function Returns a shuffled copy of an array without modifying the original. This function creates a new array with the same elements as the input but in random order, leaving the original array unchanged. **Signature:**```typescript shuffled: (array: readonly T[]) => T[] ```## std.shuffled: Parameters | Parameter | Type | Description | | --- | --- | --- | | array | readonly T\[\] | The array to shuffle | **Returns:** T\[\] A new shuffled array ## std.shuffled: Example```typescript const original = [1, 2, 3, 4, 5] const shuffled = shuffled(original) // e.g., [3, 1, 5, 2, 4] // original is still [1, 2, 3, 4, 5] ``` --- ## std.skip: skip() function Skips the first n elements and returns an iterable of the remaining elements. This function creates a new iterable that yields all elements after skipping the specified number of initial elements. **Signature:**```typescript skip: (iterable: Iterable, count: number) => Iterable ```## std.skip: Parameters | Parameter | Type | Description | | --- | --- | --- | | iterable | Iterable<T> | The iterable to skip elements from | | count | number | The number of elements to skip | **Returns:** Iterable<T> An iterable that yields remaining elements ## std.skip: Example```typescript const numbers = [1, 2, 3, 4, 5] const afterFirst2 = [...skip(numbers, 2)] // [3, 4, 5] // Use with other iterator functions const result = take(skip(largeDataset, 100), 10) // Skip 100, take next 10 ``` --- ## std.sleep: sleep() function Sleep for a given number of milliseconds. **Signature:**```typescript sleep: (ms: number, { abortSignal }?: { abortSignal?: AbortSignal; }) => Promise ```## std.sleep: Parameters | Parameter | Type | Description | | --- | --- | --- | | ms | number | The number of milliseconds to sleep. | | { abortSignal } | { abortSignal?: AbortSignal; } | _(Optional)_ | **Returns:** Promise<void> A promise that resolves after the given number of milliseconds. --- ## std.smartquote: smartQuote() function Converts a string in a quoted string. **Signature:**```typescript smartQuote: (s: string, prefer?: string) => string ```## std.smartquote: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to quote. | | prefer | string | _(Optional)_ The preferred quote character. Defaults to single quote (`'`). | **Returns:** string The quoted string. --- ## std.some: some() function Tests whether at least one element in an iterable satisfies the predicate. This function returns true if the predicate returns true for any element, or false if no elements satisfy the predicate. It short-circuits on the first true result. **Signature:**```typescript some: (iterable: Iterable, predicate: (item: T) => boolean) => boolean ```## std.some: Parameters | Parameter | Type | Description | | --- | --- | --- | | iterable | Iterable<T> | The iterable to test | | predicate | (item: T) => boolean | Function that tests each element | **Returns:** boolean true if any element satisfies the predicate, false otherwise ## std.some: Example```typescript const numbers = [1, 3, 5, 8, 9] const hasEven = some(numbers, n => n % 2 === 0) // true const users = [{ age: 15 }, { age: 16 }, { age: 17 }] const hasAdult = some(users, user => user.age >= 18) // false ``` --- ## std.splitliteral: SplitLiteral type Splits a string literal type `T` by a specified delimiter `SplitBy`. Returns a tuple containing the split parts of the string. **Signature:**```typescript export type SplitLiteral = FilterTuple, ...SplitLiteral] : [T], ''>; ``` **References:** [FilterTuple](#std-filtertuple), [SplitLiteral](#std-splitliteral) --- ## std.splitliteraltounion: SplitLiteralToUnion type Converts a string literal type `T` into a union type by splitting it using the specified delimiter `SplitBy`. **Signature:**```typescript export type SplitLiteralToUnion = TupleToUnion>; ``` **References:** [TupleToUnion](#std-tupletounion), [SplitLiteral](#std-splitliteral) --- ## std.splitstringonce: splitStringOnce() function It only splits on the first occurrance of separator. **Signature:**```typescript splitStringOnce: (s: string, separator: string) => [string] | [string, string] ```## std.splitstringonce: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to split. | | separator | string | The separator to split the string on. | **Returns:** \[string\] \| \[string, string\] An array with the split string. --- ## std.splitstringonfirst: splitStringOnFirst() function Splits a string into two parts based on the first occurrence of a specified substring. If the substring is found, returns an array with two elements: the part of the string before the substring and the part after the substring. If the substring is not found, returns an array with a single element: the original string. **Signature:**```typescript splitStringOnFirst: (s: string, find: string) => [string] | [string, string] ```## std.splitstringonfirst: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to split. | | find | string | The substring to search for. | **Returns:** \[string\] \| \[string, string\] An array containing the split parts of the string. --- ## std.splitstringonlast: splitStringOnLast() function Splits a string into two parts at the last occurrence of a specified substring. If the substring is found, the function returns an array with two elements: the part of the string before the substring and the part after the substring. If the substring is not found, the function returns an array with a single element, which is the original string. **Signature:**```typescript splitStringOnLast: (s: string, find: string) => [string] | [string, string] ```## std.splitstringonlast: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to split. | | find | string | The substring to search for. | **Returns:** \[string\] \| \[string, string\] An array containing the split parts of the string. --- ## std.startofday: startOfDay() function Returns a new Date representing the start of the day (00:00:00.000). This is useful for date comparisons and range queries where you need to normalize dates to the beginning of the day. **Signature:**```typescript startOfDay: (date: Date) => Date ```## std.startofday: Parameters | Parameter | Type | Description | | --- | --- | --- | | date | Date | The input date | **Returns:** Date A new Date set to the start of the day ## std.startofday: Example```typescript const date = new Date('2023-01-15T14:30:45.123') const start = startOfDay(date) // Result: 2023-01-15T00:00:00.000 ``` --- ## std.startofweek: startOfWeek() function Returns a new Date representing the start of the week (Monday 00:00:00.000). This follows the ISO 8601 standard where Monday is the first day of the week. Useful for weekly reports and date grouping. **Signature:**```typescript startOfWeek: (date: Date) => Date ```## std.startofweek: Parameters | Parameter | Type | Description | | --- | --- | --- | | date | Date | The input date | **Returns:** Date A new Date set to the start of the week ## std.startofweek: Example```typescript const date = new Date('2023-01-18') // Wednesday const start = startOfWeek(date) // Result: 2023-01-16T00:00:00.000 (Monday) ``` --- ## std.strictequal: strictEqual() function Checks if two values are strictly equal. **Signature:**```typescript strictEqual: (a: A, b: A) => boolean ```## std.strictequal: Parameters | Parameter | Type | Description | | --- | --- | --- | | a | A | The first value to compare. | | b | A | The second value to compare. | **Returns:** boolean `true` if the values are strictly equal, `false` otherwise. --- ## std.stringendswithany: stringEndsWithAny() function Returns `true` if `s` ends with any of the values in `values`. **Signature:**```typescript stringEndsWithAny: (s: string, values: string[]) => boolean ```## std.stringendswithany: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to compare. | | values | string\[\] | The values to compare with the end of `s`. | **Returns:** boolean `true` if `s` ends with any of the values in `values`, `false` otherwise. --- ## std.stringhascontent: stringHasContent() function Returns `true` if `value` is not `null` and contains at least one character. **Signature:**```typescript stringHasContent: (value: string) => boolean ```## std.stringhascontent: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to check. | **Returns:** boolean `true` if the string is not `null` and contains at least one character, `false` otherwise. --- ## std.stringhashcode: stringHashCode() function Calculates the hash code for a given string. **Signature:**```typescript stringHashCode: (value: string, seed?: number) => number ```## std.stringhashcode: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to calculate the hash code for. | | seed | number | _(Optional)_ The seed value for the hash code calculation. Default is 0x811c9dc5. | **Returns:** number The calculated hash code as a number. --- ## std.stringsdifferatindex: stringsDifferAtIndex() function Compares strings `a` and `b` and returns the position where they differ. If the strings are equal, it returns `-1`. **Signature:**```typescript stringsDifferAtIndex: (a: string, b: string) => number ```## std.stringsdifferatindex: Parameters | Parameter | Type | Description | | --- | --- | --- | | a | string | The first string to compare. | | b | string | The second string to compare. | **Returns:** number The position where the strings differ, or `-1` if they are equal. ## std.stringsdifferatindex: Example```ts stringsDifferAtIndex('abcdef', 'abc123') // returns 3 ``` --- ## std.stringstartswithany: stringStartsWithAny() function Returns `true` if `s` starts with any of the values in `values`. **Signature:**```typescript stringStartsWithAny: (s: string, values: string[]) => boolean ```## std.stringstartswithany: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to compare. | | values | string\[\] | The values to compare with the start of `s`. | **Returns:** boolean `true` if `s` starts with any of the values in `values`, `false` otherwise. --- ## std.stringtocharcodes: stringToCharcodes() function It transforms a string into an `Array` of char codes in integer format. **Signature:**```typescript stringToCharcodes: (s: string) => number[] ```## std.stringtocharcodes: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to transform. | **Returns:** number\[\] An array of char codes. --- ## std.substringafter: substringAfter() function `substringAfter` searches for the first occurrance of `searchFor` and returns the text after that. If `searchFor` is not found, an empty string is returned. **Signature:**```typescript substringAfter: (value: string, searchFor: string) => string ```## std.substringafter: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to search in. | | searchFor | string | The string to search for. | **Returns:** string The text after the first occurrance of `searchFor` or an empty string if `searchFor` is not found. --- ## std.substringafterlast: substringAfterLast() function `substringAfterLast` searches for the last occurrance of `searchFor` and returns the text after that. If `searchFor` is not found, an empty string is returned. **Signature:**```typescript substringAfterLast: (value: string, searchFor: string) => string ```## std.substringafterlast: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to search in. | | searchFor | string | The string to search for. | **Returns:** string The text after the last occurrance of `searchFor` or an empty string if `searchFor` is not found. --- ## std.substringbefore: substringBefore() function `substringBefore` searches for the first occurrance of `searchFor` and returns the text before that. If `searchFor` is not found, an empty string is returned. **Signature:**```typescript substringBefore: (value: string, searchFor: string) => string ```## std.substringbefore: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to search in. | | searchFor | string | The string to search for. | **Returns:** string The text before the first occurrance of `searchFor` or an empty string if `searchFor` is not found. --- ## std.substringbeforelast: substringBeforeLast() function `substringBeforeLast` searches for the last occurrance of `searchFor` and returns the text before that. If `searchFor` is not found, an empty string is returned. **Signature:**```typescript substringBeforeLast: (value: string, searchFor: string) => string ```## std.substringbeforelast: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to search in. | | searchFor | string | The string to search for. | **Returns:** string The text before the last occurrance of `searchFor` or an empty string if `searchFor` is not found. --- ## std.success: Success type Represents a successful result. **Signature:**```typescript export type Success = { readonly type: 'Success'; readonly value: V; }; ``` --- ## std.surroundstring: surroundString() function Surrounds a string with the contents of `left` and `right`. If `right` is omitted, `left` will be used on both sides **Signature:**```typescript surroundString: (s: string, left: string, right?: string) => string ```## std.surroundstring: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to surround. | | left | string | The left side of the surrounding text. | | right | string | _(Optional)_ The right side of the surrounding text. Defaults to `left`. | **Returns:** string The surrounded string. --- ## std.take: take() function Takes the first n elements from an iterable. This function creates a new array containing the first n elements from the iterable. It's useful for limiting results or sampling data. **Signature:**```typescript take: (iterable: Iterable, count: number) => T[] ```## std.take: Parameters | Parameter | Type | Description | | --- | --- | --- | | iterable | Iterable<T> | The iterable to take elements from | | count | number | The number of elements to take | **Returns:** T\[\] An array containing the first count elements ## std.take: Example```typescript const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] const first3 = take(numbers, 3) // [1, 2, 3] const firstUsers = take(userGenerator(), 5) // First 5 users from generator ``` --- ## std.textcontainscaseinsensitive: textContainsCaseInsensitive() function `textContainsCaseInsensitive` returns `true` if `s` contains one or more occurrences of `test` regardless of the text case. **Signature:**```typescript textContainsCaseInsensitive: (s: string, test: string) => boolean ```## std.textcontainscaseinsensitive: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to search in. | | test | string | The string to search for. | **Returns:** boolean `true` if `s` contains `test` (case-insensitive), `false` otherwise. --- ## std.textendswithanycaseinsensitive: textEndsWithAnyCaseInsensitive() function Compares a string `s` with many `values` and see if one of them matches its end ignoring their case. **Signature:**```typescript textEndsWithAnyCaseInsensitive: (s: string, values: string[]) => boolean ```## std.textendswithanycaseinsensitive: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to compare. | | values | string\[\] | The values to compare with the end of `s`. | **Returns:** boolean `true` if `s` ends with any of the values in `values` (case-insensitive), `false` otherwise. --- ## std.textendswithcaseinsensitive: textEndsWithCaseInsensitive() function Checks if a string ends with another string in a case-insensitive manner. **Signature:**```typescript textEndsWithCaseInsensitive: (s: string, end: string) => boolean ```## std.textendswithcaseinsensitive: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to check. | | end | string | The string to check if it is the ending of `s`. | **Returns:** boolean `true` if `s` ends with `end` (case-insensitive), otherwise `false`. --- ## std.textstartswithanycaseinsensitive: textStartsWithAnyCaseInsensitive() function Compares a string `s` with many `values` and see if one of them matches its beginning ignoring their case. **Signature:**```typescript textStartsWithAnyCaseInsensitive: (s: string, values: string[]) => boolean ```## std.textstartswithanycaseinsensitive: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to compare. | | values | string\[\] | The values to compare with the start of `s`. | **Returns:** boolean `true` if `s` starts with any of the values in `values` (case-insensitive), `false` otherwise. --- ## std.textstartswithcaseinsensitive: textStartsWithCaseInsensitive() function Checks if a string starts with another string in a case-insensitive manner. **Signature:**```typescript textStartsWithCaseInsensitive: (s: string, start: string) => boolean ```## std.textstartswithcaseinsensitive: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to check. | | start | string | The string to compare with the start of `s`. | **Returns:** boolean `true` if `s` starts with `start` (case-insensitive), `false` otherwise. --- ## std.texttolines: textToLines() function Returns an array of `string` split by line breaks. **Signature:**```typescript textToLines: (s: string) => string[] ```## std.texttolines: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to split. | **Returns:** string\[\] An array of lines. --- ## std.throttle: throttle() function Creates a throttled version of a function that limits how often the function can be called. **Signature:**```typescript export declare function throttle any>(delay: number, callback: F, options?: ThrottleOptions): ThrottledFunction, This>; ```## std.throttle: Parameters | Parameter | Type | Description | | --- | --- | --- | | delay | number | Milliseconds to wait before allowing the next call. | | callback | F | The function to throttle. | | options | [ThrottleOptions](#std-throttleoptions) | _(Optional)_ Configuration options for the throttle behavior. | **Returns:** [ThrottledFunction](#std-throttledfunction)<Parameters<F>, This> A throttled version of the function with a cancel method. ## std.throttle: Remarks Throttling is useful for rate-limiting event handlers, API calls, and other expensive operations. Common delay values are 100-250ms for UI updates and 1000ms+ for API calls. ## std.throttle: Example```ts // Create a throttled function that executes at most once every second const throttledScroll = throttle(1000, () => { console.warn('Scroll event handled'); }); // Attach to scroll event window.addEventListener('scroll', throttledScroll); // Cancel throttle if needed throttledScroll.cancel(); ``` --- ## std.throttledfunction.cancel: ThrottledFunction.cancel property **Signature:**```typescript cancel: (options?: CancelOptions) => void; ``` --- ## std.throttledfunction: ThrottledFunction interface Represents a throttled function with a cancel method. **Signature:**```typescript export interface ThrottledFunction ```## std.throttledfunction: Properties | Property | Modifiers | Type | Description | | --- | --- | --- | --- | | [cancel](#std-throttledfunction-cancel) | | (options?: [CancelOptions](#std-canceloptions)) => void | | --- ## std.throttleoptions.debouncemode: ThrottleOptions.debounceMode property Controls the throttle behavior: - If true, schedules clearing instead of the callback - If false, schedules the callback - If undefined, applies normal throttle behavior **Signature:**```typescript debounceMode?: boolean; ``` --- ## std.throttleoptions: ThrottleOptions interface Configuration options for throttle function. **Signature:**```typescript export interface ThrottleOptions ```## std.throttleoptions: Properties | Property | Modifiers | Type | Description | | --- | --- | --- | --- | | [debounceMode?](#std-throttleoptions-debouncemode) | | boolean | _(Optional)_ Controls the throttle behavior: - If true, schedules clearing instead of the callback - If false, schedules the callback - If undefined, applies normal throttle behavior | | [noLeading?](#std-throttleoptions-noleading) | | boolean | _(Optional)_ If true, suppresses the immediate call on the first trigger. false | | [noTrailing?](#std-throttleoptions-notrailing) | | boolean | _(Optional)_ If true, suppresses the final call after the last trigger. false | --- ## std.throttleoptions.noleading: ThrottleOptions.noLeading property If true, suppresses the immediate call on the first trigger. false **Signature:**```typescript noLeading?: boolean; ``` --- ## std.throttleoptions.notrailing: ThrottleOptions.noTrailing property If true, suppresses the final call after the last trigger. false **Signature:**```typescript noTrailing?: boolean; ``` --- ## std.toarray: toArray() function Converts an iterable to an array. This function creates a new array containing all elements from the iterable. It's equivalent to \[...iterable\] but more explicit in intent. **Signature:**```typescript toArray: (iterable: Iterable) => T[] ```## std.toarray: Parameters | Parameter | Type | Description | | --- | --- | --- | | iterable | Iterable<T> | The iterable to convert | **Returns:** T\[\] A new array containing all elements from the iterable ## std.toarray: Example```typescript const set = new Set([1, 2, 3, 2, 1]) const array = toArray(set) // [1, 2, 3] const mapped = map([1, 2, 3], n => n * 2) const result = toArray(mapped) // [2, 4, 6] ``` --- ## std.tohex: toHex() function Converts a number to its hexadecimal representation. **Signature:**```typescript toHex: (num: number, length?: number) => string ```## std.tohex: Parameters | Parameter | Type | Description | | --- | --- | --- | | num | number | The number to convert. | | length | number | _(Optional)_ The desired length of the hexadecimal string. Defaults to 0. | **Returns:** string The hexadecimal representation of the number. ## std.tohex: Example```ts toHex(255) // returns 'ff' toHex(255, 4) // returns '00ff' toHex(255, 8) // returns '000000ff' ``` --- ## std.trimchars: trimChars() function `trimChars` removes from the beginning and the end of the string any character that is present in `charlist`. **Signature:**```typescript trimChars: (value: string, charlist: string) => string ```## std.trimchars: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to trim. | | charlist | string | The characters to remove from the beginning and end of the string. | **Returns:** string The trimmed string. --- ## std.trimcharsleft: trimCharsLeft() function `trimCharsLeft` removes from the beginning of the string any character that is present in `charlist`. **Signature:**```typescript trimCharsLeft: (value: string, charlist: string) => string ```## std.trimcharsleft: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to trim. | | charlist | string | The characters to remove from the beginning of the string. | **Returns:** string The trimmed string. --- ## std.trimcharsright: trimCharsRight() function `trimCharsRight` removes from the end of the string any character that is present in `charlist`. **Signature:**```typescript trimCharsRight: (value: string, charlist: string) => string ```## std.trimcharsright: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to trim. | | charlist | string | The characters to remove from the end of the string. | **Returns:** string The trimmed string. --- ## std.trimstringslice: trimStringSlice() function Removes a slice from `index` to `index + length` from `value`. **Signature:**```typescript trimStringSlice: (value: string, index: number, length: number) => string ```## std.trimstringslice: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to remove the slice from. | | index | number | The starting index of the slice to remove. | | length | number | The length of the slice to remove. | **Returns:** string The string with the slice removed. --- ## std.tupletounion: TupleToUnion type Converts a tuple type to a union type. **Signature:**```typescript export type TupleToUnion = T[number]; ``` --- ## std.underscore: underscore() function `underscore` finds UpperCase characters and turns them into LowerCase and prepends them with a whtiespace. Sequences of more than one UpperCase character are left untouched. **Signature:**```typescript underscore: (s: string) => string ```## std.underscore: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to underscore. | **Returns:** string The underscored string. --- ## std.uniquebyprimitive: uniqueByPrimitive() function Removes duplicate objects from an array based on a key extraction function. This function removes duplicates from arrays of objects by extracting a primitive key from each object and using that key to determine uniqueness. When duplicates are found, the first occurrence is kept. **Signature:**```typescript uniqueByPrimitive: (values: T[], predicate: (a: T) => string | number | symbol) => T[] ```## std.uniquebyprimitive: Parameters | Parameter | Type | Description | | --- | --- | --- | | values | T\[\] | The input array containing objects to deduplicate | | predicate | (a: T) => string \\| number \\| symbol | Function that extracts a primitive key from each element for comparison | **Returns:** T\[\] A new array with duplicate elements removed based on the extracted key ## std.uniquebyprimitive: Example 1```typescript // Remove users with duplicate IDs const users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 1, name: 'Alice Clone' }, { id: 3, name: 'Charlie' } ] const uniqueUsers = uniqueByPrimitive(users, user => user.id) // Result: [ // { id: 1, name: 'Alice' }, // { id: 2, name: 'Bob' }, // { id: 3, name: 'Charlie' } // ] ``` ## std.uniquebyprimitive: Example 2 ```typescript // Remove products with duplicate names const products = [ { name: 'Laptop', price: 1000 }, { name: 'Mouse', price: 25 }, { name: 'Laptop', price: 1200 }, { name: 'Keyboard', price: 75 } ] const uniqueProducts = uniqueByPrimitive(products, p => p.name) // Result: [ // { name: 'Laptop', price: 1000 }, // { name: 'Mouse', price: 25 }, // { name: 'Keyboard', price: 75 } // ] ``` ## std.uniquebyprimitive: Example 3 ```typescript // Use with complex key extraction const events = [ { date: '2023-01-01', type: 'click' }, { date: '2023-01-01', type: 'hover' }, { date: '2023-01-01', type: 'click' }, { date: '2023-01-02', type: 'click' } ] const uniqueEvents = uniqueByPrimitive(events, e => `${e.date}-${e.type}`) // Result: [ // { date: '2023-01-01', type: 'click' }, // { date: '2023-01-01', type: 'hover' }, // { date: '2023-01-02', type: 'click' } // ] ``` --- ## std.uppercasefirst: upperCaseFirst() function Convert first letter in `value` to upper case. **Signature:**```typescript upperCaseFirst: (value: string) => string ```## std.uppercasefirst: Parameters | Parameter | Type | Description | | --- | --- | --- | | value | string | The string to convert. | **Returns:** string The string with the first letter in upper case. --- ## std.valid: Valid type Represents a valid result. **Signature:**```typescript export type Valid = { readonly type: 'valid'; }; ``` --- ## std.validation: Validation variable Utility functions for working with `Validation` types. **Signature:**```typescript Validation: { valid: { type: "valid"; }; invalid(error: E): Validation; isValid(r: Validation): r is Valid; isInvalid(r: Validation): r is Invalid; match: (r: Validation, valid: () => V, invalid: (error: E) => V) => V; toResult: (validation: Validation, value: T) => Result; effect: (v: Validation, handlers: { valid?: () => void; invalid?: (error: E) => void; else?: () => void; }) => Validation; whenValid: (r: Validation, apply: () => void) => Validation; whenInvalid: (r: Validation, apply: (e: E) => void) => Validation; mapError: (v: Validation, f: (error: E) => F) => Validation; flatMapError: (v: Validation, f: (error: E) => Validation) => Validation; combine: (v1: Validation, v2: Validation, combineErrors: (e1: E, e2: E) => E) => Validation; all: (validations: Validation[]) => Validation; allErrors: (validations: Validation[]) => Validation; equals: (v1: Validation, v2: Validation, errorEquals?: (e1: E, e2: E) => boolean) => boolean; recover: (_v: Validation) => Validation; getError: (v: Validation) => E | undefined; getErrorOrElse: (v: Validation, defaultError: E) => E; } ``` --- ## std.widestangledifference: widestAngleDifference() function Calculates the minimum difference between two angles in degrees. Note: Despite the name "widest", this function actually calculates the shortest angle difference, identical to `angleDifference`. The name is misleading for historical reasons. **Signature:**```typescript widestAngleDifference: (a: number, b: number, turn?: number) => number ```## std.widestangledifference: Parameters | Parameter | Type | Description | | --- | --- | --- | | a | number | The first angle in degrees. | | b | number | The second angle in degrees. | | turn | number | _(Optional)_ The total angle of a full turn. Defaults to 360 degrees. | **Returns:** number The shortest angle difference between `a` and `b`. ## std.widestangledifference: Example```ts widestAngleDifference(0, 90) // returns 90 (shortest path) widestAngleDifference(90, 0) // returns -90 (shortest path) widestAngleDifference(0, 270) // returns -90 (shortest path, not +270) widestAngleDifference(270, 0) // returns 90 (shortest path, not -270) ``` --- ## std.wrap: wrap() function Passed two boundaries values (`min`, `max`), `wrap` ensures that the passed value `v` will be included in the boundaries. If the value exceeds `max`, the value is reduced by `min` repeatedely until it falls within the range. Similar and inverted treatment is performed if the value is below `min`. **Signature:**```typescript wrap: (v: number, min: number, max: number) => number ```## std.wrap: Parameters | Parameter | Type | Description | | --- | --- | --- | | v | number | The value to wrap. | | min | number | The minimum value of the range. | | max | number | The maximum value of the range. | **Returns:** number The wrapped value. ## std.wrap: Example```ts wrap(5, 0, 10) // returns 5 wrap(15, 0, 10) // returns 5 wrap(-5, 0, 10) // returns 5 ``` --- ## std.wrapcircular: wrapCircular() function Similar to `wrap`, it works for numbers between 0 and `max`. **Signature:**```typescript wrapCircular: (v: number, max: number) => number ```## std.wrapcircular: Parameters | Parameter | Type | Description | | --- | --- | --- | | v | number | The value to wrap. | | max | number | The maximum value of the range. | **Returns:** number The wrapped value. ## std.wrapcircular: Example```ts wrapCircular(5, 10) // returns 5 wrapCircular(15, 10) // returns 5 wrapCircular(-5, 10) // returns 5 ``` --- ## std.wrapcolumns: wrapColumns() function `wrapColumns` splits a long string into lines that are at most `columns` long. Individual words whose length exceeds `columns` are not split. **Signature:**```typescript wrapColumns: (s: string, columns?: number, indent?: string, newline?: string) => string ```## std.wrapcolumns: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to wrap. | | columns | number | _(Optional)_ The number of columns per line. | | indent | string | _(Optional)_ The indentation string to prepend to each line. | | newline | string | _(Optional)_ The newline character to use for line breaks. | **Returns:** string The wrapped string. --- ## std.wrapline: wrapLine() function Wraps a string into multiple lines based on the specified number of columns, indentation, and newline character. **Signature:**```typescript wrapLine: (s: string, columns: number, indent: string, newline: string) => string ```## std.wrapline: Parameters | Parameter | Type | Description | | --- | --- | --- | | s | string | The string to wrap. | | columns | number | The number of columns per line. | | indent | string | The indentation string to prepend to each line. | | newline | string | The newline character to use for line breaks. | **Returns:** string The wrapped string. --- ## std.xorboolean: xorBoolean() function Returns `true` when arguments are different. **Signature:**```typescript xorBoolean: (a: boolean, b: boolean) => boolean ```## std.xorboolean: Parameters | Parameter | Type | Description | | --- | --- | --- | | a | boolean | The first boolean value. | | b | boolean | The second boolean value. | **Returns:** boolean The result of the XOR operation. --- # tempots-ui api index [Home](#tempots-ui-api-index) ## tempots-ui: API Reference ## tempots-ui: Packages | Package | Description | | --- | --- | | [@tempots/ui](#ui) | | --- ## ui.allplacements: allPlacements variable Represents all possible placements for a pop-over. **Signature:**```typescript allPlacements: Placement[] ``` --- ## ui.anchor: Anchor() function Creates an anchor element with the specified href and children. When the anchor element is clicked, the location is updated to the specified href. **Signature:**```typescript Anchor: (hrefOrOptions: HrefOrAnchorOptions, ...children: TNode[]) => Renderable ```## ui.anchor: Parameters | Parameter | Type | Description | | --- | --- | --- | | hrefOrOptions | [HrefOrAnchorOptions](#ui-hreforanchoroptions) | The href attribute of the anchor element. | | children | TNode\[\] | The child elements of the anchor element. | **Returns:** Renderable The anchor element. --- ## ui.anchoroptions: AnchorOptions type Options for configuring an anchor element. **Signature:**```typescript export type AnchorOptions = Merge<{ href: Value; } & NavigationOptions, HandleAnchorClickOptions>; ``` **References:** [NavigationOptions](#ui-navigationoptions), [HandleAnchorClickOptions](#ui-handleanchorclickoptions) --- ## ui.appearance: Appearance variable A provider that provides a child component with an appearance context, which can be used to determine the current appearance (light or dark) based on the user's system preferences. The appearance context is updated whenever the user's system preferences change, and the component is cleaned up when it is no longer needed. **Signature:**```typescript Appearance: Provider> ``` --- ## ui.appearancetype: AppearanceType type Defines the possible appearance types for the application. **Signature:**```typescript export type AppearanceType = 'light' | 'dark'; ``` --- ## ui.arelocationsequal: areLocationsEqual() function Compares two location objects and returns true if they are equal, false otherwise. **Signature:**```typescript areLocationsEqual: (a: LocationData, b: LocationData) => boolean ```## ui.arelocationsequal: Parameters | Parameter | Type | Description | | --- | --- | --- | | a | [LocationData](#ui-locationdata) | The first location object to compare. | | b | [LocationData](#ui-locationdata) | The second location object to compare. | **Returns:** boolean True if the location objects are equal, false otherwise. --- ## ui.asyncresultview: AsyncResultView() function Renders the view based on the result of an asynchronous operation. **Signature:**```typescript AsyncResultView: (result: Value>, options: AsyncResultViewOptions | ((value: Signal) => TNode)) => Renderable ```## ui.asyncresultview: Parameters | Parameter | Type | Description | | --- | --- | --- | | result | Value<AsyncResult<T, E>> | The result of the asynchronous operation. | | options | [AsyncResultViewOptions](#ui-asyncresultviewoptions)<T, E> \\| ((value: Signal<T>) => TNode) | The options object or a function that returns a TNode. | **Returns:** Renderable The rendered view. --- ## ui.asyncresultviewoptions: AsyncResultViewOptions type Represents the options for rendering an asynchronous result view. **Signature:**```typescript export type AsyncResultViewOptions = { success: (value: Signal) => TNode; failure?: (error: Signal) => TNode; notAsked?: () => TNode; loading?: (previousValue: Signal) => TNode; }; ``` --- ## ui.autofocus: AutoFocus() function Automatically focuses an element when it's rendered to the DOM. This utility is commonly used for form inputs, modals, or any interactive element that should receive focus immediately when it appears. The small default delay ensures the element is fully rendered before attempting to focus. **Signature:**```typescript AutoFocus: (delay?: number) => Renderable ```## ui.autofocus: Parameters | Parameter | Type | Description | | --- | --- | --- | | delay | number | _(Optional)_ Delay in milliseconds before focusing (default: 10ms) | **Returns:** Renderable A renderable that focuses the element when rendered ## ui.autofocus: Example 1```typescript // Auto-focus a text input html.input( AutoFocus(), attr.placeholder('Enter your name'), attr.type('text') ) ``` ## ui.autofocus: Example 2 ```typescript // Auto-focus with custom delay html.textarea( AutoFocus(100), // Wait 100ms before focusing attr.placeholder('Enter your message') ) ``` ## ui.autofocus: Example 3 ```typescript // Use in a modal dialog const showModal = prop(false) When(showModal, () => html.div( attr.class('modal'), html.input( AutoFocus(), // Focus when modal opens attr.placeholder('Search...') ), html.button( on.click(() => showModal.value = false), 'Close' ) ) ) ``` ## ui.autofocus: Example 4 ```typescript // Combine with other input enhancements html.input( AutoFocus(), AutoSelect(), // Also select the text attr.value(searchTerm), on.input(emitValue(value => searchTerm.value = value)) ) ``` --- ## ui.autoselect: AutoSelect() function Automatically selects all text content in an input element when it's rendered. This utility is particularly useful for input fields where you want the user to be able to immediately start typing to replace the existing content, or easily copy the current value. The small default delay ensures the element is fully rendered before attempting to select. **Signature:**```typescript AutoSelect: (delay?: number) => Renderable ```## ui.autoselect: Parameters | Parameter | Type | Description | | --- | --- | --- | | delay | number | _(Optional)_ Delay in milliseconds before selecting text (default: 10ms) | **Returns:** Renderable A renderable that selects all text in the input element when rendered ## ui.autoselect: Example 1```typescript // Auto-select text in an input const username = prop('john_doe') html.input( AutoSelect(), attr.value(username), attr.type('text') ) // When rendered, 'john_doe' will be automatically selected ``` ## ui.autoselect: Example 2 ```typescript // Combine with AutoFocus for complete UX html.input( AutoFocus(), // Focus the input AutoSelect(), // Select all text attr.value(editableValue), attr.placeholder('Enter value') ) ``` ## ui.autoselect: Example 3 ```typescript // Use in an edit dialog const editMode = prop(false) const itemName = prop('Default Name') When(editMode, () => html.div( html.label('Edit name:'), html.input( AutoFocus(), AutoSelect(), // Select existing name for easy editing attr.value(itemName), on.keydown(e => { if (e.key === 'Enter') editMode.value = false if (e.key === 'Escape') editMode.value = false }) ) ) ) ``` ## ui.autoselect: Example 4 ```typescript // Custom delay for specific timing needs html.input( AutoSelect(50), // Wait 50ms before selecting attr.value(sensitiveData) ) ``` --- ## ui.childrouter: ChildRouter() function Creates a nested router that matches against the remaining path from parent routers. ChildRouter is used for nested routing scenarios where a parent router (RootRouter or another ChildRouter) has matched a portion of the path and passed the remaining path to child components. ChildRouter reads the parent routing context and matches its routes against the remaining path. **Signature:**```typescript ChildRouter: >, K>> : never) => TNode; }>(routes: T) => Renderable ```## ui.childrouter: Parameters | Parameter | Type | Description | | --- | --- | --- | | routes | T | Object mapping route patterns to handler functions | **Returns:** Renderable A renderable router component that handles nested URL routing ## ui.childrouter: Exceptions {Error} When no matching route is found for the remaining path ## ui.childrouter: Example 1```typescript // Parent RootRouter passes remaining path to AdminRoutes const App = RootRouter({ '/admin/*': () => AdminRoutes(), '/blog/*': () => BlogRoutes() }) // ChildRouter matches against remaining path const AdminRoutes = ChildRouter({ '/users': () => html.div('User List'), '/users/:id': (info) => html.div('User: ', info.$.params.$.id), '/settings': () => html.div('Admin Settings'), '*': () => html.div('Admin 404') }) ``` ## ui.childrouter: Example 2 ```typescript // Multiple levels of nesting const BlogRoutes = ChildRouter({ '/posts/*': () => PostRoutes(), '/categories': () => html.div('Categories') }) const PostRoutes = ChildRouter({ '/': () => html.div('All Posts'), '/:id': (info) => html.div('Post: ', info.$.params.$.id), '/:id/comments': (info) => html.div('Comments for: ', info.$.params.$.id) }) ``` --- ## ui.classes: classes() function Creates a renderable that applies classes based on a record of boolean signals. **Signature:**```typescript export declare function classes(obj: Record>): import('@tempots/dom').Renderable; ```## ui.classes: Parameters | Parameter | Type | Description | | --- | --- | --- | | obj | Record<string, Value<boolean>> | The record of signals. | **Returns:** import('@tempots/dom').Renderable<import('@tempots/dom').DOMContext> The created renderable. --- ## ui.elementrect: ElementRect() function Creates a renderable function that monitors the size of an element and provides it as a signal. **Signature:**```typescript ElementRect: (fn: (rect: Signal) => TNode) => import('@tempots/dom').Renderable ```## ui.elementrect: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn | (rect: Signal<[Rect](#ui-rect)>) => TNode | The renderable function that receives the size signal and returns a TNode. | **Returns:** import('@tempots/dom').Renderable A function that takes a DOMContext and returns a renderable function. --- ## ui.evaluatelocationmatch: evaluateLocationMatch() function **Signature:**```typescript evaluateLocationMatch: (location: LocationData, matcher: string | RegExp | ((location: LocationData) => boolean), options: LocationMatchOptions | undefined) => boolean ```## ui.evaluatelocationmatch: Parameters | Parameter | Type | Description | | --- | --- | --- | | location | [LocationData](#ui-locationdata) | | | matcher | string \\| RegExp \\| ((location: [LocationData](#ui-locationdata)) => boolean) | | | options | [LocationMatchOptions](#ui-locationmatchoptions) \\| undefined | | **Returns:** boolean --- ## ui.extractparams: ExtractParams type Extracts the parameters from a string literal representing a route path. **Signature:**```typescript export type ExtractParams = SplitLiteral extends infer T ? T extends unknown[] ? ExtractParamsFromTuple : never : never; ``` **References:** [ExtractParamsFromTuple](#ui-extractparamsfromtuple) --- ## ui.extractparamsfromtuple: ExtractParamsFromTuple type Extracts the parameter names from a tuple type. **Signature:**```typescript export type ExtractParamsFromTuple = S extends [] ? [] : S extends [infer H, ...infer R] ? H extends `:${infer P}` ? [P, ...ExtractParamsFromTuple] : H extends `*${infer C}` ? C extends '' ? ExtractParamsFromTuple : [C, ...ExtractParamsFromTuple] : ExtractParamsFromTuple : never; ``` **References:** [ExtractParamsFromTuple](#ui-extractparamsfromtuple) --- ## ui.getabsoluterect: getAbsoluteRect() function Gets the absolute rectangle of an element relative to the document. This function calculates the element's position relative to the entire document (including scroll offset), rather than just the viewport. It combines the element's bounding client rectangle with the current scroll position to provide absolute coordinates. **Signature:**```typescript export declare function getAbsoluteRect(el: HTMLElement): Rect; ```## ui.getabsoluterect: Parameters | Parameter | Type | Description | | --- | --- | --- | | el | HTMLElement | The DOM element to get the absolute rectangle for | **Returns:** [Rect](#ui-rect) A Rect instance representing the element's absolute position and size ## ui.getabsoluterect: Example```typescript const element = document.getElementById('myElement'); const absoluteRect = getAbsoluteRect(element); console.log(absoluteRect.left); // Absolute x position in document console.log(absoluteRect.top); // Absolute y position in document console.log(absoluteRect.width); // Element width console.log(absoluteRect.height); // Element height ``` --- ## ui.handleanchorclick: handleAnchorClick() function Handles anchor click events, optionally checking for external URLs and file extensions. **Signature:**```typescript handleAnchorClick: (callback: () => boolean, options?: HandleAnchorClickOptions) => (e: MouseEvent) => void ```## ui.handleanchorclick: Parameters | Parameter | Type | Description | | --- | --- | --- | | callback | () => boolean | A function that is called when the anchor click should be handled. The function should return a boolean indicating whether the default anchor click behavior should be prevented. | | options | [HandleAnchorClickOptions](#ui-handleanchorclickoptions) | _(Optional)_ An optional object of type `HandleAnchorClickOptions`. | **Returns:** (e: MouseEvent) => void A function that handles the anchor click event, calling the provided callback and preventing the default behavior if the callback returns `true`. --- ## ui.handleanchorclickoptions: HandleAnchorClickOptions type Options for handling anchor click events. **Signature:**```typescript export type HandleAnchorClickOptions = Merge<{ ignoreUrlWithExtension?: true; allowedExtensions?: string[]; } | { ignoreUrlWithExtension: false; }, { ignoreExternalUrl?: boolean; }>; ``` --- ## ui.hiddenwhenempty: HiddenWhenEmpty variable Hides the element when it is empty and restores its initial state when necessary. **Signature:**```typescript HiddenWhenEmpty: Renderable ``` --- ## ui.hreforanchoroptions: HrefOrAnchorOptions type Represents either a string value (or Signal of string) for the href, or a full AnchorOptions object. This type is used as the first parameter of the Anchor function, allowing for flexible configuration of anchor elements. **Signature:**```typescript export type HrefOrAnchorOptions = Value | AnchorOptions; ``` **References:** [AnchorOptions](#ui-anchoroptions) --- ## ui.htmltitle: HTMLTitle() function Creates an HTML title element with the specified title. **Signature:**```typescript HTMLTitle: (title: Value) => import('@tempots/dom').Renderable ```## ui.htmltitle: Parameters | Parameter | Type | Description | | --- | --- | --- | | title | Value<string> | The title to be set for the HTML title element. | **Returns:** import('@tempots/dom').Renderable The created HTML title element. --- ## ui.inviewport: InViewport() function Creates a component that tracks whether an element is visible in the viewport. This component uses the Intersection Observer API to efficiently detect when an element enters or exits the viewport. It's perfect for implementing lazy loading, infinite scrolling, animations on scroll, and other viewport-based interactions. **Signature:**```typescript InViewport: ({ mode, once }: InViewportOptions, fn: (value: Signal) => TNode) => Renderable ```## ui.inviewport: Parameters | Parameter | Type | Description | | --- | --- | --- | | { mode, once } | [InViewportOptions](#ui-inviewportoptions) | | | fn | (value: Signal<boolean>) => TNode | Function that receives the visibility signal and returns content to render | **Returns:** Renderable A renderable component that tracks viewport visibility ## ui.inviewport: Example 1```typescript // Basic viewport detection InViewport( { mode: 'partial' }, (isVisible) => html.div( attr.class(isVisible.map(v => v ? 'visible' : 'hidden')), 'This element changes class when visible' ) ) ``` ## ui.inviewport: Example 2 ```typescript // Lazy load images const imageUrl = 'https://example.com/large-image.jpg' InViewport( { mode: 'partial', once: true }, (isVisible) => isVisible.value ? html.img(attr.src(imageUrl), attr.alt('Lazy loaded image')) : html.div(attr.class('placeholder'), 'Loading...') ) ``` ## ui.inviewport: Example 3 ```typescript // Infinite scrolling trigger const loadMore = () => { // Load more data console.log('Loading more items...') } html.div( ForEach(items, item => ItemComponent(item)), InViewport( { mode: 'partial' }, (isVisible) => { // Trigger load more when sentinel comes into view isVisible.on(visible => { if (visible) loadMore() }) return html.div(attr.class('loading-sentinel'), 'Loading more...') } ) ) ``` ## ui.inviewport: Example 4 ```typescript // Animation on scroll InViewport( { mode: 'full' }, // Only trigger when fully visible (isVisible) => html.div( attr.class(isVisible.map(v => v ? 'animate-fade-in' : 'opacity-0' )), 'This animates when fully in view' ) ) ``` --- ## ui.inviewportmode: InViewportMode type Represents the mode for determining if an element is in the viewport. - `partial`: Indicates that the element is considered in the viewport if any part of it is visible. - `full`: Indicates that the element is considered in the viewport only if it is fully visible. **Signature:**```typescript export type InViewportMode = 'partial' | 'full'; ``` --- ## ui.inviewportoptions: InViewportOptions type **Signature:**```typescript export type InViewportOptions = { mode?: InViewportMode; once?: boolean; }; ``` **References:** [InViewportMode](#ui-inviewportmode) --- ## ui.keycombo: KeyCombo type **Signature:**```typescript export type KeyCombo = { key?: string; code?: string; ctrlKey?: boolean; altKey?: boolean; shiftKey?: boolean; metaKey?: boolean; repeat?: boolean; commandOrControlKey?: boolean; }; ``` --- ## ui.location_2: Location\_2 variable Provider exposing the LocationHandle for navigation and location state. **Signature:**```typescript Location: Provider ``` --- ## ui.locationdata: LocationData type Represents the data for a location. **Signature:**```typescript export type LocationData = { readonly pathname: string; readonly search: Record; readonly hash?: string; }; ``` --- ## ui.locationdraft: LocationDraft type Draft object provided inside `LocationHandle.run` for staged updates. **Signature:**```typescript export type LocationDraft = { readonly location: LocationData; setLocation: (data: LocationData) => LocationDraft; setPathname: (pathname: string) => LocationDraft; setHash: (hash: string | undefined | null) => LocationDraft; clearHash: () => LocationDraft; setSearch: (entries: Record) => LocationDraft; setSearchParam: (key: string, value: string | null | undefined) => LocationDraft; updateSearch: (updater: (curr: Record) => Record) => LocationDraft; }; ``` **References:** [LocationData](#ui-locationdata), [LocationDraft](#ui-locationdraft) --- ## ui.locationfromurl: locationFromURL() function Converts a URL string into a LocationData object. **Signature:**```typescript locationFromURL: (url: string, baseUrl?: string) => LocationData ```## ui.locationfromurl: Parameters | Parameter | Type | Description | | --- | --- | --- | | url | string | The URL string to convert. | | baseUrl | string | _(Optional)_ | **Returns:** [LocationData](#ui-locationdata) The LocationData object representing the URL. --- ## ui.locationhandle: LocationHandle type A read/write navigation handle exposed by the Location provider. **Signature:**```typescript export type LocationHandle = { readonly location: Signal; readonly url: Signal; readonly pathname: Signal; readonly search: Signal>; readonly hash: Signal; setLocation: (data: LocationData, options?: NavigationOptions) => void; updateLocation: (updater: (curr: LocationData) => LocationData, options?: NavigationOptions) => void; navigate: (url: string, options?: NavigationOptions) => void; replace: (url: string, options?: NavigationOptions) => void; back: (options?: NavigationOptions) => void; forward: (options?: NavigationOptions) => void; go: (delta: number, options?: NavigationOptions) => void; setPathname: (pathname: string, options?: NavigationOptions) => void; setHash: (hash: string | undefined | null, options?: NavigationOptions) => void; clearHash: (options?: NavigationOptions) => void; setSearch: (entries: Record, options?: NavigationOptions) => void; setSearchParam: (key: string, value: string | null | undefined, options?: NavigationOptions) => void; updateSearch: (updater: (curr: Record) => Record, options?: NavigationOptions) => void; queryParam: (key: string) => Signal; run: (mutate: (draft: LocationDraft) => void, options?: NavigationOptions) => void; match: (matcher: string | RegExp | ((location: LocationData) => boolean), options?: LocationMatchOptions) => boolean; matchSignal: (matcher: SplitValue boolean)>, options?: LocationMatchOptions) => Signal; }; ``` **References:** [LocationData](#ui-locationdata), [NavigationOptions](#ui-navigationoptions), [LocationDraft](#ui-locationdraft), [LocationMatchOptions](#ui-locationmatchoptions) --- ## ui.locationmatchoptions: LocationMatchOptions type Options that control how `LocationHandle.match` and `matchSignal` interpret URL parts. **Signature:**```typescript export type LocationMatchOptions = { includeSearch?: boolean; includeHash?: boolean; ignoreSearchParams?: string[]; }; ``` --- ## ui.makemutationresource: makeMutationResource() function **Signature:**```typescript makeMutationResource: ({ mutate, convertError, onSuccess, onError, onSettled, }: { mutate: (options: MutationResourceExecuteOptions) => Promise; convertError: (error: unknown) => E; onSuccess?: (value: Res, req: Req) => void; onError?: (error: E, req: Req) => void; onSettled?: (result: AsyncResult, req: Req) => void; }) => MutationResource ```## ui.makemutationresource: Parameters | Parameter | Type | Description | | --- | --- | --- | | { mutate, convertError, onSuccess, onError, onSettled, } | { mutate: (options: [MutationResourceExecuteOptions](#ui-mutationresourceexecuteoptions)<Req, Res, E>) => Promise<Res>; convertError: (error: unknown) => E; onSuccess?: (value: Res, req: Req) => void; onError?: (error: E, req: Req) => void; onSettled?: (result: AsyncResult<Res, E>, req: Req) => void; } | | **Returns:** [MutationResource](#ui-mutationresource)<Req, Res, E> --- ## ui.makeparams: MakeParams type Represents a type that transforms a tuple of strings into an object with string keys. If the input type is a tuple, each element of the tuple will become a key in the resulting object, with the corresponding value being a string. If the input type is not a tuple, the resulting type will be `never`. **Signature:**```typescript export type MakeParams

= P extends string[] ? { [K in TupleToUnion

]: string; } : never; ``` --- ## ui.makequeryresource: makeQueryResource() function Creates an asynchronous query that can be loaded, reloaded, and disposed of. **Signature:**```typescript makeQueryResource: ({ request, load, convertError, onSuccess, onError, onSettled, }: { request: Value; load: (options: QueryResourceLoadOptions) => Promise; convertError: (error: unknown) => E; onSuccess?: (value: Res, req: Req) => void; onError?: (error: E, req: Req) => void; onSettled?: (result: AsyncResult, req: Req) => void; }) => QueryResource ```## ui.makequeryresource: Parameters | Parameter | Type | Description | | --- | --- | --- | | { request, load, convertError, onSuccess, onError, onSettled, } | { request: Value<Req>; load: (options: [QueryResourceLoadOptions](#ui-queryresourceloadoptions)<Req, Res, E>) => Promise<Res>; convertError: (error: unknown) => E; onSuccess?: (value: Res, req: Req) => void; onError?: (error: E, req: Req) => void; onSettled?: (result: AsyncResult<Res, E>, req: Req) => void; } | | **Returns:** [QueryResource](#ui-queryresource)<Res, E> The created asynchronous query. --- ## ui.matcheskeycombo: matchesKeyCombo() function **Signature:**```typescript export declare function matchesKeyCombo(keyCombo: KeyCombo | string, event: KeyboardEvent): boolean; ```## ui.matcheskeycombo: Parameters | Parameter | Type | Description | | --- | --- | --- | | keyCombo | [KeyCombo](#ui-keycombo) \\| string | | | event | KeyboardEvent | | **Returns:** boolean --- ## ui.matchesroute: matchesRoute() function Matches a path against a route. **Signature:**```typescript matchesRoute:

(route: Route, path: P) => MatchResult

```## ui.matchesroute: Parameters | Parameter | Type | Description | | --- | --- | --- | | route | [Route](#ui-route) | The route to match against. | | path | P | The path to match. | **Returns:** [MatchResult](#ui-matchresult)<P> The match result. --- ## ui.matchresult: MatchResult type The result of a route match. **Signature:**```typescript export type MatchResult

= { params: ExtractParams

; path: P; } | null; ``` **References:** [ExtractParams](#ui-extractparams) --- ## ui.matchresultwithroute: MatchResultWithRoute type The result of a route match with the matched route. **Signature:**```typescript export type MatchResultWithRoute

= { params: ExtractParams

; route: R; path: P; } | null; ``` **References:** [ExtractParams](#ui-extractparams) --- ## ui package ## ui: Classes | Class | Description | | --- | --- | | [Rect](#ui-rect) | Represents a rectangle with position and dimensions. A Rect defines a rectangular area in 2D space with a position (left, top) and dimensions (width, height). It provides convenient methods for accessing computed properties like right, bottom, center, and size. | | [Ticker](#ui-ticker) | A property that can be used to force an update. Internally, it's a number that is incremented by one on each tick. Extends the Prop class with a number value. It can be used as a counter Signal. | ## ui: Functions | Function | Description | | --- | --- | | [Anchor(hrefOrOptions, children)](#ui-anchor) | Creates an anchor element with the specified href and children. When the anchor element is clicked, the location is updated to the specified href. | | [areLocationsEqual(a, b)](#ui-arelocationsequal) | Compares two location objects and returns true if they are equal, false otherwise. | | [AsyncResultView(result, options)](#ui-asyncresultview) | Renders the view based on the result of an asynchronous operation. | | [AutoFocus(delay)](#ui-autofocus) | Automatically focuses an element when it's rendered to the DOM. This utility is commonly used for form inputs, modals, or any interactive element that should receive focus immediately when it appears. The small default delay ensures the element is fully rendered before attempting to focus. | | [AutoSelect(delay)](#ui-autoselect) | Automatically selects all text content in an input element when it's rendered. This utility is particularly useful for input fields where you want the user to be able to immediately start typing to replace the existing content, or easily copy the current value. The small default delay ensures the element is fully rendered before attempting to select. | | [ChildRouter(routes)](#ui-childrouter) | Creates a nested router that matches against the remaining path from parent routers. ChildRouter is used for nested routing scenarios where a parent router (RootRouter or another ChildRouter) has matched a portion of the path and passed the remaining path to child components. ChildRouter reads the parent routing context and matches its routes against the remaining path. | | [classes(obj)](#ui-classes) | Creates a renderable that applies classes based on a record of boolean signals. | | [ElementRect(fn)](#ui-elementrect) | Creates a renderable function that monitors the size of an element and provides it as a signal. | | [evaluateLocationMatch(location, matcher, options)](#ui-evaluatelocationmatch) | | | [getAbsoluteRect(el)](#ui-getabsoluterect) | Gets the absolute rectangle of an element relative to the document. This function calculates the element's position relative to the entire document (including scroll offset), rather than just the viewport. It combines the element's bounding client rectangle with the current scroll position to provide absolute coordinates. | | [handleAnchorClick(callback, options)](#ui-handleanchorclick) | Handles anchor click events, optionally checking for external URLs and file extensions. | | [HTMLTitle(title)](#ui-htmltitle) | Creates an HTML title element with the specified title. | | [InViewport({ mode, once }, fn)](#ui-inviewport) | Creates a component that tracks whether an element is visible in the viewport. This component uses the Intersection Observer API to efficiently detect when an element enters or exits the viewport. It's perfect for implementing lazy loading, infinite scrolling, animations on scroll, and other viewport-based interactions. | | [locationFromURL(url, baseUrl)](#ui-locationfromurl) | Converts a URL string into a LocationData object. | | [makeMutationResource({ mutate, convertError, onSuccess, onError, onSettled, })](#ui-makemutationresource) | | | [makeQueryResource({ request, load, convertError, onSuccess, onError, onSettled, })](#ui-makequeryresource) | Creates an asynchronous query that can be loaded, reloaded, and disposed of. | | [matchesKeyCombo(keyCombo, event)](#ui-matcheskeycombo) | | | [matchesRoute(route, path)](#ui-matchesroute) | Matches a path against a route. | | [Mutation({ mutate, convertError, onSuccess, onError, onSettled, content, })](#ui-mutation) | Creates a reactive mutation component for handling asynchronous data loading. This component provides a declarative way to handle async operations with proper loading, success, and error states. It automatically manages the lifecycle of async requests and provides reload functionality. | | [MutationDisplay(resource, options)](#ui-mutationdisplay) | Component to display an asynchronous mutation based on its current status. | | [nowSignal(frequency)](#ui-nowsignal) | Creates a signal that automatically updates with the current time at a specified frequency. The signal will clean up its interval when disposed. | | [OnClickOutside(handler)](#ui-onclickoutside) | Executes a callback function when a click event occurs outside of the parent element. | | [OnEnterKey(handler)](#ui-onenterkey) | | | [OnEscapeKey(handler)](#ui-onescapekey) | | | [OnKeyPressed({ allowedKeys, handler, })](#ui-onkeypressed) | | | [PopOver(fn, options)](#ui-popover) | Creates a pop-over component. | | [Query({ request, load, convertError, onSuccess, onError, onSettled, success, pending, failure, })](#ui-query) | Creates a reactive query component for handling asynchronous data loading. This component provides a declarative way to handle async operations with proper loading, success, and error states. It automatically manages the lifecycle of async requests and provides reload functionality. | | [QueryDisplay(query, options)](#ui-querydisplay) | Component to display an asynchronous query based on its current status. | | [relativeTime(date, options)](#ui-relativetime) | Creates a signal that computes a human-readable relative time string between a target date and a reference date. | | [relativeTimeMillisSignal(date, { now, frequency })](#ui-relativetimemillissignal) | Creates a signal that computes the time difference in milliseconds between a target date and a reference date. | | [relativeTimeSignal(date, options)](#ui-relativetimesignal) | Creates a signal that computes a human-readable relative time string between a target date and a reference date. | | [ResultView(result, options)](#ui-resultview) | Renders a view based on the result of a computation. | | [RootRouter(routes)](#ui-rootrouter) | Creates the root router for an application that provides routing context to child components. RootRouter is the top-level router that matches against the full browser pathname and creates the initial routing context. It provides the RouterContextProvider that child ChildRouter components can use for nested routing scenarios. | | [SelectOnFocus()](#ui-selectonfocus) | Selects the text inside an input element when it receives focus. | | [ticker(initial)](#ui-ticker) | Creates a new Ticker instance with an optional initial value. | | [timeDiffToString(diffInMillis)](#ui-timedifftostring) | Converts a time difference in milliseconds to a human-readable relative time string. | | [urlFromLocation(location)](#ui-urlfromlocation) | Returns the full URL based on the provided location data. | | [useAppearance()](#ui-useappearance) | Creates a signal that represents the current appearance (light or dark) based on the user's system preferences. The appearance is updated whenever the user's system preferences change, and the signal is cleaned up when it is no longer needed. | | [WhenInViewport(options, then, otherwise)](#ui-wheninviewport) | Conditionally renders content based on whether an element is in the viewport. This is a convenience wrapper around `InViewport` that provides a simpler API for cases where you just want to show/hide content based on viewport visibility. It's perfect for simple lazy loading or reveal animations. | | [WindowSize(fn)](#ui-windowsize) | Creates a renderable function that monitors the window size and invokes the provided function with the current size. | ## ui: Interfaces | Interface | Description | | --- | --- | | [MutationContentOptions](#ui-mutationcontentoptions) | | | [MutationDisplayOptions](#ui-mutationdisplayoptions) | Options for displaying the different states of an asynchronous resource. | | [MutationResource](#ui-mutationresource) | A write-side wrapper for async state around POST/PUT/PATCH/DELETE. Mirrors AsyncResource but the action is explicit (execute), not implicit (reload). | | [MutationResourceExecuteOptions](#ui-mutationresourceexecuteoptions) | Execution-time options for a mutation. Useful for optimistic UI and side-effects. | | [QueryDisplayOptions](#ui-querydisplayoptions) | Options for displaying the different states of an asynchronous query. | | [QueryResource](#ui-queryresource) | Represents an asynchronous query with its current status, value, error, and loading state. Provides methods to reload the query and dispose of it. | | [QueryResourceLoadOptions](#ui-queryresourceloadoptions) | Options for loading a query, including the request, abort signal, and previous result. | | [RouterContext](#ui-routercontext) | Represents the context information for a router level in nested routing. Each router level (AppRouter or SubRouter) creates a RouterContext that contains information about the matched path, remaining path for child routers, and accumulated parameters from all parent router levels. | ## ui: Variables | Variable | Description | | --- | --- | | [allPlacements](#ui-allplacements) | Represents all possible placements for a pop-over. | | [Appearance](#ui-appearance) | A provider that provides a child component with an appearance context, which can be used to determine the current appearance (light or dark) based on the user's system preferences. The appearance context is updated whenever the user's system preferences change, and the component is cleaned up when it is no longer needed. | | [HiddenWhenEmpty](#ui-hiddenwhenempty) | Hides the element when it is empty and restores its initial state when necessary. | | [Location\_2](#ui-location2) | Provider exposing the LocationHandle for navigation and location state. | | [NavigationService](#ui-navigationservice) | | | [RouterContextProvider](#ui-routercontextprovider) | Provider for router context stack in nested routing scenarios. The RouterContextProvider maintains a stack of RouterContext objects, where each level represents a router in the nested hierarchy. Child routers can access the context stack to determine what path remains to be processed and what parameters have been accumulated from parent router levels. | ## ui: Type Aliases | Type Alias | Description | | --- | --- | | [AnchorOptions](#ui-anchoroptions) | Options for configuring an anchor element. | | [AppearanceType](#ui-appearancetype) | Defines the possible appearance types for the application. | | [AsyncResultViewOptions](#ui-asyncresultviewoptions) | Represents the options for rendering an asynchronous result view. | | [ExtractParams](#ui-extractparams) | Extracts the parameters from a string literal representing a route path. | | [ExtractParamsFromTuple](#ui-extractparamsfromtuple) | Extracts the parameter names from a tuple type. | | [HandleAnchorClickOptions](#ui-handleanchorclickoptions) | Options for handling anchor click events. | | [HrefOrAnchorOptions](#ui-hreforanchoroptions) | Represents either a string value (or Signal of string) for the href, or a full AnchorOptions object. This type is used as the first parameter of the Anchor function, allowing for flexible configuration of anchor elements. | | [InViewportMode](#ui-inviewportmode) | Represents the mode for determining if an element is in the viewport. - `partial`: Indicates that the element is considered in the viewport if any part of it is visible. - `full`: Indicates that the element is considered in the viewport only if it is fully visible. | | [InViewportOptions](#ui-inviewportoptions) | | | [KeyCombo](#ui-keycombo) | | | [LocationData](#ui-locationdata) | Represents the data for a location. | | [LocationDraft](#ui-locationdraft) | Draft object provided inside `LocationHandle.run` for staged updates. | | [LocationHandle](#ui-locationhandle) | A read/write navigation handle exposed by the Location provider. | | [LocationMatchOptions](#ui-locationmatchoptions) | Options that control how `LocationHandle.match` and `matchSignal` interpret URL parts. | | [MakeParams](#ui-makeparams) | Represents a type that transforms a tuple of strings into an object with string keys. If the input type is a tuple, each element of the tuple will become a key in the resulting object, with the corresponding value being a string. If the input type is not a tuple, the resulting type will be `never`. | | [MatchResult](#ui-matchresult) | The result of a route match. | | [MatchResultWithRoute](#ui-matchresultwithroute) | The result of a route match with the matched route. | | [NavigationOptions](#ui-navigationoptions) | Configuration applied when committing a navigation update. | | [Placement](#ui-placement) | Represents the placement options for a pop-over. | | [PopOverArrowOptions](#ui-popoverarrowoptions) | Represents the options for the arrow of a pop-over. | | [PopOverOptions](#ui-popoveroptions) | Represents the properties for a pop-over. | | [ResultViewOptions](#ui-resultviewoptions) | Represents the signal for a result. | | [Route](#ui-route) | Represents a route in the application. | | [RouteCatchAll](#ui-routecatchall) | Represents a catch-all route. | | [RouteInfo](#ui-routeinfo) | Represents information about a route. | | [RouteLiteral](#ui-routeliteral) | Represents a literal route. | | [RouteParam](#ui-routeparam) | Represents a route parameter. | | [RouteSegment](#ui-routesegment) | Represents a segment of a route. | --- ## ui.mutation: Mutation() function Creates a reactive mutation component for handling asynchronous data loading. This component provides a declarative way to handle async operations with proper loading, success, and error states. It automatically manages the lifecycle of async requests and provides reload functionality. **Signature:**```typescript Mutation: ({ mutate, convertError, onSuccess, onError, onSettled, content, }: { mutate: (options: MutationResourceExecuteOptions) => Promise; convertError?: (error: unknown) => E; onSuccess?: (value: Res, req: Req) => void; onError?: (error: E, req: Req) => void; onSettled?: (result: AsyncResult, req: Req) => void; } & MutationDisplayOptions) => Renderable ```## ui.mutation: Parameters | Parameter | Type | Description | | --- | --- | --- | | { mutate, convertError, onSuccess, onError, onSettled, content, } | { mutate: (options: [MutationResourceExecuteOptions](#ui-mutationresourceexecuteoptions)<Req, Res, E>) => Promise<Res>; convertError?: (error: unknown) => E; onSuccess?: (value: Res, req: Req) => void; onError?: (error: E, req: Req) => void; onSettled?: (result: AsyncResult<Res, E>, req: Req) => void; } & [MutationDisplayOptions](#ui-mutationdisplayoptions)<Req, Res, E> | | **Returns:** Renderable {Renderable} A node representing the current state of the resource. --- ## ui.mutationcontentoptions.cancel: MutationContentOptions.cancel property **Signature:**```typescript cancel: (newState?: NonLoading) => void; ``` --- ## ui.mutationcontentoptions.error: MutationContentOptions.error property **Signature:**```typescript error: Signal; ``` --- ## ui.mutationcontentoptions.execute: MutationContentOptions.execute property **Signature:**```typescript execute: (request: Req) => void; ``` --- ## ui.mutationcontentoptions: MutationContentOptions interface **Signature:**```typescript export interface MutationContentOptions ```## ui.mutationcontentoptions: Properties | Property | Modifiers | Type | Description | | --- | --- | --- | --- | | [cancel](#ui-mutationcontentoptions-cancel) | | (newState?: NonLoading<Res, E>) => void | | | [error](#ui-mutationcontentoptions-error) | | Signal<E \\| undefined> | | | [execute](#ui-mutationcontentoptions-execute) | | (request: Req) => void | | | [pending](#ui-mutationcontentoptions-pending) | | Signal<boolean> | | | [previous](#ui-mutationcontentoptions-previous) | | Signal<Res \\| undefined> | | | [status](#ui-mutationcontentoptions-status) | | Signal<AsyncResult<Res, E>> | | | [value](#ui-mutationcontentoptions-value) | | Signal<Res \\| undefined> | | --- ## ui.mutationcontentoptions.pending: MutationContentOptions.pending property **Signature:**```typescript pending: Signal; ``` --- ## ui.mutationcontentoptions.previous: MutationContentOptions.previous property **Signature:**```typescript previous: Signal; ``` --- ## ui.mutationcontentoptions.status: MutationContentOptions.status property **Signature:**```typescript status: Signal>; ``` --- ## ui.mutationcontentoptions.value: MutationContentOptions.value property **Signature:**```typescript value: Signal; ``` --- ## ui.mutationdisplay: MutationDisplay() function Component to display an asynchronous mutation based on its current status. **Signature:**```typescript MutationDisplay: (resource: MutationResource, options: MutationDisplayOptions) => Renderable ```## ui.mutationdisplay: Parameters | Parameter | Type | Description | | --- | --- | --- | | resource | [MutationResource](#ui-mutationresource)<Req, Res, E> | The asynchronous resource to display. | | options | [MutationDisplayOptions](#ui-mutationdisplayoptions)<Req, Res, E> | The display options for the resource. | **Returns:** Renderable {Renderable} A node representing the current state of the resource. --- ## ui.mutationdisplayoptions.content: MutationDisplayOptions.content property Function to render when the query is loading. **Signature:**```typescript content: (options: MutationContentOptions) => TNode; ``` --- ## ui.mutationdisplayoptions: MutationDisplayOptions interface Options for displaying the different states of an asynchronous resource. **Signature:**```typescript export interface MutationDisplayOptions ```## ui.mutationdisplayoptions: Properties | Property | Modifiers | Type | Description | | --- | --- | --- | --- | | [content](#ui-mutationdisplayoptions-content) | | (options: [MutationContentOptions](#ui-mutationcontentoptions)<Req, Res, E>) => TNode | Function to render when the query is loading. | --- ## ui.mutationresource.cancel: MutationResource.cancel property Abort the current in-flight request (if any) and clean up. **Signature:**```typescript readonly cancel: (newState?: NonLoading) => void; ``` --- ## ui.mutationresource.dispose: MutationResource.dispose property Dispose of resources, aborting any in-flight request. **Signature:**```typescript readonly dispose: () => void; ``` --- ## ui.mutationresource.error: MutationResource.error property Latest error (if any). **Signature:**```typescript readonly error: Signal; ``` --- ## ui.mutationresource.execute: MutationResource.execute property Execute the mutation. **Signature:**```typescript readonly execute: (request: Req, options?: MutationResourceExecuteOptions) => void; ``` --- ## ui.mutationresource: MutationResource interface A write-side wrapper for async state around POST/PUT/PATCH/DELETE. Mirrors AsyncResource but the action is explicit (execute), not implicit (reload). **Signature:**```typescript export interface MutationResource ```## ui.mutationresource: Properties | Property | Modifiers | Type | Description | | --- | --- | --- | --- | | [cancel](#ui-mutationresource-cancel) | `readonly` | (newState?: NonLoading<Res, E>) => void | Abort the current in-flight request (if any) and clean up. | | [dispose](#ui-mutationresource-dispose) | `readonly` | () => void | Dispose of resources, aborting any in-flight request. | | [error](#ui-mutationresource-error) | `readonly` | Signal<E \\| undefined> | Latest error (if any). | | [execute](#ui-mutationresource-execute) | `readonly` | (request: Req, options?: [MutationResourceExecuteOptions](#ui-mutationresourceexecuteoptions)<Req, Res, E>) => void | Execute the mutation. | | [pending](#ui-mutationresource-pending) | `readonly` | Signal<boolean> | Whether a mutation is currently in flight. | | [status](#ui-mutationresource-status) | `readonly` | Signal<AsyncResult<Res, E>> | Current async status (Idle \\| Loading \\| Success \\| Failure). | | [value](#ui-mutationresource-value) | `readonly` | Signal<Res \\| undefined> | Latest successful value (if any). | --- ## ui.mutationresource.pending: MutationResource.pending property Whether a mutation is currently in flight. **Signature:**```typescript readonly pending: Signal; ``` --- ## ui.mutationresource.status: MutationResource.status property Current async status (Idle \| Loading \| Success \| Failure). **Signature:**```typescript readonly status: Signal>; ``` --- ## ui.mutationresource.value: MutationResource.value property Latest successful value (if any). **Signature:**```typescript readonly value: Signal; ``` --- ## ui.mutationresourceexecuteoptions.abortsignal: MutationResourceExecuteOptions.abortSignal property External abort signal for this single execution. **Signature:**```typescript readonly abortSignal: AbortSignal; ``` --- ## ui.mutationresourceexecuteoptions: MutationResourceExecuteOptions interface Execution-time options for a mutation. Useful for optimistic UI and side-effects. **Signature:**```typescript export interface MutationResourceExecuteOptions ```## ui.mutationresourceexecuteoptions: Properties | Property | Modifiers | Type | Description | | --- | --- | --- | --- | | [abortSignal](#ui-mutationresourceexecuteoptions-abortsignal) | `readonly` | AbortSignal | External abort signal for this single execution. | | [onError?](#ui-mutationresourceexecuteoptions-onerror) | `readonly` | (error: E, req: Req) => void | _(Optional)_ | | [onSettled?](#ui-mutationresourceexecuteoptions-onsettled) | `readonly` | (result: AsyncResult<Res, E>, req: Req) => void | _(Optional)_ | | [onSuccess?](#ui-mutationresourceexecuteoptions-onsuccess) | `readonly` | (value: Res, req: Req) => void | _(Optional)_ Side-effects | | [optimisticFromRequest?](#ui-mutationresourceexecuteoptions-optimisticfromrequest) | `readonly` | (req: Req) => Res | _(Optional)_ Optionally derive an optimistic value from the request. Runs only if optimisticValue is not provided. | | [optimisticValue?](#ui-mutationresourceexecuteoptions-optimisticvalue) | `readonly` | Res | _(Optional)_ Optionally provide an optimistic value to set immediately. This will set status to Loading with value prefilled. | | [previous](#ui-mutationresourceexecuteoptions-previous) | `readonly` | AsyncResult<Res, E> | The previous result of the mutation, if any. | | [request](#ui-mutationresourceexecuteoptions-request) | `readonly` | Req | The request to execute the mutation. | --- ## ui.mutationresourceexecuteoptions.onerror: MutationResourceExecuteOptions.onError property **Signature:**```typescript readonly onError?: (error: E, req: Req) => void; ``` --- ## ui.mutationresourceexecuteoptions.onsettled: MutationResourceExecuteOptions.onSettled property **Signature:**```typescript readonly onSettled?: (result: AsyncResult, req: Req) => void; ``` --- ## ui.mutationresourceexecuteoptions.onsuccess: MutationResourceExecuteOptions.onSuccess property Side-effects **Signature:**```typescript readonly onSuccess?: (value: Res, req: Req) => void; ``` --- ## ui.mutationresourceexecuteoptions.optimisticfromrequest: MutationResourceExecuteOptions.optimisticFromRequest property Optionally derive an optimistic value from the request. Runs only if optimisticValue is not provided. **Signature:**```typescript readonly optimisticFromRequest?: (req: Req) => Res; ``` --- ## ui.mutationresourceexecuteoptions.optimisticvalue: MutationResourceExecuteOptions.optimisticValue property Optionally provide an optimistic value to set immediately. This will set status to Loading with value prefilled. **Signature:**```typescript readonly optimisticValue?: Res; ``` --- ## ui.mutationresourceexecuteoptions.previous: MutationResourceExecuteOptions.previous property The previous result of the mutation, if any. **Signature:**```typescript readonly previous: AsyncResult; ``` --- ## ui.mutationresourceexecuteoptions.request: MutationResourceExecuteOptions.request property The request to execute the mutation. **Signature:**```typescript readonly request: Req; ``` --- ## ui.navigationoptions: NavigationOptions type Configuration applied when committing a navigation update. **Signature:**```typescript export type NavigationOptions = { state?: unknown; scroll?: 'preserve' | 'auto'; viewTransition?: boolean; replace?: boolean; }; ``` --- ## ui.navigationservice: NavigationService variable **Signature:**```typescript NavigationService: NavigationServiceImpl ``` --- ## ui.nowsignal: nowSignal() function Creates a signal that automatically updates with the current time at a specified frequency. The signal will clean up its interval when disposed. **Signature:**```typescript nowSignal: (frequency?: number) => Signal ```## ui.nowsignal: Parameters | Parameter | Type | Description | | --- | --- | --- | | frequency | number | _(Optional)_ Milliseconds between updates (defaults to 1000ms/1 second) | **Returns:** Signal<Date> A Value that updates with the current time at the specified frequency --- ## ui.onclickoutside: OnClickOutside() function Executes a callback function when a click event occurs outside of the parent element. **Signature:**```typescript export declare function OnClickOutside(handler: (event: MouseEvent) => void): import('@tempots/dom').Renderable; ```## ui.onclickoutside: Parameters | Parameter | Type | Description | | --- | --- | --- | | handler | (event: MouseEvent) => void | The callback function to be executed when a click event occurs outside of the parent element. | **Returns:** import('@tempots/dom').Renderable A renderable function that takes a DOMContext and returns a function that takes a boolean indicating whether to remove the tree. --- ## ui.onenterkey: OnEnterKey() function **Signature:**```typescript export declare function OnEnterKey(handler: (event: KeyboardEvent) => void): import('@tempots/dom').Renderable; ```## ui.onenterkey: Parameters | Parameter | Type | Description | | --- | --- | --- | | handler | (event: KeyboardEvent) => void | | **Returns:** import('@tempots/dom').Renderable --- ## ui.onescapekey: OnEscapeKey() function **Signature:**```typescript export declare function OnEscapeKey(handler: (event: KeyboardEvent) => void): import('@tempots/dom').Renderable; ```## ui.onescapekey: Parameters | Parameter | Type | Description | | --- | --- | --- | | handler | (event: KeyboardEvent) => void | | **Returns:** import('@tempots/dom').Renderable --- ## ui.onkeypressed: OnKeyPressed() function **Signature:**```typescript export declare function OnKeyPressed({ allowedKeys, handler, }: { allowedKeys: (KeyCombo | string)[]; handler: (event: KeyboardEvent) => void; }): import('@tempots/dom').Renderable; ```## ui.onkeypressed: Parameters | Parameter | Type | Description | | --- | --- | --- | | { allowedKeys, handler, } | { allowedKeys: ([KeyCombo](#ui-keycombo) \\| string)\[\]; handler: (event: KeyboardEvent) => void; } | | **Returns:** import('@tempots/dom').Renderable --- ## ui.placement: Placement type Represents the placement options for a pop-over. **Signature:**```typescript export type Placement = 'top' | 'top-start' | 'top-end' | 'right' | 'right-start' | 'right-end' | 'bottom' | 'bottom-start' | 'bottom-end' | 'left' | 'left-start' | 'left-end'; ``` --- ## ui.popover: PopOver() function Creates a pop-over component. **Signature:**```typescript PopOver: (fn: (open: (options: PopOverOptions) => void, close: () => void) => TNode, options?: { isOpen: Value; }) => import('@tempots/dom').Renderable ```## ui.popover: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn | (open: (options: [PopOverOptions](#ui-popoveroptions)) => void, close: () => void) => TNode | A function that returns the content of the pop-over. | | options | { isOpen: Value<boolean>; } | _(Optional)_ The options for the pop-over. | **Returns:** import('@tempots/dom').Renderable<import('@tempots/dom').DOMContext> The pop-over component. --- ## ui.popoverarrowoptions: PopOverArrowOptions type Represents the options for the arrow of a pop-over. **Signature:**```typescript export type PopOverArrowOptions = { x?: number; y?: number; centerOffset: number; alignmentOffset?: number; placement: Placement; containerWidth: number; containerHeight: number; }; ``` **References:** [Placement](#ui-placement) --- ## ui.popoveroptions: PopOverOptions type Represents the properties for a pop-over. **Signature:**```typescript export type PopOverOptions = { content: TNode; placement?: Value; mainAxisOffset?: Value; crossAxisOffset?: Value; arrowPadding?: Value; arrow?: (signal: Signal) => TNode; target?: string | HTMLElement; onClickOutside?: () => void; }; ``` **References:** [Placement](#ui-placement), [PopOverArrowOptions](#ui-popoverarrowoptions) --- ## ui.query: Query() function Creates a reactive query component for handling asynchronous data loading. This component provides a declarative way to handle async operations with proper loading, success, and error states. It automatically manages the lifecycle of async requests and provides reload functionality. **Signature:**```typescript Query: ({ request, load, convertError, onSuccess, onError, onSettled, success, pending, failure, }: { request: Value; load: (options: QueryResourceLoadOptions) => Promise; convertError?: (error: unknown) => E; onSuccess?: (value: Res, req: Req) => void; onError?: (error: E, req: Req) => void; onSettled?: (result: AsyncResult, req: Req) => void; } & QueryDisplayOptions) => Renderable ```## ui.query: Parameters | Parameter | Type | Description | | --- | --- | --- | | { request, load, convertError, onSuccess, onError, onSettled, success, pending, failure, } | { request: Value<Req>; load: (options: [QueryResourceLoadOptions](#ui-queryresourceloadoptions)<Req, Res, E>) => Promise<Res>; convertError?: (error: unknown) => E; onSuccess?: (value: Res, req: Req) => void; onError?: (error: E, req: Req) => void; onSettled?: (result: AsyncResult<Res, E>, req: Req) => void; } & [QueryDisplayOptions](#ui-querydisplayoptions)<Res, E> | | **Returns:** Renderable Function that takes display options and returns a renderable component ## ui.query: Example 1```typescript // Basic API data loading const userId = prop(1) const UserProfile = Query({ request: userId, load: async ({ request }) => { const response = await fetch(`/api/users/${request}`) if (!response.ok) throw new Error('Failed to load user') return response.json() }, loading: () => html.div('Loading user...'), failure: (error, reload) => html.div( 'Error: ', error, html.button(on.click(reload), 'Retry') ), success: (user) => html.div( html.h2(user.map(u => u.name)), html.p(user.map(u => u.email)) ) }) ``` ## ui.query: Example 2 ```typescript // Query with dependencies const searchQuery = prop('') const filters = prop({ category: 'all', sort: 'name' }) const SearchResults = Query({ request: computed(() => ({ query: searchQuery.value, ...filters.value })), load: async ({ request, abortSignal }) => { const params = new URLSearchParams(request) const response = await fetch(`/api/search?${params}`, { signal: abortSignal }) return response.json() }, convertError: (error) => error instanceof Error ? error.message : 'Unknown error', loading: (previous) => html.div( 'Searching...', previous.value && html.div('Previous results:', previous.value.length) ), failure: (error, reload) => html.div( attr.class('error'), 'Search failed: ', error, html.button(on.click(reload), 'Try again') ), success: (results, reload) => html.div( html.button(on.click(reload), 'Refresh'), ForEach(results, result => SearchResultItem(result)) ) }) ``` ## ui.query: Example 3 ```typescript // File upload query const selectedFile = prop(null) const FileUpload = Query({ request: selectedFile, load: async ({ request }) => { if (!request) throw new Error('No file selected') const formData = new FormData() formData.append('file', request) const response = await fetch('/api/upload', { method: 'POST', body: formData }) if (!response.ok) throw new Error('Upload failed') return response.json() }, loading: () => html.div( attr.class('upload-progress'), 'Uploading file...' ), failure: (error, reload) => html.div( attr.class('upload-error'), 'Upload failed: ', error, html.button(on.click(reload), 'Retry upload') ), success: (result) => html.div( attr.class('upload-success'), 'File uploaded successfully!', html.a( attr.href(result.map(r => r.url)), 'View file' ) ) }) ``` --- ## ui.querydisplay: QueryDisplay() function Component to display an asynchronous query based on its current status. **Signature:**```typescript QueryDisplay: (query: QueryResource, options: QueryDisplayOptions) => Renderable ```## ui.querydisplay: Parameters | Parameter | Type | Description | | --- | --- | --- | | query | [QueryResource](#ui-queryresource)<Res, E> | The asynchronous query to display. | | options | [QueryDisplayOptions](#ui-querydisplayoptions)<Res, E> | The display options for the query. | **Returns:** Renderable {TNode} A node representing the current state of the query. --- ## ui.querydisplayoptions.failure: QueryDisplayOptions.failure property Function to render when the query has failed to load. **Signature:**```typescript failure?: (options: { error: Signal; reload: () => void; }) => TNode; ``` --- ## ui.querydisplayoptions: QueryDisplayOptions interface Options for displaying the different states of an asynchronous query. **Signature:**```typescript export interface QueryDisplayOptions ```## ui.querydisplayoptions: Properties | Property | Modifiers | Type | Description | | --- | --- | --- | --- | | [failure?](#ui-querydisplayoptions-failure) | | (options: { error: Signal<E>; reload: () => void; }) => TNode | _(Optional)_ Function to render when the query has failed to load. | | [pending?](#ui-querydisplayoptions-pending) | | (options: { previous: Signal<Res \\| undefined>; reload: () => void; cancel: (newState?: NonLoading<Res, E>) => void; }) => TNode | _(Optional)_ Function to render when the query is loading. | | [success](#ui-querydisplayoptions-success) | | (options: { value: Signal<Res>; reload: () => void; }) => TNode | Function to render when the query has successfully loaded. | --- ## ui.querydisplayoptions.pending: QueryDisplayOptions.pending property Function to render when the query is loading. **Signature:**```typescript pending?: (options: { previous: Signal; reload: () => void; cancel: (newState?: NonLoading) => void; }) => TNode; ``` --- ## ui.querydisplayoptions.success: QueryDisplayOptions.success property Function to render when the query has successfully loaded. **Signature:**```typescript success: (options: { value: Signal; reload: () => void; }) => TNode; ``` --- ## ui.queryresource.cancel: QueryResource.cancel property Abort the current in-flight request (if any) and clean up. **Signature:**```typescript readonly cancel: (newState?: NonLoading) => void; ``` --- ## ui.queryresource.dispose: QueryResource.dispose property Disposes of the query, aborting any ongoing requests and cleaning up. **Signature:**```typescript readonly dispose: () => void; ``` --- ## ui.queryresource.error: QueryResource.error property The current error of the query, or undefined if not failed. **Signature:**```typescript readonly error: Signal; ``` --- ## ui.queryresource.loading: QueryResource.loading property Whether the query is currently loading. **Signature:**```typescript readonly loading: Signal; ``` --- ## ui.queryresource: QueryResource interface Represents an asynchronous query with its current status, value, error, and loading state. Provides methods to reload the query and dispose of it. **Signature:**```typescript export interface QueryResource ```## ui.queryresource: Properties | Property | Modifiers | Type | Description | | --- | --- | --- | --- | | [cancel](#ui-queryresource-cancel) | `readonly` | (newState?: NonLoading<Res, E>) => void | Abort the current in-flight request (if any) and clean up. | | [dispose](#ui-queryresource-dispose) | `readonly` | () => void | Disposes of the query, aborting any ongoing requests and cleaning up. | | [error](#ui-queryresource-error) | `readonly` | Signal<E \\| undefined> | The current error of the query, or undefined if not failed. | | [loading](#ui-queryresource-loading) | `readonly` | Signal<boolean> | Whether the query is currently loading. | | [reload](#ui-queryresource-reload) | `readonly` | () => void | Reloads the query using the current request. | | [status](#ui-queryresource-status) | `readonly` | Signal<AsyncResult<Res, E>> | The current status of the query as an AsyncResult. | | [value](#ui-queryresource-value) | `readonly` | Signal<Res \\| undefined> | The current value of the query, or undefined if not loaded or failed. | --- ## ui.queryresource.reload: QueryResource.reload property Reloads the query using the current request. **Signature:**```typescript readonly reload: () => void; ``` --- ## ui.queryresource.status: QueryResource.status property The current status of the query as an AsyncResult. **Signature:**```typescript readonly status: Signal>; ``` --- ## ui.queryresource.value: QueryResource.value property The current value of the query, or undefined if not loaded or failed. **Signature:**```typescript readonly value: Signal; ``` --- ## ui.queryresourceloadoptions.abortsignal: QueryResourceLoadOptions.abortSignal property The signal to abort the loading process if needed. **Signature:**```typescript readonly abortSignal: AbortSignal; ``` --- ## ui.queryresourceloadoptions: QueryResourceLoadOptions interface Options for loading a query, including the request, abort signal, and previous result. **Signature:**```typescript export interface QueryResourceLoadOptions ```## ui.queryresourceloadoptions: Properties | Property | Modifiers | Type | Description | | --- | --- | --- | --- | | [abortSignal](#ui-queryresourceloadoptions-abortsignal) | `readonly` | AbortSignal | The signal to abort the loading process if needed. | | [onError?](#ui-queryresourceloadoptions-onerror) | `readonly` | (error: E, req: Req) => void | _(Optional)_ | | [onSettled?](#ui-queryresourceloadoptions-onsettled) | `readonly` | (result: AsyncResult<Res, E>, req: Req) => void | _(Optional)_ | | [onSuccess?](#ui-queryresourceloadoptions-onsuccess) | `readonly` | (value: Res, req: Req) => void | _(Optional)_ Side-effects | | [previous](#ui-queryresourceloadoptions-previous) | `readonly` | AsyncResult<Res, E> | The previous result of the query loading, if any. | | [request](#ui-queryresourceloadoptions-request) | `readonly` | Req | The request to load the query. | --- ## ui.queryresourceloadoptions.onerror: QueryResourceLoadOptions.onError property **Signature:**```typescript readonly onError?: (error: E, req: Req) => void; ``` --- ## ui.queryresourceloadoptions.onsettled: QueryResourceLoadOptions.onSettled property **Signature:**```typescript readonly onSettled?: (result: AsyncResult, req: Req) => void; ``` --- ## ui.queryresourceloadoptions.onsuccess: QueryResourceLoadOptions.onSuccess property Side-effects **Signature:**```typescript readonly onSuccess?: (value: Res, req: Req) => void; ``` --- ## ui.queryresourceloadoptions.previous: QueryResourceLoadOptions.previous property The previous result of the query loading, if any. **Signature:**```typescript readonly previous: AsyncResult; ``` --- ## ui.queryresourceloadoptions.request: QueryResourceLoadOptions.request property The request to load the query. **Signature:**```typescript readonly request: Req; ``` --- ## ui.rect._constructor_: Rect.(constructor) Creates a new Rect instance. **Signature:**```typescript constructor( left: number, top: number, width: number, height: number, localLeft: number, localTop: number); ```## ui.rect._constructor_: Parameters | Parameter | Type | Description | | --- | --- | --- | | left | number | The x-coordinate of the left edge | | top | number | The y-coordinate of the top edge | | width | number | The width of the rectangle | | height | number | The height of the rectangle | | localLeft | number | | | localTop | number | | ## ui.rect._constructor_: Example```typescript const rect = new Rect(10, 20, 100, 50); console.log(rect.left); // 10 console.log(rect.top); // 20 console.log(rect.width); // 100 console.log(rect.height); // 50 ``` --- ## ui.rect.bottom: Rect.bottom property Gets the y-coordinate of the bottom edge of the rectangle. **Signature:**```typescript get bottom(): number; ``` ## ui.rect.bottom: Example ```typescript const rect = new Rect(10, 20, 100, 50); console.log(rect.bottom); // 70 ``` --- ## ui.rect.center: Rect.center property Gets the center point of the rectangle. **Signature:**```typescript get center(): { x: number; y: number; }; ``` ## ui.rect.center: Example ```typescript const rect = new Rect(10, 20, 100, 50); const center = rect.center; console.log(center.x); // 60 (left + width/2) console.log(center.y); // 45 (top + height/2) ``` --- ## ui.rect.equals: Rect.equals property Compares this rectangle with another rectangle for equality. Uses near-equality comparison for floating-point precision tolerance. Two rectangles are considered equal if all their corresponding properties (left, top, width, height) are nearly equal within a small tolerance. **Signature:**```typescript readonly equals: (other: Rect) => boolean; ``` ## ui.rect.equals: Example ```typescript const rect1 = new Rect(10, 20, 100, 50); const rect2 = new Rect(10, 20, 100, 50); const rect3 = new Rect(10.00000001, 20, 100, 50); // Very close values console.log(rect1.equals(rect2)); // true console.log(rect1.equals(rect3)); // true (within tolerance) ``` --- ## ui.rect.height: Rect.height property The height of the rectangle **Signature:**```typescript readonly height: number; ``` --- ## ui.rect.left: Rect.left property The x-coordinate of the left edge of the rectangle **Signature:**```typescript readonly left: number; ``` --- ## ui.rect.localbottom: Rect.localBottom property Gets the bottom edge of the rectangle relative to the parent. **Signature:**```typescript get localBottom(): number; ``` ## ui.rect.localbottom: Example ```typescript const rect = new Rect(10, 20, 100, 50, 5, 10); console.log(rect.localBottom); // 60 (localTop + height) ``` --- ## ui.rect.localcenter: Rect.localCenter property Gets the center point of the rectangle relative to the parent. **Signature:**```typescript get localCenter(): { x: number; y: number; }; ``` ## ui.rect.localcenter: Example ```typescript const rect = new Rect(10, 20, 100, 50, 5, 10); const localCenter = rect.localCenter; console.log(localCenter.x); // 55 (localLeft + width/2) console.log(localCenter.y); // 65 (localTop + height/2) ``` --- ## ui.rect.localleft: Rect.localLeft property The x-coordinate of the left edge of the rectangle relative to the parent **Signature:**```typescript readonly localLeft: number; ``` --- ## ui.rect.localright: Rect.localRight property Gets the right edge of the rectangle relative to the parent. **Signature:**```typescript get localRight(): number; ``` ## ui.rect.localright: Example ```typescript const rect = new Rect(10, 20, 100, 50, 5, 10); console.log(rect.localRight); // 105 (localLeft + width) ``` --- ## ui.rect.localtop: Rect.localTop property The y-coordinate of the top edge of the rectangle relative to the parent **Signature:**```typescript readonly localTop: number; ``` --- ## ui.rect: Rect class Represents a rectangle with position and dimensions. A Rect defines a rectangular area in 2D space with a position (left, top) and dimensions (width, height). It provides convenient methods for accessing computed properties like right, bottom, center, and size. **Signature:**```typescript export declare class Rect ``` ## ui.rect: Example ```typescript // Create a rectangle using the constructor const rect1 = new Rect(10, 20, 100, 50); // Create a rectangle using the static factory method const rect2 = Rect.of({ left: 10, top: 20, width: 100, height: 50 }); // Access computed properties console.log(rect1.right); // 110 (left + width) console.log(rect1.bottom); // 70 (top + height) console.log(rect1.center); // { x: 60, y: 45 } // Compare rectangles const areEqual = rect1.equals(rect2); // true ```## ui.rect: Constructors | Constructor | Modifiers | Description | | --- | --- | --- | | [(constructor)(left, top, width, height, localLeft, localTop)](#ui-rect-constructor) | | Creates a new Rect instance. | ## ui.rect: Properties | Property | Modifiers | Type | Description | | --- | --- | --- | --- | | [bottom](#ui-rect-bottom) | `readonly` | number | Gets the y-coordinate of the bottom edge of the rectangle. | | [center](#ui-rect-center) | `readonly` | { x: number; y: number; } | Gets the center point of the rectangle. | | [equals](#ui-rect-equals) | `readonly` | (other: [Rect](#ui-rect)) => boolean | Compares this rectangle with another rectangle for equality. Uses near-equality comparison for floating-point precision tolerance. Two rectangles are considered equal if all their corresponding properties (left, top, width, height) are nearly equal within a small tolerance. | | [height](#ui-rect-height) | `readonly` | number | The height of the rectangle | | [left](#ui-rect-left) | `readonly` | number | The x-coordinate of the left edge of the rectangle | | [localBottom](#ui-rect-localbottom) | `readonly` | number | Gets the bottom edge of the rectangle relative to the parent. | | [localCenter](#ui-rect-localcenter) | `readonly` | { x: number; y: number; } | Gets the center point of the rectangle relative to the parent. | | [localLeft](#ui-rect-localleft) | `readonly` | number | The x-coordinate of the left edge of the rectangle relative to the parent | | [localRight](#ui-rect-localright) | `readonly` | number | Gets the right edge of the rectangle relative to the parent. | | [localTop](#ui-rect-localtop) | `readonly` | number | The y-coordinate of the top edge of the rectangle relative to the parent | | [right](#ui-rect-right) | `readonly` | number | Gets the x-coordinate of the right edge of the rectangle. | | [size](#ui-rect-size) | `readonly` | { width: number; height: number; } | Gets the size dimensions of the rectangle. | | [top](#ui-rect-top) | `readonly` | number | The y-coordinate of the top edge of the rectangle | | [width](#ui-rect-width) | `readonly` | number | The width of the rectangle | ## ui.rect: Methods | Method | Modifiers | Description | | --- | --- | --- | | [of({ left, top, width, height, localLeft, localTop, })](#ui-rect-of) | `static` | Creates a new Rect instance using an object with optional properties. This factory method provides a convenient way to create rectangles with default values for any unspecified properties. | --- ## ui.rect.of: Rect.of() method Creates a new Rect instance using an object with optional properties. This factory method provides a convenient way to create rectangles with default values for any unspecified properties. **Signature:**```typescript static of({ left, top, width, height, localLeft, localTop, }: { left?: number; top?: number; width?: number; height?: number; localLeft?: number; localTop?: number; }): Rect; ```## ui.rect.of: Parameters | Parameter | Type | Description | | --- | --- | --- | | { left, top, width, height, localLeft, localTop, } | { left?: number; top?: number; width?: number; height?: number; localLeft?: number; localTop?: number; } | | **Returns:** [Rect](#ui-rect) A new Rect instance ## ui.rect.of: Example```typescript // Create a rectangle at origin with no size const emptyRect = Rect.of({}); // Create a rectangle with only position const positioned = Rect.of({ left: 10, top: 20 }); // Create a rectangle with all properties const fullRect = Rect.of({ left: 10, top: 20, width: 100, height: 50 }); ``` --- ## ui.rect.right: Rect.right property Gets the x-coordinate of the right edge of the rectangle. **Signature:**```typescript get right(): number; ``` ## ui.rect.right: Example ```typescript const rect = new Rect(10, 20, 100, 50); console.log(rect.right); // 110 ``` --- ## ui.rect.size: Rect.size property Gets the size dimensions of the rectangle. **Signature:**```typescript get size(): { width: number; height: number; }; ``` ## ui.rect.size: Example ```typescript const rect = new Rect(10, 20, 100, 50); const size = rect.size; console.log(size.width); // 100 console.log(size.height); // 50 ``` --- ## ui.rect.top: Rect.top property The y-coordinate of the top edge of the rectangle **Signature:**```typescript readonly top: number; ``` --- ## ui.rect.width: Rect.width property The width of the rectangle **Signature:**```typescript readonly width: number; ``` --- ## ui.relativetime: relativeTime() function > Warning: This API is now obsolete. > > Use makeRelativeTimeSignal instead > Creates a signal that computes a human-readable relative time string between a target date and a reference date. **Signature:**```typescript relativeTime: (date: Value, options?: { now?: Value; frequency?: number; }) => import('@tempots/core').Computed ```## ui.relativetime: Parameters | Parameter | Type | Description | | --- | --- | --- | | date | Value<Date> | The target date to compare | | options | { now?: Value<Date>; frequency?: number; } | _(Optional)_ Configuration options | **Returns:** import('@tempots/core').Computed<string> A signal containing a human-readable relative time string (e.g., "2 minutes ago", "in 3 hours"). The signal will clean up its resources when disposed. --- ## ui.relativetimemillissignal: relativeTimeMillisSignal() function Creates a signal that computes the time difference in milliseconds between a target date and a reference date. **Signature:**```typescript relativeTimeMillisSignal: (date: Value, { now, frequency }?: { now?: Value; frequency?: number; }) => import('@tempots/core').Computed ```## ui.relativetimemillissignal: Parameters | Parameter | Type | Description | | --- | --- | --- | | date | Value<Date> | The target date to compare | | { now, frequency } | { now?: Value<Date>; frequency?: number; } | _(Optional)_ | **Returns:** import('@tempots/core').Computed<number> A signal containing the time difference in milliseconds. Negative values indicate past times, positive values indicate future times. The signal will clean up its resources when disposed. --- ## ui.relativetimesignal: relativeTimeSignal() function Creates a signal that computes a human-readable relative time string between a target date and a reference date. **Signature:**```typescript relativeTimeSignal: (date: Value, options?: { now?: Value; frequency?: number; }) => import('@tempots/core').Computed ```## ui.relativetimesignal: Parameters | Parameter | Type | Description | | --- | --- | --- | | date | Value<Date> | The target date to compare | | options | { now?: Value<Date>; frequency?: number; } | _(Optional)_ Configuration options | **Returns:** import('@tempots/core').Computed<string> A signal containing a human-readable relative time string (e.g., "2 minutes ago", "in 3 hours"). The signal will clean up its resources when disposed. --- ## ui.resultview: ResultView() function Renders a view based on the result of a computation. **Signature:**```typescript ResultView: (result: Value>, options: ResultViewOptions | ((value: Signal) => TNode)) => Renderable ```## ui.resultview: Parameters | Parameter | Type | Description | | --- | --- | --- | | result | Value<Result<T, E>> | The result of the computation. | | options | [ResultViewOptions](#ui-resultviewoptions)<T, E> \\| ((value: Signal<T>) => TNode) | The options for rendering the view. | **Returns:** Renderable The rendered view. --- ## ui.resultviewoptions: ResultViewOptions type Represents the signal for a result. **Signature:**```typescript export type ResultViewOptions = { success: (value: Signal) => TNode; failure?: (error: Signal) => TNode; }; ``` --- ## ui.rootrouter: RootRouter() function Creates the root router for an application that provides routing context to child components. RootRouter is the top-level router that matches against the full browser pathname and creates the initial routing context. It provides the RouterContextProvider that child ChildRouter components can use for nested routing scenarios. **Signature:**```typescript RootRouter: >, K>> : never) => TNode; }>(routes: T) => Renderable ```## ui.rootrouter: Parameters | Parameter | Type | Description | | --- | --- | --- | | routes | T | Object mapping route patterns to handler functions | **Returns:** Renderable A renderable router component that handles URL routing and provides context ## ui.rootrouter: Exceptions {Error} When no matching route is found for the current URL ## ui.rootrouter: Example 1```typescript // Basic app routing const App = RootRouter({ '/': () => html.div('Home Page'), '/about': () => html.div('About Page'), '/admin/*': () => AdminSection(), // Passes remaining path to AdminSection '*': () => html.div('404 - Page Not Found') }) render(App, document.body) ``` ## ui.rootrouter: Example 2 ```typescript // Nested routing with RootRouter and ChildRouter const App = RootRouter({ '/': () => html.div('Home'), '/admin/*': () => AdminRoutes(), '/blog/*': () => BlogRoutes() }) const AdminRoutes = ChildRouter({ '/users': () => html.div('User List'), '/users/:id': (info) => html.div('User: ', info.$.params.$.id), '/settings': () => html.div('Admin Settings') }) ``` --- ## ui.route: Route type Represents a route in the application. **Signature:**```typescript export type Route = RouteSegment[]; ``` **References:** [RouteSegment](#ui-routesegment) --- ## ui.routecatchall: RouteCatchAll type Represents a catch-all route. **Signature:**```typescript export type RouteCatchAll = { type: 'catch-all'; name?: string; }; ``` --- ## ui.routeinfo: RouteInfo type Represents information about a route. **Signature:**```typescript export type RouteInfo = { readonly params: P; readonly route: R; readonly path: string; readonly search: Record; readonly hash?: string; }; ``` --- ## ui.routeliteral: RouteLiteral type Represents a literal route. **Signature:**```typescript export type RouteLiteral = { type: 'literal'; value: string; }; ``` --- ## ui.routeparam: RouteParam type Represents a route parameter. **Signature:**```typescript export type RouteParam = { type: 'param'; name: string; }; ``` --- ## ui.routercontext.fullpath: RouterContext.fullPath property The full original pathname from the browser location. This remains the same across all router levels. **Signature:**```typescript readonly fullPath: string; ``` --- ## ui.routercontext.matchedpath: RouterContext.matchedPath property The portion of the path that was matched by this router level. For RootRouter, this is the matched portion of the full pathname. For ChildRouter, this is the matched portion of the remaining path from parent. **Signature:**```typescript readonly matchedPath: string; ``` --- ## ui.routercontext: RouterContext interface Represents the context information for a router level in nested routing. Each router level (AppRouter or SubRouter) creates a RouterContext that contains information about the matched path, remaining path for child routers, and accumulated parameters from all parent router levels. **Signature:**```typescript export interface RouterContext ``` ## ui.routercontext: Example ```typescript // For URL "/admin/users/123" with routes: // RootRouter: { '/admin/*': () => AdminRoutes() } // ChildRouter: { '/users/:id': (info) => UserDetail(info) } // RootRouter context: { matchedPath: '/admin', remainingPath: '/users/123', fullPath: '/admin/users/123', params: {} } // ChildRouter context: { matchedPath: '/users/123', remainingPath: '', fullPath: '/admin/users/123', params: { id: '123' } } ```## ui.routercontext: Properties | Property | Modifiers | Type | Description | | --- | --- | --- | --- | | [fullPath](#ui-routercontext-fullpath) | `readonly` | string | The full original pathname from the browser location. This remains the same across all router levels. | | [matchedPath](#ui-routercontext-matchedpath) | `readonly` | string | The portion of the path that was matched by this router level. For RootRouter, this is the matched portion of the full pathname. For ChildRouter, this is the matched portion of the remaining path from parent. | | [params](#ui-routercontext-params) | `readonly` | Record<string, string> | Route parameters extracted at this router level. These are accumulated with parameters from parent router levels. | | [remainingPath](#ui-routercontext-remainingpath) | `readonly` | string | The remaining path that should be processed by child routers. Empty string if no remaining path. | --- ## ui.routercontext.params: RouterContext.params property Route parameters extracted at this router level. These are accumulated with parameters from parent router levels. **Signature:**```typescript readonly params: Record; ``` --- ## ui.routercontext.remainingpath: RouterContext.remainingPath property The remaining path that should be processed by child routers. Empty string if no remaining path. **Signature:**```typescript readonly remainingPath: string; ``` --- ## ui.routercontextprovider: RouterContextProvider variable Provider for router context stack in nested routing scenarios. The RouterContextProvider maintains a stack of RouterContext objects, where each level represents a router in the nested hierarchy. Child routers can access the context stack to determine what path remains to be processed and what parameters have been accumulated from parent router levels. **Signature:**```typescript RouterContextProvider: Provider> ``` ## ui.routercontextprovider: Example 1 ```typescript // RootRouter creates the initial context const RootRouter = (routes: T) => Provide( RouterContextProvider, {}, () => { // Router implementation that creates initial context return Use(Location, location => { // Match routes and create context... }) } ) ``` ## ui.routercontextprovider: Example 2 ```typescript // ChildRouter reads parent context and adds its own const ChildRouter = (routes: T) => Use(RouterContextProvider, contextStack => { const parentContext = contextStack.value[contextStack.value.length - 1] const remainingPath = parentContext?.remainingPath || '' // Match against remaining path and create new context... }) ``` --- ## ui.routesegment: RouteSegment type Represents a segment of a route. **Signature:**```typescript export type RouteSegment = RouteParam | RouteLiteral | RouteCatchAll; ``` **References:** [RouteParam](#ui-routeparam), [RouteLiteral](#ui-routeliteral), [RouteCatchAll](#ui-routecatchall) --- ## ui.selectonfocus: SelectOnFocus() function Selects the text inside an input element when it receives focus. **Signature:**```typescript SelectOnFocus: () => import('@tempots/dom').Renderable ``` **Returns:** import('@tempots/dom').Renderable A renderable function that selects the text inside an input element when it receives focus. --- ## ui.ticker: ticker() function Creates a new Ticker instance with an optional initial value. **Signature:**```typescript ticker: (initial?: number) => Ticker ```## ui.ticker: Parameters | Parameter | Type | Description | | --- | --- | --- | | initial | number | _(Optional)_ The initial value for the ticker (defaults to 0) | **Returns:** [Ticker](#ui-ticker) A new Ticker instance that only updates when the value changes --- ## ui.ticker.tick: Ticker.tick property Triggers an update of the Ticker by incrementing its internal value. **Signature:**```typescript readonly tick: () => void; ``` --- ## ui.timedifftostring: timeDiffToString() function Converts a time difference in milliseconds to a human-readable relative time string. **Signature:**```typescript timeDiffToString: (diffInMillis: number) => string ```## ui.timedifftostring: Parameters | Parameter | Type | Description | | --- | --- | --- | | diffInMillis | number | The time difference in milliseconds. Negative values indicate past times, positive values indicate future times. | **Returns:** string A human-readable string representing the relative time difference: - For very recent times (< 1 minute): "just now" or "in a moment" - For other times: formatted strings like "2 minutes ago", "in 3 hours", "yesterday", etc. ## ui.timedifftostring: Exceptions {Error} Should never throw due to the Infinity max value in units array --- ## ui.urlfromlocation: urlFromLocation() function Returns the full URL based on the provided location data. **Signature:**```typescript urlFromLocation: (location: LocationData) => string ```## ui.urlfromlocation: Parameters | Parameter | Type | Description | | --- | --- | --- | | location | [LocationData](#ui-locationdata) | The location data object. | **Returns:** string The full URL string. --- ## ui.useappearance: useAppearance() function Creates a signal that represents the current appearance (light or dark) based on the user's system preferences. The appearance is updated whenever the user's system preferences change, and the signal is cleaned up when it is no longer needed. **Signature:**```typescript export declare function useAppearance(): Signal; ``` **Returns:** Signal<[AppearanceType](#ui-appearancetype)> A signal representing the current appearance. --- ## ui.wheninviewport: WhenInViewport() function Conditionally renders content based on whether an element is in the viewport. This is a convenience wrapper around `InViewport` that provides a simpler API for cases where you just want to show/hide content based on viewport visibility. It's perfect for simple lazy loading or reveal animations. **Signature:**```typescript WhenInViewport: (options: InViewportOptions, then: () => TNode, otherwise?: () => TNode) => Renderable ```## ui.wheninviewport: Parameters | Parameter | Type | Description | | --- | --- | --- | | options | [InViewportOptions](#ui-inviewportoptions) | Configuration options for viewport detection | | then | () => TNode | Function that returns content to render when element is in viewport | | otherwise | () => TNode | _(Optional)_ Optional function that returns content when element is not in viewport | **Returns:** Renderable A renderable component that conditionally shows content based on viewport visibility ## ui.wheninviewport: Example 1```typescript // Simple lazy loading WhenInViewport( { mode: 'partial', once: true }, () => html.img( attr.src('https://example.com/image.jpg'), attr.alt('Lazy loaded image') ), () => html.div(attr.class('skeleton'), 'Loading...') ) ``` ## ui.wheninviewport: Example 2 ```typescript // Reveal animation WhenInViewport( { mode: 'full' }, () => html.div( attr.class('animate-slide-up'), 'This content slides up when visible' ) ) ``` ## ui.wheninviewport: Example 3 ```typescript // Load expensive component only when needed WhenInViewport( { mode: 'partial', once: true }, () => ExpensiveChart({ data: chartData }), () => html.div('Chart will load when visible') ) ``` --- ## ui.windowsize: WindowSize() function Creates a renderable function that monitors the window size and invokes the provided function with the current size. **Signature:**```typescript WindowSize: (fn: (size: Signal) => TNode) => import('@tempots/dom').Renderable ```## ui.windowsize: Parameters | Parameter | Type | Description | | --- | --- | --- | | fn | (size: Signal<Size>) => TNode | The function to be invoked with the current window size. | **Returns:** import('@tempots/dom').Renderable A renderable function that monitors the window size.