Further simplify formResult, setupEvents

This commit is contained in:
Liam 2024-06-23 14:56:31 -04:00
parent e30a1922ed
commit e5b476f07f

View file

@ -3,32 +3,34 @@
*/ */
import store from './utils/store'; import store from './utils/store';
import { $, $$ } from './utils/dom'; import { $, $$, hideEl, showEl } from './utils/dom';
import { assertNotNull } from './utils/assert'; import { assertNotNull, assertType } from './utils/assert';
import '../types/ujs'; import '../types/ujs';
let touchMoved = false; let touchMoved = false;
function formResult({target, detail}: FetchcompleteEvent) { function formResult({target, detail}: FetchcompleteEvent) {
const elements: {[key: string]: string} = { const elements: Record<string, string> = {
'#description-form': '.image-description', '#description-form': '.image-description',
'#uploader-form': '.image_uploader' '#uploader-form': '.image_uploader'
}; };
function showResult(resultEl: HTMLElement, formEl: HTMLFormElement, response: string) { function showResult(formEl: HTMLFormElement, resultEl: HTMLElement, response: string) {
resultEl.innerHTML = response; resultEl.innerHTML = response;
resultEl.classList.remove('hidden'); hideEl(formEl);
formEl.classList.add('hidden'); showEl(resultEl);
const inputEl = $<HTMLInputElement>('input[type="submit"]', formEl);
const buttonEl = $<HTMLButtonElement>('button', formEl);
if (inputEl) inputEl.disabled = false; $$<HTMLInputElement | HTMLButtonElement>('input[type="submit"],button', formEl).forEach(button => {
if (buttonEl) buttonEl.disabled = false; button.disabled = false;
});
} }
for (const element in elements) { for (const [ formSelector, resultSelector ] of Object.entries(elements)) {
if (target.matches(element)) { if (target.matches(formSelector)) {
detail.text().then(text => showResult(assertNotNull($<HTMLElement>(elements[element])), target as HTMLFormElement, text)); const form = assertType(target, HTMLFormElement);
const result = assertNotNull($<HTMLElement>(resultSelector));
detail.text().then(text => showResult(form, result, text));
} }
} }
} }
@ -79,11 +81,11 @@ export function setupEvents() {
const extrameta = $<HTMLElement>('#extrameta'); const extrameta = $<HTMLElement>('#extrameta');
if (extrameta && store.get('hide_uploader')) { if (extrameta && store.get('hide_uploader')) {
extrameta.classList.add('hidden'); hideEl(extrameta);
} }
if (store.get('hide_score')) { if (store.get('hide_score')) {
$$<HTMLElement>('.upvotes,.score,.downvotes').forEach(s => s.classList.add('hidden')); $$<HTMLElement>('.upvotes,.score,.downvotes').forEach(s => hideEl(s));
} }
document.addEventListener('fetchcomplete', formResult); document.addEventListener('fetchcomplete', formResult);