Components

Introduction

A component is a reusable part of a KScript website. Give it typed inputs and render it with a tag. State, event handlers, bindings and directives such as @focus() automatically make the component live. The page runtime sends actions and updates the component.

Build your first component

Create _components/click-counter.kscript inside your site folder.

import KScript.Web

type ClickCounter extends Component {
  count: int = 0

  fn render() {
    return ```html
    <button type="button" @on-click(increment: $count)>Count is {$count}</button>
    ```
  }
}

Create index.html in the same site folder.

<h1>Counters</h1>
<click-counter />
<click-counter />

Run kscript serve from the site folder and open the address it prints. Click the first button. It reads Count is 1, and the second still reads Count is 0.

The click handler makes each counter live. Each instance gets its own root and keeps its own count between clicks. Passing <click-counter count="{5}" /> starts an instance at five.

An explicit <live> block lets you choose the root element with as, defer rendering, or make only a portion of a component live. Use explicit blocks for interactive markup directly in a page. Plain display components render without loading the live runtime.

Component styles

A component can implement the optional fn style() method to keep its stylesheet beside its render() method. The renderer validates the HTML returned by render() as a KScript page fragment.

type Badge extends Component {
  label: string

  fn render() => ```html
  <span class="note-badge">{$label}</span>
  ```

  override fn style() => ```css
  .note-badge {
    padding: 0.25rem;
  }
  ```
}

Use css for browser-ready CSS or ks.css to run it through KScript.Style. In ks.css, $vars holds the component fields. Rules follow normal CSS selector scope, so use a class specific to the component. SCSS fences can be edited in the editor. Sass compilation uses the existing stylesheet build.

Component inputs, rendering and slots

Give a component typed inputs by defining a KScript type. Save this as _components/hello-card.kscript.

import KScript.Web

type HelloCard extends Component {
  name: string

  fn render() {
    return ```html
    <p>Hello, {$name}!</p>
    ```
  }
}

Add <hello-card name="Sam" /> to index.html to render Hello, Sam!. Use kebab-case for attributes like display-name and underscores for fields like display_name. An attribute that consists of one expression passes its original type. For example, start="{3}" passes an integer.

Part How it works
Discovery KScript resolves <item-card /> to a component such as _components/item-card.kscript or _components/item-card.html.
Class contract A script component extends Component and defines fn render(). The html block it returns shows that it draws a page, so the method needs no return type.
Inputs The caller can initialize stored fields using attributes. A field initializer supplies a default. Simple field types also have built-in initial values.
Render-time values HTML can read a field as $title or $.title. Computed fields and component methods can prepare display values.
Children Put <slot /> in the template to render the caller’s child markup.
Template components HTML and Markdown components can declare <prop name="title" required />. A companion script can expose load(props: map) and other functions.

The page may render more than once during an action. Keep render methods, computed values and companion load functions free of writes. Put persistent changes in a live action or a controller. Actions can persist through KScript.Data. File and storage writes require a controller view rendered with @view() and permission from http.write_files. See template props and companion scripts for the template form and its onLoad callback.

How a live update works

  1. On the first request, KScript evaluates the <state> defaults and renders the live root. The HTML includes signed state and action arguments.
  2. On an event, the browser sends the state, the event, and any bound input values to the URL that rendered the page. The original GET route and middleware run again when the page comes from a controller.
  3. KScript verifies the route, session, block and action. It checks that the submitted action and fields are still rendered and then runs the handler.
  4. The browser applies the result to that block. Matching DOM nodes stay in place, including correctly keyed rows and independent nested live blocks.

HTML escapes ordinary { expression } output. Signed values are still visible to the browser. Read private data from the server when you need it. Authorize writes and validate input in the action even when a control is normally hidden or disabled.

State and binding

In a class component, declare each field once. This editor starts with an empty title, an unchecked box and an empty list. Its color defaults to yellow.

import KScript.Web

type NoteEditor extends Component {
  title: string
  done: bool
  descriptions: string[]
  color: color = 'yellow'

  fn render() {
    return ```html
    <label>Title <input @bind($title, on: blur)></label>
    <label><input type="checkbox" @bind($done)> Done</label>
    <button type="button" @on-click($title = ''; $done = false)>Clear</button>
    ```
  }
}

Mount it with <note-editor /> or give it an initial title with <note-editor title="First draft" />. Numbers start at zero, strings at empty text, booleans at false and collections at an empty list or map. Nullable fields start at null. Give domain types such as color, enums and records a valid initializer or pass their value from the caller. A named enum such as enum NoteColor { red, blue } limits the editor’s choices to those members.

