VKP1     m{"name":"web_live","version":"1.0.0","tier":6,"tier_label":"Tier 6: Local-First, IoT, Web & Media","category":"Server-Driven Live Views","description":"Homoiconic HTML virtual-DOM differ, keyed patch ops, Server-Sent Events (SSE) morphing frames, and typed HTMX request/response helpers.","modules":["web_live"],"homepage":"https://veko-lang.org/packages/web_live"}    	README.md  ø# web_live

Server-driven LiveView virtual DOM tree differ, minimal DOM patch morpher, SSE patch streamer, `< 2 KB` browser runtime, and HTMX hypermedia helpers built over `lib/html` and `lib/web`.

## Installation

```powershell
veko pkg add web_live@1.0.0
```

Import in any Veko module:

```rebol
use [live = web_live]
```

## Architecture Notes

- **Homoiconic Hiccup Compatibility:** Operates directly on `lib/html` Hiccup blocks (`[.div { id = 'app' } [ [.h1 {} ['Hello']] ]]`) with zero intermediate JSX compilation step.
- **Minimal Tree-Path Patch Operations:** `live/diff-trees` walks `old_tree` and `new_tree` in lockstep, emitting `.replace`, `.set_text`, `.set_attr`, `.del_attr`, `.insert_child`, and back-to-front `.remove_child` operations addressed by integer `childNodes` paths (such as `[0 2 1]`).
- **Exact Structural Roundtrip:** `live/apply-patches` applies patch sequences in pure Veko so `(live/apply-patches old_tree patches) == new_tree` holds deterministically in unit tests without launching a browser.
- **Compact `< 2 KB` Client Morph Runtime:** `live/client-runtime-js` embeds an `EventSource` listener (`veko-patch`) and `[vk-click]` event delegation script in under 1.2 KB of vanilla JavaScript.
- **HTMX Hypermedia Engine:** First-class helpers for `HX-Request`, `HX-Boosted`, `HX-Target`, `HX-Trigger`, `HX-Redirect`, `HX-Reswap`, `HX-Retarget`, `hx-swap-oob`, and automatic full-page vs fragment rendering (`live/render-page-or-partial`).

## API Reference

### Types

- `PatchOp` â€” `{ op enum, path block, key str, val any, index i64 }`
- `LiveSession` â€” `{ id str, state any, tree any, version i64, reducer any, view any }`
- `LiveStep` â€” `{ version i64, patches block[PatchOp], sse str, tree any }`

### Virtual DOM & LiveView Functions

- `live/hiccup-el? node` -> `bool`
- `live/diff-trees old_tree new_tree` -> `block[PatchOp]`
- `live/apply-patches tree patches` -> `any`
- `live/encode-sse-patch patches [/id event_id] [/event ev_name]` -> `str`
- `live/client-runtime-js endpoint_prefix` -> `str`
- `live/new-session id initial_state reducer_fn view_fn` -> `LiveSession`
- `live/dispatch-event mut sess event_name payload` -> `LiveStep`

### HTMX Hypermedia Functions

- `live/htmx-request? req` -> `bool`
- `live/htmx-boosted? req` -> `bool`
- `live/htmx-target req` -> `str`
- `live/htmx-trigger-name req` -> `str`
- `live/hx-trigger resp event_spec` -> `web/Response`
- `live/hx-redirect location` -> `web/Response`
- `live/hx-reswap resp strategy` -> `web/Response`
- `live/hx-retarget resp selector` -> `web/Response`
- `live/hx-swap-oob node swap_spec` -> `block`
- `live/render-page-or-partial req title head_extra fragment_node` -> `web/Response`

## Idiomatic Veko Example

```rebol
use [live = web_live, html]

view = fn [count i64] block [
    [.div { id = 'counter' } [
        [.span { class = 'val' } [`Count: {mold count}`]]
        [.button { 'vk-click' = 'inc' } ['+1']]
    ]]
]

t0 = view 0
t1 = view 1
patches = live/diff-trees t0 t1
sse = live/encode-sse-patch/id patches '1'
println sse
```
¶ŒéƒÚ¢ê€x«Ø#ÿÙ¢wÓ…ùr»:%©‡†•¦	5¥ examples/demo.vk  |// packages/web_live/examples/demo.vk
// Verification suite for `web_live`: Virtual DOM `diff-trees`, `apply-patches`
// roundtrip invariants, SSE patch framing, <2 KB JS morph runtime, LiveSession
// reducer transitions, and HTMX hypermedia helpers.

