# Introduction
> Unframework is the compiler that speaks seven UI frameworks: write a component once, and get native React, Vue, Svelte, Angular, Solid, Qwik and Astro code.
Unframework is the compiler that speaks seven UI frameworks: write a component once, and it compiles to native React, Vue, Svelte, Angular, Solid, Qwik and Astro code, and to whichever faster framework comes next, with no migration.
One beam of light goes into a prism and comes out as seven. Unframework does the same with your components: one source goes into the compiler and comes out as seven frameworks.
## How it works
### Source
One component is the source of truth for every framework. Change it in one place, and all seven get the change on the next build.
- **One source**: no port per framework to write, review and keep in sync.
- **No drift**: seven outputs can't fall out of step when there is only one input.
- **One standard**: meet the [Open Components](https://opencomponents.dev) standard once, and every output meets it.
- **Agent-ready**: agents change one component, not seven, so no port is missed.
### Compiler
The compiler reads what your component does, then writes it the way each framework expects: its reactivity, its templates, its conventions.
- **Idiomatic**: hooks in React, refs in Vue, runes in Svelte, signals in Solid.
- **Consistent**: props, events and slots keep their names in every framework.
- **Build-time**: the translation happens in your build, not in the browser.
- **Deterministic**: the same source compiles to the same output, every time.
### Output
Each framework gets a real component in its own format, typed and readable, with no wrapper or adapter in between: React, Vue, Svelte, Angular, Solid, Qwik and Astro.
Props, events and slots keep their names in every framework, so a component reads the same wherever you use it.
## The eighth framework
AI is speeding everything up, and a faster framework is always around the corner. When it lands, it's one more compile target: your components move on the next build, not in a migration.
- **No migration**: a new framework is a new compile target, not a rewrite of every component.
- **No bet to make**: don't guess which framework wins. Your components go where it goes.
- **Side by side**: ship the old framework and the new one from the same source while you move.
- **On your schedule**: switch when the numbers say so, not when a rewrite fits the roadmap.
## Status
Unframework is in early development, and its packages are on npm: [Installation](/docs/getting-started/installation) says which ones you need. Watch the [GitHub repository](https://github.com/uxfront-com/unframework) to hear about new releases. These docs grow with it.
## For agents
Every page of these docs is also published as markdown: prefix its path with `/raw` and add `.md`, as in [`/raw/docs/getting-started/introduction.md`](/raw/docs/getting-started/introduction.md){external=""}. [`/llms.txt`](/llms.txt){external=""} lists every page, and [`/llms-full.txt`](/llms-full.txt){external=""} holds them all in one file.
# Installation
> What to install from npm, for a design system that builds its components with the CLI and for an app that compiles them with the bundler plugin.
Unframework fits into a project in one of two ways. A design system writes its components once and builds them for every framework with the `unframework` command, then publishes them as one package. An app imports `.uf.tsx` components, its own or a design system's, and the bundler plugin compiles them to the app's framework as part of its build. Most teams use both: the design system builds, and its apps install the result.
## What you install
| Package | What it gives you | Who needs it |
| --------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ |
| `@uxfront/unframework` | The authoring API that a `.uf.tsx` file imports, its JSX types, `defineConfig` and the [`unframework` command](/docs/tooling/cli) | every project |
| `@unframework.dev/unplugin` | The [bundler plugin](/docs/tooling/bundler-plugin), and the Astro integration | an app that compiles `.uf.tsx` files |
| `typescript` | `tsc`, to type-check `.uf.tsx` files through `tsconfig.uf.json` | any project that type-checks |
[Packaging](/docs/tooling/packaging#install-the-packagers) lists what each framework's packager needs, for a design system that publishes a package.
We build and test with Node 24, TypeScript 7 and Vite 8.
## Install the packages
The packages are on npm. Every project installs `@uxfront/unframework`:
```bash
npm install @uxfront/unframework
```
An app that compiles `.uf.tsx` files adds the bundler plugin, and a project that type-checks adds TypeScript:
```bash
npm install @unframework.dev/unplugin typescript
```
Keep in mind that the unscoped `unframework` on npm is another project's package, so don't install it.
## Start a project
With `@uxfront/unframework` installed, `unframework init` writes a config, an example component with its stylesheet, `tsconfig.uf.json` and `AGENTS.md`, and `unframework check` passes on them. In a new directory, `create-unframework
` writes a `package.json` that depends on `@uxfront/unframework`. Once you've installed its dependencies, run `unframework init` there. [The CLI](/docs/tooling/cli#init) lists what each file holds.
From there:
- **To build a design system,** set your targets in [`unframework.config.ts`](/docs/tooling/configuration), then run `unframework build`, or `unframework build --package` to [package](/docs/tooling/packaging) it.
- **To use components in an app,** add the [bundler plugin](/docs/tooling/bundler-plugin) to your Vite config, or the Astro integration, and import a `.uf.tsx` file.
- **To write components,** start with [Props](/docs/components/props).
# Props
> A component takes its props as one typed parameter, destructured with static defaults or read as props.x, and every framework declares them its own way.
A component takes its props as its only parameter, typed by an object type. You destructure them, with a static default for any optional prop, or read them from one object as `props.name`. The compiler copies the type into every output and declares the props the way each framework does.
## Destructured props
The canonical form destructures each prop by its own name:
```tsx [ProductTile.uf.tsx]
export interface ProductTileProps {
name: string;
price: number;
stock: number;
available?: boolean;
}
export default function ProductTile({ name, price, stock, available = true }: ProductTileProps) {
return (
{name}
Price: {price} EUR
{stock} in stock
{available ? "Available to order" : "Currently unavailable"}
);
}
```
Each framework gets the same props, declared its own way:
::framework-switcher
#react
```tsx [ProductTile.tsx]
import type { CSSProperties } from "react";
export interface ProductTileProps {
name: string;
price: number;
stock: number;
available?: boolean;
}
export interface ProductTileAttributes {
className?: string;
style?: CSSProperties;
}
export default function ProductTile({
name,
price,
stock,
available = true,
className,
style,
...attributes
}: ProductTileProps & ProductTileAttributes) {
return (
{name}
Price: {price} EUR
{stock} in stock
{available ? "Available to order" : "Currently unavailable"}
);
}
/** Joins class names, and the keys of an object's truthy entries, into one `className`. */
function cx(...parts: unknown[]): string {
const names: string[] = [];
for (const part of parts) {
if (typeof part === "string") {
if (part) names.push(part);
} else if (part && typeof part === "object") {
for (const [key, on] of Object.entries(part)) {
if (on) names.push(key);
}
}
}
return names.join(" ");
}
/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record {
const scope: Record = {};
for (const key of Object.keys(props)) {
if (key.startsWith("data-uf-")) scope[key] = "";
}
return scope;
}
```
#vue
```vue [ProductTile.vue]
{{ name }}
Price: {{ price }} EUR
{{ stock }} in stock
{{ available ? "Available to order" : "Currently unavailable" }}
```
#svelte
```svelte [ProductTile.svelte]
{name}
Price: {price} EUR
{stock} in stock
{available ? "Available to order" : "Currently unavailable"}
```
#angular
```ts [product-tile.ts]
import {
Component,
Directive,
ElementRef,
type OnInit,
Renderer2,
inject,
input,
} from "@angular/core";
export interface ProductTileProps {
name: string;
price: number;
stock: number;
available?: boolean;
}
/** The scope attributes taken off each host, for the roots its component renders later. */
const scopes = new WeakMap();
/**
* Gives a root node of its component the scope attributes the component's styled parents put on
* its host (ADR-0063), and takes them off the host, which keeps only `display: contents`.
*/
@Directive({ selector: "[ufScope]" })
export class ScopeAttributes implements OnInit {
readonly ufScope = input.required();
private readonly element = inject>(ElementRef);
private readonly renderer = inject(Renderer2);
ngOnInit(): void {
const host = this.ufScope();
let names = scopes.get(host);
if (!names) {
names = host.getAttributeNames().filter((name) => name.startsWith("data-uf-"));
for (const name of names) this.renderer.removeAttribute(host, name);
scopes.set(host, names);
}
for (const name of names) this.renderer.setAttribute(this.element.nativeElement, name, "");
}
}
@Component({
selector: "uf-product-tile",
imports: [ScopeAttributes],
host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
preserveWhitespaces: false,
template: `
@let name = this.name();
@let price = this.price();
@let stock = this.stock();
@let available = this.available();
{{ name }}
Price: {{ price }} EUR
{{ stock }} in stock
{{ available ? "Available to order" : "Currently unavailable" }}
{props.available ? "Available to order" : "Currently unavailable"}
);
}
/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record {
const scope: Record = {};
for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
return scope;
}
```
#qwik
```tsx [ProductTile.tsx]
import { type CSSProperties, type ClassList, component$ } from "@qwik.dev/core";
export interface ProductTileProps {
name: string;
price: number;
stock: number;
available?: boolean;
}
export default component$(
({ name, price, stock, available = true, class: className, style, ...attributes }) => {
return (
{name}
Price: {price} EUR
{stock} in stock
{available ? "Available to order" : "Currently unavailable"}
);
},
);
/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record {
const scope: Record = {};
for (const key of Object.keys(props)) {
if (key.startsWith("data-uf-")) scope[key] = "";
}
return scope;
}
```
#astro
```astro [ProductTile.astro]
---
export interface ProductTileProps {
name: string;
price: number;
stock: number;
available?: boolean;
}
interface Props extends ProductTileProps {
class?: string;
style?: Record;
}
const { name, price, stock, available = true, class: className, style } = Astro.props;
/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record {
const scope: Record = {};
for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
return scope;
}
---
{name}
Price: {price} EUR
{stock} in stock
{available ? "Available to order" : "Currently unavailable"}
```
::
- React and Qwik keep the pattern and its defaults in the component's parameter.
- Vue destructures `defineProps
()`. An optional prop without a default gets `= undefined`, so Vue does not turn an absent boolean prop into `false`.
- Svelte destructures `$props()`.
- Angular declares one signal input per prop: `input.required()` for a required prop, `input()` for an optional one, and `input(default, { transform })` for one with a default. The transform applies the default to an explicit `undefined` too. The template reads each input once, with `@let`.
- Solid never destructures its props, because they are reactive getters. It merges the defaults in with `mergeProps`, typed `satisfies Partial
`, and reads every prop as `props.name`. A default that holds an object or an array literal makes the defaults a `const defaults: Required>` of their own, as in `Notice` below: `satisfies` would type the prop by the literal, without the optional members an object leaves out, and an array of `"info"` as `"info"[]` rather than `Tone[]`.
- Astro names the type `Props` and destructures `Astro.props`.
A destructured prop that the template never reads is left out of the pattern, so the outputs pass their frameworks' unused-variable rules. The type still declares it, and Angular still declares its input. Vue keeps an optional one, because `vue/require-default-prop` asks for its default, under a local whose `_` tells the lint it is unread:
```vue [ArticleTeaser.vue]
const {
title,
summary,
minutes = 5,
featured: _featured = undefined,
category: _category = undefined,
pinned: _pinned = false,
layout: _layout = "row",
} = defineProps();
```
When the template reads no prop at all, every output still declares the props:
```tsx [ArticleSkeleton.uf.tsx]
export interface ArticleSkeletonProps {
title: string;
summary?: string;
minutes?: number;
}
export default function ArticleSkeleton(_props: ArticleSkeletonProps) {
return (
);
}
/** Joins class names, and the keys of an object's truthy entries, into one `className`. */
function cx(...parts: unknown[]): string {
const names: string[] = [];
for (const part of parts) {
if (typeof part === "string") {
if (part) names.push(part);
} else if (part && typeof part === "object") {
for (const [key, on] of Object.entries(part)) {
if (on) names.push(key);
}
}
}
return names.join(" ");
}
/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record {
const scope: Record = {};
for (const key of Object.keys(props)) {
if (key.startsWith("data-uf-")) scope[key] = "";
}
return scope;
}
```
#vue
```vue [ArticleSkeleton.vue]
Loading the article
```
#svelte
```svelte [ArticleSkeleton.svelte]
Loading the article
```
#angular
```ts [article-skeleton.ts]
import {
Component,
Directive,
ElementRef,
type OnInit,
Renderer2,
inject,
input,
} from "@angular/core";
export interface ArticleSkeletonProps {
title: string;
summary?: string;
minutes?: number;
}
/** The scope attributes taken off each host, for the roots its component renders later. */
const scopes = new WeakMap();
/**
* Gives a root node of its component the scope attributes the component's styled parents put on
* its host (ADR-0063), and takes them off the host, which keeps only `display: contents`.
*/
@Directive({ selector: "[ufScope]" })
export class ScopeAttributes implements OnInit {
readonly ufScope = input.required();
private readonly element = inject>(ElementRef);
private readonly renderer = inject(Renderer2);
ngOnInit(): void {
const host = this.ufScope();
let names = scopes.get(host);
if (!names) {
names = host.getAttributeNames().filter((name) => name.startsWith("data-uf-"));
for (const name of names) this.renderer.removeAttribute(host, name);
scopes.set(host, names);
}
for (const name of names) this.renderer.setAttribute(this.element.nativeElement, name, "");
}
}
@Component({
selector: "uf-article-skeleton",
imports: [ScopeAttributes],
host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
preserveWhitespaces: false,
template: `
);
}
/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record {
const scope: Record = {};
for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
return scope;
}
```
#qwik
```tsx [ArticleSkeleton.tsx]
import { type CSSProperties, type ClassList, component$ } from "@qwik.dev/core";
export interface ArticleSkeletonProps {
title: string;
summary?: string;
minutes?: number;
}
export default component$(
(_props) => {
return (
Loading the article
);
},
);
/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record {
const scope: Record = {};
for (const key of Object.keys(props)) {
if (key.startsWith("data-uf-")) scope[key] = "";
}
return scope;
}
```
#astro
```astro [ArticleSkeleton.astro]
---
export interface ArticleSkeletonProps {
title: string;
summary?: string;
minutes?: number;
}
interface Props extends ArticleSkeletonProps {
class?: string;
style?: Record;
}
const { class: className, style } = Astro.props;
/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record {
const scope: Record = {};
for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
return scope;
}
---
Loading the article
```
::
React, Solid and Svelte name destructured props nothing reads `_props`. An object nothing reads keeps its name when the name is `_` and more (`_props`, `_unused`); otherwise React and Svelte write `_` before it (`_props` for `props`, `__` for a bare `_`), and Solid names it `_props`. Qwik's component takes no parameter, Vue calls `defineProps
()` alone, and Astro exports its `Props`, so that its lint counts the type as used.
## The props object
When no prop has a default, a component can take its props as one object:
```tsx [AuthorByline.uf.tsx]
export interface AuthorBylineProps {
author: string;
published: string;
minutes: number;
affiliation?: string;
}
export default function AuthorByline(props: AuthorBylineProps) {
return (
By {props.author}, {props.affiliation ?? "independent"}
· {props.minutes} min read
);
}
```
Read every prop as `props.name`. Any other use of the object is [UF2001](/docs/reference/diagnostics#UF2001): passing it on, destructuring it, reading `props[key]`, assigning to it, or reading through parentheses, `(props).name`, which the fix unwraps. The parameter's name cannot start with `$$`, which Astro's compiled component uses for its own names. A default needs the destructured form.
The outputs keep the object where their framework has one. React, Solid and Qwik take `props` as their parameter. The others declare it, Svelte as the rest once the `class` and `style` that fall through are taken out ([Fallthrough](/docs/components/fallthrough)):
```vue [AuthorByline.vue]
const props = withDefaults(defineProps(), { affiliation: undefined });
```
```svelte [AuthorByline.svelte]
type Props = AuthorBylineProps & { class?: ClassValue; style?: string };
let { class: className, style, ...props }: Props = $props();
```
```astro [AuthorByline.astro]
const props = Astro.props;
```
Angular declares the same inputs as for the destructured form.
## Types
The props type is an inline object type, or a local `interface` or `type` alias:
```tsx [ProductSpec.uf.tsx]
type Availability = "in-stock" | "backorder" | "discontinued";
interface Finish {
sku: string;
label: string;
}
export interface ProductSpecProps {
name: string;
availability: Availability;
size: { width: number; depth: number; unit: "cm" | "in" };
finishes: Finish[];
```
Every output copies the declarations the props reach, exactly as written, and exports them as the source does. Angular, for example, types its inputs with them:
```ts [product-spec.ts]
readonly finishes = input.required();
```
A member is a property with a plain name, declared once ([UF2001](/docs/reference/diagnostics#UF2001)). Its type can be built from:
- `string`, `number`, `boolean`, `null` and `undefined`;
- string, number and boolean literal types;
- unions of these;
- arrays: `T[]`, `readonly T[]`, `Array` and `ReadonlyArray`;
- object type literals, and local interfaces and aliases, nested to any depth;
- interfaces and aliases imported from a `.ts` module, a child's module or a package, `extends` chains, intersections, generic declarations and the five utility types ([Types and generics](/docs/components/types-and-generics)).
Anything else is a diagnostic at the type:
| Type | Why | Code |
| ---------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| A function type or a method | A callback is an [event](/docs/components/events#component-events), which `defineEmits` declares, and a render function is a [slot](/docs/components/slots) | [UF1002](/docs/reference/diagnostics#UF1002): use an event or a slot |
| A global type, such as `Date` | The compiler reads only the types the module declares or imports | [UF6001](/docs/reference/diagnostics#UF6001) |
| `any`, `unknown`, `object`, `{}`, `symbol`, `bigint` or a tuple | The targets' props can't declare it (ADR-0034) | [UF6002](/docs/reference/diagnostics#UF6002) |
| A template literal type, an index signature, a computed key, `keyof`, a conditional or a mapped type | The default type oracle reads types as written, and these need a type checker | [UF6002](/docs/reference/diagnostics#UF6002): the tsgo type oracle evaluates some of them ([What stays out](/docs/components/types-and-generics#what-stays-out)) |
| An enum | An enum declaration is itself UF1002, and the default type oracle doesn't evaluate one | [UF1002](/docs/reference/diagnostics#UF1002) and [UF6002](/docs/reference/diagnostics#UF6002) |
| A props type that isn't an object type, such as a union of two object types | The targets declare props as the members of one object type | [UF6004](/docs/reference/diagnostics#UF6004) |
| A union of a boolean with `string`, `""` or the prop's own kebab-case name | Vue reads `""` and the prop's own name as `true` for such a prop, and its casting rule stays (ADR-0034) | [UF1002](/docs/reference/diagnostics#UF1002): give the prop one kind |
A type declaration that no component's props reach is UF1002 unless the module exports it, since no output would declare it. Every output exports one the module exports ([Exported types](/docs/components/types-and-generics#exported-types)). `import type` reads from a `.ts` module, a child's module or a package. Keep a type that several components share in a `.ts` module: the Vite plugin joins the components of one file into one module on React, Solid, Qwik and Angular, where two outputs that both declare a type clash. (Vue, Svelte and Astro files hold one component each.)
## Defaults
A default goes on an optional prop, in the pattern:
```tsx [Notice.uf.tsx]
export default function Notice({
message,
title = "Notice",
tone = "info",
priority = 1,
expanded = false,
tags = ["general"],
author = { name: "System" },
}: NoticeProps) {
```
A default is a static value: a string, number, boolean or `null` literal, a negated number, a template literal without expressions, or an array or object literal of those. It cannot read anything, not a prop, a global or a function's result ([UF2002](/docs/reference/diagnostics#UF2002)): Vue hoists defaults out of the component, and Angular reads them before any input is set. Write the value itself, or compute it in the template (`pageCount ?? 10`).
::framework-switcher
#react
```tsx [Notice.tsx]
import type { CSSProperties } from "react";
export interface NoticeProps {
message: string;
title?: string;
tone?: "info" | "warning";
priority?: number;
expanded?: boolean;
tags?: string[];
author?: { name: string };
}
export interface NoticeAttributes {
className?: string;
style?: CSSProperties;
}
export default function Notice({
message,
title = "Notice",
tone = "info",
priority = 1,
expanded = false,
tags = ["general"],
author = { name: "System" },
className,
style,
...attributes
}: NoticeProps & NoticeAttributes) {
return (
{title}
{message}
Priority {priority}
Tagged {tags.join(", ")}, posted by {author.name}.
);
}
/** Joins class names, and the keys of an object's truthy entries, into one `className`. */
function cx(...parts: unknown[]): string {
const names: string[] = [];
for (const part of parts) {
if (typeof part === "string") {
if (part) names.push(part);
} else if (part && typeof part === "object") {
for (const [key, on] of Object.entries(part)) {
if (on) names.push(key);
}
}
}
return names.join(" ");
}
/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record {
const scope: Record = {};
for (const key of Object.keys(props)) {
if (key.startsWith("data-uf-")) scope[key] = "";
}
return scope;
}
```
#vue
```vue [Notice.vue]
{{ title }}
{{ message }}
Priority {{ priority }}
Tagged {{ tags.join(", ") }}, posted by {{ author.name }}.
```
#svelte
```svelte [Notice.svelte]
{title}
{message}
Priority {priority}
Tagged {tags.join(", ")}, posted by {author.name}.
```
#angular
```ts [notice.ts]
import {
Component,
Directive,
ElementRef,
type OnInit,
Renderer2,
inject,
input,
} from "@angular/core";
export interface NoticeProps {
message: string;
title?: string;
tone?: "info" | "warning";
priority?: number;
expanded?: boolean;
tags?: string[];
author?: { name: string };
}
/** The scope attributes taken off each host, for the roots its component renders later. */
const scopes = new WeakMap();
/**
* Gives a root node of its component the scope attributes the component's styled parents put on
* its host (ADR-0063), and takes them off the host, which keeps only `display: contents`.
*/
@Directive({ selector: "[ufScope]" })
export class ScopeAttributes implements OnInit {
readonly ufScope = input.required();
private readonly element = inject>(ElementRef);
private readonly renderer = inject(Renderer2);
ngOnInit(): void {
const host = this.ufScope();
let names = scopes.get(host);
if (!names) {
names = host.getAttributeNames().filter((name) => name.startsWith("data-uf-"));
for (const name of names) this.renderer.removeAttribute(host, name);
scopes.set(host, names);
}
for (const name of names) this.renderer.setAttribute(this.element.nativeElement, name, "");
}
}
@Component({
selector: "uf-notice",
imports: [ScopeAttributes],
host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
preserveWhitespaces: false,
template: `
@let message = this.message();
@let title = this.title();
@let tone = this.tone();
@let priority = this.priority();
@let expanded = this.expanded();
@let tags = this.tags();
@let author = this.author();
{{ title }}
{{ message }}
Priority {{ priority }}
Tagged {{ tags.join(", ") }}, posted by {{ author.name }}.
Tagged {props.tags.join(", ")}, posted by {props.author.name}.
);
}
/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record {
const scope: Record = {};
for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
return scope;
}
```
#qwik
```tsx [Notice.tsx]
import { type CSSProperties, type ClassList, component$ } from "@qwik.dev/core";
export interface NoticeProps {
message: string;
title?: string;
tone?: "info" | "warning";
priority?: number;
expanded?: boolean;
tags?: string[];
author?: { name: string };
}
export default component$(
({
message,
title = "Notice",
tone = "info",
priority = 1,
expanded = false,
tags = ["general"],
author = { name: "System" },
class: className,
style,
...attributes
}) => {
return (
{title}
{message}
Priority {priority}
Tagged {tags.join(", ")}, posted by {author.name}.
);
},
);
/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record {
const scope: Record = {};
for (const key of Object.keys(props)) {
if (key.startsWith("data-uf-")) scope[key] = "";
}
return scope;
}
```
#astro
```astro [Notice.astro]
---
export interface NoticeProps {
message: string;
title?: string;
tone?: "info" | "warning";
priority?: number;
expanded?: boolean;
tags?: string[];
author?: { name: string };
}
interface Props extends NoticeProps {
class?: string;
style?: Record;
}
const {
message,
title = "Notice",
tone = "info",
priority = 1,
expanded = false,
tags = ["general"],
author = { name: "System" },
class: className,
style,
} = Astro.props;
/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record {
const scope: Record = {};
for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
return scope;
}
---
{title}
{message}
Priority {priority}
Tagged {tags.join(", ")}, posted by {author.name}.
```
::
The compiler also reports, as [UF2001](/docs/reference/diagnostics#UF2001):
- a default on a required prop, which would never apply;
- a default other than `null` on a prop whose type admits `null`: Qwik's optimiser applies a destructured default to `null` too.
## Absent, undefined and null
A prop that is left out and a prop that is set to `undefined` are the same, on every target: the prop takes its default, or stays `undefined`. `null` is a value, and does not take the default.
`undefined` and `null` render nothing as text, and leave out an attribute they are bound to:
```tsx [ContactCard.uf.tsx]
export interface ContactCardProps {
name: string;
jobTitle?: string;
team?: string;
pronouns?: string;
phone?: string | null;
}
export default function ContactCard({ name, jobTitle, team, pronouns, phone }: ContactCardProps) {
return (
{name}
{jobTitle}
Phone: {phone ?? "not listed"}
);
}
```
Given only `name`, the `` has no `data-team`, the `
` has no `title`, the first `
` is empty and the last reads "Phone: not listed". Given `phone: ""`, the last reads "Phone:" and nothing more: `??` falls back only for `null` and `undefined`.
Compare with `null` to tell it from an absent prop:
```tsx [ContactLine.uf.tsx]
```
::
## Names
A prop's name is ASCII letters and digits, starting with a letter: Angular's expression lexer reads no other letter. These names are reserved ([UF2003](/docs/reference/diagnostics#UF2003)):
- `key`, `ref`, `children`, `class`, `style`, `slot` and `is`, which the frameworks read themselves;
- `props`, `rawProps`, `constructor` and `Astro`, which the outputs declare beside the props, and `Fragment`, which Astro's output imports to render `<>`;
- JavaScript's reserved words, Angular's expression keywords (`as`, `let`, `typeof`, …) and the globals expressions may read (`Math`, `String`, …);
- event names such as `onClick`: a component declares its events with `defineEmits`, and the outputs name their event props after them ([Events](/docs/components/events#component-events)); names that start with `ng` and a capital letter, such as `ngIf`; and names that end in `$`, which Qwik reads as a lazy function.
A local type cannot take a name the outputs declare or import themselves, such as `CSSProperties`, `Component` or `Partial`. A type named `Props` is accepted when every component whose props reach it takes it as its props type: Astro's output declares a `Props` of its own for any other component.
## Not yet
- A rest element (`...rest`) is [UF2001](/docs/reference/diagnostics#UF2001): a component's fallthrough is its `class` and `style`, which merge into its root ([Fallthrough](/docs/components/fallthrough)).
- A conditional or mapped type, `keyof`, `typeof` or a template literal type in the props is [UF6002](/docs/reference/diagnostics#UF6002) under the default type oracle, which reads types as written ([What stays out](/docs/components/types-and-generics#what-stays-out)).
The decisions behind this page are [ADR-0001](https://github.com/uxfront-com/unframework/blob/main/docs/adrs/0001-component-shape.md), [ADR-0007](https://github.com/uxfront-com/unframework/blob/main/docs/adrs/0007-canonical-forms.md) and [ADR-0034](https://github.com/uxfront-com/unframework/blob/main/docs/adrs/0034-props-in-the-signature.md).
# Templates
> The JSX a component returns is its template. Its expressions, text, conditionals, lists and fragments compile to each framework's own template syntax.
A component returns its template: one element, or one fragment that holds several. The compiler lowers that JSX to each framework's template. Vue, Svelte, Angular and Astro have template languages of their own, so the compiler accepts the JSX that all seven read alike, and reports anything else with a code that names the reason.
A component is an exported function declaration. One written as an arrow function in a `const` is [UF1102](/docs/reference/diagnostics#UF1102), with a fix that declares it as a function. A returned conditional or list is UF1102 too, with a fix that wraps it in `<>…>`, which renders the same, and so is an empty fragment.
## Expressions
An expression in braces can be a child, an attribute's value, a condition, a list's source or key, a part of a `class` or a `style`, or the source of a spread. It can read:
- the component's props;
- the setup's bindings: state and derived values as `count.value`, constants, ids, and calls of local functions that change nothing ([State](/docs/components/state));
- the item and the index of each list around it;
- the parameters of the arrow functions inside it, as in `items.filter((item) => item.done)`;
- a few pure globals: `undefined`, `NaN`, `Infinity`, `Math`, `Number`, `String`, `Boolean`, `Array`, `Object`, `JSON`, `parseInt`, `parseFloat`, `isNaN`, `isFinite`, `encodeURIComponent`, `decodeURIComponent`, `encodeURI` and `decodeURI`.
Any other name is [UF3020](/docs/reference/diagnostics#UF3020): Angular's templates see only the component's members, and the outputs may run where `window` does not exist. A template reads no template ref and no setup `let`, which are not reactive ([UF2010](/docs/reference/diagnostics#UF2010)), and calls only local functions that write, emit and await nothing ([UF2014](/docs/reference/diagnostics#UF2014)). Listeners are on [Events](/docs/components/events).
A list's or an arrow function's parameter cannot take a name the outputs rewrite or declare ([UF3024](/docs/reference/diagnostics#UF3024)): a prop's, a setup binding's, the props parameter's, an outer list variable's or a global's, `props`, `rawProps`, `Fragment`, or a name that starts with `$`, or with `_` and more (`_` alone is accepted). Nor can it take one of Angular's expression keywords, such as `as`, which its templates cannot read as a name.
```tsx [OrderSummary.uf.tsx]
```
::
Solid reads a prop as `props.name`, because its props are reactive getters. Angular's template sits inside a TypeScript template literal, so its output writes a template literal as a concatenation, and it declares each global an expression reads as a member of the component:
```ts [order-summary.ts]
protected readonly Math = Math;
protected readonly String = String;
```
Angular's output also writes literals in the spellings its template lexer reads. In a regular expression, for example, `'` becomes `\x27` and `;` becomes `\x3b`.
### The syntax every target reads
- Literals: strings, decimal numbers, booleans, `null`, regular expressions and template literals.
- Member access (`a.b`, `a[b]`, `a?.b`), calls and optional calls.
- Array literals, and object literals with identifier or string keys, both with spreads.
- Arrow functions, as a call's argument, with plain parameters and an expression body.
- The unary operators `!`, `-`, `+` and `typeof`, the arithmetic, equality and comparison operators, `&&`, `||` and `??`, the conditional operator and parentheses.
Angular's template parser rejects or misreads most of the rest, so it waits as [UF1002](/docs/reference/diagnostics#UF1002). Where a rewrite is mechanical, the diagnostic carries a fix:
| Not yet | Why | Fix |
| -------------------------------------------------------------- | ------------------------------------------------------- | --------------------------- |
| An arrow function with a block body | Angular: "Multi-line arrow functions are not supported" | `{ return e; }` becomes `e` |
| Arrow parameters with patterns, defaults, types or rest | Angular's parser rejects each | |
| `as`, `!`, `satisfies` and type arguments | Angular's templates have no TypeScript syntax | |
| `0x10`, `0o7` and `0b1` | Angular: "Unexpected token" | The decimal value |
| `\u{…}` escapes | Angular: "Invalid unicode escape" | `\uXXXX` pairs |
| Holes in arrays, and `Array(…)` | Angular rejects holes, and holes iterate differently | |
| Computed keys, methods, getters and setters in object literals | Angular rejects them | |
| Names outside ASCII | Angular's lexer reads ASCII only | |
| `new` and the bitwise operators | Angular rejects `new`, and `\|` is its pipe | |
| `in`, `instanceof`, tagged templates and BigInt literals | No case needs them yet | |
### Narrowing
A condition narrows what it tests, as TypeScript does. In the branch of `member && …`, an optional `member` is present, so the branch reads `member.email`:
```tsx [AccountSummary.uf.tsx]
{member &&
Signed in as {member.email}
}
```
A union narrows the same way, by `Array.isArray`, `typeof` or a discriminant:
```tsx [FilterSummary.uf.tsx]
)}
```
::
Every target's checker narrows as TypeScript narrows the source, and the compiler follows the same tests: a test of the value itself, through `!`, `&&` and `||`, a comparison with `null`, `undefined` or a value, `typeof`, a member read through `?.`, `Array.isArray`, and a discriminant of a union, as `plan.kind === "paid"` narrows `plan`. Where a value can be neither `null` nor `undefined`, by its type or by such a test, `a?.b` and `a ?? b` do nothing, and Angular's compiler rejects them: [UF3023](/docs/reference/diagnostics#UF3023), with a fix that removes the operator.
A destructured prop that a conditional child narrows stays narrowed in that branch's lists and arrow functions, on every target. TypeScript forgets a property's narrowing inside a callback, though, where Angular's loops keep it. So where the checkers read a value apart, a use that relies on a narrowing some of them do not see is [UF1002](/docs/reference/diagnostics#UF1002):
- a member, or a prop of the object form, that a condition outside a list narrows, used inside the list's callback: test it inside the callback;
- a prop that a conditional inside an expression narrows, used in an arrow function in that expression: read it through `?.`, or give it a value with `??`, as in `item.includes(query ?? "")`;
- a narrowed prop that a list's key uses, because Angular's `track` reads the input again: give it a value where it may be absent, as in `(count ?? 0) + index`.
Testing the value, reading it through `?.`, giving it a value with `??`, comparing it for equality and writing it into a string read alike everywhere, so those uses are accepted. An equality with a value that is no literal (`box.inner?.title === label`) is a test the compiler does not follow: a `?.` or `??` that Angular may then reject is UF1002 too. A relational comparison or a call narrows nothing on any checker, so the source's own type check judges what follows it.
### Pure and deterministic
A component renders on the server and again in the browser, and a framework renders when it decides to, sometimes twice. So an expression must not change anything, and must give the same result everywhere:
- [UF3021](/docs/reference/diagnostics#UF3021): no assignment, `++`, `delete`, `void`, comma operator, `await`, `yield`, `this`, function or class expression, and no call of a method that changes its receiver (`sort`, `reverse`, `splice`, `push`, …). The fix writes `toSorted`, `toReversed` and `toSpliced`.
- [UF3019](/docs/reference/diagnostics#UF3019): no `Date`, `Intl`, `crypto`, `performance`, `globalThis` or `Math.random`, and no locale methods (`toLocaleString`, `localeCompare`, …). Pass such a value in as a prop.
## Text
An expression child renders its value as text: a string as it is, and a number as `String(n)`. `null` and `undefined` render nothing, and so do `{""}` and a comment, `{/* … */}`.
A boolean, an array or an object is [UF3016](/docs/reference/diagnostics#UF3016): JSX and the template languages render them differently. Turn the value into text first: `done ? "Done" : "Open"`, `tags.join(", ")`, or a member of the object.
### Whitespace
Text between tags follows JSX's rules: each line is trimmed, lines that hold only whitespace are dropped, and the lines that remain join with one space. Character references decode as JSX decodes them: the named references of XHTML 1.0 (`&`, ` `) and numeric ones. A reference only HTML knows, such as `✓`, stays as written and warns ([UF3011](/docs/reference/diagnostics#UF3011)).
A string literal child is a JavaScript string: it is neither trimmed nor decoded. Write a significant space or line break as one, `{" "}` or `{"\n"}`:
```tsx [ShippingLabel.uf.tsx]
{city}{" "}
{postcode}{" "}
United Kingdom
```
Each target writes that space the way its compiler keeps it:
::framework-switcher
#react
```tsx [ShippingLabel.tsx]
{city}{" "}
{postcode}{" "}
United Kingdom
```
#vue
```vue [ShippingLabel.vue]
{{ city }}{{ postcode }}United Kingdom
```
#svelte
```svelte [ShippingLabel.svelte]
{city}{postcode}United Kingdom
```
#angular
```ts [shipping-label.ts]
{{ city }}&ngsp;{{ postcode }}&ngsp;United Kingdom
```
#solid
```tsx [ShippingLabel.tsx]
{props.city}{" "}
{props.postcode}{" "}
United Kingdom
```
#qwik
```tsx [ShippingLabel.tsx]
{city}{" "}
{postcode}{" "}
United Kingdom
```
#astro
```astro [ShippingLabel.astro]
{city}{postcode}United Kingdom
```
::
Each output breaks its lines only where its framework drops the whitespace. Svelte keeps the whitespace between tags, so its output closes a tag at the start of the next line (`
`), which adds no text to the page.
A line feed that starts the text of a `
`, a `
}>
{(member) =>
Role: {member.admin ? "administrator" : "member"}
}
No profile}>
{(member) =>
Profile of {member().name}
}
{(narrowed) =>
Team: {narrowed().team.name}
}
{(narrowed) =>
Uptime {narrowed().uptime.toFixed(1)}%
}
```
`x || ` and `x ?? ` are [UF3025](/docs/reference/diagnostics#UF3025): they render either the value of `x` or an element, which no template language writes as one conditional. Write `x ? x : ` for `||`, and `x != null ? x : ` for `??`, which renders `0` and `""` as `??` does. Where `x` is a prop rendered as text, the fix writes it.
## Lists
A list is a `.map` child whose callback returns one element with a `key`:
```tsx [StepList.uf.tsx]
export interface StepListProps {
title: string;
steps: string[];
}
export default function StepList({ title, steps }: StepListProps) {
return (
{steps.map((step, index) => (
))}
);
}
/** Joins class names, and the keys of an object's truthy entries, into one `className`. */
function cx(...parts: unknown[]): string {
const names: string[] = [];
for (const part of parts) {
if (typeof part === "string") {
if (part) names.push(part);
} else if (part && typeof part === "object") {
for (const [key, on] of Object.entries(part)) {
if (on) names.push(key);
}
}
}
return names.join(" ");
}
/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record {
const scope: Record = {};
for (const key of Object.keys(props)) {
if (key.startsWith("data-uf-")) scope[key] = "";
}
return scope;
}
```
#vue
```vue [StepList.vue]
Step {{ index + 1 }}: {{ step }}
```
#svelte
```svelte [StepList.svelte]
{#each steps as step, index (index)}
Step {index + 1}: {step}
{/each}
```
#angular
```ts [step-list.ts]
import {
Component,
Directive,
ElementRef,
type OnInit,
Renderer2,
inject,
input,
} from "@angular/core";
export interface StepListProps {
title: string;
steps: string[];
}
/** The scope attributes taken off each host, for the roots its component renders later. */
const scopes = new WeakMap();
/**
* Gives a root node of its component the scope attributes the component's styled parents put on
* its host (ADR-0063), and takes them off the host, which keeps only `display: contents`.
*/
@Directive({ selector: "[ufScope]" })
export class ScopeAttributes implements OnInit {
readonly ufScope = input.required();
private readonly element = inject>(ElementRef);
private readonly renderer = inject(Renderer2);
ngOnInit(): void {
const host = this.ufScope();
let names = scopes.get(host);
if (!names) {
names = host.getAttributeNames().filter((name) => name.startsWith("data-uf-"));
for (const name of names) this.renderer.removeAttribute(host, name);
scopes.set(host, names);
}
for (const name of names) this.renderer.setAttribute(this.element.nativeElement, name, "");
}
}
@Component({
selector: "uf-step-list",
imports: [ScopeAttributes],
host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
preserveWhitespaces: false,
template: `
@let title = this.title();
@let steps = this.steps();
@for (step of steps; track index; let index = $index) {
)}
);
}
/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record {
const scope: Record = {};
for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
return scope;
}
/** A list whose rows follow their keys, so a row keeps its element while the list reorders and while its item is replaced. */
function KeyedFor(props: {
each: readonly T[];
by: (item: T, index: number) => unknown;
children: (row: { readonly value: T; readonly index: number }) => JSX.Element;
}): JSX.Element {
const items = createMemo(() => {
const rows = new Map();
props.each.forEach((item, index) => {
const key = props.by(item, index);
rows.set(rows.has(key) ? {} : key, item);
});
return rows;
});
return (
{(key, index) => {
const item = createMemo(() => items().get(key) as T);
return untrack(() =>
props.children({
get value() {
return item();
},
get index() {
return index();
},
}),
);
}}
);
}
```
#qwik
```tsx [StepList.tsx]
import { type CSSProperties, type ClassList, component$ } from "@qwik.dev/core";
export interface StepListProps {
title: string;
steps: string[];
}
export default component$(
({ title, steps, class: className, style, ...attributes }) => {
return (
{steps.map((step, index) => (
Step {index + 1}: {step}
))}
);
},
);
/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record {
const scope: Record = {};
for (const key of Object.keys(props)) {
if (key.startsWith("data-uf-")) scope[key] = "";
}
return scope;
}
```
#astro
```astro [StepList.astro]
---
export interface StepListProps {
title: string;
steps: string[];
}
interface Props extends StepListProps {
class?: string;
style?: Record;
}
const { title, steps, class: className, style } = Astro.props;
/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record {
const scope: Record = {};
for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
return scope;
}
---
{steps.map((step, index) => (
Step {index + 1}: {step}
))}
```
::
- The callback is an arrow function with one or two plain parameters: the item, and its index. Read the item's members as `item.name`, rather than destructuring it, and an entry of `Object.entries` as `entry[0]` and `entry[1]` ([UF3015](/docs/reference/diagnostics#UF3015)).
- It returns one element. Filter out an item that renders nothing first: `items.filter((item) => item.done).map(…)`. An item that renders one element or another keeps one keyed element that holds the conditional, and several elements are wrapped in one.
- The element has a `key` that reads the item or its index ([UF3013](/docs/reference/diagnostics#UF3013), [UF3018](/docs/reference/diagnostics#UF3018)). It is a string or a number, unique in the list. It is written `key`, in lower case: in JSX, `KEY` is an attribute ([UF3004](/docs/reference/diagnostics#UF3004), with a fix). A second `key` is [UF3007](/docs/reference/diagnostics#UF3007), and `key` anywhere else is [UF3014](/docs/reference/diagnostics#UF3014).
- The source is an array. When it can be absent, default it: `(items ?? []).map(…)`. For `items?.map(…)`, the compiler reports [UF3018](/docs/reference/diagnostics#UF3018) with a fix that writes the default, or, where `items` is never absent, [UF3023](/docs/reference/diagnostics#UF3023) with a fix that writes `.map`.
```tsx [BuildLog.uf.tsx]
{(warnings ?? []).map((warning) => (
))}
```
::
Each target writes its own list. Solid's `` follows the items themselves, so its list goes through an inline helper, `KeyedFor`, which keys each row by the source's `key`, as `by`, and passes each row an object of getters, `warning.value` and `warning.index`, which TypeScript narrows as it narrows a prop. Astro renders on the server only, so its output leaves the key out. An unread index is left out too.
A list renders its items' content in the array's order on every target, and a keyed item keeps its element, with what was typed into it, while the array reorders or replaces it. Its focus stays where it keeps its place ([Semantics](/docs/reference/semantics#keyed-lists)). Astro renders a list once, on the server.
## Fragments
A fragment groups nodes without an element. It can be the component's root, a branch of a conditional, or a run of children, which it flattens into its parent:
```tsx [ArticleHeader.uf.tsx]
export interface ArticleHeaderProps {
title: string;
subtitle?: string;
draft: boolean;
tags: string[];
}
export default function ArticleHeader({ title, subtitle, draft, tags }: ArticleHeaderProps) {
return (
<>
{title}
{subtitle &&
{subtitle}
}
{draft ? (
<>
Draft
Only editors can see this article.
>
) : (
<>
Published
Everyone can read this article.
>
)}
Tagged <>{tags.join(", ")}>
>
);
}
```
Each target groups a branch's nodes its own way:
::framework-switcher
#react
```tsx [ArticleHeader.tsx]
{draft ? (
<>
>
)}
```
::
On Angular, a root fragment renders inside the component's host element, which is styled `display: contents` (see [Targets](/docs/reference/targets#the-angular-host)).
## Where nodes can go
The HTML parser repairs some markup, and server-rendered HTML then differs from a client's DOM. The nesting rules ([UF3003](/docs/reference/diagnostics#UF3003)) look through conditionals, lists and fragments:
- rows that a `.map` renders directly in a `
` would get a ``: write it;
- an expression renders text, so it cannot sit where text cannot, such as a table part, a `