Skip to content

Instantly share code, notes, and snippets.

@Kukunin
Forked from Intrepidd/turbo_frame_history_controller.ts
Last active September 16, 2021 13:30
Show Gist options
  • Save Kukunin/5033345db6da9d2edc002dc3f39702ac to your computer and use it in GitHub Desktop.
Save Kukunin/5033345db6da9d2edc002dc3f39702ac to your computer and use it in GitHub Desktop.
import { Controller } from 'stimulus'
import { useMutation } from 'stimulus-use'
export default class extends Controller {
connect () {
useMutation(this, { attributes: true })
this.popStateListener = this.popStateListener.bind(this)
window.addEventListener("popstate", this.popStateListener)
// Make Turbo ignore popstate events for the initial state
history.replaceState(this.historyState(), "", window.location.href)
}
disconnect() {
window.removeEventListener("popstate", this.popStateListener)
}
mutate (entries) {
entries.forEach((mutation) => {
if (mutation.type === 'attributes' && mutation.attributeName === 'src') {
const src = this.element.getAttribute('src')
if (src != null && src !== window.location.href) {
history.pushState(this.historyState(), "", src)
}
}
})
}
popStateListener(event) {
if (event.state.turbo_frame_history && event.state.turbo_frame === this.element.id) {
this.element.src = window.location.href
}
}
historyState() {
return {
turbo_frame_history: true,
turbo_frame: this.element.id,
}
}
}
@Kukunin
Copy link
Author

Kukunin commented Sep 16, 2021

@baarkerlounger, how do you change frames content without having a src? What use-case do you have?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment