Zap
Documentation / Frontend

Litewire

Litewire is Zap's first-party reactive UI layer: an inherent part of the framework's frontend toolkit, much like Livewire's role in Laravel applications. Litewire runs in the browser and talks to ordinary HTTP endpoints, so it can also be used with any PHP or JavaScript framework—or without a backend framework at all.

How Litewire works

Litewire enhances HTML in the browser. Its lw-* attributes connect elements to JavaScript modules or HTTP requests; its lw:* attributes provide local reactive state, events, bindings, and rendering. For server-backed interactions, your endpoint returns an HTML fragment and Litewire swaps that fragment into the page.

Litewire is not coupled to Blade, PHP, Laravel, or a particular router. In Zap, its script is registered as a default asset in config/js.php, and the shared layout supplies the base URL and CSRF meta token. In another stack, include litewire.js, provide the expected meta tags where needed, and implement endpoints that return HTML.

Use the local state directives for browser-only interactions. Use request directives when the server must validate, authorize, persist, or calculate something. They work together; neither requires a single-page application.

Setup and a first reactive widget

In Zap, Litewire is loaded by the shared layout. For another application, include the browser module as a JavaScript module:

<script type="module" src="/assets/js/litewire.js"></script>

The simplest example keeps state on an element. Updating a top-level property rerenders its Litewire bindings:

<section lw:state="{ count: 0 }">
 <button type="button" lw:click="count++">Add one</button>
 <output lw:text="count"></output>
</section>
Count:

A lw:state value is a JavaScript object expression. Its top-level properties are reactive when assigned or deleted. Keep expressions and initial state under your control; they are evaluated as JavaScript and are not a place for user-provided code. Nested object/array mutations do not pass through the root proxy; replace the top-level property to trigger a rerender.

HTTP request directives: lw-get, lw-post, lw-put, lw-delete

Add a request attribute to a button, link-like element, or form. Buttons and other elements default to a click trigger; forms default to submit. A request with lw-trigger="load" runs when Litewire initializes the element. lw-trigger can also name another DOM event.

<button type="button" lw-get="/products/fragment" lw-target="#product-list">
 Refresh products
</button>

<form lw-post="/comments" lw-target="#comments" lw-swap="prepend">
 <textarea name="body" required></textarea>
 <button type="submit">Add comment</button>
</form>

<div id="product-list"></div>
<div id="comments"></div>

GET form values become URL query parameters. For POST, PUT, and DELETE, Litewire sends the nearest form as FormData when one exists. Non-GET requests include the X-CSRF-TOKEN header when the page contains <meta name="csrf-token">. Successful responses are treated as HTML, not decoded as JSON.

Zap also registers an optional auto-CSRF plugin for ordinary non-GET HTML forms. It skips forms handled by Litewire; Litewire requests use the header above instead.

Litewire sends non-GET form data as FormData. PHP does not fill $_POST for PUT and DELETE requests by default, so make sure the backend parses those request bodies or use a request format your backend supports.

Request targets, swaps, loading, and history

  • lw-target="#selector" chooses the element that receives the response. Without it, the requesting element is the target.
  • lw-swap supports innerHTML (default), outerHTML, prepend, and append.
  • lw-indicator=".selector" selects loading indicators. Without it, Litewire finds descendant elements with class litewire-indicator. The requesting element and indicators receive litewire-request while the request is pending.
  • lw-push-url="true" pushes the request URL (including its query string) into browser history; a URL value pushes that URL instead. false or no attribute leaves history unchanged. Back/forward navigation restores the stored fragment when possible. The implemented attribute is lw-push-url; there is no separate lw-push directive.
  • Litewire checks response.ok, emits request lifecycle events, and logs request errors to the console. It does not interpret arbitrary JSON response bodies.
<button
 type="button"
 lw-get="/search/results"
 lw-target="#search-results"
 lw-swap="innerHTML"
 lw-indicator="#search-spinner"
 lw-push-url="true">
 Search
</button>
<span id="search-spinner" class="docs-litewire-spinner">Loading…</span>
<div id="search-results"></div>
<!-- In your stylesheet: .docs-litewire-spinner { display: none; } -->
<!-- In your stylesheet: .docs-litewire-spinner.litewire-request { display: inline; } -->

