# Markup

Tags, values, styles, colour roles, conditional styles, control, routes,
binding, components. Events are in [events.md](events.md); the kit's
components are in [kit.md](kit.md). Back to the [map](README.md).

```mote
// docs: whole
state n = 0 persist
derive double = n * 2

row gap=12 padding=24 align-items=center
  button "−" press={n -= 1} disabled=(n <= 0)
  text `${n}` font-size=24
  button "+" press={n += 1}
  if n > 0
    text `doubled: ${double}` color=dim
```

## Mental model

A line of markup is `tag text? name=value…`, and its children are the lines
indented under it. There is one syntax for attributes, styles and events:
`name=value`. The compiler knows which is which from the name
(`compiler/src/tables.rs`):

- an event (`press`, `input`, …) becomes a listener ([events.md](events.md));
- an HTML attribute (`id`, `href`, `placeholder`, `aria-*`, `data-*`, …) is
  set on the element;
- anything else that is a CSS property is a style.

A name that is none of these is refused (`H041`), so a typo cannot ship.

What can never change becomes HTML text at build time. A page with nothing
dynamic on it ships no JavaScript at all. The rest becomes JavaScript that
builds the nodes once and binds each dynamic value to the state it reads
(`view.rs`, `Gen::el`): when `n` changes, only the text node that shows `n`
is touched. There is no virtual DOM and nothing is re-rendered
([reactivity.md](reactivity.md)).

Constant styles become atomic CSS classes in the page's `<style>` (one class
per `property: value`, shared by every element that says it). A computed
style is set on the element itself.

## Tags

