Skip to content

Commit

Permalink
Fix turbo redirect
Browse files Browse the repository at this point in the history
The previous fix doesn't quite work as turbo just ends up doing a
browser native visit and breaks on form action due to 200 status.
  • Loading branch information
nanaya committed Nov 25, 2024
1 parent 047195b commit 0827c35
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
10 changes: 9 additions & 1 deletion app/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -942,7 +942,15 @@ function page_title()
function ujs_redirect($url, $status = 200)
{
$request = Request::instance();
if ($request->headers->get('x-turbo-request-id') !== null || ($request->ajax() && !$request->isMethod('get'))) {
if ($request->headers->get('x-turbo-request-id') !== null) {
if ($status === 200 && $request->getMethod() !== 'GET') {
// Turbo doesn't like 200 response on non-GET requests.
// Reference: https://github.com/hotwired/turbo/issues/22
$status = 201;
}

return response($url, $status, ['content-type' => 'text/osu-turbo-redirect']);
} elseif ($request->ajax() && $request->getMethod() !== 'GET') {
return ext_view('layout.ujs-redirect', compact('url'), 'js', $status);
} else {
// because non-3xx redirects make no sense.
Expand Down
18 changes: 18 additions & 0 deletions resources/js/setup-turbo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,24 @@ document.addEventListener('turbo:submit-end', (e) => {
}
});

document.addEventListener('turbo:before-fetch-response', (e) => {
if (!e.detail.fetchResponse.contentType.match(/^text\/osu-turbo-redirect[ ;]*/)) {
return;
}

e.preventDefault();
e.detail.fetchResponse.responseText.then((url) => {
const [currentUrlBase, urlBase] = [document.location.href, url].map((u) => u.replace(/#.*/, ''));

if (currentUrlBase === urlBase) {
// a normal/advance visit to same url won't reload the page
Turbo.visit(url, { action: 'replace' });
} else {
Turbo.visit(url);
}
});
});

// disable turbo navigation for old webs
document.addEventListener('turbo:click', (event) => {
const url = new URL(event.detail.url);
Expand Down

0 comments on commit 0827c35

Please sign in to comment.