turbo-rails 1.5.0 → 2.0.0.pre.beta.2

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,19 +1,7 @@
1
- (function() {
2
- if (window.Reflect === undefined || window.customElements === undefined || window.customElements.polyfillWrapFlushCallback) {
3
- return;
4
- }
5
- const BuiltInHTMLElement = HTMLElement;
6
- const wrapperForTheName = {
7
- HTMLElement: function HTMLElement() {
8
- return Reflect.construct(BuiltInHTMLElement, [], this.constructor);
9
- }
10
- };
11
- window.HTMLElement = wrapperForTheName["HTMLElement"];
12
- HTMLElement.prototype = BuiltInHTMLElement.prototype;
13
- HTMLElement.prototype.constructor = HTMLElement;
14
- Object.setPrototypeOf(HTMLElement, BuiltInHTMLElement);
15
- })();
16
-
1
+ /*!
2
+ Turbo 8.0.0-beta.2
3
+ Copyright © 2023 37signals LLC
4
+ */
17
5
  (function(prototype) {
18
6
  if (typeof prototype.requestSubmit == "function") return;
19
7
  prototype.requestSubmit = function(submitter) {
@@ -44,7 +32,7 @@ const submittersByForm = new WeakMap;
44
32
  function findSubmitterFromClickTarget(target) {
45
33
  const element = target instanceof Element ? target : target instanceof Node ? target.parentElement : null;
46
34
  const candidate = element ? element.closest("input, button") : null;
47
- return (candidate === null || candidate === void 0 ? void 0 : candidate.type) == "submit" ? candidate : null;
35
+ return candidate?.type == "submit" ? candidate : null;
48
36
  }
49
37
 
50
38
  function clickCaptured(event) {
@@ -57,10 +45,13 @@ function clickCaptured(event) {
57
45
  (function() {
58
46
  if ("submitter" in Event.prototype) return;
59
47
  let prototype = window.Event.prototype;
60
- if ("SubmitEvent" in window && /Apple Computer/.test(navigator.vendor)) {
61
- prototype = window.SubmitEvent.prototype;
62
- } else if ("SubmitEvent" in window) {
63
- return;
48
+ if ("SubmitEvent" in window) {
49
+ const prototypeOfSubmitEvent = window.SubmitEvent.prototype;
50
+ if (/Apple Computer/.test(navigator.vendor) && !("submitter" in prototypeOfSubmitEvent)) {
51
+ prototype = prototypeOfSubmitEvent;
52
+ } else {
53
+ return;
54
+ }
64
55
  }
65
56
  addEventListener("click", clickCaptured, true);
66
57
  Object.defineProperty(prototype, "submitter", {
@@ -72,20 +63,19 @@ function clickCaptured(event) {
72
63
  });
73
64
  })();
74
65
 
75
- var FrameLoadingStyle;
76
-
77
- (function(FrameLoadingStyle) {
78
- FrameLoadingStyle["eager"] = "eager";
79
- FrameLoadingStyle["lazy"] = "lazy";
80
- })(FrameLoadingStyle || (FrameLoadingStyle = {}));
66
+ const FrameLoadingStyle = {
67
+ eager: "eager",
68
+ lazy: "lazy"
69
+ };
81
70
 
82
71
  class FrameElement extends HTMLElement {
72
+ static delegateConstructor=undefined;
73
+ loaded=Promise.resolve();
83
74
  static get observedAttributes() {
84
75
  return [ "disabled", "complete", "loading", "src" ];
85
76
  }
86
77
  constructor() {
87
78
  super();
88
- this.loaded = Promise.resolve();
89
79
  this.delegate = new FrameElement.delegateConstructor(this);
90
80
  }
91
81
  connectedCallback() {
@@ -118,6 +108,16 @@ class FrameElement extends HTMLElement {
118
108
  this.removeAttribute("src");
119
109
  }
120
110
  }
111
+ get refresh() {
112
+ return this.getAttribute("refresh");
113
+ }
114
+ set refresh(value) {
115
+ if (value) {
116
+ this.setAttribute("refresh", value);
117
+ } else {
118
+ this.removeAttribute("refresh");
119
+ }
120
+ }
121
121
  get loading() {
122
122
  return frameLoadingStyleFromString(this.getAttribute("loading") || "");
123
123
  }
@@ -155,8 +155,7 @@ class FrameElement extends HTMLElement {
155
155
  return this.ownerDocument === document && !this.isPreview;
156
156
  }
157
157
  get isPreview() {
158
- var _a, _b;
159
- return (_b = (_a = this.ownerDocument) === null || _a === void 0 ? void 0 : _a.documentElement) === null || _b === void 0 ? void 0 : _b.hasAttribute("data-turbo-preview");
158
+ return this.ownerDocument?.documentElement?.hasAttribute("data-turbo-preview");
160
159
  }
161
160
  }
162
161
 
@@ -183,8 +182,8 @@ function getAnchor(url) {
183
182
  }
184
183
  }
185
184
 
186
- function getAction(form, submitter) {
187
- const action = (submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute("formaction")) || form.getAttribute("action") || form.action;
185
+ function getAction$1(form, submitter) {
186
+ const action = submitter?.getAttribute("formaction") || form.getAttribute("action") || form.action;
188
187
  return expandURL(action);
189
188
  }
190
189
 
@@ -323,6 +322,14 @@ function dispatch(eventName, {target: target, cancelable: cancelable, detail: de
323
322
  return event;
324
323
  }
325
324
 
325
+ function nextRepaint() {
326
+ if (document.visibilityState === "hidden") {
327
+ return nextEventLoopTick();
328
+ } else {
329
+ return nextAnimationFrame();
330
+ }
331
+ }
332
+
326
333
  function nextAnimationFrame() {
327
334
  return new Promise((resolve => requestAnimationFrame((() => resolve()))));
328
335
  }
@@ -370,7 +377,7 @@ function uuid() {
370
377
  }
371
378
 
372
379
  function getAttribute(attributeName, ...elements) {
373
- for (const value of elements.map((element => element === null || element === void 0 ? void 0 : element.getAttribute(attributeName)))) {
380
+ for (const value of elements.map((element => element?.getAttribute(attributeName)))) {
374
381
  if (typeof value == "string") return value;
375
382
  }
376
383
  return null;
@@ -456,21 +463,57 @@ function setMetaContent(name, content) {
456
463
  }
457
464
 
458
465
  function findClosestRecursively(element, selector) {
459
- var _a;
460
466
  if (element instanceof Element) {
461
- return element.closest(selector) || findClosestRecursively(element.assignedSlot || ((_a = element.getRootNode()) === null || _a === void 0 ? void 0 : _a.host), selector);
467
+ return element.closest(selector) || findClosestRecursively(element.assignedSlot || element.getRootNode()?.host, selector);
468
+ }
469
+ }
470
+
471
+ function elementIsFocusable(element) {
472
+ const inertDisabledOrHidden = "[inert], :disabled, [hidden], details:not([open]), dialog:not([open])";
473
+ return !!element && element.closest(inertDisabledOrHidden) == null && typeof element.focus == "function";
474
+ }
475
+
476
+ function queryAutofocusableElement(elementOrDocumentFragment) {
477
+ return Array.from(elementOrDocumentFragment.querySelectorAll("[autofocus]")).find(elementIsFocusable);
478
+ }
479
+
480
+ async function around(callback, reader) {
481
+ const before = reader();
482
+ callback();
483
+ await nextAnimationFrame();
484
+ const after = reader();
485
+ return [ before, after ];
486
+ }
487
+
488
+ class LimitedSet extends Set {
489
+ constructor(maxSize) {
490
+ super();
491
+ this.maxSize = maxSize;
492
+ }
493
+ add(value) {
494
+ if (this.size >= this.maxSize) {
495
+ const iterator = this.values();
496
+ const oldestValue = iterator.next().value;
497
+ this.delete(oldestValue);
498
+ }
499
+ super.add(value);
462
500
  }
463
501
  }
464
502
 
465
- var FetchMethod;
503
+ const recentRequests = new LimitedSet(20);
504
+
505
+ const nativeFetch = window.fetch;
466
506
 
467
- (function(FetchMethod) {
468
- FetchMethod[FetchMethod["get"] = 0] = "get";
469
- FetchMethod[FetchMethod["post"] = 1] = "post";
470
- FetchMethod[FetchMethod["put"] = 2] = "put";
471
- FetchMethod[FetchMethod["patch"] = 3] = "patch";
472
- FetchMethod[FetchMethod["delete"] = 4] = "delete";
473
- })(FetchMethod || (FetchMethod = {}));
507
+ function fetchWithTurboHeaders(url, options = {}) {
508
+ const modifiedHeaders = new Headers(options.headers || {});
509
+ const requestUID = uuid();
510
+ recentRequests.add(requestUID);
511
+ modifiedHeaders.append("X-Turbo-Request-Id", requestUID);
512
+ return nativeFetch(url, {
513
+ ...options,
514
+ headers: modifiedHeaders
515
+ });
516
+ }
474
517
 
475
518
  function fetchMethodFromString(method) {
476
519
  switch (method.toLowerCase()) {
@@ -491,16 +534,81 @@ function fetchMethodFromString(method) {
491
534
  }
492
535
  }
493
536
 
537
+ const FetchMethod = {
538
+ get: "get",
539
+ post: "post",
540
+ put: "put",
541
+ patch: "patch",
542
+ delete: "delete"
543
+ };
544
+
545
+ function fetchEnctypeFromString(encoding) {
546
+ switch (encoding.toLowerCase()) {
547
+ case FetchEnctype.multipart:
548
+ return FetchEnctype.multipart;
549
+
550
+ case FetchEnctype.plain:
551
+ return FetchEnctype.plain;
552
+
553
+ default:
554
+ return FetchEnctype.urlEncoded;
555
+ }
556
+ }
557
+
558
+ const FetchEnctype = {
559
+ urlEncoded: "application/x-www-form-urlencoded",
560
+ multipart: "multipart/form-data",
561
+ plain: "text/plain"
562
+ };
563
+
494
564
  class FetchRequest {
495
- constructor(delegate, method, location, body = new URLSearchParams, target = null) {
496
- this.abortController = new AbortController;
497
- this.resolveRequestPromise = _value => {};
565
+ abortController=new AbortController;
566
+ #resolveRequestPromise=_value => {};
567
+ constructor(delegate, method, location, requestBody = new URLSearchParams, target = null, enctype = FetchEnctype.urlEncoded) {
568
+ const [url, body] = buildResourceAndBody(expandURL(location), method, requestBody, enctype);
498
569
  this.delegate = delegate;
499
- this.method = method;
500
- this.headers = this.defaultHeaders;
501
- this.body = body;
502
- this.url = location;
570
+ this.url = url;
503
571
  this.target = target;
572
+ this.fetchOptions = {
573
+ credentials: "same-origin",
574
+ redirect: "follow",
575
+ method: method,
576
+ headers: {
577
+ ...this.defaultHeaders
578
+ },
579
+ body: body,
580
+ signal: this.abortSignal,
581
+ referrer: this.delegate.referrer?.href
582
+ };
583
+ this.enctype = enctype;
584
+ }
585
+ get method() {
586
+ return this.fetchOptions.method;
587
+ }
588
+ set method(value) {
589
+ const fetchBody = this.isSafe ? this.url.searchParams : this.fetchOptions.body || new FormData;
590
+ const fetchMethod = fetchMethodFromString(value) || FetchMethod.get;
591
+ this.url.search = "";
592
+ const [url, body] = buildResourceAndBody(this.url, fetchMethod, fetchBody, this.enctype);
593
+ this.url = url;
594
+ this.fetchOptions.body = body;
595
+ this.fetchOptions.method = fetchMethod;
596
+ }
597
+ get headers() {
598
+ return this.fetchOptions.headers;
599
+ }
600
+ set headers(value) {
601
+ this.fetchOptions.headers = value;
602
+ }
603
+ get body() {
604
+ if (this.isSafe) {
605
+ return this.url.searchParams;
606
+ } else {
607
+ return this.fetchOptions.body;
608
+ }
609
+ }
610
+ set body(value) {
611
+ this.fetchOptions.body = value;
504
612
  }
505
613
  get location() {
506
614
  return this.url;
@@ -517,14 +625,14 @@ class FetchRequest {
517
625
  async perform() {
518
626
  const {fetchOptions: fetchOptions} = this;
519
627
  this.delegate.prepareRequest(this);
520
- await this.allowRequestToBeIntercepted(fetchOptions);
628
+ await this.#allowRequestToBeIntercepted(fetchOptions);
521
629
  try {
522
630
  this.delegate.requestStarted(this);
523
- const response = await fetch(this.url.href, fetchOptions);
631
+ const response = await fetchWithTurboHeaders(this.url.href, fetchOptions);
524
632
  return await this.receive(response);
525
633
  } catch (error) {
526
634
  if (error.name !== "AbortError") {
527
- if (this.willDelegateErrorHandling(error)) {
635
+ if (this.#willDelegateErrorHandling(error)) {
528
636
  this.delegate.requestErrored(this, error);
529
637
  }
530
638
  throw error;
@@ -551,25 +659,13 @@ class FetchRequest {
551
659
  }
552
660
  return fetchResponse;
553
661
  }
554
- get fetchOptions() {
555
- var _a;
556
- return {
557
- method: FetchMethod[this.method].toUpperCase(),
558
- credentials: "same-origin",
559
- headers: this.headers,
560
- redirect: "follow",
561
- body: this.isSafe ? null : this.body,
562
- signal: this.abortSignal,
563
- referrer: (_a = this.delegate.referrer) === null || _a === void 0 ? void 0 : _a.href
564
- };
565
- }
566
662
  get defaultHeaders() {
567
663
  return {
568
664
  Accept: "text/html, application/xhtml+xml"
569
665
  };
570
666
  }
571
667
  get isSafe() {
572
- return this.method === FetchMethod.get;
668
+ return isSafe(this.method);
573
669
  }
574
670
  get abortSignal() {
575
671
  return this.abortController.signal;
@@ -577,20 +673,21 @@ class FetchRequest {
577
673
  acceptResponseType(mimeType) {
578
674
  this.headers["Accept"] = [ mimeType, this.headers["Accept"] ].join(", ");
579
675
  }
580
- async allowRequestToBeIntercepted(fetchOptions) {
581
- const requestInterception = new Promise((resolve => this.resolveRequestPromise = resolve));
676
+ async #allowRequestToBeIntercepted(fetchOptions) {
677
+ const requestInterception = new Promise((resolve => this.#resolveRequestPromise = resolve));
582
678
  const event = dispatch("turbo:before-fetch-request", {
583
679
  cancelable: true,
584
680
  detail: {
585
681
  fetchOptions: fetchOptions,
586
682
  url: this.url,
587
- resume: this.resolveRequestPromise
683
+ resume: this.#resolveRequestPromise
588
684
  },
589
685
  target: this.target
590
686
  });
687
+ this.url = event.detail.url;
591
688
  if (event.defaultPrevented) await requestInterception;
592
689
  }
593
- willDelegateErrorHandling(error) {
690
+ #willDelegateErrorHandling(error) {
594
691
  const event = dispatch("turbo:fetch-request-error", {
595
692
  target: this.target,
596
693
  cancelable: true,
@@ -603,15 +700,38 @@ class FetchRequest {
603
700
  }
604
701
  }
605
702
 
703
+ function isSafe(fetchMethod) {
704
+ return fetchMethodFromString(fetchMethod) == FetchMethod.get;
705
+ }
706
+
707
+ function buildResourceAndBody(resource, method, requestBody, enctype) {
708
+ const searchParams = Array.from(requestBody).length > 0 ? new URLSearchParams(entriesExcludingFiles(requestBody)) : resource.searchParams;
709
+ if (isSafe(method)) {
710
+ return [ mergeIntoURLSearchParams(resource, searchParams), null ];
711
+ } else if (enctype == FetchEnctype.urlEncoded) {
712
+ return [ resource, searchParams ];
713
+ } else {
714
+ return [ resource, requestBody ];
715
+ }
716
+ }
717
+
718
+ function entriesExcludingFiles(requestBody) {
719
+ const entries = [];
720
+ for (const [name, value] of requestBody) {
721
+ if (value instanceof File) continue; else entries.push([ name, value ]);
722
+ }
723
+ return entries;
724
+ }
725
+
726
+ function mergeIntoURLSearchParams(url, requestBody) {
727
+ const searchParams = new URLSearchParams(entriesExcludingFiles(requestBody));
728
+ url.search = searchParams.toString();
729
+ return url;
730
+ }
731
+
606
732
  class AppearanceObserver {
733
+ started=false;
607
734
  constructor(delegate, element) {
608
- this.started = false;
609
- this.intersect = entries => {
610
- const lastEntry = entries.slice(-1)[0];
611
- if (lastEntry === null || lastEntry === void 0 ? void 0 : lastEntry.isIntersecting) {
612
- this.delegate.elementAppearedInViewport(this.element);
613
- }
614
- };
615
735
  this.delegate = delegate;
616
736
  this.element = element;
617
737
  this.intersectionObserver = new IntersectionObserver(this.intersect);
@@ -628,9 +748,16 @@ class AppearanceObserver {
628
748
  this.intersectionObserver.unobserve(this.element);
629
749
  }
630
750
  }
751
+ intersect=entries => {
752
+ const lastEntry = entries.slice(-1)[0];
753
+ if (lastEntry?.isIntersecting) {
754
+ this.delegate.elementAppearedInViewport(this.element);
755
+ }
756
+ };
631
757
  }
632
758
 
633
759
  class StreamMessage {
760
+ static contentType="text/vnd.turbo-stream.html";
634
761
  static wrap(message) {
635
762
  if (typeof message == "string") {
636
763
  return new this(createDocumentFragment(message));
@@ -643,8 +770,6 @@ class StreamMessage {
643
770
  }
644
771
  }
645
772
 
646
- StreamMessage.contentType = "text/vnd.turbo-stream.html";
647
-
648
773
  function importStreamElements(fragment) {
649
774
  for (const element of fragment.querySelectorAll("turbo-stream")) {
650
775
  const streamElement = document.importNode(element, true);
@@ -656,85 +781,54 @@ function importStreamElements(fragment) {
656
781
  return fragment;
657
782
  }
658
783
 
659
- var FormSubmissionState;
660
-
661
- (function(FormSubmissionState) {
662
- FormSubmissionState[FormSubmissionState["initialized"] = 0] = "initialized";
663
- FormSubmissionState[FormSubmissionState["requesting"] = 1] = "requesting";
664
- FormSubmissionState[FormSubmissionState["waiting"] = 2] = "waiting";
665
- FormSubmissionState[FormSubmissionState["receiving"] = 3] = "receiving";
666
- FormSubmissionState[FormSubmissionState["stopping"] = 4] = "stopping";
667
- FormSubmissionState[FormSubmissionState["stopped"] = 5] = "stopped";
668
- })(FormSubmissionState || (FormSubmissionState = {}));
669
-
670
- var FormEnctype;
671
-
672
- (function(FormEnctype) {
673
- FormEnctype["urlEncoded"] = "application/x-www-form-urlencoded";
674
- FormEnctype["multipart"] = "multipart/form-data";
675
- FormEnctype["plain"] = "text/plain";
676
- })(FormEnctype || (FormEnctype = {}));
677
-
678
- function formEnctypeFromString(encoding) {
679
- switch (encoding.toLowerCase()) {
680
- case FormEnctype.multipart:
681
- return FormEnctype.multipart;
682
-
683
- case FormEnctype.plain:
684
- return FormEnctype.plain;
685
-
686
- default:
687
- return FormEnctype.urlEncoded;
688
- }
689
- }
784
+ const FormSubmissionState = {
785
+ initialized: "initialized",
786
+ requesting: "requesting",
787
+ waiting: "waiting",
788
+ receiving: "receiving",
789
+ stopping: "stopping",
790
+ stopped: "stopped"
791
+ };
690
792
 
691
793
  class FormSubmission {
794
+ state=FormSubmissionState.initialized;
692
795
  static confirmMethod(message, _element, _submitter) {
693
796
  return Promise.resolve(confirm(message));
694
797
  }
695
798
  constructor(delegate, formElement, submitter, mustRedirect = false) {
696
- this.state = FormSubmissionState.initialized;
799
+ const method = getMethod(formElement, submitter);
800
+ const action = getAction(getFormAction(formElement, submitter), method);
801
+ const body = buildFormData(formElement, submitter);
802
+ const enctype = getEnctype(formElement, submitter);
697
803
  this.delegate = delegate;
698
804
  this.formElement = formElement;
699
805
  this.submitter = submitter;
700
- this.formData = buildFormData(formElement, submitter);
701
- this.location = expandURL(this.action);
702
- if (this.method == FetchMethod.get) {
703
- mergeFormDataEntries(this.location, [ ...this.body.entries() ]);
704
- }
705
- this.fetchRequest = new FetchRequest(this, this.method, this.location, this.body, this.formElement);
806
+ this.fetchRequest = new FetchRequest(this, method, action, body, formElement, enctype);
706
807
  this.mustRedirect = mustRedirect;
707
808
  }
708
809
  get method() {
709
- var _a;
710
- const method = ((_a = this.submitter) === null || _a === void 0 ? void 0 : _a.getAttribute("formmethod")) || this.formElement.getAttribute("method") || "";
711
- return fetchMethodFromString(method.toLowerCase()) || FetchMethod.get;
810
+ return this.fetchRequest.method;
811
+ }
812
+ set method(value) {
813
+ this.fetchRequest.method = value;
712
814
  }
713
815
  get action() {
714
- var _a;
715
- const formElementAction = typeof this.formElement.action === "string" ? this.formElement.action : null;
716
- if ((_a = this.submitter) === null || _a === void 0 ? void 0 : _a.hasAttribute("formaction")) {
717
- return this.submitter.getAttribute("formaction") || "";
718
- } else {
719
- return this.formElement.getAttribute("action") || formElementAction || "";
720
- }
816
+ return this.fetchRequest.url.toString();
817
+ }
818
+ set action(value) {
819
+ this.fetchRequest.url = expandURL(value);
721
820
  }
722
821
  get body() {
723
- if (this.enctype == FormEnctype.urlEncoded || this.method == FetchMethod.get) {
724
- return new URLSearchParams(this.stringFormData);
725
- } else {
726
- return this.formData;
727
- }
822
+ return this.fetchRequest.body;
728
823
  }
729
824
  get enctype() {
730
- var _a;
731
- return formEnctypeFromString(((_a = this.submitter) === null || _a === void 0 ? void 0 : _a.getAttribute("formenctype")) || this.formElement.enctype);
825
+ return this.fetchRequest.enctype;
732
826
  }
733
827
  get isSafe() {
734
828
  return this.fetchRequest.isSafe;
735
829
  }
736
- get stringFormData() {
737
- return [ ...this.formData ].reduce(((entries, [name, value]) => entries.concat(typeof value == "string" ? [ [ name, value ] ] : [])), []);
830
+ get location() {
831
+ return this.fetchRequest.url;
738
832
  }
739
833
  async start() {
740
834
  const {initialized: initialized, requesting: requesting} = FormSubmissionState;
@@ -770,10 +864,10 @@ class FormSubmission {
770
864
  }
771
865
  }
772
866
  requestStarted(_request) {
773
- var _a;
774
867
  this.state = FormSubmissionState.waiting;
775
- (_a = this.submitter) === null || _a === void 0 ? void 0 : _a.setAttribute("disabled", "");
868
+ this.submitter?.setAttribute("disabled", "");
776
869
  this.setSubmitsWith();
870
+ markAsBusy(this.formElement);
777
871
  dispatch("turbo:submit-start", {
778
872
  target: this.formElement,
779
873
  detail: {
@@ -818,15 +912,16 @@ class FormSubmission {
818
912
  this.delegate.formSubmissionErrored(this, error);
819
913
  }
820
914
  requestFinished(_request) {
821
- var _a;
822
915
  this.state = FormSubmissionState.stopped;
823
- (_a = this.submitter) === null || _a === void 0 ? void 0 : _a.removeAttribute("disabled");
916
+ this.submitter?.removeAttribute("disabled");
824
917
  this.resetSubmitterText();
918
+ clearBusyState(this.formElement);
825
919
  dispatch("turbo:submit-end", {
826
920
  target: this.formElement,
827
- detail: Object.assign({
828
- formSubmission: this
829
- }, this.result)
921
+ detail: {
922
+ formSubmission: this,
923
+ ...this.result
924
+ }
830
925
  });
831
926
  this.delegate.formSubmissionFinished(this);
832
927
  }
@@ -857,15 +952,14 @@ class FormSubmission {
857
952
  return !request.isSafe || hasAttribute("data-turbo-stream", this.submitter, this.formElement);
858
953
  }
859
954
  get submitsWith() {
860
- var _a;
861
- return (_a = this.submitter) === null || _a === void 0 ? void 0 : _a.getAttribute("data-turbo-submits-with");
955
+ return this.submitter?.getAttribute("data-turbo-submits-with");
862
956
  }
863
957
  }
864
958
 
865
959
  function buildFormData(formElement, submitter) {
866
960
  const formData = new FormData(formElement);
867
- const name = submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute("name");
868
- const value = submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute("value");
961
+ const name = submitter?.getAttribute("name");
962
+ const value = submitter?.getAttribute("value");
869
963
  if (name) {
870
964
  formData.append(name, value || "");
871
965
  }
@@ -887,14 +981,30 @@ function responseSucceededWithoutRedirect(response) {
887
981
  return response.statusCode == 200 && !response.redirected;
888
982
  }
889
983
 
890
- function mergeFormDataEntries(url, entries) {
891
- const searchParams = new URLSearchParams;
892
- for (const [name, value] of entries) {
893
- if (value instanceof File) continue;
894
- searchParams.append(name, value);
984
+ function getFormAction(formElement, submitter) {
985
+ const formElementAction = typeof formElement.action === "string" ? formElement.action : null;
986
+ if (submitter?.hasAttribute("formaction")) {
987
+ return submitter.getAttribute("formaction") || "";
988
+ } else {
989
+ return formElement.getAttribute("action") || formElementAction || "";
895
990
  }
896
- url.search = searchParams.toString();
897
- return url;
991
+ }
992
+
993
+ function getAction(formAction, fetchMethod) {
994
+ const action = expandURL(formAction);
995
+ if (isSafe(fetchMethod)) {
996
+ action.search = "";
997
+ }
998
+ return action;
999
+ }
1000
+
1001
+ function getMethod(formElement, submitter) {
1002
+ const method = submitter?.getAttribute("formmethod") || formElement.getAttribute("method") || "";
1003
+ return fetchMethodFromString(method.toLowerCase()) || FetchMethod.get;
1004
+ }
1005
+
1006
+ function getEnctype(formElement, submitter) {
1007
+ return fetchEnctypeFromString(submitter?.getAttribute("formenctype") || formElement.enctype);
898
1008
  }
899
1009
 
900
1010
  class Snapshot {
@@ -917,11 +1027,7 @@ class Snapshot {
917
1027
  return this.element.isConnected;
918
1028
  }
919
1029
  get firstAutofocusableElement() {
920
- const inertDisabledOrHidden = "[inert], :disabled, [hidden], details:not([open]), dialog:not([open])";
921
- for (const element of this.element.querySelectorAll("[autofocus]")) {
922
- if (element.closest(inertDisabledOrHidden) == null) return element; else continue;
923
- }
924
- return null;
1030
+ return queryAutofocusableElement(this.element);
925
1031
  }
926
1032
  get permanentElements() {
927
1033
  return queryPermanentElementsAll(this.element);
@@ -951,23 +1057,8 @@ function queryPermanentElementsAll(node) {
951
1057
  }
952
1058
 
953
1059
  class FormSubmitObserver {
1060
+ started=false;
954
1061
  constructor(delegate, eventTarget) {
955
- this.started = false;
956
- this.submitCaptured = () => {
957
- this.eventTarget.removeEventListener("submit", this.submitBubbled, false);
958
- this.eventTarget.addEventListener("submit", this.submitBubbled, false);
959
- };
960
- this.submitBubbled = event => {
961
- if (!event.defaultPrevented) {
962
- const form = event.target instanceof HTMLFormElement ? event.target : undefined;
963
- const submitter = event.submitter || undefined;
964
- if (form && submissionDoesNotDismissDialog(form, submitter) && submissionDoesNotTargetIFrame(form, submitter) && this.delegate.willSubmitForm(form, submitter)) {
965
- event.preventDefault();
966
- event.stopImmediatePropagation();
967
- this.delegate.formSubmitted(form, submitter);
968
- }
969
- }
970
- };
971
1062
  this.delegate = delegate;
972
1063
  this.eventTarget = eventTarget;
973
1064
  }
@@ -983,16 +1074,31 @@ class FormSubmitObserver {
983
1074
  this.started = false;
984
1075
  }
985
1076
  }
1077
+ submitCaptured=() => {
1078
+ this.eventTarget.removeEventListener("submit", this.submitBubbled, false);
1079
+ this.eventTarget.addEventListener("submit", this.submitBubbled, false);
1080
+ };
1081
+ submitBubbled=event => {
1082
+ if (!event.defaultPrevented) {
1083
+ const form = event.target instanceof HTMLFormElement ? event.target : undefined;
1084
+ const submitter = event.submitter || undefined;
1085
+ if (form && submissionDoesNotDismissDialog(form, submitter) && submissionDoesNotTargetIFrame(form, submitter) && this.delegate.willSubmitForm(form, submitter)) {
1086
+ event.preventDefault();
1087
+ event.stopImmediatePropagation();
1088
+ this.delegate.formSubmitted(form, submitter);
1089
+ }
1090
+ }
1091
+ };
986
1092
  }
987
1093
 
988
1094
  function submissionDoesNotDismissDialog(form, submitter) {
989
- const method = (submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute("formmethod")) || form.getAttribute("method");
1095
+ const method = submitter?.getAttribute("formmethod") || form.getAttribute("method");
990
1096
  return method != "dialog";
991
1097
  }
992
1098
 
993
1099
  function submissionDoesNotTargetIFrame(form, submitter) {
994
- if ((submitter === null || submitter === void 0 ? void 0 : submitter.hasAttribute("formtarget")) || form.hasAttribute("target")) {
995
- const target = (submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute("formtarget")) || form.target;
1100
+ if (submitter?.hasAttribute("formtarget") || form.hasAttribute("target")) {
1101
+ const target = submitter?.getAttribute("formtarget") || form.target;
996
1102
  for (const element of document.getElementsByName(target)) {
997
1103
  if (element instanceof HTMLIFrameElement) return false;
998
1104
  }
@@ -1003,9 +1109,9 @@ function submissionDoesNotTargetIFrame(form, submitter) {
1003
1109
  }
1004
1110
 
1005
1111
  class View {
1112
+ #resolveRenderPromise=_value => {};
1113
+ #resolveInterceptionPromise=_value => {};
1006
1114
  constructor(delegate, element) {
1007
- this.resolveRenderPromise = _value => {};
1008
- this.resolveInterceptionPromise = _value => {};
1009
1115
  this.delegate = delegate;
1010
1116
  this.element = element;
1011
1117
  }
@@ -1054,23 +1160,23 @@ class View {
1054
1160
  const {isPreview: isPreview, shouldRender: shouldRender, newSnapshot: snapshot} = renderer;
1055
1161
  if (shouldRender) {
1056
1162
  try {
1057
- this.renderPromise = new Promise((resolve => this.resolveRenderPromise = resolve));
1163
+ this.renderPromise = new Promise((resolve => this.#resolveRenderPromise = resolve));
1058
1164
  this.renderer = renderer;
1059
1165
  await this.prepareToRenderSnapshot(renderer);
1060
- const renderInterception = new Promise((resolve => this.resolveInterceptionPromise = resolve));
1166
+ const renderInterception = new Promise((resolve => this.#resolveInterceptionPromise = resolve));
1061
1167
  const options = {
1062
- resume: this.resolveInterceptionPromise,
1168
+ resume: this.#resolveInterceptionPromise,
1063
1169
  render: this.renderer.renderElement
1064
1170
  };
1065
- const immediateRender = this.delegate.allowsImmediateRender(snapshot, options);
1171
+ const immediateRender = this.delegate.allowsImmediateRender(snapshot, isPreview, options);
1066
1172
  if (!immediateRender) await renderInterception;
1067
1173
  await this.renderSnapshot(renderer);
1068
- this.delegate.viewRenderedSnapshot(snapshot, isPreview);
1174
+ this.delegate.viewRenderedSnapshot(snapshot, isPreview, this.renderer.renderMethod);
1069
1175
  this.delegate.preloadOnLoadLinksForView(this.element);
1070
1176
  this.finishRenderingSnapshot(renderer);
1071
1177
  } finally {
1072
1178
  delete this.renderer;
1073
- this.resolveRenderPromise(undefined);
1179
+ this.#resolveRenderPromise(undefined);
1074
1180
  delete this.renderPromise;
1075
1181
  }
1076
1182
  } else {
@@ -1091,6 +1197,12 @@ class View {
1091
1197
  this.element.removeAttribute("data-turbo-preview");
1092
1198
  }
1093
1199
  }
1200
+ markVisitDirection(direction) {
1201
+ this.element.setAttribute("data-turbo-visit-direction", direction);
1202
+ }
1203
+ unmarkVisitDirection() {
1204
+ this.element.removeAttribute("data-turbo-visit-direction");
1205
+ }
1094
1206
  async renderSnapshot(renderer) {
1095
1207
  await renderer.render();
1096
1208
  }
@@ -1110,26 +1222,6 @@ class FrameView extends View {
1110
1222
 
1111
1223
  class LinkInterceptor {
1112
1224
  constructor(delegate, element) {
1113
- this.clickBubbled = event => {
1114
- if (this.respondsToEventTarget(event.target)) {
1115
- this.clickEvent = event;
1116
- } else {
1117
- delete this.clickEvent;
1118
- }
1119
- };
1120
- this.linkClicked = event => {
1121
- if (this.clickEvent && this.respondsToEventTarget(event.target) && event.target instanceof Element) {
1122
- if (this.delegate.shouldInterceptLinkClick(event.target, event.detail.url, event.detail.originalEvent)) {
1123
- this.clickEvent.preventDefault();
1124
- event.preventDefault();
1125
- this.delegate.linkClickIntercepted(event.target, event.detail.url, event.detail.originalEvent);
1126
- }
1127
- }
1128
- delete this.clickEvent;
1129
- };
1130
- this.willVisit = _event => {
1131
- delete this.clickEvent;
1132
- };
1133
1225
  this.delegate = delegate;
1134
1226
  this.element = element;
1135
1227
  }
@@ -1143,6 +1235,26 @@ class LinkInterceptor {
1143
1235
  document.removeEventListener("turbo:click", this.linkClicked);
1144
1236
  document.removeEventListener("turbo:before-visit", this.willVisit);
1145
1237
  }
1238
+ clickBubbled=event => {
1239
+ if (this.respondsToEventTarget(event.target)) {
1240
+ this.clickEvent = event;
1241
+ } else {
1242
+ delete this.clickEvent;
1243
+ }
1244
+ };
1245
+ linkClicked=event => {
1246
+ if (this.clickEvent && this.respondsToEventTarget(event.target) && event.target instanceof Element) {
1247
+ if (this.delegate.shouldInterceptLinkClick(event.target, event.detail.url, event.detail.originalEvent)) {
1248
+ this.clickEvent.preventDefault();
1249
+ event.preventDefault();
1250
+ this.delegate.linkClickIntercepted(event.target, event.detail.url, event.detail.originalEvent);
1251
+ }
1252
+ }
1253
+ delete this.clickEvent;
1254
+ };
1255
+ willVisit=_event => {
1256
+ delete this.clickEvent;
1257
+ };
1146
1258
  respondsToEventTarget(target) {
1147
1259
  const element = target instanceof Element ? target : target instanceof Node ? target.parentElement : null;
1148
1260
  return element && element.closest("turbo-frame, html") == this.element;
@@ -1150,25 +1262,8 @@ class LinkInterceptor {
1150
1262
  }
1151
1263
 
1152
1264
  class LinkClickObserver {
1265
+ started=false;
1153
1266
  constructor(delegate, eventTarget) {
1154
- this.started = false;
1155
- this.clickCaptured = () => {
1156
- this.eventTarget.removeEventListener("click", this.clickBubbled, false);
1157
- this.eventTarget.addEventListener("click", this.clickBubbled, false);
1158
- };
1159
- this.clickBubbled = event => {
1160
- if (event instanceof MouseEvent && this.clickEventIsSignificant(event)) {
1161
- const target = event.composedPath && event.composedPath()[0] || event.target;
1162
- const link = this.findLinkFromClickTarget(target);
1163
- if (link && doesNotTargetIFrame(link)) {
1164
- const location = this.getLocationForLink(link);
1165
- if (this.delegate.willFollowLinkToLocation(link, location, event)) {
1166
- event.preventDefault();
1167
- this.delegate.followedLinkToLocation(link, location);
1168
- }
1169
- }
1170
- }
1171
- };
1172
1267
  this.delegate = delegate;
1173
1268
  this.eventTarget = eventTarget;
1174
1269
  }
@@ -1184,6 +1279,23 @@ class LinkClickObserver {
1184
1279
  this.started = false;
1185
1280
  }
1186
1281
  }
1282
+ clickCaptured=() => {
1283
+ this.eventTarget.removeEventListener("click", this.clickBubbled, false);
1284
+ this.eventTarget.addEventListener("click", this.clickBubbled, false);
1285
+ };
1286
+ clickBubbled=event => {
1287
+ if (event instanceof MouseEvent && this.clickEventIsSignificant(event)) {
1288
+ const target = event.composedPath && event.composedPath()[0] || event.target;
1289
+ const link = this.findLinkFromClickTarget(target);
1290
+ if (link && doesNotTargetIFrame(link)) {
1291
+ const location = this.getLocationForLink(link);
1292
+ if (this.delegate.willFollowLinkToLocation(link, location, event)) {
1293
+ event.preventDefault();
1294
+ this.delegate.followedLinkToLocation(link, location);
1295
+ }
1296
+ }
1297
+ }
1298
+ };
1187
1299
  clickEventIsSignificant(event) {
1188
1300
  return !(event.target && event.target.isContentEditable || event.defaultPrevented || event.which > 1 || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey);
1189
1301
  }
@@ -1218,7 +1330,7 @@ class FormLinkClickObserver {
1218
1330
  this.linkInterceptor.stop();
1219
1331
  }
1220
1332
  willFollowLinkToLocation(link, location, originalEvent) {
1221
- return this.delegate.willSubmitFormLinkToLocation(link, location, originalEvent) && link.hasAttribute("data-turbo-method");
1333
+ return this.delegate.willSubmitFormLinkToLocation(link, location, originalEvent) && (link.hasAttribute("data-turbo-method") || link.hasAttribute("data-turbo-stream"));
1222
1334
  }
1223
1335
  followedLinkToLocation(link, location) {
1224
1336
  const form = document.createElement("form");
@@ -1291,7 +1403,7 @@ class Bardo {
1291
1403
  }
1292
1404
  replacePlaceholderWithPermanentElement(permanentElement) {
1293
1405
  const placeholder = this.getPlaceholderById(permanentElement.id);
1294
- placeholder === null || placeholder === void 0 ? void 0 : placeholder.replaceWith(permanentElement);
1406
+ placeholder?.replaceWith(permanentElement);
1295
1407
  }
1296
1408
  getPlaceholderById(id) {
1297
1409
  return this.placeholders.find((element => element.content == id));
@@ -1309,8 +1421,8 @@ function createPlaceholderForPermanentElement(permanentElement) {
1309
1421
  }
1310
1422
 
1311
1423
  class Renderer {
1424
+ #activeElement=null;
1312
1425
  constructor(currentSnapshot, newSnapshot, renderElement, isPreview, willRender = true) {
1313
- this.activeElement = null;
1314
1426
  this.currentSnapshot = currentSnapshot;
1315
1427
  this.newSnapshot = newSnapshot;
1316
1428
  this.isPreview = isPreview;
@@ -1330,6 +1442,7 @@ class Renderer {
1330
1442
  prepareToRender() {
1331
1443
  return;
1332
1444
  }
1445
+ render() {}
1333
1446
  finishRendering() {
1334
1447
  if (this.resolvingFunctions) {
1335
1448
  this.resolvingFunctions.resolve();
@@ -1341,20 +1454,20 @@ class Renderer {
1341
1454
  }
1342
1455
  focusFirstAutofocusableElement() {
1343
1456
  const element = this.connectedSnapshot.firstAutofocusableElement;
1344
- if (elementIsFocusable(element)) {
1457
+ if (element) {
1345
1458
  element.focus();
1346
1459
  }
1347
1460
  }
1348
1461
  enteringBardo(currentPermanentElement) {
1349
- if (this.activeElement) return;
1462
+ if (this.#activeElement) return;
1350
1463
  if (currentPermanentElement.contains(this.currentSnapshot.activeElement)) {
1351
- this.activeElement = this.currentSnapshot.activeElement;
1464
+ this.#activeElement = this.currentSnapshot.activeElement;
1352
1465
  }
1353
1466
  }
1354
1467
  leavingBardo(currentPermanentElement) {
1355
- if (currentPermanentElement.contains(this.activeElement) && this.activeElement instanceof HTMLElement) {
1356
- this.activeElement.focus();
1357
- this.activeElement = null;
1468
+ if (currentPermanentElement.contains(this.#activeElement) && this.#activeElement instanceof HTMLElement) {
1469
+ this.#activeElement.focus();
1470
+ this.#activeElement = null;
1358
1471
  }
1359
1472
  }
1360
1473
  get connectedSnapshot() {
@@ -1369,20 +1482,18 @@ class Renderer {
1369
1482
  get permanentElementMap() {
1370
1483
  return this.currentSnapshot.getPermanentElementMapForSnapshot(this.newSnapshot);
1371
1484
  }
1372
- }
1373
-
1374
- function elementIsFocusable(element) {
1375
- return element && typeof element.focus == "function";
1485
+ get renderMethod() {
1486
+ return "replace";
1487
+ }
1376
1488
  }
1377
1489
 
1378
1490
  class FrameRenderer extends Renderer {
1379
1491
  static renderElement(currentElement, newElement) {
1380
- var _a;
1381
1492
  const destinationRange = document.createRange();
1382
1493
  destinationRange.selectNodeContents(currentElement);
1383
1494
  destinationRange.deleteContents();
1384
1495
  const frameElement = newElement;
1385
- const sourceRange = (_a = frameElement.ownerDocument) === null || _a === void 0 ? void 0 : _a.createRange();
1496
+ const sourceRange = frameElement.ownerDocument?.createRange();
1386
1497
  if (sourceRange) {
1387
1498
  sourceRange.selectNodeContents(frameElement);
1388
1499
  currentElement.appendChild(sourceRange.extractContents());
@@ -1396,14 +1507,14 @@ class FrameRenderer extends Renderer {
1396
1507
  return true;
1397
1508
  }
1398
1509
  async render() {
1399
- await nextAnimationFrame();
1510
+ await nextRepaint();
1400
1511
  this.preservingPermanentElements((() => {
1401
1512
  this.loadFrameElement();
1402
1513
  }));
1403
1514
  this.scrollFrameIntoView();
1404
- await nextAnimationFrame();
1515
+ await nextRepaint();
1405
1516
  this.focusFirstAutofocusableElement();
1406
- await nextAnimationFrame();
1517
+ await nextRepaint();
1407
1518
  this.activateScriptElements();
1408
1519
  }
1409
1520
  loadFrameElement() {
@@ -1453,6 +1564,7 @@ function readScrollBehavior(value, defaultValue) {
1453
1564
  }
1454
1565
 
1455
1566
  class ProgressBar {
1567
+ static animationDuration=300;
1456
1568
  static get defaultCSS() {
1457
1569
  return unindent`
1458
1570
  .turbo-progress-bar {
@@ -1470,13 +1582,10 @@ class ProgressBar {
1470
1582
  }
1471
1583
  `;
1472
1584
  }
1585
+ hiding=false;
1586
+ value=0;
1587
+ visible=false;
1473
1588
  constructor() {
1474
- this.hiding = false;
1475
- this.value = 0;
1476
- this.visible = false;
1477
- this.trickle = () => {
1478
- this.setValue(this.value + Math.random() / 100);
1479
- };
1480
1589
  this.stylesheetElement = this.createStylesheetElement();
1481
1590
  this.progressElement = this.createProgressElement();
1482
1591
  this.installStylesheetElement();
@@ -1531,6 +1640,9 @@ class ProgressBar {
1531
1640
  window.clearInterval(this.trickleInterval);
1532
1641
  delete this.trickleInterval;
1533
1642
  }
1643
+ trickle=() => {
1644
+ this.setValue(this.value + Math.random() / 100);
1645
+ };
1534
1646
  refresh() {
1535
1647
  requestAnimationFrame((() => {
1536
1648
  this.progressElement.style.width = `${10 + this.value * 90}%`;
@@ -1555,25 +1667,22 @@ class ProgressBar {
1555
1667
  }
1556
1668
  }
1557
1669
 
1558
- ProgressBar.animationDuration = 300;
1559
-
1560
1670
  class HeadSnapshot extends Snapshot {
1561
- constructor() {
1562
- super(...arguments);
1563
- this.detailsByOuterHTML = this.children.filter((element => !elementIsNoscript(element))).map((element => elementWithoutNonce(element))).reduce(((result, element) => {
1564
- const {outerHTML: outerHTML} = element;
1565
- const details = outerHTML in result ? result[outerHTML] : {
1566
- type: elementType(element),
1567
- tracked: elementIsTracked(element),
1568
- elements: []
1569
- };
1570
- return Object.assign(Object.assign({}, result), {
1571
- [outerHTML]: Object.assign(Object.assign({}, details), {
1572
- elements: [ ...details.elements, element ]
1573
- })
1574
- });
1575
- }), {});
1576
- }
1671
+ detailsByOuterHTML=this.children.filter((element => !elementIsNoscript(element))).map((element => elementWithoutNonce(element))).reduce(((result, element) => {
1672
+ const {outerHTML: outerHTML} = element;
1673
+ const details = outerHTML in result ? result[outerHTML] : {
1674
+ type: elementType(element),
1675
+ tracked: elementIsTracked(element),
1676
+ elements: []
1677
+ };
1678
+ return {
1679
+ ...result,
1680
+ [outerHTML]: {
1681
+ ...details,
1682
+ elements: [ ...details.elements, element ]
1683
+ }
1684
+ };
1685
+ }), {});
1577
1686
  get trackedElementSignature() {
1578
1687
  return Object.keys(this.detailsByOuterHTML).filter((outerHTML => this.detailsByOuterHTML[outerHTML].tracked)).join("");
1579
1688
  }
@@ -1606,7 +1715,7 @@ class HeadSnapshot extends Snapshot {
1606
1715
  return Object.keys(this.detailsByOuterHTML).reduce(((result, outerHTML) => {
1607
1716
  const {elements: [element]} = this.detailsByOuterHTML[outerHTML];
1608
1717
  return elementIsMetaElementWithName(element, name) ? element : result;
1609
- }), undefined);
1718
+ }), undefined | undefined);
1610
1719
  }
1611
1720
  }
1612
1721
 
@@ -1656,11 +1765,12 @@ class PageSnapshot extends Snapshot {
1656
1765
  static fromElement(element) {
1657
1766
  return this.fromDocument(element.ownerDocument);
1658
1767
  }
1659
- static fromDocument({head: head, body: body}) {
1660
- return new this(body, new HeadSnapshot(head));
1768
+ static fromDocument({documentElement: documentElement, body: body, head: head}) {
1769
+ return new this(documentElement, body, new HeadSnapshot(head));
1661
1770
  }
1662
- constructor(element, headSnapshot) {
1663
- super(element);
1771
+ constructor(documentElement, body, headSnapshot) {
1772
+ super(body);
1773
+ this.documentElement = documentElement;
1664
1774
  this.headSnapshot = headSnapshot;
1665
1775
  }
1666
1776
  clone() {
@@ -1675,14 +1785,16 @@ class PageSnapshot extends Snapshot {
1675
1785
  for (const clonedPasswordInput of clonedElement.querySelectorAll('input[type="password"]')) {
1676
1786
  clonedPasswordInput.value = "";
1677
1787
  }
1678
- return new PageSnapshot(clonedElement, this.headSnapshot);
1788
+ return new PageSnapshot(this.documentElement, clonedElement, this.headSnapshot);
1789
+ }
1790
+ get lang() {
1791
+ return this.documentElement.getAttribute("lang");
1679
1792
  }
1680
1793
  get headElement() {
1681
1794
  return this.headSnapshot.element;
1682
1795
  }
1683
1796
  get rootLocation() {
1684
- var _a;
1685
- const root = (_a = this.getSetting("root")) !== null && _a !== void 0 ? _a : "/";
1797
+ const root = this.getSetting("root") ?? "/";
1686
1798
  return expandURL(root);
1687
1799
  }
1688
1800
  get cacheControlValue() {
@@ -1697,29 +1809,38 @@ class PageSnapshot extends Snapshot {
1697
1809
  get isVisitable() {
1698
1810
  return this.getSetting("visit-control") != "reload";
1699
1811
  }
1812
+ get prefersViewTransitions() {
1813
+ return this.headSnapshot.getMetaValue("view-transition") === "same-origin";
1814
+ }
1815
+ get shouldMorphPage() {
1816
+ return this.getSetting("refresh-method") === "morph";
1817
+ }
1818
+ get shouldPreserveScrollPosition() {
1819
+ return this.getSetting("refresh-scroll") === "preserve";
1820
+ }
1700
1821
  getSetting(name) {
1701
1822
  return this.headSnapshot.getMetaValue(`turbo-${name}`);
1702
1823
  }
1703
1824
  }
1704
1825
 
1705
- var TimingMetric;
1706
-
1707
- (function(TimingMetric) {
1708
- TimingMetric["visitStart"] = "visitStart";
1709
- TimingMetric["requestStart"] = "requestStart";
1710
- TimingMetric["requestEnd"] = "requestEnd";
1711
- TimingMetric["visitEnd"] = "visitEnd";
1712
- })(TimingMetric || (TimingMetric = {}));
1713
-
1714
- var VisitState;
1715
-
1716
- (function(VisitState) {
1717
- VisitState["initialized"] = "initialized";
1718
- VisitState["started"] = "started";
1719
- VisitState["canceled"] = "canceled";
1720
- VisitState["failed"] = "failed";
1721
- VisitState["completed"] = "completed";
1722
- })(VisitState || (VisitState = {}));
1826
+ class ViewTransitioner {
1827
+ #viewTransitionStarted=false;
1828
+ #lastOperation=Promise.resolve();
1829
+ renderChange(useViewTransition, render) {
1830
+ if (useViewTransition && this.viewTransitionsAvailable && !this.#viewTransitionStarted) {
1831
+ this.#viewTransitionStarted = true;
1832
+ this.#lastOperation = this.#lastOperation.then((async () => {
1833
+ await document.startViewTransition(render).finished;
1834
+ }));
1835
+ } else {
1836
+ this.#lastOperation = this.#lastOperation.then(render);
1837
+ }
1838
+ return this.#lastOperation;
1839
+ }
1840
+ get viewTransitionsAvailable() {
1841
+ return document.startViewTransition;
1842
+ }
1843
+ }
1723
1844
 
1724
1845
  const defaultOptions = {
1725
1846
  action: "advance",
@@ -1731,29 +1852,52 @@ const defaultOptions = {
1731
1852
  acceptsStreamResponse: false
1732
1853
  };
1733
1854
 
1734
- var SystemStatusCode;
1855
+ const TimingMetric = {
1856
+ visitStart: "visitStart",
1857
+ requestStart: "requestStart",
1858
+ requestEnd: "requestEnd",
1859
+ visitEnd: "visitEnd"
1860
+ };
1861
+
1862
+ const VisitState = {
1863
+ initialized: "initialized",
1864
+ started: "started",
1865
+ canceled: "canceled",
1866
+ failed: "failed",
1867
+ completed: "completed"
1868
+ };
1869
+
1870
+ const SystemStatusCode = {
1871
+ networkFailure: 0,
1872
+ timeoutFailure: -1,
1873
+ contentTypeMismatch: -2
1874
+ };
1735
1875
 
1736
- (function(SystemStatusCode) {
1737
- SystemStatusCode[SystemStatusCode["networkFailure"] = 0] = "networkFailure";
1738
- SystemStatusCode[SystemStatusCode["timeoutFailure"] = -1] = "timeoutFailure";
1739
- SystemStatusCode[SystemStatusCode["contentTypeMismatch"] = -2] = "contentTypeMismatch";
1740
- })(SystemStatusCode || (SystemStatusCode = {}));
1876
+ const Direction = {
1877
+ advance: "forward",
1878
+ restore: "back",
1879
+ replace: "none"
1880
+ };
1741
1881
 
1742
1882
  class Visit {
1883
+ identifier=uuid();
1884
+ timingMetrics={};
1885
+ followedRedirect=false;
1886
+ historyChanged=false;
1887
+ scrolled=false;
1888
+ shouldCacheSnapshot=true;
1889
+ acceptsStreamResponse=false;
1890
+ snapshotCached=false;
1891
+ state=VisitState.initialized;
1892
+ viewTransitioner=new ViewTransitioner;
1743
1893
  constructor(delegate, location, restorationIdentifier, options = {}) {
1744
- this.identifier = uuid();
1745
- this.timingMetrics = {};
1746
- this.followedRedirect = false;
1747
- this.historyChanged = false;
1748
- this.scrolled = false;
1749
- this.shouldCacheSnapshot = true;
1750
- this.acceptsStreamResponse = false;
1751
- this.snapshotCached = false;
1752
- this.state = VisitState.initialized;
1753
1894
  this.delegate = delegate;
1754
1895
  this.location = location;
1755
1896
  this.restorationIdentifier = restorationIdentifier || uuid();
1756
- const {action: action, historyChanged: historyChanged, referrer: referrer, snapshot: snapshot, snapshotHTML: snapshotHTML, response: response, visitCachedSnapshot: visitCachedSnapshot, willRender: willRender, updateHistory: updateHistory, shouldCacheSnapshot: shouldCacheSnapshot, acceptsStreamResponse: acceptsStreamResponse} = Object.assign(Object.assign({}, defaultOptions), options);
1897
+ const {action: action, historyChanged: historyChanged, referrer: referrer, snapshot: snapshot, snapshotHTML: snapshotHTML, response: response, visitCachedSnapshot: visitCachedSnapshot, willRender: willRender, updateHistory: updateHistory, shouldCacheSnapshot: shouldCacheSnapshot, acceptsStreamResponse: acceptsStreamResponse, direction: direction} = {
1898
+ ...defaultOptions,
1899
+ ...options
1900
+ };
1757
1901
  this.action = action;
1758
1902
  this.historyChanged = historyChanged;
1759
1903
  this.referrer = referrer;
@@ -1767,6 +1911,7 @@ class Visit {
1767
1911
  this.scrolled = !willRender;
1768
1912
  this.shouldCacheSnapshot = shouldCacheSnapshot;
1769
1913
  this.acceptsStreamResponse = acceptsStreamResponse;
1914
+ this.direction = direction || Direction[action];
1770
1915
  }
1771
1916
  get adapter() {
1772
1917
  return this.delegate.adapter;
@@ -1815,12 +1960,12 @@ class Visit {
1815
1960
  if (this.state == VisitState.started) {
1816
1961
  this.state = VisitState.failed;
1817
1962
  this.adapter.visitFailed(this);
1963
+ this.delegate.visitCompleted(this);
1818
1964
  }
1819
1965
  }
1820
1966
  changeHistory() {
1821
- var _a;
1822
1967
  if (!this.historyChanged && this.updateHistory) {
1823
- const actionForHistory = this.location.href === ((_a = this.referrer) === null || _a === void 0 ? void 0 : _a.href) ? "replace" : this.action;
1968
+ const actionForHistory = this.location.href === this.referrer?.href ? "replace" : this.action;
1824
1969
  const method = getHistoryMethodForAction(actionForHistory);
1825
1970
  this.history.update(method, this.location, this.restorationIdentifier);
1826
1971
  this.historyChanged = true;
@@ -1867,8 +2012,8 @@ class Visit {
1867
2012
  if (this.shouldCacheSnapshot) this.cacheSnapshot();
1868
2013
  if (this.view.renderPromise) await this.view.renderPromise;
1869
2014
  if (isSuccessful(statusCode) && responseHTML != null) {
1870
- await this.view.renderPage(PageSnapshot.fromHTMLString(responseHTML), false, this.willRender, this);
1871
- this.performScroll();
2015
+ const snapshot = PageSnapshot.fromHTMLString(responseHTML);
2016
+ await this.renderPageSnapshot(snapshot, false);
1872
2017
  this.adapter.visitRendered(this);
1873
2018
  this.complete();
1874
2019
  } else {
@@ -1905,8 +2050,7 @@ class Visit {
1905
2050
  this.adapter.visitRendered(this);
1906
2051
  } else {
1907
2052
  if (this.view.renderPromise) await this.view.renderPromise;
1908
- await this.view.renderPage(snapshot, isPreview, this.willRender, this);
1909
- this.performScroll();
2053
+ await this.renderPageSnapshot(snapshot, isPreview);
1910
2054
  this.adapter.visitRendered(this);
1911
2055
  if (!isPreview) {
1912
2056
  this.complete();
@@ -1916,8 +2060,7 @@ class Visit {
1916
2060
  }
1917
2061
  }
1918
2062
  followRedirect() {
1919
- var _a;
1920
- if (this.redirectedToLocation && !this.followedRedirect && ((_a = this.response) === null || _a === void 0 ? void 0 : _a.redirected)) {
2063
+ if (this.redirectedToLocation && !this.followedRedirect && this.response?.redirected) {
1921
2064
  this.adapter.visitProposedToLocation(this.redirectedToLocation, {
1922
2065
  action: "replace",
1923
2066
  response: this.response,
@@ -1989,7 +2132,7 @@ class Visit {
1989
2132
  this.finishRequest();
1990
2133
  }
1991
2134
  performScroll() {
1992
- if (!this.scrolled && !this.view.forceReloaded) {
2135
+ if (!this.scrolled && !this.view.forceReloaded && !this.view.shouldPreserveScrollPosition(this)) {
1993
2136
  if (this.action == "restore") {
1994
2137
  this.scrollToRestoredPosition() || this.scrollToAnchor() || this.view.scrollToTop();
1995
2138
  } else {
@@ -2019,7 +2162,9 @@ class Visit {
2019
2162
  this.timingMetrics[metric] = (new Date).getTime();
2020
2163
  }
2021
2164
  getTimingMetrics() {
2022
- return Object.assign({}, this.timingMetrics);
2165
+ return {
2166
+ ...this.timingMetrics
2167
+ };
2023
2168
  }
2024
2169
  getHistoryMethodForAction(action) {
2025
2170
  switch (action) {
@@ -2051,12 +2196,16 @@ class Visit {
2051
2196
  }
2052
2197
  async render(callback) {
2053
2198
  this.cancelRender();
2054
- await new Promise((resolve => {
2055
- this.frame = requestAnimationFrame((() => resolve()));
2056
- }));
2199
+ this.frame = await nextRepaint();
2057
2200
  await callback();
2058
2201
  delete this.frame;
2059
2202
  }
2203
+ async renderPageSnapshot(snapshot, isPreview) {
2204
+ await this.viewTransitioner.renderChange(this.view.shouldTransitionTo(snapshot), (async () => {
2205
+ await this.view.renderPage(snapshot, isPreview, this.willRender, this);
2206
+ this.performScroll();
2207
+ }));
2208
+ }
2060
2209
  cancelRender() {
2061
2210
  if (this.frame) {
2062
2211
  cancelAnimationFrame(this.frame);
@@ -2070,15 +2219,16 @@ function isSuccessful(statusCode) {
2070
2219
  }
2071
2220
 
2072
2221
  class BrowserAdapter {
2222
+ progressBar=new ProgressBar;
2073
2223
  constructor(session) {
2074
- this.progressBar = new ProgressBar;
2075
- this.showProgressBar = () => {
2076
- this.progressBar.show();
2077
- };
2078
2224
  this.session = session;
2079
2225
  }
2080
2226
  visitProposedToLocation(location, options) {
2081
- this.navigator.startVisit(location, (options === null || options === void 0 ? void 0 : options.restorationIdentifier) || uuid(), options);
2227
+ if (locationIsVisitable(location, this.navigator.rootLocation)) {
2228
+ this.navigator.startVisit(location, options?.restorationIdentifier || uuid(), options);
2229
+ } else {
2230
+ window.location.href = location.toString();
2231
+ }
2082
2232
  }
2083
2233
  visitStarted(visit) {
2084
2234
  this.location = visit.location;
@@ -2113,15 +2263,18 @@ class BrowserAdapter {
2113
2263
  return visit.loadResponse();
2114
2264
  }
2115
2265
  }
2116
- visitRequestFinished(_visit) {
2266
+ visitRequestFinished(_visit) {}
2267
+ visitCompleted(_visit) {
2117
2268
  this.progressBar.setValue(1);
2118
2269
  this.hideVisitProgressBar();
2119
2270
  }
2120
- visitCompleted(_visit) {}
2121
2271
  pageInvalidated(reason) {
2122
2272
  this.reload(reason);
2123
2273
  }
2124
- visitFailed(_visit) {}
2274
+ visitFailed(_visit) {
2275
+ this.progressBar.setValue(1);
2276
+ this.hideVisitProgressBar();
2277
+ }
2125
2278
  visitRendered(_visit) {}
2126
2279
  formSubmissionStarted(_formSubmission) {
2127
2280
  this.progressBar.setValue(0);
@@ -2153,12 +2306,14 @@ class BrowserAdapter {
2153
2306
  delete this.formProgressBarTimeout;
2154
2307
  }
2155
2308
  }
2309
+ showProgressBar=() => {
2310
+ this.progressBar.show();
2311
+ };
2156
2312
  reload(reason) {
2157
- var _a;
2158
2313
  dispatch("turbo:reload", {
2159
2314
  detail: reason
2160
2315
  });
2161
- window.location.href = ((_a = this.location) === null || _a === void 0 ? void 0 : _a.toString()) || window.location.href;
2316
+ window.location.href = this.location?.toString() || window.location.href;
2162
2317
  }
2163
2318
  get navigator() {
2164
2319
  return this.session.navigator;
@@ -2166,16 +2321,9 @@ class BrowserAdapter {
2166
2321
  }
2167
2322
 
2168
2323
  class CacheObserver {
2169
- constructor() {
2170
- this.selector = "[data-turbo-temporary]";
2171
- this.deprecatedSelector = "[data-turbo-cache=false]";
2172
- this.started = false;
2173
- this.removeTemporaryElements = _event => {
2174
- for (const element of this.temporaryElements) {
2175
- element.remove();
2176
- }
2177
- };
2178
- }
2324
+ selector="[data-turbo-temporary]";
2325
+ deprecatedSelector="[data-turbo-cache=false]";
2326
+ started=false;
2179
2327
  start() {
2180
2328
  if (!this.started) {
2181
2329
  this.started = true;
@@ -2188,6 +2336,11 @@ class CacheObserver {
2188
2336
  removeEventListener("turbo:before-cache", this.removeTemporaryElements, false);
2189
2337
  }
2190
2338
  }
2339
+ removeTemporaryElements=_event => {
2340
+ for (const element of this.temporaryElements) {
2341
+ element.remove();
2342
+ }
2343
+ };
2191
2344
  get temporaryElements() {
2192
2345
  return [ ...document.querySelectorAll(this.selector), ...this.temporaryElementsWithDeprecation ];
2193
2346
  }
@@ -2216,41 +2369,40 @@ class FrameRedirector {
2216
2369
  this.formSubmitObserver.stop();
2217
2370
  }
2218
2371
  shouldInterceptLinkClick(element, _location, _event) {
2219
- return this.shouldRedirect(element);
2372
+ return this.#shouldRedirect(element);
2220
2373
  }
2221
2374
  linkClickIntercepted(element, url, event) {
2222
- const frame = this.findFrameElement(element);
2375
+ const frame = this.#findFrameElement(element);
2223
2376
  if (frame) {
2224
2377
  frame.delegate.linkClickIntercepted(element, url, event);
2225
2378
  }
2226
2379
  }
2227
2380
  willSubmitForm(element, submitter) {
2228
- return element.closest("turbo-frame") == null && this.shouldSubmit(element, submitter) && this.shouldRedirect(element, submitter);
2381
+ return element.closest("turbo-frame") == null && this.#shouldSubmit(element, submitter) && this.#shouldRedirect(element, submitter);
2229
2382
  }
2230
2383
  formSubmitted(element, submitter) {
2231
- const frame = this.findFrameElement(element, submitter);
2384
+ const frame = this.#findFrameElement(element, submitter);
2232
2385
  if (frame) {
2233
2386
  frame.delegate.formSubmitted(element, submitter);
2234
2387
  }
2235
2388
  }
2236
- shouldSubmit(form, submitter) {
2237
- var _a;
2238
- const action = getAction(form, submitter);
2389
+ #shouldSubmit(form, submitter) {
2390
+ const action = getAction$1(form, submitter);
2239
2391
  const meta = this.element.ownerDocument.querySelector(`meta[name="turbo-root"]`);
2240
- const rootLocation = expandURL((_a = meta === null || meta === void 0 ? void 0 : meta.content) !== null && _a !== void 0 ? _a : "/");
2241
- return this.shouldRedirect(form, submitter) && locationIsVisitable(action, rootLocation);
2392
+ const rootLocation = expandURL(meta?.content ?? "/");
2393
+ return this.#shouldRedirect(form, submitter) && locationIsVisitable(action, rootLocation);
2242
2394
  }
2243
- shouldRedirect(element, submitter) {
2395
+ #shouldRedirect(element, submitter) {
2244
2396
  const isNavigatable = element instanceof HTMLFormElement ? this.session.submissionIsNavigatable(element, submitter) : this.session.elementIsNavigatable(element);
2245
2397
  if (isNavigatable) {
2246
- const frame = this.findFrameElement(element, submitter);
2398
+ const frame = this.#findFrameElement(element, submitter);
2247
2399
  return frame ? frame != element.closest("turbo-frame") : false;
2248
2400
  } else {
2249
2401
  return false;
2250
2402
  }
2251
2403
  }
2252
- findFrameElement(element, submitter) {
2253
- const id = (submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute("data-turbo-frame")) || element.getAttribute("data-turbo-frame");
2404
+ #findFrameElement(element, submitter) {
2405
+ const id = submitter?.getAttribute("data-turbo-frame") || element.getAttribute("data-turbo-frame");
2254
2406
  if (id && id != "_top") {
2255
2407
  const frame = this.element.querySelector(`#${id}:not([disabled])`);
2256
2408
  if (frame instanceof FrameElement) {
@@ -2261,32 +2413,20 @@ class FrameRedirector {
2261
2413
  }
2262
2414
 
2263
2415
  class History {
2416
+ location;
2417
+ restorationIdentifier=uuid();
2418
+ restorationData={};
2419
+ started=false;
2420
+ pageLoaded=false;
2421
+ currentIndex=0;
2264
2422
  constructor(delegate) {
2265
- this.restorationIdentifier = uuid();
2266
- this.restorationData = {};
2267
- this.started = false;
2268
- this.pageLoaded = false;
2269
- this.onPopState = event => {
2270
- if (this.shouldHandlePopState()) {
2271
- const {turbo: turbo} = event.state || {};
2272
- if (turbo) {
2273
- this.location = new URL(window.location.href);
2274
- const {restorationIdentifier: restorationIdentifier} = turbo;
2275
- this.restorationIdentifier = restorationIdentifier;
2276
- this.delegate.historyPoppedToLocationWithRestorationIdentifier(this.location, restorationIdentifier);
2277
- }
2278
- }
2279
- };
2280
- this.onPageLoad = async _event => {
2281
- await nextMicrotask();
2282
- this.pageLoaded = true;
2283
- };
2284
2423
  this.delegate = delegate;
2285
2424
  }
2286
2425
  start() {
2287
2426
  if (!this.started) {
2288
2427
  addEventListener("popstate", this.onPopState, false);
2289
2428
  addEventListener("load", this.onPageLoad, false);
2429
+ this.currentIndex = history.state?.turbo?.restorationIndex || 0;
2290
2430
  this.started = true;
2291
2431
  this.replace(new URL(window.location.href));
2292
2432
  }
@@ -2305,9 +2445,11 @@ class History {
2305
2445
  this.update(history.replaceState, location, restorationIdentifier);
2306
2446
  }
2307
2447
  update(method, location, restorationIdentifier = uuid()) {
2448
+ if (method === history.pushState) ++this.currentIndex;
2308
2449
  const state = {
2309
2450
  turbo: {
2310
- restorationIdentifier: restorationIdentifier
2451
+ restorationIdentifier: restorationIdentifier,
2452
+ restorationIndex: this.currentIndex
2311
2453
  }
2312
2454
  };
2313
2455
  method.call(history, state, "", location.href);
@@ -2320,12 +2462,14 @@ class History {
2320
2462
  updateRestorationData(additionalData) {
2321
2463
  const {restorationIdentifier: restorationIdentifier} = this;
2322
2464
  const restorationData = this.restorationData[restorationIdentifier];
2323
- this.restorationData[restorationIdentifier] = Object.assign(Object.assign({}, restorationData), additionalData);
2465
+ this.restorationData[restorationIdentifier] = {
2466
+ ...restorationData,
2467
+ ...additionalData
2468
+ };
2324
2469
  }
2325
2470
  assumeControlOfScrollRestoration() {
2326
- var _a;
2327
2471
  if (!this.previousScrollRestoration) {
2328
- this.previousScrollRestoration = (_a = history.scrollRestoration) !== null && _a !== void 0 ? _a : "auto";
2472
+ this.previousScrollRestoration = history.scrollRestoration ?? "auto";
2329
2473
  history.scrollRestoration = "manual";
2330
2474
  }
2331
2475
  }
@@ -2335,6 +2479,23 @@ class History {
2335
2479
  delete this.previousScrollRestoration;
2336
2480
  }
2337
2481
  }
2482
+ onPopState=event => {
2483
+ if (this.shouldHandlePopState()) {
2484
+ const {turbo: turbo} = event.state || {};
2485
+ if (turbo) {
2486
+ this.location = new URL(window.location.href);
2487
+ const {restorationIdentifier: restorationIdentifier, restorationIndex: restorationIndex} = turbo;
2488
+ this.restorationIdentifier = restorationIdentifier;
2489
+ const direction = restorationIndex > this.currentIndex ? "forward" : "back";
2490
+ this.delegate.historyPoppedToLocationWithRestorationIdentifierAndDirection(this.location, restorationIdentifier, direction);
2491
+ this.currentIndex = restorationIndex;
2492
+ }
2493
+ }
2494
+ };
2495
+ onPageLoad=async _event => {
2496
+ await nextMicrotask();
2497
+ this.pageLoaded = true;
2498
+ };
2338
2499
  shouldHandlePopState() {
2339
2500
  return this.pageIsLoaded();
2340
2501
  }
@@ -2349,18 +2510,15 @@ class Navigator {
2349
2510
  }
2350
2511
  proposeVisit(location, options = {}) {
2351
2512
  if (this.delegate.allowsVisitingLocationWithAction(location, options.action)) {
2352
- if (locationIsVisitable(location, this.view.snapshot.rootLocation)) {
2353
- this.delegate.visitProposedToLocation(location, options);
2354
- } else {
2355
- window.location.href = location.toString();
2356
- }
2513
+ this.delegate.visitProposedToLocation(location, options);
2357
2514
  }
2358
2515
  }
2359
2516
  startVisit(locatable, restorationIdentifier, options = {}) {
2360
2517
  this.stop();
2361
- this.currentVisit = new Visit(this, expandURL(locatable), restorationIdentifier, Object.assign({
2362
- referrer: this.location
2363
- }, options));
2518
+ this.currentVisit = new Visit(this, expandURL(locatable), restorationIdentifier, {
2519
+ referrer: this.location,
2520
+ ...options
2521
+ });
2364
2522
  this.currentVisit.start();
2365
2523
  }
2366
2524
  submitForm(form, submitter) {
@@ -2384,6 +2542,9 @@ class Navigator {
2384
2542
  get view() {
2385
2543
  return this.delegate.view;
2386
2544
  }
2545
+ get rootLocation() {
2546
+ return this.view.snapshot.rootLocation;
2547
+ }
2387
2548
  get history() {
2388
2549
  return this.delegate.history;
2389
2550
  }
@@ -2401,7 +2562,7 @@ class Navigator {
2401
2562
  this.view.clearSnapshotCache();
2402
2563
  }
2403
2564
  const {statusCode: statusCode, redirected: redirected} = fetchResponse;
2404
- const action = this.getActionForFormSubmission(formSubmission);
2565
+ const action = this.#getActionForFormSubmission(formSubmission, fetchResponse);
2405
2566
  const visitOptions = {
2406
2567
  action: action,
2407
2568
  shouldCacheSnapshot: shouldCacheSnapshot,
@@ -2424,7 +2585,9 @@ class Navigator {
2424
2585
  } else {
2425
2586
  await this.view.renderPage(snapshot, false, true, this.currentVisit);
2426
2587
  }
2427
- this.view.scrollToTop();
2588
+ if (!snapshot.shouldPreserveScrollPosition) {
2589
+ this.view.scrollToTop();
2590
+ }
2428
2591
  this.view.clearSnapshotCache();
2429
2592
  }
2430
2593
  }
@@ -2457,35 +2620,27 @@ class Navigator {
2457
2620
  get restorationIdentifier() {
2458
2621
  return this.history.restorationIdentifier;
2459
2622
  }
2460
- getActionForFormSubmission({submitter: submitter, formElement: formElement}) {
2461
- return getVisitAction(submitter, formElement) || "advance";
2623
+ #getActionForFormSubmission(formSubmission, fetchResponse) {
2624
+ const {submitter: submitter, formElement: formElement} = formSubmission;
2625
+ return getVisitAction(submitter, formElement) || this.#getDefaultAction(fetchResponse);
2626
+ }
2627
+ #getDefaultAction(fetchResponse) {
2628
+ const sameLocationRedirect = fetchResponse.redirected && fetchResponse.location.href === this.location?.href;
2629
+ return sameLocationRedirect ? "replace" : "advance";
2462
2630
  }
2463
2631
  }
2464
2632
 
2465
- var PageStage;
2466
-
2467
- (function(PageStage) {
2468
- PageStage[PageStage["initial"] = 0] = "initial";
2469
- PageStage[PageStage["loading"] = 1] = "loading";
2470
- PageStage[PageStage["interactive"] = 2] = "interactive";
2471
- PageStage[PageStage["complete"] = 3] = "complete";
2472
- })(PageStage || (PageStage = {}));
2633
+ const PageStage = {
2634
+ initial: 0,
2635
+ loading: 1,
2636
+ interactive: 2,
2637
+ complete: 3
2638
+ };
2473
2639
 
2474
2640
  class PageObserver {
2641
+ stage=PageStage.initial;
2642
+ started=false;
2475
2643
  constructor(delegate) {
2476
- this.stage = PageStage.initial;
2477
- this.started = false;
2478
- this.interpretReadyState = () => {
2479
- const {readyState: readyState} = this;
2480
- if (readyState == "interactive") {
2481
- this.pageIsInteractive();
2482
- } else if (readyState == "complete") {
2483
- this.pageIsComplete();
2484
- }
2485
- };
2486
- this.pageWillUnload = () => {
2487
- this.delegate.pageWillUnload();
2488
- };
2489
2644
  this.delegate = delegate;
2490
2645
  }
2491
2646
  start() {
@@ -2505,6 +2660,14 @@ class PageObserver {
2505
2660
  this.started = false;
2506
2661
  }
2507
2662
  }
2663
+ interpretReadyState=() => {
2664
+ const {readyState: readyState} = this;
2665
+ if (readyState == "interactive") {
2666
+ this.pageIsInteractive();
2667
+ } else if (readyState == "complete") {
2668
+ this.pageIsComplete();
2669
+ }
2670
+ };
2508
2671
  pageIsInteractive() {
2509
2672
  if (this.stage == PageStage.loading) {
2510
2673
  this.stage = PageStage.interactive;
@@ -2518,20 +2681,17 @@ class PageObserver {
2518
2681
  this.delegate.pageLoaded();
2519
2682
  }
2520
2683
  }
2684
+ pageWillUnload=() => {
2685
+ this.delegate.pageWillUnload();
2686
+ };
2521
2687
  get readyState() {
2522
2688
  return document.readyState;
2523
2689
  }
2524
2690
  }
2525
2691
 
2526
2692
  class ScrollObserver {
2693
+ started=false;
2527
2694
  constructor(delegate) {
2528
- this.started = false;
2529
- this.onScroll = () => {
2530
- this.updatePosition({
2531
- x: window.pageXOffset,
2532
- y: window.pageYOffset
2533
- });
2534
- };
2535
2695
  this.delegate = delegate;
2536
2696
  }
2537
2697
  start() {
@@ -2547,6 +2707,12 @@ class ScrollObserver {
2547
2707
  this.started = false;
2548
2708
  }
2549
2709
  }
2710
+ onScroll=() => {
2711
+ this.updatePosition({
2712
+ x: window.pageXOffset,
2713
+ y: window.pageYOffset
2714
+ });
2715
+ };
2550
2716
  updatePosition(position) {
2551
2717
  this.delegate.scrollPositionChanged(position);
2552
2718
  }
@@ -2554,7 +2720,13 @@ class ScrollObserver {
2554
2720
 
2555
2721
  class StreamMessageRenderer {
2556
2722
  render({fragment: fragment}) {
2557
- Bardo.preservingPermanentElements(this, getPermanentElementMapForFragment(fragment), (() => document.documentElement.appendChild(fragment)));
2723
+ Bardo.preservingPermanentElements(this, getPermanentElementMapForFragment(fragment), (() => {
2724
+ withAutofocusFromFragment(fragment, (() => {
2725
+ withPreservedFocus((() => {
2726
+ document.documentElement.appendChild(fragment);
2727
+ }));
2728
+ }));
2729
+ }));
2558
2730
  }
2559
2731
  enteringBardo(currentPermanentElement, newPermanentElement) {
2560
2732
  newPermanentElement.replaceWith(currentPermanentElement.cloneNode(true));
@@ -2577,33 +2749,67 @@ function getPermanentElementMapForFragment(fragment) {
2577
2749
  return permanentElementMap;
2578
2750
  }
2579
2751
 
2580
- class StreamObserver {
2581
- constructor(delegate) {
2582
- this.sources = new Set;
2583
- this.started = false;
2584
- this.inspectFetchResponse = event => {
2585
- const response = fetchResponseFromEvent(event);
2586
- if (response && fetchResponseIsStream(response)) {
2587
- event.preventDefault();
2588
- this.receiveMessageResponse(response);
2589
- }
2590
- };
2591
- this.receiveMessageEvent = event => {
2592
- if (this.started && typeof event.data == "string") {
2593
- this.receiveMessageHTML(event.data);
2594
- }
2595
- };
2752
+ async function withAutofocusFromFragment(fragment, callback) {
2753
+ const generatedID = `turbo-stream-autofocus-${uuid()}`;
2754
+ const turboStreams = fragment.querySelectorAll("turbo-stream");
2755
+ const elementWithAutofocus = firstAutofocusableElementInStreams(turboStreams);
2756
+ let willAutofocusId = null;
2757
+ if (elementWithAutofocus) {
2758
+ if (elementWithAutofocus.id) {
2759
+ willAutofocusId = elementWithAutofocus.id;
2760
+ } else {
2761
+ willAutofocusId = generatedID;
2762
+ }
2763
+ elementWithAutofocus.id = willAutofocusId;
2764
+ }
2765
+ callback();
2766
+ await nextRepaint();
2767
+ const hasNoActiveElement = document.activeElement == null || document.activeElement == document.body;
2768
+ if (hasNoActiveElement && willAutofocusId) {
2769
+ const elementToAutofocus = document.getElementById(willAutofocusId);
2770
+ if (elementIsFocusable(elementToAutofocus)) {
2771
+ elementToAutofocus.focus();
2772
+ }
2773
+ if (elementToAutofocus && elementToAutofocus.id == generatedID) {
2774
+ elementToAutofocus.removeAttribute("id");
2775
+ }
2776
+ }
2777
+ }
2778
+
2779
+ async function withPreservedFocus(callback) {
2780
+ const [activeElementBeforeRender, activeElementAfterRender] = await around(callback, (() => document.activeElement));
2781
+ const restoreFocusTo = activeElementBeforeRender && activeElementBeforeRender.id;
2782
+ if (restoreFocusTo) {
2783
+ const elementToFocus = document.getElementById(restoreFocusTo);
2784
+ if (elementIsFocusable(elementToFocus) && elementToFocus != activeElementAfterRender) {
2785
+ elementToFocus.focus();
2786
+ }
2787
+ }
2788
+ }
2789
+
2790
+ function firstAutofocusableElementInStreams(nodeListOfStreamElements) {
2791
+ for (const streamElement of nodeListOfStreamElements) {
2792
+ const elementWithAutofocus = queryAutofocusableElement(streamElement.templateElement.content);
2793
+ if (elementWithAutofocus) return elementWithAutofocus;
2794
+ }
2795
+ return null;
2796
+ }
2797
+
2798
+ class StreamObserver {
2799
+ sources=new Set;
2800
+ #started=false;
2801
+ constructor(delegate) {
2596
2802
  this.delegate = delegate;
2597
2803
  }
2598
2804
  start() {
2599
- if (!this.started) {
2600
- this.started = true;
2805
+ if (!this.#started) {
2806
+ this.#started = true;
2601
2807
  addEventListener("turbo:before-fetch-response", this.inspectFetchResponse, false);
2602
2808
  }
2603
2809
  }
2604
2810
  stop() {
2605
- if (this.started) {
2606
- this.started = false;
2811
+ if (this.#started) {
2812
+ this.#started = false;
2607
2813
  removeEventListener("turbo:before-fetch-response", this.inspectFetchResponse, false);
2608
2814
  }
2609
2815
  }
@@ -2622,6 +2828,18 @@ class StreamObserver {
2622
2828
  streamSourceIsConnected(source) {
2623
2829
  return this.sources.has(source);
2624
2830
  }
2831
+ inspectFetchResponse=event => {
2832
+ const response = fetchResponseFromEvent(event);
2833
+ if (response && fetchResponseIsStream(response)) {
2834
+ event.preventDefault();
2835
+ this.receiveMessageResponse(response);
2836
+ }
2837
+ };
2838
+ receiveMessageEvent=event => {
2839
+ if (this.#started && typeof event.data == "string") {
2840
+ this.receiveMessageHTML(event.data);
2841
+ }
2842
+ };
2625
2843
  async receiveMessageResponse(response) {
2626
2844
  const html = await response.responseHTML;
2627
2845
  if (html) {
@@ -2634,16 +2852,14 @@ class StreamObserver {
2634
2852
  }
2635
2853
 
2636
2854
  function fetchResponseFromEvent(event) {
2637
- var _a;
2638
- const fetchResponse = (_a = event.detail) === null || _a === void 0 ? void 0 : _a.fetchResponse;
2855
+ const fetchResponse = event.detail?.fetchResponse;
2639
2856
  if (fetchResponse instanceof FetchResponse) {
2640
2857
  return fetchResponse;
2641
2858
  }
2642
2859
  }
2643
2860
 
2644
2861
  function fetchResponseIsStream(response) {
2645
- var _a;
2646
- const contentType = (_a = response.contentType) !== null && _a !== void 0 ? _a : "";
2862
+ const contentType = response.contentType ?? "";
2647
2863
  return contentType.startsWith(StreamMessage.contentType);
2648
2864
  }
2649
2865
 
@@ -2678,6 +2894,575 @@ class ErrorRenderer extends Renderer {
2678
2894
  }
2679
2895
  }
2680
2896
 
2897
+ let EMPTY_SET = new Set;
2898
+
2899
+ function morph(oldNode, newContent, config = {}) {
2900
+ if (oldNode instanceof Document) {
2901
+ oldNode = oldNode.documentElement;
2902
+ }
2903
+ if (typeof newContent === "string") {
2904
+ newContent = parseContent(newContent);
2905
+ }
2906
+ let normalizedContent = normalizeContent(newContent);
2907
+ let ctx = createMorphContext(oldNode, normalizedContent, config);
2908
+ return morphNormalizedContent(oldNode, normalizedContent, ctx);
2909
+ }
2910
+
2911
+ function morphNormalizedContent(oldNode, normalizedNewContent, ctx) {
2912
+ if (ctx.head.block) {
2913
+ let oldHead = oldNode.querySelector("head");
2914
+ let newHead = normalizedNewContent.querySelector("head");
2915
+ if (oldHead && newHead) {
2916
+ let promises = handleHeadElement(newHead, oldHead, ctx);
2917
+ Promise.all(promises).then((function() {
2918
+ morphNormalizedContent(oldNode, normalizedNewContent, Object.assign(ctx, {
2919
+ head: {
2920
+ block: false,
2921
+ ignore: true
2922
+ }
2923
+ }));
2924
+ }));
2925
+ return;
2926
+ }
2927
+ }
2928
+ if (ctx.morphStyle === "innerHTML") {
2929
+ morphChildren(normalizedNewContent, oldNode, ctx);
2930
+ return oldNode.children;
2931
+ } else if (ctx.morphStyle === "outerHTML" || ctx.morphStyle == null) {
2932
+ let bestMatch = findBestNodeMatch(normalizedNewContent, oldNode, ctx);
2933
+ let previousSibling = bestMatch?.previousSibling;
2934
+ let nextSibling = bestMatch?.nextSibling;
2935
+ let morphedNode = morphOldNodeTo(oldNode, bestMatch, ctx);
2936
+ if (bestMatch) {
2937
+ return insertSiblings(previousSibling, morphedNode, nextSibling);
2938
+ } else {
2939
+ return [];
2940
+ }
2941
+ } else {
2942
+ throw "Do not understand how to morph style " + ctx.morphStyle;
2943
+ }
2944
+ }
2945
+
2946
+ function morphOldNodeTo(oldNode, newContent, ctx) {
2947
+ if (ctx.ignoreActive && oldNode === document.activeElement) ; else if (newContent == null) {
2948
+ if (ctx.callbacks.beforeNodeRemoved(oldNode) === false) return;
2949
+ oldNode.remove();
2950
+ ctx.callbacks.afterNodeRemoved(oldNode);
2951
+ return null;
2952
+ } else if (!isSoftMatch(oldNode, newContent)) {
2953
+ if (ctx.callbacks.beforeNodeRemoved(oldNode) === false) return;
2954
+ if (ctx.callbacks.beforeNodeAdded(newContent) === false) return;
2955
+ oldNode.parentElement.replaceChild(newContent, oldNode);
2956
+ ctx.callbacks.afterNodeAdded(newContent);
2957
+ ctx.callbacks.afterNodeRemoved(oldNode);
2958
+ return newContent;
2959
+ } else {
2960
+ if (ctx.callbacks.beforeNodeMorphed(oldNode, newContent) === false) return;
2961
+ if (oldNode instanceof HTMLHeadElement && ctx.head.ignore) ; else if (oldNode instanceof HTMLHeadElement && ctx.head.style !== "morph") {
2962
+ handleHeadElement(newContent, oldNode, ctx);
2963
+ } else {
2964
+ syncNodeFrom(newContent, oldNode);
2965
+ morphChildren(newContent, oldNode, ctx);
2966
+ }
2967
+ ctx.callbacks.afterNodeMorphed(oldNode, newContent);
2968
+ return oldNode;
2969
+ }
2970
+ }
2971
+
2972
+ function morphChildren(newParent, oldParent, ctx) {
2973
+ let nextNewChild = newParent.firstChild;
2974
+ let insertionPoint = oldParent.firstChild;
2975
+ let newChild;
2976
+ while (nextNewChild) {
2977
+ newChild = nextNewChild;
2978
+ nextNewChild = newChild.nextSibling;
2979
+ if (insertionPoint == null) {
2980
+ if (ctx.callbacks.beforeNodeAdded(newChild) === false) return;
2981
+ oldParent.appendChild(newChild);
2982
+ ctx.callbacks.afterNodeAdded(newChild);
2983
+ removeIdsFromConsideration(ctx, newChild);
2984
+ continue;
2985
+ }
2986
+ if (isIdSetMatch(newChild, insertionPoint, ctx)) {
2987
+ morphOldNodeTo(insertionPoint, newChild, ctx);
2988
+ insertionPoint = insertionPoint.nextSibling;
2989
+ removeIdsFromConsideration(ctx, newChild);
2990
+ continue;
2991
+ }
2992
+ let idSetMatch = findIdSetMatch(newParent, oldParent, newChild, insertionPoint, ctx);
2993
+ if (idSetMatch) {
2994
+ insertionPoint = removeNodesBetween(insertionPoint, idSetMatch, ctx);
2995
+ morphOldNodeTo(idSetMatch, newChild, ctx);
2996
+ removeIdsFromConsideration(ctx, newChild);
2997
+ continue;
2998
+ }
2999
+ let softMatch = findSoftMatch(newParent, oldParent, newChild, insertionPoint, ctx);
3000
+ if (softMatch) {
3001
+ insertionPoint = removeNodesBetween(insertionPoint, softMatch, ctx);
3002
+ morphOldNodeTo(softMatch, newChild, ctx);
3003
+ removeIdsFromConsideration(ctx, newChild);
3004
+ continue;
3005
+ }
3006
+ if (ctx.callbacks.beforeNodeAdded(newChild) === false) return;
3007
+ oldParent.insertBefore(newChild, insertionPoint);
3008
+ ctx.callbacks.afterNodeAdded(newChild);
3009
+ removeIdsFromConsideration(ctx, newChild);
3010
+ }
3011
+ while (insertionPoint !== null) {
3012
+ let tempNode = insertionPoint;
3013
+ insertionPoint = insertionPoint.nextSibling;
3014
+ removeNode(tempNode, ctx);
3015
+ }
3016
+ }
3017
+
3018
+ function syncNodeFrom(from, to) {
3019
+ let type = from.nodeType;
3020
+ if (type === 1) {
3021
+ const fromAttributes = from.attributes;
3022
+ const toAttributes = to.attributes;
3023
+ for (const fromAttribute of fromAttributes) {
3024
+ if (to.getAttribute(fromAttribute.name) !== fromAttribute.value) {
3025
+ to.setAttribute(fromAttribute.name, fromAttribute.value);
3026
+ }
3027
+ }
3028
+ for (const toAttribute of toAttributes) {
3029
+ if (!from.hasAttribute(toAttribute.name)) {
3030
+ to.removeAttribute(toAttribute.name);
3031
+ }
3032
+ }
3033
+ }
3034
+ if (type === 8 || type === 3) {
3035
+ if (to.nodeValue !== from.nodeValue) {
3036
+ to.nodeValue = from.nodeValue;
3037
+ }
3038
+ }
3039
+ if (from instanceof HTMLInputElement && to instanceof HTMLInputElement && from.type !== "file") {
3040
+ to.value = from.value || "";
3041
+ syncAttribute(from, to, "value");
3042
+ syncAttribute(from, to, "checked");
3043
+ syncAttribute(from, to, "disabled");
3044
+ } else if (from instanceof HTMLOptionElement) {
3045
+ syncAttribute(from, to, "selected");
3046
+ } else if (from instanceof HTMLTextAreaElement && to instanceof HTMLTextAreaElement) {
3047
+ let fromValue = from.value;
3048
+ let toValue = to.value;
3049
+ if (fromValue !== toValue) {
3050
+ to.value = fromValue;
3051
+ }
3052
+ if (to.firstChild && to.firstChild.nodeValue !== fromValue) {
3053
+ to.firstChild.nodeValue = fromValue;
3054
+ }
3055
+ }
3056
+ }
3057
+
3058
+ function syncAttribute(from, to, attributeName) {
3059
+ if (from[attributeName] !== to[attributeName]) {
3060
+ if (from[attributeName]) {
3061
+ to.setAttribute(attributeName, from[attributeName]);
3062
+ } else {
3063
+ to.removeAttribute(attributeName);
3064
+ }
3065
+ }
3066
+ }
3067
+
3068
+ function handleHeadElement(newHeadTag, currentHead, ctx) {
3069
+ let added = [];
3070
+ let removed = [];
3071
+ let preserved = [];
3072
+ let nodesToAppend = [];
3073
+ let headMergeStyle = ctx.head.style;
3074
+ let srcToNewHeadNodes = new Map;
3075
+ for (const newHeadChild of newHeadTag.children) {
3076
+ srcToNewHeadNodes.set(newHeadChild.outerHTML, newHeadChild);
3077
+ }
3078
+ for (const currentHeadElt of currentHead.children) {
3079
+ let inNewContent = srcToNewHeadNodes.has(currentHeadElt.outerHTML);
3080
+ let isReAppended = ctx.head.shouldReAppend(currentHeadElt);
3081
+ let isPreserved = ctx.head.shouldPreserve(currentHeadElt);
3082
+ if (inNewContent || isPreserved) {
3083
+ if (isReAppended) {
3084
+ removed.push(currentHeadElt);
3085
+ } else {
3086
+ srcToNewHeadNodes.delete(currentHeadElt.outerHTML);
3087
+ preserved.push(currentHeadElt);
3088
+ }
3089
+ } else {
3090
+ if (headMergeStyle === "append") {
3091
+ if (isReAppended) {
3092
+ removed.push(currentHeadElt);
3093
+ nodesToAppend.push(currentHeadElt);
3094
+ }
3095
+ } else {
3096
+ if (ctx.head.shouldRemove(currentHeadElt) !== false) {
3097
+ removed.push(currentHeadElt);
3098
+ }
3099
+ }
3100
+ }
3101
+ }
3102
+ nodesToAppend.push(...srcToNewHeadNodes.values());
3103
+ let promises = [];
3104
+ for (const newNode of nodesToAppend) {
3105
+ let newElt = document.createRange().createContextualFragment(newNode.outerHTML).firstChild;
3106
+ if (ctx.callbacks.beforeNodeAdded(newElt) !== false) {
3107
+ if (newElt.href || newElt.src) {
3108
+ let resolve = null;
3109
+ let promise = new Promise((function(_resolve) {
3110
+ resolve = _resolve;
3111
+ }));
3112
+ newElt.addEventListener("load", (function() {
3113
+ resolve();
3114
+ }));
3115
+ promises.push(promise);
3116
+ }
3117
+ currentHead.appendChild(newElt);
3118
+ ctx.callbacks.afterNodeAdded(newElt);
3119
+ added.push(newElt);
3120
+ }
3121
+ }
3122
+ for (const removedElement of removed) {
3123
+ if (ctx.callbacks.beforeNodeRemoved(removedElement) !== false) {
3124
+ currentHead.removeChild(removedElement);
3125
+ ctx.callbacks.afterNodeRemoved(removedElement);
3126
+ }
3127
+ }
3128
+ ctx.head.afterHeadMorphed(currentHead, {
3129
+ added: added,
3130
+ kept: preserved,
3131
+ removed: removed
3132
+ });
3133
+ return promises;
3134
+ }
3135
+
3136
+ function noOp() {}
3137
+
3138
+ function createMorphContext(oldNode, newContent, config) {
3139
+ return {
3140
+ target: oldNode,
3141
+ newContent: newContent,
3142
+ config: config,
3143
+ morphStyle: config.morphStyle,
3144
+ ignoreActive: config.ignoreActive,
3145
+ idMap: createIdMap(oldNode, newContent),
3146
+ deadIds: new Set,
3147
+ callbacks: Object.assign({
3148
+ beforeNodeAdded: noOp,
3149
+ afterNodeAdded: noOp,
3150
+ beforeNodeMorphed: noOp,
3151
+ afterNodeMorphed: noOp,
3152
+ beforeNodeRemoved: noOp,
3153
+ afterNodeRemoved: noOp
3154
+ }, config.callbacks),
3155
+ head: Object.assign({
3156
+ style: "merge",
3157
+ shouldPreserve: function(elt) {
3158
+ return elt.getAttribute("im-preserve") === "true";
3159
+ },
3160
+ shouldReAppend: function(elt) {
3161
+ return elt.getAttribute("im-re-append") === "true";
3162
+ },
3163
+ shouldRemove: noOp,
3164
+ afterHeadMorphed: noOp
3165
+ }, config.head)
3166
+ };
3167
+ }
3168
+
3169
+ function isIdSetMatch(node1, node2, ctx) {
3170
+ if (node1 == null || node2 == null) {
3171
+ return false;
3172
+ }
3173
+ if (node1.nodeType === node2.nodeType && node1.tagName === node2.tagName) {
3174
+ if (node1.id !== "" && node1.id === node2.id) {
3175
+ return true;
3176
+ } else {
3177
+ return getIdIntersectionCount(ctx, node1, node2) > 0;
3178
+ }
3179
+ }
3180
+ return false;
3181
+ }
3182
+
3183
+ function isSoftMatch(node1, node2) {
3184
+ if (node1 == null || node2 == null) {
3185
+ return false;
3186
+ }
3187
+ return node1.nodeType === node2.nodeType && node1.tagName === node2.tagName;
3188
+ }
3189
+
3190
+ function removeNodesBetween(startInclusive, endExclusive, ctx) {
3191
+ while (startInclusive !== endExclusive) {
3192
+ let tempNode = startInclusive;
3193
+ startInclusive = startInclusive.nextSibling;
3194
+ removeNode(tempNode, ctx);
3195
+ }
3196
+ removeIdsFromConsideration(ctx, endExclusive);
3197
+ return endExclusive.nextSibling;
3198
+ }
3199
+
3200
+ function findIdSetMatch(newContent, oldParent, newChild, insertionPoint, ctx) {
3201
+ let newChildPotentialIdCount = getIdIntersectionCount(ctx, newChild, oldParent);
3202
+ let potentialMatch = null;
3203
+ if (newChildPotentialIdCount > 0) {
3204
+ let potentialMatch = insertionPoint;
3205
+ let otherMatchCount = 0;
3206
+ while (potentialMatch != null) {
3207
+ if (isIdSetMatch(newChild, potentialMatch, ctx)) {
3208
+ return potentialMatch;
3209
+ }
3210
+ otherMatchCount += getIdIntersectionCount(ctx, potentialMatch, newContent);
3211
+ if (otherMatchCount > newChildPotentialIdCount) {
3212
+ return null;
3213
+ }
3214
+ potentialMatch = potentialMatch.nextSibling;
3215
+ }
3216
+ }
3217
+ return potentialMatch;
3218
+ }
3219
+
3220
+ function findSoftMatch(newContent, oldParent, newChild, insertionPoint, ctx) {
3221
+ let potentialSoftMatch = insertionPoint;
3222
+ let nextSibling = newChild.nextSibling;
3223
+ let siblingSoftMatchCount = 0;
3224
+ while (potentialSoftMatch != null) {
3225
+ if (getIdIntersectionCount(ctx, potentialSoftMatch, newContent) > 0) {
3226
+ return null;
3227
+ }
3228
+ if (isSoftMatch(newChild, potentialSoftMatch)) {
3229
+ return potentialSoftMatch;
3230
+ }
3231
+ if (isSoftMatch(nextSibling, potentialSoftMatch)) {
3232
+ siblingSoftMatchCount++;
3233
+ nextSibling = nextSibling.nextSibling;
3234
+ if (siblingSoftMatchCount >= 2) {
3235
+ return null;
3236
+ }
3237
+ }
3238
+ potentialSoftMatch = potentialSoftMatch.nextSibling;
3239
+ }
3240
+ return potentialSoftMatch;
3241
+ }
3242
+
3243
+ function parseContent(newContent) {
3244
+ let parser = new DOMParser;
3245
+ let contentWithSvgsRemoved = newContent.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim, "");
3246
+ if (contentWithSvgsRemoved.match(/<\/html>/) || contentWithSvgsRemoved.match(/<\/head>/) || contentWithSvgsRemoved.match(/<\/body>/)) {
3247
+ let content = parser.parseFromString(newContent, "text/html");
3248
+ if (contentWithSvgsRemoved.match(/<\/html>/)) {
3249
+ content.generatedByIdiomorph = true;
3250
+ return content;
3251
+ } else {
3252
+ let htmlElement = content.firstChild;
3253
+ if (htmlElement) {
3254
+ htmlElement.generatedByIdiomorph = true;
3255
+ return htmlElement;
3256
+ } else {
3257
+ return null;
3258
+ }
3259
+ }
3260
+ } else {
3261
+ let responseDoc = parser.parseFromString("<body><template>" + newContent + "</template></body>", "text/html");
3262
+ let content = responseDoc.body.querySelector("template").content;
3263
+ content.generatedByIdiomorph = true;
3264
+ return content;
3265
+ }
3266
+ }
3267
+
3268
+ function normalizeContent(newContent) {
3269
+ if (newContent == null) {
3270
+ const dummyParent = document.createElement("div");
3271
+ return dummyParent;
3272
+ } else if (newContent.generatedByIdiomorph) {
3273
+ return newContent;
3274
+ } else if (newContent instanceof Node) {
3275
+ const dummyParent = document.createElement("div");
3276
+ dummyParent.append(newContent);
3277
+ return dummyParent;
3278
+ } else {
3279
+ const dummyParent = document.createElement("div");
3280
+ for (const elt of [ ...newContent ]) {
3281
+ dummyParent.append(elt);
3282
+ }
3283
+ return dummyParent;
3284
+ }
3285
+ }
3286
+
3287
+ function insertSiblings(previousSibling, morphedNode, nextSibling) {
3288
+ let stack = [];
3289
+ let added = [];
3290
+ while (previousSibling != null) {
3291
+ stack.push(previousSibling);
3292
+ previousSibling = previousSibling.previousSibling;
3293
+ }
3294
+ while (stack.length > 0) {
3295
+ let node = stack.pop();
3296
+ added.push(node);
3297
+ morphedNode.parentElement.insertBefore(node, morphedNode);
3298
+ }
3299
+ added.push(morphedNode);
3300
+ while (nextSibling != null) {
3301
+ stack.push(nextSibling);
3302
+ added.push(nextSibling);
3303
+ nextSibling = nextSibling.nextSibling;
3304
+ }
3305
+ while (stack.length > 0) {
3306
+ morphedNode.parentElement.insertBefore(stack.pop(), morphedNode.nextSibling);
3307
+ }
3308
+ return added;
3309
+ }
3310
+
3311
+ function findBestNodeMatch(newContent, oldNode, ctx) {
3312
+ let currentElement;
3313
+ currentElement = newContent.firstChild;
3314
+ let bestElement = currentElement;
3315
+ let score = 0;
3316
+ while (currentElement) {
3317
+ let newScore = scoreElement(currentElement, oldNode, ctx);
3318
+ if (newScore > score) {
3319
+ bestElement = currentElement;
3320
+ score = newScore;
3321
+ }
3322
+ currentElement = currentElement.nextSibling;
3323
+ }
3324
+ return bestElement;
3325
+ }
3326
+
3327
+ function scoreElement(node1, node2, ctx) {
3328
+ if (isSoftMatch(node1, node2)) {
3329
+ return .5 + getIdIntersectionCount(ctx, node1, node2);
3330
+ }
3331
+ return 0;
3332
+ }
3333
+
3334
+ function removeNode(tempNode, ctx) {
3335
+ removeIdsFromConsideration(ctx, tempNode);
3336
+ if (ctx.callbacks.beforeNodeRemoved(tempNode) === false) return;
3337
+ tempNode.remove();
3338
+ ctx.callbacks.afterNodeRemoved(tempNode);
3339
+ }
3340
+
3341
+ function isIdInConsideration(ctx, id) {
3342
+ return !ctx.deadIds.has(id);
3343
+ }
3344
+
3345
+ function idIsWithinNode(ctx, id, targetNode) {
3346
+ let idSet = ctx.idMap.get(targetNode) || EMPTY_SET;
3347
+ return idSet.has(id);
3348
+ }
3349
+
3350
+ function removeIdsFromConsideration(ctx, node) {
3351
+ let idSet = ctx.idMap.get(node) || EMPTY_SET;
3352
+ for (const id of idSet) {
3353
+ ctx.deadIds.add(id);
3354
+ }
3355
+ }
3356
+
3357
+ function getIdIntersectionCount(ctx, node1, node2) {
3358
+ let sourceSet = ctx.idMap.get(node1) || EMPTY_SET;
3359
+ let matchCount = 0;
3360
+ for (const id of sourceSet) {
3361
+ if (isIdInConsideration(ctx, id) && idIsWithinNode(ctx, id, node2)) {
3362
+ ++matchCount;
3363
+ }
3364
+ }
3365
+ return matchCount;
3366
+ }
3367
+
3368
+ function populateIdMapForNode(node, idMap) {
3369
+ let nodeParent = node.parentElement;
3370
+ let idElements = node.querySelectorAll("[id]");
3371
+ for (const elt of idElements) {
3372
+ let current = elt;
3373
+ while (current !== nodeParent && current != null) {
3374
+ let idSet = idMap.get(current);
3375
+ if (idSet == null) {
3376
+ idSet = new Set;
3377
+ idMap.set(current, idSet);
3378
+ }
3379
+ idSet.add(elt.id);
3380
+ current = current.parentElement;
3381
+ }
3382
+ }
3383
+ }
3384
+
3385
+ function createIdMap(oldContent, newContent) {
3386
+ let idMap = new Map;
3387
+ populateIdMapForNode(oldContent, idMap);
3388
+ populateIdMapForNode(newContent, idMap);
3389
+ return idMap;
3390
+ }
3391
+
3392
+ var idiomorph = {
3393
+ morph: morph
3394
+ };
3395
+
3396
+ class MorphRenderer extends Renderer {
3397
+ async render() {
3398
+ if (this.willRender) await this.#morphBody();
3399
+ }
3400
+ get renderMethod() {
3401
+ return "morph";
3402
+ }
3403
+ async #morphBody() {
3404
+ this.#morphElements(this.currentElement, this.newElement);
3405
+ this.#reloadRemoteFrames();
3406
+ dispatch("turbo:morph", {
3407
+ detail: {
3408
+ currentElement: this.currentElement,
3409
+ newElement: this.newElement
3410
+ }
3411
+ });
3412
+ }
3413
+ #morphElements(currentElement, newElement, morphStyle = "outerHTML") {
3414
+ this.isMorphingTurboFrame = this.#isFrameReloadedWithMorph(currentElement);
3415
+ idiomorph.morph(currentElement, newElement, {
3416
+ morphStyle: morphStyle,
3417
+ callbacks: {
3418
+ beforeNodeAdded: this.#shouldAddElement,
3419
+ beforeNodeMorphed: this.#shouldMorphElement,
3420
+ beforeNodeRemoved: this.#shouldRemoveElement
3421
+ }
3422
+ });
3423
+ }
3424
+ #shouldAddElement=node => !(node.id && node.hasAttribute("data-turbo-permanent") && document.getElementById(node.id));
3425
+ #shouldMorphElement=(oldNode, newNode) => {
3426
+ if (oldNode instanceof HTMLElement) {
3427
+ return !oldNode.hasAttribute("data-turbo-permanent") && (this.isMorphingTurboFrame || !this.#isFrameReloadedWithMorph(oldNode));
3428
+ } else {
3429
+ return true;
3430
+ }
3431
+ };
3432
+ #shouldRemoveElement=node => this.#shouldMorphElement(node);
3433
+ #reloadRemoteFrames() {
3434
+ this.#remoteFrames().forEach((frame => {
3435
+ if (this.#isFrameReloadedWithMorph(frame)) {
3436
+ this.#renderFrameWithMorph(frame);
3437
+ frame.reload();
3438
+ }
3439
+ }));
3440
+ }
3441
+ #renderFrameWithMorph(frame) {
3442
+ frame.addEventListener("turbo:before-frame-render", (event => {
3443
+ event.detail.render = this.#morphFrameUpdate;
3444
+ }), {
3445
+ once: true
3446
+ });
3447
+ }
3448
+ #morphFrameUpdate=(currentElement, newElement) => {
3449
+ dispatch("turbo:before-frame-morph", {
3450
+ target: currentElement,
3451
+ detail: {
3452
+ currentElement: currentElement,
3453
+ newElement: newElement
3454
+ }
3455
+ });
3456
+ this.#morphElements(currentElement, newElement.children, "innerHTML");
3457
+ };
3458
+ #isFrameReloadedWithMorph(element) {
3459
+ return element.src && element.refresh === "morph";
3460
+ }
3461
+ #remoteFrames() {
3462
+ return Array.from(document.querySelectorAll("turbo-frame[src]")).filter((frame => !frame.closest("[data-turbo-permanent]")));
3463
+ }
3464
+ }
3465
+
2681
3466
  class PageRenderer extends Renderer {
2682
3467
  static renderElement(currentElement, newElement) {
2683
3468
  if (document.body && newElement instanceof HTMLBodyElement) {
@@ -2702,6 +3487,7 @@ class PageRenderer extends Renderer {
2702
3487
  }
2703
3488
  }
2704
3489
  async prepareToRender() {
3490
+ this.#setLanguage();
2705
3491
  await this.mergeHead();
2706
3492
  }
2707
3493
  async render() {
@@ -2724,6 +3510,15 @@ class PageRenderer extends Renderer {
2724
3510
  get newElement() {
2725
3511
  return this.newSnapshot.element;
2726
3512
  }
3513
+ #setLanguage() {
3514
+ const {documentElement: documentElement} = this.currentSnapshot;
3515
+ const {lang: lang} = this.newSnapshot;
3516
+ if (lang) {
3517
+ documentElement.setAttribute("lang", lang);
3518
+ } else {
3519
+ documentElement.removeAttribute("lang");
3520
+ }
3521
+ }
2727
3522
  async mergeHead() {
2728
3523
  const mergedHeadElements = this.mergeProvisionalElements();
2729
3524
  const newStylesheetElements = this.copyNewHeadStylesheetElements();
@@ -2823,9 +3618,9 @@ class PageRenderer extends Renderer {
2823
3618
  }
2824
3619
 
2825
3620
  class SnapshotCache {
3621
+ keys=[];
3622
+ snapshots={};
2826
3623
  constructor(size) {
2827
- this.keys = [];
2828
- this.snapshots = {};
2829
3624
  this.size = size;
2830
3625
  }
2831
3626
  has(location) {
@@ -2867,23 +3662,25 @@ class SnapshotCache {
2867
3662
  }
2868
3663
 
2869
3664
  class PageView extends View {
2870
- constructor() {
2871
- super(...arguments);
2872
- this.snapshotCache = new SnapshotCache(10);
2873
- this.lastRenderedLocation = new URL(location.href);
2874
- this.forceReloaded = false;
3665
+ snapshotCache=new SnapshotCache(10);
3666
+ lastRenderedLocation=new URL(location.href);
3667
+ forceReloaded=false;
3668
+ shouldTransitionTo(newSnapshot) {
3669
+ return this.snapshot.prefersViewTransitions && newSnapshot.prefersViewTransitions;
2875
3670
  }
2876
3671
  renderPage(snapshot, isPreview = false, willRender = true, visit) {
2877
- const renderer = new PageRenderer(this.snapshot, snapshot, PageRenderer.renderElement, isPreview, willRender);
3672
+ const shouldMorphPage = this.isPageRefresh(visit) && this.snapshot.shouldMorphPage;
3673
+ const rendererClass = shouldMorphPage ? MorphRenderer : PageRenderer;
3674
+ const renderer = new rendererClass(this.snapshot, snapshot, PageRenderer.renderElement, isPreview, willRender);
2878
3675
  if (!renderer.shouldRender) {
2879
3676
  this.forceReloaded = true;
2880
3677
  } else {
2881
- visit === null || visit === void 0 ? void 0 : visit.changeHistory();
3678
+ visit?.changeHistory();
2882
3679
  }
2883
3680
  return this.render(renderer);
2884
3681
  }
2885
3682
  renderError(snapshot, visit) {
2886
- visit === null || visit === void 0 ? void 0 : visit.changeHistory();
3683
+ visit?.changeHistory();
2887
3684
  const renderer = new ErrorRenderer(this.snapshot, snapshot, ErrorRenderer.renderElement, false);
2888
3685
  return this.render(renderer);
2889
3686
  }
@@ -2903,31 +3700,38 @@ class PageView extends View {
2903
3700
  getCachedSnapshotForLocation(location) {
2904
3701
  return this.snapshotCache.get(location);
2905
3702
  }
3703
+ isPageRefresh(visit) {
3704
+ return !visit || this.lastRenderedLocation.pathname === visit.location.pathname && visit.action === "replace";
3705
+ }
3706
+ shouldPreserveScrollPosition(visit) {
3707
+ return this.isPageRefresh(visit) && this.snapshot.shouldPreserveScrollPosition;
3708
+ }
2906
3709
  get snapshot() {
2907
3710
  return PageSnapshot.fromElement(this.element);
2908
3711
  }
2909
3712
  }
2910
3713
 
2911
3714
  class Preloader {
2912
- constructor(delegate) {
2913
- this.selector = "a[data-turbo-preload]";
3715
+ selector="a[data-turbo-preload]";
3716
+ constructor(delegate, snapshotCache) {
2914
3717
  this.delegate = delegate;
2915
- }
2916
- get snapshotCache() {
2917
- return this.delegate.navigator.view.snapshotCache;
3718
+ this.snapshotCache = snapshotCache;
2918
3719
  }
2919
3720
  start() {
2920
3721
  if (document.readyState === "loading") {
2921
- return document.addEventListener("DOMContentLoaded", (() => {
2922
- this.preloadOnLoadLinksForView(document.body);
2923
- }));
3722
+ document.addEventListener("DOMContentLoaded", this.#preloadAll);
2924
3723
  } else {
2925
3724
  this.preloadOnLoadLinksForView(document.body);
2926
3725
  }
2927
3726
  }
3727
+ stop() {
3728
+ document.removeEventListener("DOMContentLoaded", this.#preloadAll);
3729
+ }
2928
3730
  preloadOnLoadLinksForView(element) {
2929
3731
  for (const link of element.querySelectorAll(this.selector)) {
2930
- this.preloadURL(link);
3732
+ if (this.delegate.shouldPreloadLink(link)) {
3733
+ this.preloadURL(link);
3734
+ }
2931
3735
  }
2932
3736
  }
2933
3737
  async preloadURL(link) {
@@ -2935,41 +3739,73 @@ class Preloader {
2935
3739
  if (this.snapshotCache.has(location)) {
2936
3740
  return;
2937
3741
  }
3742
+ const fetchRequest = new FetchRequest(this, FetchMethod.get, location, new URLSearchParams, link);
3743
+ await fetchRequest.perform();
3744
+ }
3745
+ prepareRequest(fetchRequest) {
3746
+ fetchRequest.headers["Sec-Purpose"] = "prefetch";
3747
+ }
3748
+ async requestSucceededWithResponse(fetchRequest, fetchResponse) {
2938
3749
  try {
2939
- const response = await fetch(location.toString(), {
2940
- headers: {
2941
- "VND.PREFETCH": "true",
2942
- Accept: "text/html"
2943
- }
2944
- });
2945
- const responseText = await response.text();
2946
- const snapshot = PageSnapshot.fromHTMLString(responseText);
2947
- this.snapshotCache.put(location, snapshot);
3750
+ const responseHTML = await fetchResponse.responseHTML;
3751
+ const snapshot = PageSnapshot.fromHTMLString(responseHTML);
3752
+ this.snapshotCache.put(fetchRequest.url, snapshot);
2948
3753
  } catch (_) {}
2949
3754
  }
3755
+ requestStarted(fetchRequest) {}
3756
+ requestErrored(fetchRequest) {}
3757
+ requestFinished(fetchRequest) {}
3758
+ requestPreventedHandlingResponse(fetchRequest, fetchResponse) {}
3759
+ requestFailedWithResponse(fetchRequest, fetchResponse) {}
3760
+ #preloadAll=() => {
3761
+ this.preloadOnLoadLinksForView(document.body);
3762
+ };
3763
+ }
3764
+
3765
+ class Cache {
3766
+ constructor(session) {
3767
+ this.session = session;
3768
+ }
3769
+ clear() {
3770
+ this.session.clearCache();
3771
+ }
3772
+ resetCacheControl() {
3773
+ this.#setCacheControl("");
3774
+ }
3775
+ exemptPageFromCache() {
3776
+ this.#setCacheControl("no-cache");
3777
+ }
3778
+ exemptPageFromPreview() {
3779
+ this.#setCacheControl("no-preview");
3780
+ }
3781
+ #setCacheControl(value) {
3782
+ setMetaContent("turbo-cache-control", value);
3783
+ }
2950
3784
  }
2951
3785
 
2952
3786
  class Session {
2953
- constructor() {
2954
- this.navigator = new Navigator(this);
2955
- this.history = new History(this);
2956
- this.preloader = new Preloader(this);
2957
- this.view = new PageView(this, document.documentElement);
2958
- this.adapter = new BrowserAdapter(this);
2959
- this.pageObserver = new PageObserver(this);
2960
- this.cacheObserver = new CacheObserver;
2961
- this.linkClickObserver = new LinkClickObserver(this, window);
2962
- this.formSubmitObserver = new FormSubmitObserver(this, document);
2963
- this.scrollObserver = new ScrollObserver(this);
2964
- this.streamObserver = new StreamObserver(this);
2965
- this.formLinkClickObserver = new FormLinkClickObserver(this, document.documentElement);
2966
- this.frameRedirector = new FrameRedirector(this, document.documentElement);
2967
- this.streamMessageRenderer = new StreamMessageRenderer;
2968
- this.drive = true;
2969
- this.enabled = true;
2970
- this.progressBarDelay = 500;
2971
- this.started = false;
2972
- this.formMode = "on";
3787
+ navigator=new Navigator(this);
3788
+ history=new History(this);
3789
+ view=new PageView(this, document.documentElement);
3790
+ adapter=new BrowserAdapter(this);
3791
+ pageObserver=new PageObserver(this);
3792
+ cacheObserver=new CacheObserver;
3793
+ linkClickObserver=new LinkClickObserver(this, window);
3794
+ formSubmitObserver=new FormSubmitObserver(this, document);
3795
+ scrollObserver=new ScrollObserver(this);
3796
+ streamObserver=new StreamObserver(this);
3797
+ formLinkClickObserver=new FormLinkClickObserver(this, document.documentElement);
3798
+ frameRedirector=new FrameRedirector(this, document.documentElement);
3799
+ streamMessageRenderer=new StreamMessageRenderer;
3800
+ cache=new Cache(this);
3801
+ drive=true;
3802
+ enabled=true;
3803
+ progressBarDelay=500;
3804
+ started=false;
3805
+ formMode="on";
3806
+ constructor(recentRequests) {
3807
+ this.recentRequests = recentRequests;
3808
+ this.preloader = new Preloader(this, this.view.snapshotCache);
2973
3809
  }
2974
3810
  start() {
2975
3811
  if (!this.started) {
@@ -3001,6 +3837,7 @@ class Session {
3001
3837
  this.streamObserver.stop();
3002
3838
  this.frameRedirector.stop();
3003
3839
  this.history.stop();
3840
+ this.preloader.stop();
3004
3841
  this.started = false;
3005
3842
  }
3006
3843
  }
@@ -3016,6 +3853,15 @@ class Session {
3016
3853
  this.navigator.proposeVisit(expandURL(location), options);
3017
3854
  }
3018
3855
  }
3856
+ refresh(url, requestId) {
3857
+ const isRecentRequest = requestId && this.recentRequests.has(requestId);
3858
+ if (!isRecentRequest) {
3859
+ this.cache.exemptPageFromPreview();
3860
+ this.visit(url, {
3861
+ action: "replace"
3862
+ });
3863
+ }
3864
+ }
3019
3865
  connectStreamSource(source) {
3020
3866
  this.streamObserver.connectStreamSource(source);
3021
3867
  }
@@ -3040,11 +3886,24 @@ class Session {
3040
3886
  get restorationIdentifier() {
3041
3887
  return this.history.restorationIdentifier;
3042
3888
  }
3043
- historyPoppedToLocationWithRestorationIdentifier(location, restorationIdentifier) {
3889
+ shouldPreloadLink(element) {
3890
+ const isUnsafe = element.hasAttribute("data-turbo-method");
3891
+ const isStream = element.hasAttribute("data-turbo-stream");
3892
+ const frameTarget = element.getAttribute("data-turbo-frame");
3893
+ const frame = frameTarget == "_top" ? null : document.getElementById(frameTarget) || findClosestRecursively(element, "turbo-frame:not([disabled])");
3894
+ if (isUnsafe || isStream || frame instanceof FrameElement) {
3895
+ return false;
3896
+ } else {
3897
+ const location = new URL(element.href);
3898
+ return this.elementIsNavigatable(element) && locationIsVisitable(location, this.snapshot.rootLocation);
3899
+ }
3900
+ }
3901
+ historyPoppedToLocationWithRestorationIdentifierAndDirection(location, restorationIdentifier, direction) {
3044
3902
  if (this.enabled) {
3045
3903
  this.navigator.startVisit(location, restorationIdentifier, {
3046
3904
  action: "restore",
3047
- historyChanged: true
3905
+ historyChanged: true,
3906
+ direction: direction
3048
3907
  });
3049
3908
  } else {
3050
3909
  this.adapter.pageInvalidated({
@@ -3082,6 +3941,7 @@ class Session {
3082
3941
  visitStarted(visit) {
3083
3942
  if (!visit.acceptsStreamResponse) {
3084
3943
  markAsBusy(document.documentElement);
3944
+ this.view.markVisitDirection(visit.direction);
3085
3945
  }
3086
3946
  extendURLWithDeprecatedProperties(visit.location);
3087
3947
  if (!visit.silent) {
@@ -3089,6 +3949,7 @@ class Session {
3089
3949
  }
3090
3950
  }
3091
3951
  visitCompleted(visit) {
3952
+ this.view.unmarkVisitDirection();
3092
3953
  clearBusyState(document.documentElement);
3093
3954
  this.notifyApplicationAfterPageLoad(visit.getTimingMetrics());
3094
3955
  }
@@ -3099,7 +3960,7 @@ class Session {
3099
3960
  this.notifyApplicationAfterVisitingSamePageLocation(oldURL, newURL);
3100
3961
  }
3101
3962
  willSubmitForm(form, submitter) {
3102
- const action = getAction(form, submitter);
3963
+ const action = getAction$1(form, submitter);
3103
3964
  return this.submissionIsNavigatable(form, submitter) && locationIsVisitable(expandURL(action), this.snapshot.rootLocation);
3104
3965
  }
3105
3966
  formSubmitted(form, submitter) {
@@ -3119,22 +3980,21 @@ class Session {
3119
3980
  this.renderStreamMessage(message);
3120
3981
  }
3121
3982
  viewWillCacheSnapshot() {
3122
- var _a;
3123
- if (!((_a = this.navigator.currentVisit) === null || _a === void 0 ? void 0 : _a.silent)) {
3983
+ if (!this.navigator.currentVisit?.silent) {
3124
3984
  this.notifyApplicationBeforeCachingSnapshot();
3125
3985
  }
3126
3986
  }
3127
- allowsImmediateRender({element: element}, options) {
3128
- const event = this.notifyApplicationBeforeRender(element, options);
3987
+ allowsImmediateRender({element: element}, isPreview, options) {
3988
+ const event = this.notifyApplicationBeforeRender(element, isPreview, options);
3129
3989
  const {defaultPrevented: defaultPrevented, detail: {render: render}} = event;
3130
3990
  if (this.view.renderer && render) {
3131
3991
  this.view.renderer.renderElement = render;
3132
3992
  }
3133
3993
  return !defaultPrevented;
3134
3994
  }
3135
- viewRenderedSnapshot(_snapshot, _isPreview) {
3995
+ viewRenderedSnapshot(_snapshot, isPreview, renderMethod) {
3136
3996
  this.view.lastRenderedLocation = this.history.location;
3137
- this.notifyApplicationAfterRender();
3997
+ this.notifyApplicationAfterRender(isPreview, renderMethod);
3138
3998
  }
3139
3999
  preloadOnLoadLinksForView(element) {
3140
4000
  this.preloader.preloadOnLoadLinksForView(element);
@@ -3185,16 +4045,23 @@ class Session {
3185
4045
  notifyApplicationBeforeCachingSnapshot() {
3186
4046
  return dispatch("turbo:before-cache");
3187
4047
  }
3188
- notifyApplicationBeforeRender(newBody, options) {
4048
+ notifyApplicationBeforeRender(newBody, isPreview, options) {
3189
4049
  return dispatch("turbo:before-render", {
3190
- detail: Object.assign({
3191
- newBody: newBody
3192
- }, options),
4050
+ detail: {
4051
+ newBody: newBody,
4052
+ isPreview: isPreview,
4053
+ ...options
4054
+ },
3193
4055
  cancelable: true
3194
4056
  });
3195
4057
  }
3196
- notifyApplicationAfterRender() {
3197
- return dispatch("turbo:render");
4058
+ notifyApplicationAfterRender(isPreview, renderMethod) {
4059
+ return dispatch("turbo:render", {
4060
+ detail: {
4061
+ isPreview: isPreview,
4062
+ renderMethod: renderMethod
4063
+ }
4064
+ });
3198
4065
  }
3199
4066
  notifyApplicationAfterPageLoad(timing = {}) {
3200
4067
  return dispatch("turbo:load", {
@@ -3273,67 +4140,9 @@ const deprecatedLocationPropertyDescriptors = {
3273
4140
  }
3274
4141
  };
3275
4142
 
3276
- class Cache {
3277
- constructor(session) {
3278
- this.session = session;
3279
- }
3280
- clear() {
3281
- this.session.clearCache();
3282
- }
3283
- resetCacheControl() {
3284
- this.setCacheControl("");
3285
- }
3286
- exemptPageFromCache() {
3287
- this.setCacheControl("no-cache");
3288
- }
3289
- exemptPageFromPreview() {
3290
- this.setCacheControl("no-preview");
3291
- }
3292
- setCacheControl(value) {
3293
- setMetaContent("turbo-cache-control", value);
3294
- }
3295
- }
3296
-
3297
- const StreamActions = {
3298
- after() {
3299
- this.targetElements.forEach((e => {
3300
- var _a;
3301
- return (_a = e.parentElement) === null || _a === void 0 ? void 0 : _a.insertBefore(this.templateContent, e.nextSibling);
3302
- }));
3303
- },
3304
- append() {
3305
- this.removeDuplicateTargetChildren();
3306
- this.targetElements.forEach((e => e.append(this.templateContent)));
3307
- },
3308
- before() {
3309
- this.targetElements.forEach((e => {
3310
- var _a;
3311
- return (_a = e.parentElement) === null || _a === void 0 ? void 0 : _a.insertBefore(this.templateContent, e);
3312
- }));
3313
- },
3314
- prepend() {
3315
- this.removeDuplicateTargetChildren();
3316
- this.targetElements.forEach((e => e.prepend(this.templateContent)));
3317
- },
3318
- remove() {
3319
- this.targetElements.forEach((e => e.remove()));
3320
- },
3321
- replace() {
3322
- this.targetElements.forEach((e => e.replaceWith(this.templateContent)));
3323
- },
3324
- update() {
3325
- this.targetElements.forEach((targetElement => {
3326
- targetElement.innerHTML = "";
3327
- targetElement.append(this.templateContent);
3328
- }));
3329
- }
3330
- };
3331
-
3332
- const session = new Session;
3333
-
3334
- const cache = new Cache(session);
4143
+ const session = new Session(recentRequests);
3335
4144
 
3336
- const {navigator: navigator$1} = session;
4145
+ const {cache: cache, navigator: navigator$1} = session;
3337
4146
 
3338
4147
  function start() {
3339
4148
  session.start();
@@ -3384,6 +4193,7 @@ var Turbo = Object.freeze({
3384
4193
  PageRenderer: PageRenderer,
3385
4194
  PageSnapshot: PageSnapshot,
3386
4195
  FrameRenderer: FrameRenderer,
4196
+ fetch: fetchWithTurboHeaders,
3387
4197
  start: start,
3388
4198
  registerAdapter: registerAdapter,
3389
4199
  visit: visit,
@@ -3393,28 +4203,20 @@ var Turbo = Object.freeze({
3393
4203
  clearCache: clearCache,
3394
4204
  setProgressBarDelay: setProgressBarDelay,
3395
4205
  setConfirmMethod: setConfirmMethod,
3396
- setFormMode: setFormMode,
3397
- StreamActions: StreamActions
4206
+ setFormMode: setFormMode
3398
4207
  });
3399
4208
 
3400
4209
  class TurboFrameMissingError extends Error {}
3401
4210
 
3402
4211
  class FrameController {
4212
+ fetchResponseLoaded=_fetchResponse => Promise.resolve();
4213
+ #currentFetchRequest=null;
4214
+ #resolveVisitPromise=() => {};
4215
+ #connected=false;
4216
+ #hasBeenLoaded=false;
4217
+ #ignoredAttributes=new Set;
4218
+ action=null;
3403
4219
  constructor(element) {
3404
- this.fetchResponseLoaded = _fetchResponse => {};
3405
- this.currentFetchRequest = null;
3406
- this.resolveVisitPromise = () => {};
3407
- this.connected = false;
3408
- this.hasBeenLoaded = false;
3409
- this.ignoredAttributes = new Set;
3410
- this.action = null;
3411
- this.visitCachedSnapshot = ({element: element}) => {
3412
- const frame = element.querySelector("#" + this.element.id);
3413
- if (frame && this.previousFrameElement) {
3414
- frame.replaceChildren(...this.previousFrameElement.children);
3415
- }
3416
- delete this.previousFrameElement;
3417
- };
3418
4220
  this.element = element;
3419
4221
  this.view = new FrameView(this, this.element);
3420
4222
  this.appearanceObserver = new AppearanceObserver(this, this.element);
@@ -3424,12 +4226,12 @@ class FrameController {
3424
4226
  this.formSubmitObserver = new FormSubmitObserver(this, this.element);
3425
4227
  }
3426
4228
  connect() {
3427
- if (!this.connected) {
3428
- this.connected = true;
4229
+ if (!this.#connected) {
4230
+ this.#connected = true;
3429
4231
  if (this.loadingStyle == FrameLoadingStyle.lazy) {
3430
4232
  this.appearanceObserver.start();
3431
4233
  } else {
3432
- this.loadSourceURL();
4234
+ this.#loadSourceURL();
3433
4235
  }
3434
4236
  this.formLinkClickObserver.start();
3435
4237
  this.linkInterceptor.start();
@@ -3437,8 +4239,8 @@ class FrameController {
3437
4239
  }
3438
4240
  }
3439
4241
  disconnect() {
3440
- if (this.connected) {
3441
- this.connected = false;
4242
+ if (this.#connected) {
4243
+ this.#connected = false;
3442
4244
  this.appearanceObserver.stop();
3443
4245
  this.formLinkClickObserver.stop();
3444
4246
  this.linkInterceptor.stop();
@@ -3447,21 +4249,21 @@ class FrameController {
3447
4249
  }
3448
4250
  disabledChanged() {
3449
4251
  if (this.loadingStyle == FrameLoadingStyle.eager) {
3450
- this.loadSourceURL();
4252
+ this.#loadSourceURL();
3451
4253
  }
3452
4254
  }
3453
4255
  sourceURLChanged() {
3454
- if (this.isIgnoringChangesTo("src")) return;
4256
+ if (this.#isIgnoringChangesTo("src")) return;
3455
4257
  if (this.element.isConnected) {
3456
4258
  this.complete = false;
3457
4259
  }
3458
- if (this.loadingStyle == FrameLoadingStyle.eager || this.hasBeenLoaded) {
3459
- this.loadSourceURL();
4260
+ if (this.loadingStyle == FrameLoadingStyle.eager || this.#hasBeenLoaded) {
4261
+ this.#loadSourceURL();
3460
4262
  }
3461
4263
  }
3462
4264
  sourceURLReloaded() {
3463
4265
  const {src: src} = this.element;
3464
- this.ignoringChangesToAttribute("complete", (() => {
4266
+ this.#ignoringChangesToAttribute("complete", (() => {
3465
4267
  this.element.removeAttribute("complete");
3466
4268
  }));
3467
4269
  this.element.src = null;
@@ -3469,23 +4271,23 @@ class FrameController {
3469
4271
  return this.element.loaded;
3470
4272
  }
3471
4273
  completeChanged() {
3472
- if (this.isIgnoringChangesTo("complete")) return;
3473
- this.loadSourceURL();
4274
+ if (this.#isIgnoringChangesTo("complete")) return;
4275
+ this.#loadSourceURL();
3474
4276
  }
3475
4277
  loadingStyleChanged() {
3476
4278
  if (this.loadingStyle == FrameLoadingStyle.lazy) {
3477
4279
  this.appearanceObserver.start();
3478
4280
  } else {
3479
4281
  this.appearanceObserver.stop();
3480
- this.loadSourceURL();
4282
+ this.#loadSourceURL();
3481
4283
  }
3482
4284
  }
3483
- async loadSourceURL() {
4285
+ async #loadSourceURL() {
3484
4286
  if (this.enabled && this.isActive && !this.complete && this.sourceURL) {
3485
- this.element.loaded = this.visit(expandURL(this.sourceURL));
4287
+ this.element.loaded = this.#visit(expandURL(this.sourceURL));
3486
4288
  this.appearanceObserver.stop();
3487
4289
  await this.element.loaded;
3488
- this.hasBeenLoaded = true;
4290
+ this.#hasBeenLoaded = true;
3489
4291
  }
3490
4292
  }
3491
4293
  async loadResponse(fetchResponse) {
@@ -3498,34 +4300,34 @@ class FrameController {
3498
4300
  const document = parseHTMLDocument(html);
3499
4301
  const pageSnapshot = PageSnapshot.fromDocument(document);
3500
4302
  if (pageSnapshot.isVisitable) {
3501
- await this.loadFrameResponse(fetchResponse, document);
4303
+ await this.#loadFrameResponse(fetchResponse, document);
3502
4304
  } else {
3503
- await this.handleUnvisitableFrameResponse(fetchResponse);
4305
+ await this.#handleUnvisitableFrameResponse(fetchResponse);
3504
4306
  }
3505
4307
  }
3506
4308
  } finally {
3507
- this.fetchResponseLoaded = () => {};
4309
+ this.fetchResponseLoaded = () => Promise.resolve();
3508
4310
  }
3509
4311
  }
3510
4312
  elementAppearedInViewport(element) {
3511
4313
  this.proposeVisitIfNavigatedWithAction(element, element);
3512
- this.loadSourceURL();
4314
+ this.#loadSourceURL();
3513
4315
  }
3514
4316
  willSubmitFormLinkToLocation(link) {
3515
- return this.shouldInterceptNavigation(link);
4317
+ return this.#shouldInterceptNavigation(link);
3516
4318
  }
3517
4319
  submittedFormLinkToLocation(link, _location, form) {
3518
- const frame = this.findFrameElement(link);
4320
+ const frame = this.#findFrameElement(link);
3519
4321
  if (frame) form.setAttribute("data-turbo-frame", frame.id);
3520
4322
  }
3521
4323
  shouldInterceptLinkClick(element, _location, _event) {
3522
- return this.shouldInterceptNavigation(element);
4324
+ return this.#shouldInterceptNavigation(element);
3523
4325
  }
3524
4326
  linkClickIntercepted(element, location) {
3525
- this.navigateFrame(element, location);
4327
+ this.#navigateFrame(element, location);
3526
4328
  }
3527
4329
  willSubmitForm(element, submitter) {
3528
- return element.closest("turbo-frame") == this.element && this.shouldInterceptNavigation(element, submitter);
4330
+ return element.closest("turbo-frame") == this.element && this.#shouldInterceptNavigation(element, submitter);
3529
4331
  }
3530
4332
  formSubmitted(element, submitter) {
3531
4333
  if (this.formSubmission) {
@@ -3537,9 +4339,8 @@ class FrameController {
3537
4339
  this.formSubmission.start();
3538
4340
  }
3539
4341
  prepareRequest(request) {
3540
- var _a;
3541
4342
  request.headers["Turbo-Frame"] = this.id;
3542
- if ((_a = this.currentNavigationElement) === null || _a === void 0 ? void 0 : _a.hasAttribute("data-turbo-stream")) {
4343
+ if (this.currentNavigationElement?.hasAttribute("data-turbo-stream")) {
3543
4344
  request.acceptResponseType(StreamMessage.contentType);
3544
4345
  }
3545
4346
  }
@@ -3547,28 +4348,28 @@ class FrameController {
3547
4348
  markAsBusy(this.element);
3548
4349
  }
3549
4350
  requestPreventedHandlingResponse(_request, _response) {
3550
- this.resolveVisitPromise();
4351
+ this.#resolveVisitPromise();
3551
4352
  }
3552
4353
  async requestSucceededWithResponse(request, response) {
3553
4354
  await this.loadResponse(response);
3554
- this.resolveVisitPromise();
4355
+ this.#resolveVisitPromise();
3555
4356
  }
3556
4357
  async requestFailedWithResponse(request, response) {
3557
4358
  await this.loadResponse(response);
3558
- this.resolveVisitPromise();
4359
+ this.#resolveVisitPromise();
3559
4360
  }
3560
4361
  requestErrored(request, error) {
3561
4362
  console.error(error);
3562
- this.resolveVisitPromise();
4363
+ this.#resolveVisitPromise();
3563
4364
  }
3564
4365
  requestFinished(_request) {
3565
4366
  clearBusyState(this.element);
3566
4367
  }
3567
4368
  formSubmissionStarted({formElement: formElement}) {
3568
- markAsBusy(formElement, this.findFrameElement(formElement));
4369
+ markAsBusy(formElement, this.#findFrameElement(formElement));
3569
4370
  }
3570
4371
  formSubmissionSucceededWithResponse(formSubmission, response) {
3571
- const frame = this.findFrameElement(formSubmission.formElement, formSubmission.submitter);
4372
+ const frame = this.#findFrameElement(formSubmission.formElement, formSubmission.submitter);
3572
4373
  frame.delegate.proposeVisitIfNavigatedWithAction(frame, formSubmission.formElement, formSubmission.submitter);
3573
4374
  frame.delegate.loadResponse(response);
3574
4375
  if (!formSubmission.isSafe) {
@@ -3583,14 +4384,15 @@ class FrameController {
3583
4384
  console.error(error);
3584
4385
  }
3585
4386
  formSubmissionFinished({formElement: formElement}) {
3586
- clearBusyState(formElement, this.findFrameElement(formElement));
4387
+ clearBusyState(formElement, this.#findFrameElement(formElement));
3587
4388
  }
3588
- allowsImmediateRender({element: newFrame}, options) {
4389
+ allowsImmediateRender({element: newFrame}, _isPreview, options) {
3589
4390
  const event = dispatch("turbo:before-frame-render", {
3590
4391
  target: this.element,
3591
- detail: Object.assign({
3592
- newFrame: newFrame
3593
- }, options),
4392
+ detail: {
4393
+ newFrame: newFrame,
4394
+ ...options
4395
+ },
3594
4396
  cancelable: true
3595
4397
  });
3596
4398
  const {defaultPrevented: defaultPrevented, detail: {render: render}} = event;
@@ -3599,7 +4401,7 @@ class FrameController {
3599
4401
  }
3600
4402
  return !defaultPrevented;
3601
4403
  }
3602
- viewRenderedSnapshot(_snapshot, _isPreview) {}
4404
+ viewRenderedSnapshot(_snapshot, _isPreview, _renderMethod) {}
3603
4405
  preloadOnLoadLinksForView(element) {
3604
4406
  session.preloadOnLoadLinksForView(element);
3605
4407
  }
@@ -3607,7 +4409,14 @@ class FrameController {
3607
4409
  willRenderFrame(currentElement, _newElement) {
3608
4410
  this.previousFrameElement = currentElement.cloneNode(true);
3609
4411
  }
3610
- async loadFrameResponse(fetchResponse, document) {
4412
+ visitCachedSnapshot=({element: element}) => {
4413
+ const frame = element.querySelector("#" + this.element.id);
4414
+ if (frame && this.previousFrameElement) {
4415
+ frame.replaceChildren(...this.previousFrameElement.children);
4416
+ }
4417
+ delete this.previousFrameElement;
4418
+ };
4419
+ async #loadFrameResponse(fetchResponse, document) {
3611
4420
  const newFrameElement = await this.extractForeignFrameElement(document.body);
3612
4421
  if (newFrameElement) {
3613
4422
  const snapshot = new Snapshot(newFrameElement);
@@ -3618,29 +4427,28 @@ class FrameController {
3618
4427
  this.complete = true;
3619
4428
  session.frameRendered(fetchResponse, this.element);
3620
4429
  session.frameLoaded(this.element);
3621
- this.fetchResponseLoaded(fetchResponse);
3622
- } else if (this.willHandleFrameMissingFromResponse(fetchResponse)) {
3623
- this.handleFrameMissingFromResponse(fetchResponse);
4430
+ await this.fetchResponseLoaded(fetchResponse);
4431
+ } else if (this.#willHandleFrameMissingFromResponse(fetchResponse)) {
4432
+ this.#handleFrameMissingFromResponse(fetchResponse);
3624
4433
  }
3625
4434
  }
3626
- async visit(url) {
3627
- var _a;
4435
+ async #visit(url) {
3628
4436
  const request = new FetchRequest(this, FetchMethod.get, url, new URLSearchParams, this.element);
3629
- (_a = this.currentFetchRequest) === null || _a === void 0 ? void 0 : _a.cancel();
3630
- this.currentFetchRequest = request;
4437
+ this.#currentFetchRequest?.cancel();
4438
+ this.#currentFetchRequest = request;
3631
4439
  return new Promise((resolve => {
3632
- this.resolveVisitPromise = () => {
3633
- this.resolveVisitPromise = () => {};
3634
- this.currentFetchRequest = null;
4440
+ this.#resolveVisitPromise = () => {
4441
+ this.#resolveVisitPromise = () => {};
4442
+ this.#currentFetchRequest = null;
3635
4443
  resolve();
3636
4444
  };
3637
4445
  request.perform();
3638
4446
  }));
3639
4447
  }
3640
- navigateFrame(element, url, submitter) {
3641
- const frame = this.findFrameElement(element, submitter);
4448
+ #navigateFrame(element, url, submitter) {
4449
+ const frame = this.#findFrameElement(element, submitter);
3642
4450
  frame.delegate.proposeVisitIfNavigatedWithAction(frame, element, submitter);
3643
- this.withCurrentNavigationElement(element, (() => {
4451
+ this.#withCurrentNavigationElement(element, (() => {
3644
4452
  frame.src = url;
3645
4453
  }));
3646
4454
  }
@@ -3649,10 +4457,10 @@ class FrameController {
3649
4457
  if (this.action) {
3650
4458
  const pageSnapshot = PageSnapshot.fromElement(frame).clone();
3651
4459
  const {visitCachedSnapshot: visitCachedSnapshot} = frame.delegate;
3652
- frame.delegate.fetchResponseLoaded = fetchResponse => {
4460
+ frame.delegate.fetchResponseLoaded = async fetchResponse => {
3653
4461
  if (frame.src) {
3654
4462
  const {statusCode: statusCode, redirected: redirected} = fetchResponse;
3655
- const responseHTML = frame.ownerDocument.documentElement.outerHTML;
4463
+ const responseHTML = await fetchResponse.responseHTML;
3656
4464
  const response = {
3657
4465
  statusCode: statusCode,
3658
4466
  redirected: redirected,
@@ -3678,16 +4486,16 @@ class FrameController {
3678
4486
  session.history.update(method, expandURL(this.element.src || ""), this.restorationIdentifier);
3679
4487
  }
3680
4488
  }
3681
- async handleUnvisitableFrameResponse(fetchResponse) {
4489
+ async #handleUnvisitableFrameResponse(fetchResponse) {
3682
4490
  console.warn(`The response (${fetchResponse.statusCode}) from <turbo-frame id="${this.element.id}"> is performing a full page visit due to turbo-visit-control.`);
3683
- await this.visitResponse(fetchResponse.response);
4491
+ await this.#visitResponse(fetchResponse.response);
3684
4492
  }
3685
- willHandleFrameMissingFromResponse(fetchResponse) {
4493
+ #willHandleFrameMissingFromResponse(fetchResponse) {
3686
4494
  this.element.setAttribute("complete", "");
3687
4495
  const response = fetchResponse.response;
3688
- const visit = async (url, options = {}) => {
4496
+ const visit = async (url, options) => {
3689
4497
  if (url instanceof Response) {
3690
- this.visitResponse(url);
4498
+ this.#visitResponse(url);
3691
4499
  } else {
3692
4500
  session.visit(url, options);
3693
4501
  }
@@ -3702,15 +4510,15 @@ class FrameController {
3702
4510
  });
3703
4511
  return !event.defaultPrevented;
3704
4512
  }
3705
- handleFrameMissingFromResponse(fetchResponse) {
4513
+ #handleFrameMissingFromResponse(fetchResponse) {
3706
4514
  this.view.missing();
3707
- this.throwFrameMissingError(fetchResponse);
4515
+ this.#throwFrameMissingError(fetchResponse);
3708
4516
  }
3709
- throwFrameMissingError(fetchResponse) {
4517
+ #throwFrameMissingError(fetchResponse) {
3710
4518
  const message = `The response (${fetchResponse.statusCode}) did not contain the expected <turbo-frame id="${this.element.id}"> and will be ignored. To perform a full page visit instead, set turbo-visit-control to reload.`;
3711
4519
  throw new TurboFrameMissingError(message);
3712
4520
  }
3713
- async visitResponse(response) {
4521
+ async #visitResponse(response) {
3714
4522
  const wrapped = new FetchResponse(response);
3715
4523
  const responseHTML = await wrapped.responseHTML;
3716
4524
  const {location: location, redirected: redirected, statusCode: statusCode} = wrapped;
@@ -3722,10 +4530,9 @@ class FrameController {
3722
4530
  }
3723
4531
  });
3724
4532
  }
3725
- findFrameElement(element, submitter) {
3726
- var _a;
4533
+ #findFrameElement(element, submitter) {
3727
4534
  const id = getAttribute("data-turbo-frame", submitter, element) || this.element.getAttribute("target");
3728
- return (_a = getFrameElementById(id)) !== null && _a !== void 0 ? _a : this.element;
4535
+ return getFrameElementById(id) ?? this.element;
3729
4536
  }
3730
4537
  async extractForeignFrameElement(container) {
3731
4538
  let element;
@@ -3746,13 +4553,13 @@ class FrameController {
3746
4553
  }
3747
4554
  return null;
3748
4555
  }
3749
- formActionIsVisitable(form, submitter) {
3750
- const action = getAction(form, submitter);
4556
+ #formActionIsVisitable(form, submitter) {
4557
+ const action = getAction$1(form, submitter);
3751
4558
  return locationIsVisitable(expandURL(action), this.rootLocation);
3752
4559
  }
3753
- shouldInterceptNavigation(element, submitter) {
4560
+ #shouldInterceptNavigation(element, submitter) {
3754
4561
  const id = getAttribute("data-turbo-frame", submitter, element) || this.element.getAttribute("target");
3755
- if (element instanceof HTMLFormElement && !this.formActionIsVisitable(element, submitter)) {
4562
+ if (element instanceof HTMLFormElement && !this.#formActionIsVisitable(element, submitter)) {
3756
4563
  return false;
3757
4564
  }
3758
4565
  if (!this.enabled || id == "_top") {
@@ -3784,21 +4591,21 @@ class FrameController {
3784
4591
  }
3785
4592
  }
3786
4593
  set sourceURL(sourceURL) {
3787
- this.ignoringChangesToAttribute("src", (() => {
3788
- this.element.src = sourceURL !== null && sourceURL !== void 0 ? sourceURL : null;
4594
+ this.#ignoringChangesToAttribute("src", (() => {
4595
+ this.element.src = sourceURL ?? null;
3789
4596
  }));
3790
4597
  }
3791
4598
  get loadingStyle() {
3792
4599
  return this.element.loading;
3793
4600
  }
3794
4601
  get isLoading() {
3795
- return this.formSubmission !== undefined || this.resolveVisitPromise() !== undefined;
4602
+ return this.formSubmission !== undefined || this.#resolveVisitPromise() !== undefined;
3796
4603
  }
3797
4604
  get complete() {
3798
4605
  return this.element.hasAttribute("complete");
3799
4606
  }
3800
4607
  set complete(value) {
3801
- this.ignoringChangesToAttribute("complete", (() => {
4608
+ this.#ignoringChangesToAttribute("complete", (() => {
3802
4609
  if (value) {
3803
4610
  this.element.setAttribute("complete", "");
3804
4611
  } else {
@@ -3807,23 +4614,22 @@ class FrameController {
3807
4614
  }));
3808
4615
  }
3809
4616
  get isActive() {
3810
- return this.element.isActive && this.connected;
4617
+ return this.element.isActive && this.#connected;
3811
4618
  }
3812
4619
  get rootLocation() {
3813
- var _a;
3814
4620
  const meta = this.element.ownerDocument.querySelector(`meta[name="turbo-root"]`);
3815
- const root = (_a = meta === null || meta === void 0 ? void 0 : meta.content) !== null && _a !== void 0 ? _a : "/";
4621
+ const root = meta?.content ?? "/";
3816
4622
  return expandURL(root);
3817
4623
  }
3818
- isIgnoringChangesTo(attributeName) {
3819
- return this.ignoredAttributes.has(attributeName);
4624
+ #isIgnoringChangesTo(attributeName) {
4625
+ return this.#ignoredAttributes.has(attributeName);
3820
4626
  }
3821
- ignoringChangesToAttribute(attributeName, callback) {
3822
- this.ignoredAttributes.add(attributeName);
4627
+ #ignoringChangesToAttribute(attributeName, callback) {
4628
+ this.#ignoredAttributes.add(attributeName);
3823
4629
  callback();
3824
- this.ignoredAttributes.delete(attributeName);
4630
+ this.#ignoredAttributes.delete(attributeName);
3825
4631
  }
3826
- withCurrentNavigationElement(element, callback) {
4632
+ #withCurrentNavigationElement(element, callback) {
3827
4633
  this.currentNavigationElement = element;
3828
4634
  callback();
3829
4635
  delete this.currentNavigationElement;
@@ -3856,6 +4662,38 @@ function activateElement(element, currentURL) {
3856
4662
  }
3857
4663
  }
3858
4664
 
4665
+ const StreamActions = {
4666
+ after() {
4667
+ this.targetElements.forEach((e => e.parentElement?.insertBefore(this.templateContent, e.nextSibling)));
4668
+ },
4669
+ append() {
4670
+ this.removeDuplicateTargetChildren();
4671
+ this.targetElements.forEach((e => e.append(this.templateContent)));
4672
+ },
4673
+ before() {
4674
+ this.targetElements.forEach((e => e.parentElement?.insertBefore(this.templateContent, e)));
4675
+ },
4676
+ prepend() {
4677
+ this.removeDuplicateTargetChildren();
4678
+ this.targetElements.forEach((e => e.prepend(this.templateContent)));
4679
+ },
4680
+ remove() {
4681
+ this.targetElements.forEach((e => e.remove()));
4682
+ },
4683
+ replace() {
4684
+ this.targetElements.forEach((e => e.replaceWith(this.templateContent)));
4685
+ },
4686
+ update() {
4687
+ this.targetElements.forEach((targetElement => {
4688
+ targetElement.innerHTML = "";
4689
+ targetElement.append(this.templateContent);
4690
+ }));
4691
+ },
4692
+ refresh() {
4693
+ session.refresh(this.baseURI, this.requestId);
4694
+ }
4695
+ };
4696
+
3859
4697
  class StreamElement extends HTMLElement {
3860
4698
  static async renderElement(newElement) {
3861
4699
  await newElement.performAction();
@@ -3870,11 +4708,10 @@ class StreamElement extends HTMLElement {
3870
4708
  }
3871
4709
  }
3872
4710
  async render() {
3873
- var _a;
3874
- return (_a = this.renderPromise) !== null && _a !== void 0 ? _a : this.renderPromise = (async () => {
4711
+ return this.renderPromise ??= (async () => {
3875
4712
  const event = this.beforeRenderEvent;
3876
4713
  if (this.dispatchEvent(event)) {
3877
- await nextAnimationFrame();
4714
+ await nextRepaint();
3878
4715
  await event.detail.render(this);
3879
4716
  }
3880
4717
  })();
@@ -3882,15 +4719,14 @@ class StreamElement extends HTMLElement {
3882
4719
  disconnect() {
3883
4720
  try {
3884
4721
  this.remove();
3885
- } catch (_a) {}
4722
+ } catch {}
3886
4723
  }
3887
4724
  removeDuplicateTargetChildren() {
3888
4725
  this.duplicateChildren.forEach((c => c.remove()));
3889
4726
  }
3890
4727
  get duplicateChildren() {
3891
- var _a;
3892
4728
  const existingChildren = this.targetElements.flatMap((e => [ ...e.children ])).filter((c => !!c.id));
3893
- const newChildrenIds = [ ...((_a = this.templateContent) === null || _a === void 0 ? void 0 : _a.children) || [] ].filter((c => !!c.id)).map((c => c.id));
4729
+ const newChildrenIds = [ ...this.templateContent?.children || [] ].filter((c => !!c.id)).map((c => c.id));
3894
4730
  return existingChildren.filter((c => newChildrenIds.includes(c.id)));
3895
4731
  }
3896
4732
  get performAction() {
@@ -3899,9 +4735,9 @@ class StreamElement extends HTMLElement {
3899
4735
  if (actionFunction) {
3900
4736
  return actionFunction;
3901
4737
  }
3902
- this.raise("unknown action");
4738
+ this.#raise("unknown action");
3903
4739
  }
3904
- this.raise("action attribute is missing");
4740
+ this.#raise("action attribute is missing");
3905
4741
  }
3906
4742
  get targetElements() {
3907
4743
  if (this.target) {
@@ -3909,7 +4745,7 @@ class StreamElement extends HTMLElement {
3909
4745
  } else if (this.targets) {
3910
4746
  return this.targetElementsByQuery;
3911
4747
  } else {
3912
- this.raise("target or targets attribute is missing");
4748
+ this.#raise("target or targets attribute is missing");
3913
4749
  }
3914
4750
  }
3915
4751
  get templateContent() {
@@ -3923,7 +4759,7 @@ class StreamElement extends HTMLElement {
3923
4759
  } else if (this.firstElementChild instanceof HTMLTemplateElement) {
3924
4760
  return this.firstElementChild;
3925
4761
  }
3926
- this.raise("first child element must be a <template> element");
4762
+ this.#raise("first child element must be a <template> element");
3927
4763
  }
3928
4764
  get action() {
3929
4765
  return this.getAttribute("action");
@@ -3934,12 +4770,14 @@ class StreamElement extends HTMLElement {
3934
4770
  get targets() {
3935
4771
  return this.getAttribute("targets");
3936
4772
  }
3937
- raise(message) {
4773
+ get requestId() {
4774
+ return this.getAttribute("request-id");
4775
+ }
4776
+ #raise(message) {
3938
4777
  throw new Error(`${this.description}: ${message}`);
3939
4778
  }
3940
4779
  get description() {
3941
- var _a, _b;
3942
- return (_b = ((_a = this.outerHTML.match(/<[^>]+>/)) !== null && _a !== void 0 ? _a : [])[0]) !== null && _b !== void 0 ? _b : "<turbo-stream>";
4780
+ return (this.outerHTML.match(/<[^>]+>/) ?? [])[0] ?? "<turbo-stream>";
3943
4781
  }
3944
4782
  get beforeRenderEvent() {
3945
4783
  return new CustomEvent("turbo:before-stream-render", {
@@ -3952,8 +4790,7 @@ class StreamElement extends HTMLElement {
3952
4790
  });
3953
4791
  }
3954
4792
  get targetElementsById() {
3955
- var _a;
3956
- const element = (_a = this.ownerDocument) === null || _a === void 0 ? void 0 : _a.getElementById(this.target);
4793
+ const element = this.ownerDocument?.getElementById(this.target);
3957
4794
  if (element !== null) {
3958
4795
  return [ element ];
3959
4796
  } else {
@@ -3961,8 +4798,7 @@ class StreamElement extends HTMLElement {
3961
4798
  }
3962
4799
  }
3963
4800
  get targetElementsByQuery() {
3964
- var _a;
3965
- const elements = (_a = this.ownerDocument) === null || _a === void 0 ? void 0 : _a.querySelectorAll(this.targets);
4801
+ const elements = this.ownerDocument?.querySelectorAll(this.targets);
3966
4802
  if (elements.length !== 0) {
3967
4803
  return Array.prototype.slice.call(elements);
3968
4804
  } else {
@@ -3972,16 +4808,14 @@ class StreamElement extends HTMLElement {
3972
4808
  }
3973
4809
 
3974
4810
  class StreamSourceElement extends HTMLElement {
3975
- constructor() {
3976
- super(...arguments);
3977
- this.streamSource = null;
3978
- }
4811
+ streamSource=null;
3979
4812
  connectedCallback() {
3980
4813
  this.streamSource = this.src.match(/^ws{1,2}:/) ? new WebSocket(this.src) : new EventSource(this.src);
3981
4814
  connectStreamSource(this.streamSource);
3982
4815
  }
3983
4816
  disconnectedCallback() {
3984
4817
  if (this.streamSource) {
4818
+ this.streamSource.close();
3985
4819
  disconnectStreamSource(this.streamSource);
3986
4820
  }
3987
4821
  }
@@ -4026,16 +4860,21 @@ if (customElements.get("turbo-stream-source") === undefined) {
4026
4860
  }
4027
4861
  })();
4028
4862
 
4029
- window.Turbo = Turbo;
4863
+ window.Turbo = {
4864
+ ...Turbo,
4865
+ StreamActions: StreamActions
4866
+ };
4030
4867
 
4031
4868
  start();
4032
4869
 
4033
- var turbo_es2017Esm = Object.freeze({
4870
+ var Turbo$1 = Object.freeze({
4034
4871
  __proto__: null,
4872
+ FetchEnctype: FetchEnctype,
4873
+ FetchMethod: FetchMethod,
4874
+ FetchRequest: FetchRequest,
4875
+ FetchResponse: FetchResponse,
4035
4876
  FrameElement: FrameElement,
4036
- get FrameLoadingStyle() {
4037
- return FrameLoadingStyle;
4038
- },
4877
+ FrameLoadingStyle: FrameLoadingStyle,
4039
4878
  FrameRenderer: FrameRenderer,
4040
4879
  PageRenderer: PageRenderer,
4041
4880
  PageSnapshot: PageSnapshot,
@@ -4046,6 +4885,10 @@ var turbo_es2017Esm = Object.freeze({
4046
4885
  clearCache: clearCache,
4047
4886
  connectStreamSource: connectStreamSource,
4048
4887
  disconnectStreamSource: disconnectStreamSource,
4888
+ fetch: fetchWithTurboHeaders,
4889
+ fetchEnctypeFromString: fetchEnctypeFromString,
4890
+ fetchMethodFromString: fetchMethodFromString,
4891
+ isSafe: isSafe,
4049
4892
  navigator: navigator$1,
4050
4893
  registerAdapter: registerAdapter,
4051
4894
  renderStreamMessage: renderStreamMessage,
@@ -4060,14 +4903,14 @@ var turbo_es2017Esm = Object.freeze({
4060
4903
  let consumer;
4061
4904
 
4062
4905
  async function getConsumer() {
4063
- return consumer || setConsumer(createConsumer().then(setConsumer));
4906
+ return consumer || setConsumer(createConsumer$1().then(setConsumer));
4064
4907
  }
4065
4908
 
4066
4909
  function setConsumer(newConsumer) {
4067
4910
  return consumer = newConsumer;
4068
4911
  }
4069
4912
 
4070
- async function createConsumer() {
4913
+ async function createConsumer$1() {
4071
4914
  const {createConsumer: createConsumer} = await Promise.resolve().then((function() {
4072
4915
  return index;
4073
4916
  }));
@@ -4083,7 +4926,7 @@ var cable = Object.freeze({
4083
4926
  __proto__: null,
4084
4927
  getConsumer: getConsumer,
4085
4928
  setConsumer: setConsumer,
4086
- createConsumer: createConsumer,
4929
+ createConsumer: createConsumer$1,
4087
4930
  subscribeTo: subscribeTo
4088
4931
  });
4089
4932
 
@@ -4193,6 +5036,8 @@ function isBodyInit(body) {
4193
5036
  return body instanceof FormData || body instanceof URLSearchParams;
4194
5037
  }
4195
5038
 
5039
+ window.Turbo = Turbo$1;
5040
+
4196
5041
  addEventListener("turbo:before-fetch-request", encodeMethodIntoRequestBody);
4197
5042
 
4198
5043
  var adapters = {
@@ -4309,6 +5154,8 @@ ConnectionMonitor.staleThreshold = 6;
4309
5154
 
4310
5155
  ConnectionMonitor.reconnectionBackoffRate = .15;
4311
5156
 
5157
+ var ConnectionMonitor$1 = ConnectionMonitor;
5158
+
4312
5159
  var INTERNAL = {
4313
5160
  message_types: {
4314
5161
  welcome: "welcome",
@@ -4320,7 +5167,8 @@ var INTERNAL = {
4320
5167
  disconnect_reasons: {
4321
5168
  unauthorized: "unauthorized",
4322
5169
  invalid_request: "invalid_request",
4323
- server_restart: "server_restart"
5170
+ server_restart: "server_restart",
5171
+ remote: "remote"
4324
5172
  },
4325
5173
  default_mount_path: "/cable",
4326
5174
  protocols: [ "actioncable-v1-json", "actioncable-unsupported" ]
@@ -4337,7 +5185,7 @@ class Connection {
4337
5185
  this.open = this.open.bind(this);
4338
5186
  this.consumer = consumer;
4339
5187
  this.subscriptions = this.consumer.subscriptions;
4340
- this.monitor = new ConnectionMonitor(this);
5188
+ this.monitor = new ConnectionMonitor$1(this);
4341
5189
  this.disconnected = true;
4342
5190
  }
4343
5191
  send(data) {
@@ -4353,11 +5201,12 @@ class Connection {
4353
5201
  logger.log(`Attempted to open WebSocket, but existing socket is ${this.getState()}`);
4354
5202
  return false;
4355
5203
  } else {
4356
- logger.log(`Opening WebSocket, current state is ${this.getState()}, subprotocols: ${protocols}`);
5204
+ const socketProtocols = [ ...protocols, ...this.consumer.subprotocols || [] ];
5205
+ logger.log(`Opening WebSocket, current state is ${this.getState()}, subprotocols: ${socketProtocols}`);
4357
5206
  if (this.webSocket) {
4358
5207
  this.uninstallEventHandlers();
4359
5208
  }
4360
- this.webSocket = new adapters.WebSocket(this.consumer.url, protocols);
5209
+ this.webSocket = new adapters.WebSocket(this.consumer.url, socketProtocols);
4361
5210
  this.installEventHandlers();
4362
5211
  this.monitor.start();
4363
5212
  return true;
@@ -4369,7 +5218,7 @@ class Connection {
4369
5218
  if (!allowReconnect) {
4370
5219
  this.monitor.stop();
4371
5220
  }
4372
- if (this.isActive()) {
5221
+ if (this.isOpen()) {
4373
5222
  return this.webSocket.close();
4374
5223
  }
4375
5224
  }
@@ -4399,6 +5248,9 @@ class Connection {
4399
5248
  isActive() {
4400
5249
  return this.isState("open", "connecting");
4401
5250
  }
5251
+ triedToReconnect() {
5252
+ return this.monitor.reconnectAttempts > 0;
5253
+ }
4402
5254
  isProtocolSupported() {
4403
5255
  return indexOf.call(supportedProtocols, this.getProtocol()) >= 0;
4404
5256
  }
@@ -4438,6 +5290,9 @@ Connection.prototype.events = {
4438
5290
  const {identifier: identifier, message: message, reason: reason, reconnect: reconnect, type: type} = JSON.parse(event.data);
4439
5291
  switch (type) {
4440
5292
  case message_types.welcome:
5293
+ if (this.triedToReconnect()) {
5294
+ this.reconnectAttempted = true;
5295
+ }
4441
5296
  this.monitor.recordConnect();
4442
5297
  return this.subscriptions.reload();
4443
5298
 
@@ -4452,7 +5307,16 @@ Connection.prototype.events = {
4452
5307
 
4453
5308
  case message_types.confirmation:
4454
5309
  this.subscriptions.confirmSubscription(identifier);
4455
- return this.subscriptions.notify(identifier, "connected");
5310
+ if (this.reconnectAttempted) {
5311
+ this.reconnectAttempted = false;
5312
+ return this.subscriptions.notify(identifier, "connected", {
5313
+ reconnected: true
5314
+ });
5315
+ } else {
5316
+ return this.subscriptions.notify(identifier, "connected", {
5317
+ reconnected: false
5318
+ });
5319
+ }
4456
5320
 
4457
5321
  case message_types.rejection:
4458
5322
  return this.subscriptions.reject(identifier);
@@ -4487,6 +5351,8 @@ Connection.prototype.events = {
4487
5351
  }
4488
5352
  };
4489
5353
 
5354
+ var Connection$1 = Connection;
5355
+
4490
5356
  const extend = function(object, properties) {
4491
5357
  if (properties != null) {
4492
5358
  for (let key in properties) {
@@ -4556,10 +5422,12 @@ class SubscriptionGuarantor {
4556
5422
  }
4557
5423
  }
4558
5424
 
5425
+ var SubscriptionGuarantor$1 = SubscriptionGuarantor;
5426
+
4559
5427
  class Subscriptions {
4560
5428
  constructor(consumer) {
4561
5429
  this.consumer = consumer;
4562
- this.guarantor = new SubscriptionGuarantor(this);
5430
+ this.guarantor = new SubscriptionGuarantor$1(this);
4563
5431
  this.subscriptions = [];
4564
5432
  }
4565
5433
  create(channelName, mixin) {
@@ -4636,7 +5504,8 @@ class Consumer {
4636
5504
  constructor(url) {
4637
5505
  this._url = url;
4638
5506
  this.subscriptions = new Subscriptions(this);
4639
- this.connection = new Connection(this);
5507
+ this.connection = new Connection$1(this);
5508
+ this.subprotocols = [];
4640
5509
  }
4641
5510
  get url() {
4642
5511
  return createWebSocketURL(this._url);
@@ -4657,6 +5526,9 @@ class Consumer {
4657
5526
  return this.connection.open();
4658
5527
  }
4659
5528
  }
5529
+ addSubProtocol(subprotocol) {
5530
+ this.subprotocols = [ ...this.subprotocols, subprotocol ];
5531
+ }
4660
5532
  }
4661
5533
 
4662
5534
  function createWebSocketURL(url) {
@@ -4674,7 +5546,7 @@ function createWebSocketURL(url) {
4674
5546
  }
4675
5547
  }
4676
5548
 
4677
- function createConsumer$1(url = getConfig("url") || INTERNAL.default_mount_path) {
5549
+ function createConsumer(url = getConfig("url") || INTERNAL.default_mount_path) {
4678
5550
  return new Consumer(url);
4679
5551
  }
4680
5552
 
@@ -4687,18 +5559,18 @@ function getConfig(name) {
4687
5559
 
4688
5560
  var index = Object.freeze({
4689
5561
  __proto__: null,
4690
- Connection: Connection,
4691
- ConnectionMonitor: ConnectionMonitor,
5562
+ Connection: Connection$1,
5563
+ ConnectionMonitor: ConnectionMonitor$1,
4692
5564
  Consumer: Consumer,
4693
5565
  INTERNAL: INTERNAL,
4694
5566
  Subscription: Subscription,
4695
5567
  Subscriptions: Subscriptions,
4696
- SubscriptionGuarantor: SubscriptionGuarantor,
5568
+ SubscriptionGuarantor: SubscriptionGuarantor$1,
4697
5569
  adapters: adapters,
4698
5570
  createWebSocketURL: createWebSocketURL,
4699
5571
  logger: logger,
4700
- createConsumer: createConsumer$1,
5572
+ createConsumer: createConsumer,
4701
5573
  getConfig: getConfig
4702
5574
  });
4703
5575
 
4704
- export { turbo_es2017Esm as Turbo, cable };
5576
+ export { Turbo$1 as Turbo, cable };