use [live = web_live, html, web]

assert-eq = fn [label str, got any, want any] [
	if got != want [
		println `[FAIL] {label}: got {mold got}, expected {mold want}`
		return (err `assertion failed: {label}`)
	]
	println `[PASS] {label}`
	.ok
]

assert-true = fn [label str, cond bool] [
	if not cond [
		println `[FAIL] {label}`
		return (err `assertion failed: {label}`)
	]
	println `[PASS] {label}`
	.ok
]

render-dashboard = fn [st map] block [
	count = as-i64 (map/get st 'count')
	rows = map/get st 'rows'
	alert = str/append '' (map/get/or st 'alert' [ '' ])

	mut panel_attrs = {
		id          = 'live-panel'
		class       = if count >= 2 [ 'panel panel-hot' ] else [ 'panel' ]
		'data-step' = (mold count)
	}
	if alert != '' [
		map/set mut panel_attrs 'data-alert' alert
	]

	mut tr_nodes = []
	mut i = 0
	while i < (len rows) [
		r = rows[i]
		push mut tr_nodes [.tr { 'data-key' = (str/append '' (map/get r 'id')) } [
			[.td {} [(str/append '' (map/get r 'name'))]]
			[.td {} [(mold (map/get r 'ms'))]]
		]]
		i = i + 1
	]

	[.section panel_attrs [
		[.h2 {} [`Requests: {mold count}`]]
		[.table { class = 'metrics' } [
			[.tbody {} tr_nodes]
		]]
		(if count == 0 [
			[.p { class = 'hint' } ['Idle']]
		] else [
			[.span { class = 'active-badge' } ['Running']]
		])
	]]
]

dashboard-reducer = fn [st map, ev str, payload any] map [
	mut next = st
	if ev == 'inc' [
		c = as-i64 (map/get next 'count')
		map/set mut next 'count' (c + 1)
	]
	if ev == 'add_row' [
		mut rs = map/get next 'rows'
		push mut rs payload
		map/set mut next 'rows' rs
	]
	if ev == 'pop_row' [
		old_rs = map/get next 'rows'
		mut trimmed = []
		mut i = 0
		while i < ((len old_rs) - 1) [
			push mut trimmed old_rs[i]
			i = i + 1
		]
		map/set mut next 'rows' trimmed
	]
	if ev == 'clear_alert' [
		map/delete mut next 'alert'
	]
	next
]

