aktion-runtime 0.5.2 → 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 -376
  2. package/dist/aktion.iife.js +798 -790
  3. package/dist/aktion.iife.js.map +1 -1
  4. package/dist/aktion.js +10046 -8011
  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 +53 -4
  23. package/dist/types/runtime/builtins.d.ts +10 -6
  24. package/dist/types/runtime/effects.d.ts +3 -28
  25. package/dist/types/runtime/evaluator.d.ts +333 -24
  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,115 +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. Inside the body, `$x = expr` is a **declaration**: the
383
- initializer runs once when the instance first mounts, and re-renders
384
- preserve whatever value the user (or an action / effect) has written.
385
- **Always** end with an explicit `return`.
386
- - `action Name(args) { body }` — callable effects with optional
387
- `return`. Used as event handlers (`onClick: save`) or as expressions
388
- (`$result = greet("Ada")`).
389
- - `effect [ ...deps ] { body }` — declarative, anonymous side effects.
390
- The bracketed dependency list mixes state triggers (`$atom`),
391
- lifecycle / interval triggers (`on:mount`, `on:unmount`,
392
- `on:every(N)`), and rate-limit modifiers (`debounce(N)`,
393
- `throttle(N)`). `effect { ... }` (no brackets) is equivalent to
394
- `effect [on:mount] { ... }`. Declare at the program top level for
395
- global work, or inside a `component { … }` body to scope the effect
396
- to that instance — the runtime mounts it on first render and tears
397
- down its timers / subscriptions / `cleanup(fn)` handlers when the
398
- instance leaves the tree.
399
- - Expression-form control flow: `if cond { … } else { … }`,
400
- `match expr { "a": A() default: Else() }`, `for x in xs { Row(x) }`.
401
- Match and router arms use `:` and `default:` (not `->` / `_`).
402
- - `http({ url, method, headers, body, query, ... })` — the only network
403
- 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`,
404
493
  `.status`, `.loading`, `.headers`, `.lastUpdated`, `.refetch()`,
405
- `.cancel()`.
406
- - `pages = _router_({ "/path": Component(), default: NotFound() })` —
407
- function-call router. The reserved `_route_` handle exposes the
408
- reactive surface and a `navigate("/path")` method; each arm body
409
- additionally receives a scoped `params` loop var with its captures.
410
- - `bind:value: $atom` — two-way binding sugar on inputs.
411
- - Lambdas `(args) => expr` and opaque `js{ … }` blocks placed inside
412
- `effect` / `action` bodies.
413
- - `emit "name" { detail }` — dispatch an outbound `CustomEvent` on the
414
- host element.
415
- - 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.
416
562
 
417
563
  ### The 60-second pitch
418
564
 
419
- ```text
565
+ ```js
420
566
  $days = "7"
421
- $data = http({ url: "/api/metrics", method: "GET", query: { days: $days } })
567
+ $data = $http({ url: "https://api.example.com/metrics", method: "GET", query: { days: $days } })
422
568
 
423
- filter = FormControl("Range", control: Select("days",
569
+ filter = FormControl("Range", { control: Select("days", {
424
570
  items: [SelectItem("7", "7d"), SelectItem("30", "30d")],
425
- value: $days))
426
- kpi = StatCard("Events", value: `${$data.data?.events ?? 0}`, trend: "up")
427
- chart = LineChart(
571
+ value: $days
572
+ }) })
573
+ kpi = StatCard("Events", { value: `${$data.data?.events ?? 0}`, trend: "up" })
574
+ chart = LineChart({
428
575
  labels: $data.data?.daily?.day ?? [],
429
- series: [Series("Events", $data.data?.daily?.events ?? [])])
576
+ series: [Series("Events", $data.data?.daily?.events ?? [])]
577
+ })
430
578
 
431
- _app_ = Stack([CardHeader("Analytics"), filter, kpi, chart])
579
+ aktion = Column([CardHeader("Analytics"), filter, kpi, chart])
432
580
  ```
433
581
 
434
582
  Highlights:
@@ -442,86 +590,239 @@ Highlights:
442
590
  - Array shortcuts: `$rows.length`, `$rows.first`, `$rows.last`,