Litewire adds and removes its loading class; visibility and presentation are controlled by your CSS.

The server must return the fragment expected by the target. For example, a Zap controller can return a partial HTML response with $this->html($markup) or a dedicated view response. Validate request data and authorize the operation on the server; a hidden button is not access control.

Reactive state and rendering

lw:state and lw:text

State belongs to the nearest ancestor with lw:state. Without a local state root, expressions read Litewire's shared model store. Calling setModel() updates direct text bindings and global class/loop bindings; use a local state root when several binding types need to update together. lw:text evaluates an expression and writes the result using textContent, which avoids treating its value as HTML.

<div lw:state="{ firstName: 'Ada', lastName: 'Lovelace' }">
 <button type="button" lw:click="firstName = 'Grace'">Change name</button>
 <p>Name: <span lw:text="firstName + ' ' + lastName"></span></p>
</div>

lw:show and lw:class

lw:show toggles the element's native hidden property. lw:class expects an object whose enabled keys are class names; multiple class names can be grouped in one key.

<div lw:state="{ open: false, saving: false }">
 <button type="button" lw:click="open = !open">Toggle details</button>
 <p lw:show="open">These details are shown while open is true.</p>
 <span lw:class="{ 'is-saving muted': saving, ready: !saving }">
 Status
 </span>
</div>

lw:for and template loops

Use lw:for on a <template>. The expression accepts item of iterable, item in iterable, or (item, index) of iterable. Each iteration exposes $index and the optional index variable.

<ul lw:state="{ names: ['Ada', 'Grace'] }">
 <template lw:for="(name, position) of names">
 <li><span lw:text="position + 1"></span>. <span lw:text="name"></span></li>
 </template>
</ul>

The iterable must be iterable (for example, an array). Litewire recreates the rendered loop nodes when the owning state rerenders; it does not preserve per-row DOM identity like a keyed virtual-DOM renderer.

Form models: lw:model

lw:model initializes from the control and updates on its input event. lw:model.live is an input-event alias; lw:model.change updates on change, and lw:model.blur updates on blur. Inside a lw:state root, the model value becomes that root's property. Outside one, it is stored in Litewire's global models.

<div lw:state="{ query: '' }">
 <label>Search
 <input type="search" lw:model="query">
 </label>
 <p>You entered: <span lw:text="query"></span></p>
</div>

<input type="text" lw:model.change="#preview">
<output id="preview"></output>

Checkbox models are booleans. A radio model uses the checked radio's value. A model name beginning with # or . is treated as a CSS selector instead: matching form controls receive a value, while other matching elements receive text content and a litewire:model event.

The global API exposes window.litewire.getModel(name) and window.litewire.setModel(name, value). Changes dispatch a litewire:model custom event; local state changes dispatch litewire:render from the state root.

Event directives: lw:click and friends

Event expressions run in the current state scope. Supported events are click, input, change, submit, keydown, keyup, focus, and blur. The expression scope provides $event, $el, $value, $state, and $wire; loops also provide $index and their declared item/index variables.

<form lw:state="{ query: '' }" lw:submit.prevent="submitSearch($event)">
 <input lw:model="query" lw:keydown="$event.key === 'Enter' && submitSearch($event)">
 <button type="submit">Search</button>
</form>

<div lw:state="{ showHelp: false }">
 <button type="button" lw:click="showHelp = true">Help</button>
 <aside lw:show="showHelp" lw:click.outside="showHelp = false">Help text</aside>
</div>

Event modifiers

  • .prevent calls preventDefault(); .stop stops propagation; .self only runs when the event target is the element itself; .once runs once.
  • .outside listens on the document and runs only when the event occurs outside the element.
  • .window and .document attach the listener to those global targets.
  • .debounce and .throttle rate-limit calls. Add a delay such as .debounce.300ms or .throttle.100ms; the default delay is 250 ms.
  • .capture and .passive use the corresponding DOM listener options. A passive listener should not call preventDefault().

Modifiers can be combined, for example lw:click.outside.once="closePanel()". Event expressions are evaluated as JavaScript, so keep them in trusted application templates.

JavaScript widgets with lw-component