main = fn [] any [
	s0 = {
		count = 0
		alert = 'warmup'
		rows  = [
			{ id = 'r1', name = 'GET /health', ms = 2 }
			{ id = 'r2', name = 'POST /mcp', ms = 9 }
		]
	}

	s1 = {
		count = 2
		rows  = [
			{ id = 'r1', name = 'GET /health', ms = 3 }
			{ id = 'r2', name = 'POST /mcp', ms = 9 }
			{ id = 'r3', name = 'POST /chat', ms = 41 }
		]
	}

	tree0 = render-dashboard s0
	tree1 = render-dashboard s1

	// 1. Compute minimal `diff-trees` patches covering `.del_attr`, `.set_attr`, `.set_text`, `.insert_child`, and `.replace`
	patches_0_1 = live/diff-trees tree0 tree1
	_ = assert-true/or 'diff-trees produces minimal non-empty patches' ((len patches_0_1) >= 5 and (len patches_0_1) <= 8) [e -> return e]

	patched1 = live/apply-patches/or tree0 patches_0_1 [e -> return e]
	_ = assert-eq/or 'apply-patches tree0 patches == tree1 (exact structural equality)' patched1 tree1 [e -> return e]
	_ = assert-eq/or 'html/render patched1 == html/render tree1' (html/render patched1) (html/render tree1) [e -> return e]

	// 2. Test `.remove_child` when rows shrink back from 3 rows to 1 row
	s2 = {
		count = 2
		rows  = [
			{ id = 'r1', name = 'GET /health', ms = 3 }
		]
	}
	tree2 = render-dashboard s2
	patches_1_2 = live/diff-trees tree1 tree2
	_ = assert-eq/or 'shrinking 2 rows emits exactly 2 remove_child patches' (len patches_1_2) 2 [e -> return e]
	_ = assert-eq/or 'remove_child emitted back-to-front (index 2 then 1)' patches_1_2[0].index 2 [e -> return e]
	_ = assert-eq/or 'remove_child second index 1' patches_1_2[1].index 1 [e -> return e]

	patched2 = live/apply-patches/or tree1 patches_1_2 [e -> return e]
	_ = assert-eq/or 'apply-patches tree1 patches == tree2' patched2 tree2 [e -> return e]

	// 3. Test SSE patch framing & <2 KB client runtime JS
	sse_wire = live/encode-sse-patch/id patches_0_1 '42'
	_ = assert-true/or 'SSE patch carries id: 42' (str/contains? sse_wire 'id: 42\n') [e -> return e]
	_ = assert-true/or 'SSE patch carries event: veko-patch' (str/contains? sse_wire 'event: veko-patch\n') [e -> return e]
	_ = assert-true/or 'SSE patch carries data: JSON ops' (str/contains? sse_wire '"op":"set_text"') [e -> return e]

	js_code = live/client-runtime-js '/live'
	js_len = len (bytes/from-str js_code)
	_ = assert-true/or 'client-runtime-js is compact (< 2048 bytes)' (js_len > 200 and js_len < 2048) [e -> return e]
	_ = assert-true/or 'client-runtime-js wires EventSource veko-patch' (str/contains? js_code 'EventSource') [e -> return e]

	// 4. Test stateful `LiveSession` reducer manager
	mut sess = live/new-session 'sess-1' s0 fn [st map, ev str, p any] map [
		dashboard-reducer st ev p
	] fn [st map] block [
		render-dashboard st
	]
	step1 = live/dispatch-event/or mut sess 'inc' .none [e -> return e]
	_ = assert-eq/or 'LiveSession version incremented to 2' step1.version 2 [e -> return e]
	step2 = live/dispatch-event/or mut sess 'add_row' { id = 'r3', name = 'GET /live', ms = 5 } [e -> return e]
	_ = assert-eq/or 'LiveSession version incremented to 3' step2.version 3 [e -> return e]
	_ = assert-true/or 'LiveSession SSE contains insert_child' (str/contains? step2.sse 'insert_child') [e -> return e]

	// 5. Test HTMX hypermedia request detection, headers & partial vs full-page wrapper
	full_req = web/Request {
		method = 'GET', path = '/dashboard', target = '/dashboard',
		query = {}, params = {}, headers = {}, body = bytes/with-cap 0
	}
	hx_req = web/Request {
		method = 'GET', path = '/dashboard', target = '/dashboard',
		query = {}, params = {}, headers = { 'HX-Request' = 'true', 'HX-Target' = 'live-panel' }, body = bytes/with-cap 0
	}

	_ = assert-eq/or 'htmx-request? false on normal GET' (live/htmx-request? full_req) false [e -> return e]
	_ = assert-eq/or 'htmx-request? true on HX-Request' (live/htmx-request? hx_req) true [e -> return e]
	_ = assert-eq/or 'htmx-target reads HX-Target' (live/htmx-target hx_req) 'live-panel' [e -> return e]

	full_resp = live/render-page-or-partial full_req 'Live Dashboard' [] tree2
	part_resp = live/render-page-or-partial hx_req 'Live Dashboard' [] tree2
	_ = assert-true/or 'Full GET includes <!DOCTYPE html>' (str/contains? (bytes/to-str full_resp.body) '<!DOCTYPE html>') [e -> return e]
	_ = assert-true/or 'HTMX partial omits <!DOCTYPE html>' (not (str/contains? (bytes/to-str part_resp.body) '<!DOCTYPE html>')) [e -> return e]

	oob_badge = live/hx-swap-oob [.div { id = 'toast' } ['Saved']] 'outerHTML'
	_ = assert-true/or 'hx-swap-oob attribute rendered' (str/contains? (html/render oob_badge) 'hx-swap-oob="outerHTML"') [e -> return e]

	trig_resp = live/hx-trigger part_resp { showToast = 'Updated' }
	_ = assert-eq/or 'HX-Trigger JSON header' (map/get trig_resp.headers 'HX-Trigger') '{"showToast":"Updated"}' [e -> return e]

	redir_resp = live/hx-redirect '/login'
	_ = assert-eq/or 'HX-Redirect header' (map/get redir_resp.headers 'HX-Redirect') '/login' [e -> return e]

	println 'web_live demo: all checks passed.'
	0
]

