Skip to content

Commit

Permalink
Merge pull request #204 from hotwired/esm-compatibility
Browse files Browse the repository at this point in the history
Update the javascript adapter to support loading Turbo through ESM
  • Loading branch information
jayohms authored Dec 7, 2021
2 parents 03de250 + 89bb120 commit 6522c8b
Showing 1 changed file with 29 additions and 7 deletions.
36 changes: 29 additions & 7 deletions turbo/src/main/assets/js/turbo_bridge.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
(() => {
const TURBO_LOAD_TIMEOUT = 4000

// Bridge between Turbo JS and native code. Built for Turbo 7
// with backwards compatibility for Turbolinks 5
class TurboNative {
constructor() {
this.registerAdapter()
}

registerAdapter() {
if (window.Turbo) {
Turbo.registerAdapter(this)
Expand All @@ -14,8 +12,7 @@
Turbolinks.controller.adapter = this
TurboSession.turboIsReady(true)
} else {
TurboSession.turboIsReady(false)
this.pageLoadFailed()
throw new Error("Failed to register the TurboNative adapter")
}
}

Expand Down Expand Up @@ -170,5 +167,30 @@
}

window.turboNative = new TurboNative()
window.turboNative.pageLoaded()

const setup = function() {
window.turboNative.registerAdapter()
window.turboNative.pageLoaded()

document.removeEventListener("turbo:load", setup)
document.removeEventListener("turbolinks:load", setup)
}

const setupOnLoad = () => {
document.addEventListener("turbo:load", setup)
document.addEventListener("turbolinks:load", setup)

setTimeout(() => {
if (!window.Turbo && !window.Turbolinks) {
TurboSession.turboIsReady(false)
window.turboNative.pageLoadFailed()
}
}, TURBO_LOAD_TIMEOUT)
}

if (window.Turbo || window.Turbolinks) {
setup()
} else {
setupOnLoad()
}
})()

0 comments on commit 6522c8b

Please sign in to comment.