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.
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>
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-swapsupportsinnerHTML(default),outerHTML,prepend, andappend.lw-indicator=".selector"selects loading indicators. Without it, Litewire finds descendant elements with classlitewire-indicator. The requesting element and indicators receivelitewire-requestwhile 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.falseor no attribute leaves history unchanged. Back/forward navigation restores the stored fragment when possible. The implemented attribute islw-push-url; there is no separatelw-pushdirective.- 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
.preventcallspreventDefault();.stopstops propagation;.selfonly runs when the event target is the element itself;.onceruns once..outsidelistens on the document and runs only when the event occurs outside the element..windowand.documentattach the listener to those global targets..debounceand.throttlerate-limit calls. Add a delay such as.debounce.300msor.throttle.100ms; the default delay is 250 ms..captureand.passiveuse the corresponding DOM listener options. A passive listener should not callpreventDefault().
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>
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:textwrites plain text.lw:stateand 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:beforeRequestimmediately before fetch.litewire:afterRequestafter a successful response has been swapped.litewire:errorwhen fetch fails or the response is not successful; itsdetail.errorcontains 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-componentloads a component module;lw-triggercontrols event or load timing for a request/component.lw-get,lw-post,lw-put, andlw-deletemake HTTP requests.lw-targetselects a response/component target;lw-swapselects how response HTML is inserted.lw-indicatorselects loading indicators;lw-push-urlopts into history URL changes and fragment restoration.
lw:* attributes
lw:statecreates local reactive state;lw:textrenders text;lw:showtoggles visibility;lw:classtoggles classes.lw:forrepeats a template;lw:model,lw:model.live,lw:model.change, andlw:model.blurbind form controls.lw:click,lw:input,lw:change,lw:submit,lw:keydown,lw:keyup,lw:focus, andlw:blurbind DOM events and accept the event modifiers above.