@glitchr/transparent 1.0.82 → 1.1.0

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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/src/js/transparent.js +682 -468
@@ -180,77 +180,44 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
180
180
  "smoothscroll_speed" : 0,
181
181
  "smoothscroll_easing" : "swing",
182
182
  "exceptions": [],
183
- // headlock: list of url substrings/regex to preserve in <head> across page transitions
184
- // (e.g. third-party widgets that inject <style>/<link> dynamically).
185
- // In addition, head nodes injected dynamically AFTER initial DOMContentLoaded are
186
- // preserved automatically. Use data-headlock="false" on a head element to opt-out.
187
- "headlock": []
183
+ // headlock: list of URL substrings or regex patterns to preserve in
184
+ // <head> across page transitions (e.g. third-party widgets that
185
+ // inject <style>/<link> dynamically). Anything matching is treated
186
+ // as "locked" and never removed during the head merge.
187
+ //
188
+ // In addition, head nodes injected dynamically AFTER initial
189
+ // DOMContentLoaded are auto-preserved (snapshotted on load → not
190
+ // in the set → preserved).
191
+ //
192
+ // Per-element overrides:
193
+ // <link data-headlock="false"> → opt-out (allow normal removal)
194
+ // <link data-headlock="true"> → opt-in (always preserve)
195
+ //
196
+ // Ported from upstream 1.0.82's `headlock` design (cleaner API than
197
+ // the previous hardcoded SCRIPT/STYLE-never-remove heuristic).
198
+ "headlock": [],
199
+ // ── View Transitions API ────────────────────────────────────────────
200
+ // When true, the DOM swap is wrapped in document.startViewTransition()
201
+ // so the browser captures an OLD snapshot, applies the swap callback,
202
+ // then crossfades to the NEW state natively. Falls back transparently
203
+ // to the CSS-only transition path on browsers without VT support
204
+ // (Firefox < 144, Safari < 18.2, old Chromium). Per-element morph
205
+ // is opt-in via CSS:
206
+ //
207
+ // #page { view-transition-name: page; }
208
+ // .article-hero img { view-transition-name: article-hero; }
209
+ //
210
+ // Pairs the named element across the swap so the browser animates
211
+ // its position/size change instead of crossfading the snapshots.
212
+ //
213
+ // skip_transition_for_cache: when true, in-DOM cache hits bypass VT
214
+ // entirely (for Turbo-style instant-back UX). Default false because
215
+ // VT's 200ms crossfade is fast enough that the consistency win
216
+ // outweighs the saved frames.
217
+ "use_view_transitions": false,
218
+ "skip_transition_for_cache": false
188
219
  };
189
220
 
190
- // Set of <head> children present on initial load. Anything added after is treated
191
- // as dynamically injected and preserved across transitions.
192
- var originalHeadNodes = new WeakSet();
193
- function snapshotHeadNodes() {
194
- var head = document.head;
195
- if(!head) return;
196
- for(var i = 0; i < head.children.length; i++)
197
- originalHeadNodes.add(head.children[i]);
198
- }
199
- // Snapshot synchronously at module-eval time (scripts at end of <body> run before any
200
- // async script can inject <style> tags, so the snapshot is clean).
201
- // A DOMContentLoaded fallback is kept for the rare case where document.head is null
202
- // (e.g. script loaded inside <head> before it finishes parsing).
203
- snapshotHeadNodes();
204
- if(!document.head)
205
- document.addEventListener("DOMContentLoaded", snapshotHeadNodes, { once: true });
206
-
207
- Transparent.isHeadlocked = function(el) {
208
- if(!el || el.nodeType !== 1) return false;
209
- // Explicit opt-out
210
- var attr = el.getAttribute && el.getAttribute("data-headlock");
211
- if(attr === "false") return false;
212
- // Explicit opt-in via attribute
213
- if(attr !== null && attr !== undefined) return true;
214
- // Dynamically injected after initial load
215
- if(!originalHeadNodes.has(el)) return true;
216
- // URL pattern match (src/href attributes)
217
- var patterns = Settings["headlock"] || [];
218
- if(!patterns.length) return false;
219
- var url = el.getAttribute && (el.getAttribute("src") || el.getAttribute("href"));
220
- // <style> elements have no src/href — match against CSS textContent instead
221
- if(!url && el.tagName === 'STYLE') url = el.textContent || '';
222
- if(!url) return false;
223
- for(var i = 0; i < patterns.length; i++) {
224
- var p = patterns[i];
225
- if(p instanceof RegExp) { if(p.test(url)) return true; }
226
- else if(typeof p === "string" && p.length && url.indexOf(p) !== -1) return true;
227
- }
228
- return false;
229
- }
230
-
231
- // ─── NAVIGATION TRACE LOG ───────────────────────────────────────
232
- // Gated on Settings.debug. Set 'debug': true in Transparent.ready({...})
233
- // to surface a per-step trace prefixed with "[TX]" in the console.
234
- // Cheap when disabled — single boolean check, no allocation.
235
- function _tx(tag, extra) {
236
- if (!Settings || !Settings.debug) return;
237
- try {
238
- var cls = document.documentElement.className;
239
- var t = performance.now().toFixed(1);
240
- var here = (document.querySelector("#page") || document.documentElement);
241
- var lay = here.getAttribute && (here.getAttribute("data-layout") || "?");
242
- var path = location.pathname;
243
- console.log("%c[TX]", "color:#0a0;font-weight:bold",
244
- "+" + t + "ms", tag,
245
- "path=" + path,
246
- "layout=" + lay,
247
- "ajaxSem=" + (typeof ajaxSemaphore === "undefined" ? "?" : ajaxSemaphore),
248
- "classes=[" + cls + "]",
249
- extra || "");
250
- } catch(e) {}
251
- }
252
- // ────────────────────────────────────────────────────────────────
253
-
254
221
  const State = Transparent.state = {
255
222
 
256
223
  ROOT : "transparent",
@@ -269,53 +236,17 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
269
236
  CLICK : "click",
270
237
 
271
238
  PREACTIVE : "pre-active",
272
- FADEIN : "fade-in",
239
+ ACTIVEIN : "active-in",
273
240
  ACTIVE : "active",
274
- FADEOUT : "fade-out",
241
+ ACTIVEOUT : "active-out",
275
242
  POSTACTIVE : "post-active",
276
243
 
277
- NOTIFICATION: "notification",
278
- OFFLINE : "offline"
244
+ NOTIFICATION: "notification"
279
245
  };
280
246
 
281
247
  var isReady = false;
282
248
  var rescueMode = false;
283
249
 
284
- // ─── OFFLINE DETECTION ──────────────────────────────────────────
285
- // Two-source signal:
286
- // 1. window 'online'/'offline' events fired by the browser when the
287
- // OS-level connectivity changes (Wi-Fi off, airplane mode, etc.)
288
- // 2. AJAX network errors during navigation — if a request fails with
289
- // status 0 (and wasn't aborted), the device probably can't reach
290
- // the server even though navigator.onLine may still be true.
291
- // The `html.offline` class is the public surface — the project's CSS
292
- // styles the YouTube-style "Offline" banner from there. Custom events
293
- // `transparent:offline` and `transparent:online` give JS hooks too.
294
- var isOnline = (typeof navigator !== "undefined") ? navigator.onLine !== false : true;
295
- Transparent.isOnline = function() { return isOnline; }
296
- function setOnlineStatus(online) {
297
- if (online === isOnline) return; // no change
298
- isOnline = online;
299
- if (online) {
300
- $($(document).find("html")[0]).removeClass(State.OFFLINE);
301
- dispatchEvent(new Event("transparent:online"));
302
- } else {
303
- $($(document).find("html")[0]).addClass(State.OFFLINE);
304
- dispatchEvent(new Event("transparent:offline"));
305
- }
306
- }
307
- if (typeof window !== "undefined") {
308
- window.addEventListener("online", function() { setOnlineStatus(true); });
309
- window.addEventListener("offline", function() { setOnlineStatus(false); });
310
- }
311
- // Apply initial state synchronously so first-paint reflects offline if applicable.
312
- if (!isOnline) {
313
- // Use the document element directly here — Transparent.html isn't initialized yet at module-eval time.
314
- var _htmlEl = document.documentElement;
315
- if (_htmlEl && _htmlEl.classList) _htmlEl.classList.add(State.OFFLINE);
316
- }
317
- // ────────────────────────────────────────────────────────────────
318
-
319
250
  Transparent.html = $($(document).find("html")[0]);
320
251
  Transparent.html.addClass(Transparent.state.ROOT+ " " + Transparent.state.LOADING + " " + Transparent.state.FIRST);
321
252
 
@@ -324,6 +255,91 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
324
255
  dispatchEvent(new Event('transparent:'+Transparent.state.ACTIVE));
325
256
  }
326
257
 
