Skip to content

Commit

Permalink
Verify with the browser adapter before initiating link prefetching, s…
Browse files Browse the repository at this point in the history
…o the Hotwire Native libraries can have control of the link prefetching behavior.
  • Loading branch information
jayohms committed Dec 17, 2024
1 parent 1007de9 commit 76d9740
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 1 deletion.
11 changes: 11 additions & 0 deletions src/core/drive/navigator.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,17 @@ export class Navigator {
}
}

// Link prefetching

linkPrefetchingIsEnabledForLocation(location) {
// Not all adapters implement linkPrefetchingIsEnabledForLocation
if (typeof this.adapter.linkPrefetchingIsEnabledForLocation === "function") {
return this.adapter.linkPrefetchingIsEnabledForLocation(location)
}

return true
}

// Visit delegate

visitStarted(visit) {
Expand Down
6 changes: 6 additions & 0 deletions src/core/native/browser_adapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,12 @@ export class BrowserAdapter {

visitRendered(_visit) {}

// Link prefetching

linkPrefetchingIsEnabledForLocation(location) {
return true
}

// Form Submission Delegate

formSubmissionStarted(_formSubmission) {
Expand Down
3 changes: 2 additions & 1 deletion src/core/session.js
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,8 @@ export class Session {
canPrefetchRequestToLocation(link, location) {
return (
this.elementIsNavigatable(link) &&
locationIsVisitable(location, this.snapshot.rootLocation)
locationIsVisitable(location, this.snapshot.rootLocation) &&
this.navigator.linkPrefetchingIsEnabledForLocation(location)
)
}

Expand Down
15 changes: 15 additions & 0 deletions src/tests/unit/native_adapter_support_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ class NativeAdapterSupportTest {
finishedVisitRequests = []
startedFormSubmissions = []
finishedFormSubmissions = []
linkPrefetchRequests = []

// Adapter interface

Expand Down Expand Up @@ -53,6 +54,10 @@ class NativeAdapterSupportTest {
}

pageInvalidated() {}

linkPrefetchingIsEnabledForLocation(location) {
this.linkPrefetchRequests.push(location)
}
}

let adapter
Expand Down Expand Up @@ -204,3 +209,13 @@ test("visit follows redirect and proposes replace visit to adapter", async () =>
assert.equal(visit.location, redirectedLocation)
assert.equal(visit.options.action, "replace")
})

test ("link prefetch requests verify with adapter", async () => {
const locatable = window.location.toString()

Turbo.navigator.linkPrefetchingIsEnabledForLocation(locatable)
assert.equal(adapter.linkPrefetchRequests.length, 1)

const [location] = adapter.linkPrefetchRequests
assert.equal(location, locatable)
})

0 comments on commit 76d9740

Please sign in to comment.