@zvndev/darkmown 0.13.0 → 0.14.0
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.
- package/AGENTS.md +15 -4
- package/CHANGELOG.md +9 -0
- package/README.md +10 -8
- package/docs/spec-alignment.md +7 -3
- package/package.json +1 -1
- package/site/pages/docs/index.wd +7 -6
- package/site/pages/reactive.wd +10 -0
- package/src/compiler.js +72 -42
- package/src/runtime.js +42 -17
- package/src/scaffold.js +10 -1
package/AGENTS.md
CHANGED
|
@@ -20,6 +20,7 @@ package.json
|
|
|
20
20
|
- **Folders are routes.** `site/pages/blog/post.wd` serves at `/blog/post/`.
|
|
21
21
|
- Files/folders starting with `.`, `-`, or `_` are **hidden** from routing (drafts, partials).
|
|
22
22
|
- A `page.skin` next to `page.wd` attaches styling; a `page.js` attaches behavior. Matched by basename.
|
|
23
|
+
- **Colocated assets:** any other file under `site/pages/` (not a `.md`/`.wd` route, not a basename-matched `.skin`/`.js`) copies to `dist/` at its own path with the right content-type — so `site/pages/logo.svg` is served at `/logo.svg`. Use the `site/_/` shelf for assets shared across pages; colocate the ones a single page owns.
|
|
23
24
|
|
|
24
25
|
Commands: `darkmown dev`, `darkmown build`, `darkmown serve`.
|
|
25
26
|
|
|
@@ -57,15 +58,25 @@ Button actions are a **fixed whitelist**: `x++`, `x--`, `x += <number>`, `list +
|
|
|
57
58
|
|
|
58
59
|
### Conditionals
|
|
59
60
|
```wd
|
|
60
|
-
:if
|
|
61
|
+
:if plan == "pro" or seats >= 5
|
|
61
62
|
Pro plan.
|
|
62
|
-
:else if
|
|
63
|
+
:else if trialDays > 0 and not expired
|
|
63
64
|
Trial.
|
|
64
65
|
:else
|
|
65
66
|
Free plan.
|
|
66
67
|
:endif
|
|
67
68
|
```
|
|
68
|
-
`:if
|
|
69
|
+
`:if <predicate>` branches on a compile-time-validated predicate — a bare path (truthy), comparisons (`==` `!=` `<` `<=` `>` `>=` `contains`), joined with `and`/`or`/`not`. Operands are item paths, declared `:state`/`:store`, numbers, or `"strings"` — no expressions. (Same grammar as `.class when`; `@loop … where` is the comparison-only subset — operators with `and`/`or`.) Chain with `:else if` (any number; a bare `:else` must be last). Conditionals nest, including per-row inside a loop.
|
|
70
|
+
|
|
71
|
+
### Reactive classes — `.class when <predicate>`
|
|
72
|
+
```wd
|
|
73
|
+
@loop tasks into task
|
|
74
|
+
::: card .task .done when task.done .urgent when task.priority > 3 ← toggles each class by predicate
|
|
75
|
+
**{ task.title }**
|
|
76
|
+
:::
|
|
77
|
+
@endloop
|
|
78
|
+
```
|
|
79
|
+
`.class when <predicate>` on a `:::` container toggles that class from the same predicate grammar as `:if`. A predicate over only static values folds to a plain class at build time; one reading `:state` or the loop item stays reactive.
|
|
69
80
|
|
|
70
81
|
### Loops — the only loop
|
|
71
82
|
```wd
|
|
@@ -151,7 +162,7 @@ Your `.skin` selectors must match the **real** output. The emitted HTML is:
|
|
|
151
162
|
| reactive `@loop` of a list | `<ul>`/`<ol>` (or `<div>`) of items |
|
|
152
163
|
| `{ name }` | a text node |
|
|
153
164
|
|
|
154
|
-
So style with real selectors: `section`, `.card`, `button`, `input`, `form`, `h1`. **To add a class to a container, use `::: name .class`. For any other custom element, write raw HTML `<div class="…">`. There is NO `{.class}` attribute syntax.** A container class can also be reactive: `::: card .on-sale when p.price < 50` toggles the class from a predicate (same
|
|
165
|
+
So style with real selectors: `section`, `.card`, `button`, `input`, `form`, `h1`. **To add a class to a container, use `::: name .class`. For any other custom element, write raw HTML `<div class="…">`. There is NO `{.class}` attribute syntax.** A container class can also be reactive: `::: card .on-sale when p.price < 50` toggles the class from a predicate (same grammar as `:if`).
|
|
155
166
|
|
|
156
167
|
## Styling with `.skin` — ship this on every page
|
|
157
168
|
|
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to Darkmown are documented here. Versions follow [semver](https://semver.org); pre-1.0 minor versions may contain breaking changes.
|
|
4
4
|
|
|
5
|
+
## 0.14.0 — 2026-06-18
|
|
6
|
+
|
|
7
|
+
Richer conditionals — `:if` / `:else if` now read the full predicate grammar instead of a bare truthy path only. The reactive runtime is ~5.7 KB gzipped (5762 B), still under the 6 KB CI budget and shipped un-minified.
|
|
8
|
+
|
|
9
|
+
- **Conditionals — comparison & logical expressions.** A `:if` / `:else if` condition now accepts the same compile-time-validated grammar as `.class when`: a bare path (truthy) **or** the comparisons `==` `!=` `<` `<=` `>` `>=` `contains`, joined with `and`, `or`, and negated with `not`. Operands are loop-item paths, declared `:state`/`:store`, numbers, `"strings"`, or `true`/`false`/`null`. `:if plan == "pro" or seats >= 5` and `:else if trialDays > 0 and not expired` are now valid where only `:if plan` worked before. A bare path keeps the original zero-overhead fast path.
|
|
10
|
+
- **Same reactivity rules, same security.** A condition over only static values still folds the branch at build time (`runtime: false` preserved); one over `:state` emits a reactive region (`data-wd-if` + `data-wd-if-expr`); one over a loop item evaluates per row (`data-wd-each-if`). The expression compiles to the same whitelisted form over `I()`/`S()`/`C()` and runs via the shared `evalPredicate` runtime helper — no new eval surface, and `constructor`/`prototype`/`__proto__` path segments stay rejected in compiler and runtime. `:else if` chains inherit this automatically.
|
|
11
|
+
- **No grouping (caveat).** There is no parenthesis grouping; `and`/`or` associate left-to-right with no precedence between them. Split into `:else if` branches or a `:computed` boolean when grouping matters. `@loop … where` stays the comparison-only subset of this grammar (no `not`, no bare-truthy form).
|
|
12
|
+
- **Fix — nested global conditionals re-evaluate after an outer flip.** When a page-level (non-loop) `:if` flips to its falsy branch, the runtime now recurses into the freshly injected branch and evaluates any nested conditional (the desugared `:else if` tail) in the same pass. Previously the injected nested region kept its build-time branch until the next unrelated render. This also corrects bare-path nested `:else if` chains over page state, not just the new comparison form.
|
|
13
|
+
|
|
5
14
|
## 0.13.0 — 2026-06-18
|
|
6
15
|
|
|
7
16
|
Layered capabilities — four reactive features shaped as progressive disclosure: a simple default, with more power one layer down. The reactive runtime grew to ~5.7 KB gzipped; the CI budget moves from 5 KB to **6 KB** (still shipped un-minified, source fully commented).
|
package/README.md
CHANGED
|
@@ -259,7 +259,7 @@ A container class can be toggled by a predicate. Static `.class` tokens are unch
|
|
|
259
259
|
@endloop
|
|
260
260
|
```
|
|
261
261
|
|
|
262
|
-
The predicate uses the same whitelist as
|
|
262
|
+
The predicate uses the same whitelist as `:if` — item fields, declared `:state`/`:store`, numbers, strings, the `==`/`!=`/`>`/`<`/`>=`/`<=`/`contains` operators, and `and`/`or`/`not`. A bare path (`.featured when p.featured`) reads as truthy. (`@loop … where` is the comparison-only subset of this grammar.) A predicate over only static values folds at build time into a plain class; one that reads state or the loop item stays reactive and ships with the runtime.
|
|
263
263
|
|
|
264
264
|
## Reactive directives
|
|
265
265
|
|
|
@@ -270,26 +270,28 @@ Count: { count }
|
|
|
270
270
|
|
|
271
271
|
:button "Increment" -> count++
|
|
272
272
|
|
|
273
|
-
:if count
|
|
273
|
+
:if count >= 10
|
|
274
|
+
Count is high.
|
|
275
|
+
:else if count > 0
|
|
274
276
|
Count has changed.
|
|
275
277
|
:else
|
|
276
278
|
Count is still zero.
|
|
277
279
|
:endif
|
|
278
280
|
```
|
|
279
281
|
|
|
280
|
-
|
|
282
|
+
A condition reads the same predicate grammar as `.class when`: a bare path (truthy), or the comparisons `==` `!=` `<` `<=` `>` `>=` `contains`, joined with `and`, `or`, and `not`. (`@loop … where` is the comparison-only subset — operators with `and`/`or`.) Chain with `:else if` (any number; an optional bare `:else` must be the last branch):
|
|
281
283
|
|
|
282
284
|
```wd
|
|
283
|
-
:if
|
|
285
|
+
:if plan == "pro" or seats >= 5
|
|
284
286
|
Pro plan
|
|
285
|
-
:else if
|
|
286
|
-
Trial — {
|
|
287
|
+
:else if trialDays > 0 and not expired
|
|
288
|
+
Trial — { trialDays } days left
|
|
287
289
|
:else
|
|
288
290
|
Free plan
|
|
289
291
|
:endif
|
|
290
292
|
```
|
|
291
293
|
|
|
292
|
-
A whole chain compiles to nested conditional regions, so it stays reactive (or folds at build time when
|
|
294
|
+
A whole chain compiles to nested conditional regions, so it stays reactive (or folds at build time when every value is static) exactly like a single `:if`.
|
|
293
295
|
|
|
294
296
|
Directive actions are intentionally narrow and compile-time checked. Arbitrary JavaScript belongs in colocated `.js` files.
|
|
295
297
|
|
|
@@ -350,7 +352,7 @@ Effects run after a render, against settled state, and an effect that mutates st
|
|
|
350
352
|
`:fetch name from "url"` declares state and fills it from JSON over the network:
|
|
351
353
|
|
|
352
354
|
```
|
|
353
|
-
:fetch <name> from "<url>" [method=GET] [when=load|visible] [timeout=<ms>] [retry=<N>] [headers=<key>] [body=<key>]
|
|
355
|
+
:fetch <name> from "<url>" [method=GET] [when=load|visible] [timeout=<ms>] [retry=<N>] [headers=<key>] [body=<key>] [refresh=<url>]
|
|
354
356
|
```
|
|
355
357
|
|
|
356
358
|
Each fetch automatically declares four state keys you can branch on:
|
package/docs/spec-alignment.md
CHANGED
|
@@ -51,7 +51,7 @@ This audit compares the current Darkmown implementation with the original MARROW
|
|
|
51
51
|
- **Nested `:if` over loop items (v0.5.0):** conditionals nest inside reactive `@loop`, per row. Both fill paths fixed — build-time balanced `matchElement` recursion and runtime `fillItem` recursion.
|
|
52
52
|
- **State-driven list filtering — `@loop … where <predicate>`:** the #1 need surfaced by the agent-eval benchmark. Conditions (`field <op> value`, plus `contains`) join with `and` / `or` over a compile-time-validated whitelist — item paths, declared `:state`, numbers, strings; `constructor`/`prototype`/`__proto__` rejected. Raw user content is never evaluated; the validated predicate compiles to the whitelisted grammar and runs via `new Function` at runtime. The source decides reactivity, matching the loop itself: an item-only predicate filters at build time and stays zero-JS; a predicate that reads `:state` compiles to a reactive filtered loop (rows baked in for static sources). This replaces the fragile DOM-toggle escape hatch with the keyed reconciler.
|
|
53
53
|
- **`:bind <state>`:** two-way `<input>` bound to a `:state` value — the input primitive that powers live search. Accepts `type=`, `placeholder=`, `autocomplete=`, `required`, `autofocus`.
|
|
54
|
-
- **Per-row actions in reactive loops:** a `:button` inside `@loop … into item` can act on its own row — `cart += item` appends a copy of the row to another `:state` list (the only way to carry a loop item into another list), and `list remove item` removes the row from the looped `:state` source (both names compile-checked against the enclosing loop). The runtime resolves the clicked row by stamping each reconciled node with its item, so removal is exact even under a `where` filter. This closes the last "store demo" gap noted in the design memory (per-row `:button` couldn't carry row data)
|
|
54
|
+
- **Per-row actions in reactive loops:** a `:button` inside `@loop … into item` can act on its own row — `cart += item` appends a copy of the row to another `:state` list (the only way to carry a loop item into another list), and `list remove item` removes the row from the looped `:state` source (both names compile-checked against the enclosing loop). The runtime resolves the clicked row by stamping each reconciled node with its item, so removal is exact even under a `where` filter. This closes the last "store demo" gap noted in the design memory (per-row `:button` couldn't carry row data). (The `:if` string-equality gap noted here was fully closed in v0.14.0 — see Stage 10 — when `:if` gained the comparison grammar.)
|
|
55
55
|
- **`.skin` robustness:** `@media`/`@supports` at-rules wrap nested rules; the `font` shorthand passes through (size-led or containing `/`) while `font <stack>` still aliases to `font-family`; `/* … */` block comments and decorative divider lines are skipped.
|
|
56
56
|
- **Editor tooling:** VS Code extension (`editors/vscode`) ships `.wd` + `.skin` TextMate grammars, snippets, and folding, grammar-tested in CI.
|
|
57
57
|
- **`AGENTS.md`:** a model-facing build guide (shipped in the npm files array), tuned over a 5-round agent-eval benchmark that lifted build quality from 2.78→4.51/5.
|
|
@@ -62,18 +62,22 @@ Three capability gaps from the 2026-06-16 audit, closed together over a shared `
|
|
|
62
62
|
|
|
63
63
|
- **Global state — `:store`:** `:store name = value [ephemeral]` declares page-global, durable-by-default state. Non-ephemeral stores persist to `localStorage["wd:store:<name>"]`, hydrate the declared value as a seed only when absent (first write wins thereafter), and sync across tabs via a single `storage` listener that re-renders on change. `ephemeral` opts out of persistence and cross-tab sync (in-memory for the session). Stores are never section-scoped; they share the runtime `state` object with `:state`, and a compile-time collision check keeps the two namespaces disjoint (declaring a `:store` and `:state` with one name, or a store twice, is a path-and-suggestion compile error). Reads (`{ cart }`, `:if`, `@loop`, `:computed`) and all actions resolve stores identically to state.
|
|
64
64
|
- **Full action vocabulary:** `:button … ->` now covers `inc`/`dec` (`n++`, `n--`), `add`/`sub` (`n += k`, `n -= k`), `set` (`name = v`), `toggle` (`flag toggle`), `append` (`list append v` / `list += v`), `prepend`, `member-toggle` (`list toggle v`), `remove-value` (`list remove v`), `clear`, `merge` (`obj merge <key|{…}>`), `delete` (`obj delete "key"`), and `reset` (restore the declared seed) — alongside the existing `append-row` (`cart += item`) and per-row `remove`. Targets are dotted-path aware (`cart.count++`) via a safe `setPath` mirroring `getPath` (proto-pollution guards in compiler and runtime). Buttons may carry a `;`-separated action sequence, applied in order with a single render. Operands are the compile-validated literal grammar (string / number / boolean / null / inline JSON; merge also accepts a bare state/store key). **Honest caveat:** `member-toggle` and `remove-value` compare by value with `===`/`includes`, so they are reliable for primitive members but not for object members (two equal-looking objects are distinct values) — remove row objects with the per-row `remove` action instead.
|
|
65
|
-
- **Fetch lifecycle:** `:fetch name from "url" [method=] [when=load|visible] [timeout=ms] [retry=N] [headers=key] [body=key]
|
|
65
|
+
- **Fetch lifecycle:** `:fetch name from "url" [method=] [when=load|visible] [timeout=ms] [retry=N] [headers=key] [body=key] [refresh=url]` (`headers=`/`refresh=` detailed under Stage 9). Each fetch auto-declares four states — `name` (null), `name_loading` (false), `name_error` (null), `name_empty` (false, true for `null`/`[]`/`{}`) — enabling the recommended loading → error → empty → data pattern (with `@empty` absorbing the empty case for list fetches). URLs may interpolate `{ state }` and auto-refetch (≈150 ms debounce) when a dependency key changes, skipping while a required value is empty. A `refetch` action (`name refetch`) re-triggers a load on demand. Full HTTP via `method`/`headers`/`body`; `timeout` arms an AbortController; `retry` backs off on network error or 5xx before surfacing the error.
|
|
66
66
|
- **Loop ergonomics:** `@loop src into item [where …] [sort by key [asc|desc]] [reverse] [offset N] [limit N]`, clauses in that fixed order. `sort by` keys must start with the loop item (`item.path`); the comparator is numeric when both values are numbers, else `String(...).localeCompare`. `offset`/`limit` accept an integer **or** a `:state`/`:store` key for reactive pagination. Per-row meta vars — `$index` (0-based), `$number` (1-based), `$first`, `$last`, `$count` — are usable in interpolation and `:if`. An `@empty` branch renders when the post-pipeline row count is 0. **Honest caveat:** `sort by` over null/missing keys is best-effort — those values stringify (`"null"`/`"undefined"`) and fall into the lexicographic `localeCompare` path rather than getting special handling. Every clause stays build-time when the source and all arguments are static, preserving `runtime: false`.
|
|
67
67
|
|
|
68
68
|
## Stage 7 additions (2026-06-14)
|
|
69
69
|
|
|
70
70
|
- **Array frontmatter + readable `meta`:** `parseFrontmatter` now parses inline flow arrays (`tags: [a, b, "x, y"]` → real array; quoted items keep internal commas; a value without a leading `[` stays a scalar — block sequences are intentionally out of scope to keep the parser single-pass). A page's frontmatter is exposed to its body under `meta`, so `{ meta.title }` prints a field, `{ meta.tags }` renders an array joined with `, `, and `@loop meta.tags into tag` iterates a frontmatter array at build time (stays `runtime: false`). Genuine correctness fix on its own, and the groundwork for reading/emitting OKF-style bundles (Google Cloud's Open Knowledge Format — markdown + `type`-bearing frontmatter + cross-links; tracked but deliberately not coupled to its v0.1 Draft).
|
|
71
71
|
|
|
72
|
+
## Stage 10 additions (2026-06-18, v0.14.0)
|
|
73
|
+
|
|
74
|
+
- **Richer `:if` / `:else if` conditions:** a conditional now accepts the same compile-time-validated predicate grammar as `.class when` (its sibling through the shared `compileWhen`) — instead of a bare truthy path only. Operands are item paths, declared `:state`/`:store`, numbers, `"strings"`, `true`/`false`/`null`; comparisons `==` `!=` `<` `<=` `>` `>=` and `contains`; joined with `and` / `or` and negated with `not`. A bare path still reads as truthy (the fast path is unchanged). (`@loop … where` stays a comparison-only subset — each condition needs an operator; it has no `not` or bare-truthy form. Unifying it is deferred, not done here.) Reactivity is decided exactly as before: a predicate over only static values folds the branch at build time (`runtime: false` preserved); one over `:state` emits a global `data-wd-if` region carrying `data-wd-if-expr`; one over a loop item emits a per-row `data-wd-each-if` with `data-wd-if-expr`. The expression compiles to the **same** whitelisted grammar over `I()`/`S()`/`C()` and runs via `new Function` through the shared `evalPredicate` runtime helper — no new eval surface, and `constructor`/`prototype`/`__proto__` segments stay rejected in compiler and runtime. `:else if` chains inherit this automatically (each desugared condition re-enters the same path). **Honest caveat:** there is no parenthesis grouping — `and`/`or` associate left-to-right with no precedence between them, so model intent explicitly (split into `:else if` branches or a `:computed` boolean when grouping matters).
|
|
75
|
+
|
|
72
76
|
## Stage 9 additions (2026-06-18, v0.13.0)
|
|
73
77
|
|
|
74
78
|
Four progressive-disclosure capabilities plus an assets and a security change. The reactive runtime grew to ~5.7 KB gzipped; the CI budget moved 5 KB → 6 KB (still un-minified).
|
|
75
79
|
|
|
76
|
-
- **`:else if` chains:** `:if … :else if … :else … :endif`, any number of `:else if`, optional trailing bare `:else` (a `:else if` after the bare `:else` is a compile error). Implemented by **desugaring** the chain tail into a nested `:if` inside the falsy branch, which re-enters the existing compile path — so static, reactive, and per-row (loop) conditionals all behave identically with no runtime change.
|
|
80
|
+
- **`:else if` chains:** `:if … :else if … :else … :endif`, any number of `:else if`, optional trailing bare `:else` (a `:else if` after the bare `:else` is a compile error). Implemented by **desugaring** the chain tail into a nested `:if` inside the falsy branch, which re-enters the existing compile path — so static, reactive, and per-row (loop) conditionals all behave identically with no runtime change. (v0.13.0 accepted only a bare truthy path per condition; Stage 10 / v0.14.0 lifted that to the full predicate grammar.)
|
|
77
81
|
- **Reactive classes — `::: … .class when <predicate>`:** a container class toggled by a predicate using the `@loop … where` / `:if` whitelist (item fields, `:state`/`:store`, numbers, strings, `==`/`!=`/`>`/`<`/`>=`/`<=`/`contains`, `and`/`or`, plus a bare truthy path). A fully-static predicate folds to a plain class at build time (`runtime: false` preserved); a predicate over `:state` emits a global `data-wd-class`; a loop-item predicate emits `data-wd-each-class` evaluated per row. The predicate compiles to the same whitelisted grammar over `I()`/`S()`/`C()` and runs via `new Function`.
|
|
78
82
|
- **Authenticated fetch + token refresh — `:fetch … headers= refresh=`:** `headers=<stateKey>` (existing) spreads a state object into request headers. New `refresh="<url>"`: on HTTP 401 the runtime POSTs the current headers to the refresh URL, writes the returned headers object back into the `headers` state (persisting if it is a `:store`), and retries the original request once; concurrent 401s sharing a refresh URL collapse to a single in-flight refresh. **Honest caveat:** this is bearer-token-style renewal only — no OAuth authorization-code flow, no refresh-token rotation beyond what the endpoint returns; `refresh=` requires `headers=`.
|
|
79
83
|
- **Effects — `:effect <watched> -> <actions>`:** run the `:button` action vocabulary (`;`-chained) whenever a watched state path changes. Emits a zero-output `data-wd-effect` marker; the runtime snapshots each watched value and, after a render against settled state, runs the actions on change, re-rendering and re-checking up to a 10-pass settle cap (a non-settling effect warns and stops). **Honest caveat:** effects do not fire on initial load (only on change), and row-scoped actions (`append-row`/`remove`) have no clicked row in an effect, so they no-op.
|
package/package.json
CHANGED
package/site/pages/docs/index.wd
CHANGED
|
@@ -198,19 +198,19 @@ Directive actions are intentionally narrow and compile-time checked. Arbitrary J
|
|
|
198
198
|
|
|
199
199
|
### Multi-branch conditionals
|
|
200
200
|
|
|
201
|
-
|
|
201
|
+
A condition reads the same predicate grammar as `.class when` — a bare path (truthy), or the comparisons `==` `!=` `<` `<=` `>` `>=` `contains`, joined with `and`, `or`, and `not`. (`@loop … where` is the comparison-only subset.) Chain with `:else if` (any number; a bare `:else` must come last):
|
|
202
202
|
|
|
203
203
|
```wd
|
|
204
|
-
:if
|
|
204
|
+
:if plan == "pro" or seats >= 5
|
|
205
205
|
Pro plan
|
|
206
|
-
:else if
|
|
207
|
-
Trial — {
|
|
206
|
+
:else if trialDays > 0 and not expired
|
|
207
|
+
Trial — { trialDays } days left
|
|
208
208
|
:else
|
|
209
209
|
Free plan
|
|
210
210
|
:endif
|
|
211
211
|
```
|
|
212
212
|
|
|
213
|
-
A whole chain compiles to nested conditional regions, so it folds at build time when
|
|
213
|
+
A whole chain compiles to nested conditional regions, so it folds at build time when every value is static and stays reactive otherwise — exactly like a single `:if`.
|
|
214
214
|
|
|
215
215
|
### Reactive classes — `.class when …`
|
|
216
216
|
|
|
@@ -224,7 +224,7 @@ A container class can react to state or the loop item. Static `.class` tokens st
|
|
|
224
224
|
@endloop
|
|
225
225
|
```
|
|
226
226
|
|
|
227
|
-
The predicate uses the
|
|
227
|
+
The predicate uses the `:if` whitelist (item fields, `:state`, numbers, strings, comparisons, `and`/`or`/`not`, `contains`). A static predicate folds to a plain class at build; a state or loop-item predicate stays reactive.
|
|
228
228
|
|
|
229
229
|
### Effects — `:effect`
|
|
230
230
|
|
|
@@ -330,6 +330,7 @@ See [SECURITY.md](https://github.com/ZVN-DEV/darkmown/blob/main/SECURITY.md) in
|
|
|
330
330
|
- A matching `.skin` file attaches CSS to the page (indentation-based, compiles to real CSS).
|
|
331
331
|
- A matching `.js` file attaches page behavior.
|
|
332
332
|
- Both work for included fragments too, by basename.
|
|
333
|
+
- Any other file under `site/pages/` (an image, font, PDF — anything that isn't a `.md`/`.wd` route or a basename-matched `.skin`/`.js`) copies to `dist/` at its own path with the right content-type. So `site/pages/logo.svg` is served at `/logo.svg`. Use the `site/_/` shelf for assets shared across pages; colocate the ones a single page owns.
|
|
333
334
|
|
|
334
335
|
## Spec status
|
|
335
336
|
|
package/site/pages/reactive.wd
CHANGED
|
@@ -16,6 +16,16 @@ The count is { count }.
|
|
|
16
16
|
|
|
17
17
|
:button "Increment" -> count++
|
|
18
18
|
|
|
19
|
+
`:if` reads JavaScript-style comparisons — `==` `!=` `<` `<=` `>` `>=` `contains` — joined with `and`, `or`, and `not`. This chain reacts to the counter above, no handler wired by hand:
|
|
20
|
+
|
|
21
|
+
:if count >= 3 and count <= 5
|
|
22
|
+
Counter is in the sweet spot (3–5).
|
|
23
|
+
:else if count > 5
|
|
24
|
+
Counter is over the top.
|
|
25
|
+
:else
|
|
26
|
+
Counter is warming up.
|
|
27
|
+
:endif
|
|
28
|
+
|
|
19
29
|
:state open = false
|
|
20
30
|
|
|
21
31
|
:button "Show details" -> open = true
|
package/src/compiler.js
CHANGED
|
@@ -1159,48 +1159,71 @@ function handleEffect(line, ctx) {
|
|
|
1159
1159
|
* @returns {string}
|
|
1160
1160
|
*/
|
|
1161
1161
|
function handleIf(line, truthyLines, falsyLines, ctx) {
|
|
1162
|
-
const
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1162
|
+
const condition = line.replace(/^:if\s+/, "").trim();
|
|
1163
|
+
// Fast path: a bare truthy dotted path (`:if open`, `:if item.done`). Keeps the
|
|
1164
|
+
// existing markup/behavior identical. Anything with operators (`>`, `==`, `and`,
|
|
1165
|
+
// `not`, …) falls through to the predicate path below.
|
|
1166
|
+
const match = condition.match(/^([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)$/);
|
|
1167
|
+
if (match) {
|
|
1168
|
+
const segs = match[1].split(".");
|
|
1169
|
+
const head = segs[0];
|
|
1170
|
+
|
|
1171
|
+
// Per-row meta vars in :if — only valid inside a loop.
|
|
1172
|
+
if (LOOP_META[head]) {
|
|
1173
|
+
if (!ctx.loopMeta) throw new Error(`":if ${match[1]}" uses the loop meta variable "${head}" outside a @loop in ${ctx.file}. Use it inside a loop body.`);
|
|
1174
|
+
if (ctx.loopItem) {
|
|
1175
|
+
const truthy = compileBody(truthyLines, ctx).trim();
|
|
1176
|
+
const falsy = compileBody(falsyLines, ctx).trim();
|
|
1177
|
+
return `<span data-wd-each-if data-wd-meta="${LOOP_META[head]}"><template data-wd-if-true>${truthy}</template><template data-wd-if-false>${falsy}</template><span data-wd-each-if-out></span></span>`;
|
|
1178
|
+
}
|
|
1179
|
+
// static: the meta boolean is in scope — fall through to the static branch below.
|
|
1180
|
+
}
|
|
1166
1181
|
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1182
|
+
const staticValue = lookupVar(ctx.scope, head);
|
|
1183
|
+
if (staticValue.found) {
|
|
1184
|
+
const active = Boolean(getPath(staticValue.value, segs.slice(1)));
|
|
1185
|
+
return compileBody(active ? truthyLines : falsyLines, ctx);
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
if (ctx.loopItem && head === ctx.loopItem) {
|
|
1171
1189
|
const truthy = compileBody(truthyLines, ctx).trim();
|
|
1172
1190
|
const falsy = compileBody(falsyLines, ctx).trim();
|
|
1173
|
-
|
|
1191
|
+
const rest = segs.slice(1).join(".");
|
|
1192
|
+
const pathAttr = ` data-wd-path="${escapeHtml(rest)}"`;
|
|
1193
|
+
return `<span data-wd-each-if${pathAttr}><template data-wd-if-true>${truthy}</template><template data-wd-if-false>${falsy}</template><span data-wd-each-if-out></span></span>`;
|
|
1174
1194
|
}
|
|
1175
|
-
// static: the meta boolean is in scope — fall through to the static branch below.
|
|
1176
|
-
}
|
|
1177
|
-
|
|
1178
|
-
const staticValue = lookupVar(ctx.scope, head);
|
|
1179
|
-
if (staticValue.found) {
|
|
1180
|
-
const active = Boolean(getPath(staticValue.value, segs.slice(1)));
|
|
1181
|
-
return compileBody(active ? truthyLines : falsyLines, ctx);
|
|
1182
|
-
}
|
|
1183
1195
|
|
|
1184
|
-
|
|
1196
|
+
const key = resolveStateKey(head, ctx);
|
|
1197
|
+
if (!key) {
|
|
1198
|
+
throw new Error(`:if ${match[1]} in ${ctx.file} does not match a :state or in-scope value. Declare it first.`);
|
|
1199
|
+
}
|
|
1200
|
+
ctx.comp.assets.runtime = true;
|
|
1185
1201
|
const truthy = compileBody(truthyLines, ctx).trim();
|
|
1186
1202
|
const falsy = compileBody(falsyLines, ctx).trim();
|
|
1187
|
-
const
|
|
1188
|
-
const pathAttr = ` data-wd-path="${escapeHtml(
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1203
|
+
const restPath = segs.slice(1).join(".");
|
|
1204
|
+
const pathAttr = restPath ? ` data-wd-path="${escapeHtml(restPath)}"` : "";
|
|
1205
|
+
const initialTruthy = Boolean(getPath(ctx.comp.state.get(key), segs.slice(1)));
|
|
1206
|
+
const active = initialTruthy ? truthy : falsy;
|
|
1207
|
+
return `<div data-wd-if="${key}"${pathAttr} data-wd-if-active="${initialTruthy}"><template data-wd-true>${truthy}</template><template data-wd-false>${falsy}</template><div data-wd-if-out>${active}</div></div>`;
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
// Predicate path: a comparison / logical condition. Compiles through the same
|
|
1211
|
+
// whitelist as `@loop … where` / `.class when` (with `not`), so it folds at
|
|
1212
|
+
// build when static, drives a per-row each-if when it reads the loop item, and
|
|
1213
|
+
// a global if-region (evaluated each render) when it reads state. No raw eval.
|
|
1214
|
+
if (!condition) throw new Error(`Malformed :if in ${ctx.file}: ${line}. Use ":if name" or ":if a <op> b [and|or|not …]".`);
|
|
1215
|
+
const compiled = compileWhen(condition, ctx, '":if"');
|
|
1216
|
+
if (compiled.static) return compileBody(compiled.value ? truthyLines : falsyLines, ctx);
|
|
1196
1217
|
ctx.comp.assets.runtime = true;
|
|
1197
1218
|
const truthy = compileBody(truthyLines, ctx).trim();
|
|
1198
1219
|
const falsy = compileBody(falsyLines, ctx).trim();
|
|
1199
|
-
const
|
|
1200
|
-
|
|
1201
|
-
|
|
1220
|
+
const exprAttr = ` data-wd-if-expr="${escapeHtml(compiled.body)}"`;
|
|
1221
|
+
if (compiled.item) {
|
|
1222
|
+
return `<span data-wd-each-if${exprAttr}><template data-wd-if-true>${truthy}</template><template data-wd-if-false>${falsy}</template><span data-wd-each-if-out></span></span>`;
|
|
1223
|
+
}
|
|
1224
|
+
const initialTruthy = evalPredicate(compiled.body, undefined, ctx);
|
|
1202
1225
|
const active = initialTruthy ? truthy : falsy;
|
|
1203
|
-
return `<div data-wd-if="
|
|
1226
|
+
return `<div data-wd-if=""${exprAttr} data-wd-if-active="${initialTruthy}"><template data-wd-true>${truthy}</template><template data-wd-false>${falsy}</template><div data-wd-if-out>${active}</div></div>`;
|
|
1204
1227
|
}
|
|
1205
1228
|
|
|
1206
1229
|
// The fixed corrective suggestion shown for any malformed @loop header.
|
|
@@ -1503,24 +1526,25 @@ function evalPredicate(body, item, ctx) {
|
|
|
1503
1526
|
* resolution order.
|
|
1504
1527
|
* @param {string} tok
|
|
1505
1528
|
* @param {Ctx} ctx
|
|
1529
|
+
* @param {string} what Directive label for error messages.
|
|
1506
1530
|
* @returns {{ code: string, state: boolean, item: boolean }}
|
|
1507
1531
|
*/
|
|
1508
|
-
function compileWhenOperand(tok, ctx) {
|
|
1532
|
+
function compileWhenOperand(tok, ctx, what) {
|
|
1509
1533
|
if (/^"[^"]*"$/.test(tok) || /^'[^']*'$/.test(tok)) return { code: JSON.stringify(tok.slice(1, -1)), state: false, item: false };
|
|
1510
1534
|
if (/^-?\d+(?:\.\d+)?$/.test(tok)) return { code: tok, state: false, item: false };
|
|
1511
1535
|
if (["true", "false", "null"].includes(tok)) return { code: tok, state: false, item: false };
|
|
1512
1536
|
if (!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(tok)) {
|
|
1513
|
-
throw new Error(`Unsupported operand "${tok}" in
|
|
1537
|
+
throw new Error(`Unsupported operand "${tok}" in ${what} (${ctx.file}). Use item.field, a :state name, a number, or a "string".`);
|
|
1514
1538
|
}
|
|
1515
1539
|
const segs = tok.split(".");
|
|
1516
1540
|
if (segs.some((seg) => ["constructor", "prototype", "__proto__"].includes(seg))) {
|
|
1517
|
-
throw new Error(`Path "${tok}" is not allowed in
|
|
1541
|
+
throw new Error(`Path "${tok}" is not allowed in ${what} (${ctx.file})`);
|
|
1518
1542
|
}
|
|
1519
1543
|
const scoped = lookupVar(ctx.scope, segs[0]);
|
|
1520
1544
|
if (scoped.found) return { code: JSON.stringify(getPath(scoped.value, segs.slice(1)) ?? null), state: false, item: false };
|
|
1521
1545
|
if (ctx.loopItem && segs[0] === ctx.loopItem) return { code: `I(${JSON.stringify(segs.slice(1).join("."))})`, state: false, item: true };
|
|
1522
1546
|
const key = resolveStateKey(segs[0], ctx);
|
|
1523
|
-
if (!key) throw new Error(
|
|
1547
|
+
if (!key) throw new Error(`${what} references unknown name "${segs[0]}" in ${ctx.file}. Use a loop item field, a declared :state, a number, or a "string".`);
|
|
1524
1548
|
const rest = segs.slice(1).join(".");
|
|
1525
1549
|
return { code: `S(${JSON.stringify(key)}${rest ? `, ${JSON.stringify(rest)}` : ""})`, state: true, item: false };
|
|
1526
1550
|
}
|
|
@@ -1533,9 +1557,10 @@ function compileWhenOperand(tok, ctx) {
|
|
|
1533
1557
|
* (which decides data-wd-each-class vs the global data-wd-class).
|
|
1534
1558
|
* @param {string} raw
|
|
1535
1559
|
* @param {Ctx} ctx
|
|
1560
|
+
* @param {string} [what] Directive label for error messages.
|
|
1536
1561
|
* @returns {{ static: true, value: boolean } | { static: false, body: string, item: boolean }}
|
|
1537
1562
|
*/
|
|
1538
|
-
function compileWhen(raw, ctx) {
|
|
1563
|
+
function compileWhen(raw, ctx, what = '"::: … when"') {
|
|
1539
1564
|
const parts = raw.split(/\s+(and|or)\s+/i);
|
|
1540
1565
|
/** @type {string[]} */
|
|
1541
1566
|
const pieces = [];
|
|
@@ -1543,21 +1568,26 @@ function compileWhen(raw, ctx) {
|
|
|
1543
1568
|
let usesItem = false;
|
|
1544
1569
|
for (let i = 0; i < parts.length; i++) {
|
|
1545
1570
|
if (i % 2 === 1) { pieces.push(parts[i].toLowerCase() === "and" ? "&&" : "||"); continue; }
|
|
1546
|
-
|
|
1571
|
+
let seg = parts[i].trim();
|
|
1572
|
+
// Optional leading `not` negates the whole sub-condition.
|
|
1573
|
+
let negate = false;
|
|
1574
|
+
if (/^not\s+/i.test(seg)) { negate = true; seg = seg.replace(/^not\s+/i, "").trim(); }
|
|
1547
1575
|
const opMatch = seg.match(/^(.+?)\s+(contains|==|!=|>=|<=|>|<)\s+(.+)$/i);
|
|
1576
|
+
let expr;
|
|
1548
1577
|
if (opMatch) {
|
|
1549
|
-
const left = compileWhenOperand(opMatch[1].trim(), ctx);
|
|
1550
|
-
const right = compileWhenOperand(opMatch[3].trim(), ctx);
|
|
1578
|
+
const left = compileWhenOperand(opMatch[1].trim(), ctx, what);
|
|
1579
|
+
const right = compileWhenOperand(opMatch[3].trim(), ctx, what);
|
|
1551
1580
|
usesState = usesState || left.state || right.state;
|
|
1552
1581
|
usesItem = usesItem || left.item || right.item;
|
|
1553
1582
|
const op = opMatch[2].toLowerCase();
|
|
1554
|
-
|
|
1583
|
+
expr = op === "contains" ? `C(${left.code}, ${right.code})` : `${left.code} ${op} ${right.code}`;
|
|
1555
1584
|
} else {
|
|
1556
|
-
const only = compileWhenOperand(seg, ctx);
|
|
1585
|
+
const only = compileWhenOperand(seg, ctx, what);
|
|
1557
1586
|
usesState = usesState || only.state;
|
|
1558
1587
|
usesItem = usesItem || only.item;
|
|
1559
|
-
|
|
1588
|
+
expr = only.code;
|
|
1560
1589
|
}
|
|
1590
|
+
pieces.push(negate ? `(!(${expr}))` : `(${expr})`);
|
|
1561
1591
|
}
|
|
1562
1592
|
const body = pieces.join(" ");
|
|
1563
1593
|
if (!usesState && !usesItem) return { static: true, value: evalPredicate(body, undefined, ctx) };
|
package/src/runtime.js
CHANGED
|
@@ -205,12 +205,20 @@ function classToggle(el, raw, item) {
|
|
|
205
205
|
/** @type {[string, string][]} */
|
|
206
206
|
let pairs;
|
|
207
207
|
try { pairs = JSON.parse(raw); } catch { return; }
|
|
208
|
-
for (const [name, body] of pairs)
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
208
|
+
for (const [name, body] of pairs) el.classList.toggle(name, evalPredicate(body, item));
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Evaluate a compiled whitelist predicate body (over I()/S()/C()) to a boolean.
|
|
213
|
+
* Shared by reactive classes (`.class when`) and expression conditionals
|
|
214
|
+
* (`:if a > b`). `item` is the loop row for per-row predicates, else undefined.
|
|
215
|
+
* @param {string} body
|
|
216
|
+
* @param {any} item
|
|
217
|
+
* @returns {boolean}
|
|
218
|
+
*/
|
|
219
|
+
function evalPredicate(body, item) {
|
|
220
|
+
try { return Boolean(loopPredicate(body)((/** @type {string} */ p) => getPath(item, p), (/** @type {string} */ k, /** @type {string} */ r) => getPath(state[k], r || ""), containsFn)); }
|
|
221
|
+
catch (error) { warn(body, error); return false; }
|
|
214
222
|
}
|
|
215
223
|
|
|
216
224
|
/**
|
|
@@ -241,8 +249,9 @@ function fillItem(node, item, meta = {}) {
|
|
|
241
249
|
// querySelectorAll skips <template> content, so this sees only the outermost
|
|
242
250
|
// regions; recursing into each injected branch fills the rest.
|
|
243
251
|
for (const region of node.querySelectorAll("[data-wd-each-if]")) {
|
|
252
|
+
const expr = region.getAttribute("data-wd-if-expr");
|
|
244
253
|
const m = region.getAttribute("data-wd-meta");
|
|
245
|
-
const value = m ? meta[m] : getPath(item, region.getAttribute("data-wd-path"));
|
|
254
|
+
const value = expr ? evalPredicate(expr, item) : (m ? meta[m] : getPath(item, region.getAttribute("data-wd-path")));
|
|
246
255
|
const output = region.querySelector("[data-wd-each-if-out]");
|
|
247
256
|
if (!output) continue;
|
|
248
257
|
const template = /** @type {HTMLTemplateElement | null} */ (region.querySelector(value ? "template[data-wd-if-true]" : "template[data-wd-if-false]"));
|
|
@@ -301,6 +310,31 @@ function pipeline(list, region) {
|
|
|
301
310
|
return list;
|
|
302
311
|
}
|
|
303
312
|
|
|
313
|
+
/**
|
|
314
|
+
* Evaluate one global `data-wd-if` region against current state and swap its
|
|
315
|
+
* branch when the truthiness flips. `data-wd-if-expr` carries a compiled
|
|
316
|
+
* predicate (richer `:if`); otherwise it is a bare-path truthiness test. On a
|
|
317
|
+
* swap, the freshly injected branch can carry nested if-regions (a desugared
|
|
318
|
+
* `:else if`) that were never in the live tree this pass — querySelectorAll
|
|
319
|
+
* skips <template> content — so recurse to fill them. Unchanged regions are
|
|
320
|
+
* left alone; their already-live nested regions are reached by renderNow's
|
|
321
|
+
* document-wide query.
|
|
322
|
+
* @param {Element} node
|
|
323
|
+
* @returns {void}
|
|
324
|
+
*/
|
|
325
|
+
function renderIf(node) {
|
|
326
|
+
const expr = node.getAttribute("data-wd-if-expr");
|
|
327
|
+
const value = expr ? evalPredicate(expr, undefined) : getPath(state[node.getAttribute("data-wd-if") || ""], node.getAttribute("data-wd-path"));
|
|
328
|
+
const active = String(Boolean(value));
|
|
329
|
+
if (node.getAttribute("data-wd-if-active") === active) return;
|
|
330
|
+
node.setAttribute("data-wd-if-active", active);
|
|
331
|
+
const output = node.querySelector("[data-wd-if-out]");
|
|
332
|
+
if (!output) return;
|
|
333
|
+
const template = /** @type {HTMLTemplateElement | null} */ (node.querySelector(value ? "template[data-wd-true]" : "template[data-wd-false]"));
|
|
334
|
+
output.innerHTML = template?.innerHTML || "";
|
|
335
|
+
for (const nested of output.querySelectorAll("[data-wd-if]")) renderIf(nested);
|
|
336
|
+
}
|
|
337
|
+
|
|
304
338
|
/**
|
|
305
339
|
* Synchronously render the whole document from current `state`:
|
|
306
340
|
* computed → if-regions → keyed loop reconcile → text/input binds.
|
|
@@ -308,16 +342,7 @@ function pipeline(list, region) {
|
|
|
308
342
|
*/
|
|
309
343
|
function renderNow() {
|
|
310
344
|
recompute();
|
|
311
|
-
for (const node of document.querySelectorAll("[data-wd-if]"))
|
|
312
|
-
const value = getPath(state[node.getAttribute("data-wd-if") || ""], node.getAttribute("data-wd-path"));
|
|
313
|
-
const active = String(Boolean(value));
|
|
314
|
-
if (node.getAttribute("data-wd-if-active") === active) continue;
|
|
315
|
-
node.setAttribute("data-wd-if-active", active);
|
|
316
|
-
const output = node.querySelector("[data-wd-if-out]");
|
|
317
|
-
if (!output) continue;
|
|
318
|
-
const template = /** @type {HTMLTemplateElement | null} */ (node.querySelector(value ? "template[data-wd-true]" : "template[data-wd-false]"));
|
|
319
|
-
output.innerHTML = template?.innerHTML || "";
|
|
320
|
-
}
|
|
345
|
+
for (const node of document.querySelectorAll("[data-wd-if]")) renderIf(node);
|
|
321
346
|
|
|
322
347
|
// Reactive styling: toggle state-driven `.class when …` bindings. Loop-row
|
|
323
348
|
// bindings (data-wd-each-class) are handled per item inside fillItem.
|
package/src/scaffold.js
CHANGED
|
@@ -128,10 +128,19 @@ export function initProject(root) {
|
|
|
128
128
|
"",
|
|
129
129
|
"Run `npm install` and `npm run dev` to start the live compiler.",
|
|
130
130
|
"",
|
|
131
|
+
"## Commands",
|
|
132
|
+
"",
|
|
133
|
+
"- `npm run dev` — live compiler on http://localhost:5173 with hot reload.",
|
|
134
|
+
"- `npm run build` — compile the site to `dist/`.",
|
|
135
|
+
"- `npm run preview` — serve the built `dist/` locally.",
|
|
136
|
+
"",
|
|
137
|
+
"## Layout",
|
|
138
|
+
"",
|
|
131
139
|
"- Pages live in `site/pages`.",
|
|
132
140
|
"- Shared includes live in `site/_`.",
|
|
133
141
|
"- Hidden route files start with `.` or `-`.",
|
|
134
|
-
"- Colocated `index.skin` and `index.js` attach automatically."
|
|
142
|
+
"- Colocated `index.skin` and `index.js` attach automatically.",
|
|
143
|
+
"- Any other file under `site/pages` (images, fonts, …) copies to `dist/` at its own path."
|
|
135
144
|
].join("\n"));
|
|
136
145
|
return { root };
|
|
137
146
|
}
|