258
+ // ── Server-rendered element tracking ───────────────────────────────────
259
+ //
260
+ // SPA head/body merging removes elements not present in the new page's
261
+ // HTML response — correct for server-rendered tags (per-page CSS,
262
+ // <meta>, page-specific <script>), but it ALSO nukes anything that a
263
+ // third-party loader injected at runtime: Brevo's chat widget <style>
264
+ // and <div>, Google Analytics tags, Intercom, Crisp, Hotjar, etc.
265
+ // These elements are never in any page's HTML response, so the merge
266
+ // removes them on every nav → user sees the chat widget lose all its
267
+ // CSS and explode to full screen (visible in the user's screenshot of
268
+ // navigating /articles → /).
269
+ //
270
+ // Fix: maintain a WeakSet of elements known to be server-rendered. The
271
+ // initial document's head + body children are server-rendered. Anything
272
+ // we ADD via the SPA merge later is also server-rendered (it came from
273
+ // a server HTML response). Anything else — third-party script
274
+ // injections that happen AFTER snapshot — is never added to the set
275
+ // and is therefore preserved across navs.
276
+ //
277
+ // WeakSet means removed elements get garbage-collected → no leak.
278
+ //
279
+ // MutationObserver auto-tags elements added by ANY route, so even
280
+ // body-script appends or head-script appends elsewhere in this library
281
+ // stay correctly classified.
282
+ // Ported from upstream 1.0.82 — `headlock` design.
283
+ //
284
+ // Replaces the previous hardcoded "never remove SCRIPT/STYLE" rule
285
+ // with a finer-grained API: snapshot the initial head children, then
286
+ // on the next swap, *preserve* anything that's either (a) not in the
287
+ // snapshot (= dynamically injected after load), or (b) matches a
288
+ // configured URL pattern in Settings.headlock, or (c) has a
289
+ // data-headlock attribute (true/non-empty = lock, "false" = unlock).
290
+ //
291
+ // Two key wins over the previous local impl:
292
+ // 1. The previous impl never removed any <script>/<style> at all,
293
+ // which caused per-page stylesheets to leak across navigations
294
+ // (e.g. layout1's inline <style> persisting on layout2). The new
295
+ // design only locks dynamically-injected ones.
296
+ // 2. Project code can pass `headlock: ["brevo.com", "googletag", /hotjar/]`
297
+ // in Transparent.ready({...}) to explicitly opt-in third-party
298
+ // URLs by substring or regex.
299
+ var originalHeadNodes = new WeakSet();
300
+ function snapshotHeadNodes() {
301
+ if (document.head) {
302
+ for (var i = 0; i < document.head.children.length; i++) {
303
+ originalHeadNodes.add(document.head.children[i]);
304
+ }
305
+ }
306
+ }
307
+ // Snapshot synchronously at module-eval time. Defer scripts run after
308
+ // the parser has built the <head> but before async third-party loaders
309
+ // execute, so the snapshot captures the server-rendered <head> cleanly.
310
+ // The DOMContentLoaded fallback handles the rare case where the script
311
+ // ran before <head> was complete (e.g. in-head non-defer placement).
312
+ snapshotHeadNodes();
313
+ if (!document.head) {
314
+ document.addEventListener("DOMContentLoaded", snapshotHeadNodes, { once: true });
315
+ }
316
+
317
+ Transparent.isHeadlocked = function(el) {
318
+ if (!el || el.nodeType !== 1) return false;
319
+ // Explicit attribute opt-out wins over everything else.
320
+ var attr = el.getAttribute && el.getAttribute("data-headlock");
321
+ if (attr === "false") return false;
322
+ // Explicit attribute opt-in (any non-"false" value).
323
+ if (attr !== null && attr !== undefined) return true;
324
+ // Auto-lock anything injected after the initial snapshot — by
325
+ // definition, third-party widgets and their CSS.
326
+ if (!originalHeadNodes.has(el)) return true;
327
+ // URL-pattern matching: src for <script>/<link>/<iframe>, href for
328
+ // <link>, or full textContent for inline <style> blocks. Substring
329
+ // matches on strings; .test() matches on RegExp.
330
+ var patterns = Settings["headlock"] || [];
331
+ if (!patterns.length) return false;
332
+ var url = el.getAttribute && (el.getAttribute("src") || el.getAttribute("href"));
333
+ if (!url && el.tagName === 'STYLE') url = el.textContent || '';
334
+ if (!url) return false;
335
+ for (var i = 0; i < patterns.length; i++) {
336
+ var p = patterns[i];
337
+ if (p instanceof RegExp) { if (p.test(url)) return true; }
338
+ else if (typeof p === "string" && p.length && url.indexOf(p) !== -1) return true;
339
+ }
340
+ return false;
341
+ };
342
+
327
343
  window.addEventListener("DOMContentLoaded", function()
328
344
  {
329
345
  Transparent.loader = $($(document).find(Settings.loader)[0] ?? Transparent.html);
@@ -414,10 +430,71 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
414
430
  return this;
415
431
  }
416
432
 
433
+ // ── In-memory live-DOM cache ────────────────────────────────────────────
434
+ //
435
+ // Turbo-style: store cloned <html> Element nodes per uuid so popstate
436
+ // (back/forward) can short-circuit the XHR + sessionStorage round-trip
437
+ // + DOMParser.parseFromString cycle. Result: back/forward feels instant.
438
+ //
439
+ // Key vs sessionStorage flow:
440
+ // - sessionStorage: outerHTML serialize (slow) → string (5-10MB
441
+ // quota) → JSON read → DOMParser parse (slow). Whole cycle on
442
+ // every popstate. Used as the fallback when the live cache misses.
443
+ // - liveDomCache: cloneNode(true) of the rendered <html> element
444
+ // stored in a Map<uuid, {node, scroll, ts}>. Bounded with LRU.
445
+ // No serialization, no parsing — just the live DOM node ready
446
+ // for the swap to consume.
447
+ //
448
+ // setResponse populates BOTH (live cache + sessionStorage). The
449
+ // sessionStorage write is kept so tab reloads and cross-process
450
+ // restores keep working. getLiveResponse() is the new fast-path API
451
+ // used by handleResponse before the DOMParser fallback.
452
+ Transparent._liveDomCache = new Map();
453
+ Transparent.liveDomCacheMax = 25;
454
+ Transparent.liveDomCacheTTL = 5 * 60 * 1000; // 5 min
455
+
456
+ Transparent.getLiveResponse = function(uuid) {
457
+ var entry = Transparent._liveDomCache.get(uuid);
458
+ if (!entry) return null;
459
+ if (Date.now() - entry.ts > Transparent.liveDomCacheTTL) {
460
+ Transparent._liveDomCache.delete(uuid);
461
+ return null;
462
+ }
463
+ // LRU bump: re-insert to move to the back of the iteration order.
464
+ Transparent._liveDomCache.delete(uuid);
465
+ Transparent._liveDomCache.set(uuid, entry);
466
+ // Return a CLONE so the caller's swap mutations don't poison
467
+ // the cache for future popstate hits. The clone is detached
468
+ // from any document so it's safe to pass to the swap.
469
+ return entry.node.cloneNode(true);
470
+ };
471
+
472
+ Transparent.setLiveResponse = function(uuid, htmlEl, scrollableXY) {
473
+ if (!htmlEl || htmlEl.nodeType !== 1) return;
474
+ Transparent._liveDomCache.set(uuid, {
475
+ node: htmlEl.cloneNode(true),
476
+ scroll: scrollableXY || [],
477
+ ts: Date.now()
478
+ });
479
+ // LRU evict — Map iteration order is insertion order.
480
+ while (Transparent._liveDomCache.size > Transparent.liveDomCacheMax) {
481
+ var firstKey = Transparent._liveDomCache.keys().next().value;
482
+ Transparent._liveDomCache.delete(firstKey);
483
+ }
484
+ };
485
+
486
+ Transparent.clearLiveResponse = function() {
487
+ Transparent._liveDomCache.clear();
488
+ };
489
+
417
490
  Transparent.setResponse = function(uuid, responseText, scrollableXY, exceptionRaised = false)
418
491
  {
419
- if(isDomEntity(responseText))
492
+ // Populate live-DOM cache FIRST while we still have the node.
493
+ // The outerHTML conversion below loses the node identity.
494
+ if (isDomEntity(responseText)) {
495
+ Transparent.setLiveResponse(uuid, responseText, scrollableXY);
420
496
  responseText = responseText.outerHTML;
497
+ }
421
498
 
422
499
  var array = JSON.parse(sessionStorage.getItem('transparent')) || [];
423
500
  if (!array.includes(uuid)) {
@@ -554,7 +631,7 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
554
631
 
555
632
  if($(Transparent.html).hasClass(Transparent.state.FIRST)) {
556
633
  Transparent.scrollToHash(location.hash, {}, function() {
557
- Transparent.fadeOut(() => Transparent.html.removeClass(Transparent.state.FIRST));
634
+ Transparent.activeOut(() => Transparent.html.removeClass(Transparent.state.FIRST));
558
635
  });
559
636
  }
560
637
 
@@ -895,37 +972,28 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
895
972
 
896
973
  return {delay:delay, duration:duration};
897
974
  }
898
- var fadeInTime = 0;
899
- var fadeInRemainingTime = 0;
900
- // Schedule fn for after the currently in-flight fadeIn animation has
901
- // finished. Used by handleResponse's three reload/redirect paths to
902
- // ensure the loader is at full opacity before the browser unloads.
903
- function _waitForFadeIn(fn) {
904
- var elapsed = Date.now() - fadeInTime;
905
- var remaining = fadeInRemainingTime - elapsed;
906
- if (remaining > 0) setTimeout(fn, remaining + 30);
907
- else fn();
908
- }
909
- Transparent.fadeIn = function(activeCallback = function() {}) {
910
- _tx("fadeIn ENTRY");
975
+ var activeInTime = 0;
976
+ var activeInRemainingTime = 0;
977
+ Transparent.activeIn = function(activeCallback = function() {}) {
978
+
911
979
  if(!Transparent.html.hasClass(Transparent.state.PREACTIVE)) {
912
980
  Transparent.html.addClass(Transparent.state.PREACTIVE);
913
981
  dispatchEvent(new Event('transparent:'+Transparent.state.PREACTIVE));
914
982
  }
915
983
 
916
984
  var active = Transparent.activeTime();
917
- fadeInTime = Date.now();
918
- fadeInRemainingTime = active.delay+active.duration;
985
+ activeInTime = Date.now();
986
+ activeInRemainingTime = active.delay+active.duration;
919
987
 
920
988
  Transparent.html.removeClass(Transparent.state.PREACTIVE);
921
- if(!Transparent.html.hasClass(Transparent.state.FADEIN)) {
922
- Transparent.html.addClass(Transparent.state.FADEIN);
923
- dispatchEvent(new Event('transparent:'+Transparent.state.FADEIN));
989
+ if(!Transparent.html.hasClass(Transparent.state.ACTIVEIN)) {
990
+ Transparent.html.addClass(Transparent.state.ACTIVEIN);
991
+ dispatchEvent(new Event('transparent:'+Transparent.state.ACTIVEIN));
924
992
  }
925
993
 
926
994
  Transparent.callback(function() {
927
995
 
928
- Transparent.html.removeClass(Transparent.state.FADEIN);
996
+ Transparent.html.removeClass(Transparent.state.ACTIVEIN);
929
997
  if(!Transparent.html.hasClass(Transparent.state.ACTIVE)) {
930
998
  Transparent.html.addClass(Transparent.state.ACTIVE);
931
999
  dispatchEvent(new Event('transparent:'+Transparent.state.ACTIVE));
@@ -935,23 +1003,23 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
935
1003
  Transparent.callback(function() {
936
1004
 
937
1005
  activeCallback();
938
- fadeInRemainingTime = 0;
1006
+ activeInRemainingTime = 0;
939
1007
 
940
1008
  }.bind(this), active.duration);
941
1009
 
942
1010
  }.bind(this), active.delay);
943
1011
  }
944
1012
 
945
- Transparent.fadeOut = function(activeCallback = function() {}) {
946
- _tx("fadeOut ENTRY");
1013
+ Transparent.activeOut = function(activeCallback = function() {}) {
1014
+
947
1015
  if(!Transparent.html.hasClass(Transparent.state.ACTIVE)) {
948
1016
  Transparent.html.addClass(Transparent.state.ACTIVE);
949
1017
  dispatchEvent(new Event('transparent:'+Transparent.state.ACTIVE));
950
1018
  }
951
1019
 
952
- if(!Transparent.html.hasClass(Transparent.state.FADEOUT)) {
953
- Transparent.html.addClass(Transparent.state.FADEOUT);
954
- dispatchEvent(new Event('transparent:'+Transparent.state.FADEOUT));
1020
+ if(!Transparent.html.hasClass(Transparent.state.ACTIVEOUT)) {
1021
+ Transparent.html.addClass(Transparent.state.ACTIVEOUT);
1022
+ dispatchEvent(new Event('transparent:'+Transparent.state.ACTIVEOUT));
955
1023
  }
956
1024
 
957
1025
  var active = Transparent.activeTime();
@@ -963,7 +1031,7 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
963
1031
  var active = Transparent.activeTime();
964
1032
  Transparent.callback(function() {
965
1033
 
966
- Transparent.html.removeClass(Transparent.state.FADEOUT);
1034
+ Transparent.html.removeClass(Transparent.state.ACTIVEOUT);
967
1035
  if(Transparent.html.hasClass(Transparent.state.LOADING)) {
968
1036
 
969
1037
  dispatchEvent(new Event('transparent:'+Transparent.state.LOADING));
@@ -1068,25 +1136,10 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
1068
1136
  Transparent.evalScript($("body")[0]);
1069
1137
  }
1070
1138
 
1071
- Transparent.fadeOut();
1139
+ Transparent.activeOut();
1072
1140
  }
1073
1141
 
1074
- Transparent.userScroll = function(el = undefined) {
1075
- // Defensive: closestScrollable() can return a value without .prop
1076
- // when called from event handlers on transient DOM (e.g. ajaxer
1077
- // result containers, sticky-scrollpercent triggers fired during
1078
- // infinite-scroll while the page is transitioning). The app-defer.js
1079
- // wrapper around $.fn.closestScrollable is supposed to enforce the
1080
- // jQuery return, but races with timing-sensitive callers can still
1081
- // hit this. Default to true ("user is scrolling, don't autoscroll").
1082
- try {
1083
- var $target = $(el === undefined ? document.documentElement : el);
1084
- if (!$target || !$target.length) return true;
1085
- var $scroll = $target.closestScrollable && $target.closestScrollable();
1086
- if (!$scroll || typeof $scroll.prop !== "function") return true;
1087
- return $scroll.prop("user-scroll") ?? true;
1088
- } catch (e) { return true; }
1089
- }
1142
+ Transparent.userScroll = function(el = undefined) { return $(el === undefined ? document.documentElement : el).closestScrollable().prop("user-scroll") ?? true; }
1090
1143
  Transparent.scrollTo = function(dict, el = window, callback = function() {})
1091
1144
  {
1092
1145
  setTimeout(function() {
@@ -1221,8 +1274,23 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
1221
1274
  image.onload = function() {
1222
1275
  this.classList.add("loaded");
1223
1276
  this.classList.remove("loading");
1277
+ this.classList.remove("error");
1224
1278
  if(lazybox) lazybox.classList.add("loaded");
1225
1279
  if(lazybox) lazybox.classList.remove("loading");
1280
+ if(lazybox) lazybox.classList.remove("error");
1281
+ };
1282
+
1283
+ // Error handler for broken / missing images (404, ACL,
1284
+ // DNS failure, malformed URL). Without this, lazy-loaded
1285
+ // images that fail just stay invisible. The .error
1286
+ // class lets project CSS render a placeholder.
1287
+ image.onerror = function() {
1288
+ this.classList.add("error");
1289
+ this.classList.remove("loading");
1290
+ this.classList.remove("loaded");
1291
+ if(lazybox) lazybox.classList.add("error");
1292
+ if(lazybox) lazybox.classList.remove("loading");
1293
+ if(lazybox) lazybox.classList.remove("loaded");
1226
1294
  };
1227
1295
 
1228
1296
  if(lazybox) lazybox.classList.add("loading");
@@ -1350,42 +1418,60 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
1350
1418
  $(this).stop();
1351
1419
  });
1352
1420
 
1353
- // Defer the DOM swap until #page's opacity transition has had a
1354
- // chance to finish. Read the transition-duration from getComputedStyle
1355
- // (closure-local — no module state shared between navigations) so
1356
- // this stays in sync with whatever the project's CSS uses. Without
1357
- // this delay, a fast/cached AJAX response can land the swap while
1358
- // #page is still partway through the LOADING-induced fade-out,
1359
- // making the content change visible to the user (the original
1360
- // flicker).
1361
- var _swapDelay = 1;
1362
- try {
1363
- var _pageEl = $(Settings.identifier)[0];
1364
- if (_pageEl) {
1365
- var _dur = 1000 * Transparent.parseDuration(
1366
- window.getComputedStyle(_pageEl).transitionDuration || "0"
1367
- );
1368
- if (_dur > 1) _swapDelay = _dur;
1369
- }
1370
- } catch(e) {}
1421
+ activeInRemainingTime = activeInRemainingTime - (Date.now() - activeInTime);
1371
1422
 
1372
- setTimeout(function() {
1423
+ // Whole-swap body extracted so we can dispatch it either through
1424
+ // document.startViewTransition() for browsers that support it (with
1425
+ // Settings.use_view_transitions on), or directly for the legacy path.
1426
+ // Identical behavior in both branches — VT just wraps it so the
1427
+ // browser captures OLD/NEW snapshots and crossfades natively.
1428
+ var _doSwapBody = function() {
1373
1429
 
1374
- _tx("onLoad BODY (after " + _swapDelay + "ms)");
1375
1430
  // Transfert attributes
1376
1431
  Transparent.transferAttributes(dom);
1377
1432
 
1433
+ // ── Track-reload check ──────────────────────────────────────
1434
+ // Mirrors Turbo's <... data-turbo-track="reload"> mechanism.
1435
+ // Put `data-track="reload"` on critical <script> / <link>
1436
+ // bundles in <head>. On nav, if the set of tracked URLs
1437
+ // differs between current and new HTML, force a full reload
1438
+ // instead of an SPA swap — because the user's loaded JS/CSS
1439
+ // no longer matches what the server is serving (e.g. after
1440
+ // a deploy that bumped asset hashes). The browser then
1441
+ // re-downloads everything cleanly.
1442
+ //
1443
+ // Match key: tagName + src/href (or textContent for inline).
1444
+ // Same logic as Turbo: the SET of tracked URLs must match.
1445
+ (function checkTrackedReload() {
1446
+ function trackedSrcs(root) {
1447
+ var srcs = [];
1448
+ var els = root.querySelectorAll('[data-track="reload"]');
1449
+ for (var i = 0; i < els.length; i++) {
1450
+ var el = els[i];
1451
+ var src = el.getAttribute('src') || el.getAttribute('href') ||
1452
+ (el.textContent || '').slice(0, 200);
1453
+ if (src) srcs.push(el.tagName + ':' + src);
1454
+ }
1455
+ return srcs.sort();
1456
+ }
1457
+ var currentSrcs = trackedSrcs(document.head);
1458
+ if (!currentSrcs.length) return; // nothing tracked → skip
1459
+ var newDoc = dom.documentElement ? dom : (dom[0] || dom);
1460
+ var newHead = newDoc.head || newDoc.querySelector('head');
1461
+ if (!newHead) return;
1462
+ var newSrcs = trackedSrcs(newHead);
1463
+ // Compare as JSON of sorted arrays — order-independent.
1464
+ if (JSON.stringify(currentSrcs) === JSON.stringify(newSrcs)) return;
1465
+ if (Settings.debug) {
1466
+ console.log('Transparent track-reload: asset mismatch, forcing reload',
1467
+ { current: currentSrcs, new: newSrcs });
1468
+ }
1469
+ // Full reload to the requested URL.
1470
+ window.location.href = window.location.toString();
1471
+ })();
1472
+
1378
1473
  // Replace head..
1379
1474
  var head = $(dom).find("head");
1380
-
1381
- // Snapshot hrefs of already-loaded stylesheets so we can detect new ones
1382
- // added by the head merge and wait for them to finish loading before
1383
- // making #page visible (prevents FOUC on cold-cache layout transitions).
1384
- var _existingStyleHrefs = {};
1385
- $("head").children("link[rel='stylesheet']").each(function() {
1386
- var h = this.getAttribute("href"); if(h) _existingStyleHrefs[h] = true;
1387
- });
1388
-
1389
1475
  $("head").children().each(function() {
1390
1476
 
1391
1477
  var el = this;
@@ -1394,16 +1480,16 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
1394
1480
  head.children().each(function() {
1395
1481
 
1396
1482
  found = this.isEqualNode(el);
1397
- // Also match identical <style> tags by content
1398
- if(!found && el.tagName === 'STYLE' && this.tagName === 'STYLE' &&
1399
- el.textContent && this.textContent &&
1400
- el.textContent.length > 100 && this.textContent.length === el.textContent.length) {
1401
- found = this.textContent === el.textContent;
1402
- }
1403
1483
  return !found;
1404
1484
  });
1405
1485
 
1406
- // Preserve headlocked nodes (dynamically injected widgets, url-matched, etc.)
1486
+ // Preserve headlocked nodes: anything injected dynamically
1487
+ // after initial load (auto), URL-pattern matches in
1488
+ // Settings.headlock, or explicit data-headlock="true".
1489
+ // This is the win over the previous "never remove SCRIPT/
1490
+ // STYLE" rule — per-page server-rendered <style> blocks
1491
+ // (e.g. layout1 inline CSS) still get swapped, only
1492
+ // third-party / dynamically-injected ones are locked.
1407
1493
  if(!found && Transparent.isHeadlocked(el)) found = true;
1408
1494
  if(!found) this.remove();
1409
1495
  });
@@ -1416,35 +1502,20 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
1416
1502
  $("head").children().each(function() { found |= this.isEqualNode(el); });
1417
1503
  if(!found) {
1418
1504
 
1419
- if(this.tagName == "SCRIPT" && Settings["global_code"] != true) {
1420
-
1421
- // For inline scripts (without src), recreate so the browser will execute.
1422
- // Simply re-appending the same <script> node doesn't execute it.
1423
- if(!this.src || this.src === '') {
1424
- var script = document.createElement("script");
1425
- script.text = this.innerHTML;
1426
- var i = -1, attrs = this.attributes, attr;
1427
- var N = attrs.length;
1428
- while ( ++i < N ) {
1429
- if(attrs[i].name !== 'src') {
1430
- script.setAttribute( attrs[i].name, attrs[i].value );
1431
- }
1432
- }
1433
- $("head").append(script);
1434
- originalHeadNodes.add(script);
1435
- } else {
1436
- $("head").append(this);
1437
- originalHeadNodes.add(this);
1438
- }
1505
+
1506
+ if(this.tagName != "SCRIPT" || Settings["global_code"] == true) {
1507
+
1508
+ var clone = this.cloneNode(true);
1509
+ $("head").append(clone);
1510
+ // Register the new node as "original" so it falls
1511
+ // through to URL-pattern matching on the next swap
1512
+ // (and isn't auto-locked as third-party content).
1513
+ originalHeadNodes.add(clone);
1439
1514
 
1440
1515
  } else {
1441
1516
 
1442
- var clonedEl = this.cloneNode(true);
1443
- $("head").append(clonedEl);
1444
- // Register as an "original" node so it falls through to URL-pattern
1445
- // matching on future transitions — prevents layout CSS added by
1446
- // Transparent itself from being auto-headlocked as third-party content.
1447
- originalHeadNodes.add(clonedEl);
1517
+ $("head").append(this);
1518
+ originalHeadNodes.add(this);
1448
1519
  }
1449
1520
  }
1450
1521
  });
@@ -1458,27 +1529,10 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
1458
1529
  $("body").children().each(function() { found |= this.isEqualNode(el); });
1459
1530
  if(!found) {
1460
1531
 
1461
- if(this.tagName == "SCRIPT" && Settings["global_code"] != true) {
1462
-
1463
- // Same inline-script recreation as for <head>.
1464
- if(!this.src || this.src === '') {
1465
- var script = document.createElement("script");
1466
- script.text = this.innerHTML;
1467
- var i = -1, attrs = this.attributes, attr;
1468
- var N = attrs.length;
1469
- while ( ++i < N ) {
1470
- if(attrs[i].name !== 'src') {
1471
- script.setAttribute( attrs[i].name, attrs[i].value );
1472
- }
1473
- }
1474
- $("body").append(script);
1475
- } else {
1476
- $("body").append(this);
1477
- }
1478
-
1479
- } else {
1480
-
1532
+ if(this.tagName != "SCRIPT" || Settings["global_code"] == true) {
1481
1533
  $("body").append(this.cloneNode(true));
1534
+ } else {
1535
+ $("body").append(this);
1482
1536
  }
1483
1537
  }
1484
1538
  });
@@ -1495,13 +1549,7 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
1495
1549
  // Make sure name/layout keep the same after a page change (tolerance for POST or GET requests)
1496
1550
  if(oldPage.attr("data-layout") != undefined && page.attr("data-layout") != undefined) {
1497
1551
 
1498
- // X = prevLayout, Y = newLayout — must match the formula in handleResponse
1499
- // (line ~1852: SWITCH.replace("X", prevLayout).replace("Y", newLayout)).
1500
- // If these disagreed, the cleanup filter below would not recognize the
1501
- // switchLayout class that handleResponse added to <html> and would strip
1502
- // it before its CSS transition could play — visible as a race only in
1503
- // whichever direction the project's CSS actually styles.
1504
- var switchLayout = Transparent.state.SWITCH.replace("X", oldPage.attr("data-layout")).replace("Y", page.attr("data-layout"));
1552
+ var switchLayout = Transparent.state.SWITCH.replace("X", page.attr("data-layout")).replace("Y", oldPage.attr("data-layout"));
1505
1553
  page.attr("data-layout-prev", oldPage.attr("data-layout"));
1506
1554
  }
1507
1555
 
@@ -1510,13 +1558,10 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
1510
1558
  var oldHtmlClass = Array.from(($(Transparent.html).attr("class") || "").split(" "));
1511
1559
  var removeHtmlClass = oldHtmlClass.filter(x => !htmlClass.includes(x) && switchLayout != x && !states.includes(x));
1512
1560
 
1513
- _tx("onLoad classMgmt", "switchLayout=" + switchLayout + " remove=[" + removeHtmlClass.join(",") + "] add=[" + htmlClass.join(",") + "]");
1514
1561
  Transparent.html.removeClass(removeHtmlClass).addClass(htmlClass);
1515
- _tx("onLoad PAGE_SWAP_BEGIN", "oldLayout=" + (oldPage.attr("data-layout")||"?") + " newLayout=" + (page.attr("data-layout")||"?"));
1516
1562
  $(page).insertBefore(oldPage);
1517
1563
 
1518
1564
  oldPage.remove();
1519
- _tx("onLoad PAGE_SWAP_DONE");
1520
1565
 
1521
1566
  if(Settings["global_code"] == true) Transparent.evalScript($(page)[0]);
1522
1567
  document.dispatchEvent(new Event('DOMContentLoaded'));
@@ -1552,77 +1597,41 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
1552
1597
  }
1553
1598
  }
1554
1599
 
1555
- // Collect link[rel="stylesheet"] elements inserted by the head merge above
1556
- var _newStyleLinks = [];
1557
- $("head").children("link[rel='stylesheet']").each(function() {
1558
- var h = this.getAttribute("href");
1559
- if(h && !_existingStyleHrefs[h]) _newStyleLinks.push(this);
1600
+ $('head').append(function() {
1601
+
1602
+ $(Settings.identifier).append(function() {
1603
+
1604
+ // Callback if needed, or any other actions
1605
+ callback();
1606
+
1607
+ // Trigger onload event
1608
+ dispatchEvent(new Event('transparent:load'));
1609
+ dispatchEvent(new Event('load'));
1610
+ });
1560
1611
  });
1561
1612
 
1562
- // Wait for any newly added layout stylesheets to finish loading before
1563
- // calling callback() / fadeOut() — otherwise #page becomes visible while
1564
- // the new CSS is still being parsed, causing a flash of unstyled content.
1565
- (function() {
1566
- function doCallback() {
1567
- _tx("doCallback FIRES → callback() (which starts fadeOut)");
1568
- // requestAnimationFrame here guarantees the browser has had one
1569
- // full frame to apply the new page's stylesheets and re-layout
1570
- // before fadeOut starts. Without it, fadeOut can animate the
1571
- // loader away while the new page is still rendered with the
1572
- // previous layout's styles — the article→home flicker the
1573
- // [TX] trace masked via instrumentation overhead.
1574
- requestAnimationFrame(function() {
1575
- $('head').append(function() {
1576
- $(Settings.identifier).append(function() {
1577
- callback();
1578
- dispatchEvent(new Event('transparent:load'));
1579
- dispatchEvent(new Event('load'));
1580
- });
1581
- });
1582
- });
1583
- }
1584
- // For cached stylesheets, the browser may fire `load` synchronously on
1585
- // DOM insertion — BEFORE we can attach a listener — so listener-only
1586
- // waits get stuck on the 3 s guard. `.sheet !== null` indicates the
1587
- // CSSStyleSheet is already parsed and ready, which is the right
1588
- // condition to count it as "done." Cross-origin sheets still expose
1589
- // `.sheet` even though `.cssRules` throws — `.sheet !== null` is
1590
- // portable.
1591
- function isStyleLoaded(link) {
1592
- try { return link.sheet !== null; } catch(e) { return true; }
1593
- }
1594
- var pending = _newStyleLinks.filter(function(l) { return !isStyleLoaded(l); });
1595
- _tx("stylesheet-wait BEGIN", "newLinks=" + _newStyleLinks.length + " cachedSkipped=" + (_newStyleLinks.length - pending.length) + " pending=" + pending.length);
1596
- if(pending.length === 0) {
1597
- _tx("stylesheet-wait IMMEDIATE → doCallback");
1598
- doCallback();
1599
- } else {
1600
- var remaining = pending.length;
1601
- var fired = false;
1602
- // Safety valve: if a stylesheet fails or stalls, don't block forever.
1603
- var guard = setTimeout(function() {
1604
- if(!fired) {
1605
- _tx("stylesheet-wait GUARD fired (3s)", "remaining=" + remaining);
1606
- fired = true; doCallback();
1607
- }
1608
- }, 3000);
1609
- pending.forEach(function(link) {
1610
- function onDone(e) {
1611
- _tx("stylesheet-wait link.load", "remaining=" + (remaining-1) + " href=" + link.getAttribute("href"));
1612
- if(--remaining <= 0 && !fired) {
1613
- fired = true;
1614
- clearTimeout(guard);
1615
- _tx("stylesheet-wait ALL_LOADED → doCallback");
1616
- doCallback();
1617
- }
1618
- }
1619
- link.addEventListener('load', onDone, {once:true});
1620
- link.addEventListener('error', onDone, {once:true});
1621
- });
1622
- }
1623
- })();
1613
+ }.bind(this);
1624
1614
 
1625
- }.bind(this), _swapDelay);
1615
+ // Dispatch the swap. With VT enabled AND supported, wrap in
1616
+ // document.startViewTransition() so the browser captures OLD/NEW
1617
+ // snapshots and crossfades natively. The setTimeout wait is for
1618
+ // the CSS fade-out to complete BEFORE VT begins, so VT captures
1619
+ // the already-faded state cleanly. Errors inside the callback
1620
+ // don't abort the swap — fall back to direct execution.
1621
+ var _vtEnabled = Settings["use_view_transitions"]
1622
+ && typeof document.startViewTransition === "function";
1623
+ setTimeout(function() {
1624
+ if (_vtEnabled) {
1625
+ try {
1626
+ document.startViewTransition(_doSwapBody);
1627
+ } catch (e) {
1628
+ if (Settings.debug) console.warn("Transparent VT failed, falling back:", e);
1629
+ _doSwapBody();
1630
+ }
1631
+ } else {
1632
+ _doSwapBody();
1633
+ }
1634
+ }, activeInRemainingTime > 0 ? activeInRemainingTime : 1);
1626
1635
  }
1627
1636
 
1628
1637
  function uuidv4() {
@@ -1733,8 +1742,318 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
1733
1742
 
1734
1743
  var ajaxSemaphore = false;
1735
1744
  var formSubmission = false;
1745
+
1746
+ // ── User-typed form dirty tracking ──────────────────────────────────────
1747
+ //
1748
+ // True if the user has modified any form input via a real keystroke /
1749
+ // click / select. False after a fresh navigation OR after a form submit.
1750
+ // Used by onbeforeunload to decide whether to confirm.
1751
+ //
1752
+ // `e.isTrusted` filters out programmatic value mutations from JS init
1753
+ // code (Select2 setting the hidden field after dropdown selection,
1754
+ // Editor.js syncing JSON to a hidden <textarea>, datepicker init writing
1755
+ // a normalized value, etc.). Without this filter, the previous value-
1756
+ // comparison logic (formDataBefore vs formDataAfter) flagged every
1757
+ // page-with-form as "dirty" by the time the user hit Ctrl+W, even
1758
+ // when they hadn't typed anything.
1759
+ var formDirty = false;
1760
+ document.addEventListener('input', function(e) {
1761
+ if (!e.isTrusted) return;
1762
+ if (!e.target || !e.target.form) return;
1763
+ formDirty = true;
1764
+ }, true);
1765
+ document.addEventListener('change', function(e) {
1766
+ if (!e.isTrusted) return;
1767
+ if (!e.target || !e.target.form) return;
1768
+ formDirty = true;
1769
+ }, true);
1770
+ // Reset on user-initiated submit so the post-submit redirect doesn't
1771
+ // double-prompt. The existing `formSubmission` flag already handles
1772
+ // the synchronous prompt path; this clears state for any follow-up.
1773
+ document.addEventListener('submit', function() { formDirty = false; }, true);
1774
+
1775
+ // ── Transparent.formMemory ──────────────────────────────────────────────
1776
+ //
1777
+ // Persistent draft store for forms — survives accidental close, refresh,
1778
+ // power loss, browser crash. Keyed by URL + form identity (name or id).
1779
+ //
1780
+ // Save triggers:
1781
+ // - debounced (500ms) on user `input`/`change` events
1782
+ // - synchronously on beforeunload (last-resort capture for fields
1783
+ // mutated by JS like Editor.js / Select2 that don't fire trusted
1784
+ // `input` events)
1785
+ //
1786
+ // Restore: silently on initial DOMContentLoaded AND after each SPA swap
1787
+ // (transparent.js re-dispatches DOMContentLoaded post-swap, line ~1375).
1788
+ // Restored fields get `data-restored-from-draft=""` for optional
1789
+ // project-level toast / styling.
1790
+ //
1791
+ // Clear: on form submit + on TTL expiry (7 days) + manually via
1792
+ // `Transparent.formMemory.clear(form)`.
1793
+ //
1794
+ // Opt-out:
1795
+ // - `<form data-no-persist>` — entire form skipped
1796
+ // - `<input data-no-persist>` — single field skipped
1797
+ // - Auto-skipped: type="password", type="file", type="submit"/button,
1798
+ // and any hidden field whose name contains `_token` or `csrf`
1799
+ // (Symfony CSRF token field). These are never persisted.
1800
+ //
1801
+ // Editor.js compatibility: Editor.js reads its initial JSON from
1802
+ // `data-edjs` attribute (not `.value`). On restore, if the field is a
1803
+ // <textarea data-edjs>, we mirror the restored value into `data-edjs`
1804
+ // too so Editor.js renders the draft when its init pass runs.
1805
+ Transparent.formMemory = (function() {
1806
+ var KEY_PREFIX = 'tx-form-memory:';
1807
+ var DEFAULT_TTL = 7 * 24 * 60 * 60 * 1000; // 7 days
1808
+ var DEBOUNCE = 500;
1809
+
1810
+ var saveTimers = new WeakMap();
1811
+ var api = {
1812
+ enabled : true,
1813
+ ttl : DEFAULT_TTL,
1814
+ debounce: DEBOUNCE,
1815
+ };
1816
+
1817
+ function shouldSkipField(field) {
1818
+ if (!field.name) return true;
1819
+ var type = (field.type || '').toLowerCase();
1820
+ if (type === 'password' || type === 'file') return true;
1821
+ if (type === 'submit' || type === 'button' || type === 'reset') return true;
1822
+ if (field.hasAttribute && field.hasAttribute('data-no-persist')) return true;
1823
+ // CSRF tokens — never persist. Matches Symfony's `_token` and
1824
+ // any other token-named hidden input (`csrf`, `_csrf_token`, ...).
1825
+ if (type === 'hidden') {
1826
+ var n = field.name.toLowerCase();
1827
+ if (n.indexOf('_token') !== -1 || n.indexOf('csrf') !== -1) return true;
1828
+ }
1829
+ return false;
1830
+ }
1831
+
1832
+ function shouldSkipForm(form) {
1833
+ if (!form) return true;
1834
+ if (form.hasAttribute && form.hasAttribute('data-no-persist')) return true;
1835
+ if (!form.name && !form.id) return true; // need identity for key
1836
+ return false;
1837
+ }
1838
+
1839
+ function getKey(form) {
1840
+ return KEY_PREFIX + location.pathname + ':' + (form.name || form.id);
1841
+ }
1842
+
1843
+ function readLS(key) {
1844
+ try { return localStorage.getItem(key); } catch (e) { return null; }
1845
+ }
1846
+ function writeLS(key, val) {
1847
+ try { localStorage.setItem(key, val); } catch (e) {
1848
+ // Quota exceeded or storage disabled — fail silent. The
1849
+ // user keeps their work in memory, just loses persistence.
1850
+ }
1851
+ }
1852
+ function removeLS(key) {
1853
+ try { localStorage.removeItem(key); } catch (e) {}
1854
+ }
1855
+
1856
+ api.save = function(form) {
1857
+ if (!api.enabled) return;
1858
+ if (shouldSkipForm(form)) return;
1859
+
1860
+ var data = {};
1861
+ var elements = form.elements;
1862
+ for (var i = 0; i < elements.length; i++) {
1863
+ var field = elements[i];
1864
+ if (shouldSkipField(field)) continue;
1865
+
1866
+ var type = (field.type || '').toLowerCase();
1867
+ if (type === 'checkbox' || type === 'radio') {
1868
+ if (!field.checked) continue;
1869
+ if (data[field.name] === undefined) {
1870
+ data[field.name] = field.value;
1871
+ } else if (Array.isArray(data[field.name])) {
1872
+ data[field.name].push(field.value);
1873
+ } else {
1874
+ data[field.name] = [data[field.name], field.value];
1875
+ }
1876
+ } else if (field.tagName === 'SELECT' && field.multiple) {
1877
+ var sel = [];
1878
+ for (var j = 0; j < field.options.length; j++) {
1879
+ if (field.options[j].selected) sel.push(field.options[j].value);
1880
+ }
1881
+ data[field.name] = sel;
1882
+ } else {
1883
+ data[field.name] = field.value;
1884
+ }
1885
+ }
1886
+
1887
+ if (Object.keys(data).length === 0) {
1888
+ // No persistable fields with data — clear any stale entry
1889
+ // rather than write an empty record (avoids restoring "all
1890
+ // empty" later and overwriting newly-pre-filled fields).
1891
+ removeLS(getKey(form));
1892
+ return;
1893
+ }
1894
+
1895
+ writeLS(getKey(form), JSON.stringify({ t: Date.now(), d: data }));
1896
+ };
1897
+
1898
+ api.restore = function(form) {
1899
+ if (!api.enabled) return;
1900
+ if (shouldSkipForm(form)) return;
1901
+
1902
+ var key = getKey(form);
1903
+ var raw = readLS(key);
1904
+ if (!raw) return;
1905
+
1906
+ var entry;
1907
+ try { entry = JSON.parse(raw); }
1908
+ catch (e) { removeLS(key); return; }
1909
+
1910
+ if (!entry || !entry.t || !entry.d) { removeLS(key); return; }
1911
+ if (Date.now() - entry.t > api.ttl) { removeLS(key); return; }
1912
+
1913
+ Object.keys(entry.d).forEach(function(name) {
1914
+ var value = entry.d[name];
1915
+ // Use attr-selector with CSS.escape to handle names like
1916
+ // `Article[content]` that contain brackets.
1917
+ var sel = '[name="' + (typeof CSS !== 'undefined' && CSS.escape
1918
+ ? CSS.escape(name)
1919
+ : name.replace(/(["\\\[\]])/g, '\\$1')) + '"]';
1920
+ var fields = form.querySelectorAll(sel);
1921
+ if (fields.length === 0) return;
1922
+
1923
+ for (var k = 0; k < fields.length; k++) {
1924
+ var field = fields[k];
1925
+ if (shouldSkipField(field)) continue;
1926
+
1927
+ var type = (field.type || '').toLowerCase();
1928
+ if (type === 'checkbox' || type === 'radio') {
1929
+ field.checked = Array.isArray(value)
1930
+ ? (value.indexOf(field.value) !== -1)
1931
+ : (field.value === value);
1932
+ } else if (field.tagName === 'SELECT' && field.multiple) {
1933
+ if (Array.isArray(value)) {
1934
+ for (var m = 0; m < field.options.length; m++) {
1935
+ field.options[m].selected = (value.indexOf(field.options[m].value) !== -1);
1936
+ }
1937
+ }
1938
+ } else {
1939
+ field.value = value;
1940
+ // Editor.js mirrors: Editor.js reads its initial JSON
1941
+ // from the `data-edjs` attribute, not from .value. So
1942
+ // we have to mirror the restored value into the attr
1943
+ // for the upcoming Editor.js init pass to pick it up.
1944
+ if (field.tagName === 'TEXTAREA' && field.hasAttribute('data-edjs')) {
1945
+ field.setAttribute('data-edjs', value);
1946
+ }
1947
+ }
1948
+ field.setAttribute('data-restored-from-draft', '');
1949
+ }
1950
+ });
1951
+ };
1952
+
1953
+ api.clear = function(form) {
1954
+ if (!form) return;
1955
+ if (shouldSkipForm(form)) return;
1956
+ removeLS(getKey(form));
1957
+ };
1958
+
1959
+ api.restoreAll = function() {
1960
+ var forms = document.querySelectorAll('form');
1961
+ for (var i = 0; i < forms.length; i++) api.restore(forms[i]);
1962
+ };
1963
+
1964
+ api.saveAll = function() {
1965
+ var forms = document.querySelectorAll('form');
1966
+ for (var i = 0; i < forms.length; i++) api.save(forms[i]);
1967
+ };
1968
+
1969
+ api.clearExpired = function() {
1970
+ var ttl = api.ttl;
1971
+ var now = Date.now();
1972
+ try {
1973
+ for (var i = localStorage.length - 1; i >= 0; i--) {
1974
+ var key = localStorage.key(i);
1975
+ if (!key || key.indexOf(KEY_PREFIX) !== 0) continue;
1976
+ var raw;
1977
+ try { raw = localStorage.getItem(key); }
1978
+ catch (e) { continue; }
1979
+ var entry = null;
1980
+ try { entry = JSON.parse(raw); } catch (e) {}
1981
+ if (!entry || !entry.t || (now - entry.t > ttl)) {
1982
+ removeLS(key);
1983
+ }
1984
+ }
1985
+ } catch (e) {}
1986
+ };
1987
+
1988
+ // Debounced per-form save scheduler. WeakMap → no leak when forms
1989
+ // get removed from the DOM (e.g., on SPA swap).
1990
+ function debouncedSave(form) {
1991
+ if (!form || shouldSkipForm(form)) return;
1992
+ var existing = saveTimers.get(form);
1993
+ if (existing) clearTimeout(existing);
1994
+ saveTimers.set(form, setTimeout(function() {
1995
+ api.save(form);
1996
+ }, api.debounce));
1997
+ }
1998
+
1999
+ // Event wiring. Capture phase + isTrusted gate matches the
2000
+ // formDirty pattern above — programmatic field mutations from
2001
+ // Select2/Editor.js init code don't trigger a save here, which is
2002
+ // correct (those are not "user changes"; saving them would persist
2003
+ // server-rendered defaults as if they were user input).
2004
+ document.addEventListener('input', function(e) {
2005
+ if (!e.isTrusted) return;
2006
+ if (!e.target || !e.target.form) return;
2007
+ debouncedSave(e.target.form);
2008
+ }, true);
2009
+ document.addEventListener('change', function(e) {
2010
+ if (!e.isTrusted) return;
2011
+ if (!e.target || !e.target.form) return;
2012
+ debouncedSave(e.target.form);
2013
+ }, true);
2014
+
2015
+ // Successful submit clears the draft. We listen in capture so we
2016
+ // run before any user-side submit handler that might cancel.
2017
+ document.addEventListener('submit', function(e) {
2018
+ if (e.target && e.target.tagName === 'FORM') {
2019
+ api.clear(e.target);
2020
+ }
2021
+ }, true);
2022
+
2023
+ // Last-resort save on page exit. Catches state mutated only by JS
2024
+ // (Editor.js content syncs, Select2 hidden-field writes) that
2025
+ // never fired trusted input/change events. Synchronous because
2026
+ // beforeunload doesn't await microtasks.
2027
+ window.addEventListener('beforeunload', function() {
2028
+ if (!api.enabled) return;
2029
+ // Only save if the user has actually typed something — same
2030
+ // gate as the unload-confirm prompt above. If formDirty is
2031
+ // false, drafts written from the debounced handler are stale
2032
+ // and we don't want to refresh them on every page-close.
2033
+ if (formDirty) api.saveAll();
2034
+ });
2035
+
2036
+ // Initial restore. If we're already past DOMContentLoaded (defer
2037
+ // scripts run after parsing but before DCL), run synchronously.
2038
+ // For SPA navs, transparent.js re-dispatches DOMContentLoaded in
2039
+ // _doSwap (around line 1375), so this same listener fires again
2040
+ // on every swap — no extra wiring needed.
2041
+ if (document.readyState === 'loading') {
2042
+ document.addEventListener('DOMContentLoaded', api.restoreAll);
2043
+ } else {
2044
+ api.restoreAll();
2045
+ }
2046
+ document.addEventListener('DOMContentLoaded', api.restoreAll);
2047
+
2048
+ // Cleanup expired entries — once at startup, deferred so it
2049
+ // doesn't block first paint.
2050
+ setTimeout(api.clearExpired, 2000);
2051
+
2052
+ return api;
2053
+ })();
2054
+
1736
2055
  function __main__(e) {
1737
- _tx("__main__ ENTRY", "event=" + e.type + (e.target && e.target.tagName ? " target=" + e.target.tagName : ""));
2056
+
1738
2057
  // Disable transparent JS (e.g. during development..)
1739
2058
  if(Settings.disable) return;
1740
2059
 
@@ -1826,17 +2145,6 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
1826
2145
  if (ajaxSemaphore) return;
1827
2146
  if (url == location) return;
1828
2147
 
1829
- // Block navigation when offline. Project CSS / JS can react to
1830
- // html.offline + the transparent:offline event to surface a banner.
1831
- // The event is re-dispatched here on each attempted navigation so a
1832
- // listener can briefly flash/highlight the banner to acknowledge the
1833
- // click instead of doing nothing silently.
1834
- if (!isOnline || (typeof navigator !== "undefined" && navigator.onLine === false)) {
1835
- setOnlineStatus(false);
1836
- dispatchEvent(new Event("transparent:offline"));
1837
- return;
1838
- }
1839
-
1840
2148
  if((e.type == Transparent.state.CLICK || e.type == Transparent.state.HASHCHANGE) && url.pathname == location.pathname && url.search == location.search && type != "POST") {
1841
2149
 
1842
2150
  if(!url.hash) return;
@@ -1862,7 +2170,7 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
1862
2170
  $(Transparent.html).stop();
1863
2171
 
1864
2172
  Transparent.html.addClass(Transparent.state.LOADING);
1865
- Transparent.fadeIn();
2173
+ Transparent.activeIn();
1866
2174
 
1867
2175
  function isJsonResponse(str) {
1868
2176
  try { JSON.parse(str); return true; }
@@ -1870,7 +2178,6 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
1870
2178
  }
1871
2179
 
1872
2180
  function handleResponse(uuid, status = 200, method = null, data = null, xhr = null, request = null) {
1873
- _tx("handleResponse ENTRY", "status=" + status + " method=" + method);
1874
2181
 
1875
2182
  ajaxSemaphore = false;
1876
2183
 
@@ -1906,7 +2213,26 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
1906
2213
  Transparent.setResponse(uuid, responseText);
1907
2214
  }
1908
2215
 
1909
- var dom = new DOMParser().parseFromString(responseText, "text/html");
2216
+ // Try the in-memory live-DOM cache first. On popstate (back/forward)
2217
+ // we just stored the outgoing page node via setLiveResponse, so the
2218
+ // round-trip is: snapshot → cache → instant retrieve. No serialize,
2219
+ // no DOMParser cost. Falls back to the parse path on miss (first-
2220
+ // time nav, cache eviction, expired entry, etc.).
2221
+ var dom = null;
2222
+ if (Transparent.getLiveResponse) {
2223
+ var liveNode = Transparent.getLiveResponse(uuid);
2224
+ if (liveNode) {
2225
+ // The cache stores the full <html> element. Wrap it in a
2226
+ // minimal Document-shaped object that the swap path can
2227
+ // navigate the same way it navigates a DOMParser result.
2228
+ var docShell = document.implementation.createHTMLDocument('');
2229
+ docShell.replaceChild(liveNode, docShell.documentElement);
2230
+ dom = docShell;
2231
+ }
2232
+ }
2233
+ if (!dom) {
2234
+ dom = new DOMParser().parseFromString(responseText, "text/html");
2235
+ }
1910
2236
  if(request && request.getResponseHeader("Content-Type") == "application/json") {
1911
2237
 
1912
2238
  if(!isJsonResponse(responseText)) {
@@ -1956,18 +2282,12 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
1956
2282
  history.pushState({uuid: uuid, status:status, method: method, data: {}, href: responseURL}, '', responseURL);
1957
2283
 
1958
2284
  // Page not recognized.. just go fetch by yourself.. no POST information transmitted..
1959
- // Defer the redirect until fadeIn settles, same reasoning as the
1960
- // html.reload path above.
1961
- if(!Transparent.isPage(dom)) {
1962
- _waitForFadeIn(function() { window.location.href = url; });
1963
- return;
1964
- }
2285
+ if(!Transparent.isPage(dom))
2286
+ return window.location.href = url;
1965
2287
 
1966
2288
  // Layout not compatible.. needs to be reloaded (exception when POST is detected..)
1967
- if(!Transparent.isCompatiblePage(dom, method, data)) {
1968
- _waitForFadeIn(function() { window.location.href = url; });
1969
- return;
1970
- }
2289
+ if(!Transparent.isCompatiblePage(dom, method, data))
2290
+ return window.location.href = url;
1971
2291
 
1972
2292
  // Mark layout as known
1973
2293
  if(!Transparent.isKnownLayout(dom)) {
@@ -1995,46 +2315,16 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
1995
2315
  Transparent.html.addClass(Transparent.state.SAME);
1996
2316
 
1997
2317
  var switchLayout = Transparent.state.SWITCH.replace("X", prevLayout).replace("Y", newLayout);
1998
- _tx("handleResponse switchLayout", "prev=" + prevLayout + " new=" + newLayout + " adds=." + switchLayout);
1999
2318
  Transparent.html.addClass(switchLayout);
2000
2319
 
2001
2320
  dispatchEvent(new Event('transparent:'+switchLayout));
2002
2321
 
2003
- if($(dom).find("html").hasClass(Transparent.state.RELOAD) || $(dom).find("html").hasClass(Transparent.state.DISABLE)) {
2004
- // Defer the reload until fadeIn has finished, so the loader is
2005
- // at full opacity when the browser unloads. Without this, a
2006
- // fast AJAX response can fire reload() while fadeIn is still
2007
- // mid-animation: the browser swaps to a page that starts with
2008
- // .active (loader at 100%), and the user perceives a snap
2009
- // from in-progress opacity to full. Reading as "fade-out then
2010
- // fade-in" because the partial loader receded as the browser
2011
- // swapped frames.
2012
- _waitForFadeIn(function() { window.location.reload(); });
2013
- return;
2014
- }
2015
-
2016
- // Kick off preloads for stylesheets the new page needs but aren't yet in <head>.
2017
- // They download in parallel during the fadeIn animation so onLoad() finds them
2018
- // already cached — eliminating FOUC on cold-cache layout transitions.
2019
- (function() {
2020
- var loaded = {};
2021
- $("head").children("link[rel='stylesheet']").each(function() {
2022
- var h = this.getAttribute("href"); if(h) loaded[h] = true;
2023
- });
2024
-
2025
- $(dom).find("head").children("link[rel='stylesheet']").each(function() {
2026
- var h = this.getAttribute("href");
2027
- if(!h || loaded[h]) return;
2028
- if($("head").find("link[rel='preload'][href='" + h.replace(/'/g, "\\'") + "']").length) return;
2029
- var pl = document.createElement("link");
2030
- pl.rel = "preload"; pl.as = "style"; pl.href = h;
2031
- document.head.appendChild(pl);
2032
- });
2033
- })();
2322
+ if($(dom).find("html").hasClass(Transparent.state.RELOAD) || $(dom).find("html").hasClass(Transparent.state.DISABLE))
2323
+ return window.location.reload();
2034
2324
 
2035
2325
  return Transparent.onLoad(uuid, dom, function() {
2036
2326
 
2037
- Transparent.fadeOut(function() {
2327
+ Transparent.activeOut(function() {
2038
2328
 
2039
2329
  Transparent.html
2040
2330
  .removeClass(switchLayout)
@@ -2057,7 +2347,7 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
2057
2347
  if(history.state)
2058
2348
  Transparent.setResponse(history.state.uuid, Transparent.html[0], Transparent.getScrollableElementXY());
2059
2349
 
2060
- $(Transparent.html).prop("user-scroll", false); // make sure to avoid page jump during transition (cancelled in fadeIn callback)
2350
+ $(Transparent.html).prop("user-scroll", false); // make sure to avoid page jump during transition (cancelled in activeIn callback)
2061
2351
 
2062
2352
  // Submit ajax request..
2063
2353
  if(form) form.dispatchEvent(new SubmitEvent("submit", { submitter: formTrigger }));
@@ -2072,18 +2362,8 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
2072
2362
  processData: false,
2073
2363
  headers: Settings["headers"] || {},
2074
2364
  xhr: function () { return xhr; },
2075
- success: function (html, status, request) { _tx("ajax SUCCESS", "status=" + request.status); return handleResponse(uuid, request.status, type, data, xhr, request); },
2076
- error: function (request, ajaxOptions, thrownError) {
2077
- _tx("ajax ERROR", "status=" + request.status + " textStatus=" + ajaxOptions);
2078
- // status=0 with non-abort textStatus typically means the device
2079
- // couldn't reach the server: dropped connection, DNS failure,
2080
- // captive portal, etc. Flip to offline so the project's banner
2081
- // surfaces even if navigator.onLine still reports true.
2082
- if (request.status === 0 && ajaxOptions !== "abort") {
2083
- setOnlineStatus(false);
2084
- }
2085
- return handleResponse(uuid, request.status, type, data, xhr, request);
2086
- }
2365
+ success: function (html, status, request) { return handleResponse(uuid, request.status, type, data, xhr, request); },
2366
+ error: function (request, ajaxOptions, thrownError) { return handleResponse(uuid, request.status, type, data, xhr, request); }
2087
2367
  });
2088
2368
  }
2089
2369
 
@@ -2114,99 +2394,33 @@ jQuery.event.special.mousewheel = { setup: function( _, ns, handle ) { this.addE
2114
2394
  window.onpopstate = __main__; // Onpopstate pop out straight to previous page.. this creates a jump while changing pages with hash..
2115
2395
  window.onhashchange = __main__;
2116
2396
 
2117
- var formDataBefore = {};
2118
- $(window).on("load", function() {
2119
-
2120
- formDataBefore = {};
2121
- $("form").each(function() {
2122
-
2123
- var formData = new FormData();
2124
- var formInput = $("[name^='"+this.name+"\[']");
2125
- formInput.each(function() {
2126
-
2127
- if(this.type == "file") {
2128
-
2129
- for(var i = 0; i < this.files.length; i++)
2130
- formData.append(this.name+"["+i+"]", this.files[i].name+";"+this.files[i].size+";"+this.files[i].lastModified);
2131
-
2132
- } else formData.append(this.name, this.value);
2133
- });
2134
-
2135
- for (var [fieldName,fieldValue] of formData.entries()) {
2136
-
2137
- if(!fieldName.endsWith("[]") && fieldName != "undefined")
2138
- formDataBefore[fieldName] = fieldValue;
2139
- }
2140
- });
2141
- });
2142
-
2397
+ // onbeforeunload: confirm only if the user has actually typed/edited
2398
+ // a form input on this page. Pre-Turbo this used a snapshot-and-
2399
+ // compare approach (formDataBefore vs formDataAfter) which gave
2400
+ // false positives because JS init code mutates form values after
2401
+ // load — Select2 writes selected text to hidden fields, Editor.js
2402
+ // serializes its JSON to a <textarea>, datepicker normalizes
2403
+ // formats, etc. so by the time the user hit Ctrl+W the snapshot
2404
+ // and the current state always differed, and the browser always
2405
+ // prompted even on read-only pages.
2406
+ //
2407
+ // The replacement is the `formDirty` flag declared above, which is
2408
+ // set only by trusted (user-originated) `input`/`change` events.
2409
+ // No prompt unless the user genuinely typed something.
2143
2410
  window.onbeforeunload = function(e) {
2144
2411
 
2145
2412
  if(Settings.debug) console.log("Transparent onbeforeunload event called..");
2146
2413
 
2147
2414
  if(formSubmission) return; // Do not display on form submission
2148
2415
  if(Settings.disable) return;
2149
-
2150
2416
  if(e.currentTarget == window) return;
2417
+ if(!formDirty) return; // ← user hasn't modified anything; no prompt
2151
2418
 
2152
- var preventDefault = false;
2153
- var formDataAfter = [];
2154
- $("form").each(function() {
2155
-
2156
- var formData = new FormData();
2157
- var formInput = $("[name^='"+this.name+"\[']");
2158
- formInput.each(function() {
2159
-
2160
- if(this.type == "file") {
2161
-
2162
- for(var i = 0; i < this.files.length; i++)
2163
- formData.append(this.name+"["+i+"]", this.files[i].name+";"+this.files[i].size+";"+this.files[i].lastModified);
2164
-
2165
- } else formData.append(this.name, this.value);
2166
- });
2167
-
2168
- for (var [fieldName,fieldValue] of formData.entries()) {
2169
-
2170
- if(!fieldName.endsWith("[]") && fieldName != "undefined")
2171
- formDataAfter[fieldName] = fieldValue;
2172
- }
2173
- });
2174
-
2175
- var formDataBeforeKeys = Object.keys(formDataBefore);
2176
- var formDataAfterKeys = Object.keys(formDataAfter);
2177
- function same(a, b) { return JSON.stringify(a) === JSON.stringify(b); }
2178
- function sameKeys(a, b) {
2419
+ Transparent.html.addClass(Transparent.state.READY);
2420
+ Transparent.activeOut();
2421
+ dispatchEvent(new Event('load'));
2179
2422
 
2180
- var aKeys = Object.keys(a).sort();
2181
- var bKeys = Object.keys(b).sort();
2182
- return JSON.stringify(aKeys) === JSON.stringify(bKeys);
2183
- }
2184
-
2185
- if(!sameKeys(formDataBeforeKeys, formDataAfterKeys)) preventDefault = true;
2186
- else {
2187
-
2188
- for (var [fieldName,fieldValueAfter] of Object.entries(formDataAfter)) {
2189
-
2190
- var fieldValueBefore = formDataBefore[fieldName];
2191
- if(fieldValueBefore instanceof File) {
2192
-
2193
- if(!fieldValueAfter instanceof File) preventDefault = true;
2194
- else if (fieldValueBefore.size != fieldValueAfter.size) preventDefault = true;
2195
-
2196
- } else if(fieldValueBefore != fieldValueAfter) {
2197
- preventDefault = true;
2198
- }
2199
- }
2200
- }
2201
-
2202
- if(Settings.debug || preventDefault) {
2203
-
2204
- if(preventDefault) Transparent.html.addClass(Transparent.state.READY);
2205
- if(preventDefault) Transparent.fadeOut();
2206
- if(preventDefault) dispatchEvent(new Event('load'));
2207
-
2208
- return "Dude, are you sure you want to leave? Think of the kittens!";
2209
- }
2423
+ return "Dude, are you sure you want to leave? Think of the kittens!";
2210
2424
  }
2211
2425
 
2212
2426
  document.addEventListener('click', __main__, false);