KScript restores fields the instance changed on later actions. Fields the component only reads can pick up fresh values from the caller on each render. A browser can submit edits only for controls rendered with a matching binding. Use the current server session to authorize writes.

Put KScript behavior in directives on the opening HTML tag. For example, @bind($title, on: blur) takes a field and options, @live-disable() is a flag, and @on-click($count += 1) takes KScript statements. The IDE completes directive names after @, checks binding names, and checks each option’s value. The HTML spellings bind="$title" and on-click="$count += 1" work too. A binding names its field with $: @bind('title') and bind="title" are errors with a quick fix to @bind($title).

Every directive, shorthand, modifier and $event field is listed in Page directives.

Each directive has one spelling. These older attributes are errors with a quick fix that moves them where they now go:

Was Now
@bind-on(blur), bind-on="blur" @bind($draft, on: blur)
live-confirm="Delete this note?" @on-click(delete: $note, confirm: 'Delete this note?')
prevent-default="keydown" @on-keydown(save: $note, key: [ctrl, s], prevent: true)

Show a tag only when it’s needed, or once per item

@if and @each go on the tag itself, so a single tag doesn’t need a wrapping <if> or <for>:

<p @if($note)>{$note}</p>
<li @each($tasks, as: task, at: i)>{$i}. {$task.title}</li>
<li @each($tasks, as: task) @if(not $task.done)>{$task.title}</li>

@if($cond) is <if test="$cond"> around the tag: when it is false, the tag isn’t in the page. @show($cond) keeps the tag and hides it, so focus and scroll survive. @each($list, as: name) repeats the tag for each item, and at: i names the position, as in <for each="name" in="$list" at="i">. With both on one tag, @each runs first, so @if can read the item. Keep <if> and <for> for several tags at once.

Use <state name="…" value="…" /> at the top level of a component template or directly inside a <live> block. Read it with $name and assign it with $name = …. A normal state value survives actions on that rendered block.

Need Markup
Text editing <input @bind($draft)>
An existing map field <input @bind($draft.title)>
An edit that waits for a change event <input @bind($draft, on: change)>
An edit that waits for focus to leave <input @bind($draft, on: blur)>
A value sent with the next action <input @bind($draft, on: action)>
A value sent once typing stops <input @bind($query, debounce: 300ms)>
Spaces trimmed on the way in <input @bind($name, trim: true)>
A value read as a type (refused if it isn’t one) <input type="number" @bind($age, as: int)> (string, int, number or bool)
A checkbox <input type="checkbox" @bind($enabled)>
A radio group Give radios the same binding and each its own value.
Multiple selected values Bind <select multiple> to a list.
A shareable URL <state name="page" value="1" query="page" />
A value kept across visits in the current session <state name="filter" value="''" session="notes-filter" />
State writable only by server actions <state name="owner_id" value="$owner.id" locked />

Number defaults let normal numeric input update the state as a number. For query-backed state, use a text, number, Boolean or null value. A change updates the current history entry, and null clears the parameter. Session-backed instances that should remain independent need separate keys.

For database pagination, keep the current page in query-backed state, call ->paginate(page: $page) on a model query, and change the page from the next and previous buttons. The view can use has_more and the current page to disable those buttons at the ends.

Inputs and state with construct

By default a page can set every stored field of a component. Add a construct block to list the attributes a page may pass. Every other field is then the component’s own state, and passing it from a page is an error.

import KScript.Web

type NoteCard extends Component {
  construct({
    title: string,
    open: bool = false,
  }) {
    .heading = .title->upper()
  }

  heading: string
  clicks: int

  fn render() {
    return ```html
    <article>
      <h3>{$heading}</h3>
      <button type="button" @on-click(toggle: $open)>{$open ? 'Hide' : 'Show'}</button>
      <button type="button" @on-click(increment: $clicks)>Clicked {$clicks}</button>
    </article>
    ```
  }
}

<note-card title="Shopping" /> works, and <note-card clicks="{5}" /> is reported by kscript check. The block after the list is optional. It runs each time the page builds the component, before saved state is restored, so keep it free of writes. See constructors for the rules shared with every type.

Mark a field or method private to keep it to the component: private clicks: int, private fn tally(). A page can’t pass it, and no other code can read or call it. See private fields and methods.

Take the route’s record with @inject()

A component that shows a model’s record can take it from the route, so the page doesn’t pass it along. Give the input @inject() as its default:

// _components/post-card.kscript
import KScript.Web
import "../models/post.kscript"

type PostCard extends Component {
  construct({ post: Post = @inject() })

  fn render() => ```html
    <h2>{$post.title}</h2>
    ```
}
// routes.kscript
import KScript.Http

Routes {
  Get(path: /posts/{post}, view: 'posts/show')
}
<!-- views/posts/show.html -->
<post-card />

A request for /posts/42 finds post 42 once, or answers 404, and the component gets that record. The same works when the route calls a controller that takes the post, fn show(post: Post) => @view('posts/show'): the controller and the component share the one record.

What the page writes What the component gets
<post-card post="{$post}" /> That record. What a page passes always wins.
<post-card /> on /posts/{post} The record the route’s {post} names.
<post-card /> on a route with one Post under another name That record, for example fn show(article: Post).
<post-card /> anywhere else An error that names the missing input.
  • @inject() reads the model from the input’s type and the route parameter from the input’s name.
  • @inject(from: article) takes the route’s {article} when the path names it differently.
  • A route that holds only a number, such as /posts/{id} with fn show(id: int), has no Post to give. Name the parameter for the model, or pass the record: <post-card post="{Post->find($id)}" />. A key is never turned into a record for you, so every query is written where it runs.
  • @inject(can: read) asks the model’s policy as it takes the record, and answers 403 when the user may not read it. Any ability works: @inject(can: update).
  • On its own, @inject(Post) gives the route’s post anywhere a route is being answered, such as a page or a function a controller calls.
  • A live component finds the record again on each update, so the browser is never sent the record.
  • In a window, a document or the terminal there is no route, so the caller passes the record.

When the model has a policy, ask it as the record is taken:

// _components/post-card.kscript
import KScript.Web
import "../models/post.kscript"

type PostCard extends Component {
  construct({ post: Post = @inject(can: read) })

  fn render() => ```html
    <h2>{$post.title}</h2>
    ```
}

An @inject() that takes a model with a policy and asks nothing is a warning in the editor (KS5017).

@inject() works as the default of an input in any type, not only a component. See constructors.

Types that belong to a component

A type, enum, error or model that only one component uses can live inside that component’s block. The component file then holds everything it needs.

import KScript.Web
import KScript.Data

type CommentThread extends Component {
  model Comment extends Timestamps {
    post_id: int
    body: string(min: 1, max: 2000)
  }

  type Draft {
    body: string = ''
  }

  enum Order { newest, oldest }

  construct({ post_id: int, order: Order = 'newest' })

  draft: Draft = Draft({ })

  fn add() {
    Comment->create(post_id: .post_id, body: .draft.body)
    .draft = Draft({ })
  }

  fn render() {
    return ```html
    <section>
      <p>{Comment->where(post_id: $post_id)->count()} comments, {$order} first</p>
      <input @bind($draft.body)>
      <button type="button" @on-click($add)>Add</button>
    </section>
    ```
  }
}

A declaration inside a component belongs to that file. The component’s fields and methods use it by name, and no other file can, even one that imports the component. When a second file needs it, move it to its own file (types/draft.kscript, models/comment.kscript) and import it in both. kscript check says so when a file names a type that is inside a component it imports.

Only a component can hold declarations this way. A nested declaration doesn’t see the component’s fields, and it doesn’t count as a second type in the file, so the one type per file rule still holds. kscript db diff and kscript db status read the models inside components along with the models folder.

Components in windows and the terminal

A component isn’t tied to pages. Every place it can be drawn has its own render, and the content of each shows which one it is.

What render holds Where it draws
A returned html block A page
KScript.UI elements such as Column, Text and Button A window
echo or KScript.Terminal elements The terminal
KScript.Document elements such as Section and Paragraph, or a returned md or latex block A document

A component has at most one render for each place. The fields, construct block and methods are shared by all of them.

import KScript.UI

type NoteCard extends Component {
  construct({ title: string, body: string = '' })

  open: bool

  fn render() {
    Box(padding: 8, border: '#334155') {
      Row(gap: 8) {
        Text(weight: bold) "{.title}"
        Button(toggle: $open) "{ .open ? 'Hide' : 'Show' }"
      }
      if .open {
        Text(wrap) "{.body}"
        slot
      }
    }
  }

  fn render(terminal) {
    echo "* {.title}: {.body}"
    slot
  }
}

A script draws a component by writing it as a statement, with its inputs as arguments. Import the component’s file first.

