# QuickUI Generation Guide (v1.0.0)

For agents writing pages with `@pardnchiu/quickui`. Every rule was checked against `src/QuickUI.debug.js` at v1.0.0; a feature not listed here is unsupported.

QuickUI binds a data object to plain HTML. Templates accept **data paths** and five built-in functions, never JavaScript expressions. Anything it cannot resolve stays on the page as literal text, so a wrong template usually shows raw `{{ ... }}` instead of throwing.

## Setup

```html
<script src="https://cdn.jsdelivr.net/npm/@pardnchiu/quickui@1.0.0/dist/QuickUI.js"></script>
```

```js
import { QUI } from "https://cdn.jsdelivr.net/npm/@pardnchiu/quickui@1.0.0/dist/QuickUI.esm.js";
```

The script tag defines `window.QUI`, `window._` (element builder) and `window.$` (element lookup).

```html
<div id="app"><h1>{{ title }}</h1></div>
<script>
  const app = new QUI({ id: "app", data: { title: "Todo" } });
</script>
```

## Options

- `id`: mount element id without `#`; required unless `render` is given.
- `data`: becomes reactive `app.data`. Every update deep-copies it through `JSON.parse(JSON.stringify())`, so functions, `Date`, `Map`, `Set` and class instances are lost; store plain JSON values.
- `event`: named handlers for `@event="name"`.
- `when`: lifecycle hooks, snake_case only: `before_render` (return `false` to cancel), `rendered`, `before_update` (return `false` to skip), `updated`. `rendered` and `updated` receive the elapsed seconds. `before_destroy` / `destroyed` never fire; `lifecycle: {}`, top-level hooks and camelCase names are ignored.
- `i18n`: `{ en: {...}, zh: "/i18n/zh.json" }`, objects or JSON URLs.
- `option`: `{ svg: false }` or `{ lazyload: false }` turns that observer off.
- `once`: `true` renders once and leaves `data` non-reactive.
- `render`: function returning a shorthand string (see Render Shorthand).

Instance members: `app.element`, `app.data`, `app.event`, `app.lang(code)`, `await app.fragment()`. `lang()` returns `undefined`, so store the instance first and call `app.lang("zh")` on it.

Initialization is async. Until it finishes, `app.data` is `{}`, `fragment()` logs `[Conflict]` and returns an empty fragment, and `lang()` is queued. Read or touch rendered DOM only inside `when.rendered` / `when.updated`.

## Text `{{ }}`

Allowed inside `{{ }}`:

- A path: `{{ name }}`, `{{ user.name }}`, `{{ list.0.title }}` (index with `.0`, never `[0]`).
- `LENGTH(path)`: length of an array or string, key count of an object.
- `UPPER(path)` / `LOWER(path)`: the value must be a string.
- `CALC(path OP number)`: OP is `+ - * / %`, the right side a numeric literal.
- `DATE(key, format)`: `key` is a top-level key holding a Unix timestamp in **seconds**; the format is required and may use letters, digits, `,`, `-`, space and `:` only. Tokens: `YYYY YY MM M DD D HH H hh h mm m ss s SSS A a dddd ddd` (`d` / `dd` are not tokens).
- `i18n.key`: translation for the current locale.

Everything else fails. `a + b`, `price * qty`, ternaries and function calls render as raw text; precompute them into `data`. `CALC(a + b)` (paths on both sides) and `DATE(ts)` without a format throw `[Internal]` and blank every expression in that text node. `DATE(item.ts, ...)` and formats containing `/` or `.` do not render; inside a loop, store the formatted date string in the item.

A missing path also stays visible as `{{ path }}`: initialize every key you render.

## Attributes

Prefix with `:` (or `q-`). The value is a **data path**; an unresolved path is used as a literal string.

- `:src`, `:href`, `:id`, `:alt`, `:value`, `:data-id`, any other name: set as the attribute without the colon.
- A value mixing text and data takes one `{{ }}`: `:title="Hi {{ name }}"`. Text after a second `{{ }}` is dropped.
- `:class` replaces the whole `class` attribute, static `class="..."` included; the data value must hold every class.
- Boolean attributes (`:disabled`, `:checked`) stay present once set: `false` becomes `disabled="false"`, which still disables. Use `:if` / `:else` variants, or set the DOM property in `when.updated`.
- Kebab-case CSS names write to `style`: `:color`, `:width`, `:background-color`. camelCase (`:backgroundColor`) fails because HTML lowercases attribute names.
- `:html="raw"` sets `innerHTML`; never feed it untrusted input.
- `:hide="flag"` sets `display: none` while truthy.

A plain attribute is never bound: `title="{{ name }}"` stays literal. The only exception is i18n: `placeholder="i18n.search"` translates without a colon.

## Events

```html
<li :for="item in items" :data-id="item.id" @click="remove">{{ item.name }}</li>
```

```js
event: {
  remove(e) {
    const id = Number(e.currentTarget.dataset.id);
    app.data.items = app.data.items.filter((x) => x.id !== id);
  },
}
```

