litewire 1.0.1 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +2 -2
- package/README.MD +318 -219
- package/package.json +11 -10
- package/src/litewire.js +0 -261
package/LICENSE
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
MIT License
|
|
2
2
|
|
|
3
|
-
Copyright (c) 2026
|
|
3
|
+
Copyright (c) 2026 Zainurrahman
|
|
4
4
|
|
|
5
5
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
6
|
of this software and associated documentation files (the "Software"), to deal
|
|
@@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
|
18
18
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
19
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
20
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
21
|
+
SOFTWARE.
|
package/README.MD
CHANGED
|
@@ -1,305 +1,404 @@
|
|
|
1
|
-
# Litewire
|
|
1
|
+
# Litewire 1.0.2
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
## Complete Architecture Manual & Reference Guide
|
|
3
|
+
Litewire is a browser-side HTML-over-the-wire library. It binds requests and
|
|
4
|
+
reactive behaviors to HTML attributes, swaps server-rendered HTML into the
|
|
5
|
+
page, and can load ES module components on demand.
|
|
8
6
|
|
|
9
|
-
|
|
7
|
+
## Contents
|
|
10
8
|
|
|
11
|
-
|
|
9
|
+
- [Install and start](#install-and-start)
|
|
10
|
+
- [Configuration](#configuration)
|
|
11
|
+
- [AJAX requests](#ajax-requests)
|
|
12
|
+
- [Reactive state and bindings](#reactive-state-and-bindings)
|
|
13
|
+
- [Dynamic components](#dynamic-components)
|
|
14
|
+
- [HTML swaps and DOM updates](#html-swaps-and-dom-updates)
|
|
15
|
+
- [Browser history](#browser-history)
|
|
16
|
+
- [Lifecycle events](#lifecycle-events)
|
|
17
|
+
- [CSRF](#csrf)
|
|
18
|
+
- [Security considerations](#security-considerations)
|
|
19
|
+
- [API reference](#api-reference)
|
|
12
20
|
|
|
13
|
-
##
|
|
21
|
+
## Install and start
|
|
14
22
|
|
|
15
|
-
|
|
16
|
-
2. [Core Configuration & Initialization](#2-core-configuration--initialization)
|
|
17
|
-
3. [Attribute Reference API](#3-attribute-reference-api)
|
|
18
|
-
4. [Dynamic ES Module Loader (`lw-component`)](#4-dynamic-es-module-loader-lw-component)
|
|
19
|
-
5. [DOM Swapping & Navigation Mechanisms](#5-dom-swapping--navigation-mechanisms)
|
|
20
|
-
6. [History & State Caching](#6-history--state-caching)
|
|
21
|
-
7. [Event System & Lifecycle Hooks](#7-event-system--lifecycle-hooks)
|
|
22
|
-
8. [CSRF & Security Protocols](#8-csrf--security-protocols)
|
|
23
|
-
9. [Practical Implementation Patterns](#9-practical-implementation-patterns)
|
|
23
|
+
### Use the browser file
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
Download `litewire.js` and load it as an ES module:
|
|
26
26
|
|
|
27
|
-
|
|
27
|
+
```html
|
|
28
|
+
<script type="module" src="/js/litewire.js"></script>
|
|
29
|
+
```
|
|
28
30
|
|
|
29
|
-
|
|
31
|
+
Litewire creates `window.litewire` when the document is ready, unless that
|
|
32
|
+
global already exists. It scans the page, binds supported attributes, and
|
|
33
|
+
continues scanning elements added later.
|
|
30
34
|
|
|
31
|
-
|
|
32
|
-
> Litewire eliminates the need for full-page reloads and complex SPA frameworks by leveraging declarative markup, dynamic MutationObservers, and native browser features like `fetch()` and `history.pushState()`.
|
|
35
|
+
### Use the npm package
|
|
33
36
|
|
|
34
|
-
|
|
37
|
+
If version 1.0.2 is available from your configured npm registry:
|
|
35
38
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
4. **Execution:** Sends non-blocking background HTTP requests with built-in CSRF security headers.
|
|
40
|
-
5. **Swap & Mount:** Replaces target DOM regions with backend HTML and automatically boots dynamic JS components on newly introduced elements.
|
|
39
|
+
```sh
|
|
40
|
+
npm install litewire@1.0.2
|
|
41
|
+
```
|
|
41
42
|
|
|
42
|
-
|
|
43
|
+
Import the package from your application's JavaScript entry point:
|
|
43
44
|
|
|
44
|
-
|
|
45
|
+
```js
|
|
46
|
+
import "litewire";
|
|
47
|
+
```
|
|
45
48
|
|
|
46
|
-
|
|
49
|
+
The package module auto-initializes in a browser environment. Do not create a
|
|
50
|
+
second instance unless you intentionally want an additional set of listeners
|
|
51
|
+
and observers.
|
|
47
52
|
|
|
48
|
-
###
|
|
53
|
+
### First request
|
|
49
54
|
|
|
50
|
-
|
|
55
|
+
```html
|
|
56
|
+
<button
|
|
57
|
+
lw-get="/hello"
|
|
58
|
+
lw-target="#result"
|
|
59
|
+
>
|
|
60
|
+
Load greeting
|
|
61
|
+
</button>
|
|
51
62
|
|
|
52
|
-
|
|
53
|
-
1. Constructor Option: new Litewire({ baseUrl: '[https://example.com/api](https://example.com/api)' })
|
|
54
|
-
2. Meta Tag Element: <meta name="base-url" content="[https://example.com](https://example.com)">
|
|
55
|
-
3. Global App Config: window.AppConfig.baseUrl
|
|
56
|
-
4. Window Location: window.location.origin (Default)
|
|
63
|
+
<div id="result">The response will appear here.</div>
|
|
57
64
|
```
|
|
58
65
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
```javascript
|
|
62
|
-
// Custom manual instantiation with options
|
|
63
|
-
const customLitewire = new Litewire({
|
|
64
|
-
baseUrl: "[https://api.myproject.com](https://api.myproject.com)",
|
|
65
|
-
loadingClass: "is-loading", // Class applied to active triggers and indicators
|
|
66
|
-
});
|
|
67
|
-
```
|
|
66
|
+
Litewire sends a GET request when the button is clicked and replaces the
|
|
67
|
+
contents of `#result` with the response HTML.
|
|
68
68
|
|
|
69
|
-
|
|
69
|
+
## Configuration
|
|
70
70
|
|
|
71
|
-
|
|
71
|
+
Litewire resolves its base URL in this order:
|
|
72
72
|
|
|
73
|
-
|
|
73
|
+
1. `baseUrl` constructor option
|
|
74
|
+
2. `<meta name="base-url" content="...">`
|
|
75
|
+
3. `window.AppConfig.baseUrl`
|
|
76
|
+
4. `window.location.origin`
|
|
74
77
|
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
| `lw-post` | Relative / Absolute Path | None | Executes an HTTP POST request. Submits form payload if bound to or inside a `<form>`. |
|
|
79
|
-
| `lw-put` | Relative / Absolute Path | None | Executes an HTTP PUT request with FormData payload attachment. |
|
|
80
|
-
| `lw-delete` | Relative / Absolute Path | None | Executes an HTTP DELETE request. |
|
|
81
|
-
| `lw-trigger` | `click`, `submit`, `load`, custom | Contextual | Overrides trigger event. Defaults to `submit` for forms, `click` for interactive tags. `load` fires instantly. |
|
|
82
|
-
| `lw-target` | CSS Selector | Self Element | Specifies the container element where the returned HTML response will be rendered. |
|
|
83
|
-
| `lw-swap` | `innerHTML`, `outerHTML`, `prepend`, `append` | `innerHTML` | Controls how the received HTML response replaces or integrates into the target element. |
|
|
84
|
-
| `lw-indicator` | CSS Selector | `.litewire-indicator` | Specifies target loading elements. Automatically toggles the active `loadingClass` during request execution. |
|
|
85
|
-
| `lw-push-url` | `true`, `false`, Custom Path | `false` | Pushes a new state to the browser history, caching DOM contents for native back/forward navigation. |
|
|
86
|
-
| `lw-component` | JS File Path | None | Asynchronously imports a JavaScript module and mounts it directly onto the host DOM element. |
|
|
78
|
+
The default loading class is `litewire-request`. Configure these values before
|
|
79
|
+
Litewire auto-initializes by setting a meta tag or `window.AppConfig` before
|
|
80
|
+
loading the module:
|
|
87
81
|
|
|
88
|
-
|
|
82
|
+
```html
|
|
83
|
+
<meta name="base-url" content="https://example.com/app">
|
|
84
|
+
<script>
|
|
85
|
+
window.AppConfig = { baseUrl: "https://example.com/app" };
|
|
86
|
+
</script>
|
|
87
|
+
<script type="module" src="/js/litewire.js"></script>
|
|
88
|
+
```
|
|
89
89
|
|
|
90
|
-
|
|
90
|
+
The constructor also accepts options when you instantiate the exported class
|
|
91
|
+
yourself:
|
|
91
92
|
|
|
92
|
-
|
|
93
|
+
```js
|
|
94
|
+
window.litewire = {};
|
|
95
|
+
const { default: Litewire } = await import("./litewire.js");
|
|
93
96
|
|
|
94
|
-
|
|
97
|
+
window.litewire = new Litewire({
|
|
98
|
+
baseUrl: "https://example.com/app",
|
|
99
|
+
loadingClass: "is-loading",
|
|
100
|
+
});
|
|
101
|
+
```
|
|
95
102
|
|
|
96
|
-
|
|
103
|
+
The placeholder prevents the module's browser auto-initializer from creating
|
|
104
|
+
another instance before your configured instance is constructed.
|
|
97
105
|
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
3. Extracts component constructors or functions via fallback export resolution:
|
|
101
|
-
`module.default` → `module.imageUploader` → `Object.values(module)[0]`
|
|
102
|
-
4. Instantiates the module using `new componentFn(el, params)` or direct function execution.
|
|
103
|
-
5. Passes all `data-*` HTML attributes as an object to the component's `params` argument.
|
|
106
|
+
Request and component paths are joined to the resolved base URL. Leading
|
|
107
|
+
slashes are removed from the supplied path before joining.
|
|
104
108
|
|
|
105
|
-
|
|
109
|
+
## AJAX requests
|
|
106
110
|
|
|
107
|
-
|
|
111
|
+
Litewire recognizes `lw-get`, `lw-post`, `lw-put`, and `lw-delete`. It binds
|
|
112
|
+
forms to `submit` by default and other elements to `click`. Set `lw-trigger` to
|
|
113
|
+
choose a different event or to run a request when the element is scanned:
|
|
108
114
|
|
|
109
115
|
```html
|
|
110
|
-
|
|
111
|
-
<
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
+
<form lw-post="/messages" lw-target="#messages">
|
|
117
|
+
<label>
|
|
118
|
+
Message
|
|
119
|
+
<input name="message" required>
|
|
120
|
+
</label>
|
|
121
|
+
<button type="submit">Send</button>
|
|
122
|
+
</form>
|
|
123
|
+
|
|
124
|
+
<div id="messages"></div>
|
|
116
125
|
```
|
|
117
126
|
|
|
118
|
-
|
|
127
|
+
For GET requests, form fields are encoded as URL query parameters. For POST,
|
|
128
|
+
PUT, and DELETE requests, a containing form is sent as `FormData`. If the
|
|
129
|
+
trigger is not in a form, no request body is added.
|
|
119
130
|
|
|
120
|
-
```
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
131
|
+
```html
|
|
132
|
+
<input
|
|
133
|
+
name="q"
|
|
134
|
+
lw-get="/search"
|
|
135
|
+
lw-trigger="keyup"
|
|
136
|
+
lw-target="#results"
|
|
137
|
+
lw-indicator="#search-status"
|
|
138
|
+
>
|
|
139
|
+
<span id="search-status" class="litewire-indicator">Searching…</span>
|
|
140
|
+
<div id="results"></div>
|
|
141
|
+
```
|
|
126
142
|
|
|
127
|
-
|
|
128
|
-
|
|
143
|
+
When a request starts, Litewire adds the configured loading class to the
|
|
144
|
+
trigger and its indicators. Indicators default to `.litewire-indicator`
|
|
145
|
+
descendants of the trigger; `lw-indicator` can instead specify a document-wide
|
|
146
|
+
CSS selector. Litewire removes the class when the request finishes, whether it
|
|
147
|
+
succeeds or fails.
|
|
129
148
|
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
149
|
+
Use `lw-trigger="load"` with a request attribute to start a request as soon as
|
|
150
|
+
the element is scanned:
|
|
151
|
+
|
|
152
|
+
```html
|
|
153
|
+
<section
|
|
154
|
+
lw-get="/account/summary"
|
|
155
|
+
lw-trigger="load"
|
|
156
|
+
lw-target="#account-summary"
|
|
157
|
+
>
|
|
158
|
+
Loading account summary…
|
|
159
|
+
</section>
|
|
160
|
+
<div id="account-summary"></div>
|
|
139
161
|
```
|
|
140
162
|
|
|
141
|
-
|
|
163
|
+
## Reactive state and bindings
|
|
142
164
|
|
|
143
|
-
|
|
165
|
+
Litewire 1.0.2 adds a small reactive layer using `lw:state`, `lw:model`,
|
|
166
|
+
`lw:text`, `lw:show`, and event-expression attributes. The colon in these
|
|
167
|
+
attribute names is intentional.
|
|
144
168
|
|
|
145
|
-
|
|
169
|
+
### Local state
|
|
146
170
|
|
|
147
|
-
|
|
171
|
+
Put `lw:state` on an element to create state for that element and its
|
|
172
|
+
descendants. Its value must be a JavaScript expression that evaluates to an
|
|
173
|
+
object:
|
|
148
174
|
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
175
|
+
```html
|
|
176
|
+
<section lw:state="{ count: 0, visible: true }">
|
|
177
|
+
<button lw:click="count++">Count: <span lw:text="count"></span></button>
|
|
178
|
+
<p lw:show="visible">This paragraph can be hidden.</p>
|
|
179
|
+
<button lw:click="visible = !visible">Toggle paragraph</button>
|
|
180
|
+
</section>
|
|
181
|
+
```
|
|
153
182
|
|
|
154
|
-
|
|
183
|
+
Assignments and deletions of top-level state properties trigger rendering of
|
|
184
|
+
descendant `lw:text` and `lw:show` bindings owned by that state root. State is
|
|
185
|
+
shallowly reactive: mutating a nested object or array in place does not itself
|
|
186
|
+
trigger a render. Replace the top-level property to trigger one, for example
|
|
187
|
+
`settings = { ...settings, enabled: false }`.
|
|
155
188
|
|
|
156
|
-
|
|
189
|
+
Nested `lw:state` elements establish their own state scope. A binding uses the
|
|
190
|
+
nearest ancestor state root. Bindings outside a state root use Litewire's
|
|
191
|
+
global models instead.
|
|
157
192
|
|
|
158
|
-
|
|
193
|
+
### Text and visibility
|
|
159
194
|
|
|
160
|
-
|
|
195
|
+
- `lw:text="expression"` evaluates the expression and writes its result as
|
|
196
|
+
text. `null` and `undefined` render as an empty string.
|
|
197
|
+
- `lw:show="expression"` sets the element's `hidden` property based on the
|
|
198
|
+
truthiness of the result.
|
|
161
199
|
|
|
162
|
-
|
|
200
|
+
Expressions are evaluated when the element is first scanned and again when
|
|
201
|
+
their owning local state renders. Global model updates also update matching
|
|
202
|
+
`lw:text` bindings.
|
|
163
203
|
|
|
164
|
-
###
|
|
204
|
+
### Form models
|
|
165
205
|
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
206
|
+
```html
|
|
207
|
+
<div lw:state="{ name: '' }">
|
|
208
|
+
<label>
|
|
209
|
+
Your name
|
|
210
|
+
<input lw:model="name">
|
|
211
|
+
</label>
|
|
212
|
+
<p>Hello, <span lw:text="name"></span>.</p>
|
|
213
|
+
</div>
|
|
214
|
+
```
|
|
171
215
|
|
|
172
|
-
|
|
216
|
+
The default `lw:model` and `lw:model.live` listen for `input`.
|
|
217
|
+
`lw:model.change` listens for `change`, and `lw:model.blur` listens for `blur`.
|
|
218
|
+
For checkboxes, the model value is a boolean; for radio inputs, it is the
|
|
219
|
+
checked value or `null`; other controls use their value.
|
|
173
220
|
|
|
174
|
-
|
|
221
|
+
Without a local `lw:state` root, models are stored globally and can be read or
|
|
222
|
+
written with the instance methods `litewire.getModel(name)` and
|
|
223
|
+
`litewire.setModel(name, value)`. Global model changes dispatch a
|
|
224
|
+
`litewire:model` event on `document`, with `{ name, value }` in `event.detail`.
|
|
175
225
|
|
|
176
|
-
|
|
226
|
+
A model name beginning with `#` or `.` is treated as a CSS selector instead of
|
|
227
|
+
a state key. Litewire copies the control's value to matching elements (to
|
|
228
|
+
`value` for form controls, otherwise to `textContent`) and dispatches
|
|
229
|
+
`litewire:model` on each target with `{ value }` in `event.detail`.
|
|
177
230
|
|
|
178
|
-
|
|
179
|
-
| ------------------------ | ------------------ | --------------------------------------------------------------------------------------------------------------- |
|
|
180
|
-
| `litewire:beforeRequest` | `null` | Fires immediately before the HTTP request is initiated. Ideal for disabling inputs or custom client validation. |
|
|
181
|
-
| `litewire:afterRequest` | `null` | Fires after the request succeeds and the HTML content swap is complete. Ideal for triggering animations. |
|
|
182
|
-
| `litewire:error` | `{ error: Error }` | Fires if a network error occurs or the HTTP response returns an error status (non-2xx). |
|
|
231
|
+
### Event expressions
|
|
183
232
|
|
|
184
|
-
|
|
233
|
+
Supported event attributes are:
|
|
185
234
|
|
|
186
|
-
```
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
});
|
|
235
|
+
```text
|
|
236
|
+
lw:click lw:input lw:change lw:submit
|
|
237
|
+
lw:keydown lw:keyup lw:focus lw:blur
|
|
238
|
+
```
|
|
191
239
|
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
240
|
+
The attribute value is evaluated when its event fires. Within the expression,
|
|
241
|
+
the nearest local state properties (or global models) are in scope. Special
|
|
242
|
+
values are available:
|
|
243
|
+
|
|
244
|
+
- `$event`: the DOM event
|
|
245
|
+
- `$el`: the element carrying the directive
|
|
246
|
+
- `$value`: the current value of that element
|
|
247
|
+
- `$state`: the current state object
|
|
248
|
+
- `$wire`: the Litewire instance
|
|
249
|
+
|
|
250
|
+
```html
|
|
251
|
+
<div lw:state="{ query: '' }">
|
|
252
|
+
<input lw:model="query">
|
|
253
|
+
<button lw:click="console.log(query, $event)">Log query</button>
|
|
254
|
+
</div>
|
|
195
255
|
```
|
|
196
256
|
|
|
197
|
-
|
|
257
|
+
Supported event modifiers:
|
|
198
258
|
|
|
199
|
-
|
|
259
|
+
| Modifier | Behavior |
|
|
260
|
+
|---|---|
|
|
261
|
+
| `.prevent` | Calls `preventDefault()` |
|
|
262
|
+
| `.stop` | Calls `stopPropagation()` |
|
|
263
|
+
| `.once` | Runs the handler at most once |
|
|
264
|
+
| `.capture` | Registers the listener in capture phase |
|
|
265
|
+
| `.passive` | Registers a passive listener |
|
|
266
|
+
| `.self` | Runs only when the event target is the directive element |
|
|
267
|
+
| `.outside` | Runs only when the event target is outside the directive element |
|
|
268
|
+
| `.window` | Registers the listener on `window` |
|
|
269
|
+
| `.document` | Registers the listener on `document` |
|
|
270
|
+
| `.debounce` | Delays execution until events stop for 250 ms |
|
|
271
|
+
| `.throttle` | Runs at most once per 250 ms |
|
|
200
272
|
|
|
201
|
-
|
|
273
|
+
Modifiers can be combined, for example `lw:click.prevent.once="save()"`.
|
|
202
274
|
|
|
203
|
-
|
|
275
|
+
## Dynamic components
|
|
204
276
|
|
|
205
|
-
|
|
277
|
+
An element with `lw-component` dynamically imports a JavaScript module. The
|
|
278
|
+
path is joined to Litewire's base URL. Litewire selects the module's default
|
|
279
|
+
export first, then a named `imageUploader` export, then the first export. If
|
|
280
|
+
the selected export is a function, it is called with the host element and its
|
|
281
|
+
`data-*` attributes converted to an object:
|
|
206
282
|
|
|
207
283
|
```html
|
|
208
|
-
<
|
|
284
|
+
<div
|
|
285
|
+
lw-component="components/greeting.js"
|
|
286
|
+
data-user-name="Ada"
|
|
287
|
+
></div>
|
|
209
288
|
```
|
|
210
289
|
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
290
|
+
```js
|
|
291
|
+
// /app/components/greeting.js
|
|
292
|
+
export default class Greeting {
|
|
293
|
+
constructor(element, params) {
|
|
294
|
+
element.textContent = `Hello, ${params.userName}!`;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
215
297
|
```
|
|
216
298
|
|
|
217
|
-
|
|
299
|
+
New components inserted by a swap or added to the document are discovered
|
|
300
|
+
automatically. A given element is mounted only once.
|
|
218
301
|
|
|
219
|
-
##
|
|
302
|
+
## HTML swaps and DOM updates
|
|
220
303
|
|
|
221
|
-
|
|
304
|
+
Set `lw-target` to a CSS selector to choose where a response is inserted. If
|
|
305
|
+
omitted, the element that triggered the request is the target. `lw-swap`
|
|
306
|
+
controls how response HTML is applied:
|
|
222
307
|
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
lw-get="/users/search"
|
|
230
|
-
lw-trigger="keyup"
|
|
231
|
-
lw-target="#user-table-body"
|
|
232
|
-
lw-push-url="true"
|
|
233
|
-
/>
|
|
308
|
+
| Value | Behavior |
|
|
309
|
+
|---|---|
|
|
310
|
+
| `innerHTML` (default) | Replaces the target's contents |
|
|
311
|
+
| `outerHTML` | Replaces the target element |
|
|
312
|
+
| `prepend` | Inserts response HTML at the beginning of the target |
|
|
313
|
+
| `append` | Inserts response HTML at the end of the target |
|
|
234
314
|
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
</tbody>
|
|
239
|
-
</table>
|
|
240
|
-
```
|
|
315
|
+
Litewire scans swapped content and mounts its components. It also observes
|
|
316
|
+
added DOM elements so directives in newly inserted content are bound
|
|
317
|
+
automatically.
|
|
241
318
|
|
|
242
|
-
|
|
243
|
-
// Route
|
|
244
|
-
Route::get('/users/search', 'UsersController@search')->name('user.search');
|
|
245
|
-
|
|
246
|
-
//UserController
|
|
247
|
-
public function search(Request $request)
|
|
248
|
-
{
|
|
249
|
-
$query = $request->input('q', '');
|
|
250
|
-
$search = $this->model('UsersModel')->searchUser($query);
|
|
251
|
-
$data = [
|
|
252
|
-
'users' => $search
|
|
253
|
-
];
|
|
254
|
-
|
|
255
|
-
$html = $this->render('users/search', $data);
|
|
256
|
-
return $this->response($html);
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
//Blade
|
|
260
|
-
@if (!empty($users))
|
|
261
|
-
@foreach ($users as $index => $user)
|
|
262
|
-
<tr>
|
|
263
|
-
<td>{{ $index + 1 }}</td>
|
|
264
|
-
<td>{{ $user['fullname'] }}</td>
|
|
265
|
-
</tr>
|
|
266
|
-
@endforeach
|
|
267
|
-
@endif
|
|
268
|
-
```
|
|
319
|
+
## Browser history
|
|
269
320
|
|
|
270
|
-
|
|
321
|
+
Set `lw-push-url="true"` to push the request URL to browser history, or provide
|
|
322
|
+
a custom URL as the attribute value:
|
|
271
323
|
|
|
272
324
|
```html
|
|
273
|
-
<
|
|
274
|
-
|
|
275
|
-
lw-
|
|
276
|
-
lw-
|
|
277
|
-
lw-
|
|
325
|
+
<a
|
|
326
|
+
href="/products"
|
|
327
|
+
lw-get="/products"
|
|
328
|
+
lw-target="#page"
|
|
329
|
+
lw-push-url="true"
|
|
278
330
|
>
|
|
279
|
-
|
|
331
|
+
Products
|
|
332
|
+
</a>
|
|
333
|
+
```
|
|
280
334
|
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
335
|
+
Litewire stores the URL, target selector, and target HTML in history state.
|
|
336
|
+
When navigating with Back or Forward, it restores cached HTML when the state
|
|
337
|
+
contains a selector and markup and the target still exists. Otherwise it
|
|
338
|
+
attempts to fetch the stored URL. This caches only the selected target's HTML,
|
|
339
|
+
not the complete document or JavaScript state.
|
|
286
340
|
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
341
|
+
## Lifecycle events
|
|
342
|
+
|
|
343
|
+
Litewire dispatches bubbling events from the request trigger:
|
|
344
|
+
|
|
345
|
+
| Event | `event.detail` | When it fires |
|
|
346
|
+
|---|---|---|
|
|
347
|
+
| `litewire:beforeRequest` | — | Immediately before sending a request |
|
|
348
|
+
| `litewire:afterRequest` | — | After a successful response has been swapped |
|
|
349
|
+
| `litewire:error` | `{ error }` | On a network failure or non-success HTTP response |
|
|
350
|
+
|
|
351
|
+
Reactive local state also dispatches `litewire:render` from its state root
|
|
352
|
+
after a render, with `{ state }` in `event.detail`.
|
|
353
|
+
|
|
354
|
+
```js
|
|
355
|
+
document.addEventListener("litewire:error", (event) => {
|
|
356
|
+
console.error("Litewire request failed:", event.detail.error);
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
document.addEventListener("litewire:render", (event) => {
|
|
360
|
+
console.log("State rendered:", event.detail.state);
|
|
361
|
+
});
|
|
290
362
|
```
|
|
291
363
|
|
|
292
|
-
|
|
364
|
+
## CSRF
|
|
293
365
|
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
<div
|
|
297
|
-
lw-get="/analytics/widget"
|
|
298
|
-
lw-trigger="load"
|
|
299
|
-
lw-target="#analytics-container"
|
|
300
|
-
>
|
|
301
|
-
<p>Loading real-time analytics data...</p>
|
|
302
|
-
</div>
|
|
366
|
+
When this meta tag is present, Litewire adds its token as the
|
|
367
|
+
`X-CSRF-TOKEN` header to outgoing requests:
|
|
303
368
|
|
|
304
|
-
|
|
369
|
+
```html
|
|
370
|
+
<meta name="csrf-token" content="your-server-generated-token">
|
|
305
371
|
```
|
|
372
|
+
|
|
373
|
+
The server must still validate the token and enforce its own authorization and
|
|
374
|
+
request protections.
|
|
375
|
+
|
|
376
|
+
## Security considerations
|
|
377
|
+
|
|
378
|
+
Litewire inserts response bodies as HTML. Only return trusted or appropriately
|
|
379
|
+
sanitized HTML from your server.
|
|
380
|
+
|
|
381
|
+
`lw:state` and event-expression attributes are evaluated as JavaScript. Use
|
|
382
|
+
them only in markup you control; do not construct these expressions from
|
|
383
|
+
untrusted user input.
|
|
384
|
+
|
|
385
|
+
## API reference
|
|
386
|
+
|
|
387
|
+
| Attribute / API | Description |
|
|
388
|
+
|---|---|
|
|
389
|
+
| `lw-get`, `lw-post`, `lw-put`, `lw-delete` | Request path and HTTP method |
|
|
390
|
+
| `lw-trigger` | Event name; defaults to `click` or form `submit`; `load` runs immediately |
|
|
391
|
+
| `lw-target` | CSS selector for the response target |
|
|
392
|
+
| `lw-swap` | `innerHTML`, `outerHTML`, `prepend`, or `append` |
|
|
393
|
+
| `lw-indicator` | CSS selector for loading indicators |
|
|
394
|
+
| `lw-push-url` | `true`, `false`, or a custom history URL |
|
|
395
|
+
| `lw-component` | Path to a dynamically imported ES module |
|
|
396
|
+
| `lw:state` | JavaScript object expression that initializes local reactive state |
|
|
397
|
+
| `lw:model`, `.live`, `.change`, `.blur` | Bind a form control to a state or global model |
|
|
398
|
+
| `lw:text` | Render an expression as text |
|
|
399
|
+
| `lw:show` | Toggle the element's `hidden` property from an expression |
|
|
400
|
+
| `lw:click`, `lw:input`, `lw:change`, `lw:submit`, `lw:keydown`, `lw:keyup`, `lw:focus`, `lw:blur` | Evaluate an expression in response to an event; supports the modifiers documented above |
|
|
401
|
+
| `litewire.getModel(name)` | Read a global model |
|
|
402
|
+
| `litewire.setModel(name, value)` | Set a global model and update matching bindings |
|
|
403
|
+
|
|
404
|
+
**Buy my kids schoolbooks:** [https://paypal.me/justumg](https://paypal.me/justumg)
|
package/package.json
CHANGED
|
@@ -1,24 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "litewire",
|
|
3
|
-
"version": "1.0.
|
|
4
|
-
"description": "A lightweight HTML-driven
|
|
5
|
-
"main": "
|
|
6
|
-
"module": "
|
|
3
|
+
"version": "1.0.2",
|
|
4
|
+
"description": "A lightweight HTML-driven request engine with reactive state and dynamic ES module components.",
|
|
5
|
+
"main": "./litewire.js",
|
|
6
|
+
"module": "./litewire.js",
|
|
7
|
+
"browser": "./litewire.js",
|
|
7
8
|
"type": "module",
|
|
8
9
|
"exports": {
|
|
9
|
-
".": "./
|
|
10
|
+
".": "./litewire.js"
|
|
10
11
|
},
|
|
11
12
|
"files": [
|
|
12
|
-
"
|
|
13
|
-
"README.md"
|
|
14
|
-
"LICENSE"
|
|
13
|
+
"litewire.js",
|
|
14
|
+
"README.md"
|
|
15
15
|
],
|
|
16
16
|
"keywords": [
|
|
17
17
|
"ajax",
|
|
18
|
-
"htmx",
|
|
19
18
|
"html-over-the-wire",
|
|
19
|
+
"reactive",
|
|
20
20
|
"components",
|
|
21
|
-
"
|
|
21
|
+
"javascript",
|
|
22
|
+
"frontend"
|
|
22
23
|
],
|
|
23
24
|
"author": "Zainurrahman <languaojs@gmail.com>",
|
|
24
25
|
"license": "MIT",
|
package/src/litewire.js
DELETED
|
@@ -1,261 +0,0 @@
|
|
|
1
|
-
class Litewire {
|
|
2
|
-
constructor(options = {}) {
|
|
3
|
-
const metaBaseUrl = document.querySelector('meta[name="base-url"]')?.getAttribute('content');
|
|
4
|
-
const rawBaseUrl = options.baseUrl
|
|
5
|
-
|| metaBaseUrl
|
|
6
|
-
|| window.AppConfig?.baseUrl
|
|
7
|
-
|| window.location.origin;
|
|
8
|
-
this.baseUrl = rawBaseUrl.replace(/\/+$/, '');
|
|
9
|
-
this.loadingClass = options.loadingClass || 'litewire-request';
|
|
10
|
-
this.init();
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
init() {
|
|
14
|
-
this.scan(document);
|
|
15
|
-
this.loadComponents(document);
|
|
16
|
-
this.observe();
|
|
17
|
-
this.listenToHistory();
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
async loadComponents(root) {
|
|
21
|
-
const selector = '[lw-component]';
|
|
22
|
-
const elements = root.querySelectorAll ? root.querySelectorAll(selector) : [];
|
|
23
|
-
|
|
24
|
-
if (root.nodeType === Node.ELEMENT_NODE && root.matches(selector)) {
|
|
25
|
-
this.mountComponent(root);
|
|
26
|
-
}
|
|
27
|
-
elements.forEach(el => this.mountComponent(el));
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
async mountComponent(el) {
|
|
31
|
-
if (el._litewireComponentMounted) return;
|
|
32
|
-
el._litewireComponentMounted = true;
|
|
33
|
-
|
|
34
|
-
const rawPath = el.getAttribute('lw-component');
|
|
35
|
-
if (!rawPath) return;
|
|
36
|
-
|
|
37
|
-
const cleanPath = rawPath.replace(/^\/+/, '');
|
|
38
|
-
const fullPath = `${this.baseUrl}/${cleanPath}`;
|
|
39
|
-
|
|
40
|
-
try {
|
|
41
|
-
const module = await import(fullPath);
|
|
42
|
-
const params = { ...el.dataset };
|
|
43
|
-
|
|
44
|
-
const componentFn = module.default || module.imageUploader || Object.values(module)[0];
|
|
45
|
-
|
|
46
|
-
if (typeof componentFn === 'function') {
|
|
47
|
-
try {
|
|
48
|
-
new componentFn(el, params);
|
|
49
|
-
} catch {
|
|
50
|
-
componentFn(el, params);
|
|
51
|
-
}
|
|
52
|
-
} else {
|
|
53
|
-
console.error(`[Litewire Error] No valid export found in module: ${fullPath}`);
|
|
54
|
-
}
|
|
55
|
-
} catch (err) {
|
|
56
|
-
console.error(`[Litewire Error] Failed to import component from ${fullPath}:`, err);
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
scan(root) {
|
|
61
|
-
const selector = '[lw-get], [lw-post], [lw-put], [lw-delete], [lw-trigger="load"]';
|
|
62
|
-
const elements = root.querySelectorAll ? root.querySelectorAll(selector) : [];
|
|
63
|
-
|
|
64
|
-
if (root.nodeType === Node.ELEMENT_NODE && root.matches(selector)) {
|
|
65
|
-
this.bindElement(root);
|
|
66
|
-
}
|
|
67
|
-
elements.forEach(el => this.bindElement(el));
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
bindElement(el) {
|
|
71
|
-
if (el._litewireBound) return;
|
|
72
|
-
el._litewireBound = true;
|
|
73
|
-
|
|
74
|
-
const trigger = el.getAttribute('lw-trigger') || (el.tagName === 'FORM' ? 'submit' : 'click');
|
|
75
|
-
|
|
76
|
-
if (trigger === 'load') {
|
|
77
|
-
this.executeRequest(el);
|
|
78
|
-
} else {
|
|
79
|
-
el.addEventListener(trigger, (e) => {
|
|
80
|
-
if (el.tagName === 'FORM' || trigger === 'click') e.preventDefault();
|
|
81
|
-
this.executeRequest(el);
|
|
82
|
-
});
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
getIndicators(el) {
|
|
87
|
-
const indicatorAttr = el.getAttribute('lw-indicator');
|
|
88
|
-
if (!indicatorAttr) {
|
|
89
|
-
return Array.from(el.querySelectorAll('.litewire-indicator'));
|
|
90
|
-
}
|
|
91
|
-
return Array.from(document.querySelectorAll(indicatorAttr));
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
async executeRequest(el, isPopState = false) {
|
|
95
|
-
const method = ['post', 'put', 'delete', 'get'].find(m => el.hasAttribute(`lw-${m}`)) || 'get';
|
|
96
|
-
const path = el.getAttribute(`lw-${method}`);
|
|
97
|
-
if (!path) return;
|
|
98
|
-
|
|
99
|
-
const cleanPath = path.replace(/^\/+/, '');
|
|
100
|
-
let url = `${this.baseUrl}/${cleanPath}`;
|
|
101
|
-
|
|
102
|
-
const options = { method: method.toUpperCase(), headers: {} };
|
|
103
|
-
|
|
104
|
-
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
|
|
105
|
-
if (csrfToken) {
|
|
106
|
-
options.headers['X-CSRF-TOKEN'] = csrfToken;
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
if (method === 'get') {
|
|
110
|
-
const form = el.tagName === 'FORM' ? el : el.closest('form');
|
|
111
|
-
let params = new URLSearchParams();
|
|
112
|
-
|
|
113
|
-
if (form) {
|
|
114
|
-
params = new URLSearchParams(new FormData(form));
|
|
115
|
-
} else if (el.name && el.value !== undefined) {
|
|
116
|
-
params.append(el.name, el.value);
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
const queryString = params.toString();
|
|
120
|
-
if (queryString) {
|
|
121
|
-
url += (url.includes('?') ? '&' : '?') + queryString;
|
|
122
|
-
}
|
|
123
|
-
} else {
|
|
124
|
-
const form = el.tagName === 'FORM' ? el : el.closest('form');
|
|
125
|
-
if (form) {
|
|
126
|
-
options.body = new FormData(form);
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
const indicators = this.getIndicators(el);
|
|
131
|
-
|
|
132
|
-
try {
|
|
133
|
-
el.classList.add(this.loadingClass);
|
|
134
|
-
indicators.forEach(ind => ind.classList.add(this.loadingClass));
|
|
135
|
-
|
|
136
|
-
el.dispatchEvent(new CustomEvent('litewire:beforeRequest', { bubbles: true }));
|
|
137
|
-
|
|
138
|
-
const response = await fetch(url, options);
|
|
139
|
-
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
140
|
-
const html = await response.text();
|
|
141
|
-
|
|
142
|
-
const target = this.swapHTML(el, html);
|
|
143
|
-
|
|
144
|
-
if (!isPopState) {
|
|
145
|
-
this.handleHistoryPush(el, url, target);
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
el.dispatchEvent(new CustomEvent('litewire:afterRequest', { bubbles: true }));
|
|
149
|
-
} catch (err) {
|
|
150
|
-
console.error(`[Litewire Error] ${method.toUpperCase()} ${url} failed:`, err);
|
|
151
|
-
el.dispatchEvent(new CustomEvent('litewire:error', { bubbles: true, detail: { error: err } }));
|
|
152
|
-
} finally {
|
|
153
|
-
el.classList.remove(this.loadingClass);
|
|
154
|
-
indicators.forEach(ind => ind.classList.remove(this.loadingClass));
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
swapHTML(el, html) {
|
|
159
|
-
const targetSelector = el.getAttribute('lw-target');
|
|
160
|
-
const target = targetSelector ? document.querySelector(targetSelector) : el;
|
|
161
|
-
const swapType = el.getAttribute('lw-swap') || 'innerHTML';
|
|
162
|
-
|
|
163
|
-
if (!target) return target;
|
|
164
|
-
|
|
165
|
-
if (swapType === 'outerHTML') {
|
|
166
|
-
const parent = target.parentElement;
|
|
167
|
-
target.outerHTML = html;
|
|
168
|
-
if (parent) {
|
|
169
|
-
this.scan(parent);
|
|
170
|
-
this.loadComponents(parent);
|
|
171
|
-
}
|
|
172
|
-
} else if (swapType === 'prepend') {
|
|
173
|
-
target.insertAdjacentHTML('afterbegin', html);
|
|
174
|
-
this.scan(target);
|
|
175
|
-
this.loadComponents(target);
|
|
176
|
-
} else if (swapType === 'append') {
|
|
177
|
-
target.insertAdjacentHTML('beforeend', html);
|
|
178
|
-
this.scan(target);
|
|
179
|
-
this.loadComponents(target);
|
|
180
|
-
} else {
|
|
181
|
-
target.innerHTML = html;
|
|
182
|
-
this.scan(target);
|
|
183
|
-
this.loadComponents(target);
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
return target;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
handleHistoryPush(el, requestUrl, target) {
|
|
190
|
-
const pushAttr = el.getAttribute('lw-push-url');
|
|
191
|
-
if (!pushAttr || pushAttr === 'false') return;
|
|
192
|
-
|
|
193
|
-
const newUrl = pushAttr === 'true' ? requestUrl : pushAttr;
|
|
194
|
-
const targetSelector = el.getAttribute('lw-target') || '';
|
|
195
|
-
|
|
196
|
-
if (!history.state) {
|
|
197
|
-
history.replaceState({
|
|
198
|
-
litewireUrl: window.location.href,
|
|
199
|
-
targetSelector: targetSelector,
|
|
200
|
-
html: target ? target.innerHTML : ''
|
|
201
|
-
}, '', window.location.href);
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
history.pushState({
|
|
205
|
-
litewireUrl: newUrl,
|
|
206
|
-
targetSelector: targetSelector,
|
|
207
|
-
html: target ? target.innerHTML : ''
|
|
208
|
-
}, '', newUrl);
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
listenToHistory() {
|
|
212
|
-
window.addEventListener('popstate', (e) => {
|
|
213
|
-
if (!e.state) return;
|
|
214
|
-
|
|
215
|
-
const { targetSelector, html, litewireUrl } = e.state;
|
|
216
|
-
|
|
217
|
-
if (targetSelector && html !== undefined) {
|
|
218
|
-
const target = document.querySelector(targetSelector);
|
|
219
|
-
if (target) {
|
|
220
|
-
target.innerHTML = html;
|
|
221
|
-
this.scan(target);
|
|
222
|
-
this.loadComponents(target);
|
|
223
|
-
return;
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
const fallbackEl = document.createElement('div');
|
|
228
|
-
fallbackEl.setAttribute('lw-get', litewireUrl || window.location.href);
|
|
229
|
-
if (targetSelector) fallbackEl.setAttribute('lw-target', targetSelector);
|
|
230
|
-
|
|
231
|
-
this.executeRequest(fallbackEl, true);
|
|
232
|
-
});
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
observe() {
|
|
236
|
-
const observer = new MutationObserver((mutations) => {
|
|
237
|
-
for (const m of mutations) {
|
|
238
|
-
m.addedNodes.forEach(node => {
|
|
239
|
-
if (node.nodeType === Node.ELEMENT_NODE) {
|
|
240
|
-
this.scan(node);
|
|
241
|
-
this.loadComponents(node);
|
|
242
|
-
}
|
|
243
|
-
});
|
|
244
|
-
}
|
|
245
|
-
});
|
|
246
|
-
observer.observe(document.body, { childList: true, subtree: true });
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
export default Litewire;
|
|
251
|
-
|
|
252
|
-
// Auto-instantiate in browser environments if not loaded as a module
|
|
253
|
-
if (typeof window !== 'undefined' && typeof document !== 'undefined') {
|
|
254
|
-
if (document.readyState === 'loading') {
|
|
255
|
-
document.addEventListener('DOMContentLoaded', () => {
|
|
256
|
-
if (!window.litewire) window.litewire = new Litewire();
|
|
257
|
-
});
|
|
258
|
-
} else {
|
|
259
|
-
if (!window.litewire) window.litewire = new Litewire();
|
|
260
|
-
}
|
|
261
|
-
}
|