import KScript.UI
import "components/note-card.kscript"

Window(title: 'Notes', width: 420, height: 320) {
  $notes = [
    { title: 'Milk', body: 'Two pints' },
    { title: 'Eggs', body: 'Six, free range' },
  ]

  for note in $notes {
    NoteCard(title: $note.title, body: $note.body, id: $note.title) {
      Text(color: '#94a3b8') "From the shopping list"
    }
  }
}
  • Inside Window, the component draws with its window render. Written on its own in a script, it draws with its terminal render. kscript check reports a component drawn where it has no render.
  • slot in a render draws what the caller wrote inside the component.
  • In a window each component keeps its own state between draws, so $open above belongs to one card. What the caller passes follows the caller on every draw, and every other field stays as the component left it.
  • Components drawn in a loop are told apart by their turn. Pass id: to keep a component’s state with its item when the list changes order or loses items.
  • A component that is no longer drawn is gone. It starts fresh if it is drawn again.
  • When a render holds only other components, if, for or slot, its content doesn’t show where it draws. Name the place: fn render(window), fn render(terminal) or fn render(document).

In XML the place is the surface attribute, <fn name="render" surface="terminal">, and a component is an element named after its type, <NoteCard title="Milk" />.

The editor offers the components a statement can draw where you type it, each with its inputs filled in, and completes the inputs inside the brackets. It offers each surface’s own elements only there: a window’s in a window render, a document’s in a document. After fn render( it offers window, terminal and document.

kscript make component NoteCard --for window writes a component with a fn render(window) into components/ beside the windows. --for document writes one into documents/components/, and --for terminal one into scripts/components/.

Components in documents

A component can be a part of a document: a finding, a method, a signature block. Its render holds document elements, or returns the part written in Markdown or LaTeX.

import KScript.Document

type Panel extends Component {
  construct({ heading: string })

  fn render() {
    Section(title: "{.heading}") {
      slot
    }
  }
}

type Finding extends Component {
  construct({ title: string, count: int })

  fn render() => ```md
    ## {$title}

    We saw **{$count}** of them in \( 10^{3} \) generations.
    ```
}

type Method extends Component {
  construct({ name: string, share: string })

  fn render() => ```latex
    \subsection{Method: {$name}}
    We used \textbf{$name} on {$share} of the runs.
    \begin{equation}
      N(t) = N_0 e^{rt}
    \end{equation}
    ```
}

Document(title: "Gliders", into: report) {
  Panel(heading: "Results") {
    Finding(title: "Gliders", count: 3)
    Method(name: "counting", share: "50%")
  }
}

echo $report->convert(to: markdown)
  • Inside Document, a component draws with its document render. What it adds goes where it is written, so a heading in a part that sits inside a Section becomes a subsection.
  • slot works in a render that holds elements. A block is all text, so it has nowhere to put the caller’s content.
  • A document is drawn once, so a component in it keeps no state between draws.
  • In a md block, { } holds a value, as it does in a Paragraph. Maths is written \( x^{2} \) and \[ x^{2} \], and keeps its braces.
  • In a latex block the braces are LaTeX’s. A group that holds only a value, such as {$name} or {@today()}, is filled in and keeps its braces, so \textbf{$name} is the name in bold. The value is escaped, so a %, & or _ in it is shown as text.
  • A latex block reads the LaTeX a part is usually written in:
LaTeX What it reads
Structure \section, \subsection, \subsubsection (with * for no number) and \label
Text \textbf, \textit, \emph, \texttt, \underline, \href, \url, \footnote, \cite, \ref, \\, ~, `` and '', -- and ---, and % comments
Maths $...$, \( \), \[ \], $$ $$, and the equation, equation*, displaymath, align and align* environments
Blocks itemize, enumerate, quote, quotation, center, verbatim and figure (with \includegraphics, \caption and \label)
Layout \newpage, \clearpage, \tableofcontents, \hrule, \smallskip, \medskip, \bigskip and \par

A command it doesn’t read is an error that names it, so nothing is left out without a word. kscript check and the editor report it where it is written. Write that part with document elements instead.

Actions and browser events

Handlers contain KScript statements and can call imported functions. A handler can also be a function or one of the component’s methods, which is called, so @on-click($save) runs fn save(). To flip a bool field, use the toggle: shorthand: @on-click(toggle: $open) is the same as @on-click($open = not $open). A bare bool such as @on-click($open) is an error with a quick fix to toggle:.

Handler shorthands

A handler can name what it does instead of spelling out the statement. Each shorthand is optional: the statement form keeps working. Several shorthands run left to right in one handler, such as @on-click(add: $draft, to: $tags, set: $draft, to: ''). A handler holds shorthands or statements, not both.

Shorthand Same as Field
toggle: $open open = not $open bool
call: $save fn save() of the component, or a function in a variable fn or method
call: $save, with: [$note.id] $this->save($note.id) fn or method
increment: $count count = $count + 1 number
increment: $count, by: 5 count = $count + 5 number
decrement: $count, by: count = $count - 1 number
set: $tab, to: 'notes' tab = 'notes' any
add: $draft, to: $tags tags = $tags->push($draft) list
remove: $tag, from: $tags tags = $tags->remove($tag) list
reset: $draft, reset: [$title, $done] each field back to the value it starts with (its default, or its <state> value) any
cycle: $view, through: ['list', 'grid'] the next value in the list, wrapping round (without through:, the next value of the field’s enum) any
save: $note $note->save() KScript.Data record
delete: $note $note->delete() KScript.Data record
emit: 'notes-changed' @emit_event('notes-changed') none
go: '/notes' @live_redirect('/notes') none

Modifiers go with the actions and change when or how they run. The browser applies them before it sends anything.

Modifier What it does
confirm: 'Remove this note?' Asks first, and runs only if the person says yes.
key: enter, key: [ctrl, s] Runs only for that key, with exactly those modifier keys (ctrl, alt, shift, meta). Keys are enter, escape, space, tab, up, down, left, right, a letter or a digit.
prevent: true Stops the browser’s own action, such as saving the page on ctrl+s.
debounce: 300ms Waits until the events stop for that long, then runs once.
throttle: 1s Runs at most once in that long.
once: true Runs the first time only.
self: true Runs only when the event starts on the element itself, not on something inside it.
disable: true Disables the element while its action runs.
<input @bind($query, debounce: 300ms) @on-keydown(reset: $query, key: escape)>
<button @on-click(delete: $note, confirm: 'Delete this note?', emit: 'notes-changed')>Delete</button>
<form @on-keydown(save: $note, key: [ctrl, s], prevent: true)>…</form>

In a window, the actions go straight on a button or box: Button(toggle: $open) "Details" and Button(increment: $count, by: 5) "+5". Modifiers need a browser, so a window handler that has one stops with an error saying so.

decrement: never takes a field below its min:: with stock: int(min: 0), decrement: $stock, by: 2 at 1 leaves it at 0.

kscript check and the editor check each field’s type, complete the names (and by:, to:, from: or with: after the action they go with), and show the statement a shorthand stands for on hover. After an action’s name, completion lists only the fields it fits: toggle: offers the bool fields, increment: the numbers and to: after add: the lists.

Switching classes

@class(...) adds classes to a tag’s own class while their conditions are true. Put the class first for one class per condition, or the condition first to switch several classes at once:

<li class="item" @class(done: $todo.done, 'is-late': $todo.due < @today())>{$todo.title}</li>
<li @class({
  $todo.done: ['done', 'struck'],
  [$todo.done, $open]: 'expanded',
  $todo.done or $open: 'highlight',
})>{$todo.title}</li>

A condition is a bool, or a list of bools that must all be true. With the condition first, the value is a class name or a list of them. Browser details are available as $event. A key event includes its key, code and modifiers. Pointer events include coordinates, button, pointer ID and pointer type where applicable. $event.x and $event.y are where the pointer is inside the handler’s own element, counting how far that element is scrolled, so @on-dblclick(call: $add, with: [$event.x, $event.y]) on a scrolling board gives the spot in the board’s content.

Interaction Attributes
Buttons and forms on-click, on-dblclick, on-submit
Input changes on-input, on-change
Keyboard and focus on-keydown, on-keyup, on-enter, on-escape, on-focusin, on-focusout
Dialog and pointer events on-cancel, on-close, on-pointerdown, on-pointerup, on-pointercancel
Lifecycle on-init, on-visible, on-tick with every="1s"
Other components and client code on-event and a named on-action

Use prevent: true in a handler to cancel a browser default synchronously, and confirm: 'Remove this note?' to confirm a destructive action before posting it. @show($open) keeps a tag in the page and hides it while the value is false, so focus and scroll survive, and @live-disable(while: $saving) disables a control while a condition holds as well as while an action runs. An action can call @live_redirect('/notes') for a same-site redirect or @skip_render() to save state without updating the current HTML.

Events between components

Emit an event from an action with @emit_event('notes-changed', data: $note.id, target: 'summary'). Omit the target to broadcast. Each receiving block runs its first matching listener, such as on-event="$latest = $event.data" event-name="notes-changed". The handler can read $event.name, $event.data and $event.source.

Drag, drop and sorting

To drag one element onto another, put @drag(copy: true, value: $item.id) on the source and on-drop on the destination (see the next section). The action reads $event.drag_value, and $event.x and $event.y give the drop point inside the destination. @drop-class('over') on the destination adds the class while something it takes is dragged over it.

Move an element with @drag

@drag() lets the visitor move an absolutely positioned element with the pointer. When the drag ends, the element’s on-dragend handler runs with where it landed, so the action can save it:

<article class="note" style="left: {$note.x}px; top: {$note.y}px; z-index: {$note.z}"
  @drag(front: true, skip: '.thumb')
  @on-dragend(call: $move, with: [$event.x, $event.y, $event.z, $event.vx])>
  …
</article>
$event field Value
x, y The element’s new left and top, in pixels inside its positioned parent.
vx, vy How fast it was moving when it was let go, in pixels per frame.
moved false when the press was a click. The handler still runs, so a click can bring an element to the front.
z With front: true, the z-index it was raised to above its siblings.
Option What it does
front: true Raises the element above the other @drag elements in its positioned parent.
scroll: '.surface' The container that scrolls when the pointer nears its edges. Defaults to the nearest scrolling ancestor.
skip: '.thumb' Presses on these belong to them, not to dragging. Fields, buttons, links and labels are always skipped.
threshold: 6 How far the pointer moves before a press becomes a drag. Defaults to 4 pixels, so a click stays a click.
copy: true Drags a ghost copy instead of the element, onto an on-drop target. A plain click still runs the element’s on-click.
value: $color With copy:, what the drop handler reads as $event.drag_value.
ghost: 'note-ghost' With copy:, the classes of the ghost. Its top centre follows the pointer. Defaults to the element’s own classes.

While it moves, the element (or the ghost) has the dragging class and the CSS variables --drag-vx, --drag-vy and --drag-speed, so a stylesheet can tilt it with the movement. After a drop it has drag-settled until its animation ends.

.note.dragging {
  --tilt-y: clamp(-28deg, calc(var(--drag-vx) * 1.6deg), 28deg);
  transform: perspective(900px) rotateY(var(--tilt-y));
}
.note.drag-settled { animation: settle 0.5s ease-out; }

A tray item that drops a new note on a board uses copy::

<button type="button" class="pad" @drag(copy: true, value: $color, ghost: "note-ghost c-$color") @on-click($this->add($color))></button>
<div class="surface" @on-drop(call: $add, with: [$event.drag_value, $event.x, $event.y]) @drop-class('over')>…</div>

To take files dropped on an element, give it @drop-files('upload') and put a live-upload file input named upload inside it. Dropped files go through that input and its on-change action, the same as files picked by hand:

<article class="note" @drop-files('upload') @drop-class('file-over')>
  <label>Attach <input type="file" name="upload" multiple hidden live-upload @on-change($this->attach($event.files.upload))></label>
</article>

kscript check reports a @drop-files name with no matching live-upload input inside the element.

For sortable siblings, give each item a unique sort-item="{$item.id}" and put on-sort on their container. The handler gets the item ID, the old and new zero-based indexes, and the proposed order. Users can drag an item or focus it and use Alt+Up or Alt+Down. Set sort-axis="horizontal" for left-to-right lists. Validate the item IDs before persisting a new order.

Forms, uploads and loading feedback

A form with on-submit can send several bindings in one action. Paste this block into index.html, enter a name, and click Greet to see the result. The binding is sent when you submit the form.

<live id="greeting-form">
  <state name="name" value="''" />
  <state name="message" value="''" />
  <form on-submit="$message = 'Hello, ' + $name + '!'">
    <label>Name <input @bind($name, on: action) required></label>
    <button live-disable>Greet</button>
  </form>
  <p role="status">{$message}</p>
</live>

Use HTML controls such as required for immediate feedback and KScript types or rules for server validation. To save to a database, use model forms.

Attribute Browser behavior
live-loading Shows the element while the action is pending.
live-disable Disables the control until the request completes.
live-dirty Shows the element when a bound value has unsent edits. Give it a binding name to watch one field.
live-offline Shows the element while the browser reports that it is offline.
live-error Shows feedback when the action fails.
live-cloak Hides markup until the live runtime starts.

Use live-upload on a named file input. The upload travels with its on-change action or its form’s on-submit action. For an input named attachment, $event.files.attachment contains file entries with name, type, size and base64 bytes. The request accepts up to 8 MiB of files. Validate content and permissions before saving. Mark the file input live-replace to clear its selection on the next redraw.

Use @live_download('report.txt', bytes: $report->to_base64()) to offer bytes generated by an action as a file.

Focus, growing text and pending classes

Three directives cover browser behaviour that would otherwise need a script:

Directive What it does
@focus() Gives the element focus when it appears.
@focus($t.id == $new_todo) Gives the element focus each time its condition turns true, such as the row an action just added.
@autogrow() Makes a <textarea> as tall as its text. It uses CSS field-sizing where the browser has it and resizes on input where it doesn’t.
@pending('saving') Adds the class to the element while any of the component’s actions runs, and takes it off when the action finishes or fails.
@pending('crumple', for: 'delete') Adds the class only while an action that runs delete is in flight. for: takes a method name or a list, such as for: ['save', 'delete'].
<article class="note" @pending('crumple', for: 'delete')>
  <textarea @autogrow() @on-change($this->edit($event.value))>{$note.body}</textarea>
  <for each="t" in="$note.todos">
    <input value="{$t.text}" @focus($t.id == $focus_todo)>
  </for>
  <button type="button" @on-click($delete)>Delete</button>
</article>

A handler runs delete when it is $delete, call: $delete or a statement that calls $this->delete(...). kscript check reports a for: method that no handler runs, a condition that isn’t a bool and @autogrow() on anything but a textarea. The HTML spellings are focus, focus="{$cond}", autogrow and pending="'saving'".

@pending is the class form of live-loading, which shows and hides an element. Use it for an animation while an action runs, and wrap the animation in @media (prefers-reduced-motion: no-preference) in your stylesheet so visitors who ask for less motion don’t get it.

Nesting, identity and lazy rendering

A live component can contain an independent child component. A parent update keeps the child’s DOM and state, and a child action uses the signed ancestor state to reconstruct the context it was rendered in. Changing the child’s ID mounts a new instance. To update a mounted child from the parent, send it an event.

  • For a list of components that can reorder or change membership, pass each one a unique ID such as <row-editor live-id="editor-{$row.id}" record="{$row}" />. For an explicit <live> block, set its id attribute.
  • Use live-key="{$item.id}" for repeated siblings whose DOM identity should survive a reorder.
  • Use live-ignore for a browser-owned widget. Keep KScript’s bound controls and action handlers outside that widget.
  • Use live-replace to build a fresh node on each redraw.
  • Add lazy to initialize and render the block when it enters the viewport, or defer to load just after the document is ready. The optional direct <placeholder> child is rendered before the block mounts.
<live id="summary" lazy>
  <placeholder><p role="status">Loading summary…</p></placeholder>
  <state name="shown" value="true" />
  <p @if($shown)>Ready</p>
</live>

In-page navigation

Add live-navigate to a same-site link to fetch the destination page and replace the document body in place. Back and Forward restore the page and its scroll location. Links keep their ordinary behavior for modified clicks, downloads, other origins, and page policies that require a new document.

<a href="/notes" live-navigate>Notes</a>

The browser dispatches kscript:navigating before an in-page visit and kscript:navigated after it. Call preventDefault() on the first event to cancel the visit. Body scripts run on subsequent visits unless marked live-navigate-once. Optional JavaScript can also call KScriptLive.navigate('/notes').

Stream an action’s output

Paste this block into index.html and click Run. The action sends text to the element named progress. In a longer action, each chunk can appear before the action finishes.

<live id="stream-demo">
  <p live-stream="progress" role="status"></p>
  <button on-click="@stream('progress', 'Ready'); @skip_render()">Run</button>
</live>

Call @stream() more than once to send several chunks. The target must be rendered in the same component. Chunks append by default. Use mode: replace for a progress label, and html: true only with markup you trust. A successful action normally replaces the preview with its final rendered fragment. Use @skip_render() to keep the streamed output. A failed action restores the pre-stream content. Actions that change session cookies, such as signing in or out, need a regular response.

Portals

A portal moves its template contents to a matching HTML container outside the live component. This lets overlays escape local clipping while their events and bindings still belong to the source component. The portal disappears when its template disappears or when the page changes. Include a form in the template with its fields, or associate the fields with an external form using HTML’s form attribute.

<div id="overlay-root"></div>
<live id="editor">
  <state name="open" value="true" />
  <if test="$open">
    <template live-portal="#overlay-root">
      <aside><button on-click="$open = false">Close</button></aside>
    </template>
  </if>
</live>

Client-side extensions

For behaviour KScript has no directive for, register a client directive. This one selects a field’s text when it gets focus. Save this as _components/search-field.html.

<label>Search <input type="search" value="notes" live-use-select></label>

Add the component and its directive to index.html.

<search-field />
<script>
document.addEventListener("kscript:init", () => {
  KScriptLive.directive("select", ({ element, signal }) => {
    element.addEventListener("focus", () => element.select(), { signal });
  });
}, { once: true });
</script>

Reload the page and click the field. Its text is selected, and live-use-select gives its component a live root automatically. The runtime fires kscript:init once per browser document. Registrations survive in-page navigation. The directive receives its element, owning component, attribute value, and an abort signal. It can return a cleanup function. The runtime aborts and cleans up when the element, owning component, or directive value changes.

To mount a display component so a JavaScript lifecycle hook can observe it, give the invocation a live-id, such as <hello-card name="Sam" live-id="welcome" />.

KScriptLive.on(name, callback) subscribes to mount, unmount, request, response, stream, morph, commit, error, navigate:leave, or navigate. It returns an unsubscribe function. Component hooks include the owning element as component. The request hook also receives url, event and signal. The response hook receives status, streamed and the HTTP response. A stream hook receives element and the incoming frame. Use commit to react after the DOM is updated.

Register a browser-only action using KScriptLive.action('name', callback) and invoke it from live-client="name". The callback receives component, element, the browser event, and a call(name, payload) function for that component.

Give a server action a name in the component’s HTML. The on-action handler receives the payload as $event.data.

<span hidden @live-action('save') @on-action(@save($event.data))></span>

Call KScriptLive.call(component, 'save', payload) with the component element or its live ID. The server checks that the action belongs to the rendered component before it runs. The HTML attribute live-action="save" exposes the same action.

Test a component

Run kscript check . from the site folder to catch invalid declarations and missing props. Put parsing, validation, and persistence logic in functions that can also be exercised by kscript test. A browser test should serve the project, open an actual page, perform the interaction, and assert what the visitor sees.

For a streamed action, wait for an intermediate value while the request is still pending, then assert the final state and run another action. For a portal, exercise its controls at the destination, trigger a redraw, and verify it disappears when the source is removed. For in-page navigation, test Back and Forward after query and hash changes. Keep a test for a rejected action or unauthorized field when the component writes data.

Troubleshoot

Symptom Check
A tag renders without its content Check the component filename, the page’s component folder and the diagnostic from kscript check.
An input keeps its old value Declare its binding in the block’s state. A dotted binding needs an existing map field. Check whether its on: option is waiting for a change, blur, or action.
A repeated block updates the wrong row Use a stable live ID per instance and a stable live-key for reordered siblings.
A live request expires The registered route, session or visible action may have changed. Refresh the page. Set a stable KSCRIPT_SECRET if sessions must survive server restarts.
A portal has no visible content Check that the selector matches an HTML container outside any live block. The template stays inert while the destination is missing.
Stream output arrives only at the end Start the action inside a live block, keep the target visible, and ensure intermediaries can forward chunks without buffering the whole response.
A streamed preview disappears after success The normal final fragment is authoritative. Render the final content from state or use @skip_render() to keep the streamed output.
A navigation opens a new browser document Check that the link is opted in and stays on the same origin. Destination policies and certain document features, such as <base>, require a native visit.
A custom directive appears to run twice A changed attribute value or replaced element remounts the directive. Use its abort signal or returned cleanup to release listeners. Keep app-wide registrations in a script that runs once.

Coming from Livewire 4

KScript uses its own component syntax. These are the common workflows and their equivalents.

Livewire 4 KScript
Component template and properties extends Component, typed fields and <state>
wire:model @bind($field, on: …)
wire:click and wire:submit on-click and on-submit
Dispatch and listeners @emit_event() and on-event
wire:navigate live-navigate
wire:stream live-stream and @stream()
@teleport <template live-portal="…">
JavaScript hooks, directives and component calls KScriptLive.on(), KScriptLive.directive() and KScriptLive.call()

For the surrounding site, see Web pages. For middleware, ownership and controller contracts, see Routes and APIs. In an MCP client, ask read_doc for the components page.

Edit this page on GitHub