feat(turbo): prevent scroll on form submits
This commit is contained in:
parent
a9d4ff85e6
commit
a0878ffde5
1 changed files with 29 additions and 10 deletions
|
@ -1,4 +1,5 @@
|
|||
import { show, hide } from '@utils';
|
||||
import { session as TurboSession } from '@hotwired/turbo';
|
||||
|
||||
import { ApplicationController } from './application_controller';
|
||||
|
||||
|
@ -8,16 +9,34 @@ export class TurboController extends ApplicationController {
|
|||
declare readonly spinnerTarget: HTMLElement;
|
||||
declare readonly hasSpinnerTarget: boolean;
|
||||
|
||||
#submitting = true;
|
||||
|
||||
connect() {
|
||||
this.onGlobal('turbo:submit-start', () => {
|
||||
if (this.hasSpinnerTarget) {
|
||||
show(this.spinnerTarget);
|
||||
}
|
||||
});
|
||||
this.onGlobal('turbo:submit-end', () => {
|
||||
if (this.hasSpinnerTarget) {
|
||||
hide(this.spinnerTarget);
|
||||
}
|
||||
});
|
||||
this.onGlobal('turbo:submit-start', () => this.startSpinner());
|
||||
this.onGlobal('turbo:submit-end', () => this.stopSpinner());
|
||||
this.onGlobal('turbo:fetch-request-error', () => this.stopSpinner());
|
||||
|
||||
// prevent scroll on turbo form submits
|
||||
this.onGlobal('turbo:render', () => this.preventScrollIfNeeded());
|
||||
}
|
||||
|
||||
startSpinner() {
|
||||
this.#submitting = true;
|
||||
if (this.hasSpinnerTarget) {
|
||||
show(this.spinnerTarget);
|
||||
}
|
||||
}
|
||||
|
||||
stopSpinner() {
|
||||
this.#submitting = false;
|
||||
if (this.hasSpinnerTarget) {
|
||||
hide(this.spinnerTarget);
|
||||
}
|
||||
}
|
||||
|
||||
preventScrollIfNeeded() {
|
||||
if (this.#submitting && TurboSession.navigator.currentVisit) {
|
||||
TurboSession.navigator.currentVisit.scrolled = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue