refactor(ujs): adapt safari-11-empty-file-workaround to turbo

This commit is contained in:
Paul Chavard 2022-07-19 12:22:43 +02:00 committed by simon lehericey
parent 5de74ae322
commit 099eecaa6c
3 changed files with 37 additions and 27 deletions

View file

@ -5,7 +5,7 @@ import { Application } from '@hotwired/stimulus';
import '@gouvfr/dsfr/dist/dsfr.module.js'; import '@gouvfr/dsfr/dist/dsfr.module.js';
import '../shared/activestorage/ujs'; import '../shared/activestorage/ujs';
import '../shared/safari-11-file-xhr-workaround'; import '../shared/safari-11-empty-file-workaround';
import '../shared/toggle-target'; import '../shared/toggle-target';
import { registerControllers } from '../shared/stimulus-loader'; import { registerControllers } from '../shared/stimulus-loader';

View file

@ -0,0 +1,36 @@
// iOS 11.3 Safari / macOS Safari 11.1 empty <input type="file"> XHR bug workaround.
// This should work with every modern browser which supports ES5 (including IE9).
// https://stackoverflow.com/questions/49614091/safari-11-1-ajax-xhr-form-submission-fails-when-inputtype-file-is-empty
// https://github.com/rails/rails/issues/32440
document.documentElement.addEventListener(
'turbo:before-fetch-request',
(event) => {
const target = event.target as Element;
const inputs = target.querySelectorAll<HTMLInputElement>(
'input[type="file"]:not([disabled])'
);
for (const input of inputs) {
if (input.files?.length == 0) {
input.setAttribute('data-safari-temp-disabled', 'true');
input.setAttribute('disabled', '');
}
}
}
);
document.documentElement.addEventListener(
'turbo:before-fetch-response',
(event) => {
const target = event.target as Element;
const inputs = target.querySelectorAll(
'input[type="file"][data-safari-temp-disabled]'
);
for (const input of inputs) {
input.removeAttribute('data-safari-temp-disabled');
input.removeAttribute('disabled');
}
}
);
export {};

View file

@ -1,26 +0,0 @@
// iOS 11.3 Safari / macOS Safari 11.1 empty <input type="file"> XHR bug workaround.
// This should work with every modern browser which supports ES5 (including IE9).
// https://stackoverflow.com/questions/49614091/safari-11-1-ajax-xhr-form-submission-fails-when-inputtype-file-is-empty
// https://github.com/rails/rails/issues/32440
document.addEventListener('ajax:before', function (e) {
let inputs = e.target.querySelectorAll('input[type="file"]:not([disabled])');
inputs.forEach(function (input) {
if (input.files.length > 0) {
return;
}
input.setAttribute('data-safari-temp-disabled', 'true');
input.setAttribute('disabled', '');
});
});
// You should call this by yourself when you aborted an ajax request by stopping a event in ajax:before hook.
document.addEventListener('ajax:beforeSend', function (e) {
let inputs = e.target.querySelectorAll(
'input[type="file"][data-safari-temp-disabled]'
);
inputs.forEach(function (input) {
input.removeAttribute('data-safari-temp-disabled');
input.removeAttribute('disabled');
});
});