443
591
  plus pluck (`$rows.title` → `[title1, title2, …]`).
444
592
  - Responsive prop maps on layout components:
445
- `Grid(items, columns: { sm: 1, md: 2, lg: 4 }, gap: "l")`.
446
- - 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
447
595
  and let the children stream in beneath it.
448
596
 
449
- ### Declarative todo app (no JS required)
597
+ ### Declarative todo app
450
598
 
451
- ```text
599
+ ```js
452
600
  $todos = [{ id: 1, text: "Welcome — try editing", done: false }]
453
601
  $draft = ""
454
602
 
455
- action add() {
603
+ function add() {
456
604
  $todos = [...$todos, { id: $todos.length + 1, text: $draft, done: false }]
457
605
  $draft = ""
458
606
  }
459
607
 
460
- action remove(id) {
461
- $todos = @Filter($todos, "id", "!=", id)
608
+ function remove(id) {
609
+ $todos = $util.filter($todos, "id", "!=", id)
462
610
  }
463
611
 
464
- row = (t) => Card([Stack([
612
+ row = t => Card([Stack([
465
613
  Text(t.text),
466
- Button("Delete", onClick: () => remove(t.id), variant: "ghost")
614
+ Button("Delete", { onClick: () => remove(t.id), variant: "ghost" })
467
615
  ])])
468
616
 
469
- list = for t in $todos { row(t) }
470
- _app_ = Stack([
471
- Input("draft-input", placeholder: "What needs doing?", value: $draft),
472
- 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" }),
473
621
  list
474
622
  ])
475
623
  ```
476
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
+
477
695
  ### Per-instance state & content-addressed identity
478
696
 
479
- ```text
480
- component Counter(label) {
697
+ ```js
698
+ function Counter(label) {
481
699
  $n = 0
482
700
  return Stack([
483
701
  Text(`${label}: ${$n}`),
484
- Button("inc", onClick: () => $n = $n + 1)
702
+ Button("inc", { onClick: () => $n = $n + 1 })
485
703
  ])
486
704
  }
487
705
 
488
- # Two independent counters — each holds its own atom.
489
- _app_ = Stack([Counter("A"), Counter("B")])
706
+ // Two independent counters — each holds its own atom.
707
+ aktion = Stack([Counter("A"), Counter("B")])
490
708
  ```
491
709
 
492
- Every call site accepts a universal `key:` named argument. The renderer
710
+ Every call site accepts a universal `key` named argument. The renderer
493
711
  uses it as the instance suffix instead of source location, so reordering
494
712
  siblings keeps per-instance state attached to the right element:
495
713
 
496
- ```text
497
- component TaskRow(task) {
498
- return Stack([Text(task.title)], key: task.id)
714
+ ```js
715
+ function TaskRow(task) {
716
+ return Stack([Text(task.title)], { key: task.id })
499
717
  }
500
718
  ```
501
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
+
502
803
  ### Component-scoped effects
503
804
 
504
- `effect [ ...deps ] { … }` blocks can live at the program top level
505
- **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
506
807
  runtime mounts the effect when the instance first renders and tears it
507
808
  down (clearing timers, unsubscribing watched atoms, firing every
508
809
  registered `cleanup(fn)`) the moment the instance disappears from the
509
810
  tree. Two `LiveClock()` calls produce two independent intervals — and
510
811
  removing one stops only that one:
511
812
 
512
- ```text
513
- _app_ = Stack([LiveClock("UTC"), LiveClock("Local")])
514
-
515
- component LiveClock(label) {
516
- $now = @Now()
517
- effect [on:every(1000)] {
518
- $now = @Now()
519
- }
520
- 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"))])
521
822
  }
522
823
  ```
523
824
 
524
- Use a top-level `effect [...] { … }` for global work (analytics,
825
+ Use a top-level `$effect(() => { … }, [...])` for global work (analytics,
525
826
  app-wide keyboard shortcuts, hydration of shared atoms); use a
526
827
  component-local effect whenever the background work logically belongs
527
828
  to the UI it serves.
@@ -532,10 +833,10 @@ to the UI it serves.
532
833
  [`src/library/index.js`](./src/library/index.ts)) emits **hard errors**
533
834
  for:
534
835
 
535
- - Closed-token enum mismatches (`Button("Save", variant: "magic")`).
536
- - Unknown named args (`Stack(junk: 1)`).
836
+ - Closed-token enum mismatches (`Button("Save", { variant: "magic" })`).
837
+ - Unknown named args (`Stack({ junk: 1 })`).
537
838
  - One-positional-max violations (`Button("Save", "primary", true)` →
538
- "use `variant: "primary"`, `loading: true`").
839
+ "use `{ variant: "primary", loading: true }`").
539
840
 
540
841
  The host element merges these into `program.errors` so the on-screen
541
842
  banner surfaces every violation.
@@ -555,7 +856,7 @@ deep authoring guide [`coding-gen-skill.md`](./coding-gen-skill.md).
555
856
 
556
857
  ## Component library
557
858
 
558
- 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**
559
860
  (`Hero`, `PageHeader`, `Stats`, `Toolbar`, `EmptyState`, `Timeline`,
560
861
  `KanbanBoard`, `DescriptionList`, `PricingTable`, …) before hand-rolling
561
862
  the equivalent with `Card` + `Stack` — they're tuned to produce dense,
@@ -563,8 +864,8 @@ production-quality SaaS UI in a single line.
563
864
 
564
865
  | Group | Components |
565
866
  | ------------------ | ---------- |
566
- | **Layout** | `Stack`, `StackItem`, `Grid`, `GridItem`, `Container`, `Box`, `Spacer`, `Card`, `CardHeader`, `CardFooter`, `Separator`, `Tabs`, `TabItem`, `Accordion`, `AccordionItem`, `Modal`, `Drawer`, `Steps`, `AspectRatio`, `ScrollArea`, `Sticky`, `ResizablePanels`, `MasonryGrid` |
567
- | **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` |
568
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` |
569
870
  | **Data** | `Table`, `Col`, `DataGrid`, `List`, `ListItem`, `StatCard`, `Stats`, `Sparkline`, `Tile`, `Progress`, `ProgressRing`, `Pagination`, `Tree`, `TreeNode`, `CalendarView`, `ComparisonTable`, `InfiniteList` |
570
871
  | **Charts** | `BarChart`, `LineChart`, `PieChart`, `RadarChart`, `ScatterChart`, `Histogram`, `Heatmap`, `Gauge`, `Series` |
@@ -574,11 +875,56 @@ production-quality SaaS UI in a single line.
574
875
  | **Editors** | `RichTextEditor`, `CodeEditor` |
575
876
  | **Chat** | `SectionBlock`, `ListBlock`, `FollowUpBlock`, `FollowUpItem`, `ActionLink`, `ChatBubble` |
576
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` |
577
- | **App shell** | `AppShell`, `Sidebar`, `SidebarSection`, `SidebarItem`, `SplitView` |
878
+ | **App shell** | `AppShell`, `Sidebar`, `SidebarSection`, `SidebarItem` (supports `to` for router navigation), `SplitView` |
578
879
  | **Advanced UI** | `IconButton`, `CommandPalette`, `FilterChips`, `FieldRepeater`, `VirtualList`, `QueryBuilder`, `DiffViewer`, `JsonTree`, `Gantt`, `Truncate`, `InlineEdit`, `NotificationBell` |
579
880
  | **Helpers** | `Async`, `Show`, `Portal`, `Redirect`, `Lazy`, `ErrorBoundary` |
580
- | **Theming** | `Theme` |
581
- | **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`).
582
928
 
583
929
  The full catalog with positional signatures, prop tables, enum values, and
584
930
  live previews is at
@@ -586,27 +932,27 @@ live previews is at
586
932
 
587
933
  ### Rich pattern composites
588
934
 
589
- ```text
590
- action export_q3() { $exp = http({ url: "/exports/q3", method: "POST" }) }
591
- 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") }
592
938
 
593
- dashHeader = PageHeader("Engineering Q3", subtitle: "12 active · 4 at risk", breadcrumbs: ["Workspace", "Engineering"], actions: dashActions, status: Badge("On track", "success"))
594
- 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" })]
595
941
  kpis = Stats([
596
- StatCard("Active", value: "12", trend: "flat"),
597
- StatCard("At risk", value: "4", trend: "up", delta: "+2"),
598
- StatCard("Shipped", value: "8", trend: "up", delta: "+3"),
599
- 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%" })
600
946
  ])
601
947
  board = KanbanBoard([
602
- KanbanColumn("To do", items: [KanbanCard("Migrate auth", description: "Roll out new SDK.", tags: ["auth"], assignee: "Asha")]),
603
- KanbanColumn("Doing", items: [KanbanCard("Streaming UI v2", description: "20 new components.", tags: ["frontend"], assignee: "Alex", tone: "primary")]),
604
- KanbanColumn("Review", items: [KanbanCard("Mobile onboarding", description: "Awaiting design.", tags: ["mobile"], assignee: "Wren", tone: "warning")]),
605
- 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" })] })
606
952
  ])
607
953
  follow = FollowUpBlock(["Show at-risk projects", "Compare to Q2", "Who needs help?"])
608
954
 
609
- _app_ = Stack([dashHeader, kpis, board, follow])
955
+ aktion = Column([dashHeader, kpis, board, follow])
610
956
  ```
611
957
 
612
958
  ### Adding your own components
@@ -676,14 +1022,14 @@ el.setTheme({
676
1022
  });
677
1023
  ```
678
1024
 
679
- ### `Theme({...})` from inside a response
1025
+ ### `$theme({...})` from inside a response
680
1026
 
681
- A response can brand itself by assigning a `Theme({...})` call to the
682
- reserved `theme` binding. The tokens land on the host as CSS variables on
683
- 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.
684
1030
 
685
- ```text
686
- theme = Theme({
1031
+ ```js
1032
+ theme = $theme({
687
1033
  colors: {
688
1034
  primary: "#0969da",
689
1035
  border: "#d0d7de",
@@ -697,12 +1043,12 @@ theme = Theme({
697
1043
  radius: { button: "6px", input: "6px" }
698
1044
  })
699
1045
 
700
- _app_ = Stack([CardHeader("GitHub-style page"), Buttons([Button("New repository")])])
1046
+ aktion = Column([CardHeader("GitHub-style page"), Buttons([Button("New repository")])])
701
1047
  ```
702
1048
 
703
- `Theme` expects the **structured** form — top-level groups `colors` /
1049
+ `$theme` expects the **structured** form — top-level groups `colors` /
704
1050
  `radius` / `font` / `motion` / `elevation` (plus metadata keys `name`
705
- and `direction`). Removing the `Theme(...)` line snaps the UI back to
1051
+ and `direction`). Removing the `$theme(...)` line snaps the UI back to
706
1052
  the base theme. Unknown keys are ignored silently, so typos in an
707
1053
  LLM-emitted token map can never break the page.
708
1054
 
@@ -737,8 +1083,8 @@ shadow root. Host apps do **not** need to add a stylesheet.
737
1083
  `"circle-check"`, `"triangle-exclamation"`, `"sack-dollar"`.
738
1084
  - Optional variant prefix: `"regular:star"`, `"brands:github"`. The
739
1085
  default variant is `solid`.
740
- - Use the dedicated `Icon(name, variant?, size?)` component to render a
741
- 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`).
742
1088
  - Every component prop named `icon` — `NavLink`, `SidebarItem`, `Banner`,
743
1089
  `Notification`, `FeatureItem`, `Badge`, `StatCard`, `ListItem`,
744
1090
  `TimelineItem`, `DescriptionItem`, `Tile`, `EmptyState`, … — expects a
@@ -747,16 +1093,16 @@ shadow root. Host apps do **not** need to add a stylesheet.
747
1093
  stripped silently so legacy emoji leftovers still resolve to the
748
1094
  proper icon.
749
1095
 
750
- ```text
751
- brandIcon = Icon("rocket", "solid", "lg")
1096
+ ```js
1097
+ brandIcon = Icon("rocket", { variant: "solid", size: "lg" })
752
1098
  homeIcon = Icon("house")
753
- profileTab = NavLink("Profile", to: "/profile", variant: "ghost", icon: "user")
1099
+ profileTab = NavLink("Profile", { to: "/profile", variant: "ghost", icon: "user" })
754
1100
  kpis = Stats([
755
- StatCard("Revenue", value: "$48k", trend: "up", delta: "+12%", icon: "sack-dollar"),
756
- StatCard("Orders", value: "1,284", trend: "up", delta: "+8%", icon: "cart-shopping"),
757
- 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" })
758
1104
  ])
759
- _app_ = Stack([brandIcon, kpis, profileTab])
1105
+ aktion = Stack([brandIcon, kpis, profileTab])
760
1106
  ```
761
1107
 
762
1108
  ---
@@ -768,39 +1114,39 @@ stay in sync with the URL (`#/dashboard`, `#/users/42`). Browser
768
1114
  back/forward, bookmarks, and deep links all work — and the host page
769
1115
  never reloads.
770
1116
 
771
- ```text
772
- pages = _router_({
1117
+ ```js
1118
+ pages = $router({
773
1119
  "/": homePage,
774
1120
  "/dashboard": dashboardPage,
775
- "/users/:id": userPage(id: params.id),
1121
+ "/users/:id": userPage({ id: params.id }),
776
1122
  default: notFoundPage
777
1123
  })
778
1124
 
779
- nav = Stack([
780
- NavLink("Home", to: "/", exact: true),
781
- NavLink("Dashboard", to: "/dashboard"),
782
- NavLink("Users", to: "/users")
783
- ], 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" })
784
1130
 
785
- _app_ = Stack([nav, pages])
1131
+ aktion = Stack([nav, pages])
786
1132
 
787
1133
  homePage = Card([CardHeader("Welcome")])
788
1134
  dashboardPage = Card([CardHeader("Dashboard")])
789
1135
  userPage = (id) => Card([CardHeader(`User ${id}`)])
790
- 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" })
791
1137
  ```
792
1138
 
793
- - `pages = _router_({ "/path": Component(), default: Fallback() })` picks
1139
+ - `pages = $router({ "/path": Component(), default: Fallback() })` picks
794
1140
  the matching arm based on the current hash path. First match wins;
795
1141
  `default:` is the fallback.
796
1142
  - Route patterns support literal segments (`"/about"`), parameter
797
1143
  segments (`"/users/:id"` → `params.id`), and trailing wildcards
798
1144
  (`"/docs/*"` → `params._`).
799
- - `NavLink(label, to:, variant?, exact?, icon?)` is a router-aware anchor
800
- 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
801
1147
  current path.
802
- - The reactive `_route_` handle exposes `_route_.path`, `_route_.params`,
803
- `_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")`
804
1150
  from inside the script, or `el.navigate("/path")` from the host.
805
1151
 
806
1152
  The default ("full") system prompt teaches the LLM about routing. The
@@ -810,88 +1156,27 @@ for the full walkthrough.
810
1156
 
811
1157
  ---
812
1158
 
813
- ## JavaScript escape hatch
814
-
815
- `js{ … }` blocks live inside `effect` or `action` bodies — no host
816
- attribute, no allow-list. Reach for them only when no declarative path
817
- captures the behaviour (timers, clipboard, audio, complex computations,
818
- host-tool calls).
819
-
820
- ```text
821
- $todos = []
822
-
823
- action toggle(id) {
824
- js {
825
- const todos = ctx.state.get("todos") || []
826
- ctx.state.set("todos", todos.map(t => t.id === ctx.args.id ? { ...t, done: !t.done } : t))
827
- }
828
- }
829
-
830
- row = (t) => Card([Stack([
831
- Text(t.text),
832
- Button("Toggle", onClick: () => toggle(t.id))
833
- ])])
834
-
835
- list = for t in $todos { row(t) }
836
- _app_ = Stack([list])
837
- ```
838
-
839
- Inside the `js{ … }` block:
840
-
841
- - `ctx.state.get(name)` / `ctx.state.set(name, value)` read and write
842
- reactive atoms.
843
- - `ctx.args` exposes the action's positional parameters keyed by name.
844
- - `ctx.cleanup(fn)` (effects only) registers a teardown to fire on
845
- re-run and unmount.
846
- - `ctx.host` is the host element, for DOM-observing effects.
847
- - `ctx.tools` is a host-registered async tool registry (see `el.setTools(...)`).
848
-
849
- The body runs inside `(async () => { … })()` so `await` is free. Errors
850
- are caught and logged — a broken body never crashes the host page.
851
-
852
- For long-lived behaviour, prefer an `effect`:
853
-
854
- ```text
855
- effect [$draft, debounce(500)] {
856
- js {
857
- await fetch("/save", { method: "POST", body: JSON.stringify({ draft: ctx.state.get("draft") }) })
858
- }
859
- }
860
- ```
861
-
862
- The default (full) system prompt teaches `effect` / `action` / `js{}`;
863
- the chat-flavoured prompt (`getSystemPrompt({ mode: "chat" })`) omits
864
- the JS section entirely.
865
-
866
- See the
867
- [JavaScript interactions guide](https://asfand-dev.github.io/aktion/javascript-interactions.html)
868
- or the deep
869
- [`coding-gen-skill.md`](./coding-gen-skill.md)
870
- for a full walkthrough.
871
-
872
- ---
873
-
874
1159
  ## Built-in globals
875
1160
 
876
- Two namespace globals are always in scope inside a Aktion
877
- program — no import, no `js{}` block required. Both follow the standard
878
- `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.
879
1164
 
880
- ```text
881
- # localStorage is the default; `storage.local` is its alias.
882
- storage.set("name", "John")
883
- $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")
884
1169
 
885
- # Per-tab sessionStorage.
886
- storage.session.set("draft", $draft)
887
- $draft = storage.session.get("draft")
1170
+ // Per-tab sessionStorage.
1171
+ $storage.session.set("draft", $draft)
1172
+ $draft = $storage.session.get("draft")
888
1173
 
889
- # Cookies — named-arg options become a single options object.
890
- storage.cookies.set("user", "John", expires: 7, path: "/", sameSite: "Lax")
891
- $user = storage.cookies.get("user")
892
- 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: "/" })
893
1178
 
894
- # Forwards to the host console.
1179
+ // Forwards to the host console.
895
1180
  console.log("Hello", $user)
896
1181
  console.error("Something failed", $error)
897
1182
  ```
@@ -912,28 +1197,45 @@ for the full surface.
912
1197
 
913
1198
  ## Internationalization
914
1199
 
915
- The `$i18n = i18n({...})` declaration configures the active locale,
916
- message bundles, and fallback. A global `t(key, vars?)` builtin and a
917
- `Locale()` helper feed the active locale into `@Format` / `@FormatDate`.
918
-
919
- ```text
920
- $i18n = i18n({
921
- locale: "fr-FR",
922
- fallback: "en",
923
- messages: {
924
- greeting: "Bonjour, ${name}!",
925
- 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" }
926
1212
  }
927
1213
  })
928
1214
 
929
- welcome = Text(t("greeting", { name: $user.name }))
930
- sectionTitle = SectionHeader(t("orders.title"))
931
- 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 }))
932
1218
  ```
933
1219
 
934
- Keys support dot paths. Variables are interpolated using `${name}`
935
- placeholders. Missing keys fall back to the fallback locale's bundle,
936
- 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
+ ```
937
1239
 
938
1240
  ---
939
1241
 
@@ -988,8 +1290,8 @@ import {
988
1290
  ```
989
1291
 
990
1292
  - `formatProgram` projects the parsed AST back to canonical source —
991
- `prop: value` named args, double-quoted strings, two-space block
992
- indentation, `bind:` preserved, template literals intact.
1293
+ object-literal named args, double-quoted strings, two-space block
1294
+ indentation, template literals intact.
993
1295
  - `inspectAST(source)` returns a JSON-friendly view of the Committed +
994
1296
  Drafting ASTs at the current byte position — bindings (with
995
1297
  kind / line / column / summary), in-flight names, and any parse errors.
@@ -1016,14 +1318,16 @@ consumes from the CDN.
1016
1318
  | `get-started.html` | Step-by-step integration walkthrough. |
1017
1319
  | `frameworks.html` | Integration recipes for React, Next.js, Vue, Angular, Svelte, plain HTML. |
1018
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. |
1019
1322
  | `components.html` | Every built-in component with a live preview, positional signatures, prop tables, and enum values. |
1020
- | `actions.html` | `action Name() { … }` guide — declarative state mutations, optimistic snapshot/rollback, lambda-based click handlers, navigation, and end-to-end examples. |
1021
- | `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. |
1022
- | `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. |
1023
1326
  | `routing.html` | Hash-based routing guide — always available at runtime. |
1024
1327
  | `themes.html` | Built-in themes gallery, live picker, side-by-side compare, and the token customization studio. |
1025
1328
  | `examples.html` | Curated showcase of real-world block UIs (auth, products, FAQ, cart, todos, …). |
1026
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. |
1027
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. |
1028
1332
  | `live-examples.html` | Catalog page that links every demo into the shared `live-example.html?example=<slug>` shell. |
1029
1333
  | `live-example.html` | Shared shell for the bundled live examples — picks the demo from the `?example=<slug>` query parameter. |
@@ -1034,20 +1338,19 @@ consumes from the CDN.
1034
1338
 
1035
1339
  Every standalone demo is served by a single shell page
1036
1340
  (`docs/live-example.html`) and a single JS bundle
1037
- (`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
1038
1342
  and setup code together. Open any example with
1039
1343
  `live-example.html?example=<slug>` — the shell renders the original
1040
1344
  hero / source / output layout, so each demo doubles as an integration
1041
- recipe for `setResponse`, `appendChunk`, `setTools`, and `setTheme`.
1345
+ recipe for `setResponse`, `appendChunk`, and `setTheme`.
1042
1346
 
1043
1347
  | Demo slug | Highlights |
1044
1348
  | ------------------------------- | ----------------------------------------------------------------------------------------------------------- |
1045
- | `routing-demo` | A four-page app driven by `pages = _router_({ … })` + `NavLink`, deep links, browser back/forward. |
1046
1349
  | `settings-app` | Tabs, `Switch`, `ToggleGroup`, `Progress`, `Kbd`, danger-zone confirmation `Drawer`. |
1047
1350
  | `data-explorer` | Analytics surface: sortable `DataGrid` + bulk toolbar, `Gauge` SLA dials, `LineChart`, `Heatmap`, `RadarChart`, `ScatterChart`, `Histogram`, `InfiniteList`, `ActivityLog`. |
1048
1351
  | `media-gallery` | Travel magazine: `Carousel` hero, `Gallery` + click-to-zoom `Lightbox`, `VideoPlayer`, `AudioPlayer`, Leaflet-backed `Map`. |
1049
1352
  | `content-studio` | CMS-style authoring surface: `RichTextEditor`, `CodeEditor`, `MultiStepForm`, `ColorPicker`, `TagInput`, `MentionInput`, `PinInput`, `ValidationSummary`, `TopBar`. |
1050
- | `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). |
1051
1354
 
1052
1355
  The full catalog with tag filters lives at
1053
1356
  [`docs/live-examples.html`](https://asfand-dev.github.io/aktion/live-examples.html).
@@ -1064,12 +1367,12 @@ The full catalog with tag filters lives at
1064
1367
  │ │ ├── builtins.ts # pure @-function helpers
1065
1368
  │ │ ├── evaluator.ts # program planner + binding resolver
1066
1369
  │ │ ├── state.ts # reactive store — `$name = value`
1067
- │ │ ├── effects.ts # EffectRunner + ActionDeclRunner + js{} executor
1068
- │ │ ├── http.ts # http({...}) reactive HTTP primitive + interceptors
1069
- │ │ ├── i18n.ts # $i18n runtime + t() / Locale() builtins
1070
- │ │ ├── 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
1071
1374
  │ │ ├── console.ts # console.* host bridge
1072
- │ │ └── router.ts # Hash-based router for _router_({…}) calls and NavLink
1375
+ │ │ └── router.ts # Hash-based router for $router({…}) calls and NavLink
1073
1376
  │ ├── library/ # Component specs and registry
1074
1377
  │ │ └── components/ # layout / content / forms / data / charts / chat /
1075
1378
  │ │ # feedback / navigation / menu / patterns / helpers / router
@@ -1156,23 +1459,14 @@ script.
1156
1459
  npm test
1157
1460
  ```
1158
1461
 
1159
- The suite covers:
1160
-
1161
- - Parser / lexer correctness (`tests/parser.test.ts`).
1162
- - Runtime evaluator + reactive state + `http({...})` (`tests/runtime.test.ts`).
1163
- - `effect` / `action` declarations + `js{}` execution (`tests/javascript-integration.test.ts`).
1164
- - Hash-based router + `NavLink` (`tests/router.test.ts`).
1165
- - Theme resolution and token application (`tests/theme.test.ts`).
1166
- - In-script `Theme(...)` overrides (`tests/in-script-theme.test.ts`).
1167
- - Component library smoke tests (`tests/library.test.ts`).
1168
- - Element-level integration via happy-dom (`tests/element.test.ts`).
1169
- - System prompt generator output (`tests/prompt.test.ts`).
1170
- - Storage + console globals (`tests/storage-console.test.ts`).
1171
- - End-to-end programs (`tests/suis2-end-to-end.test.ts`).
1172
- - Language support spec for editor / tooling integrations (`tests/language.test.ts`).
1173
- - One-positional-max enforcement (`tests/suis2-one-positional.test.ts`).
1174
- - Component prop aliases (`tests/suis2-prop-aliases.test.ts`).
1175
- - 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).
1176
1470
 
1177
1471
  ### Build the documentation site
1178
1472
 
@@ -1197,7 +1491,7 @@ Then open <http://localhost:4321/index.html>.
1197
1491
 
1198
1492
  The library treats every LLM-supplied attribute as untrusted and runs
1199
1493
  it through a small set of sanitisers before it lands on the DOM. HTTP
1200
- 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
1201
1495
  `registerHttpInterceptors({ onRequest, onResponse, onError })` chain so
1202
1496
  auth headers, CORS workarounds, and refresh-token retries stay under
1203
1497
  host control.
@@ -1215,37 +1509,21 @@ renderer get `rel="noopener noreferrer"` so the destination cannot
1215
1509
  read the opener's `document.referrer`.
1216
1510
 
1217
1511
  If you embed `<aktion-app>` behind a CSP, the bundle does not
1218
- use `eval`. `js{}` bodies inside `effect` / `action` declarations are
1219
- evaluated with `new Function(...)` which requires `'unsafe-eval'` if
1220
- you want them to work; if you cannot relax CSP, simply avoid emitting
1221
- `js{}` blocks from the LLM — every other part of the runtime keeps
1222
- 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`.
1223
1517
 
1224
1518
  ---
1225
1519
 
1226
1520
  ## CDN deployment
1227
1521
 
1228
- This repository ships its own copy of the bundle on GitHub Pages, so
1229
- most users do not need to host anything themselves:
1230
-
1231
- ```html
1232
- <script type="module" src="https://asfand-dev.github.io/aktion/dist/aktion.js"></script>
1233
- <aktion-app theme="dark"></aktion-app>
1234
- ```
1235
-
1236
- …plus a fetch of `system_prompt.txt` server-side to build LLM messages:
1237
-
1238
- ```bash
1239
- curl https://asfand-dev.github.io/aktion/dist/system_prompt.txt
1240
- ```
1241
-
1242
- To ship your own copy, run `npm run build` and serve the `dist/` folder
1243
- from any static host — every artifact in `dist/` is self-contained.
1244
-
1245
- GitHub Pages deployment for this repo is automated via
1246
- [`.github/workflows/deploy-pages.yml`](.github/workflows/deploy-pages.yml).
1247
- Push to `main` and the workflow will build, test, assemble `site/`, and
1248
- 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.
1249
1527
 
1250
1528
  ---
1251
1529