aktion-runtime 0.5.1 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +654 -373
  2. package/dist/aktion.iife.js +798 -790
  3. package/dist/aktion.iife.js.map +1 -1
  4. package/dist/aktion.js +10059 -7997
  5. package/dist/aktion.js.map +1 -1
  6. package/dist/aktion.umd.cjs +798 -790
  7. package/dist/aktion.umd.cjs.map +1 -1
  8. package/dist/system_prompt.txt +595 -829
  9. package/dist/system_prompt_chat.txt +98 -263
  10. package/dist/types/element.d.ts +46 -26
  11. package/dist/types/language/grammar.d.ts +25 -9
  12. package/dist/types/language/index.d.ts +8 -6
  13. package/dist/types/library/components/content.d.ts +0 -1
  14. package/dist/types/library/components/escape-hatch.d.ts +3 -0
  15. package/dist/types/library/components/layout.d.ts +3 -0
  16. package/dist/types/library/components/wrappers.d.ts +12 -0
  17. package/dist/types/library/utils.d.ts +42 -0
  18. package/dist/types/parser/frontier.d.ts +3 -3
  19. package/dist/types/parser/lexer.d.ts +7 -17
  20. package/dist/types/parser/types.d.ts +239 -113
  21. package/dist/types/prompt/generator.d.ts +0 -11
  22. package/dist/types/renderer/renderer.d.ts +60 -7
  23. package/dist/types/runtime/builtins.d.ts +10 -6
  24. package/dist/types/runtime/effects.d.ts +5 -30
  25. package/dist/types/runtime/evaluator.d.ts +356 -25
  26. package/dist/types/runtime/http.d.ts +35 -30
  27. package/dist/types/runtime/i18n.d.ts +23 -32
  28. package/dist/types/runtime/router.d.ts +5 -6
  29. package/dist/types/runtime/state.d.ts +77 -33
  30. package/dist/types/runtime/util.d.ts +88 -0
  31. package/dist/types/theme/styles.d.ts +1 -1
  32. package/dist/types/tooling/delta.d.ts +1 -1
  33. package/dist/types/tooling/inspector.d.ts +1 -1
  34. package/package.json +2 -2
  35. package/dist/types/language/builtins.d.ts +0 -33
