KScript docs
EN

Web pages

Reactive pages with <live> (no JavaScript)

A <live> block reacts to clicks and typing without any JavaScript in the page. Its handlers are KScript statements. The server runs them, and sends back just that block's new HTML:

HTML page
<live id="counter">
  <state name="count" value="0" />
  <p>{$count}</p>
  <button on-click="decrement: $count">−</button>
  <button on-click="increment: $count">+</button>
</live>

kscript serve adds its small runtime (/_ks/live.js) to pages that use <live>, so pages never include it themselves. Reusable components become live by themselves when their templates use state, handlers, bindings or live directives. Use a <live> block in a page, or when a component needs to customize its live root. Every directive and handler is listed in Page directives.

See /demo in Example Sites/team for a counter, live search, a to-do list and a temperature converter, and samples/life-lab for a game whose rules are a KScript script shared with a terminal version and a desktop app.

State

<state name value> declares the block's state. It travels with the page, signed so the browser can't change it, so the server can restore the block from the browser's next request.

A signed state is not used up: the browser may send the same one again (the back button, a second tab), so a handler that must run only once checks that for itself, for example against the database. Signed state is visible in the page, so keep secrets in server-side values. Add locked when only server actions should change a state variable.

query="page" starts a state value from the query string and keeps the URL up to date as it changes, which suits filters and pagination. Query-backed state holds text, a number, true or false, or null, and null removes the parameter. Each update replaces the browser's current history entry:

HTML page
<live id="people">
  <state name="page" value="1" query="page" />
  <button on-click="increment: $page">Next page</button>
</live>

session="search-filters" carries a state value across visits in the same session. Use a separate key for each independent block.

Handlers

on-click, on-change, on-input, on-submit, on-keydown and on-enter run statements, such as $count += 1; $draft = ''. Inside a loop, the loop variable is there for the handler. $event.value, $event.key and $event.checked describe the browser event:

HTML page
<live id="todo">
  <state name="items" value="[{ id: 1, title: 'Milk' }]" />
  <for each="item" in="$items">
    <li>{$item.title} <button on-click="$items = $items->reject(fn(i) => $i.id == $item.id)">Remove</button></li>
  </for>
</live>

A component's own <live> block may also use on-keyup, on-escape, on-focusin, on-focusout, on-cancel, on-close, on-pointerdown, on-pointerup and on-pointercancel. The event then includes code, the keyboard modifiers (alt, ctrl, meta, shift), repeat, the pointer's position (client_x, client_y, page_x, page_y), button, pointer_id and pointer_type where they apply. The modifier prevent cancels the browser's own action before the request: @on-keydown(call: $save, key: [ctrl, s], prevent).

A handler's confirm: modifier asks before the action runs: @on-click(delete: $item, confirm: 'Remove this item?').

on-init runs a handler when the block mounts, and on-visible when its element first comes into view. Each runs once per block.

Binding inputs

@bind($name) ties an input to a state variable both ways, and redraws the block as you type:

HTML page
<live id="search">
  <state name="query" value="''" />
  <input @bind($query) placeholder="Search…">
  <li @each($people->filter(fn(p) => $p.name->lower()->contains($query->lower())), as: p)>{$p.name}</li>
</live>

A bound value is what a form control sends: text, a number, true or false, or a list of those. Anything else from the browser is refused with a 422. A radio group binds to one value, and a multiple select to a list of the selected values. @bind($draft.title) updates one field of a state map and keeps its others.

on: chooses when an edit sends an update: @bind($name, on: change) or on: blur. With on: action, the value travels with the block's next action.

Timers

on-tick="…" every="200ms" runs a handler every 200 milliseconds for as long as the element is in the block, counted from when the last answer arrived. Give it @if to start and stop it:

HTML page
<span on-tick="$frame += 1" every="100ms" @if($playing)></span>

Dragging and sorting

To drag one element onto another, mark the source with @drag(copy, value: $item.id), handle on-drop on the destination, and read $event.drag_value. Check the ID and the person's permissions in a handler that saves changes, and offer a keyboard action that does the same.

To reorder siblings, use on-sort on their container and a unique sort-item="{$item.id}" on each child. People may drag a child, or focus it and press Alt+Up or Alt+Down. sort-axis="horizontal" suits left-to-right lists. The handler receives $event.item, $event.from and $event.index (counted from 0), and the proposed $event.order. Check the order before saving it.

Feedback while a request runs

live-loading shows a status message while a request runs, live-disable disables a control, and live-offline shows an offline notice. live-dirty shows that an edit hasn't been sent yet, and naming a binding watches only that field. <span role="alert" live-error></span> shows a failed request:

HTML page
<live id="note">
  <state name="draft" value="''" />
  <textarea @bind($draft)></textarea>
  <button on-click="$draft = $draft->trim()" live-disable>Save</button>
  <p live-loading>Saving…</p>
  <p live-dirty>Unsaved changes</p>
  <span role="alert" live-error></span>
</live>

lazy on a live block waits until it comes into view before starting its state and drawing it, and defer loads it just after the page is ready. A <placeholder> directly inside the block reserves space while it loads.

Keeping elements

Live updates keep matching elements in place. Give repeated siblings live-key="{$item.id}", so they keep their identity when they're reordered, and use live-replace on an element that should be rebuilt on every update. live-cloak hides an element until the browser runtime starts. live-ignore keeps a widget the browser owns as it is through updates. Keep server handlers and bindings outside that widget.

Blocks inside blocks, and events between them

A live block may hold another, independent one. Give the inner block a unique, stable ID so it keeps its state when the outer one redraws, and change the ID when a change should start a fresh one. Requests from the inner block carry the signed state of the blocks around it.

@emit_event('items-changed', data: $item.id, target: 'summary') in a handler tells another block that something happened. Leave out target to tell the whole page. The first matching on-event in each block runs. event-name="items-changed" filters by name, and the handler reads $event.name, $event.data and $event.source. Check event data before saving a change.

Uploads, downloads and navigation

A named <input type="file" name="attachment" live-upload> sends what was picked with its on-change handler, or its form's on-submit. The handler receives $event.files.attachment, a list with each file's name, type, size and base64 bytes. Uploads are limited to 8 MiB per request. Treat file names and types as the browser's word, and check the content before saving it. live-replace on the input clears what was picked after the action.

From a handler, @live_redirect('/account') goes to another page on the site once the action succeeds, @live_download('report.txt', bytes: $report->to_base64()) downloads a file, and @skip_render() keeps the block's HTML as it is, for an action that only changes state or sends an event.

How live requests are checked

A live block calls back by asking for its page again with GET. A view shown in answer to a POST needs a GET route at the same address, or better, a redirect to a GET page after the POST. Without one, the page is an error that says so.

For a controller view, each interaction runs the original route and its middleware again. KScript ties the block's state and actions to the current session, URL and block ID, and checks that a field or action it receives is still on the page before using it. Give each block a unique ID when you render one in a loop, such as id="profile-{$profile.id}". Keep render expressions free of side effects, because the server may evaluate them more than once, and put lasting changes in an action that checks who may make them, or in a model binding.

Set KSCRIPT_SECRET so pages keep working when the server restarts.

See the component guide for reusable component classes, more live interactions and client extensions.