TurboHandler
TurboHandler wires the Turbo Drive / Frame / Stream lifecycle to a single pair of onMount / onUnmount
callbacks, so your per-container listeners (tooltips, selects, date pickers…) initialize and clean up correctly across
every Turbo navigation, including Stream and Mercure mutations, which fire no render event of their own.
import { TurboHandler } from '@silarhi/turbo'
const handler = new TurboHandler({ onMount: (container) => app.mount(container), onUnmount: (container) => app.unmount(container),})
handler.start() // attach listeners (idempotent)// handler.stop() // detach them all and resetonMount runs on every freshly rendered or inserted container; onUnmount runs before one leaves the DOM. Point them
at whatever initializes and tears down your widgets: TurboHandler decides when and on which element, you decide
what.
Writing the callbacks
Section titled “Writing the callbacks”- The callbacks are typed
(container: Element) => void: the handler always passes an element. A function typed(container: Element | Document) => void, such as an existingmount(root = document), fits too. - The container can be the
<body>, a<turbo-frame>, or a single node a Stream inserted. Look for your widgets inside the container and on the container itself: a Stream that appends<select data-choices>passes the<select>. morphMutationscalls them on individual elements, and may callonUnmountthenonMounton the same element: make them safe to call on any element, and idempotent.
Cleanup and signal
Section titled “Cleanup and signal”onMount can return a function that tears down what it mounted, and gets a signal as its second argument. Both
end when the handler unmounts that container, before it calls onUnmount, which becomes optional:
new TurboHandler({ onMount: (container, { signal }) => { const selects = [...container.querySelectorAll('select[data-tom-select]')].map( (select) => new TomSelect(select) ) container.addEventListener('click', onClick, { signal }) fetch('/notifications', { signal }).then(render)
return () => selects.forEach((select) => select.destroy()) },}).start()- The signal is aborted, and the cleanup called, when the handler unmounts the container itself or an element around
it. Each
onMountcall gets its own. - With
morphMutations, the handler unmounts and mounts single elements inside a mounted container: the cleanup of the container still runs only when the container goes. Tear the widgets of an element down inonUnmountthere. - A permanent element that
onMountmounted with its container is torn down by the cleanup of that container too: the handler mounts it again right after, on its own, with its own cleanup. Its widgets start over that once (a Tom Select goes back to the value it had on its first mount). Tear them down inonUnmountto keep their state. - A container that leaves the page without an unmount (removed by your own code) has its scope ended on the next
turbo:load.
When the callbacks run
Section titled “When the callbacks run”| What Turbo does | Call |
|---|---|
First turbo:load |
onMount(container) |
turbo:before-cache |
onUnmount(container): the page Turbo caches holds the server markup, not what your listeners added |
A Drive render: a visit, Back, a failed form submission (a 422), an error page |
onUnmount(container) right before Turbo swaps the body, onMount(container) on the new one right after |
| A preview of the cache | nothing: the preview stays unmounted, the render of the response mounts the page |
| A frame render | onUnmount(frame) right before Turbo swaps its content, onMount(frame) right after |
turbo:load after the first (a frame navigation with data-turbo-action="advance" renders no body, and fires one) |
nothing: the render mounted the page already |
turbo:before-stream-render |
onUnmount / onMount on each removed / inserted node: Stream mutations |
turbo:before-morph-element (opt-in) |
onUnmount(element) changed or removed, onMount once the morph is done: Morph mutations |
container is the element returned by getContainer, document.body by default.
The handler replaces the render function of turbo:before-render and turbo:before-frame-render: the callbacks run
at the swap itself, before turbo:render, turbo:frame-render and turbo:frame-load, and before Turbo runs the
scripts of a new frame. It keeps the elements it mounted, so each widget is mounted once whatever the order Turbo’s
events come in: a frame or a stream that renders before the first turbo:load (an eager frame, a <turbo-stream> in
the page itself) is unmounted before the body is mounted, and a turbo:load never mounts a page a render mounted.
Permanent elements
Section titled “Permanent elements”Turbo moves an element with data-turbo-permanent (and an id) to the new content when that content has one with the
same id: on a Drive visit, Back and a preview from the cache, a frame navigation, a morph refresh and a stream. The
widgets inside stay mounted, with their state (a picked value, an open dropdown, a playing video):
- the handler moves the elements Turbo keeps out of the container while it calls
onUnmountandonMounton it, and back right after. It usesmoveBefore()where the browser has it, which keeps an iframe loaded and a video playing; elsewhere, the element is detached for that call, as Turbo itself does when it moves it to the new page, - the copy of the page Turbo caches gets the markup each permanent element had before its first mount: a page restored from the cache without the element mounts it once,
- a stream that keeps one inserts a copy of it, and takes the element itself out of the page: the handler puts the element back in place of the copy.
A permanent element the new content doesn’t have is unmounted with its container.
The handler also listens to:
turbo:before-fetch-request, to add theTurbo-Frame-Follow-Redirectheader to the requests of frames carryingdata-turbo-follow-redirect(Keeping a redirect in its frame),turbo:before-fetch-response, to follow aTurbo-Locationheader (Frame redirects),turbo:frame-missing, whenvisitOnFrameMissingis on,turbo:frame-render, whenframeStreamsis on.
The snapshot cache
Section titled “The snapshot cache”Turbo caches a copy of the page it leaves, to show it again on Back or as the preview of a visit. The handler unmounts
the container on turbo:before-cache, so that copy holds the markup of the server: a widget that changes the DOM (a
Tom Select inserting its own markup next to its <select>) is mounted once when the page comes back.
A frame navigation promoted to a page visit (data-turbo-action="advance" on a link, or on a search form that targets
a results frame) is the exception. Turbo caches a copy of the page taken while it stays on screen, which no
turbo:before-cache listener can clean: Turbo 8 takes it when the navigation starts. The handler keeps these visits
out of the cache instead (Turbo’s shouldCacheSnapshot: false, as for a Turbo 8 page refresh): Back loads that page
from the server. It wraps Turbo.session.visit for that, on start(), or on the first request when Turbo loads after
the handler.
Starting and stopping
Section titled “Starting and stopping”start()attaches every listener todocument. Calling it again is a no-op.stop()detaches them all, putsTurbo.session.visitback (The snapshot cache), and resets the handler to its pre-boot state: after a newstart(), the nextturbo:loadcounts as the first one and mounts the container. Calling it on a stopped handler is a no-op.
The render container
Section titled “The render container”getContainer returns the element a full Drive render mounts on and unmounts from, and the root
Stream mutations are observed under. It receives the document:
new TurboHandler({ onMount: (container) => app.mount(container), onUnmount: (container) => app.unmount(container), getContainer: (document) => document.getElementById('app') ?? document.body,})Following redirects
Section titled “Following redirects”When a response carries a Turbo-Location header, the handler cancels Turbo’s handling of the response and calls
onRedirect with its value. The default visits it with window.Turbo.visit(url), the global @hotwired/turbo sets
when imported. Without that global, it falls back to a full page load (window.location.assign(url)) and logs a
warning, so the redirect is never lost. Pass your own function to log the redirect, or to visit with options:
import * as Turbo from '@hotwired/turbo'
new TurboHandler({ onMount: (container) => app.mount(container), onUnmount: (container) => app.unmount(container), onRedirect: (url) => Turbo.visit(url, { action: 'replace' }),})The header comes from the PHP TurboFrameListener, or from any backend that sends it.
Options
Section titled “Options”Every option is described in the options reference. Three of them change how renders are handled:
streamMutations, on by default: per-node lifecycle for Turbo Streams.morphMutations, off by default: per-element refresh for Drive, frame and stream morphs.visitOnFrameMissing, off by default: render a frame response without a matching frame as a full page.frameStreams, off by default: run the streams a frame response carries outside its frames.
