Web pages: kscript serve
Introduction
kscript serve runs a folder as a website. Every .html and .md page in it is a template: KScript elements sit directly in the HTML, { expression } works in text and attributes, and the visitor gets plain HTML. There is no build step, and no JavaScript to write.
To get started, serve a folder and open it in a browser:
kscript serve "Example Sites/team" --port 8080 # then open http://localhost:8080
Here is a page that reads a JSON file and lists the people in it:
<!-- people.html -->
<let name="people" value="@read_json(./data/people.json)" />
<let name="min" value="($request.query.min_age ?? '0')->to_number(default: 0)" />
<layout path="_layout.html" title="People">
<h1>People aged {$min} and over</h1>
<ul>
<for each="p" in="$people |> filter(fn(p) => $p.age ge $min) |> sort(by: .name)">
<li class="{ $p.age ge 65 ? 'senior' : '' }">
<a href="/people/{$p.id}">{$p.name}</a> ({$p.age})
</li>
</for>
<else>
<li>Nobody matches.</li>
</else>
</ul>
</layout>
See Example Sites/team for a complete site with a layout, a component, a Markdown page, a dynamic route and a JSON endpoint. For controllers, JSON APIs and middleware, add a route file: see Routes, controllers and middleware. Routes are matched before pages, and anything they don’t match is served as described here.
Live reload
During development, open the site in a browser and save a page, component, script, stylesheet or asset. Open HTML pages reload by themselves. kscript serve --no-reload turns that off. Production and compiled sites serve pages without the reload script.
Each request runs your scripts fresh, so a save shows up on the next request without restarting the server. The server doesn’t parse every script again for that, though: it parses each script once and keeps the result, and parses a script again only when its text changes. When you save one controller, that controller is the only file parsed again. The pages and route files that import it pick up the new version on the next request. The route table is built again when a route file changes, or any script or file the routes reach does, such as a controller or a config file.
For a development site in a container, add a Compose file and run kscript serve, which then serves from Docker. --no-docker serves on the host instead, and serve.docker in kscript.json makes Docker the default. See Running the development site in Docker.
Templates
Displaying values
{ value } puts a value into the page, HTML-escaped (Markdown-escaped in .md pages). {! value } puts in trusted HTML as it is, and {{ and }} are literal braces:
<p>Hello, {$user.name}</p>
<div>{! $post.html }</div>
<code>{{ not a value }}</code>
An attribute that is exactly { value } is left out when the value is false or null, so checked="{$done}" just works.
Expressions are KScript’s: + - * / %, == and != (loose, so '3' == 3), === and !== (strict: type and value), ??, ?., a ? b : c, in, lists, maps, $p.name, $list[0], ->method(), |> and fn(x) => …. In attributes, use the words lt, le, gt, ge, and, or and not, since XML can’t hold a raw < or && there.
Variables
<let> declares a variable in the current block, and <set> changes one. <do> runs a few statements:
<let name="total" value="0" />
<let>$count = 3</let>
<set name="total" value="$total + 10" />
<set>$count += 1</set>
<do>$count += 1; $total = $total + 5</do>
Conditionals
<if>, <elif> and <else> pick a branch. <match> picks one <case>, with <default> for anything else:
<if test="$cart->count() == 0">
<p>Your cart is empty.</p>
</if>
<elif test="$cart->count() == 1">
<p>One item.</p>
</elif>
<else>
<p>{$cart->count()} items.</p>
</else>
<match value="$order.status">
<case is="'paid', 'shipped'">Thanks for your order.</case>
<case when="$it == 'refunded'">Refunded.</case>
<default>Waiting for payment.</default>
</match>
Loops
<for> loops over a list, or over a map’s keys and values. at names the position, and $loop.index and $loop.first are set too. An <else> straight after a <for> runs when there was nothing to loop over:
<ol>
<for each="task" in="$tasks" at="i">
<li>{$i + 1}. {$task.title}</li>
</for>
<else>
<li>No tasks.</li>
</else>
</ol>
<for each="key, value" in="$settings">
<p>{$key}: {$value}</p>
</for>
<while test> loops while its test is true, and stops after 100,000 runs.
Layouts
<layout> wraps the page in a layout. The layout puts the page where its <slot /> is, and the layout tag’s other attributes become variables in it:
<!-- _layout.html -->
<html>
<head><title>{$title}</title></head>
<body><slot /></body>
</html>
<!-- about.html -->
<layout path="_layout.html" title="About us">
<h1>About us</h1>
</layout>
Components and includes
A tag such as <my-card> renders the component in _components/my-card.kscript, with <slot /> for its children. The tag matches the component’s file name. <include> puts another template in place:
<my-card user="{$u}">Joined this year</my-card>
<include path="_footer.html" />
Components are in the components guide.
Markdown
<markdown> renders Markdown, with { } values escaped. A .md page may start with --- front matter, such as title: About and layout: _layout.html, and its keys become variables. Inline code and fenced code blocks keep their contents as written:
---
title: About
layout: _layout.html
---
# About {$title}
This page was written in Markdown.
Sending a different response
<respond> sends something other than the page: JSON, another status such as a 404, a redirect, another content type or extra headers:
<if test="$user == null">
<respond redirect="/sign-in" />
</if>
<respond status="404" />
A status is from 100 to 999, and header values are plain ASCII without line breaks. Anything else is an error page that says which value was wrong, so a visitor’s text put in a header can’t add a header of its own. A redirect to an address with other characters, such as /café, is sent percent-encoded.
Routing
The file a URL serves comes from its path. /people serves people.html, people.md or people/index.html. A folder or file name in brackets matches any value, so /people/42 can match people/[id].html, where the value is $request.params.id.
Files and folders whose names start with _ or ., and KScript sources (.kscript, .ks.xml and any other .xml), are never served. _404.html is used for missing pages, and may use layouts, components and live blocks like any page.
The request
$request holds the request a page is answering: method, scheme, path, url, query, form, headers, cookies, params and body. For https://example.com/people?page=2, $request.scheme is https, $request.path is /people and $request.url is /people?page=2:
<let name="page" value="($request.query.page ?? '1')->to_number(default: 1)" />
<p>Page {$page} of the people list, at {$request.path}</p>
A value in query or form is text. A name sent more than once (?tag=a&tag=b, or a group of checkboxes) is a list of texts. For an ordinary form post, body is the text as sent (name=Ada&tag=a). For a form with files it is empty. A page under a locale prefix also gets $request.locale.
KScript in pages
Pages run on the same interpreter as scripts, so every KScript.Core command and method works in them. Pages also get KScript.IO, KScript.Markdown and KScript.Web without importing them: @read_json, @read_text, @read_markdown (which gives html, title and meta), @files, @exists and @markdown. Import other packages at the top of the page, as in a script:
<import package="KScript.Math" as="math" />
<p>The square root of 2 is { @math.sqrt(2) }</p>
<import path> at the top of a page gives it a script’s top-level functions and const values. as="text" (then @text.shout(...)) and names="shout" work as they do in scripts:
<import path="lib/text.kscript" />
<h1>{ @shout('welcome') }</h1>
Files, errors and safety
Paths start in the site folder and can’t leave it, and rendering a page can only read files. A live action in a controller view may write when http.write_files allows it.
Errors show the file and line, and endless loops and runaway recursion are stopped. In the production environment (kscript serve --env production), a visitor gets a plain 500 page instead, and the message, file and line go to the server’s log only.
Template props and component scripts
A layout or component may declare the inputs it takes with <prop>, at its top level:
<!-- _layout.html -->
<prop name="page-title" required />
<prop name="subtitle" />
<h1>{$page_title}</h1>
<slot />
Call the layout with <layout path="_layout.html" page-title="Home">…</layout>. The editor suggests the declared props, and reports a missing required value for a known layout path. Rendering checks required props even for a layout path worked out while the page runs. Markdown pages pass layout props in front matter. An optional prop is null when it is left out.
Component scripts
Put note.kscript next to _components/note.html, and the component’s template can call the script’s functions. An optional load(props: map) function receives the props and gives the template $data. The template may also read $props, and each prop as its own variable:
fn load(props: map) => { title: $props.title->trim() }
fn heading(title: string) => $title->upper()
<!-- _components/note.html -->
<prop name="title" required />
<article>{@heading($data.title)}<slot /></article>
The page using the component may pass onLoad, a callback that runs on the server with the result of load (or null when the component has no load):
<Note title="A note" onLoad={fn(data) => @note_loaded($data)}>
<p>Content supplied by the page</p>
</Note>
Loading may run again when the component renders, including during live redraws, so keep render-time callbacks free of lasting writes.
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:
<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:
<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:
<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: true cancels the browser’s own action before the request: @on-keydown(call: $save, key: [ctrl, s], prevent: true).
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:
<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:
<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: true, 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:
<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.
Model forms
kscript make component may write a component for an existing model, or a model and its component together:
kscript make component NoteCard --model Note --fields title,body # a component that shows a Note
kscript make model Note --fields "title: string, body: string" --component # a model, and a component for it
The first command writes _components/note-card.kscript. The component takes the row as an input named after its model, so a page renders it with <note-card note="{$note}" />:
import KScript.Web
import "../models/note.kscript"
type NoteCard extends Component {
construct({ note: Note })
fn render() => ```html
<section class="note-card">
<p>{$note.title}</p>
<p>{$note.body}</p>
<slot />
</section>
```
}
The tag’s attributes fill the component’s inputs, which render() reads as $note. Computed fields, local constants, and methods called with $this->method() are there for the HTML too. The editor completes props on the tag, and model fields inside the fence. A Component needs fn render().
Add --inject to take the record from the route instead, so the page writes <note-card /> on /notes/{note}. The component asks the model’s policy as it takes the record: construct({ note: Note = @inject(can: read) }). Give another ability with --inject update. See Take the route’s record with @inject().
Saving edits to a model
A component may save edits straight to a KScript.Data model. Declare the fields that may be written, and who owns the row, once in the web routes. Here a Profile model holds a user_id and a bio:
import KScript.Http
Routes {
ModelUpdate(name: edit_profile, model: Profile, owner: user_id, fields: [bio])
}
Then generate the editor:
kscript make component ProfileEditor --model-update edit_profile # a form that saves the bio
Pass the owned row as <profile-editor profile="{$profile}" />. A protected GET controller loads the signed-in user’s row and passes it to the page, which renders <profile-editor profile="{$data.profile}" />. The auth sample includes this profile editor and its migration. For a component with its own interactive state, start with kscript make component OrderDetails --live.
The generated form saves when Save is clicked. Typing leaves the database alone until then. In a live block, Save updates the model in place and a message confirms it. A form outside a live block posts as usual and redirects back, so it works with JavaScript turned off.
Add --autosave to save when typing pauses, after 500 ms, or choose a delay with autosave="750ms". Save still sends pending edits at once. The runtime sends only edited fields, waits for each save to finish, and keeps the draft when validation fails.
How saves are checked
KScript writes the POST handler and includes a CSRF token. Every save checks the session and token, matches the row’s user_id with the signed-in user’s id, and validates the fields against the model and the binding’s list of fields. Use owner: id when the row’s key is the account id, and add route middleware to ModelUpdate for permissions of your own. Check ownership when reading the row too. Keep SQLite files of your own outside the public site, or in a folder whose name starts with _.
Docs while you work
kscript serve --with-docs also serves these docs on localhost, next to the site, with a page about your project at /project:
kscript serve --with-docs # the site, and the docs with a page about your project
The project page is built from the project itself, and is rebuilt when a script changes. It shows how code is written here (the project’s format, standard, layout and lint rules, the packages every script gets, and the folders kscript make puts files in), the routes kscript routes lists, and every function, type and constant each script declares at its top level, with its /// doc comment. Search finds them too.
The docs listen on localhost only, even when the site is served with --host 0.0.0.0, because their examples run code. --docs-port 4190 picks their port (4180, or a free one, otherwise). To have them every time, set "docs": true in the serve section of kscript.json, and "docs_port" to pick the port. --no-docs turns them off for one run. Compiled programs never serve the docs, and neither does kscript serve in the production environment.
For the same docs as a file, run kscript docs --project. It writes .kscript/docs/project.md, Markdown that reads well in an editor, on GitHub or in a code review. From then on, kscript watch, kscript serve and saving a script in the editor keep it up to date. Delete .kscript/docs to stop.