# hype › Guide

Signals, `html` templates and custom elements, drawn in the page or written to a
string. No dependencies, no compiler, about 4 KB gzipped.

```ts
import { define, html, signal } from "@diso.io/hype";

define("x-counter", { props: { start: 0 } }, ({ start }) => {
	const count = signal(start.value);
	return html`
		<button @click=${() => count.value++}>clicked ${() => count.value} times</button>
	`;
});
```

```html
<x-counter start="3"></x-counter>
```

## Signals

A signal holds a value. Anything that reads it inside an effect or a template is
rerun when the value changes.

```ts
import { computed, effect, onCleanup, signal } from "@diso.io/hype";

const name = signal("Ada");
const shout = computed(() => name.value.toUpperCase());

const stop = effect(() => {
	console.log(shout.value);
	onCleanup(() => console.log("before the next run, and on stop"));
});

name.value = "Grace";
```

| | |
| --- | --- |
| `signal(value)` | A value to read and set through `.value`. |
| `computed(fn)` | A value worked out from other signals. Its readers rerun only when the result changes. |
| `effect(fn)` | Runs `fn` now and after any signal it read changes. Returns a function that stops it. |
| `onCleanup(fn)` | Inside an effect or an element: runs `fn` before the next run and on stop. |

Changes are batched: setting several signals in a row reruns each effect once,
in a microtask. An effect made inside another effect or an element stops with it.

## Templates

`html` takes HTML with values in it. A value that is a **function** is live: it
is called again whenever a signal it reads changes, and only that place in the
page is updated. Any other value is placed once.

```ts
html`<p class=${kind}>${() => count.value}</p>`;
```

| Written | Does |
| --- | --- |
| `${value}` between tags | Content: text, a template, a DOM node, or a list of these. `null`, `undefined` and `false` draw nothing. |
| `name=${value}` | An attribute. `null` or `undefined` removes it. |
| `name="a ${value} b"` | An attribute made of text and values. |
| `?name=${value}` | A boolean attribute, present when the value is truthy. |
| `.name=${value}` | A property of the element. Use it to pass objects to a custom element. To pass a function itself, wrap it: `.name=${() => fn}`. |
| `@name=${handler}` | An event listener. |

`svg` is the same for a piece of SVG that goes inside an `<svg>`. `nothing` is a
value that draws nothing. `raw(text)` is a string of HTML as a template,
for markup made elsewhere; the string is placed as it is, so it must come from
a source that is trusted.

A function that returns a template rebuilds that piece each time it reruns. Keep
state such as a text input out of pieces that rebuild, by having the function
read a `computed` that changes less often and placing narrower functions inside:

```ts
const failed = computed(() => error.value !== "");
html`${() => (failed.value ? html`<p role="alert">${() => error.value}</p>` : nothing)}`;
```

A template is checked the first time it is drawn. A value where one cannot go —
as a tag name, loose inside a tag, inside a comment, or inside `<textarea>`,
`<style>`, `<script>` or `<title>` — throws an error that says so. A custom
element must be closed with its own closing tag.

`render(value, container)` draws a value into a container and returns a function
that stops its effects.

## Elements

`define(name, options, setup)` defines a custom element. `setup` runs each time
the element enters the page and returns what to draw.

```ts
import { css, define, html, onMount } from "@diso.io/hype";

define(
	"x-card",
	{
		props: { heading: "", wide: false, item: null as Item | null },
		styles: css`
			h2 { margin: 0; }
		`,
	},
	({ heading, wide, item }, host) => {
		onMount(() => host.querySelector("h2")?.focus());
		return html`<h2>${() => heading.value}</h2><slot></slot>`;
	},
);
```

- **`props`** names the element's props and gives their defaults. `setup`
  receives each one as a signal. A prop can be set as a property, or as an
  attribute named in kebab-case (`videoId` is `video-id`). An attribute is read
  as the type of the prop's default: a boolean is whether the attribute is
  present, a number is parsed, anything else is the attribute's text.
- **`styles`** is CSS for the element alone. Giving it draws the element in a
  shadow root, where content placed inside the element shows through `<slot>`.
  `shadow: true` does the same without styles.
- Without `styles` or `shadow` the element draws directly inside itself, where
  the page's own CSS applies, and replaces anything written inside it.
- **`onMount(fn)`** runs once the content is in the page. Call `onCleanup`
  inside it to undo what it did.
- `host` is the element. It is not in a page when rendering to a string, so use
  it only inside `onMount` and event handlers.

Signals read directly in `setup` are not followed; `setup` runs once. An element
moved within the page keeps its state. One that leaves the page stops, and
starts again if it comes back.

### An element as a class

Write an element as a class when other code calls its methods, or when it has
to meet an interface. Extend `HypeElement`, give `draw`, and pass the class to
`define`.

```ts
import { define, html, HypeElement, signal } from "@diso.io/hype";

interface Cart {
	add(item: Item): void;
}

class ShopCart extends HypeElement<typeof ShopCart.props> implements Cart {
	static props = { currency: "USD" };

	items = signal<Item[]>([]);

	add(item: Item) {
		this.items.value = [...this.items.value, item];
	}

	draw() {
		return html`<button>
			${() => this.items.value.length} items, in ${() => this.props.currency.value}
		</button>`;
	}
}

define("shop-cart", ShopCart);
```

The class is the element itself, so its methods are called on the element:

```ts
document.querySelector<ShopCart>("shop-cart")?.add(item);
```

- **`draw()`** is what `setup` is to a function: it runs each time the element
  enters the page and returns what to draw. `onMount` and `onCleanup` work
  inside it.
- **`static props`**, **`static styles`** and **`static shadow`** are the
  options a function's element takes. `this.props` holds each prop as a
  signal. `HypeElement<typeof ShopCart.props>` types them from the defaults,
  so props are written once.
- **State** is a signal in a field, as `items` is above.
- **`implements`** holds the class to an interface, so two elements that meet
  the same one can stand in for each other.

A prop whose type is wider than its default says so on the default, or the
props are given an interface of their own:

```ts
static props = { size: "small" as "small" | "large" };
```

```ts
interface CartProps {
	size: "small" | "large";
}

class ShopCart extends HypeElement<CartProps> {
	static props: CartProps = { size: "small" };
}
```

`draw` also runs when a page is written to a string, where the element is not
in a page. Reach for the page (`this.querySelector`, `this.dispatchEvent`)
inside `onMount`, event handlers and methods, never in `draw` itself.

## Rendering to a string

`renderToString(value)` returns markup with every defined element's content
written inside it. It needs no DOM, so it runs in Node or a Worker.

```ts
import { html, renderToString } from "@diso.io/hype";
import "./components";

const page = renderToString(html`<x-card heading="Hello">Welcome.</x-card>`);
```

Its purpose is to give crawlers and first paint something to read. The page is
still an app: when the script loads, each element draws over what was written
for it. An element in a shadow root is written as a
[declarative shadow root](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/template#shadowrootmode)
with its styles.

When rendering to a string, `setup` runs and `onCleanup` runs after it;
`onMount`, event listeners and effects that rerun belong to the page and do not.

## What it does not do

- Reorder a list in place. A list drawn from a signal is redrawn when the signal
  changes.
- Pass content into an element that has no shadow root.