`@click="name"` (or `qe-click`) assigns `element.onclick = event[name]`. Arguments bind nothing (`@click="remove(item.id)"` does not work): pass values through `:data-*` and read `e.currentTarget.dataset`. `this` is the element, so reach data through the `app` variable. A second `@click` on the same element replaces the first.

## Two-way Binding `:model`

```html
<input :model="keyword" :value="keyword" />
```

Works on `input`, `select` and `textarea`, from DOM to data only; add `:value` with the same key to show the current value. The key must be top-level (`form.name` logs `[Invalid]` and is ignored). It listens to `keyup` and `change` (`change` only for `select`). Checkboxes and radios write the checked values of every input with that `name` in the document as one comma-joined string, not an array.

## Loops `:for`

```html
<li :for="item in items">{{ item }}</li>
<li :for="(item, index) in items" :key="item.id">{{ index }} {{ item.name }}</li>
<li :for="(key, value) in obj">{{ key }}={{ value }}</li>
```

The element carrying `:for` is repeated. The source is a path to an array or object; anything else renders nothing. `:key` names an item path and keeps unchanged items' DOM (a missing value logs `[Not found]`). Inside an item, names resolve from the loop variables, then outer loops, then root `data`, so nested loops can read the outer item. `:for` and `:if` on one element is fine: the loop expands first, then each item tests `:if`. Each block is wrapped in `<!--:for-->...<!--/:for-->` comments; skip comment nodes when walking `childNodes`.

## Conditionals `:if`

```html
<p :if="status == active">Active</p>
<p :else-if="count > 0">Has items</p>
<p :else>Empty</p>
```

A condition is `path` (truthy) or `path OP literal` with OP `== != > < >= <=`. `list.length > 1` and `LENGTH(list) > 1` both work.

- The right side is a bare literal: `status == "active"` compares against the quotes and fails, and a path on the right (`count > max`) counts as `0`.
- Special literals: `null`, `true`, `false`, `empty`. `empty` matches `null`, `undefined` and `""`, not `0`; test zero with `== 0`.
- No `!`, `&&` or `||`: write `flag == false`, nest elements, or precompute a boolean into `data`.
- `:else-if` (or `:elif`) and `:else` must be the next sibling elements of the `:if`.

## Including Files `:path`

```html
<temp :path="/components/header.html"></temp>
<temp :path="footerUrl"></temp>
```

Only on a `<temp>` element, which the fetched HTML replaces; that HTML may use bindings too. It cannot share an element with `:for` / `:if` / `:else*` (logs `[Invalid]`), so put the `<temp>` inside. Outside a loop or condition it is fetched once at init; inside, each time the block renders. A failed fetch logs `[Upstream]` / `[Unavailable]` and removes only that `<temp>`. A file that includes itself loops forever.

## i18n

```js
const app = new QUI({
  id: "app",
  i18n: { en: { hello: "Hello", nav: { home: "Home" } }, zh: "/i18n/zh.json" },
});
app.lang("en");
```

Text uses `{{ i18n.hello }}` or nested `{{ i18n.nav.home }}`; attributes use `title="i18n.hello"` or `:title="i18n.hello"`, with no nested keys. There is no default locale: until `lang()` is called, and for any missing key, the raw `i18n.xxx` shows. `app.lang("zh")` re-renders text and attributes; unknown codes are ignored.

## Reactivity

Writes such as `app.data.count++`, `app.data.user.name = "x"`, `app.data.items.push(x)` and `app.data.items = [...]` update every block that reads the changed top-level key (`user`, `items`). Several writes in a row are batched into one update on the next animation frame, so DOM read on the following line is stale; read it in `when.updated`.

## Lazy Images and Inline SVG

```html
<img :lazyload="photoUrl" />
<temp-svg src="/icons/star.svg" class="icon"></temp-svg>
```

`:lazyload` loads the image when it enters the viewport. `<temp-svg>` (`src` or `:src`) is replaced by the fetched `<svg>`, keeping its `id`, classes and `onclick`.

## Render Shorthand

```js
const card = new QUI({
  render: () => `div.card[ h2( q-title: "title" )[ "{{title}}" ] p[ "Hello&#32;World" ] ]`,
  data: { title: "QuickUI" },
  when: { rendered: async () => document.body.append(await card.fragment()) },
});
```

Syntax is `tag#id.class( attr: "v" )[ children ]` with text in double quotes. Every space inside quotes is removed, so write `&#32;`. The parser strips `:`, so bind attributes with the `q-` prefix (`q-title`). With `id` the result replaces that element's children; without it, insert `await app.fragment()` yourself.

## Helpers

`_("div#card.box", { title: "x" }, ["text", _("b", "bold")])` builds an element. Array children accept strings and numbers (as text) and any `Node`; a single string argument becomes `innerHTML`, so wrap untrusted text in an array. `$("app")`, `$("#app")` and `$(".item")` map to `getElementById` / `querySelector`.
