KScript docs
EN

Components

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 package="KScript.Web" />

<type name="NoteEditor" extends="Component">
  <field name="title" type="string" />
  <field name="done" type="bool" />
  <field name="descriptions" type="string[]" />
  <field name="color" type="color" default="'yellow'" />

  <fn name="render">
    <return value="```html
        &lt;label>Title &lt;input @bind($title, on: blur)>&lt;/label>
        &lt;label>&lt;input type=&quot;checkbox&quot; @bind($done)> Done&lt;/label>
        &lt;button type=&quot;button&quot; @on-click($title = ''; $done = false)>Clear&lt;/button>
        ```" />
  </fn>
</type>
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)

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>:

HTML page
<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)>
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 package="KScript.Web" />

<type name="NoteCard" extends="Component">
  <construct>
    <field name="title" type="string" />
    <field name="open" type="bool" default="false" />
    <do>.heading = .title->upper()</do>
  </construct>

  <field name="heading" type="string" />
  <field name="clicks" type="int" />

  <fn name="render">
    <return value="```html
        &lt;article>
          &lt;h3>{$heading}&lt;/h3>
          &lt;button type=&quot;button&quot; @on-click(toggle: $open)>{$open ? 'Hide' : 'Show'}&lt;/button>
          &lt;button type=&quot;button&quot; @on-click(increment: $clicks)>Clicked {$clicks}&lt;/button>
        &lt;/article>
        ```" />
  </fn>
</type>
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 package="KScript.Web" />
<import path="../models/post.kscript" />

<type name="PostCard" extends="Component">
  <construct>
    <field name="post" type="Post" default="@inject()" />
  </construct>

  <fn name="render" value="```html
      &lt;h2>{$post.title}&lt;/h2>
      ```" />
</type>
// _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 -->
<KScript.Routes>
  <Get path="/posts/{post}" view="posts/show" />
</KScript.Routes>
// routes.kscript
import KScript.Http

Routes {
  Get(path: /posts/{post}, view: 'posts/show')
}
HTML page
<!-- 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 package="KScript.Web" />
<import path="../models/post.kscript" />

<type name="PostCard" extends="Component">
  <construct>
    <field name="post" type="Post" default="@inject(can: read)" />
  </construct>

  <fn name="render" value="```html
      &lt;h2>{$post.title}&lt;/h2>
      ```" />
</type>
// _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 package="KScript.Web" />
<import package="KScript.Data" />

<type name="CommentThread" extends="Component">
  <model name="Comment" with="Timestamps">
    <field name="post_id" type="int" />
    <field name="body" type="string(min: 1, max: 2000)" />
  </model>

  <type name="Draft">
    <field name="body" type="string" default="''" />
  </type>

  <enum name="Order" values="newest, oldest" />

  <construct>
    <field name="post_id" type="int" />
    <field name="order" type="Order" default="'newest'" />
  </construct>

  <field name="draft" type="Draft" default="Draft({ })" />

  <fn name="add">
    <do>Comment->create(post_id: .post_id, body: .draft.body)</do>
    <do>.draft = Draft({ })</do>
  </fn>

  <fn name="render">
    <return value="```html
        &lt;section>
          &lt;p>{Comment->where(post_id: $post_id)->count()} comments, {$order} first&lt;/p>
          &lt;input @bind($draft.body)>
          &lt;button type=&quot;button&quot; @on-click($add)>Add&lt;/button>
        &lt;/section>
        ```" />
  </fn>
</type>
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.