KScript docs
EN

Components

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.

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

Add the component and its directive to index.html.

HTML page
<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.

HTML page
<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.

Edit this page on GitHub