| Tag | Is | Notes |
|---|---|---|
| `view`, `box` | `<div>` | |
| `row` | `<div>` | `display: flex` |
| `column` | `<div>` | `display: flex; flex-direction: column` |
| `grid` | `<div>` | `display: grid` |
| `text` | `<span>` | |
| `image "src"` | `<img>` | The text is the source ([below](#pictures-and-assets)). |
| `link "label" href="…"` | `<a>` | |
| `icon "camera"` | `<svg>` | One of Lucide's icons ([below](#icons)). |
| `popover`, `tip` | floating panels | Written under the element they belong to ([below](#popover-and-tip)). |
| HTML's own names | themselves | `button input textarea select option label form h1`…`h6 p ul ol li table thead tbody tfoot tr th td caption section header footer main nav article aside pre code strong em small kbd mark del ins sub sup hr br details summary dialog progress time iframe fieldset legend blockquote figure figcaption dl dt dd datalist video audio canvas div span a img` |
| `camera`, `reel` | media | [media.md](media.md) |
| `canvas layers=…`, `canvas boxes=…`, `surface` | drawing | [media.md](media.md#paint), [drawing.md](drawing.md) |
| `editor`, `terminal`, `flow` | widgets the runtime builds | [widgets.md](widgets.md) |
| A capitalised name | a component | [below](#components), [kit.md](kit.md) |

An unknown tag is refused (`H040`). `View` and `Text` are told to be `view`
and `text`.

## Text

The first thing after the tag, if it is not `name=value`, is the element's
text: a string, a template, or a name.

```mote
text "Hello"
text `${n} left`
text t.title
text (a ?? b)              // anything with an operator goes in parentheses
```

`text Hello` is refused (`H020`: quote it). A text shows a string, a number
or a bool; a list, a record or bytes is refused (`H069`). `none` shows as
nothing.

On `input`, `textarea`, `select`, `hr`, `br`, `video`, `audio`, `dialog`,
`details` and `form`, which have no text, a lone word is a boolean attribute
(`input autofocus`). On other tags a lone word after the text is one too:
`button "Go" disabled`.

## Values

A value is one of:

| Form | Example |
|---|---|
| a string or template | `"Save"`, `` `${n} items` `` |
| a number | `12`, `-4`, `0.8` |
| a number with a unit | `12px`, `50%`, `1fr`, `2rem`, `400ms` |
| a colour | `#0a84ff`, `#fff` |
| a bare keyword | `center`, `space-between`, `checkbox`, `inline-flex` |
| a name with its chain | `t.title`, `draft.trim()`, `xs[0]`, `!done` |
| any expression, in parentheses | `(n <= 0)`, `(done ? "dim" : "fg")` |
| a handler block | `{n += 1; open = false}` |

**A space ends a value.** Anything with an operator goes in parentheses:
`disabled=(n <= 0)`, not `disabled=n <= 0` (`H018`). A value of several
words is a string: `margin="0 auto"`, `border="1px solid"`.

A bare word that names nothing in scope is a keyword (`center`). If the page
has a state called `center`, the bare word is that state. Three kinds of bare
word are always themselves, whatever the page has of the same name:

- on a style, a word that names a `fn` or an `action`: a fn is no style's
  value, so `flex-wrap=wrap` and `justify-content=center` mean CSS's words
  in a program that has an `action wrap` or a `fn center`;
- where HTML has its own words for an attribute (`type=color`, `role=tab`,
  `loading=lazy`, `dir=rtl`, `wrap=off`, `method=post`, `preload=none`,
  `inputmode=numeric`, `enterkeyhint=send`, `autocapitalize=words`,
  `decoding=async`, `fetchpriority=low`), the word;
- on a colour property, a colour role: `color=accent` is the role. A state
  named `accent` is `color=(accent)`.

## Styles

Any CSS property by its own name: `padding=16 gap=8 color=dim`.

- A bare number is pixels, except on `flex`, `flex-grow`, `flex-shrink`,
  `opacity`, `z-index`, `line-height`, `font-weight`, `order`,
  `aspect-ratio`, `scale`, `zoom`, `line-clamp`, `columns`, `grid-column`,
  `grid-row`, `grid-area`. `0` is `0`.
- `display=none`: on a style, `none` is CSS's keyword.
- `lines=2` on anything that holds words: no more than two lines of them,
  the last ending in an ellipsis (`lines=1` for one). It may be worked out:
  `lines=(open ? 99 : 2)`. (On an `editor`, `lines` is its gutter.)
- A property of one browser's own is written as CSS writes it, hyphen
  first: `-webkit-text-stroke-width=1`, `-webkit-line-clamp=3`. A bare
  number on one is pixels or not as on the property without its prefix.
- A longhand always wins over its shorthand, whatever the order written:
  `padding=16 padding-top=4`.
- `width` and `height` are HTML attributes on `image`, `canvas`, `video` and
  `iframe`, and styles everywhere else.
- `image-rendering=pixelated` shows a scaled picture or canvas with hard
  pixels.
- There is no `style=` and no `class`-based styling to write; `class` exists
  for hooks of your own (a test's selector, a library).

The page starts from a small base: `font: 16px/1.5 system-ui`, border-box
sizing, no body margin, and `color-scheme: light dark`.

### Colour roles

Nine names follow light and dark on their own:

`fg` `bg` `dim` `card` `line` `accent` `danger` `ok` `warn`

Use them bare on any colour property (`color`, `background`, anything ending
in `color`, `fill`, `stroke`): `color=dim background=card border-color=line`.
In a computed colour, name the role as a string:
`color=(done ? "dim" : "fg")`.

A role written bare is always the role, whatever the page names:
`color=accent` is the accent colour even if the page has `state accent`.
To use that state, put it in parentheses: `color=(accent)`.

`accent` is `app … accent=#…` if the app says one. Each role is a CSS
variable (`--dim`) on the root; only the roles a page uses are written.

### Animation

`animation="rise 400ms ease"`. Five are built in: `spin`, `pulse`, `fade`,
`rise`, `pop`. A named one ships its keyframes; the rest stay out of the page.

### glass

`row glass` (or `glass=24` for more blur): what is behind the element shows
through, blurred, with a lit rim. In Chromium the rim also bends what is
behind it (`runtime/page/glass.mote`). A background, border or shadow written
beside it replaces glass's own.

## Conditional styles

A child line that starts with one of these words is not an element: it is
styles for the element above it, while the condition holds.

```mote
// docs: whole
state items = ["One", "Two"]

column gap=8 padding=16
  button "Save" background=accent color=#ffffff
    hover opacity=0.8
    active scale=0.98
    focus outline="2px solid"
    disabled opacity=0.5
  for t in items
    row group gap=8 padding=8
      text t
      button "Delete" opacity=0
        in hover opacity=1
  row gap=24
    phone flex-direction=column gap=12
    dark background=#111111
    text "Side by side, or stacked on a phone"
```

| Word | Holds while |
|---|---|
| `hover` `active` `focus` `disabled` `checked` | the element is in that state |
| `phone` | the window is under 640 wide |
| `tablet` | 640 to 1023 |
| `desktop` | 1024 and up |
| `dark` `light` | that colour scheme is on |
| `print` | the page is on paper (or in the print preview) |
| `still` | less motion is wanted: the system asks for it, or the page said `root motion="less"` ([below](#values-of-the-whole-page)) |
| `in root[density=compact]` · `in root[contrast]` | the page's root says so: a value a `root` line set ([below](#values-of-the-whole-page)) |
| `dragging` · `over` · `over top` (`bottom` `left` `right`) | the element is being carried · something is held over it · over that half of it ([events.md](events.md#dragging)) |

No media queries to write. Under `print`, a length may be in paper's units
(`width=190mm`).

**A value worked out when the page runs** is written as anywhere else, in
parentheses if it has an operator:

```mote
// docs: whole
state skin = {hover: "#2b6cb0", on: "#1a4971"}
state busy = false

column gap=8 padding=16
  button "Blue" press={skin = {hover: "#2b6cb0", on: "#1a4971"}}
  button "Plum" press={skin = {hover: "#7b3f8c", on: "#4a2355"}}
  row padding=12 background=card
    hover background=skin.hover color=#ffffff
    active background=skin.on scale=(busy ? 1 : 0.98)
    phone padding=(busy ? 4 : 8)
    text "A row whose hover colour follows the theme"
```

The line's rule reads a CSS custom property (`--hover-background`), and the
element is given that property and keeps it current. So every word of the
table takes such values (`hover`, `in hover`, `phone`, `dark`, `over top`,
…), a colour role may be computed (`hover color=(done ? "dim" : "fg")`), and
a bare number is pixels where the style takes a length. What a line may not
be is something that is not a style (`H043`).

**From an element above**: mark it `group`, and inside it a line
`in hover …` (or `in active`, `in focus`, `in checked`, `in disabled`)
styles a child while *that* element is in the state. `in focus` holds while
the keyboard is anywhere inside the group. With several groups, name them:
`group="card"` and `in card hover …`.

The same in logic and markup, as values: `screen.phone` `screen.tablet`
`screen.desktop` `screen.dark` `screen.still` (bools), `screen.width` `screen.height`
(numbers), all reactive. `screen.keyboard` is how many pixels of the window's
foot a keyboard on the screen stands over, 0 without one: a phone puts its
keyboard over the page and leaves the window the size it was, so what is fixed
to the foot is behind it (`padding-bottom=screen.keyboard` at the end of a
list lets its end be scrolled up from under it). `scheme("dark" | "light" | "auto")` tells the page a
scheme and keeps it for the next visit; `screen.scheme` is what it was told
(`"auto"` when it follows the system). `app … scheme=dark` fixes it.

### Values of the whole page

A preference (compact rows, larger text, a theme's colour, less motion) is
one value that elements in every file must follow. `root` puts values on
the page's root element, from state; a style line anywhere asks about them
with `in root[…]`, or reads a variable.

```mote
// docs: whole
state density = "cozy" persist
state zoom = 1 persist
state brand = "#0a84ff" persist
state calm = false persist

root density=density zoom=zoom var-brand=brand motion=(calm ? "less" : "system")

column gap=8 padding=16
  in root[density=compact] gap=2 padding=4
  row gap=8
    button "Compact" press={density = "compact"}
    button "Cozy" press={density = "cozy"}
    button "Larger" press={zoom = 1.25}
    button "Pink" press={brand = "#ff0066"}
    button "Less motion" press={calm = true}
  link "A link in the theme's colour" href="https://example.com" color="var(--brand)"
  text "This eases in" transition="opacity 300ms"
    still transition=none
```

`root name=value …` is written at the top of a file (any file of the
program: the entry or one it `use`s), outside any component. It shows
nothing. Each value is kept current, and is one of three things by its
name:

| Name | Is | Read with |
|---|---|---|
| a CSS property (`zoom=1.1`, `font-size=18`) | a style of the root element itself; a bare number is pixels where the property takes a length | it applies as CSS does (`zoom` scales the page, `font-size` is what `rem` and unset text follow) |
| `var-name` (`var-brand=brand`) | the CSS variable `--name` | `"var(--name)"` wherever a style takes a value: `color="var(--brand)"`, `padding="var(--pad)"`. A role's own name re-colours the role everywhere: `var-accent=brand`, `var-bg=…`, `var-fg=…` ([roles](#colour-roles)) |
| any other name (`density=density`, `contrast=high`) | a value on the root (`data-density="compact"`). `none`, `false` and `""` take it away; `true` is there with nothing to say | a child line `in root[density=compact] padding=2` (the value is that), or `in root[contrast] …` (it is there at all) |

An `in root[…]` line is a line of styles like `hover` or `phone`: it
takes worked-out values too, and wins over the element's plain styles and
its states. The value in the brackets is a word, a number or a string, as
it is written on the root.

**The language.** `lang`, `dir` and `translate` on `root` are HTML's own
attributes on the page's root element, not values: `root lang=locale`
says the language the page is in now (screen readers, translators,
hyphenation and spell checking follow it), `dir=rtl` turns the page to
run right to left, `translate=no` keeps translators off the whole page.
`none` or `""` takes one away. The page's `<html lang>` is, in this
order: what `root lang=` says, while it says one; else, in an app with
[`words`](words.md), the language its words are shown in (`words.lang`,
which follows the reader's choice); else the app's own, `app "X"
lang="de"` (unsaid `"en"`).

**Less motion.** `motion` is the one name the runtime itself reads.
Wherever a page animates or eases anything, what moves arrives at once
when the system asks for less motion (the reader's own setting), with
nothing to write. `root motion="less"` asks for that whatever the system
says; `motion="full"` keeps motion also where the system asks for less;
`"system"` (or nothing) follows it. A `still …` line styles an element
while less is wanted, `screen.still` is the same as a value, and
`scroll(…)` goes at once instead of gliding.

**The title and the badge.** Two more names are the runtime's: `title`
is the page's title (what its tab says), `badge` a number on the app's
icon.

```mote
// docs: whole
app "Inbox"

state unread = 0

root title=(unread > 0 ? `(${unread}) Inbox` : "") badge=unread

action signOut
  unread = 0
  title("Signed out")
  badge(0)

row gap=8 padding=16
  button "One more" press={unread = unread + 1}
  button "Read them" press={unread = 0}
  button "Sign out" press=signOut
```

- `root title=…` keeps the title current; `""` (or `none`) is the title
  the app was built with (`app "Inbox"`). `title(text)` sets it once, in an
  action or a fn. Use one or the other: a `root title=` writes again
  whenever what it reads changes.
- `root description=…` is what the page says of itself to whoever lists it
  (a search engine, a link shown in a chat): `""` is the app's own. A
  browser shows it nowhere; it counts where the back end sends the page
  drawn ([`render=ahead`](back-end.md#a-page-drawn-ahead)), which writes
  the title and the description the page set into the page's head.
- `root badge=n` and `badge(n)` put a number on the app's icon where the
  device shows one: an installed app on a desktop, or on a phone that
  allows it (`navigator.setAppBadge`). 0 takes it away. In a browser tab
  nothing is shown, and nothing fails: the title is where a tab says a
  count.
- The badge is the device's, not the page's: it stays when the page is
  closed. An app that signs someone out clears it there (`badge(0)`, or
  the state `root badge=` reads going to 0).
- (A state, a fn or a parameter called `title` or `badge` is the page's
  own, as with any of the language's names.)

Source: `compiler/src/view.rs` (`root`), `compiler/src/emit.rs` (`Css::render`),
`runtime/page/screen.mote` (part `RO`), `runtime/page/media.mote` (part
`TTL`). Recorded in `tests/expect/real_zone_lang_page.txt` and
`tests/expect/real_media_page.txt`.

### Drawn before it arrives

`app "Shop" render=ahead` has the back end draw each page it sends, with
its data, so the first thing on the screen is the page and not an empty
one that fills in: [A page drawn ahead](back-end.md#a-page-drawn-ahead).

### The screen's edges

A phone lays a page out between its notch and its home bar, and fills the
rest with the page's ground. `edges=cover` takes the page to the screen's
edges, under both:

```mote
// docs: whole
app "Shop" edges=cover

column min-height=100vh padding="max(16px, env(safe-area-inset-top)) max(16px, env(safe-area-inset-right)) 96px max(16px, env(safe-area-inset-left))"
  text "Cabinets"
row position=fixed left=0 right=0 bottom=0 padding=12 padding-bottom="max(12px, env(safe-area-inset-bottom))" background=card
  button "Save"
```

- What matters then keeps clear by itself:
  `env(safe-area-inset-top)`, `-right`, `-bottom` and `-left` are how far
  in the screen is free, 0 on a side (or a device) with nothing there. They
  are lengths, written in any value in quotes: the larger of two with
  `max(16px, env(safe-area-inset-bottom))`, added with
  `calc(16px + env(safe-area-inset-bottom))`.
- **Without the word they are 0**, and the page is as it was.
- **The kit's parts that touch the edges keep clear of them**: Sheet and
  SheetContent, Drawer, Sidebar, Dialog and AlertDialog, Toaster, a
  WebPreview filling the screen, and the notes of `toast(…)`. In a program
  that does not say the word they are exactly as they were.
- `cover` is the one word (`H188`).

### A shared link

What a chat, a feed, a search result or a phone's share sheet shows for a
link to the app fills itself in. A second string on the `app` line is the
description, and a picture called `share.png` beside the entry is the
picture:

```mote
// docs: whole
app "Shop" "Cabinets drawn by you, cut by shops near you."

text "Welcome"
```

- **With nothing said**, the page carries its title as `og:title`,
  `og:site_name` and `twitter:title`, `og:type` `website`, a `summary`
  Twitter card, and `apple-mobile-web-app-title` (the name under the
  icon on a phone's home screen). An `accent=` is its `theme-color`.
- **The description** is the second string, or `description="…"` (one or
  the other: both is `H168`). It is the page's `description` and the
  `og:description` and `twitter:description`.
- **The picture is found by its name**: `share.png`, `share.jpg`, then
  `og.png`, `og.jpg`, beside the entry or in `public/`. Its width and
  height are read from the file into the tags, and the card is the large
  one. Make it 1200 × 630. With none, the app's icon (its `icon.png`, or
  the one the build draws) is the picture, as the small card; an
  `icon.svg` is no picture here, and then there is none.
- **`image="cover.png"`** says another one: a file beside the entry or in
  `public/`, or a whole address (`https://cdn.example/a.png`). A file
  that is not there is `H169`.
- **No SVG.** X, Facebook, LinkedIn, Slack and iMessage do not show one:
  `image="og.svg"` is `H169`, and so is a `share.svg` or `og.svg` beside
  the entry with no PNG of it. Draw it as an SVG if you like, and put a
  PNG of it beside it (`og.svg` and `og.png`): the PNG is the picture and
  the SVG stays as its source, unshipped. There is no rasterizer in the
  build.
- **Whole addresses.** A site that shows a link fetches the picture
  itself, so `og:image`, `og:url` and the canonical link are whole
  addresses. Where the program's back end serves the page it writes them
  in, from the address each request was sent to: its `Host` and scheme;
  behind a proxy, with `MOTE_PROXY=1`, what the proxy says (`Forwarded`,
  `X-Forwarded-Host`, `X-Forwarded-Proto`); or, where `MOTE_URL` is set
  (`https://shop.example`), that. A `Host` that is not a host's name and
  port is never written into the page. Each page made is kept, with its
  tag (a 304 for whoever has it) and its gzip.
- **`url="https://shop.example"`** says the address in the build itself,
  for a page no back end serves (`mote serve`, any static host), or to
  fix the canonical address whatever a request says. A page with no back
  end and no `url=` has no whole address: a picture it says is `H169`; one
  found by its name is left out, with a warning; the icon quietly.

**A route's own.** A route can say its title, description and picture:

```mote
// docs: whole
app "Shop" "Cabinets drawn by you."

server fn price(sheets: number): number = sheets * 42

column gap=8 padding=16
  row gap=8
    link "Home" href="/"
    link "Pricing" href="/pricing"
  route "/"
    text "Welcome"
  route "/pricing" title="Pricing · Shop" description="What a cut costs, by the sheet." image="pricing.png"
    text "Pricing"
  button "Share" press=share()
```

- While the route is shown the tab says its title and the page's
  description is its own; a route that says nothing puts back the app's.
- Where the back end serves the page, `/pricing` (the path, not
  `#/pricing`) is answered with that route's tags, and the page there
  moves itself to `#/pricing` before anything is drawn. `share()` on that
  route shares `https://shop.example/pricing`, so the preview is the
  route's. A `:name` pattern works the same (`route "/planet/:id"
  title="A planet"`): the title is written out, the same for every planet.
- Routes are read after `#`, which never reaches a server. So a page no
  back end serves (a static host, one file) shows every link with the
  app's tags, and `share()` shares the address as it stands. (With
  `routes=paths` the route is the path itself: the back end answers it
  with the route's tags and the page stays where it is. A path no route
  names with tags of its own is answered with the app's, and with its own
  address as `og:url` and the canonical link, so each address of a program
  that shows its own views from `route.path` is told apart.)
- `title=`, `description=` and `image=` are strings written out: the back
  end writes them before any code runs (`H172`). A title that changes as
  the page is used is `title(…)` or `root title=(…)`. `route "*"` has no
  title of its own (`H172`).
- **`share()`** opens the share sheet with the page:
  [data.md](data.md#share).

Source: `compiler/src/share.rs`, `runtime/server/share.mote` (part `SHP`),
`runtime/page/routes.mote` (part `RTH`). Recorded in
`tests/expect/real_share.txt`.

### In front, and at it

```mote
// docs: whole
state unread = 0

server fn here(state: string): number
  return 1

// Presence: "active" while the page is in front and somebody is at it.
derive presence = screen.visible && !screen.idle(120000) ? "active" : "away"
watch presence
  here(presence) else 0

column gap=8 padding=16
  text `You are ${presence}`
  text (screen.focused ? "This window has the keyboard" : "Another window has the keyboard")
  text `${unread} unread` font-weight=(screen.visible ? 400 : 700)
```

| Value | Is |
|---|---|
| `screen.visible` | Whether the page is the one shown: false in a tab behind another, in a window put away, on a locked phone. |
| `screen.focused` | Whether the page's window is the one in front, the one the keyboard is in. A page can be visible and not focused (beside another window). |
| `screen.filesOver` | Whether files are being held over the window, dragged in from outside it: `if screen.filesOver` + an overlay ("Drop to add to #general"). True from when they come over the window until they leave it or are let go; `drop=` on an element is what takes them ([events.md](events.md#the-events)). A page that reads it is not left for a file let go where nothing takes it. |
| `screen.idle(ms)` | Whether nobody has moved the pointer, pressed a key, turned the wheel or touched the page for `ms` milliseconds. Coming back to the page is being at it. |

All three are bools and reactive: a binding, a `derive` or a `watch` on one
runs when it turns. Nothing listens until the page first reads one, and
`screen.idle` costs nothing as the pointer moves: a move writes down the
time, and each length asked about has one timer. Ask for a few lengths, not
a different one each second.

`screen.idle` is about this page. It is false for a page nobody has touched
yet until `ms` have passed since it was first asked.

Source: `runtime/page/screen.mote`, parts `SC` and `SCI`.

### Keeping the screen on

`screen.awake(true)?` keeps the screen from dimming and locking while the
page is in front (the Wake Lock API): for a long import, a recipe being
cooked from, a call. `screen.awake(false)?` lets it go.

- The browser lets go of it whenever the page is hidden (another tab, the
  window put away, the phone locked); the page asks for it again each time
  it is seen, for as long as the program has not said `false`.
- A browser that has no Wake Lock fails, kind `"unsupported"`; one that
  says no (Firefox may ask the person; any refuses a hidden page), kind
  `"refused"`. It is the page's: in a `server fn` it is `H411`.

```mote
// docs: whole
state said = ""

action work
  screen.awake(true) else none
  said = "working, with the screen kept on"

action done
  screen.awake(false)?
  said = "done"

button "Begin" press=work
button "Done" press=done
text said
```

Tested in `tests/all.sh real_bigfiles`: held, let go when the window is put
away, held again when it is back, let go with `false`. Source:
`runtime/page/screen.mote`, part `SCW`.

### Print and the whole screen

```mote
// docs: whole
state sheet: element? = none

column gap=8 padding=16
  row gap=8
    print display=none
    button "Print" press={screen.print()}
    button "Print the invoice only" press={screen.print(sheet)}
    button (screen.full ? "Leave full screen" : "Fill the screen") press={screen.fullscreen(!screen.full)}
  column ref=sheet padding=24 background=card
    print width=190mm background=#ffffff
    text "Invoice 42" font-size=24
    text "Two doors, hung"
```

| Call | Does |
|---|---|
| `screen.print()` | Opens the browser's print dialog (a printer, or Save as PDF) for the page. |
| `screen.print(box)` | The same for one element alone (a `ref=`): nothing else is laid out on the paper. |
| `screen.fullscreen(true)` | Fills the screen with the page. |
| `screen.fullscreen(true, box)` | Fills it with that element. |
| `screen.fullscreen(false)` | Leaves. |
| `screen.full` | Whether the screen is filled now (a bool, reactive). Escape leaves too. |

- None of these waits or can fail. The browser allows the whole screen
  only from a press or a key; asked at another moment, nothing happens and
  `screen.full` stays false.
- A `print …` line under an element is its styles on paper: `print
  display=none` under what is not to be printed.

Source: `runtime/page/screen.mote`, parts `SCP`, `SCF`.

## HTML attributes

By their own names: `class` `for` `id` `href` `type` `placeholder`
`disabled` `title` `hidden` `tabindex` `role` `name` `src` `alt` `target`
`rel` `min` `max` `step` `required` `readonly` `autofocus` `rows` `cols`
`open` `download` (alone, or with the name to save under:
`download="report.pdf"`) `loading` `start` (the number an `ol` begins at)
`lang` `dir` `spellcheck` `inputmode` `enterkeyhint` `autocapitalize`
`autocorrect` `aria-*` `data-*` and the rest of `tables.rs`'s `HTML_ATTRS`.
What a browser fetches and when: `preload=none` (or `metadata`, `auto`) on
`audio` and `video`, `loading=lazy` `decoding=async` `fetchpriority=low` on
a picture, `crossorigin` and `referrerpolicy`. `translate="no"` (or
`translate=no`, `translate=false`, and `"yes"`) is HTML's: a page
translator leaves the words inside as they are (a name, a code, a
product). With any other value (`translate="10px 4px"`) `translate` is
CSS's property, which moves the element.

To show HTML from elsewhere (a letter), use `htmlframe` instead
([text.md](text.md#htmlframe)): it cleans it and shows it where nothing runs,
under `policy=strict` too. An `iframe` takes `sandbox` (alone: the page in it may do nothing; or
the things it may: `sandbox="allow-scripts allow-forms"`), `allow` (what
of the device it may ask for: `allow="fullscreen; camera"`),
`allowfullscreen`, and `srcdoc`, a page given as text instead of `src`.
What `srcdoc` holds would run as this page itself, with its storage and
its signed-in calls, so it needs a `sandbox`, and one that does not allow
both `allow-scripts` and `allow-same-origin` (which together let it take
its sandbox off): `H232`.

```mote
// docs: whole
state preview = "<h1>Hello</h1>"
column
  iframe sandbox srcdoc=preview width=320 height=200
  iframe src="https://example.com/" sandbox="allow-scripts" allow="fullscreen" allowfullscreen width=320 height=200
```

An attribute whose value is `none` is not on the element: `title=tip` with
`tip: string?` writes a title when there is one and none when there is not
(never the word "undefined").

A lone word is a boolean attribute: `input autofocus`, `button "Go" disabled`.
A bool attribute given a number, a string or a list is refused (`H067`:
compare it, `n > 0`).

## Binding

`input value=draft` and `input type=checkbox checked=t.done` write back when
the value is state, or reaches into state (`t.done` in a `for` row, a field
of a derive's result). Anything computed is one-way.

```mote
// docs: whole
shape Note
  id: string
  title: string

state notes: Note[] = [{id: "a", title: "One"}, {id: "b", title: "Two"}]
state sel = "a"
state volume = 5
derive open = notes.find(n => n.id == sel)

column gap=8 padding=16
  select value=sel
    for n in notes key=n.id
      option n.title value=n.id
  if open
    input value=open.title
  input type=range min=0 max=10 value=volume
  text `${volume * 10}%`
```

- A field gives text; state that holds a number gets a number.
- `value` writes on every `input` event; `checked` on `change`.
- Writing into what a derive found writes the state: `open.title` above
  writes into `notes`.
- `dialog open=flag` shows the browser's modal dialog while `flag` is true.
  `close()` in a handler inside it closes it ([Popover and tip](#popover-and-tip)).
  Escape and a click outside close it, and `flag` is written back at once:
  closed and opened again within the same moment, it is open.

## Control

```text
if c                         else if c … / else …
for t in todos key=t.id      for t, i in todos (i is the index)
for t in todos key=t.id virtual             only the rows in view: a long list
match tab                    like logic's match, with markup under each arm
  "list", "all"
    text "…"
  else
    text "?"
let p = planets.find(x => x.id == id)     a derived value for the nodes after it
let options: string[] = m.data.options ?? []     with its type, as in logic: what `json` holds is read as that
```

```mote
// docs: whole
shape Planet
  id: string
  name: string
  moons: number

state planets: Planet[] = [{id: "e", name: "Earth", moons: 1}, {id: "m", name: "Mars", moons: 2}]
state id = "e"
state tab = "list"

column gap=8 padding=16
  row gap=8
    button "List" press={tab = "list"}
    button "One" press={tab = "one"}
  match tab
    "list"
      for p, i in planets key=p.id
        row gap=8
          text `${i + 1}.`
          button p.name press={id = p.id}
    else
      let p = planets.find(x => x.id == id)
      if p
        text `${p.name} has ${p.moons} moons`
      else
        text "No such planet" color=danger
```

How each works (`runtime/page/core.mote`):

- **`if`** (part `I`) keeps two empty text nodes as markers and builds the
  chosen branch between them. When the test flips, the old branch's nodes
  are removed, its bindings and timers end, and the other branch is built.
  The test is boiled down to true or false first, so a branch is not rebuilt
  when the test's value changes but its truth does not.
- **`for`** (part `L`) keeps a row per key. A row whose key stays keeps its
  nodes and is told its new item and index; rows are moved only when out of
  order; rows whose keys are gone are removed. A list with no `key` is keyed
  by position, which is fine for a list that only grows at its end and wrong
  for one that is reordered or filtered while its rows hold state (a field's
  focus, a nested `if`). Give lists of records a `key`.
- **`let`** in markup is a derive for the nodes after it; `if p` narrows it.
  Only they see it: an action or a fn that names it is told so (`H020`,
  "`p` is a `let` in the markup"). What an action needs too is a
  declaration: `derive p = …` above the markup (in a component, among the
  component's declarations).
- **`for … virtual`** (part `VR`) draws only the rows in view, for long
  lists: [below](#long-lists).

### try

A part of the page that may fail to draw, and what stands there instead:

```mote
// docs: whole
state rows: json = [3, 1, 2]

fn biggest(rows: json): number
  return rows.reduce((a, b) => a > b ? a : b)

component Chart(rows: json)
  text `${rows.length} rows, the biggest ${biggest(rows)}`

column gap=8 padding=16
  try
    Chart rows=rows
  else err
    text `This chart could not be drawn: ${err.words}` color=danger
    button "Try again" press={rows = [1]; again()}
  button "Break it" press={rows = none}
```

- **What is caught.** Anything that throws while what is under `try` is
  built, or while any of it updates later: a component given what it cannot
  draw (`none` where it reads a field), a binding or a `let` whose value
  throws, a fn they call. A `derive` that throws is caught where it is read:
  in a program with a `try`, a derive keeps its failure and hands it to
  whatever reads it. A `resource` or a `live` value with no `else` of its
  own that failed is caught by a `try` that reads it (and then `on failure`
  is not told of it). Not caught: what a handler does when it is pressed. An
  action's failure is the action's (`failure(save)`, else `on failure`), as
  it was.
- **`else err`**: what is built in its place, and when. `err` is the
  failure: written into text it is its words, and `err.words`, `err.kind`
  (`"fault"` for something that simply broke; a resource's or a `live`
  value's own kind), `err.id`, `err.where` and `err.at` are its fields, as
  under `else err => …`. The name may be left out: `else` alone.
- **`again`**, inside the `else`, builds what is under `try` once more, as
  things are now. Fix what it reads first, in the same handler
  (`press={rows = [1]; again()}`); a resource that failed is built again
  once it has loaded (`refresh(sales)`, then `again` when it is back).
- **With no `else`**, a failure leaves nothing there, and `on failure` is
  told of it.
- **Nested**: the innermost `try` around what failed hears it.
- **Told no further**: a failure a `try` caught is not told to `on failure`
  (it was looked after); under `mote dev` it is written on the console.

How it works (`runtime/page/try.mote`, part `TRY`): what is under `try` is
built under an owner of its own whose set of owned effects is a guarded one.
Each effect added to it has its work wrapped, and is given a guarded set of
its own for what it makes in turn: a row of a `for`, an `if`'s branch, a
component's bindings, all made under an owner that is under the `try`, are
guarded by it, when they are built and whenever they run again. A failure
ends what it built (its effects, its nodes) and builds the `else` in its
place. A program with no `try` carries none of this, and its page is
written as it was.

**What a page did before `try`, and still does outside one.** A derive that
throws as the page is first built stops the page's script: nothing is
drawn. One that throws later keeps its last value, so the page shows a
stale value, and the error is on the console only. A component given `none`
keeps showing what it drew last; built again with it (an `if` around it
turning on), its part of the page is left empty. `on failure` hears none of
these (it hears an error nobody caught, an action's and a resource's
failure: [back-end.md](back-end.md#when-something-fails)).

## Long lists

`for … virtual` draws only the rows in view, and a screenful and a half
around them, however long the list. A plain `for` over 50,000 rows makes
50,000 sets of elements; this makes thirty.

```mote
// docs: whole
shape Post
  id: string
  words: string

state posts: Post[] = Array.from({length: 100000}, (x, i) => ({id: `p${i}`, words: "word ".repeat(1 + i % 40)}))

column height=480 overflow-y=auto
  for p, i in posts key=p.id virtual
    column padding=8 gap=4 border-bottom="1px solid" border-bottom-color=line
      text `${i + 1}` font-weight=600
      text p.words
```

| You write | |
|---|---|
| `for r in rows key=r.id virtual` | Each row is measured as it is drawn, and kept by its key; a row not drawn yet counts as the mean of those measured. For rows of any height, and rows whose height changes. |
| `for r in rows key=r.id virtual=32` | Every row is 32 pixels along the list's way. Nothing is measured: a million rows cost what thirty do. The value may be worked out (`virtual=(compact ? 28 : 40)`). |
| `… virtual sticky=r.head` | The rows for which it is true head a group: the head of the group in view stays drawn, so a `position=sticky` on it holds ([below](#groups-and-their-heads)). |

Nothing else is written. What a list needs to know is read from the page:

- **What shows of it** is what the window and every box around it that
  clips its way (`overflow-y=auto`, `scroll`, `hidden`) leave in sight. It
  is scrolled by the nearest of those boxes that has more than it shows,
  else the window: a box with a height (or `flex=1 min-height=0` in a
  column) scrolls itself; one that grows with the list is moved through by
  the window's scroll.
- **Its way** is its parent's. A `row` that does not wrap, and a table's
  `tr`, run across, and their scroller is the one that scrolls across;
  anything else runs down.
- **A grid of cards**: a parent that wraps (`grid`, or a `row` with
  `flex-wrap=wrap`) puts as many rows on a line as fit, counted from where
  the drawn rows stand, and again when its width changes.

**A model's rows, more than a page holds**: a `live` read that says `window: 200` is as
long as its count and holds the rows of the windows around the view; a `for … virtual`
over it asks for them as it scrolls ([models.md](models.md#a-long-list-a-window-at-a-time)).
That is the first thing to reach for when the rows are a model's.

It keeps all a plain `for` does: keys, `for r, i in rows` (`i` is the
place in the whole list), markup of any depth under a row, events,
`el.from().row`, `el.row(list, key)` for a drawn row. A list of 64 rows or
fewer is drawn whole, at once, wherever it is, and is on the page what a
plain `for` draws: the spacers that stand for rows left out are only there
while rows are. What it costs: a page that says `virtual` carries 15 KB of
runtime (6.5 KB gzipped); a page that does not carries none of it, byte for
byte the same as before. Measurements are in
[bench/README.md](../bench/README.md#long-lists).

**Not jumping.** Before it changes anything, a list notes the row at the
top of its view, by key, and where it stands; after drawing, measuring and
sizing, it scrolls by however far that row moved. So rows measured taller
than guessed above the view, a picture that loads, words that wrap when the
window narrows, rows put in above (a thread's older messages), a filter
and a sort all leave the row the reader was at where it was. (Filtered
out, the next row after it that remains takes its place; if none of the
rows in view remain, the view stays as far into the list as it was.)
Staying at the end while new rows arrive, unless the reader has scrolled
up, is the kit's `Feed` (`stuck=`), as for any list; a virtual list never
holds to its end of itself, or rows added at its end by "load more" would
be skipped.

**A row's own state goes when it is no longer drawn.** A component in a row
keeps its `state` while the row is drawn; scrolled far enough away, the row
is taken out and the state with it, as when a row leaves a plain `for`.
Keeping every row's state by key would hold on to every row ever scrolled
past, a million of them, and what is worth keeping (what is picked, a
draft, a row opened out) belongs to the program, by key: `state picked:
string[]`, `state drafts: json = {}`. Two things are kept for you: the row
that holds the keyboard (a field being typed in, a cell being edited) is
not taken out while it does, and the head of the group in view stays.

**Keys.** With the keyboard in a row (not in a text field, which keeps its
arrows), ArrowDown and ArrowUp (ArrowRight and ArrowLeft across, and in a
grid of cards), PageDown and PageUp, Home and End go to that row of the
whole list, drawing it if it was not, and give the keyboard to the element
in the same place among what can take it in that row. Tab goes on through
the rows: the element it reaches is scrolled into view, which draws the
rows after it. A key the program takes from the browser with `keys=`, on
the row or around it ([events.md](events.md#keys)), stays the program's.

**What a screen reader is told.** Table rows are given `aria-rowindex`
(after the head's rows) and the table `aria-rowcount`; cells drawn across
a row `aria-colindex`, and the table `aria-colcount`; rows that are `li`
or say `role=listitem`, `option`, `article`, `treeitem`, `menuitem…`,
`radio` or `tab`, `aria-setsize` and `aria-posinset`. Spacers are
`aria-hidden`.

**Coming back.** A list taken off the page because the page went elsewhere
(another route) keeps its sizes and the row at its top, for that address;
drawn again there (back, or a link to it), it is where it was.

**Where it cannot reach.** The browser's find-in-page (Ctrl-F) finds only
drawn rows; a list people search in wants a field that filters it. Print
prints the drawn rows. Styles by place among siblings (`nth-child`) count
the drawn rows only: stripe by `i % 2` instead. A row's own outer margin is
not counted: space rows with the parent's `gap` or with padding inside the
row. A list taller than the browser lays out (about 33 million pixels in
Chrome and Safari, 17 million in Firefox: a million rows of 32 in Firefox)
is held to nine tenths of that, and moves through in proportion, a little
faster than the finger. Two lists of one source in one parent, and a
virtual `for` inside another's row, are fine; a list inside a `display:
contents` parent is measured through it.

### Groups and their heads

```mote
// docs: whole
shape Contact
  id: string
  name: string
  head: bool

fn contacts(): Contact[]
  let out: Contact[] = []
  for c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")
    out.push({id: c, name: c, head: true})
    for n in ["Ada", "Ben", "Cy", "Di", "Ed", "Flo", "Gus", "Hal", "Ivy", "Jo"]
      out.push({id: `${c}-${n}`, name: `${c}. ${n}`, head: false})
  return out

state people = contacts()

column height=400 overflow-y=auto
  for c in people key=c.id virtual sticky=c.head
    if c.head
      text c.name position=sticky top=0 z-index=1 background=card padding="4px 12px" font-weight=600
    else
      text c.name padding="8px 12px" border-bottom="1px solid" border-bottom-color=line
```

Each head is a row of its own. Its `position=sticky` holds it at the top
while the rows of its group pass; `sticky=` is what keeps it drawn while
they do (else it would be taken out with the rows above the view, and the
group would scroll by headless). A head that is outside the list (a table's
`thead`, a title over a column) is sticky as anywhere.

### Tables and wide grids

Rows of a table and the cells of each row may both be virtual: a table of
5,000 rows by 300 columns draws what shows of it.

```mote
// docs: whole
state cols = Array.from({length: 300}, (x, i) => `c${i}`)
state rows = Array.from({length: 5000}, (x, i) => i)
state edits: json = {}

view height=480 overflow=auto
  table border-collapse=separate border-spacing=0 table-layout=fixed
    thead
      tr
        th "#" position=sticky top=0 left=0 z-index=3 background=bg width=60
        for c in cols key=c virtual=100
          th c position=sticky top=0 z-index=2 background=bg width=100
    tbody
      for r in rows key=r virtual=32
        tr height=32
          td `${r}` position=sticky left=0 z-index=1 background=bg width=60
          for c in cols key=c virtual=100
            td width=100
              input value=(edits[`${r}.${c}`] ?? "") input={edits[`${r}.${c}`] = it} width=96 border=none
```

- A cell drawn by a `for … virtual=100` across a row is made 100 pixels
  wide (`width` and `min-width`): a table left to size its columns would
  squeeze them to their words once the spacers make it wider than its box.
  Measured cells (`virtual` alone) are not: give them a width.
- The head row (`thead`, `position=sticky top=0` on its cells) and the
  first columns (cells written before the `for`, `position=sticky left=0`)
  stand still while the rest scrolls.
- A cell with the keyboard (an `input` being typed in) stays while it is
  scrolled out of sight, either way, and its row with it.
- A spacer in a table body is a row of one cell as wide as the table; in a
  row, a cell. In a list (`ul`, `ol`) it is an `li`.

### Data that comes a page at a time

A million rows need not be on the page to be scrolled through. For a
model's rows, say so in the read and the runtime does it, rows written by
anyone included: `live orders = Order.find({}, {order: "placed", window: 200})`,
drawn by `for o in orders key=o?.id virtual=36`
([models.md](models.md#a-long-list-a-window-at-a-time)). By hand, for data
that is not a model's: the list holds a place for each (`none` until its
page has come), and a place that comes into view asks for its page:

```mote
// docs: whole
model Order
  number: int
  customer: string
  total: number
  index number

shape Line
  number: int
  customer: string
  total: number

state total = 0
state rows: json[] = []
state asked: json = {}

server fn orderCount(): int
  return Order.count({})?

// A hundred orders from a place, in the order of `number` (its index makes the offset a walk along it).
server fn ordersFrom(from: int): Line[]
  return sql.run(sql.open("app")?, "select number, customer, total from \"Order\" order by number limit 100 offset ?", [from])?

task
  total = orderCount()?
  rows = Array.from({length: total}, x => none)

action want(i: number)
  let from = i - i % 100
  if asked[from] return
  asked[from] = true
  let got = ordersFrom(from)?
  let j = 0
  while j < got.length
    rows[from + j] = got[j]
    j += 1

column height=480 overflow-y=auto
  for o, i in rows virtual=36
    if o
      row height=36 gap=12 align-items=center padding="0 12px"
        text `#${o.number}` width=80
        text o.customer flex=1
        text `${o.total}`
    else
      row height=36 align-items=center padding="0 12px" color=dim seen={if it.visible want(i)}
        text "…"
```

- `seen=` ([events.md](events.md#seen)) on the placeholder asks for its
  page; one in flight is not asked for again.
- The list is filled in place (`rows[from + j] = …`), so the list sees
  the rows that changed and nothing else: a page of 100 costs the rows in
  view, whatever the total.
- A row stays keyed by its place (no `key=`): the places do not move.
- `sql.run` reads past the model's `read` rule: where there is one, page
  by `T.find(filter, {order, limit, after})` instead (the next page after
  the last row: "load more" at the end, with `seen=` on a line after the
  list), or check the caller in the `server fn`.
- What is not done for you: rows added or taken away above the window
  shift every place after them (ask again: clear `asked`, read `total`
  again); an order other than one with an index walks the whole table for
  each page.

For a model's rows, `live orders = Order.find(filter, {order: "placed desc",
window: 200})` does all of this, and keeps it right as rows come and go:
[a long list, a window at a time](models.md#a-long-list-a-window-at-a-time). The
pattern above is for what is not a model's `find`: a `server fn` of your own, an
outside service's pages.

## Routes

```mote
// docs: whole
state visits = 0

column gap=12 padding=16
  row gap=12
    link "Home" href="/"
    link "Mars" href="/planet/mars"
    button "Venus" press={go("/planet/venus")}
    button "Back" press={back()}
  route "/"
    text "Home"
  route "/planet/:id"
    text `Planet ${id}`
    task
      visits += 1
  route "*"
    text `Nothing at ${route.path}`
  text `${visits} planets visited` color=dim
```

- `route "/planet/:id"` shows its children while the address matches; each
  `:name` is a string in scope.
- Routes written one after another are one group: the first match wins.
  `route "*"` is anything else.
- `route "/pricing" title="Pricing"` (and `description=`, `image=`): the
  tab follows the route, and a shared link to it shows its own
  ([a shared link](#a-shared-link)).
- `link "About" href="/about"` goes there; so does `go("/about")`.
  `go` with a whole address (`go("https://example.com/")`,
  `go(route.origin + "/export")`) leaves the page for it, as a link to one
  does.
  `back()` goes back and `forward()` forward again, as the browser's own two buttons do.
  `route.path` is the current address, reactive.
- Addresses live after `#` (`…/index.html#/planet/mars`), so any static
  host, and `file://`, serves them. `app "X" routes=paths` makes them the
  address's own path (`https://shop.example/planet/mars`): [routes as
  paths](#routes-as-paths).
- **A program routes in the page** if it has `route` blocks, or reads
  `route.path`, or calls `go` or `back`: any one of them (the last three
  are how a program that shows its own views from `route.path` does it,
  with no `route` block). In such a program an `href` that starts with `/`
  is an address of the app (`href="/about"` is written `#/about` in the
  page, a worked-out `href=`/c/${id}`` too), and pressing it changes
  `route.path` without loading anything. Four kinds of link leave the app
  as they are: a whole address (`https://…`, `route.origin + "/export"`),
  one with `download`, one with `target=`, and `/file/…` (where the back
  end serves a model's files). In a program that does none of the three,
  `href="/about"` is the site's `/about`: another page.
- **The page's own address**, for a link someone else is to open:

  | | For a page at `https://chat.example.com/app/#/planet/mars` |
  |---|---|
  | `route.path` | `"/planet/mars"` |
  | `route.url` | `"https://chat.example.com/app/#/planet/mars"`, reactive |
  | `route.origin` | `"https://chat.example.com"` (`"file://"` for a page opened from a file) |
  | `route.link("/join/abc")` | `"https://chat.example.com/app/#/join/abc"`: the whole address of a path of this page |

  All are strings and read-only: `go` is how the address changes. (What
  stands after `#` where routes are paths, `route.fragment`, is
  [below](#the-fragment).)
  `copy(route.link(`/join/${code}`))` is an invitation someone else can
  open. In a `server fn`, `route.origin` is the origin the caller reached
  the back end at ([back-end.md](back-end.md#what-a-server-fn-can-use)).
- A route is built when it matches and removed when it stops matching; a
  `task`, `every` or `after` under it starts and stops with it
  ([reactivity.md](reactivity.md#tasks)).

- **`route.query("q")`** is a value of the address's query (`?q=oak`;
  after the route, `#/list?q=oak`, where routes are after `#`), or none,
  and reactive. **`route.setQuery({q: text, page: none})`** changes it
  where it stands: no new entry in the history (a filter typed is not a
  page to go back to); none or `""` takes a value away. `go("/list?q=oak")`
  is a new entry with a query.

  ```mote
  // docs: whole
  state found = ["oak", "ash", "pine"]
  derive shown = found.filter(t => t.includes(route.query("q") ?? ""))

  column gap=8 padding=16
    input value=(route.query("q") ?? "") input={route.setQuery({q: it})}
    for t in shown
      text t
  ```

### Routes as paths

```mote
// docs: whole
app "Shop" routes=paths

column gap=12 padding=16
  row gap=12
    link "Home" href="/"
    link "Mars" href="/planet/mars"
    link "Plans" href="#plans"
    button "Venus" press={go("/planet/venus")}
  route "/"
    text "Home"
    text "Plans" id="plans" margin-top=1200
  route "/planet/:id"
    text `Planet ${id}`
```

`routes=paths` puts a route in the address's own path, with the History
API: `https://shop.example/planet/mars`, which search engines index, an
OAuth or payment provider takes as a return address, and analytics keep.
Everything said above holds; what differs:

- A link of the app, or `go`, pushes the new address without loading
  anything; back and forward are the browser's own. A new route starts
  at the top of the window; back and forward put the window back where it
  was scrolled to. `href="#plans"` scrolls to `id=plans` (and is in the
  address, `…/#plans`, so it can be shared); opened at such an address,
  the page goes there once it is drawn. What stands after `#` is never
  taken for a route: changed by hand, or by a move back over such a link,
  the route stays ([the fragment](#the-fragment)).
- **An address from before.** One kept from when the app's routes were
  after `#` (`https://shop.example/#/planet/mars`, in a bookmark or on
  another site) opens at that path, and the address becomes the path; a
  link written `href="#/planet/mars"` goes there too.
- **A host that only serves files** can still send pages with their words:
  a program that says [`render=ahead`](back-end.md#a-page-drawn-ahead) and
  has no back end of its own has `/` and each written-out route drawn by
  `mote build`, as files.
- **The host must answer every route's path with the page.** The program's
  back end does (any path with no `.` in its last part and no file is the
  page; a route with `title=` is answered with its own tags, [a shared
  link](#a-shared-link)). So do `mote dev` and `mote serve`. A static
  build also writes `404.html`, the page under another name, which GitHub
  Pages and most static hosts send for an address they have no file for.
  Elsewhere, say it to the host: Netlify and Cloudflare Pages
  `_redirects` with `/* /index.html 200`; nginx `try_files $uri
  /index.html;`; Caddy `try_files {path} /index.html`.
- **The page's root.** The build writes `<base href="/">`, so what the
  page names beside itself is found from `/planet/mars` too. A page served
  below a path says where: `app "Shop" routes=paths base="/shop/"` (the
  host then answers `/shop/…` with the page). A page with a back end is
  served from its host's root.
- A path whose last part has a `.` (`/report.pdf`) is a file, not a route:
  a link to it is left to the browser, as is `/file/…`, a whole address,
  and a link with `target=` or `download`.
- Opened from a file (`file://`, `mote build --single`), there are no
  paths to go to: the routes are after `#`, as in any app.
- `route.url` and `route.link("/join/abc")` give `https://shop.example/join/abc`.
- Unsaid, or `routes=hash`, routes are after `#` and nothing here
  applies. `base=` is only for `routes=paths` (`H247`).

### The fragment

What stands after `#` in an address never reaches a server: the browser
keeps it. Where routes are paths it is free, and a page can read it, change
it, or be handed a value in it by another site.

```mote
// docs: whole
app "Vault" routes=paths

// Held by the page, in memory, and nowhere else.
state key = ""

task
  key = route.takeFragment()

column gap=8 padding=16
  text (key == "" ? "Open your link to unlock" : "Unlocked")
  button "Send it on" press={go(`https://mail.example.com/#${key}`)}
```

| | For a page at `https://vault.example.com/open#k1.c2Vj` |
|---|---|
| `route.fragment` | `"k1.c2Vj"`: what stands after `#`, as the address holds it (not decoded), and reactive. `""` when there is none. |
| `route.setFragment("plans")` | Changes it where it stands: the entry of the history is replaced, none is added, nothing is scrolled to. `route.setFragment("")` takes the `#` away too. |
| `route.takeFragment()` | `"k1.c2Vj"`, **which is no longer in the address**: read and removed in one step, for a value that is a secret. |

- **`go("https://id.example.com/#k1.c2Vj")` leaves the page with the fragment
  as written**, as a link to that address does, whichever way this app's
  routes stand. That is how one site's page hands a value to another's
  without either server seeing it.
- **`route.takeFragment()` is taken before anything else runs.** A page whose
  program calls it anywhere is built with one more script, the first of the
  page, before its `<base>`, its styles and every other script. That script
  takes what stands after `#` out of the address and out of the entry of the
  history (`history.replaceState`) and keeps it in memory. So by the time
  the page's own code, the service worker's registration, or anything that
  reads the address runs, the address has no fragment, and `route.url`,
  `route.fragment`, `share()` and the agent's reading of the page have none
  either. `route.takeFragment()` then hands the value over **once**: the
  next call gives `""`. Where it goes from there is the program's.
- **One that arrives while the page is open** (an address pasted over this
  one, which loads nothing) is taken the same way, at once, and
  `route.takeFragment()` is followed: a `derive` that calls it is worked out
  again and holds the new one.

  ```mote
  // docs: whole
  app "Vault" routes=paths

  state key = ""
  derive arrived = route.takeFragment()

  task
    key = arrived

  watch arrived
    if arrived != ""
      key = arrived

  text (key == "" ? "Locked" : "Unlocked")
  ```
- In a page that takes it, every fragment an address arrives with is taken,
  `#plans` too: such a page does not scroll to an `id` it was opened at. A
  link of its own to `#plans`, and `go("#plans")`, work as anywhere.
- **Where the routes are after `#`** (unsaid, or `routes=hash`), what stands
  after `#` is the route, and there is no fragment beside it: all three are
  refused when compiled (`H355`), with the fix, `routes=paths`. A page
  opened from a file (`file://`, `mote build --single`) has its routes
  after `#` whatever it says: there `route.fragment` and
  `route.takeFragment()` are `""` and `route.setFragment` does nothing.
- None of the three is in a `server fn` (`H092`): a fragment never reaches a
  back end.

**Where a value taken this way can and cannot be found afterwards.** With
`route.takeFragment()`, and a program that keeps what it was handed in
`state` (not `persist`) and shows it nowhere:

| | |
|---|---|
| The address bar, `route.url`, `location` | Not there: removed before any other script ran. |
| The tab's history (back, forward, a reload) | Not there: the entry was replaced. Going back to the page that sent it and forward again arrives with no fragment. The sending page's own entry never had it: `go` leaves from where it was. |
| The back end: its log, a page [drawn ahead](back-end.md#a-page-drawn-ahead), `Referer` | Never there: a browser sends no fragment, in a request or in the `Referer` of a later one. |
| The service worker and its caches | Not there: it keeps the files of the build by their addresses, and matches a request without its fragment. |
| [Usage](usage.md) | Not there: it sends the path, never the query or the fragment (with `paths=full` too), and reads the address after the fragment is gone. |
| A fault told to the back end (`on failure`, `mote.fault`) | Not there: the page's scripts were read after the address was changed, so a stack names the address without it. |
| The [agent's block](agents.md) and `mote.read()` | Not there: they hold what the page shows and its address as it now is. |
| `persist`, `store`, `db` | Only if the program puts it there. Nothing of Mote's does. |
| The browser's record of the load (`performance.getEntriesByType("navigation")[0].name`) | **Still there**, until the page is closed or loaded again: the browser writes it, and no script can change it. Only a script of this page can read it, Mote's runtime does not, and a program with no `extern js` or `extern script` has no other script. |
| The browser's own list of pages visited (`chrome://history`) | Not checked by Mote's tests: a browser may have written the address down as it arrived, before any page's script ran. |

`route.fragment` alone leaves the fragment in the address, where each of the
above that reads the address finds it: for an `#id` or a filter, not for a
secret.

Source: `runtime/page/routes.mote` (parts `RTF`, `RTT`), `TAKE_FRAGMENT` in
`compiler/src/build.rs`. Run: `tests/all.sh real_fragment` (two origins).

### Unsaved work

```mote
// docs: whole
state draft = ""
state saved = ""

root unsaved=(draft != saved)

column gap=8 padding=16
  textarea value=draft
  button "Save" press={saved = draft}
  link "Elsewhere" href="/elsewhere"
  route "/elsewhere"
    text "Elsewhere"
```

`root unsaved=` says the page has work that is not saved: a bool, or the
words to ask with (`unsaved=(dirty ? "Your note is not saved" : "")`;
anything else is `H253`). While it is so, closing the tab, reloading or
leaving for another site asks the browser's own question
(`beforeunload`); a move inside the app (a link, `go`, and back and
forward where routes are paths) asks first, "Leave this page? What you
changed is not saved." unless the page says its own words, and stays if
the answer is no.

Source: `runtime/page/routes.mote` (parts `RT`, `RTA`, `RS`, `HR`, `RTP`
and `RTPL` for paths, `RTQ` for the query, `UNS` and `GO` for unsaved
work). Recorded in `tests/expect/real_paths.txt`.

## Components

```mote
// docs: whole
component Badge(label: string, tone: string?)
  text label color=(tone ?? "fg") border="1px solid" padding="2px 8px" border-radius=999

component Go(press: () => none)
  button press=press
    slot

component Switch(on: bool)
  button (on ? "on" : "off") press={on = !on}

component Card(title: string)
  column gap=8 padding=16 background=card border-radius=12
    text title font-weight=600
    slot

state dark = false
state saved = 0

action save
  saved += 1

column gap=8 padding=16
  Badge label="New" tone="danger"
  Badge label="plain"
  Go "Save" press=save
  Switch on=dark
  Card title="Names" width=100% id="names"
    text "inside"
  text `${dark} ${saved}`
```

- `component Name(prop: type, …)`: declarations and markup indented under
  it. It has its own state, derives, actions and fns, and sees the page's.
- Use it as a tag: `Badge label=t.title tone="red"`. A `T?` prop may be left
  out; any other missing prop is refused (`H072`).
- **A handler prop.** An event's name is a handler the component may call:
  `Go press=save`, and inside, `button press=press`.
- **A prop written back.** A prop the component assigns is written back to
  what the page gave, when that can be written: `Switch on=dark`.
- **Everything else goes on its first element**: `id`, `class`, `aria-*`,
  events, `drag=`, and styles, which win over the component's own:
  `Button "Save" width=100% id="save"`. A first element that is a `form`
  taking no room (`form method=dialog display=contents`, put around a
  button so that it closes a dialog) has no place to be pressed, found or
  measured at, so there it is the first element inside it:
  `AlertDialogAction "Delete" id="yes"` puts the id on the button. An event there is heard as on the
  element itself, with what it hands over
  ([events.md](events.md#events-on-a-component)). Something that is neither
  a prop nor an attribute, style or event is refused (`H046`).
- **`slot`.** Children, and a positional text, appear where the component
  writes `slot`:

  ```text
  component Card(title: string)      Card title="Names"
    text title                         text "inside"
    slot
  ```

  The children are built in the caller's scope: they see the caller's names,
  not the component's.

- **A named slot: `slot "name"` and `fill "name"`.** A place one file owns
  and any file may draw in. The owner writes `slot "composer.above"` where
  the markup should stand (in a component or on the page, also in a `for`),
  with what it offers as `name=value`. A file that has something to put
  there writes, at its top level, `fill "composer.above"(channel: string)`
  with markup under it:

  ```text
  // composer.mote                               // files.mote (a `use` of app.mote; composer.mote never names it)
  component Composer(to: string)                 fill "composer.above"(channel: string, draft: string)
    column                                         FilesTray channel=channel
      slot "composer.above" channel=to draft=draft button "Send with files" press={sendFiles(channel, draft); draft = ""}
      textarea value=draft
  ```

  A fill is a component with no name: it takes the props it declares from
  what the slot gives (checked there like any prop: `H067`, and `H072` for
  one the slot does not give and the fill has not made `T?`), follows them
  as they change, writes back one it assigns, and sees its own file's
  names. What a slot gives and a fill does not take is not handed over.
  Every fill of a name is drawn, in the order of the files (`use`) and of
  the lines; a slot nobody fills draws nothing. A `fill` for a slot that is
  written nowhere is refused (`H048`), as is one inside a component.

Underneath, a component is a function called once per use. Each prop is
handed over as a getter, so a binding inside the component follows whatever
state the caller's expression read (`view.rs`, `Gen::instance`).

A page's own component takes the place of a kit component of the same
name, inside the kit's own components too: a page that declares `Button`
and uses the kit's `Pagination` gets its own `Button` there. So it must
take the props the kit gives it ([kit.md](kit.md#pitfalls)).

## Popover and tip

Written under any element:

```mote
// docs: whole
state open = false

action rename
  toast("Renamed")

button "Options"
  popover placement="bottom-start" open=open
    button "Rename" press=rename data-close=""
  tip "More to do with this"
```

- `popover`: a panel beside the element, opened by a press on it, closed by
  a press outside, Escape, or a press on anything inside marked
  `data-close`.
- `placement="bottom-start"`: `top` `bottom` `left` `right`, with `-start`
  or `-end`. It flips to stay on the screen.
- `open=flag` opens it by a value as well; the flag is written back.
- `close()` in a handler or an action closes the popover (or the `dialog`)
  the reader is in: the one around what was last pressed or typed in, so
  it also works after the action has waited (`save()?` then `close()`).
  `close("card")` closes the one with that id, or around the element with
  that id, from anywhere. An `open=flag` hears it and becomes `false`.
- `on="hover"` opens it while the pointer is on the element; `on="context"`
  on the other mouse button or a long press.
- `tip "Words"` shows them on hover and on keyboard focus.
- An element may have both, as above: each floats beside it in its own
  place.
- A press inside a popover is not a press on the element it was written
  under, nor on anything around that ([events.md](events.md#a-press-inside-a-press)).

Both are the browser's Popover API with CSS anchoring
(`runtime/page/popover.mote`, part `PO`).

**Where a popover or a tip is in the page.** It is written under the element
it floats beside, and is put in the page as that element's *next sibling*,
not inside it:

```text
row class="name"                      <div class="name">
  button "Ada" class="who"              <button class="who">Ada</button>
    popover                             <div popover>…</div>      ← after the button, not in it
      text "Ada Lovelace"               <span class="badge">app</span>
  text "app" class="badge"            </div>
```

It cannot stay inside: what it is written under is most often a button or a
link, and a press, a key or the keyboard's place inside a popover that was
inside one would be the button's or the link's too. And it cannot go to the
end of the page: a popover opened from inside another popover, or inside a
dialog, has to stay inside it to be reachable and to keep the outer one
open. So the element's own contents, and everything before it, are as
written; what changes is what comes *after* it:

- a selector that asks for the element's next sibling (`.who + *`) finds
  the popover; ask past it, `.who ~ .badge`, or for what you mean by its
  own class or id (a test, an agent: `[data-mote]`, an id);
- `gap` and the layout are not touched: a popover that is not open takes no
  room and is no flex or grid item;
- with a tip and a popover under one element, both follow it, in the order
  written;
- it leaves the page when the `if` or the `for` row it was written in does.

To hang a card from something that is not one element (a name and its
badge), put a `row` around them and write the popover under the row.

## Icons

`icon "camera" size=20`: one of Lucide's 2,356 icons (lucide.dev/icons), drawn in
the text's colour; `1em` if no size. Only the icons a page names are in it.
An unknown name is refused with the nearest names (`H045`).

**A name that is a value.** `icon glyph` draws whichever icon `glyph` (a
string: a prop, a row's field, a state) names, and follows it. The names it
may come to are written once, anywhere in the program, as `icon("camera")`:
a call that gives the name back, checked at build like the tag's (`H045`),
and that puts that icon's drawing in the page.

```mote
// docs: whole
shape Tab
  name: string
  glyph: string

component HeadLink(label: string, glyph: string)
  row gap=6
    icon glyph size=16
    text label

state tabs: Tab[] = [{name: "Files", glyph: icon("file")}, {name: "People", glyph: icon("users")}]
state lock = false

column gap=4
  for t in tabs
    HeadLink label=t.name glyph=t.glyph
  HeadLink label="Door" glyph=(lock ? icon("lock") : icon("lock-open"))
  button "Lock" press={lock = !lock}
```

What it costs: each icon named with `icon("…")` is in the page once (its
drawing, 100 to 400 bytes), whether or not it is ever shown, plus 300 bytes
of runtime (part `IC`) for the first `icon` that takes a value; none of
Lucide's other 2,350 ship. An icon written `icon "camera"` is in the markup
itself, as before, and is not in that table. A name the page was not told
of (a plain `"camera"` that never met `icon(…)`, a name out of a database)
draws a dashed box and is said once in the console; an empty name or `none`
draws nothing. So for names that come from data, list the ones allowed:
`fn glyphs() = [icon("hash"), icon("lock"), icon("star")]`.

## Pictures and assets

`image "hero.jpg"` is a file in `assets/` beside the entry: checked at build
time, shipped under a name with its contents' hash, with its width and
height filled in so the page does not jump when it arrives. A missing file
is refused (`H092`).

`asset("name")` is the address of any file in `assets/`, for anything else
(a font, a download). The name is written out, in quotes. Only what is named
ships.

A font file the page has read (picked, fetched, or an asset's bytes) becomes
a family markup can name with `font.use(f, "Name")`: then
`font-family="Name"` ([text.md](text.md#font)).

An `image` whose source has a `:` in it, starts with `/`, or is a file in
`public/` is left as it is. `public/` ships whole, under the names it has.
`image shot.url()` shows bytes ([language.md](language.md#bytes)). An
`image` value (a picture's pixels) is refused there (`H069`): encode it, or
draw it ([media.md](media.md#mental-model)).

| Build | Where an asset goes |
|---|---|
| `mote build` | `dist/assets/<name>.<hash>.<ext>` |
| `mote build --single` | inside the page, as a `data:` address |
| `mote dev` | served from `assets/` as it lies |

## Refused

| You write | Write instead |
|---|---|
| `className` `onClick` `htmlFor` | `class` · `press` · `for` |
| `style="…"` | the property itself: `color=dim` |
| `onChange` `onInput` `onSubmit` `onKeyDown` | `change` · `input` · `submit` · `key` |
| `bg=…` `p=…` `m=…` | `background` · `padding` · `margin` |
| `text Hello` | `text "Hello"` |
| `text a ?? b` | `text (a ?? b)`: a space ends a value |
| `disabled=n <= 0` | `disabled=(n <= 0)` |
| `icon glyph` drawing a dashed box | the name never met `icon("…")`: write `icon("camera")` where the value is made |
| `slot` outside a component | it belongs inside a `component` |
| `fill "name"` with no `slot "name"` anywhere, or inside a component | `H048`: write the slot where it should be drawn; a fill stands at the top of a file |

## Pitfalls

- **Parentheses.** The most common mistake is an operator outside
  parentheses in a value. `H018` says so.
- **Roles in computed colours are strings.** `color=(on ? accent : dim)`
  reads two names that do not exist; write `(on ? "accent" : "dim")`.
- **A bare word may be your own state.** `text title` shows the state
  `title`; `justify-content=center` is the keyword only while nothing is
  called `center`. (Not so for a colour role on a colour property, or one
  of HTML's own words: those are always themselves.)
- **Conditional style lines take constants.** For a computed style under
  hover, compute the style on the element and switch on state instead.
- **A component's styles from outside land on its first element only.**
- **No `key`, wrong rows.** See [Control](#control).
- **A virtual list in a box with no height** is as tall as the list, and the
  window scrolls through it: give the box a height for a list that scrolls
  in its own place ([long lists](#long-lists)).
- **CSS custom properties** (`--x=…`) cannot be written in markup.

## In the source

| What | Where |
|---|---|
| Tags, attributes, style properties, units, roles, habits | `compiler/src/tables.rs` |
| Parsing a markup line, pseudo lines, `match`, `for`, `route` | `compiler/src/parse.rs`: `node`, `children`, `attr_value` |
| Static HTML and atomic classes | `compiler/src/view.rs`: `prep`, `html_el`; `compiler/src/emit.rs`: `Css` |
| Bindings, events, components | `compiler/src/view.rs`: `el`, `instance` |
| `if`, `for`, effects | `runtime/page/core.mote` |
| `for … virtual`, `seen=` | `runtime/page/virtual.mote` (parts `VR`, `VLS`, `SEEN`) |
| Nodes, attributes, fields | `runtime/page/dom.mote` |
| Routes | `runtime/page/routes.mote` |
| `screen`, `scheme`, print, the whole screen | `runtime/page/screen.mote`: parts `SC`, `SCP`, `SCF` |
| `root`, `in root[…]`, `still`, less motion | `compiler/src/view.rs` (`root`), `compiler/src/parse.rs` (`root_cond`), `compiler/src/emit.rs` (`Css::render`), `runtime/page/screen.mote` (part `RO`) |
| Dialogs, popovers, tips, `close()` | `runtime/page/popover.mote` (parts `DG`, `PO`, `CL`) |
| Assets | `compiler/src/assets.rs` |
| Icons | `compiler/src/icons.rs`, `icons/lucide.txt` |
| Recorded behaviour | `tests/pages/kitchen`, `tests/pages/pages`, `tests/el`, `tests/kit.real.mjs` |