Litewire can dynamically import an ES module and mount its default export as a class or function. Components receive the target DOM element and a plain object made from the source element's data-* attributes. Put browser-loadable modules in the framework's root widgets/ directory. Since that directory is outside public/, Zap exposes only explicitly registered widgets through WidgetController at /widgets/{name}. This avoids making the source directory generally web-accessible.

<section lw-component="widgets/CounterWidget.js" data-step="2">
 <button type="button" data-counter-action="decrement">−</button>
 <output data-counter-value aria-live="polite">0</output>
 <button type="button" data-counter-action="increment">+</button>
</section>

<section lw-component="widgets/CharacterCountWidget.js">
 <label>Message
 <textarea data-character-input maxlength="120"></textarea>
 </label>
 <output data-character-count aria-live="polite"></output>
</section>
Counter widget
0

Components receive (element, params), where params comes from the source element's data-* attributes. For example, data-step="2" becomes params.step === "2"; dataset values are strings, so convert numbers and booleans explicitly. A data-max-count attribute becomes params.maxCount. With a triggered component, the trigger element supplies the parameters.

<div
 lw-component="widgets/HelloWidget.js"
 data-name="Ada Lovelace">
</div>

<div
 lw-component="widgets/LoginForm.js"
 data-route="/login"
 data-title="Member sign in"
 data-submit-label="Continue">
</div>

The framework ships function-style HelloWidget and LoginForm examples as well as the class-based counter and character-count widgets. They use DOM APIs and text properties instead of inserting parameter values as HTML. The login form includes Zap's CSRF meta token as a hidden field when it is present. To defer mounting, set lw-trigger="click" and optionally lw-target on the trigger element; lw-trigger="load" runs a request on load.

To add a widget, create a module in widgets/ and add its exact filename to the allowlist in WidgetController. It is then importable as lw-component="widgets/YourWidget.js". The widget modules themselves are framework-independent ES modules.

Security, response handling, and lifecycle

  • Protect state-changing endpoints with CSRF validation and server-side authorization. Litewire sends the meta token in X-CSRF-TOKEN; in Zap, use the framework's request validation in controller actions.
  • Validate all form input on the server. Client-side constraints and hidden controls are usability features, not security controls.
  • Request responses are inserted as HTML. Escape untrusted output in server-rendered fragments; do not build markup by concatenating raw user input.
  • lw:text writes plain text. lw:state and event expressions are evaluated JavaScript: never place user-controlled strings into those expressions.
  • Litewire scans the initial document and newly inserted elements, so request fragments can contain further Litewire bindings and components.

Request elements dispatch these bubbling custom events:

  • litewire:beforeRequest immediately before fetch.
  • litewire:afterRequest after a successful response has been swapped.
  • litewire:error when fetch fails or the response is not successful; its detail.error contains the error.
use Zap\Core\Http\Response;
use Zap\Core\Utils\Security;

public function store(): Response
{
 if (!Security::get_instance()->validate_request()) {
 return $this->text('Invalid CSRF token.', 419);
 }

 // Validate input and authorize the operation before persisting it.
 return $this->html('<li>Saved</li>');
}
<button id="load-panel" type="button" lw-get="/panel" lw-target="#panel-content">
 Load panel
</button>
<div id="panel-content"></div>

<script>
document.querySelector('#load-panel').addEventListener('litewire:afterRequest', () => {
 console.info('Panel updated');
});
</script>

Custom event listeners can be attached directly in a component with addEventListener(). The lw: event directives bind standard DOM events, not these litewire:* lifecycle events.

Directive reference

lw-* attributes

  • lw-component loads a component module; lw-trigger controls event or load timing for a request/component.
  • lw-get, lw-post, lw-put, and lw-delete make HTTP requests.
  • lw-target selects a response/component target; lw-swap selects how response HTML is inserted.
  • lw-indicator selects loading indicators; lw-push-url opts into history URL changes and fragment restoration.

lw:* attributes

  • lw:state creates local reactive state; lw:text renders text; lw:show toggles visibility; lw:class toggles classes.
  • lw:for repeats a template; lw:model, lw:model.live, lw:model.change, and lw:model.blur bind form controls.
  • lw:click, lw:input, lw:change, lw:submit, lw:keydown, lw:keyup, lw:focus, and lw:blur bind DOM events and accept the event modifiers above.