main
çDxâú54&ÂJá>¸àe°Z:iÜÁ‚Í?X¤Æ mod.vk  53// packages/web_live/src/mod.vk
// Server-Driven LiveView Virtual DOM Differ, Patch Morpher, SSE Patch Streamer,
// <2 KB Browser Client Runtime, and HTMX Hypermedia Engine built on `lib/html` & `lib/web`.

use [html, web]

// Minimal DOM patch operation emitted by `diff-trees` and consumed by `apply-patches` / `encode-sse-patch`.
// `op`: `.replace`, `.set_text`, `.set_attr`, `.del_attr`, `.insert_child`, `.remove_child`
pub PatchOp = struct {
	op    enum
	path  block
	key   str = ''
	val   any = .none
	index i64 = 0
}

// Stateful server-driven LiveView component session.
pub LiveSession = struct {
	id      str
	state   any
	tree    any
	version i64 = 1
	reducer any
	view    any
}

// Output of `dispatch-event` containing minimal patches, SSE wire frame, and updated tree.
pub LiveStep = struct {
	version i64
	patches block[PatchOp]
	sse     str
	tree    any
}

invoke-1 = fn [f any, a any] any [
	(f a)
]

invoke-3 = fn [f any, a any, b any, c any] any [
	(f a b c)
]

// Returns `true` if `node` is a homoiconic Hiccup element (`[.div { ... } [...]]` or `[.div [...]]`).
pub hiccup-el? = fn [node any] bool [
	if (type-of node) != .block [ return false ]
	if (len node) == 0 [ return false ]
	t0 = node[0]
	(type-of t0) == .enum_sym and t0 != .none and t0 != .null and t0 != .ok
]

el-tag = fn [node block] enum [
	node[0]
]

has-explicit-attrs? = fn [node block] bool [
	(len node) >= 2 and (type-of node[1]) == .map_val
]

el-attrs = fn [node block] map [
	if has-explicit-attrs? node [ return node[1] ]
	{}
]

el-children = fn [node block] block [
	n = len node
	start_i = if has-explicit-attrs? node [ 2 ] else [ 1 ]
	if start_i >= n [ return [] ]
	// Standard canonical Hiccup `[.div { ... } [ child0 child1 ... ]]`
	if (start_i + 1) == n and (type-of node[start_i]) == .block and (not (hiccup-el? node[start_i])) [
		return node[start_i]
	]
	mut out = []
	mut i = start_i
	while i < n [
		push mut out node[i]
		i = i + 1
	]
	out
]

rebuild-el = fn [orig block, tag enum, attrs map, kids block] block [
	if (has-explicit-attrs? orig) or (len (map/keys attrs)) > 0 [
		return [tag attrs kids]
	]
	[tag kids]
]

is-scalar-text? = fn [node any] bool [
	tv = type-of node
	tv == .str or tv == .i64_val or tv == .f64_val or tv == .boolean
]

scalar-to-str = fn [node any] str [
	if (type-of node) == .str [ return (str/append '' node) ]
	mold node
]

append-path = fn [base block, idx i64] block [
	mut next = []
	mut i = 0
	while i < (len base) [
		push mut next base[i]
		i = i + 1
	]
	push mut next idx
	next
]