package/README.md CHANGED
@@ -5,16 +5,16 @@
5
5
  [![PRs welcome](https://img.shields.io/badge/PRs-welcome-10b981.svg)](#contributing)
6
6
 
7
7
  A framework-agnostic web component that renders LLM-generated UI from
8
- **Aktion** — a compact, declarative language designed for chat
9
- assistants. Drop one `<script>` tag and one `<aktion-app>` tag into
10
- any HTML page and you have a streaming, interactive renderer for an LLM's
11
- response.
8
+ **Aktion** — a reactive language whose surface syntax is a strict subset of
9
+ JavaScript, designed for chat assistants. Drop one `<script>` tag and one
10
+ `<aktion-app>` tag into any HTML page and you have a streaming, interactive
11
+ renderer for an LLM's response.
12
12
 
13
13
  ```html
14
14
  <script type="module" src="https://asfand-dev.github.io/aktion/dist/aktion.js"></script>
15
15
  <aktion-app theme="light">
16
- _app_ = Card([
17
- CardHeader("Hello", subtitle: "Generative UI in plain HTML"),
16
+ aktion = Card([
17
+ CardHeader("Hello", { subtitle: "Generative UI in plain HTML" }),
18
18
  Markdown("This card was streamed in as **plain text**.")
19
19
  ])
20
20
  </aktion-app>
@@ -42,9 +42,8 @@ HTML, or no framework at all.
42
42
  - [Themes](#themes)
43
43
  - [Icons](#icons)
44
44
  - [Routing](#routing)
45
- - [JavaScript escape hatch](#javascript-escape-hatch)
46
- - [Built-in globals (`storage`, `console`)](#built-in-globals)
47
- - [Internationalization (`i18n`)](#internationalization)
45
+ - [Built-in globals (`$storage`, `$console`)](#built-in-globals)
46
+ - [Internationalization (`$i18n`)](#internationalization)
48
47
  - [System prompt generator](#system-prompt-generator)
49
48
  - [Tooling](#tooling)
50
49
  - [Documentation site](#documentation-site)
@@ -62,61 +61,85 @@ HTML, or no framework at all.
62
61
  Everything you need at runtime ships in a single bundle:
63
62
 
64
63
  - **A streaming-first parser.** Line-oriented, error-tolerant. Each
65
- statement commits to the DOM as soon as it arrives. Single, double, and
66
- backtick-quoted strings (with `${expression}` interpolation). `js{ … }`
67
- opaque blocks and `{ … }` declaration bodies for `component` / `effect` /
68
- `action`.
69
- - **One reactive atom kind.** Declare any reactive state with `$name = value`
70
- and read or write it with `$name`. The runtime tracks dependencies
71
- automatically. Template literals, spread, bracket access, optional
72
- chaining, nullish coalescing, expression-form `if` / `match` / `for`,
73
- lambdas (`(p) => …`), `bind:prop: $atom` two-way binding, and **30+ pure
74
- `@`-functions** (`@Filter`, `@Sort`, `@Find`, `@GroupBy`, `@Format`,
75
- `@FormatDate`, `@Plural`, `@Case`, `@Range`, `@Pick`, …).
76
- - **One HTTP primitive.** `http({ url, method, headers, body, query, ... })`
77
- is the only network call. It returns a reactive resource bag exposing
64
+ statement commits to the DOM as soon as it arrives. The surface syntax
65
+ is a **strict subset of JavaScript** — `function` declarations,
66
+ `for...of`, `if/else`, `switch/case`, template literals with
67
+ `${expression}` interpolation, arrow functions, default parameters,
68
+ destructuring, spread, optional chaining (`a?.b`), nullish coalescing
69
+ (`a ?? b`), and object-literal named arguments. Every Aktion program
70
+ is valid JavaScript.
71
+ - **One reactive atom kind.** Declare any reactive state with
72
+ `$name = value` and read or write it with `$name`. The `$` prefix is
73
+ the only thing that makes a binding reactive — `let` / `const` /
74
+ `var` keywords are optional and have no effect on reactivity. The
75
+ runtime tracks dependencies automatically — and at **path
76
+ granularity**: reading `$user.name` subscribes to `user.name` alone,
77
+ so a write to `$user.role` never re-renders, recomputes, or re-fires
78
+ an effect that only read `name` (see *Fine-grained reactivity* below).
79
+ Automatic two-way binding
80
+ via direct state refs (and member chains rooted at one —
81
+ `value: $form.email`), and a **`$util` runtime namespace** of pure
82
+ helpers (`$util.filter`, `$util.sort`, `$util.find`, `$util.groupBy`,
83
+ `$util.format`, `$util.formatDate`, `$util.plural`, `$util.case`,
84
+ `$util.range`, `$util.pick`, …) callable from Aktion expressions and
85
+ ordinary JavaScript alike.
86
+ - **One component-call shape.** Every call follows the trailing-object
87
+ rule — `Component(positionalArg, { prop: value, … })`. At most one
88
+ positional argument; every other argument goes in a trailing
89
+ `{ }` object literal.
90
+ - **One HTTP primitive.** `$http({ url, method, headers, body, query, ... })`
91
+ is the only network call. Each call is self-contained (pass a full
92
+ absolute `url`; `GET` is the default; no host-wide defaults). It returns
93
+ a reactive resource bag exposing
78
94
  `data | error | status | loading | headers | lastUpdated`, plus the
79
- callables `refetch()` and `cancel()`. Re-runs automatically when any
80
- reactive input in the options object changes.
81
- - **`storage` and `console` globals.** Always in scope. `storage.set/get`
82
- (localStorage by default), `storage.session.*`, `storage.cookies.*` with
83
- named-arg options, and `console.log/error/warn/info/debug`. No `js{}`
84
- escape hatch needed.
95
+ callables `refetch()` and `cancel()`. Re-run a request via `refetch()`
96
+ or by wrapping it in an `$effect(..., [$dep])`.
97
+ - **`$storage` and `$console` globals.** Always in scope, no import,
98
+ lowercase. `$storage.set/get` (localStorage by default),
99
+ `$storage.session.*`, `$storage.cookies.*` with object-literal options,
100
+ and `console.log/error/warn/info/debug`.
85
101
  - **A React-like DOM reconciler.** Diffs each re-render against the live
86
102
  DOM. Text-input value, selection, IME state, scroll positions,
87
103
  `<details>.open`, and stateful primitives like `Tabs` are all preserved
88
104
  across renders. Components that need to hold UI state get a
89
105
  `helpers.useInstanceState(...)` slot keyed by their position in the tree.
90
- - **A rich component library** of **130+ components** spanning layout,
106
+ - **A rich component library** of **170+ components** spanning layout,
91
107
  forms, charts, data, feedback, navigation, patterns, app-shell composites,
92
108
  editors, advanced UI, and standard helpers. See [Component library](#component-library).
93
- - **Declarative side effects.** `effect [ ...deps ] { … }` for background
94
- work — anonymous blocks where the dependency list mixes state triggers
95
- (`$atom`), lifecycle triggers (`on:mount`, `on:unmount`, `on:every(N)`),
96
- and rate-limit modifiers (`debounce(N)`, `throttle(N)`). `effect { … }`
97
- with an empty list is equivalent to `effect [on:mount] { … }`. Declare
98
- an effect **at the top level** for program-wide work, or **inside a
99
- `component { … }` body** to scope it to a single instance — timers,
100
- watched atoms, and `cleanup(fn)` registrations tear down when the
101
- component leaves the tree. `action Name(args) { … }` declares
102
- click-driven mutations and may optionally `return` a value.
103
- - **A built-in router.** `pages = _router_({ "/path": Component(), "/users/:id": UserPage(id: params.id), default: NotFound() })` plus
104
- `NavLink(label, to)` and a reserved `_route_` handle that exposes
105
- `_route_.path`, `_route_.params`, `_route_.query`, `_route_.pattern`,
106
- and `_route_.navigate("/path")`. Hash-based, framework-agnostic,
107
- always wired up.
109
+ - **Declarative side effects.** `$effect(() => { body }, [...deps])` for
110
+ background work — anonymous blocks where the dependency list mixes
111
+ state triggers (`$atom`), lifecycle triggers (`"mount"`, `"unmount"`,
112
+ `"every(N)"`), and rate-limit modifiers (`"debounce(N)"`,
113
+ `"throttle(N)"`). `$effect(() => { … })` with no dependency array is
114
+ equivalent to `$effect(() => { … }, ["mount"])`. Declare an effect
115
+ **at the top level** for program-wide work, or **inside a component
116
+ function body** to scope it to a single instance — timers, watched
117
+ atoms, and `cleanup(fn)` registrations tear down when the component
118
+ leaves the tree. `function name(args) { … }` (camelCase) declares an
119
+ action — click-driven mutations that may optionally `return` a value.
120
+ - **Outbound events.** `$emit("name", { detail })` dispatches a
121
+ `CustomEvent` on the host element from inside any action / effect /
122
+ lambda body. The host listens with
123
+ `el.addEventListener("name", …)`.
124
+ - **A built-in router.**
125
+ `pages = $router({ "/path": Component(), "/users/:id": UserPage({ id: params.id }), default: NotFound() })`
126
+ plus `NavLink(label, { to })` and a reserved `route` handle that
127
+ exposes `route.path`, `route.params`, `route.query`, `route.pattern`,
128
+ and `route.navigate("/path")`. Hash-based, framework-agnostic, always
129
+ wired up.
108
130
  - **Seven built-in themes** (`light`, `dark`, `neon`, `pastel`, `glass`,
109
131
  `brutalist`, `skyline`) plus full custom-token support via CSS custom
110
132
  properties. **50+ design tokens** organised into `colors`, `radius`,
111
- `font`, `motion`, and `elevation` groups. Brand the UI from inside the
112
- script with `theme = Theme({...})`.
113
- - **`i18n` runtime.** `$i18n = i18n({ locale, messages, fallback })` plus
114
- a global `t("key", vars?)` builtin and a `Locale()` helper that feeds
115
- the active locale into `@Format` / `@FormatDate`.
133
+ `font`, `motion`, and `elevation` groups. Brand the UI from inside
134
+ the script with `theme = $theme({...})`.
135
+ - **`$i18n` factory.** `const { t, setCurrentLanguage, getCurrentLanguage } = $i18n({ defaultLanguage, currentLanguage, translations })` builds a translation bundle keyed by language, with `{name}` placeholder interpolation.
116
136
  - **Font Awesome 6.7.2** auto-loaded — every `icon` prop accepts a Free
117
- Font Awesome name (no `fa-` prefix). Use `Icon(name, variant?, size?)`
137
+ Font Awesome name (no `fa-` prefix). Use `Icon(name, { variant?, size? })`
118
138
  for standalone glyphs. Variant prefixes supported: `"regular:star"`,
119
139
  `"brands:github"`.
140
+ - **Markup escape hatches.** `HTMLTag(tag, { attributes?, children? })`
141
+ and `Styles(css)` are the last-resort raw-HTML / raw-CSS injectors
142
+ when no standard component captures the design.
120
143
  - **A system prompt generator.** Emits a clean, ordered prompt teaching
121
144
  the LLM exactly which components, builtins, and tools are available.
122
145
  Two flavours ship: `system_prompt.txt` (full — every feature) and
@@ -188,19 +211,19 @@ Three equivalent ways:
188
211
 
189
212
  ```html
190
213
  <!-- as an attribute -->
191
- <aktion-app response='_app_ = Card([CardHeader("Hi")])'></aktion-app>
214
+ <aktion-app response='aktion = Card([CardHeader("Hi")])'></aktion-app>
192
215
 
193
216
  <!-- as inner text (rendered on connect) -->
194
217
  <aktion-app>
195
- _app_ = Card([CardHeader("Hi")])
218
+ aktion = Card([CardHeader("Hi")])
196
219
  </aktion-app>
197
220
 
198
221
  <!-- as a property/method -->
199
222
  <script>
200
223
  const el = document.querySelector("aktion-app");
201
224
  el.setResponse(`
202
- _app_ = Stack([greeting])
203
- greeting = Card([CardHeader("Hello", subtitle: "Generative UI in plain HTML")])
225
+ aktion = Column([greeting])
226
+ greeting = Card([CardHeader("Hello", { subtitle: "Generative UI in plain HTML" })])
204
227
  `);
205
228
  </script>
206
229
  ```
@@ -242,24 +265,15 @@ const prompt = el.getSystemPrompt({
242
265
  mode: "full", // or "chat" for the compact read-only prompt
243
266
  preamble: "You are an analytics assistant.",
244
267
  additionalRules: ["Always end with a FollowUpBlock of 2 prompts."],
245
- tools: [{ name: "list_orders", description: "Return recent orders.", argsExample: { limit: 10 } }],
246
268
  });
247
269
  ```
248
270
 
249
- ### 6. (Optional) Provide tools
271
+ > Network calls are issued by the LLM-authored code itself via the
272
+ > `$http({ url, method, body, ... })` primitive. The host is not involved.
273
+ > Install `el.registerHttpInterceptors(...)` if you need to attach auth
274
+ > headers, retry on 401, or log every request.
250
275
 
251
- Register host-side async functions exposed to `js{}` bodies as
252
- `ctx.tools.<name>(args)`:
253
-
254
- ```js
255
- el.setTools({
256
- list_orders: async ({ limit }) => fetch(`/api/orders?limit=${limit}`).then(r => r.json()),
257
- update_order: async ({ id, status }) =>
258
- fetch(`/api/orders/${id}`, { method: "PATCH", body: JSON.stringify({ status }) }).then(r => r.json()),
259
- });
260
- ```
261
-
262
- ### 7. (Optional) Listen for assistant messages
276
+ ### 6. (Optional) Listen for assistant messages
263
277
 
264
278
  Wire LLM-driven follow-ups back into your chat loop:
265
279
 
@@ -284,9 +298,9 @@ All members live on the `<aktion-app>` element.
284
298
  | `response` | Aktion text | Sets the program declaratively. Re-renders whenever the attribute changes. |
285
299
  | `showerrors` | `true` / unset | If present and `true`, displays parse errors in the rendered UI. Defaults to off. |
286
300
 
287
- Routing and the JavaScript escape hatch (`js{ … }` inside `effect` /
288
- `action` bodies) are always available — no host attribute, no allow-list.
289
- To omit those surfaces from the *generated prompt*, build it via
301
+ Routing and JavaScript execution inside `effect` / action bodies are
302
+ always available — no host attribute, no allow-list. To omit those
303
+ surfaces from the *generated prompt*, build it via
290
304
  `getSystemPrompt({ mode: "chat" })`.
291
305
 
292
306
  ### Properties
@@ -306,11 +320,10 @@ To omit those surfaces from the *generated prompt*, build it via
306
320
  | `appendChunk(chunk)` | Append a streaming chunk and re-render. |
307
321
  | `clear()` | Reset state, queries, and the rendered output. |
308
322
  | `setTheme(name \| tokens)` | Apply a built-in theme by name or a partial token map. |
309
- | `setTools(tools)` | Register host async tools exposed to `js{}` blocks as `ctx.tools.<name>(args)`. Replaces previously-registered tools. |
310
323
  | `registerComponents(specs, root?)` | Extend the built-in library with your own components. |
311
- | `getSystemPrompt(options?)` | Build a system prompt that matches the current library and tools. Pass `{ mode: "chat" }` for the compact variant. |
324
+ | `getSystemPrompt(options?)` | Build a system prompt that matches the current library. Pass `{ mode: "chat" }` for the compact variant. |
312
325
  | `navigate(path)` | Programmatically navigate. Updates `window.location.hash`. |
313
- | `registerHttpInterceptors({ onRequest?, onResponse?, onError? })` | Install interceptors for the `http({...})` layer. `onResponse` receives a `retry()` one-shot for e.g. 401 refresh flows. |
326
+ | `registerHttpInterceptors({ onRequest?, onResponse?, onError? })` | Install interceptors for the `$http({...})` layer. `onResponse` receives a `retry()` one-shot for e.g. 401 refresh flows. |
314
327
  | `serializeState()` | Return every reactive atom as a plain JSON-friendly object (for SSR / resumption). |
315
328
  | `hydrateState(snapshot)` | Apply a snapshot to the live store and schedule a re-render. Atoms not in the snapshot are untouched. |
316
329
  | `loadSnapshot({ programText, state })` | Atomic program + state load. The next render plans the program with the hydrated state already in place. |
@@ -320,112 +333,250 @@ To omit those surfaces from the *generated prompt*, build it via
320
333
 
321
334
  | Event | Detail | When it fires |
322
335
  | -------------------- | --------------------------------------------- | ------------------------------------------------------------------------------ |
323
- | `assistant-message` | `{ message: string }` | When an action or lambda emits `emit "assistant-message" { message: "..." }`. |
336
+ | `assistant-message` | `{ message: string }` | When an action or lambda calls `$emit("assistant-message", { message: "..." })`. |
324
337
  | `error` | `{ errors: ParseError[] }` | After each render whose source had parse errors. |
325
338
  | `route-change` | `{ path, previousPath, source }` | When the current hash path changes. `source` is `"init" \| "hashchange" \| "navigate" \| "external"`. |
326
- | `<custom-name>` | User-defined `{ ... }` | When script emits `emit "name" { ... }` inside an `action` / `effect` body. |
339
+ | `<custom-name>` | User-defined `{ ... }` | When script calls `$emit("name", { ... })` inside an action / effect body. |
327
340
 
328
341
  The `error` event always fires regardless of `showerrors`, so host apps
329
342
  can log or report errors even when the in-page banner is suppressed.
330
343
 
344
+ ### Runtime safety limits
345
+
346
+ Every program is evaluated under a per-render **runtime budget** that
347
+ bounds three independent dimensions so a partial / accidentally
348
+ recursive program (typed live in the playground, mid-stream LLM token,
349
+ …) can't freeze the browser:
350
+
351
+ | Dimension | Default | Triggers on |
352
+ | ------------------- | ------------ | -------------------------------------------------------- |
353
+ | `componentDepth` | 150 levels | `function Foo() { return Foo() }` and other recursive trees |
354
+ | `iterations` | 250 000 / render | unbounded `for`/`while` loops inside function bodies |
355
+ | `arrayLength` | 100 000 entries | `$util.range(0, 1e9)`, `$util.repeat(value, 1e9)` |
356
+
357
+ When a limit trips, the runtime aborts the render, emits an `error`
358
+ event whose detail is shaped like a parse error (`{ line: 0, column:
359
+ 0, message }`), and leaves the previous tick's DOM intact so the user
360
+ still sees something useful. The defaults comfortably fit any
361
+ realistic app; tighten or relax them by constructing a custom budget
362
+ via `createRuntimeBudget({ … })` and passing it through `createContext`
363
+ (or pass `null` to disable enforcement entirely in trusted offline
364
+ pipelines).
365
+
331
366
  ---
332
367
 
333
368
  ## Aktion — the language
334
369
 
335
- A program is a flat list of `name = expression` statements. The renderer
370
+ Aktion's surface syntax is a **strict subset of JavaScript**. Every
371
+ declaration uses standard JS constructs — `function`, `for...of`,
372
+ `if/else`, `switch/case`, arrow functions, object literals — so any
373
+ developer reading the output immediately knows what it does. The renderer
336
374
  commits each line as soon as it streams in, so the user sees the page
337
375
  shell before the leaves arrive.
338
376
 
339
- ```text
377
+ ```js
340
378
  $count = 0
341
379
  $theme = "dark"
342
380
 
343
- component Counter(label = "Count") {
381
+ function Counter(label = "Count") {
344
382
  return Stack([
345
383
  SectionHeader(label),
346
- Button("Inc", onClick: () => $count = $count + 1),
384
+ Button("Inc", { onClick: () => $count = $count + 1 }),
347
385
  Text(`Current: ${$count}`)
348
386
  ])
349
387
  }
350
388
 
351
- action loadOrders() {
352
- $orders = http({ url: "/api/orders", method: "GET" })
389
+ function loadOrders() {
390
+ $orders = $http({ url: "https://api.example.com/orders", method: "GET" })
353
391
  }
354
392
 
355
- effect [$draft, debounce(500)] {
356
- $save = http({ url: "/api/draft", method: "PUT", body: $draft })
357
- }
393
+ $effect(() => {
394
+ $save = $http({ url: "https://api.example.com/draft", method: "PUT", body: $draft })
395
+ }, [$draft, "debounce(500)"])
358
396
 
359
- $orders = http({
360
- url: "/api/users/42/orders",
397
+ $orders = $http({
398
+ url: "https://api.example.com/users/42/orders",
361
399
  method: "GET",
362
400
  query: { limit: 5 }
363
401
  })
364
402
 
365
- pages = _router_({
403
+ pages = $router({
366
404
  "/": Counter(),
367
- "/orders": Async($orders, loading: Spinner(), data: OrderTable($orders.data)),
405
+ "/orders": Async($orders, { loading: Spinner(), data: OrderTable($orders.data) }),
368
406
  default: NotFound()
369
407
  })
370
408
 
371
- _app_ = pages
409
+ aktion = pages
372
410
  ```
373
411
 
374
412
  ### Key constructs
375
413
 
376
- - `_app_ = …` — the reserved entry point. Every program starts with it.
414
+ - `aktion = …` — the reserved entry point. Every program renders from
415
+ it.
377
416
  - `$name = value` — reactive state. One kind. Read or write with the
378
- same sigil. Inside `action` / `effect` / lambda bodies, assignment
417
+ same sigil. Inside action / effect / lambda bodies, assignment
379
418
  operators (`= += -= *= /= ??= ++ --`) are all allowed.
380
- - `component Name(p = default) { return Expression }` — first-class
381
- declarations with default expressions, lexical scope, and per-instance
382
- state. **Always** end with an explicit `return`.
383
- - `action Name(args) { body }` — callable effects with optional
384
- `return`. Used as event handlers (`onClick: save`) or as expressions
385
- (`$result = greet("Ada")`).
386
- - `effect [ ...deps ] { body }` — declarative, anonymous side effects.
387
- The bracketed dependency list mixes state triggers (`$atom`),
388
- lifecycle / interval triggers (`on:mount`, `on:unmount`,
389
- `on:every(N)`), and rate-limit modifiers (`debounce(N)`,
390
- `throttle(N)`). `effect { ... }` (no brackets) is equivalent to
391
- `effect [on:mount] { ... }`. Declare at the program top level for
392
- global work, or inside a `component { … }` body to scope the effect
393
- to that instance — the runtime mounts it on first render and tears
394
- down its timers / subscriptions / `cleanup(fn)` handlers when the
395
- instance leaves the tree.
396
- - Expression-form control flow: `if cond { … } else { … }`,
397
- `match expr { "a": A() default: Else() }`, `for x in xs { Row(x) }`.
398
- Match and router arms use `:` and `default:` (not `->` / `_`).
399
- - `http({ url, method, headers, body, query, ... })` — the only network
400
- primitive. Returns a reactive resource with `.data`, `.error`,
419
+ `let/const/var` are optional and do not affect reactivity — only the
420
+ `$` prefix makes a value reactive.
421
+ - **Component-call shape** — every call follows the trailing-object
422
+ rule:
423
+
424
+ ```js
425
+ Component(positionalArg, { prop: value, … })
426
+ ```
427
+
428
+ Each component accepts **at most one positional argument** (typically
429
+ the title, children array, or primary value); every other argument
430
+ goes in a trailing `{ }` object literal. This is the *only* call
431
+ shape — `Button("Save", "primary", true)` is a schema error; write
432
+ `Button("Save", { variant: "primary", loading: true })` instead.
433
+ - `function Name(p = default) { return Expression }` — PascalCase name
434
+ means it's a component. Parameters use standard JS defaults (`=`).
435
+ Inside the body, `$x = expr` is a **declaration**: the initializer
436
+ runs once when the instance first mounts, and re-renders preserve
437
+ whatever value the user (or an action / effect) has written.
438
+ **Always** end with an explicit `return`. Components do not have a
439
+ `props` object — every parameter is a real JS parameter.
440
+ - `function name(args) { body }` — camelCase name means it's an action.
441
+ Callable effects with optional `return`. Used as event handlers
442
+ (`onClick: save`) or as expressions (`$result = greet("Ada")`).
443
+ - `$effect(() => { body }, [...deps])` — declarative, anonymous side
444
+ effects. The dependency array mixes state triggers (`$atom`),
445
+ lifecycle / interval triggers (`"mount"`, `"unmount"`, `"every(N)"`),
446
+ and rate-limit modifiers (`"debounce(N)"`, `"throttle(N)"`).
447
+ `$effect(() => { … })` (no second argument) is equivalent to
448
+ `$effect(() => { … }, ["mount"])`. Declare at the program top level
449
+ for global work, or inside a component function body to scope the
450
+ effect to that instance — the runtime mounts it on first render and
451
+ tears down its timers / subscriptions / `cleanup(fn)` handlers when
452
+ the instance leaves the tree.
453
+ - `$emit("name", { detail })` — dispatch an outbound `CustomEvent` on
454
+ the host element. Call from any action / effect / lambda body
455
+ whenever the surrounding host page needs to react to a user
456
+ interaction.
457
+ - Standard JS control flow — `if`, `switch`, `for`, `while`, `do…while`,
458
+ `try` are **statements**, exactly as in JavaScript. They run inside
459
+ any imperative body (`function`, lambda with `{ … }`, `effect`) but
460
+ cannot appear on the right-hand side of an assignment. Use ternaries
461
+ and `.map`/`.filter` for value-producing expressions. Bodies may be
462
+ either a block or a single statement (`if (!ok) return`):
463
+
464
+ ```js
465
+ banner = $error ? ErrorAlert($error) : Notice("All good")
466
+ rows = $items.map(item => Row(item))
467
+ // Multi-way dispatch: wrap a `switch` in a function and `return` per arm.
468
+ function viewFor(tab) {
469
+ switch (tab) {
470
+ case "list": return ListView($items)
471
+ case "grid": return GridView($items)
472
+ default: return EmptyState("Pick a view")
473
+ }
474
+ }
475
+ view = viewFor($tab)
476
+ ```
477
+ - Full operator set — arithmetic (`+`, `-`, `*`, `/`, `%`, `**`),
478
+ comparison (`==` / `!=` / `===` / `!==`, `<` / `>` / `<=` / `>=`),
479
+ logical (`&&`, `||`, `??`), bitwise / shift (`&`, `|`, `^`, `~`, `<<`,
480
+ `>>`, `>>>`), and the relational keywords `instanceof` / `in`. Every
481
+ compound-assignment form is supported too (`+=`, `-=`, `*=`, `/=`,
482
+ `%=`, `**=`, `&&=`, `||=`, `??=`, `&=`, `|=`, `^=`, `<<=`, `>>=`,
483
+ `>>>=`).
484
+ - Line continuations — any expression operator (`.`, `?.`, `?`, `:`,
485
+ `&&`, `||`, `??`, `==` / `!=` / `===` / `!==`, `<` / `>` / `<=` /
486
+ `>=`, `instanceof`, `+`, `-`, `*`, `/`, `%`, `**`) may appear at the
487
+ start of the next line and the parser keeps building the same
488
+ expression — matches JavaScript's ASI rules. Use this to split long
489
+ method chains, ternaries, and logical expressions across lines.
490
+ - `$http({ url, method, headers, body, query, ... })` — the only network
491
+ primitive (absolute `url`; `GET` default; no host-wide defaults).
492
+ Returns a reactive resource with `.data`, `.error`,
401
493
  `.status`, `.loading`, `.headers`, `.lastUpdated`, `.refetch()`,
402
- `.cancel()`.
403
- - `pages = _router_({ "/path": Component(), default: NotFound() })` —
404
- function-call router. The reserved `_route_` handle exposes the
405
- reactive surface and a `navigate("/path")` method; each arm body
406
- additionally receives a scoped `params` loop var with its captures.
407
- - `bind:value: $atom` — two-way binding sugar on inputs.
408
- - Lambdas `(args) => expr` and opaque `js{ … }` blocks placed inside
409
- `effect` / `action` bodies.
410
- - `emit "name" { detail }` — dispatch an outbound `CustomEvent` on the
411
- host element.
412
- - Comments: `// line`, `# line`, and `/* block */` — all stripped silently.
494
+ `.cancel()`, and a settable `.onDone` callback that fires each time the
495
+ request settles (handy for `$todos.refetch()` after a write).
496
+ - `pages = $router({ "/path": Component(), default: NotFound() })` —
497
+ function-call router. The reserved `route` handle exposes the
498
+ reactive surface (`route.path`, `route.params`, `route.query`,
499
+ `route.pattern`) and a `route.navigate("/path")` method; each arm
500
+ body additionally receives a scoped `params` loop var with its
501
+ captures.
502
+ - Two-way binding is implicit: pass a `$variable` (or a member chain
503
+ rooted at one — `value: $form.email`) as an input prop and the
504
+ runtime wires it both ways.
505
+ - Lambdas — every JavaScript arrow form is supported: `() => expr`,
506
+ `x => expr` (single param, no parens), `(x) => expr`, `(x, y) => expr`,
507
+ `(x = 0) => x + 1` (defaults), `(...args) => sum(args)` (rest),
508
+ `({ a, b }) => a + b` / `([x, y]) => x` (destructured params),
509
+ `(args) => { … }` (multi-statement, may `return`). The body can wrap
510
+ onto the next line (`x =>\n expr`).
511
+ - Destructured parameters — both `function` declarations and lambdas
512
+ accept array / object patterns (`function Card({ title, tone = "info" })`,
513
+ `function head([first, ...rest])`), with the same defaults / renames /
514
+ rest support as `let`-destructuring.
515
+ - JS expression niceties — array / object spread (`[...xs, y]`,
516
+ `{ ...base, k: v }`), array / object destructuring in `let` / `const`
517
+ / `var` (`let [a, b, ...rest] = arr`, `let { name, age = 0 } = user`),
518
+ computed property keys (`{ [$dynamic]: value }`), prefix and postfix
519
+ `++` / `--` (with JS-accurate return semantics), `new Constructor(...)`
520
+ with trailing member / call chains (`new Date(0).getTime()`), trailing
521
+ commas in function params / call args / literal lists. `async function`
522
+ is accepted as a no-op modifier; `await` is allowed in both statement
523
+ and expression position inside action / effect bodies.
524
+ - Top-level imperative statements — `if` / `for` / `while` / `try` and
525
+ bare expression statements written at the program top level run once
526
+ per plan (e.g. building a `$state` array with a `while` loop). Inside
527
+ a render they behave like a module init block; prefer pure expressions
528
+ (`.map`, `$util.range`) where you can.
529
+ - **`$util` runtime namespace** — pure, side-effect-free helpers for data
530
+ shaping, formatting, dates, math, and strings (`$util.filter`, `$util.sort`,
531
+ `$util.groupBy`, `$util.format`, `$util.formatDate`, `$util.plural`, `$util.range`,
532
+ `$util.addDays`, `$util.pick`, `$util.count`, …). Never carry hidden state —
533
+ safe to call anywhere.
534
+ - **Escape hatches** — `HTMLTag(tag, { attributes?, children? })` for
535
+ raw HTML elements and `Styles(css)` for raw CSS injected into the
536
+ shadow root. Use only when the standard component library cannot
537
+ express the design.
538
+ - **Hoisting & streaming** — references resolve from the entire
539
+ top-level scope, not source order. Always emit `aktion = …` first
540
+ so the reconciler has the page shell to attach streamed leaves to.
541
+ - Comments: `//` line comments and `/* block */` comments — standard
542
+ JS style.
543
+
544
+ #### Built-in globals at a glance
545
+
546
+ | Global | Purpose |
547
+ | --------- | -------------------------------------------------------------------- |
548
+ | `$storage` | Browser persistence — `$storage.set/get`, `$storage.session.*`, `$storage.cookies.*`. |
549
+ | `$console` | Forwards to the host console — `log` / `error` / `warn` / `info` / `debug`. |
550
+ | `route` | Reactive router handle — `path`, `params`, `query`, `pattern`, `navigate(path)`. |
551
+ | JS stdlib | The JS standard library — `Math`, `JSON`, `Object`, `Array`, `Number`, `String`, `Boolean`, `Date`, `Map`, `Set`, `RegExp`, `Promise`, plus `parseInt` / `parseFloat` / `isNaN` / `isFinite` / `encodeURIComponent` / … Use directly (`Math.max(a, b)`, `JSON.stringify(x)`, `Object.keys(o)`) or with `new` (`new Date()`, `new Map()`). |
552
+ | timers | `setTimeout` / `setInterval` / `clearTimeout` / `clearInterval` — like their JS counterparts, but tracked by the runtime and cleared automatically on re-plan/disconnect. Use inside an `effect` and clear in `cleanup`. |
553
+ | full JS globals | The **entire** JavaScript global surface is available — dialogs (`alert`, `confirm`, `prompt`), Web APIs (`fetch`, `URL`, `URLSearchParams`, `Blob`, `FormData`, `crypto`, `navigator`, `localStorage`, `atob`/`btoa`, `Intl`, `BigInt`, `Reflect`, …), and `window` / `document` themselves. Any `globalThis` member resolves by name. |
554
+
555
+ Both `$storage` and `$console` are **lowercase**; the `route` handle is
556
+ **reserved** (never declare a state slot named `route`). Author declarations
557
+ and built-in components always win over a same-named global (a library
558
+ `Text` / `Map` component is never shadowed by the DOM `Text` / `Map`), so the
559
+ global passthrough only resolves names you haven't otherwise defined. For
560
+ reactive data prefer `$http({...})` over raw `fetch`, and timers/listeners
561
+ belong inside an `$effect(...)` so they're cleaned up on unmount.
413
562
 
414
563
  ### The 60-second pitch
415
564
 
416
- ```text
565
+ ```js
417
566
  $days = "7"
418
- $data = http({ url: "/api/metrics", method: "GET", query: { days: $days } })
567
+ $data = $http({ url: "https://api.example.com/metrics", method: "GET", query: { days: $days } })
419
568
 
420
- filter = FormControl("Range", control: Select("days",
569
+ filter = FormControl("Range", { control: Select("days", {
421
570
  items: [SelectItem("7", "7d"), SelectItem("30", "30d")],
422
- value: $days))
423
- kpi = StatCard("Events", value: `${$data.data?.events ?? 0}`, trend: "up")
424
- chart = LineChart(
571
+ value: $days
572
+ }) })
573
+ kpi = StatCard("Events", { value: `${$data.data?.events ?? 0}`, trend: "up" })
574
+ chart = LineChart({
425
575
  labels: $data.data?.daily?.day ?? [],
426
- series: [Series("Events", $data.data?.daily?.events ?? [])])
576
+ series: [Series("Events", $data.data?.daily?.events ?? [])]
577
+ })
427
578
 
428
- _app_ = Stack([CardHeader("Analytics"), filter, kpi, chart])
579
+ aktion = Column([CardHeader("Analytics"), filter, kpi, chart])
429
580
  ```
430
581
 
431
582
  Highlights:
@@ -439,86 +590,239 @@ Highlights:
439
590
  - Array shortcuts: `$rows.length`, `$rows.first`, `$rows.last`,
440
591
  plus pluck (`$rows.title` → `[title1, title2, …]`).
441
592
  - Responsive prop maps on layout components:
442
- `Grid(items, columns: { sm: 1, md: 2, lg: 4 }, gap: "l")`.
443
- - Forward references are allowed — list `_app_ = Stack([...])` first
593
+ `Grid(items, { columns: { sm: 1, md: 2, lg: 4 }, gap: "l" })`.
594
+ - Forward references are allowed — list `aktion = Column([...])` first
444
595
  and let the children stream in beneath it.
445
596
 
446
- ### Declarative todo app (no JS required)
597
+ ### Declarative todo app
447
598
 
448
- ```text
599
+ ```js
449
600
  $todos = [{ id: 1, text: "Welcome — try editing", done: false }]
450
601
  $draft = ""
451
602
 
452
- action add() {
603
+ function add() {
453
604
  $todos = [...$todos, { id: $todos.length + 1, text: $draft, done: false }]
454
605
  $draft = ""
455
606
  }
456
607
 
457
- action remove(id) {
458
- $todos = @Filter($todos, "id", "!=", id)
608
+ function remove(id) {
609
+ $todos = $util.filter($todos, "id", "!=", id)
459
610
  }
460
611
 
461
- row = (t) => Card([Stack([
612
+ row = t => Card([Stack([
462
613
  Text(t.text),
463
- Button("Delete", onClick: () => remove(t.id), variant: "ghost")
614
+ Button("Delete", { onClick: () => remove(t.id), variant: "ghost" })
464
615
  ])])
465
616
 
466
- list = for t in $todos { row(t) }
467
- _app_ = Stack([
468
- Input("draft-input", placeholder: "What needs doing?", value: $draft),
469
- Button("Add", onClick: add, variant: "primary"),
617
+ list = $todos.map(t => row(t))
618
+ aktion = Stack([
619
+ Input("draft-input", { placeholder: "What needs doing?", value: $draft }),
620
+ Button("Add", { onClick: add, variant: "primary" }),
470
621
  list
471
622
  ])
472
623
  ```
473
624
 
625
+ ### Fine-grained reactivity
626
+
627
+ Dependencies are tracked at the **path** you read, not the whole atom.
628
+ Reading `$user.name` subscribes to `user.name` — so a write to a
629
+ **sibling** field leaves that reader untouched, while replacing the whole
630
+ atom (an ancestor) or writing a descendant still wakes it. This is the
631
+ auto-tracking of MobX, the path-granularity of Solid, and the
632
+ "recompute-only-on-input-change" of Redux selectors — with no selectors
633
+ or special syntax. You just read the path.
634
+
635
+ ```js
636
+ $user = { name: "Ada", role: "Engineer" }
637
+
638
+ // Reads `user.name` → depends on `user.name` only.
639
+ greeting = Text(`Hi ${$user.name}`)
640
+
641
+ // Writing the sibling `role` does NOT re-render `greeting`, recompute a
642
+ // `$user.name`-derived value, or fire a `[$user.name]` effect.
643
+ function promote() { $user.role = "Manager" } // greeting stays put
644
+ function rename(next) { $user.name = next } // greeting updates
645
+ ```
646
+
647
+ The rule that keeps it predictable:
648
+
649
+ | You read… | You depend on… |
650
+ | --- | --- |
651
+ | `$user` | `user` (the whole atom) |
652
+ | `$user.name` | `user.name` |
653
+ | `$user.address.city` | `user.address.city` |
654
+ | `$rows[i]` / `$rows.name` (array index / pluck) | `rows` (the array) |
655
+ | `$obj[$key]` (dynamic key) | `obj` + whatever `$key` reads |
656
+
657
+ A change to path **C** wakes a dependency on path **D** exactly when one
658
+ is a prefix of the other (equal, ancestor, or descendant) — sibling paths
659
+ never interfere. Object fields are tracked field-by-field; reading into an
660
+ array (or through a dynamic key) subscribes at the array/container, so
661
+ mutating any element re-renders the list. The same model powers the four
662
+ places work is triggered: **render scheduling** (the app re-renders only
663
+ when a changed path overlaps what it displayed), **computed values**
664
+ (`$total = $util.sum($cart.lines)` recomputes only when `cart.lines`
665
+ changes), **effects** (`$effect(..., [$user.name])`), and **per-component
666
+ re-rendering** (below).
667
+
668
+ #### Per-component re-rendering
669
+
670
+ A component only re-executes when **its own inputs change** — its args
671
+ (props) or a `$state` path its body read. This is the granularity of
672
+ `React.memo` / Solid, but automatic: no `memo()` wrapper. If `$user.age`
673
+ changes, a `ShowName($user.name)` that only read `name` is skipped (its
674
+ body — and any `console.log` in it — doesn't run); only the components that
675
+ actually depend on `age` re-execute.
676
+
677
+ ```js
678
+ function App() {
679
+ $user = { name: "Ada", age: 30 }
680
+ return [ShowName($user.name), ShowAge($user.age)] // siblings, independent
681
+ }
682
+ // Changing $user.age re-runs ShowAge only; ShowName is reused (memoized).
683
+ ```
684
+
685
+ Args are compared shallowly (`Object.is`), so — exactly as in React —
686
+ passing a **fresh inline lambda** each render (`onClick: () => …`) makes the
687
+ receiving component re-render every time; hoist the handler to a stable
688
+ binding if you want it skipped. State changes the path-tracker can't see
689
+ (hook setters, timers, HTTP, effects) fall back to a full re-render.
690
+
691
+ > Granularity is at both the *subscription* and *component* level. When a
692
+ > component does re-execute, Aktion rebuilds its render tree and the morph
693
+ > reconciler patches only the DOM that actually differs.
694
+
474
695
  ### Per-instance state & content-addressed identity
475
696
 
476
- ```text
477
- component Counter(label) {
697
+ ```js
698
+ function Counter(label) {
478
699
  $n = 0
479
700
  return Stack([
480
701
  Text(`${label}: ${$n}`),
481
- Button("inc", onClick: () => $n = $n + 1)
702
+ Button("inc", { onClick: () => $n = $n + 1 })
482
703
  ])
483
704
  }
484
705
 
485
- # Two independent counters — each holds its own atom.
486
- _app_ = Stack([Counter("A"), Counter("B")])
706
+ // Two independent counters — each holds its own atom.
707
+ aktion = Stack([Counter("A"), Counter("B")])
487
708
  ```
488
709
 
489
- Every call site accepts a universal `key:` named argument. The renderer
710
+ Every call site accepts a universal `key` named argument. The renderer
490
711
  uses it as the instance suffix instead of source location, so reordering
491
712
  siblings keeps per-instance state attached to the right element:
492
713
 
493
- ```text
494
- component TaskRow(task) {
495
- return Stack([Text(task.title)], key: task.id)
714
+ ```js
715
+ function TaskRow(task) {
716
+ return Stack([Text(task.title)], { key: task.id })
496
717
  }
497
718
  ```
498
719
 
720
+ ### Hooks — `$state`, `$memo`, and custom `$name`
721
+
722
+ A function whose name starts with `$` is a **hook**, mirroring React's
723
+ `use*` convention. Hooks are the composable way to manage per-instance
724
+ state. Built-in `$state` and `$memo` mirror React's `useState` and
725
+ `useMemo`:
726
+
727
+ ```js
728
+ function Counter() {
729
+ const [count, setCount] = $state(0)
730
+ const label = $memo(() => `Count: ${count}`, [count])
731
+ return Stack([
732
+ Text(label),
733
+ Button("+1", { onClick: () => setCount(c => c + 1) })
734
+ ])
735
+ }
736
+
737
+ aktion = Counter()
738
+ ```
739
+
740
+ - `$state(initial)` returns a `[value, setValue]` pair. `setValue(next)`
741
+ replaces the value; `setValue(prev => next)` derives it from the
742
+ previous value. The initializer is evaluated once, on first render.
743
+ - `$memo(() => compute, [deps])` returns a cached value and recomputes
744
+ only when a dependency changes (shallow `Object.is` compare). Omit the
745
+ deps array to recompute every render.
746
+
747
+ Declare your own hooks with `function $name(...)`. A custom hook's
748
+ body runs **inline in the calling component's hook scope**, so its
749
+ `$state` / `$memo` calls attach to that component — exactly how a React
750
+ custom hook shares its caller's slots:
751
+
752
+ ```js
753
+ function $useCounter(start) {
754
+ const [count, setCount] = $state(start)
755
+ return { count: count, increment: () => setCount(c => c + 1) }
756
+ }
757
+
758
+ function Counter(label) {
759
+ const c = $useCounter(0)
760
+ return Stack([Text(`${label}: ${c.count}`), Button("+1", { onClick: c.increment })])
761
+ }
762
+ ```
763
+
764
+ Two rules, both inherited from React: call hooks **unconditionally and in
765
+ a stable order** at the top level of a component / hook body (slots are
766
+ matched by call order across renders), and remember that hook state
767
+ **resets when the instance leaves the tree** — a remounted component
768
+ starts again from its initial value. `$state` and `$memo` are reserved
769
+ names. The lighter `$name = value` per-instance form above remains
770
+ available when an atom is written directly by the component's actions.
771
+
772
+ ### Global stores — `$store({...})`
773
+
774
+ For state shared across components — the role Redux / Zustand / Pinia play
775
+ elsewhere — declare a **store**. Non-function entries are reactive state;
776
+ function entries are methods that receive the store handle `s` first. Read
777
+ state with `store.field` (fine-grained), call methods with
778
+ `store.method(args)`, and mutate inside a method with `s.field = …`. The
779
+ handle is an app-global singleton with reference-stable methods, so any
780
+ component reads it or calls its actions directly — no prop drilling.
781
+
782
+ ```js
783
+ cart = $store({
784
+ items: [], // state
785
+ count: (s) => s.items.length, // getter → cart.count()
786
+ total: (s) => $util.sum(s.items.map(i => i.price)), // getter → cart.total()
787
+ add: (s, item) => { s.items = [...s.items, item] }, // action → cart.add(item)
788
+ clear: (s) => { s.items = [] },
789
+ })
790
+
791
+ // Siblings with no relationship both talk to the same cart.
792
+ function AddLatte() { return Button("Add", { onClick: () => cart.add({ price: 4.5 }) }) }
793
+ function MiniCart() { return Text(`${cart.count()} items — ${$util.format(cart.total(), "currency")}`) }
794
+ aktion = Column([AddLatte(), MiniCart()])
795
+ ```
796
+
797
+ Reads are fine-grained and per-component (changing `cart.items` re-renders
798
+ only components that read it), and store fields support two-way binding
799
+ (`Input(value: form.draft)`). Use a `$store` for shared state; use a
800
+ component's local `$state` / `$name = value` for state one component owns.
801
+ See the [Global state guide](https://asfand-dev.github.io/aktion/stores.html).
802
+
499
803
  ### Component-scoped effects
500
804
 
501
- `effect [ ...deps ] { … }` blocks can live at the program top level
502
- **or** inside a `component { … }` body. Inside a component body the
805
+ `$effect(() => { … }, [...deps])` blocks can live at the program top level
806
+ **or** inside a component function body. Inside a component body the
503
807
  runtime mounts the effect when the instance first renders and tears it
504
808
  down (clearing timers, unsubscribing watched atoms, firing every
505
809
  registered `cleanup(fn)`) the moment the instance disappears from the
506
810
  tree. Two `LiveClock()` calls produce two independent intervals — and
507
811
  removing one stops only that one:
508
812
 
509
- ```text
510
- _app_ = Stack([LiveClock("UTC"), LiveClock("Local")])
511
-
512
- component LiveClock(label) {
513
- $now = @Now()
514
- effect [on:every(1000)] {
515
- $now = @Now()
516
- }
517
- return Stack([Text(label), Text(@FormatDate($now, "time"))])
813
+ ```js
814
+ aktion = Stack([LiveClock("UTC"), LiveClock("Local")])
815
+
816
+ function LiveClock(label) {
817
+ $now = $util.now()
818
+ $effect(() => {
819
+ $now = $util.now()
820
+ }, ["every(1000)"])
821
+ return Stack([Text(label), Text($util.formatDate($now, "time"))])
518
822
  }
519
823
  ```
520
824
 
521
- Use a top-level `effect [...] { … }` for global work (analytics,
825
+ Use a top-level `$effect(() => { … }, [...])` for global work (analytics,
522
826
  app-wide keyboard shortcuts, hydration of shared atoms); use a
523
827
  component-local effect whenever the background work logically belongs
524
828
  to the UI it serves.
@@ -529,10 +833,10 @@ to the UI it serves.
529
833
  [`src/library/index.js`](./src/library/index.ts)) emits **hard errors**
530
834
  for:
531
835
 
532
- - Closed-token enum mismatches (`Button("Save", variant: "magic")`).
533
- - Unknown named args (`Stack(junk: 1)`).
836
+ - Closed-token enum mismatches (`Button("Save", { variant: "magic" })`).
837
+ - Unknown named args (`Stack({ junk: 1 })`).
534
838
  - One-positional-max violations (`Button("Save", "primary", true)` →
535
- "use `variant: "primary"`, `loading: true`").
839
+ "use `{ variant: "primary", loading: true }`").
536
840
 
537
841
  The host element merges these into `program.errors` so the on-screen
538
842
  banner surfaces every violation.
@@ -552,7 +856,7 @@ deep authoring guide [`coding-gen-skill.md`](./coding-gen-skill.md).
552
856
 
553
857
  ## Component library
554
858
 
555
- The bundle ships **130+ components** grouped by domain. Reach for **pattern composites**
859
+ The bundle ships **170+ components** grouped by domain. Reach for **pattern composites**
556
860
  (`Hero`, `PageHeader`, `Stats`, `Toolbar`, `EmptyState`, `Timeline`,
557
861
  `KanbanBoard`, `DescriptionList`, `PricingTable`, …) before hand-rolling
558
862
  the equivalent with `Card` + `Stack` — they're tuned to produce dense,
@@ -560,8 +864,8 @@ production-quality SaaS UI in a single line.
560
864
 
561
865
  | Group | Components |
562
866
  | ------------------ | ---------- |
563
- | **Layout** | `Stack`, `StackItem`, `Grid`, `GridItem`, `Container`, `Box`, `Spacer`, `Card`, `CardHeader`, `CardFooter`, `Separator`, `Tabs`, `TabItem`, `Accordion`, `AccordionItem`, `Modal`, `Drawer`, `Steps`, `AspectRatio`, `ScrollArea`, `Sticky`, `ResizablePanels`, `MasonryGrid` |
564
- | **Content** | `Text`, `Image`, `Icon`, `Link`, `Badge`, `BadgeList`, `Callout`, `Quote`, `CodeBlock`, `Skeleton`, `Spinner`, `Markdown`, `Kbd` |
867
+ | **Layout** | `Column`, `Row`, `Center`, `Stack`, `StackItem`, `Grid`, `GridItem`, `Container`, `Box`, `Spacer`, `Card`, `CardHeader`, `CardFooter`, `Separator`, `Tabs`, `TabItem`, `Accordion`, `AccordionItem`, `Modal`, `Drawer`, `Steps`, `AspectRatio`, `ScrollArea`, `Sticky`, `ResizablePanels`, `MasonryGrid` |
868
+ | **Content** | `Text`, `Image`, `Icon`, `Badge`, `BadgeList`, `Callout`, `Quote`, `CodeBlock`, `Skeleton`, `Spinner`, `Markdown`, `Kbd` |
565
869
  | **Forms** | `Form`, `FormControl`, `FormSection`, `FieldSet`, `ValidationSummary`, `Input`, `TextArea`, `PasswordInput`, `MaskedInput`, `MentionInput`, `TagInput`, `Select`, `SelectItem`, `Combobox`, `MultiSelect`, `Checkbox`, `CheckBoxGroup`, `CheckBoxItem`, `Radio`, `Switch`, `ToggleGroup`, `Button`, `Buttons`, `SearchBar`, `Slider`, `NumberInput`, `ColorPicker`, `DatePicker`, `DateRangePicker`, `TimePicker`, `DateTimePicker`, `FileUpload`, `PinInput`, `MultiStepForm` |
566
870
  | **Data** | `Table`, `Col`, `DataGrid`, `List`, `ListItem`, `StatCard`, `Stats`, `Sparkline`, `Tile`, `Progress`, `ProgressRing`, `Pagination`, `Tree`, `TreeNode`, `CalendarView`, `ComparisonTable`, `InfiniteList` |
567
871
  | **Charts** | `BarChart`, `LineChart`, `PieChart`, `RadarChart`, `ScatterChart`, `Histogram`, `Heatmap`, `Gauge`, `Series` |
@@ -571,11 +875,56 @@ production-quality SaaS UI in a single line.
571
875
  | **Editors** | `RichTextEditor`, `CodeEditor` |
572
876
  | **Chat** | `SectionBlock`, `ListBlock`, `FollowUpBlock`, `FollowUpItem`, `ActionLink`, `ChatBubble` |
573
877
  | **Patterns** | `Hero`, `PageHeader`, `SectionHeader`, `Toolbar`, `EmptyState`, `Timeline`, `TimelineItem`, `ActivityLog`, `FeatureGrid`, `FeatureItem`, `MediaCard`, `Testimonial`, `ProfileCard`, `Comment`, `Banner`, `Notification`, `InboxPanel`, `OnboardingChecklist`, `KanbanBoard`, `KanbanColumn`, `KanbanCard`, `DescriptionList`, `DescriptionItem`, `StatusDot`, `PricingTable`, `PricingCard`, `LoadingState`, `ErrorState`, `SuccessState`, `Tour`, `Spotlight` |
574
- | **App shell** | `AppShell`, `Sidebar`, `SidebarSection`, `SidebarItem`, `SplitView` |
878
+ | **App shell** | `AppShell`, `Sidebar`, `SidebarSection`, `SidebarItem` (supports `to` for router navigation), `SplitView` |
575
879
  | **Advanced UI** | `IconButton`, `CommandPalette`, `FilterChips`, `FieldRepeater`, `VirtualList`, `QueryBuilder`, `DiffViewer`, `JsonTree`, `Gantt`, `Truncate`, `InlineEdit`, `NotificationBell` |
576
880
  | **Helpers** | `Async`, `Show`, `Portal`, `Redirect`, `Lazy`, `ErrorBoundary` |
577
- | **Theming** | `Theme` |
578
- | **Routing** | `_router_({ … })`, `NavLink` |
881
+ | **Behaviour wrappers** | `OnClick`, `OnMouse`, `OnKeyboard`, `OnFocus`, `OnIntersect`, `Css`, `Link` — attach click / mouse / keyboard / focus / intersection listeners or raw class / style to ANY component without it needing a dedicated prop. `Link(label_or_child, { to?, href?, external? })` wraps either a string or a component as a router-aware anchor. |
882
+ | **Escape hatches** | `HTMLTag`, `Styles` (last-resort raw HTML / CSS — see [language.html](https://asfand-dev.github.io/aktion/language.html#escape-hatches)) |
883
+ | **Theming** | `$theme` |
884
+ | **Routing** | `$router({ … })`, `NavLink` |
885
+
886
+ ### Form `onChange` callback
887
+
888
+ Every input component accepts an optional `onChange(value)` callable
889
+ that fires with the freshly-read value on every change. Use it alongside
890
+ (or instead of) `$variable` two-way binding when you need to react
891
+ beyond a state write (debounce a search, persist a setting, kick off
892
+ a fetch).
893
+
894
+ ```js
895
+ Input("query", { onChange: q => $results = $http({ url: `https://api.example.com/search?q=${q}` }) })
896
+ Slider("vol", { min: 0, max: 100, value: $vol, onChange: v => $storage.set("volume", v) })
897
+ Switch("dark", { value: $theme == "dark", onChange: on => $theme = on ? "dark" : "light" })
898
+ ```
899
+
900
+ ### Behaviour wrappers
901
+
902
+ Six tiny wrappers attach behaviour to any component:
903
+
904
+ ```js
905
+ // Clickable / tappable card
906
+ OnClick(Card([Text("View order")]), { onClick: () => route.navigate("/orders/4821") })
907
+
908
+ // Lazy-load sentinel — fires once when the placeholder scrolls into view
909
+ OnIntersect(Skeleton({ variant: "card" }), { onEnter: $items.refetch, once: true })
910
+
911
+ // Drop zone — uses standard HTML5 drag-and-drop
912
+ OnMouse(Card([Text("Drop files here")]), {
913
+ dragOver: e => e.preventDefault(),
914
+ drop: e => { e.preventDefault(); $files = e.dataTransfer.files }
915
+ })
916
+
917
+ // Apply a custom class / style without breaking out of the component
918
+ Css(Card([Text("Highlighted")]), { class: "highlight", style: "border-color: #f59e0b;" })
919
+ ```
920
+
921
+ `OnClick` / `OnMouse` / `OnKeyboard` / `OnFocus` render the child via a
922
+ transparent wrapper (`display: contents`) so the visual tree is
923
+ unchanged — only events bubble through the wrapper. `OnIntersect` uses
924
+ `IntersectionObserver` and disposes cleanly when the component leaves
925
+ the tree. `Css` merges classes / inline styles directly onto the
926
+ rendered child element. `Link` is the same wrapper applied as an
927
+ `<a>` anchor with optional router-aware navigation (`to`).
579
928
 
580
929
  The full catalog with positional signatures, prop tables, enum values, and
581
930
  live previews is at
@@ -583,27 +932,27 @@ live previews is at
583
932
 
584
933
  ### Rich pattern composites
585
934
 
586
- ```text
587
- action export_q3() { $exp = http({ url: "/exports/q3", method: "POST" }) }
588
- action new_project() { _route_.navigate("/projects/new") }
935
+ ```js
936
+ function export_q3() { $exp = $http({ url: "https://api.example.com/exports/q3", method: "POST" }) }
937
+ function new_project() { route.navigate("/projects/new") }
589
938
 
590
- dashHeader = PageHeader("Engineering Q3", subtitle: "12 active · 4 at risk", breadcrumbs: ["Workspace", "Engineering"], actions: dashActions, status: Badge("On track", "success"))
591
- dashActions = [Button("Export", onClick: export_q3, variant: "secondary"), Button("New project", onClick: new_project, variant: "primary")]
939
+ dashHeader = PageHeader("Engineering Q3", { subtitle: "12 active · 4 at risk", breadcrumbs: ["Workspace", "Engineering"], actions: dashActions, status: Badge("On track", "success") })
940
+ dashActions = [Button("Export", { onClick: export_q3, variant: "secondary" }), Button("New project", { onClick: new_project, variant: "primary" })]
592
941
  kpis = Stats([
593
- StatCard("Active", value: "12", trend: "flat"),
594
- StatCard("At risk", value: "4", trend: "up", delta: "+2"),
595
- StatCard("Shipped", value: "8", trend: "up", delta: "+3"),
596
- StatCard("On-time", value: "87%", trend: "down", delta: "-3%")
942
+ StatCard("Active", { value: "12", trend: "flat" }),
943
+ StatCard("At risk", { value: "4", trend: "up", delta: "+2" }),
944
+ StatCard("Shipped", { value: "8", trend: "up", delta: "+3" }),
945
+ StatCard("On-time", { value: "87%", trend: "down", delta: "-3%" })
597
946
  ])
598
947
  board = KanbanBoard([
599
- KanbanColumn("To do", items: [KanbanCard("Migrate auth", description: "Roll out new SDK.", tags: ["auth"], assignee: "Asha")]),
600
- KanbanColumn("Doing", items: [KanbanCard("Streaming UI v2", description: "20 new components.", tags: ["frontend"], assignee: "Alex", tone: "primary")]),
601
- KanbanColumn("Review", items: [KanbanCard("Mobile onboarding", description: "Awaiting design.", tags: ["mobile"], assignee: "Wren", tone: "warning")]),
602
- KanbanColumn("Done", items: [KanbanCard("Activity timeline", description: "Shipped to 100%.", tags: ["shipped"], assignee: "Mira", tone: "success")])
948
+ KanbanColumn("To do", { items: [KanbanCard("Migrate auth", { description: "Roll out new SDK.", tags: ["auth"], assignee: "Asha" })] }),
949
+ KanbanColumn("Doing", { items: [KanbanCard("Streaming UI v2", { description: "20 new components.", tags: ["frontend"], assignee: "Alex", tone: "primary" })] }),
950
+ KanbanColumn("Review", { items: [KanbanCard("Mobile onboarding", { description: "Awaiting design.", tags: ["mobile"], assignee: "Wren", tone: "warning" })] }),
951
+ KanbanColumn("Done", { items: [KanbanCard("Activity timeline", { description: "Shipped to 100%.", tags: ["shipped"], assignee: "Mira", tone: "success" })] })
603
952
  ])
604
953
  follow = FollowUpBlock(["Show at-risk projects", "Compare to Q2", "Who needs help?"])
605
954
 
606
- _app_ = Stack([dashHeader, kpis, board, follow])
955
+ aktion = Column([dashHeader, kpis, board, follow])
607
956
  ```
608
957
 
609
958
  ### Adding your own components
@@ -673,14 +1022,14 @@ el.setTheme({
673
1022
  });
674
1023
  ```
675
1024
 
676
- ### `Theme({...})` from inside a response
1025
+ ### `$theme({...})` from inside a response
677
1026
 
678
- A response can brand itself by assigning a `Theme({...})` call to the
679
- reserved `theme` binding. The tokens land on the host as CSS variables on
680
- top of the base theme.
1027
+ A response can brand itself by assigning a `$theme({...})` call to the
1028
+ reserved top-level `theme` binding. The tokens land on the host as CSS
1029
+ variables on top of the base theme.
681
1030
 
682
- ```text
683
- theme = Theme({
1031
+ ```js
1032
+ theme = $theme({
684
1033
  colors: {
685
1034
  primary: "#0969da",
686
1035
  border: "#d0d7de",
@@ -694,12 +1043,12 @@ theme = Theme({
694
1043
  radius: { button: "6px", input: "6px" }
695
1044
  })
696
1045
 
697
- _app_ = Stack([CardHeader("GitHub-style page"), Buttons([Button("New repository")])])
1046
+ aktion = Column([CardHeader("GitHub-style page"), Buttons([Button("New repository")])])
698
1047
  ```
699
1048
 
700
- `Theme` expects the **structured** form — top-level groups `colors` /
1049
+ `$theme` expects the **structured** form — top-level groups `colors` /
701
1050
  `radius` / `font` / `motion` / `elevation` (plus metadata keys `name`
702
- and `direction`). Removing the `Theme(...)` line snaps the UI back to
1051
+ and `direction`). Removing the `$theme(...)` line snaps the UI back to
703
1052
  the base theme. Unknown keys are ignored silently, so typos in an
704
1053
  LLM-emitted token map can never break the page.
705
1054
 
@@ -734,8 +1083,8 @@ shadow root. Host apps do **not** need to add a stylesheet.
734
1083
  `"circle-check"`, `"triangle-exclamation"`, `"sack-dollar"`.
735
1084
  - Optional variant prefix: `"regular:star"`, `"brands:github"`. The
736
1085
  default variant is `solid`.
737
- - Use the dedicated `Icon(name, variant?, size?)` component to render a
738
- standalone glyph (`size` ∈ `xs`, `sm`, `md`, `lg`, `xl`).
1086
+ - Use the dedicated `Icon(name, { variant?, size? })` component to render
1087
+ a standalone glyph (`size` ∈ `xs`, `sm`, `md`, `lg`, `xl`).
739
1088
  - Every component prop named `icon` — `NavLink`, `SidebarItem`, `Banner`,
740
1089
  `Notification`, `FeatureItem`, `Badge`, `StatCard`, `ListItem`,
741
1090
  `TimelineItem`, `DescriptionItem`, `Tile`, `EmptyState`, … — expects a
@@ -744,16 +1093,16 @@ shadow root. Host apps do **not** need to add a stylesheet.
744
1093
  stripped silently so legacy emoji leftovers still resolve to the
745
1094
  proper icon.
746
1095
 
747
- ```text
748
- brandIcon = Icon("rocket", "solid", "lg")
1096
+ ```js
1097
+ brandIcon = Icon("rocket", { variant: "solid", size: "lg" })
749
1098
  homeIcon = Icon("house")
750
- profileTab = NavLink("Profile", to: "/profile", variant: "ghost", icon: "user")
1099
+ profileTab = NavLink("Profile", { to: "/profile", variant: "ghost", icon: "user" })
751
1100
  kpis = Stats([
752
- StatCard("Revenue", value: "$48k", trend: "up", delta: "+12%", icon: "sack-dollar"),
753
- StatCard("Orders", value: "1,284", trend: "up", delta: "+8%", icon: "cart-shopping"),
754
- StatCard("Refunds", value: "12", trend: "down", delta: "-3", icon: "rotate-left")
1101
+ StatCard("Revenue", { value: "$48k", trend: "up", delta: "+12%", icon: "sack-dollar" }),
1102
+ StatCard("Orders", { value: "1,284", trend: "up", delta: "+8%", icon: "cart-shopping" }),
1103
+ StatCard("Refunds", { value: "12", trend: "down", delta: "-3", icon: "rotate-left" })
755
1104
  ])
756
- _app_ = Stack([brandIcon, kpis, profileTab])
1105
+ aktion = Stack([brandIcon, kpis, profileTab])
757
1106
  ```
758
1107
 
759
1108
  ---
@@ -765,39 +1114,39 @@ stay in sync with the URL (`#/dashboard`, `#/users/42`). Browser
765
1114
  back/forward, bookmarks, and deep links all work — and the host page
766
1115
  never reloads.
767
1116
 
768
- ```text
769
- pages = _router_({
1117
+ ```js
1118
+ pages = $router({
770
1119
  "/": homePage,
771
1120
  "/dashboard": dashboardPage,
772
- "/users/:id": userPage(id: params.id),
1121
+ "/users/:id": userPage({ id: params.id }),
773
1122
  default: notFoundPage
774
1123
  })
775
1124
 
776
- nav = Stack([
777
- NavLink("Home", to: "/", exact: true),
778
- NavLink("Dashboard", to: "/dashboard"),
779
- NavLink("Users", to: "/users")
780
- ], direction: "row", gap: "s")
1125
+ nav = Row([
1126
+ NavLink("Home", { to: "/", exact: true }),
1127
+ NavLink("Dashboard", { to: "/dashboard" }),
1128
+ NavLink("Users", { to: "/users" })
1129
+ ], { gap: "s" })
781
1130
 
782
- _app_ = Stack([nav, pages])
1131
+ aktion = Stack([nav, pages])
783
1132
 
784
1133
  homePage = Card([CardHeader("Welcome")])
785
1134
  dashboardPage = Card([CardHeader("Dashboard")])
786
1135
  userPage = (id) => Card([CardHeader(`User ${id}`)])
787
- notFoundPage = Callout("Not found", description: `We couldn't find ${_route_.path}.`, variant: "warning")
1136
+ notFoundPage = Callout("Not found", { description: `We couldn't find ${route.path}.`, variant: "warning" })
788
1137
  ```
789
1138
 
790
- - `pages = _router_({ "/path": Component(), default: Fallback() })` picks
1139
+ - `pages = $router({ "/path": Component(), default: Fallback() })` picks
791
1140
  the matching arm based on the current hash path. First match wins;
792
1141
  `default:` is the fallback.
793
1142
  - Route patterns support literal segments (`"/about"`), parameter
794
1143
  segments (`"/users/:id"` → `params.id`), and trailing wildcards
795
1144
  (`"/docs/*"` → `params._`).
796
- - `NavLink(label, to:, variant?, exact?, icon?)` is a router-aware anchor
797
- that intercepts clicks and reflects `data-active="true"` for the
1145
+ - `NavLink(label, { to, variant?, exact?, icon? })` is a router-aware
1146
+ anchor that intercepts clicks and reflects `data-active="true"` for the
798
1147
  current path.
799
- - The reactive `_route_` handle exposes `_route_.path`, `_route_.params`,
800
- `_route_.query`, and `_route_.pattern`. Call `_route_.navigate("/path")`
1148
+ - The reactive `route` handle exposes `route.path`, `route.params`,
1149
+ `route.query`, and `route.pattern`. Call `route.navigate("/path")`
801
1150
  from inside the script, or `el.navigate("/path")` from the host.
802
1151
 
803
1152
  The default ("full") system prompt teaches the LLM about routing. The
@@ -807,88 +1156,27 @@ for the full walkthrough.
807
1156
 
808
1157
  ---
809
1158
 
810
- ## JavaScript escape hatch
811
-
812
- `js{ … }` blocks live inside `effect` or `action` bodies — no host
813
- attribute, no allow-list. Reach for them only when no declarative path
814
- captures the behaviour (timers, clipboard, audio, complex computations,
815
- host-tool calls).
816
-
817
- ```text
818
- $todos = []
819
-
820
- action toggle(id) {
821
- js {
822
- const todos = ctx.state.get("todos") || []
823
- ctx.state.set("todos", todos.map(t => t.id === ctx.args.id ? { ...t, done: !t.done } : t))
824
- }
825
- }
826
-
827
- row = (t) => Card([Stack([
828
- Text(t.text),
829
- Button("Toggle", onClick: () => toggle(t.id))
830
- ])])
831
-
832
- list = for t in $todos { row(t) }
833
- _app_ = Stack([list])
834
- ```
835
-
836
- Inside the `js{ … }` block:
837
-
838
- - `ctx.state.get(name)` / `ctx.state.set(name, value)` read and write
839
- reactive atoms.
840
- - `ctx.args` exposes the action's positional parameters keyed by name.
841
- - `ctx.cleanup(fn)` (effects only) registers a teardown to fire on
842
- re-run and unmount.
843
- - `ctx.host` is the host element, for DOM-observing effects.
844
- - `ctx.tools` is a host-registered async tool registry (see `el.setTools(...)`).
845
-
846
- The body runs inside `(async () => { … })()` so `await` is free. Errors
847
- are caught and logged — a broken body never crashes the host page.
848
-
849
- For long-lived behaviour, prefer an `effect`:
850
-
851
- ```text
852
- effect [$draft, debounce(500)] {
853
- js {
854
- await fetch("/save", { method: "POST", body: JSON.stringify({ draft: ctx.state.get("draft") }) })
855
- }
856
- }
857
- ```
858
-
859
- The default (full) system prompt teaches `effect` / `action` / `js{}`;
860
- the chat-flavoured prompt (`getSystemPrompt({ mode: "chat" })`) omits
861
- the JS section entirely.
862
-
863
- See the
864
- [JavaScript interactions guide](https://asfand-dev.github.io/aktion/javascript-interactions.html)
865
- or the deep
866
- [`coding-gen-skill.md`](./coding-gen-skill.md)
867
- for a full walkthrough.
868
-
869
- ---
870
-
871
1159
  ## Built-in globals
872
1160
 
873
- Two namespace globals are always in scope inside a Aktion
874
- program — no import, no `js{}` block required. Both follow the standard
875
- `obj.method(args)` method-call syntax and accept named-arg options.
1161
+ Two namespace globals are always in scope inside an Aktion
1162
+ program — no import required. Both follow the standard
1163
+ `obj.method(args)` method-call syntax and accept object-literal options.
876
1164
 
877
- ```text
878
- # localStorage is the default; `storage.local` is its alias.
879
- storage.set("name", "John")
880
- $name = storage.get("name")
1165
+ ```js
1166
+ // localStorage is the default; `$storage.local` is its alias.
1167
+ $storage.set("name", "John")
1168
+ $name = $storage.get("name")
881
1169
 
882
- # Per-tab sessionStorage.
883
- storage.session.set("draft", $draft)
884
- $draft = storage.session.get("draft")
1170
+ // Per-tab sessionStorage.
1171
+ $storage.session.set("draft", $draft)
1172
+ $draft = $storage.session.get("draft")
885
1173
 
886
- # Cookies — named-arg options become a single options object.
887
- storage.cookies.set("user", "John", expires: 7, path: "/", sameSite: "Lax")
888
- $user = storage.cookies.get("user")
889
- storage.cookies.remove("user", path: "/")
1174
+ // Cookies — options as an object literal.
1175
+ $storage.cookies.set("user", "John", { expires: 7, path: "/", sameSite: "Lax" })
1176
+ $user = $storage.cookies.get("user")
1177
+ $storage.cookies.remove("user", { path: "/" })
890
1178
 
891
- # Forwards to the host console.
1179
+ // Forwards to the host console.
892
1180
  console.log("Hello", $user)
893
1181
  console.error("Something failed", $error)
894
1182
  ```
@@ -909,28 +1197,45 @@ for the full surface.
909
1197
 
910
1198
  ## Internationalization
911
1199
 
912
- The `$i18n = i18n({...})` declaration configures the active locale,
913
- message bundles, and fallback. A global `t(key, vars?)` builtin and a
914
- `Locale()` helper feed the active locale into `@Format` / `@FormatDate`.
915
-
916
- ```text
917
- $i18n = i18n({
918
- locale: "fr-FR",
919
- fallback: "en",
920
- messages: {
921
- greeting: "Bonjour, ${name}!",
922
- orders: { title: "Commandes récentes" }
1200
+ Call `$i18n({...})` to build a translation bundle. You can destructure
1201
+ `t`, `setCurrentLanguage`, and `getCurrentLanguage`, or keep the result
1202
+ as an instance and call its methods.
1203
+
1204
+ ```js
1205
+ const { t, setCurrentLanguage, getCurrentLanguage } = $i18n({
1206
+ defaultLanguage: "en",
1207
+ currentLanguage: "fr",
1208
+ translations: {
1209
+ greeting: { en: "Hello, {name}!", fr: "Bonjour, {name}!" },
1210
+ orders_title:{ en: "Recent orders", fr: "Commandes récentes" },
1211
+ items_count: { en: "{count} items", fr: "{count} objets" }
923
1212
  }
924
1213
  })
925
1214
 
926
- welcome = Text(t("greeting", { name: $user.name }))
927
- sectionTitle = SectionHeader(t("orders.title"))
928
- formatted = Text(@Format(1234.5, "currency", "EUR", Locale()))
1215
+ welcome = Text(t("greeting", { name: $user.name }))
1216
+ sectionTitle = SectionHeader(t("orders_title"))
1217
+ count = Text(t("items_count", { count: 5 }))
929
1218
  ```
930
1219
 
931
- Keys support dot paths. Variables are interpolated using `${name}`
932
- placeholders. Missing keys fall back to the fallback locale's bundle,
933
- then to the bare key as a literal string.
1220
+ Lookups resolve `translations[key][currentLanguage]`, fall back to
1221
+ `translations[key][defaultLanguage]`, then to the bare key as a literal
1222
+ string. Variables are interpolated using `{name}` placeholders.
1223
+
1224
+ For reactive language switching, drive `currentLanguage` from a state
1225
+ atom and either call `setCurrentLanguage(...)` or rebuild the bundle:
1226
+
1227
+ ```js
1228
+ $lang = "fr"
1229
+ const i18nInstance = $i18n({
1230
+ defaultLanguage: "en",
1231
+ currentLanguage: $lang,
1232
+ translations: { hi: { en: "Hi", fr: "Salut", de: "Hallo" } }
1233
+ })
1234
+ aktion = Column([
1235
+ Text(i18nInstance.t("hi")),
1236
+ Button("Deutsch", { onClick: () => { $lang = "de" } })
1237
+ ])
1238
+ ```
934
1239
 
935
1240
  ---
936
1241
 
@@ -985,8 +1290,8 @@ import {
985
1290
  ```
986
1291
 
987
1292
  - `formatProgram` projects the parsed AST back to canonical source —
988
- `prop: value` named args, double-quoted strings, two-space block
989
- indentation, `bind:` preserved, template literals intact.
1293
+ object-literal named args, double-quoted strings, two-space block
1294
+ indentation, template literals intact.
990
1295
  - `inspectAST(source)` returns a JSON-friendly view of the Committed +
991
1296
  Drafting ASTs at the current byte position — bindings (with
992
1297
  kind / line / column / summary), in-flight names, and any parse errors.
@@ -1013,14 +1318,16 @@ consumes from the CDN.
1013
1318
  | `get-started.html` | Step-by-step integration walkthrough. |
1014
1319
  | `frameworks.html` | Integration recipes for React, Next.js, Vue, Angular, Svelte, plain HTML. |
1015
1320
  | `language.html` | Full Aktion language reference. |
1321
+ | `http.html` | HTTP guide — the `$http({...})` primitive, config options, the reactive resource bag, `Async`, refetch/cancel patterns, and a full CRUD walkthrough. |
1016
1322
  | `components.html` | Every built-in component with a live preview, positional signatures, prop tables, and enum values. |
1017
- | `actions.html` | `action Name() { … }` guide — declarative state mutations, optimistic snapshot/rollback, lambda-based click handlers, navigation, and end-to-end examples. |
1018
- | `side-effects.html` | `effect [ ...deps ] { … }` guide — anonymous side effects, dependency entries (state, lifecycle, intervals, debounce/throttle), top-level vs. component-local scope, cleanup, and effect vs. action. |
1019
- | `javascript-interactions.html` | `effect [ ...deps ] { js { … } }` + action `js{}` bodies — the JS escape hatch. |
1323
+ | `actions.html` | `function name() { … }` guide — declarative state mutations, optimistic snapshot/rollback, lambda-based click handlers, navigation, and end-to-end examples. |
1324
+ | `side-effects.html` | `$effect(() => { … }, [...deps])` guide — anonymous side effects, dependency entries (state, lifecycle, intervals, debounce/throttle), top-level vs. component-local scope, cleanup, and effect vs. action. |
1325
+ | `javascript-interactions.html` | Effect + action bodies — the JavaScript execution surface. |
1020
1326
  | `routing.html` | Hash-based routing guide — always available at runtime. |
1021
1327
  | `themes.html` | Built-in themes gallery, live picker, side-by-side compare, and the token customization studio. |
1022
1328
  | `examples.html` | Curated showcase of real-world block UIs (auth, products, FAQ, cart, todos, …). |
1023
1329
  | `playground.html` | CodeMirror 6 editor with custom highlighting / autocomplete, live preview, share links, hover-over component info, and an inspection mode. |
1330
+ | `visual-editor.html` | Drag-and-drop visual editor for the full 170+ component library. Three canvas modes (Raw Edit / Visual Edit / Preview), an Outline tab for top-level entity navigation, typed prop editors, cross-entity selection, and import / export of `.aktion` + self-contained HTML via an editable Source drawer. |
1024
1331
  | `chat-bot.html` | OpenRouter-powered streaming chat with four generation modes (Chat Compact, Chat Full, Website Builder, App Builder), image / PDF attachment support, and download-as-standalone-HTML. |
1025
1332
  | `live-examples.html` | Catalog page that links every demo into the shared `live-example.html?example=<slug>` shell. |
1026
1333
  | `live-example.html` | Shared shell for the bundled live examples — picks the demo from the `?example=<slug>` query parameter. |
@@ -1031,20 +1338,19 @@ consumes from the CDN.
1031
1338
 
1032
1339
  Every standalone demo is served by a single shell page
1033
1340
  (`docs/live-example.html`) and a single JS bundle
1034
- (`docs/assets/live-example.js`) that ships every demo's UI Script source
1341
+ (`docs/assets/live-example.js`) that ships every demo's Aktion source
1035
1342
  and setup code together. Open any example with
1036
1343
  `live-example.html?example=<slug>` — the shell renders the original
1037
1344
  hero / source / output layout, so each demo doubles as an integration
1038
- recipe for `setResponse`, `appendChunk`, `setTools`, and `setTheme`.
1345
+ recipe for `setResponse`, `appendChunk`, and `setTheme`.
1039
1346
 
1040
1347
  | Demo slug | Highlights |
1041
1348
  | ------------------------------- | ----------------------------------------------------------------------------------------------------------- |
1042
- | `routing-demo` | A four-page app driven by `pages = _router_({ … })` + `NavLink`, deep links, browser back/forward. |
1043
1349
  | `settings-app` | Tabs, `Switch`, `ToggleGroup`, `Progress`, `Kbd`, danger-zone confirmation `Drawer`. |
1044
1350
  | `data-explorer` | Analytics surface: sortable `DataGrid` + bulk toolbar, `Gauge` SLA dials, `LineChart`, `Heatmap`, `RadarChart`, `ScatterChart`, `Histogram`, `InfiniteList`, `ActivityLog`. |
1045
1351
  | `media-gallery` | Travel magazine: `Carousel` hero, `Gallery` + click-to-zoom `Lightbox`, `VideoPlayer`, `AudioPlayer`, Leaflet-backed `Map`. |
1046
1352
  | `content-studio` | CMS-style authoring surface: `RichTextEditor`, `CodeEditor`, `MultiStepForm`, `ColorPicker`, `TagInput`, `MentionInput`, `PinInput`, `ValidationSummary`, `TopBar`. |
1047
- | `brand-themes.html` | Same UI reskinned with `Theme({...})` for **GitHub**, **Apple**, **Stripe**, **IONOS**, **Notion**, **Vercel** (bespoke UI on its own page). |
1353
+ | `brand-themes.html` | Same UI reskinned with `$theme({...})` for **GitHub**, **Apple**, **Stripe**, **IONOS**, **Notion**, **Vercel** (bespoke UI on its own page). |
1048
1354
 
1049
1355
  The full catalog with tag filters lives at
1050
1356
  [`docs/live-examples.html`](https://asfand-dev.github.io/aktion/live-examples.html).
@@ -1061,12 +1367,12 @@ The full catalog with tag filters lives at
1061
1367
  │ │ ├── builtins.ts # pure @-function helpers
1062
1368
  │ │ ├── evaluator.ts # program planner + binding resolver
1063
1369
  │ │ ├── state.ts # reactive store — `$name = value`
1064
- │ │ ├── effects.ts # EffectRunner + ActionDeclRunner + js{} executor
1065
- │ │ ├── http.ts # http({...}) reactive HTTP primitive + interceptors
1066
- │ │ ├── i18n.ts # $i18n runtime + t() / Locale() builtins
1067
- │ │ ├── storage.ts # storage.local / .session / .cookies bridge
1370
+ │ │ ├── effects.ts # EffectRunner + ActionDeclRunner
1371
+ │ │ ├── http.ts # $http({...}) reactive HTTP primitive + interceptors
1372
+ │ │ ├── i18n.ts # $i18n({...}) factory — returns { t, setCurrentLanguage, getCurrentLanguage }
1373
+ │ │ ├── $storage.ts # $storage.local / .session / .cookies bridge
1068
1374
  │ │ ├── console.ts # console.* host bridge
1069
- │ │ └── router.ts # Hash-based router for _router_({…}) calls and NavLink
1375
+ │ │ └── router.ts # Hash-based router for $router({…}) calls and NavLink
1070
1376
  │ ├── library/ # Component specs and registry
1071
1377
  │ │ └── components/ # layout / content / forms / data / charts / chat /
1072
1378
  │ │ # feedback / navigation / menu / patterns / helpers / router
@@ -1153,23 +1459,14 @@ script.
1153
1459
  npm test
1154
1460
  ```
1155
1461
 
1156
- The suite covers:
1157
-
1158
- - Parser / lexer correctness (`tests/parser.test.ts`).
1159
- - Runtime evaluator + reactive state + `http({...})` (`tests/runtime.test.ts`).
1160
- - `effect` / `action` declarations + `js{}` execution (`tests/javascript-integration.test.ts`).
1161
- - Hash-based router + `NavLink` (`tests/router.test.ts`).
1162
- - Theme resolution and token application (`tests/theme.test.ts`).
1163
- - In-script `Theme(...)` overrides (`tests/in-script-theme.test.ts`).
1164
- - Component library smoke tests (`tests/library.test.ts`).
1165
- - Element-level integration via happy-dom (`tests/element.test.ts`).
1166
- - System prompt generator output (`tests/prompt.test.ts`).
1167
- - Storage + console globals (`tests/storage-console.test.ts`).
1168
- - End-to-end programs (`tests/suis2-end-to-end.test.ts`).
1169
- - Language support spec for editor / tooling integrations (`tests/language.test.ts`).
1170
- - One-positional-max enforcement (`tests/suis2-one-positional.test.ts`).
1171
- - Component prop aliases (`tests/suis2-prop-aliases.test.ts`).
1172
- - Icon rendering (`tests/icons.test.ts`).
1462
+ The suite covers parser/lexer, runtime evaluator + reactive state +
1463
+ `$http({...})`, effects / actions, the hash-based router + `NavLink`,
1464
+ theme resolution, in-script `$theme(...)` overrides, the component
1465
+ library, element-level integration via happy-dom, the system prompt
1466
+ generator, storage / console globals, the language-support spec for
1467
+ editor tooling, prop aliases & one-positional-max enforcement, icon
1468
+ rendering, and language-concept coverage (computed values, math,
1469
+ lambdas, hoisting, i18n, `for` extensions, user components).
1173
1470
 
1174
1471
  ### Build the documentation site
1175
1472
 
@@ -1194,7 +1491,7 @@ Then open <http://localhost:4321/index.html>.
1194
1491
 
1195
1492
  The library treats every LLM-supplied attribute as untrusted and runs
1196
1493
  it through a small set of sanitisers before it lands on the DOM. HTTP
1197
- requests issued by the LLM through `http({...})` flow through your host's
1494
+ requests issued by the LLM through `$http({...})` flow through your host's
1198
1495
  `registerHttpInterceptors({ onRequest, onResponse, onError })` chain so
1199
1496
  auth headers, CORS workarounds, and refresh-token retries stay under
1200
1497
  host control.
@@ -1212,37 +1509,21 @@ renderer get `rel="noopener noreferrer"` so the destination cannot
1212
1509
  read the opener's `document.referrer`.
1213
1510
 
1214
1511
  If you embed `<aktion-app>` behind a CSP, the bundle does not
1215
- use `eval`. `js{}` bodies inside `effect` / `action` declarations are
1216
- evaluated with `new Function(...)` which requires `'unsafe-eval'` if
1217
- you want them to work; if you cannot relax CSP, simply avoid emitting
1218
- `js{}` blocks from the LLM — every other part of the runtime keeps
1219
- working without the JS escape hatch.
1512
+ use `eval`. Effect and action bodies are evaluated with
1513
+ `new Function(...)` which requires `'unsafe-eval'` if you want them to
1514
+ run arbitrary JavaScript; if you cannot relax CSP, simply avoid emitting
1515
+ complex JS expressions from the LLM — declarative constructs (component
1516
+ trees, `$http()`, `@`-functions) keep working without `unsafe-eval`.
1220
1517
 
1221
1518
  ---
1222
1519
 
1223
1520
  ## CDN deployment
1224
1521
 
1225
- This repository ships its own copy of the bundle on GitHub Pages, so
1226
- most users do not need to host anything themselves:
1227
-
1228
- ```html
1229
- <script type="module" src="https://asfand-dev.github.io/aktion/dist/aktion.js"></script>
1230
- <aktion-app theme="dark"></aktion-app>
1231
- ```
1232
-
1233
- …plus a fetch of `system_prompt.txt` server-side to build LLM messages:
1234
-
1235
- ```bash
1236
- curl https://asfand-dev.github.io/aktion/dist/system_prompt.txt
1237
- ```
1238
-
1239
- To ship your own copy, run `npm run build` and serve the `dist/` folder
1240
- from any static host — every artifact in `dist/` is self-contained.
1241
-
1242
- GitHub Pages deployment for this repo is automated via
1243
- [`.github/workflows/deploy-pages.yml`](.github/workflows/deploy-pages.yml).
1244
- Push to `main` and the workflow will build, test, assemble `site/`, and
1245
- publish.
1522
+ This repo serves its own bundle on GitHub Pages (see Quick start §1).
1523
+ To ship your own copy, run `npm run build` and serve `dist/` from any
1524
+ static host — every artifact in `dist/` is self-contained. Push to
1525
+ `main` and [`.github/workflows/deploy-pages.yml`](.github/workflows/deploy-pages.yml)
1526
+ builds, tests, and publishes.
1246
1527
 
1247
1528
  ---
1248
1529