1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
// Larust reactive-component client runtime. No build step, no npm, no CDN -
// vendored in full and served at GET /__larust_wire/runtime.js, version-
// locked to the installed larust-live crate.
//
// v1 scope: wire:model (deferred - sent only when another trigger fires),
// wire:model.live (immediate, 150ms debounced), wire:click="action" and
// wire:submit="action" (no arguments). Explicitly out of scope for v1:
// .lazy/.throttle/custom debounce values, .number/.boolean coercion,
// action arguments.
(function () {
"use strict";
var DEBOUNCE_MS = 150;
var inFlight = Object.create(null); // component id -> { promise, resyncPending }
function csrfToken() {
var meta = document.querySelector('meta[name="csrf-token"]');
return meta ? meta.content : "";
}
function findRoot(el) {
return el.closest("[data-wire-id]");
}
// Every sync sends the *entire* current wire:model/wire:model.live
// field set for the component, not just whatever triggered it - this
// is what correctly threads a deferred field's just-typed value
// through when a different element (a click, or another field's live
// sync) is what actually fires the request.
function collectProps(root) {
var props = {};
root.querySelectorAll("[wire\\:model], [wire\\:model\\.live]").forEach(function (el) {
var name = el.getAttribute("wire:model") || el.getAttribute("wire:model.live");
if (!name) return;
if (el.type === "checkbox") {
props[name] = el.checked;
} else {
props[name] = el.value;
}
});
return props;
}
function sync(root, action) {
var id = root.getAttribute("data-wire-id");
var body = JSON.stringify({
props: collectProps(root),
action: action || null,
});
var existing = inFlight[id];
if (existing) {
// A request for this component is already in flight - don't
// fire a second, concurrent one (an older response could
// otherwise land after and clobber a newer edit). Remember to
// resync once the in-flight one settles instead.
existing.resyncPending = { action: action || null };
return;
}
var entry = { resyncPending: null };
inFlight[id] = entry;
entry.promise = fetch("/__larust_wire/" + encodeURIComponent(id), {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-CSRF-TOKEN": csrfToken(),
},
body: body,
})
.then(function (response) {
// An action's `Ok(Some(path))` (Livewire's `redirect()`)
// arrives as a response header, checked before the body is
// ever read - navigating away makes patching the current
// fragment moot, and (unlike the body) a header is always
// present even on this component's very last response.
var redirect = response.headers.get("X-Wire-Redirect");
if (redirect) {
window.location.href = redirect;
return null;
}
if (!response.ok) return null;
// Any `'head'` content this render pushed (e.g. a live
// page-title update) - applied here, not in the body
// fragment, since it targets a `<!--wire-head:{id}-->...
// <!--/wire-head:{id}-->` marker pair `mount()` already
// wrote into `document.head` at initial render. See
// `larust_view::push_registry`'s doc comment for the full
// design.
var headPatch = response.headers.get("X-Wire-Head-Patch");
if (headPatch) applyHeadPatch(id, headPatch);
return response.text();
})
.then(function (html) {
if (html) applyFragment(root, html);
})
.catch(function (error) {
// eslint-disable-next-line no-console
console.error("larust-wire sync failed", error);
})
.finally(function () {
delete inFlight[id];
if (entry.resyncPending) {
sync(root, entry.resyncPending.action);
}
});
}
function applyFragment(root, html) {
var template = document.createElement("template");
template.innerHTML = html.trim();
var newRoot = template.content.firstElementChild;
if (!newRoot) return;
larustWirePatch(root, newRoot);
}
// Replaces the content between `document.head`'s `<!--wire-head:{id}-->`
// / `<!--/wire-head:{id}-->` comment markers with freshly pushed
// content. A silent no-op if either marker is missing - the component's
// *initial* mount always writes both (even when empty, see `mount()`'s
// own comment), so a missing marker only happens for a page whose
// layout never actually declares `@stack('head')` in the first place,
// the mechanism's own documented precondition.
function applyHeadPatch(id, encodedPatch) {
var html;
try {
var binary = atob(encodedPatch);
var bytes = new Uint8Array(binary.length);
for (var i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
html = new TextDecoder("utf-8").decode(bytes);
} catch (error) {
// eslint-disable-next-line no-console
console.error("larust-wire: failed to decode head patch", error);
return;
}
var start = null;
var end = null;
var node = document.head.firstChild;
while (node) {
if (node.nodeType === Node.COMMENT_NODE) {
if (node.data === "wire-head:" + id) start = node;
else if (start && node.data === "/wire-head:" + id) {
end = node;
break;
}
}
node = node.nextSibling;
}
if (!start || !end) return;
var toRemove = start.nextSibling;
while (toRemove && toRemove !== end) {
var next = toRemove.nextSibling;
toRemove.parentNode.removeChild(toRemove);
toRemove = next;
}
var template = document.createElement("template");
template.innerHTML = html;
end.parentNode.insertBefore(template.content, end);
}
// The vendored DOM patcher - deliberately not a general morphdom port.
// Scope: attribute + text-node diffing, children matched by position +
// tag (+ id when present on both sides), no keyed-list reordering (a
// component's own re-render is a structurally-stable subtree, not a
// general list-diffing target). This is what avoids the naive-
// innerHTML-replace bug of destroying focus/cursor position on the
// input the user is actively typing into: an attribute/property is
// only written when its value actually differs from what's already
// there, and the server always echoes back the same value the client
// just sent for a wire:model field, so the active input's own value
// never gets rewritten mid-edit.
//
// `wire:ignore` (same attribute name/meaning as real Livewire) opts an
// element's entire subtree out of patching, full stop - needed for any
// element a *different* piece of JS manages after mount (a rich-text
// editor like Trix being the canonical case: it builds its own real
// DOM children - an internal contenteditable surface - that never
// exist in the server-rendered HTML, which only ever contains the
// empty `<trix-editor>` tag itself. Without this, every re-render's
// child-diff would see those Trix-owned children as extra nodes not
// present in the fresh HTML and delete them, wiping out the editor's
// visible content on every single sync.
function larustWirePatch(oldEl, newEl) {
if (isIgnored(oldEl)) return;
if (oldEl.tagName !== newEl.tagName) {
oldEl.replaceWith(newEl);
return;
}
patchAttributes(oldEl, newEl);
var oldChildren = Array.prototype.slice.call(oldEl.childNodes);
var newChildren = Array.prototype.slice.call(newEl.childNodes);
var max = Math.max(oldChildren.length, newChildren.length);
for (var i = 0; i < max; i++) {
var oldChild = oldChildren[i];
var newChild = newChildren[i];
if (oldChild && isIgnored(oldChild)) continue;
if (oldChild && !newChild) {
oldEl.removeChild(oldChild);
continue;
}
if (!oldChild && newChild) {
oldEl.appendChild(newChild);
continue;
}
patchNode(oldEl, oldChild, newChild);
}
}
function isIgnored(node) {
return (
node.nodeType === Node.ELEMENT_NODE &&
node.hasAttribute &&
node.hasAttribute("wire:ignore")
);
}
function patchNode(parent, oldChild, newChild) {
if (oldChild.nodeType !== newChild.nodeType) {
parent.replaceChild(newChild, oldChild);
return;
}
if (oldChild.nodeType === Node.TEXT_NODE) {
if (oldChild.data !== newChild.data) oldChild.data = newChild.data;
return;
}
if (oldChild.nodeType !== Node.ELEMENT_NODE) {
parent.replaceChild(newChild, oldChild);
return;
}
if (
oldChild.tagName !== newChild.tagName ||
oldChild.id !== newChild.id
) {
parent.replaceChild(newChild, oldChild);
return;
}
larustWirePatch(oldChild, newChild);
}
function patchAttributes(oldEl, newEl) {
var oldAttrs = oldEl.attributes;
var newAttrs = newEl.attributes;
for (var i = oldAttrs.length - 1; i >= 0; i--) {
var name = oldAttrs[i].name;
if (!newEl.hasAttribute(name)) oldEl.removeAttribute(name);
}
for (var j = 0; j < newAttrs.length; j++) {
var attr = newAttrs[j];
if (oldEl.getAttribute(attr.name) !== attr.value) {
oldEl.setAttribute(attr.name, attr.value);
}
}
// Form controls: browsers don't always reflect an attribute change
// onto the live JS property for a user-edited control, so sync the
// property too - only when it actually differs, for the same
// cursor/focus-preservation reason as the attribute diff above.
//
// Never overwrite the *currently focused* control's value/checked
// state, though: a response reflects whatever value that field had
// at the moment its triggering request was *sent*, not necessarily
// now - if the user kept typing (a deferred `wire:model` field, or
// fast typing outrunning the debounce) while this response was in
// flight, blindly applying a stale echoed-back value here would
// silently overwrite those newer, not-yet-synced keystrokes. The
// field's own next sync (or the debounce that's already pending)
// carries the truly current value forward instead.
var isEditingThis =
typeof document !== "undefined" && document.activeElement === oldEl;
if (!isEditingThis) {
if ("value" in newEl && oldEl.value !== newEl.value) {
oldEl.value = newEl.value;
}
if ("checked" in newEl && oldEl.checked !== newEl.checked) {
oldEl.checked = newEl.checked;
}
}
}
function debounce(fn, ms) {
var timers = new WeakMap();
return function (el) {
var existing = timers.get(el);
if (existing) clearTimeout(existing);
timers.set(
el,
setTimeout(function () {
timers.delete(el);
fn(el);
}, ms)
);
};
}
var debouncedWireSync = debounce(function (el) {
var root = findRoot(el);
if (root) sync(root);
}, DEBOUNCE_MS);
document.addEventListener("input", function (event) {
var el = event.target;
if (!el || !el.hasAttribute) return;
if (el.hasAttribute("wire:model.live")) {
debouncedWireSync(el);
}
// Plain wire:model is deferred - collectProps() reads its current
// value from the DOM whenever some other trigger fires a sync, but
// typing into it never triggers one on its own.
});
document.addEventListener("click", function (event) {
var el = event.target.closest("[wire\\:click]");
if (!el) return;
var root = findRoot(el);
if (!root) return;
event.preventDefault();
sync(root, { name: el.getAttribute("wire:click"), args: null });
});
document.addEventListener("submit", function (event) {
var form = event.target;
if (!form || !form.hasAttribute || !form.hasAttribute("wire:submit")) return;
var root = findRoot(form);
if (!root) return;
event.preventDefault();
sync(root, { name: form.getAttribute("wire:submit"), args: null });
});
})();