diff-at = fn [old_n any, new_n any, cur_path block, mut patches block] [
	if (is-scalar-text? old_n) and (is-scalar-text? new_n) [
		if old_n != new_n [
			push mut patches (PatchOp {
				op   = .set_text
				path = cur_path
				val  = new_n
			})
		]
		return .ok
	]

	if (hiccup-el? old_n) and (hiccup-el? new_n) [
		otag = el-tag old_n
		ntag = el-tag new_n
		if otag != ntag [
			push mut patches (PatchOp {
				op   = .replace
				path = cur_path
				val  = new_n
			})
			return .ok
		]

		oattrs = el-attrs old_n
		nattrs = el-attrs new_n
		oks = map/keys oattrs
		mut oi = 0
		while oi < (len oks) [
			ok = str/append '' oks[oi]
			if not (map/has? nattrs ok) [
				push mut patches (PatchOp {
					op   = .del_attr
					path = cur_path
					key  = ok
				})
			]
			oi = oi + 1
		]

		nks = map/keys nattrs
		mut ni = 0
		while ni < (len nks) [
			nk = str/append '' nks[ni]
			nv = map/get nattrs nk
			if (not (map/has? oattrs nk)) or (map/get oattrs nk) != nv [
				push mut patches (PatchOp {
					op   = .set_attr
					path = cur_path
					key  = nk
					val  = nv
				})
			]
			ni = ni + 1
		]

		okids = el-children old_n
		nkids = el-children new_n
		olen = len okids
		nlen = len nkids
		common = if olen < nlen [ olen ] else [ nlen ]

		mut ci = 0
		while ci < common [
			diff-at okids[ci] nkids[ci] (append-path cur_path ci) mut patches
			ci = ci + 1
		]

		if nlen > olen [
			mut ins_i = olen
			while ins_i < nlen [
				push mut patches (PatchOp {
					op    = .insert_child
					path  = cur_path
					index = ins_i
					val   = nkids[ins_i]
				})
				ins_i = ins_i + 1
			]
		]

		if olen > nlen [
			mut rem_i = olen - 1
			while rem_i >= nlen [
				push mut patches (PatchOp {
					op    = .remove_child
					path  = cur_path
					index = rem_i
				})
				rem_i = rem_i - 1
			]
		]
		return .ok
	]

	if old_n != new_n [
		push mut patches (PatchOp {
			op   = .replace
			path = cur_path
			val  = new_n
		})
	]
	.ok
]

// Computes the minimal ordered block of `PatchOp` mutations transforming `old_tree` into `new_tree`.
pub diff-trees = fn [old_tree any, new_tree any] block[PatchOp] [
	mut patches = []
	diff-at old_tree new_tree [] mut patches
	patches
]

insert-at = fn [xs block, idx i64, item any] block [
	n = len xs
	clamped = if idx < 0 [ 0 ] else [ if idx > n [ n ] else [ idx ] ]
	mut out = []
	mut i = 0
	while i < clamped [
		push mut out xs[i]
		i = i + 1
	]
	push mut out item
	while i < n [
		push mut out xs[i]
		i = i + 1
	]
	out
]

remove-at = fn [xs block, idx i64] block [
	n = len xs
	mut out = []
	mut i = 0
	while i < n [
		if i != idx [
			push mut out xs[i]
		]
		i = i + 1
	]
	out
]

copy-map = fn [m map] map [
	mut out = {}
	ks = map/keys m
	mut i = 0
	while i < (len ks) [
		k = str/append '' ks[i]
		map/set mut out k (map/get m k)
		i = i + 1
	]
	out
]

apply-one-at = fn [node any, patch PatchOp, depth i64] any [
	plen = len patch.path
	if depth < plen [
		if not (hiccup-el? node) [
			return (err 'web_live/apply-patches: path descends into non-element node')
		]
		child_idx = as-i64 patch.path[depth]
		mut kids = el-children node
		if child_idx < 0 or child_idx >= (len kids) [
			return (err `web_live/apply-patches: child index {mold child_idx} out of bounds`)
		]
		updated_child = apply-one-at/or kids[child_idx] patch (depth + 1) [e -> return e]
		block/set mut kids child_idx updated_child
		return (rebuild-el node (el-tag node) (el-attrs node) kids)
	]

	op = patch.op
	if op == .replace  [ return patch.val ]
	if op == .set_text [ return patch.val ]

	if not (hiccup-el? node) [
		return (err `web_live/apply-patches: op {mold op} requires element target`)
	]
	tag = el-tag node
	mut attrs = copy-map (el-attrs node)
	kids = el-children node

	if op == .set_attr [
		map/set mut attrs patch.key patch.val
		return [tag attrs kids]
	]
	if op == .del_attr [
		map/delete mut attrs patch.key
		return (rebuild-el node tag attrs kids)
	]
	if op == .insert_child [
		nkids = insert-at kids patch.index patch.val
		return (rebuild-el node tag attrs nkids)
	]
	if op == .remove_child [
		nkids = remove-at kids patch.index
		return (rebuild-el node tag attrs nkids)
	]
	err `web_live/apply-patches: unsupported patch op {mold op}`
]

// Applies `patches` sequentially to `tree`, returning the updated Hiccup virtual DOM tree.
pub apply-patches = fn [tree any, patches block] any [
	mut cur = tree
	mut i = 0
	while i < (len patches) [
		cur = apply-one-at/or cur patches[i] 0 [e -> return e]
		i = i + 1
	]
	cur
]

// --- SSE Patch Wire Framing & <2 KB Client Morph Runtime ---

op-name-str = fn [op enum] str [
	if op == .replace      [ return 'replace' ]
	if op == .set_text     [ return 'set_text' ]
	if op == .set_attr     [ return 'set_attr' ]
	if op == .del_attr     [ return 'del_attr' ]
	if op == .insert_child [ return 'insert_child' ]
	if op == .remove_child [ return 'remove_child' ]
	mold op
]

// Serializes `patches` into a JSON-encoded `veko-patch` Server-Sent Events (SSE) wire frame.
pub encode-sse-patch = fn [patches block /id event_id str = '' /event ev_name str = 'veko-patch'] str [
	mut wire_ops = []
	mut i = 0
	while i < (len patches) [
		p = patches[i]
		op_s = op-name-str p.op
		mut item = {
			op   = op_s
			path = p.path
		}
		if p.op == .replace [
			map/set mut item 'html' (html/render p.val)
		]
		if p.op == .set_text [
			map/set mut item 'text' (scalar-to-str p.val)
		]
		if p.op == .set_attr [
			map/set mut item 'key' p.key
			map/set mut item 'val' (scalar-to-str p.val)
		]
		if p.op == .del_attr [
			map/set mut item 'key' p.key
		]
		if p.op == .insert_child [
			map/set mut item 'index' p.index
			map/set mut item 'html' (html/render p.val)
		]
		if p.op == .remove_child [
			map/set mut item 'index' p.index
		]
		push mut wire_ops item
		i = i + 1
	]
	web/sse-event ev_name (json/encode wire_ops) event_id
]

// Returns the self-contained (<2 KB) browser LiveView DOM morphing & event delegation runtime JS.
pub client-runtime-js = fn [endpoint_prefix str] str [
	str/join [
		'(()=>{'
		'const ep=' (json/encode endpoint_prefix) ';'
		'const root=document.querySelector("[data-vk-live]")||document.body;'
		'const walk=(n,p)=>{let c=n;for(const i of p){if(!c||!c.childNodes[i])return null;c=c.childNodes[i];}return c;};'
		'const frag=(h)=>{const t=document.createElement("template");t.innerHTML=h;return t.content.firstChild||document.createTextNode(h);};'
		'const apply=(ops)=>{for(const o of ops){'
		'const t=walk(root.firstElementChild||root,o.path);if(!t)continue;'
		'if(o.op==="replace")t.replaceWith(frag(o.html));'
		'else if(o.op==="set_text")t.textContent=o.text;'
		'else if(o.op==="set_attr")t.setAttribute(o.key,o.val);'
		'else if(o.op==="del_attr")t.removeAttribute(o.key);'
		'else if(o.op==="insert_child"){const ref=t.childNodes[o.index]||null;t.insertBefore(frag(o.html),ref);}'
		'else if(o.op==="remove_child"){const ch=t.childNodes[o.index];if(ch)ch.remove();}'
		'}};'
		'const es=new EventSource(ep+"/stream");'
		'es.addEventListener("veko-patch",(e)=>apply(JSON.parse(e.data)));'
		'document.addEventListener("click",(e)=>{'
		'const el=e.target.closest("[vk-click]");if(!el)return;'
		'e.preventDefault();'
		'fetch(ep+"/event",{method:"POST",headers:{"Content-Type":"application/json"},'
		'body:JSON.stringify({event:el.getAttribute("vk-click"),val:el.getAttribute("vk-val")||""})});'
		'});'
		'})();'
	] ''
]

// --- Stateful LiveSession Reducer Manager ---

// Creates a new `LiveSession` with initial rendered virtual DOM tree.
pub new-session = fn [id str, initial_state any, reducer_fn any, view_fn any] LiveSession [
	initial_tree = invoke-1 view_fn initial_state
	LiveSession {
		id      = id
		state   = initial_state
		tree    = initial_tree
		version = 1
		reducer = reducer_fn
		view    = view_fn
	}
]

// Applies `(reducer state event_name payload)`, diffs the resulting view tree, advances `sess`, and returns a `LiveStep`.
pub dispatch-event = fn [mut sess LiveSession, event_name str, payload any] any [
	rfn = sess.reducer
	vfn = sess.view
	next_state = invoke-3/or rfn sess.state event_name payload [e -> return e]
	next_tree = invoke-1/or vfn next_state [e -> return e]
	patches = diff-trees sess.tree next_tree
	next_ver = sess.version + 1
	sse_frame = encode-sse-patch/id patches (mold next_ver)

	put mut sess .state next_state
	put mut sess .tree next_tree
	put mut sess .version next_ver

	LiveStep {
		version = next_ver
		patches = patches
		sse     = sse_frame
		tree    = next_tree
	}
]

// --- HTMX Hypermedia Engine Helpers ---

// Returns `true` when `req` carries `HX-Request: true`.
pub htmx-request? = fn [req web/Request] bool [
	(str/lower (web/header req 'HX-Request' '')) == 'true'
]

// Returns `true` when `req` carries `HX-Boosted: true`.
pub htmx-boosted? = fn [req web/Request] bool [
	(str/lower (web/header req 'HX-Boosted' '')) == 'true'
]

// Returns the target DOM element ID sent in `HX-Target` (or `''`).
pub htmx-target = fn [req web/Request] str [
	web/header req 'HX-Target' ''
]

// Returns the triggering element name sent in `HX-Trigger-Name` (or `''`).
pub htmx-trigger-name = fn [req web/Request] str [
	web/header req 'HX-Trigger-Name' ''
]

with-resp-header = fn [resp web/Response, name str, value str] web/Response [
	mut out = resp
	mut hdrs = copy-map out.headers
	map/set mut hdrs name value
	put mut out .headers hdrs
	out
]

// Attaches an `HX-Trigger` client-side event header (`str` event name or JSON-encoded `map` payload) to `resp`.
pub hx-trigger = fn [resp web/Response, event_spec any] web/Response [
	hval = if (type-of event_spec) == .str [
		str/append '' event_spec
	] else [
		json/encode event_spec
	]
	with-resp-header resp 'HX-Trigger' hval
]

// Builds or updates an HTMX client redirect response (`HX-Redirect: <location>`).
pub hx-redirect = fn [location str] web/Response [
	mut r = web/text 200 ''
	with-resp-header r 'HX-Redirect' location
]

// Overrides the HTMX swap strategy (`HX-Reswap`) on `resp`.
pub hx-reswap = fn [resp web/Response, strategy str] web/Response [
	with-resp-header resp 'HX-Reswap' strategy
]

// Overrides the HTMX target selector (`HX-Retarget`) on `resp`.
pub hx-retarget = fn [resp web/Response, selector str] web/Response [
	with-resp-header resp 'HX-Retarget' selector
]

// Annotates a Hiccup element node with `hx-swap-oob` (`'true'` when `swap_spec == ''`) for Out-Of-Band DOM updates.
pub hx-swap-oob = fn [node block, swap_spec str] block [
	if not (hiccup-el? node) [ return node ]
	mut attrs = copy-map (el-attrs node)
	oob_val = if swap_spec == '' [ 'true' ] else [ swap_spec ]
	map/set mut attrs 'hx-swap-oob' oob_val
	[(el-tag node) attrs (el-children node)]
]

// Serves an HTML fragment for non-boosted `HX-Request` partial requests, or wraps `fragment_node` in a full `<!DOCTYPE html>` layout.
pub render-page-or-partial = fn [req web/Request, title str, head_extra block, fragment_node any] web/Response [
	if (htmx-request? req) and (not (htmx-boosted? req)) [
		return (web/view 200 fragment_node)
	]
	web/page 200 title head_extra [
		[.div { 'data-vk-live' = 'true' } [fragment_node]]
	]
]
ÞÕ�j™Ð„æQµ-¶’dÓ·ÂÛi¡ßÁ§A|PsEd%twù¹ž‰�¼w:ƒÎ“[Õf©ï%Þu¿P¿ºr   '@`tØh¡ÔæB]ˆ|¬Ã3L$šÀGº�N-÷+p   @ƒ¡nÊ±´˜‹·$|lNa|¬dý;�ð}”
Dÿ._¾05†–ËçÊ$sQ²3º	¸�Ç¡¢nÊ^Y=üäRHÞŠ