arrowParens: avoid

This commit is contained in:
Luna D. 2024-07-03 23:03:46 +02:00
parent 33ede2722b
commit fbd18fd1fd
No known key found for this signature in database
GPG key ID: 4B1C63448394F688
45 changed files with 154 additions and 154 deletions

View file

@ -7,7 +7,7 @@ bracketSpacing: true
endOfLine: lf endOfLine: lf
quoteProps: as-needed quoteProps: as-needed
trailingComma: all trailingComma: all
arrowParens: always arrowParens: avoid
overrides: overrides:
- files: "*.css" - files: "*.css"
options: options:

View file

@ -70,10 +70,10 @@ describe('Remote utilities', () => {
}); });
it('should emit fetchcomplete event', () => it('should emit fetchcomplete event', () =>
new Promise<void>((resolve) => { new Promise<void>(resolve => {
let a: HTMLAnchorElement | null = null; let a: HTMLAnchorElement | null = null;
addOneShotEventListener('fetchcomplete', (event) => { addOneShotEventListener('fetchcomplete', event => {
expect(event.target).toBe(a); expect(event.target).toBe(a);
resolve(); resolve();
}); });
@ -95,8 +95,8 @@ describe('Remote utilities', () => {
}; };
it('should submit a form with the given action', () => it('should submit a form with the given action', () =>
new Promise<void>((resolve) => { new Promise<void>(resolve => {
addOneShotEventListener('submit', (event) => { addOneShotEventListener('submit', event => {
event.preventDefault(); event.preventDefault();
const target = assertType(event.target, HTMLFormElement); const target = assertType(event.target, HTMLFormElement);
@ -192,10 +192,10 @@ describe('Remote utilities', () => {
}); });
it('should emit fetchcomplete event', () => it('should emit fetchcomplete event', () =>
new Promise<void>((resolve) => { new Promise<void>(resolve => {
let form: HTMLFormElement | null = null; let form: HTMLFormElement | null = null;
addOneShotEventListener('fetchcomplete', (event) => { addOneShotEventListener('fetchcomplete', event => {
expect(event.target).toBe(form); expect(event.target).toBe(form);
resolve(); resolve();
}); });
@ -214,7 +214,7 @@ describe('Remote utilities', () => {
describe('Form utilities', () => { describe('Form utilities', () => {
beforeEach(() => { beforeEach(() => {
vi.spyOn(window, 'requestAnimationFrame').mockImplementation((cb) => { vi.spyOn(window, 'requestAnimationFrame').mockImplementation(cb => {
cb(1); cb(1);
return 1; return 1;
}); });
@ -260,7 +260,7 @@ describe('Form utilities', () => {
// jsdom has no implementation for HTMLFormElement.prototype.submit // jsdom has no implementation for HTMLFormElement.prototype.submit
// and will return an error if the event's default isn't prevented // and will return an error if the event's default isn't prevented
form.addEventListener('submit', (event) => event.preventDefault()); form.addEventListener('submit', event => event.preventDefault());
const button = document.createElement('button'); const button = document.createElement('button');
button.type = 'submit'; button.type = 'submit';

View file

@ -137,8 +137,8 @@ describe('Image upload form', () => {
const failedUnloadEvent = new Event('beforeunload', { cancelable: true }); const failedUnloadEvent = new Event('beforeunload', { cancelable: true });
expect(fireEvent(window, failedUnloadEvent)).toBe(false); expect(fireEvent(window, failedUnloadEvent)).toBe(false);
await new Promise<void>((resolve) => { await new Promise<void>(resolve => {
form.addEventListener('submit', (event) => { form.addEventListener('submit', event => {
event.preventDefault(); event.preventDefault();
resolve(); resolve();
}); });
@ -153,7 +153,7 @@ describe('Image upload form', () => {
fetchMock.mockResolvedValue(new Response(JSON.stringify(scrapeResponse), { status: 200 })); fetchMock.mockResolvedValue(new Response(JSON.stringify(scrapeResponse), { status: 200 }));
fireEvent.input(remoteUrl, { target: { value: 'http://localhost/images/1' } }); fireEvent.input(remoteUrl, { target: { value: 'http://localhost/images/1' } });
await new Promise<void>((resolve) => { await new Promise<void>(resolve => {
tagsEl.addEventListener('addtag', (event: Event) => { tagsEl.addEventListener('addtag', (event: Event) => {
expect((event as CustomEvent).detail).toEqual({ name: 'artist:test' }); expect((event as CustomEvent).detail).toEqual({ name: 'artist:test' });
resolve(); resolve();

View file

@ -139,7 +139,7 @@ function createList(suggestions) {
list = document.createElement('ul'); list = document.createElement('ul');
list.className = 'autocomplete__list'; list.className = 'autocomplete__list';
suggestions.forEach((suggestion) => createItem(list, suggestion)); suggestions.forEach(suggestion => createItem(list, suggestion));
parent.appendChild(list); parent.appendChild(list);
} }
@ -176,7 +176,7 @@ function showAutocomplete(suggestions, fetchedTerm, targetInput) {
function getSuggestions(term) { function getSuggestions(term) {
// In case source URL was not given at all, do not try sending the request. // In case source URL was not given at all, do not try sending the request.
if (!inputField.dataset.acSource) return []; if (!inputField.dataset.acSource) return [];
return fetch(`${inputField.dataset.acSource}${term}`).then((response) => response.json()); return fetch(`${inputField.dataset.acSource}${term}`).then(response => response.json());
} }
function getSelectedTerm() { function getSelectedTerm() {
@ -212,7 +212,7 @@ function listenAutocomplete() {
document.addEventListener('focusin', fetchLocalAutocomplete); document.addEventListener('focusin', fetchLocalAutocomplete);
document.addEventListener('input', (event) => { document.addEventListener('input', event => {
removeParent(); removeParent();
fetchLocalAutocomplete(event); fetchLocalAutocomplete(event);
window.clearTimeout(timeout); window.clearTimeout(timeout);
@ -258,7 +258,7 @@ function listenAutocomplete() {
showAutocomplete(cache[fetchedTerm], fetchedTerm, event.target); showAutocomplete(cache[fetchedTerm], fetchedTerm, event.target);
} else { } else {
// inputField could get overwritten while the suggestions are being fetched - use event.target // inputField could get overwritten while the suggestions are being fetched - use event.target
getSuggestions(fetchedTerm).then((suggestions) => { getSuggestions(fetchedTerm).then(suggestions => {
if (fetchedTerm === event.target.value) { if (fetchedTerm === event.target.value) {
showAutocomplete(suggestions, fetchedTerm, event.target); showAutocomplete(suggestions, fetchedTerm, event.target);
} }
@ -269,7 +269,7 @@ function listenAutocomplete() {
}); });
// If there's a click outside the inputField, remove autocomplete // If there's a click outside the inputField, remove autocomplete
document.addEventListener('click', (event) => { document.addEventListener('click', event => {
if (event.target && event.target !== inputField) removeParent(); if (event.target && event.target !== inputField) removeParent();
if (event.target === inputField && isSearchField() && isSelectionOutsideCurrentTerm()) removeParent(); if (event.target === inputField && isSearchField() && isSelectionOutsideCurrentTerm()) removeParent();
}); });
@ -283,8 +283,8 @@ function listenAutocomplete() {
fetch(`/autocomplete/compiled?vsn=2&key=${cacheKey}`, { credentials: 'omit', cache: 'force-cache' }) fetch(`/autocomplete/compiled?vsn=2&key=${cacheKey}`, { credentials: 'omit', cache: 'force-cache' })
.then(handleError) .then(handleError)
.then((resp) => resp.arrayBuffer()) .then(resp => resp.arrayBuffer())
.then((buf) => { .then(buf => {
localAc = new LocalAutocompleter(buf); localAc = new LocalAutocompleter(buf);
}); });
} }

View file

@ -27,7 +27,7 @@ function isStale(tag) {
} }
function clearTags() { function clearTags() {
Object.keys(localStorage).forEach((key) => { Object.keys(localStorage).forEach(key => {
if (key.substring(0, 9) === 'bor_tags_') { if (key.substring(0, 9) === 'bor_tags_') {
store.remove(key); store.remove(key);
} }
@ -84,8 +84,8 @@ function fetchAndPersistTags(tagIds) {
const remaining = tagIds.slice(41); const remaining = tagIds.slice(41);
fetch(`/fetch/tags?ids[]=${ids.join('&ids[]=')}`) fetch(`/fetch/tags?ids[]=${ids.join('&ids[]=')}`)
.then((response) => response.json()) .then(response => response.json())
.then((data) => data.tags.forEach((tag) => persistTag(tag))) .then(data => data.tags.forEach(tag => persistTag(tag)))
.then(() => fetchAndPersistTags(remaining)); .then(() => fetchAndPersistTags(remaining));
} }
@ -96,7 +96,7 @@ function fetchAndPersistTags(tagIds) {
function fetchNewOrStaleTags(tagIds) { function fetchNewOrStaleTags(tagIds) {
const fetchIds = []; const fetchIds = [];
tagIds.forEach((t) => { tagIds.forEach(t => {
const stored = store.get(`bor_tags_${t}`); const stored = store.get(`bor_tags_${t}`);
if (!stored || isStale(stored)) { if (!stored || isStale(stored)) {
fetchIds.push(t); fetchIds.push(t);

View file

@ -26,27 +26,27 @@ const types = {
const actions = { const actions = {
hide(data) { hide(data) {
selectorCb(data.base, data.value, (el) => el.classList.add('hidden')); selectorCb(data.base, data.value, el => el.classList.add('hidden'));
}, },
tabHide(data) { tabHide(data) {
selectorCbChildren(data.base, data.value, (el) => el.classList.add('hidden')); selectorCbChildren(data.base, data.value, el => el.classList.add('hidden'));
}, },
show(data) { show(data) {
selectorCb(data.base, data.value, (el) => el.classList.remove('hidden')); selectorCb(data.base, data.value, el => el.classList.remove('hidden'));
}, },
toggle(data) { toggle(data) {
selectorCb(data.base, data.value, (el) => el.classList.toggle('hidden')); selectorCb(data.base, data.value, el => el.classList.toggle('hidden'));
}, },
submit(data) { submit(data) {
selectorCb(data.base, data.value, (el) => el.submit()); selectorCb(data.base, data.value, el => el.submit());
}, },
disable(data) { disable(data) {
selectorCb(data.base, data.value, (el) => { selectorCb(data.base, data.value, el => {
el.disabled = true; el.disabled = true;
}); });
}, },
@ -65,7 +65,7 @@ const actions = {
}, },
checkall(data) { checkall(data) {
$$(`${data.value} input[type=checkbox]`).forEach((c) => { $$(`${data.value} input[type=checkbox]`).forEach(c => {
c.checked = !c.checked; c.checked = !c.checked;
}); });
}, },
@ -102,8 +102,8 @@ const actions = {
if (loadTab && !newTab.dataset.loaded) { if (loadTab && !newTab.dataset.loaded) {
fetchHtml(loadTab) fetchHtml(loadTab)
.then(handleError) .then(handleError)
.then((response) => response.text()) .then(response => response.text())
.then((response) => { .then(response => {
newTab.innerHTML = response; newTab.innerHTML = response;
}) })
.then(() => { .then(() => {

View file

@ -40,7 +40,7 @@ function copyUserLinksTo(burger: HTMLElement) {
} }
}; };
$$<HTMLElement>('.js-burger-links').forEach((container) => copy(container.children)); $$<HTMLElement>('.js-burger-links').forEach(container => copy(container.children));
} }
export function setupBurgerMenu() { export function setupBurgerMenu() {
@ -53,7 +53,7 @@ export function setupBurgerMenu() {
copyUserLinksTo(burger); copyUserLinksTo(burger);
toggle.addEventListener('click', (event) => { toggle.addEventListener('click', event => {
event.stopPropagation(); event.stopPropagation();
event.preventDefault(); event.preventDefault();

View file

@ -27,7 +27,7 @@ function commentPosted(response) {
commentEditForm.reset(); commentEditForm.reset();
if (requestOk) { if (requestOk) {
response.text().then((text) => { response.text().then(text => {
if (text.includes('<div class="flash flash--warning">')) { if (text.includes('<div class="flash flash--warning">')) {
window.location.reload(); window.location.reload();
} else { } else {
@ -60,7 +60,7 @@ function loadParentPost(event) {
fetchHtml(`/images/${imageId}/comments/${commentId}`) fetchHtml(`/images/${imageId}/comments/${commentId}`)
.then(handleError) .then(handleError)
.then((data) => { .then(data => {
clearParentPost(clickedLink, fullComment); clearParentPost(clickedLink, fullComment);
insertParentPost(data, clickedLink, fullComment); insertParentPost(data, clickedLink, fullComment);
}); });
@ -97,7 +97,7 @@ function clearParentPost(clickedLink, fullComment) {
} }
// Remove class active_reply_link from all links in the comment // Remove class active_reply_link from all links in the comment
[].slice.call(fullComment.getElementsByClassName('active_reply_link')).forEach((link) => { [].slice.call(fullComment.getElementsByClassName('active_reply_link')).forEach(link => {
link.classList.remove('active_reply_link'); link.classList.remove('active_reply_link');
}); });
@ -129,7 +129,7 @@ function loadComments(event) {
fetchHtml(getURL) fetchHtml(getURL)
.then(handleError) .then(handleError)
.then((data) => { .then(data => {
displayComments(container, data); displayComments(container, data);
// Make sure the :target CSS selector applies to the inserted content // Make sure the :target CSS selector applies to the inserted content
@ -165,7 +165,7 @@ function setupComments() {
'#js-refresh-comments': loadComments, '#js-refresh-comments': loadComments,
}; };
document.addEventListener('click', (event) => { document.addEventListener('click', event => {
if (event.button === 0) { if (event.button === 0) {
// Left-click only // Left-click only
for (const target in targets) { for (const target in targets) {
@ -176,7 +176,7 @@ function setupComments() {
} }
}); });
document.addEventListener('fetchcomplete', (event) => { document.addEventListener('fetchcomplete', event => {
if (event.target.id === 'js-comment-form') commentPosted(event.detail); if (event.target.id === 'js-comment-form') commentPosted(event.detail);
}); });
} }

View file

@ -102,8 +102,8 @@ function getUserAgentBrands(): string {
// NB: Chromium implements GREASE protocol to prevent ossification of // NB: Chromium implements GREASE protocol to prevent ossification of
// the "Not a brand" string - see https://stackoverflow.com/a/64443187 // the "Not a brand" string - see https://stackoverflow.com/a/64443187
brands = data.brands brands = data.brands
.filter((e) => !e.brand.match(/.*ot.*rand.*/gi)) .filter(e => !e.brand.match(/.*ot.*rand.*/gi))
.map((e) => `${e.brand}${e.version}`) .map(e => `${e.brand}${e.version}`)
.sort() .sort()
.join(''); .join('');
} }

View file

@ -22,7 +22,7 @@ export function setupGalleryEditing() {
initDraggables(); initDraggables();
$$<HTMLDivElement>('.media-box', containerEl).forEach((i) => { $$<HTMLDivElement>('.media-box', containerEl).forEach(i => {
i.draggable = true; i.draggable = true;
}); });
@ -35,7 +35,7 @@ export function setupGalleryEditing() {
sortableEl.classList.remove('editing'); sortableEl.classList.remove('editing');
containerEl.classList.remove('drag-container'); containerEl.classList.remove('drag-container');
newImages = $$<HTMLDivElement>('.image-container', containerEl).map((i) => newImages = $$<HTMLDivElement>('.image-container', containerEl).map(i =>
parseInt(assertNotUndefined(i.dataset.imageId), 10), parseInt(assertNotUndefined(i.dataset.imageId), 10),
); );

View file

@ -22,7 +22,7 @@ function graphSlice(el: SVGSVGElement, width: number, offset: number) {
} }
function resizeGraphs() { function resizeGraphs() {
$$<SVGSVGElement>('#js-graph-svg').forEach((el) => { $$<SVGSVGElement>('#js-graph-svg').forEach(el => {
const parent: HTMLElement | null = el.parentElement; const parent: HTMLElement | null = el.parentElement;
if (parent) { if (parent) {
@ -47,7 +47,7 @@ function scaleGraph(target: HTMLElement, min: number, max: number) {
} }
function setupSliders() { function setupSliders() {
$$<HTMLInputElement>('#js-graph-slider').forEach((el) => { $$<HTMLInputElement>('#js-graph-slider').forEach(el => {
const targetId = el.getAttribute('data-target'); const targetId = el.getAttribute('data-target');
if (!targetId) return; if (!targetId) return;

View file

@ -156,7 +156,7 @@ function bindImageForClick(target) {
} }
function bindImageTarget(node = document) { function bindImageTarget(node = document) {
$$('.image-target', node).forEach((target) => { $$('.image-target', node).forEach(target => {
pickAndResize(target); pickAndResize(target);
if (target.dataset.mimeType === 'video/webm') { if (target.dataset.mimeType === 'video/webm') {

View file

@ -84,15 +84,15 @@ export function filterNode(node: Pick<Document, 'querySelectorAll'>) {
// Image thumb boxes with vote and fave buttons on them // Image thumb boxes with vote and fave buttons on them
$$<HTMLDivElement>('.image-container', node) $$<HTMLDivElement>('.image-container', node)
.filter((img) => !run(img, hiddenTags, hiddenFilter, hideThumbTyped)) .filter(img => !run(img, hiddenTags, hiddenFilter, hideThumbTyped))
.filter((img) => !run(img, spoileredTags, spoileredFilter, spoilerThumbTyped)) .filter(img => !run(img, spoileredTags, spoileredFilter, spoilerThumbTyped))
.forEach((img) => showThumb(img)); .forEach(img => showThumb(img));
// Individual image pages and images in posts/comments // Individual image pages and images in posts/comments
$$<HTMLDivElement>('.image-show-container', node) $$<HTMLDivElement>('.image-show-container', node)
.filter((img) => !run(img, hiddenTags, hiddenFilter, hideBlockTyped)) .filter(img => !run(img, hiddenTags, hiddenFilter, hideBlockTyped))
.filter((img) => !run(img, spoileredTags, spoileredFilter, spoilerBlockTyped)) .filter(img => !run(img, spoileredTags, spoileredFilter, spoilerBlockTyped))
.forEach((img) => showBlock(img)); .forEach(img => showBlock(img));
} }
export function initImagesClientside() { export function initImagesClientside() {

View file

@ -41,7 +41,7 @@ export function inputDuplicatorCreator({
const maxOptionCountElement = assertNotNull($(maxInputCountSelector, form)); const maxOptionCountElement = assertNotNull($(maxInputCountSelector, form));
const maxOptionCount = parseInt(maxOptionCountElement.innerHTML, 10); const maxOptionCount = parseInt(maxOptionCountElement.innerHTML, 10);
addButton.addEventListener('click', (e) => { addButton.addEventListener('click', e => {
e.preventDefault(); e.preventDefault();
const existingFields = $$<HTMLElement>(fieldSelector, form); const existingFields = $$<HTMLElement>(fieldSelector, form);
@ -52,7 +52,7 @@ export function inputDuplicatorCreator({
const prevField = existingFields[existingFieldsLength - 1]; const prevField = existingFields[existingFieldsLength - 1];
const prevFieldCopy = prevField.cloneNode(true) as HTMLElement; const prevFieldCopy = prevField.cloneNode(true) as HTMLElement;
$$<HTMLInputElement>('input', prevFieldCopy).forEach((prevFieldCopyInput) => { $$<HTMLInputElement>('input', prevFieldCopy).forEach(prevFieldCopyInput => {
// Reset new input's value // Reset new input's value
prevFieldCopyInput.value = ''; prevFieldCopyInput.value = '';
prevFieldCopyInput.removeAttribute('value'); prevFieldCopyInput.removeAttribute('value');

View file

@ -39,33 +39,33 @@ function modifyCache(callback) {
} }
function cacheStatus(imageId, interactionType, value) { function cacheStatus(imageId, interactionType, value) {
modifyCache((cache) => { modifyCache(cache => {
cache[`${imageId}${interactionType}`] = { imageId, interactionType, value }; cache[`${imageId}${interactionType}`] = { imageId, interactionType, value };
return cache; return cache;
}); });
} }
function uncacheStatus(imageId, interactionType) { function uncacheStatus(imageId, interactionType) {
modifyCache((cache) => { modifyCache(cache => {
delete cache[`${imageId}${interactionType}`]; delete cache[`${imageId}${interactionType}`];
return cache; return cache;
}); });
} }
function setScore(imageId, data) { function setScore(imageId, data) {
onImage(imageId, '.score', (el) => { onImage(imageId, '.score', el => {
el.textContent = data.score; el.textContent = data.score;
}); });
onImage(imageId, '.favorites', (el) => { onImage(imageId, '.favorites', el => {
el.textContent = data.faves; el.textContent = data.faves;
}); });
onImage(imageId, '.upvotes', (el) => { onImage(imageId, '.upvotes', el => {
el.textContent = data.upvotes; el.textContent = data.upvotes;
}); });
onImage(imageId, '.downvotes', (el) => { onImage(imageId, '.downvotes', el => {
el.textContent = data.downvotes; el.textContent = data.downvotes;
}); });
} }
@ -75,50 +75,50 @@ function setScore(imageId, data) {
function showUpvoted(imageId) { function showUpvoted(imageId) {
cacheStatus(imageId, 'voted', 'up'); cacheStatus(imageId, 'voted', 'up');
onImage(imageId, '.interaction--upvote', (el) => el.classList.add('active')); onImage(imageId, '.interaction--upvote', el => el.classList.add('active'));
} }
function showDownvoted(imageId) { function showDownvoted(imageId) {
cacheStatus(imageId, 'voted', 'down'); cacheStatus(imageId, 'voted', 'down');
onImage(imageId, '.interaction--downvote', (el) => el.classList.add('active')); onImage(imageId, '.interaction--downvote', el => el.classList.add('active'));
} }
function showFaved(imageId) { function showFaved(imageId) {
cacheStatus(imageId, 'faved', ''); cacheStatus(imageId, 'faved', '');
onImage(imageId, '.interaction--fave', (el) => el.classList.add('active')); onImage(imageId, '.interaction--fave', el => el.classList.add('active'));
} }
function showHidden(imageId) { function showHidden(imageId) {
cacheStatus(imageId, 'hidden', ''); cacheStatus(imageId, 'hidden', '');
onImage(imageId, '.interaction--hide', (el) => el.classList.add('active')); onImage(imageId, '.interaction--hide', el => el.classList.add('active'));
} }
function resetVoted(imageId) { function resetVoted(imageId) {
uncacheStatus(imageId, 'voted'); uncacheStatus(imageId, 'voted');
onImage(imageId, '.interaction--upvote', (el) => el.classList.remove('active')); onImage(imageId, '.interaction--upvote', el => el.classList.remove('active'));
onImage(imageId, '.interaction--downvote', (el) => el.classList.remove('active')); onImage(imageId, '.interaction--downvote', el => el.classList.remove('active'));
} }
function resetFaved(imageId) { function resetFaved(imageId) {
uncacheStatus(imageId, 'faved'); uncacheStatus(imageId, 'faved');
onImage(imageId, '.interaction--fave', (el) => el.classList.remove('active')); onImage(imageId, '.interaction--fave', el => el.classList.remove('active'));
} }
function resetHidden(imageId) { function resetHidden(imageId) {
uncacheStatus(imageId, 'hidden'); uncacheStatus(imageId, 'hidden');
onImage(imageId, '.interaction--hide', (el) => el.classList.remove('active')); onImage(imageId, '.interaction--hide', el => el.classList.remove('active'));
} }
function interact(type, imageId, method, data = {}) { function interact(type, imageId, method, data = {}) {
return fetchJson(method, endpoints[type](imageId), data) return fetchJson(method, endpoints[type](imageId), data)
.then((res) => res.json()) .then(res => res.json())
.then((res) => setScore(imageId, res)); .then(res => setScore(imageId, res));
} }
function displayInteractionSet(interactions) { function displayInteractionSet(interactions) {
interactions.forEach((i) => { interactions.forEach(i => {
switch (i.interaction_type) { switch (i.interaction_type) {
case 'faved': case 'faved':
showFaved(i.image_id); showFaved(i.image_id);
@ -143,8 +143,8 @@ function loadInteractions() {
if (!document.getElementById('imagelist-container')) return; if (!document.getElementById('imagelist-container')) return;
/* Users will blind downvote without this */ /* Users will blind downvote without this */
window.booru.imagesWithDownvotingDisabled.forEach((i) => { window.booru.imagesWithDownvotingDisabled.forEach(i => {
onImage(i, '.interaction--downvote', (a) => { onImage(i, '.interaction--downvote', a => {
// TODO Use a 'js-' class to target these instead // TODO Use a 'js-' class to target these instead
const icon = a.querySelector('i') || a.querySelector('.oc-icon-small'); const icon = a.querySelector('i') || a.querySelector('.oc-icon-small');
@ -152,7 +152,7 @@ function loadInteractions() {
a.classList.add('disabled'); a.classList.add('disabled');
a.addEventListener( a.addEventListener(
'click', 'click',
(event) => { event => {
event.stopPropagation(); event.stopPropagation();
event.preventDefault(); event.preventDefault();
}, },
@ -205,7 +205,7 @@ const targets = {
}; };
function bindInteractions() { function bindInteractions() {
document.addEventListener('click', (event) => { document.addEventListener('click', event => {
if (event.button === 0) { if (event.button === 0) {
// Is it a left-click? // Is it a left-click?
for (const target in targets) { for (const target in targets) {
@ -222,7 +222,7 @@ function bindInteractions() {
} }
function loggedOutInteractions() { function loggedOutInteractions() {
[].forEach.call(document.querySelectorAll('.interaction--fave,.interaction--upvote,.interaction--downvote'), (a) => [].forEach.call(document.querySelectorAll('.interaction--fave,.interaction--upvote,.interaction--downvote'), a =>
a.setAttribute('href', '/sessions/new'), a.setAttribute('href', '/sessions/new'),
); );
} }

View file

@ -156,13 +156,13 @@ function insertLink(textarea, options) {
} }
function wrapSelection(textarea, options) { function wrapSelection(textarea, options) {
transformSelection(textarea, (selectedText) => { transformSelection(textarea, selectedText => {
const { text = selectedText, prefix = '', suffix = options.prefix } = options, const { text = selectedText, prefix = '', suffix = options.prefix } = options,
emptyText = text === ''; emptyText = text === '';
let newText = text; let newText = text;
if (!emptyText) { if (!emptyText) {
newText = text.replace(/(\n{2,})/g, (match) => { newText = text.replace(/(\n{2,})/g, match => {
return suffix + match + prefix; return suffix + match + prefix;
}); });
} }
@ -188,7 +188,7 @@ function wrapLines(textarea, options, eachLine = true) {
? prefix + text.trim() + suffix ? prefix + text.trim() + suffix
: text : text
.split(/\n/g) .split(/\n/g)
.map((line) => prefix + line.trim() + suffix) .map(line => prefix + line.trim() + suffix)
.join('\n'); .join('\n');
// Force a space at the end of lines with only blockquote markers // Force a space at the end of lines with only blockquote markers
@ -205,7 +205,7 @@ function wrapSelectionOrLines(textarea, options) {
} }
function escapeSelection(textarea, options) { function escapeSelection(textarea, options) {
transformSelection(textarea, (selectedText) => { transformSelection(textarea, selectedText => {
const { text = selectedText } = options, const { text = selectedText } = options,
emptyText = text === ''; emptyText = text === '';
@ -255,10 +255,10 @@ function shortcutHandler(event) {
} }
function setupToolbar() { function setupToolbar() {
$$('.communication__toolbar').forEach((toolbar) => { $$('.communication__toolbar').forEach(toolbar => {
toolbar.addEventListener('click', clickHandler); toolbar.addEventListener('click', clickHandler);
}); });
$$('.js-toolbar-input').forEach((textarea) => { $$('.js-toolbar-input').forEach(textarea => {
textarea.addEventListener('keydown', shortcutHandler); textarea.addEventListener('keydown', shortcutHandler);
}); });
} }

View file

@ -20,7 +20,7 @@ function formResult({ target, detail }: FetchcompleteEvent) {
hideEl(formEl); hideEl(formEl);
showEl(resultEl); showEl(resultEl);
$$<HTMLInputElement | HTMLButtonElement>('input[type="submit"],button', formEl).forEach((button) => { $$<HTMLInputElement | HTMLButtonElement>('input[type="submit"],button', formEl).forEach(button => {
button.disabled = false; button.disabled = false;
}); });
} }
@ -30,7 +30,7 @@ function formResult({ target, detail }: FetchcompleteEvent) {
const form = assertType(target, HTMLFormElement); const form = assertType(target, HTMLFormElement);
const result = assertNotNull($<HTMLElement>(resultSelector)); const result = assertNotNull($<HTMLElement>(resultSelector));
detail.text().then((text) => showResult(form, result, text)); detail.text().then(text => showResult(form, result, text));
} }
} }
} }
@ -85,7 +85,7 @@ export function setupEvents() {
} }
if (store.get('hide_score')) { if (store.get('hide_score')) {
$$<HTMLElement>('.upvotes,.score,.downvotes').forEach((s) => hideEl(s)); $$<HTMLElement>('.upvotes,.score,.downvotes').forEach(s => hideEl(s));
} }
document.addEventListener('fetchcomplete', formResult); document.addEventListener('fetchcomplete', formResult);

View file

@ -13,10 +13,10 @@ const NOTIFICATION_INTERVAL = 600000,
function bindSubscriptionLinks() { function bindSubscriptionLinks() {
delegate(document, 'fetchcomplete', { delegate(document, 'fetchcomplete', {
'.js-subscription-link': (event) => { '.js-subscription-link': event => {
const target = assertNotNull(event.target.closest('.js-subscription-target')); const target = assertNotNull(event.target.closest('.js-subscription-target'));
event.detail.text().then((text) => { event.detail.text().then(text => {
target.outerHTML = text; target.outerHTML = text;
}); });
}, },
@ -30,7 +30,7 @@ function getNewNotifications() {
fetchJson('GET', '/notifications/unread') fetchJson('GET', '/notifications/unread')
.then(handleError) .then(handleError)
.then((response) => response.json()) .then(response => response.json())
.then(({ notifications }) => { .then(({ notifications }) => {
updateNotificationTicker(notifications); updateNotificationTicker(notifications);
storeNotificationCount(notifications); storeNotificationCount(notifications);

View file

@ -47,7 +47,7 @@ function getPreview(body, anonymous, previewLoading, previewIdle, previewContent
fetchJson('POST', path, { body, anonymous }) fetchJson('POST', path, { body, anonymous })
.then(handleError) .then(handleError)
.then((data) => { .then(data => {
previewContent.innerHTML = data; previewContent.innerHTML = data;
filterNode(previewContent); filterNode(previewContent);
bindImageTarget(previewContent); bindImageTarget(previewContent);
@ -117,7 +117,7 @@ function setupPreviews() {
updatePreview(); updatePreview();
}); });
document.addEventListener('click', (event) => { document.addEventListener('click', event => {
if (event.target && event.target.closest('.post-reply')) { if (event.target && event.target.closest('.post-reply')) {
const link = event.target.closest('.post-reply'); const link = event.target.closest('.post-reply');
commentReply(link.dataset.author, link.getAttribute('href'), textarea, link.dataset.post); commentReply(link.dataset.author, link.getAttribute('href'), textarea, link.dataset.post);

View file

@ -1,11 +1,11 @@
import { AstMatcher } from './types'; import { AstMatcher } from './types';
export function matchAny(...matchers: AstMatcher[]): AstMatcher { export function matchAny(...matchers: AstMatcher[]): AstMatcher {
return (e: HTMLElement) => matchers.some((matcher) => matcher(e)); return (e: HTMLElement) => matchers.some(matcher => matcher(e));
} }
export function matchAll(...matchers: AstMatcher[]): AstMatcher { export function matchAll(...matchers: AstMatcher[]): AstMatcher {
return (e: HTMLElement) => matchers.every((matcher) => matcher(e)); return (e: HTMLElement) => matchers.every(matcher => matcher(e));
} }
export function matchNot(matcher: AstMatcher): AstMatcher { export function matchNot(matcher: AstMatcher): AstMatcher {

View file

@ -17,16 +17,16 @@ function makeMatcher(bottomDate: PosixTimeMs, topDate: PosixTimeMs, qual: RangeE
// done compared to numeric ranges. // done compared to numeric ranges.
switch (qual) { switch (qual) {
case 'lte': case 'lte':
return (v) => new Date(v).getTime() < topDate; return v => new Date(v).getTime() < topDate;
case 'gte': case 'gte':
return (v) => new Date(v).getTime() >= bottomDate; return v => new Date(v).getTime() >= bottomDate;
case 'lt': case 'lt':
return (v) => new Date(v).getTime() < bottomDate; return v => new Date(v).getTime() < bottomDate;
case 'gt': case 'gt':
return (v) => new Date(v).getTime() >= topDate; return v => new Date(v).getTime() >= topDate;
case 'eq': case 'eq':
default: default:
return (v) => { return v => {
const t = new Date(v).getTime(); const t = new Date(v).getTime();
return t >= bottomDate && t < topDate; return t >= bottomDate && t < topDate;
}; };

View file

@ -2,7 +2,7 @@ import { FieldMatcher, RangeEqualQualifier } from './types';
export function makeNumberMatcher(term: number, fuzz: number, qual: RangeEqualQualifier): FieldMatcher { export function makeNumberMatcher(term: number, fuzz: number, qual: RangeEqualQualifier): FieldMatcher {
// Range matching. // Range matching.
return (v) => { return v => {
const attrVal = parseFloat(v); const attrVal = parseFloat(v);
if (isNaN(attrVal)) { if (isNaN(attrVal)) {

View file

@ -8,7 +8,7 @@ function interactionMatch(
interactions: Interaction[], interactions: Interaction[],
): boolean { ): boolean {
return interactions.some( return interactions.some(
(v) => v.image_id === imageId && v.interaction_type === type && (value === null || v.value === value), v => v.image_id === imageId && v.interaction_type === type && (value === null || v.value === value),
); );
} }

View file

@ -30,10 +30,10 @@ function toggleActiveState() {
setTagButton(`Submit (${currentTags()})`); setTagButton(`Submit (${currentTags()})`);
$$('.media-box__header').forEach((el) => el.classList.toggle('media-box__header--unselected')); $$('.media-box__header').forEach(el => el.classList.toggle('media-box__header--unselected'));
$$('.media-box__header').forEach((el) => el.classList.remove('media-box__header--selected')); $$('.media-box__header').forEach(el => el.classList.remove('media-box__header--selected'));
currentQueue().forEach((id) => currentQueue().forEach(id =>
$$(`.media-box__header[data-image-id="${id}"]`).forEach((el) => el.classList.add('media-box__header--selected')), $$(`.media-box__header[data-image-id="${id}"]`).forEach(el => el.classList.add('media-box__header--selected')),
); );
} }
@ -64,8 +64,8 @@ function submit() {
image_ids: currentQueue(), image_ids: currentQueue(),
}) })
.then(handleError) .then(handleError)
.then((r) => r.json()) .then(r => r.json())
.then((data) => { .then(data => {
if (data.failed.length) window.alert(`Failed to add tags to the images with these IDs: ${data.failed}`); if (data.failed.length) window.alert(`Failed to add tags to the images with these IDs: ${data.failed}`);
reset(); reset();
@ -80,7 +80,7 @@ function modifyImageQueue(mediaBox) {
isSelected ? queue.splice(queue.indexOf(imageId), 1) : queue.push(imageId); isSelected ? queue.splice(queue.indexOf(imageId), 1) : queue.push(imageId);
$$(`.media-box__header[data-image-id="${imageId}"]`).forEach((el) => $$(`.media-box__header[data-image-id="${imageId}"]`).forEach(el =>
el.classList.toggle('media-box__header--selected'), el.classList.toggle('media-box__header--selected'),
); );

View file

@ -2,7 +2,7 @@ import { $, $$ } from './utils/dom';
import { addTag } from './tagsinput'; import { addTag } from './tagsinput';
function showHelp(subject: string, type: string | null) { function showHelp(subject: string, type: string | null) {
$$<HTMLElement>('[data-search-help]').forEach((helpBox) => { $$<HTMLElement>('[data-search-help]').forEach(helpBox => {
if (helpBox.getAttribute('data-search-help') === type) { if (helpBox.getAttribute('data-search-help') === type) {
const searchSubject = $<HTMLElement>('.js-search-help-subject', helpBox); const searchSubject = $<HTMLElement>('.js-search-help-subject', helpBox);

View file

@ -18,7 +18,7 @@ export function setupSettings() {
const styleSheet = assertNotNull($<HTMLLinkElement>('#js-theme-stylesheet')); const styleSheet = assertNotNull($<HTMLLinkElement>('#js-theme-stylesheet'));
// Local settings // Local settings
localCheckboxes.forEach((checkbox) => { localCheckboxes.forEach(checkbox => {
checkbox.addEventListener('change', () => { checkbox.addEventListener('change', () => {
store.set(checkbox.id.replace('user_', ''), checkbox.checked); store.set(checkbox.id.replace('user_', ''), checkbox.checked);
}); });

View file

@ -169,7 +169,7 @@ function setupSlider(el: HTMLInputElement) {
// Sets up all sliders currently on the page. // Sets up all sliders currently on the page.
function setupSliders() { function setupSliders() {
$$<HTMLInputElement>('input[type="dualrange"]').forEach((el) => { $$<HTMLInputElement>('input[type="dualrange"]').forEach(el => {
setupSlider(el); setupSlider(el);
}); });
} }

View file

@ -19,7 +19,7 @@ export function imageSourcesCreator() {
if (target.matches('#source-form')) { if (target.matches('#source-form')) {
const sourceSauce = assertNotNull($<HTMLElement>('.js-sourcesauce')); const sourceSauce = assertNotNull($<HTMLElement>('.js-sourcesauce'));
detail.text().then((text) => { detail.text().then(text => {
sourceSauce.outerHTML = text; sourceSauce.outerHTML = text;
setupInputs(); setupInputs();
}); });

View file

@ -8,6 +8,6 @@ import { $$, hideEl } from './utils/dom';
export function hideStaffTools() { export function hideStaffTools() {
if (window.booru.hideStaffTools === 'true') { if (window.booru.hideStaffTools === 'true') {
$$<HTMLElement>('.js-staff-action').forEach((el) => hideEl(el)); $$<HTMLElement>('.js-staff-action').forEach(el => hideEl(el));
} }
} }

View file

@ -82,7 +82,7 @@ function createTagDropdown(tag: HTMLSpanElement) {
if (!userIsSignedIn) showEl(signIn); if (!userIsSignedIn) showEl(signIn);
if (userIsSignedIn && !userCanEditFilter) showEl(filter); if (userIsSignedIn && !userCanEditFilter) showEl(filter);
tag.addEventListener('fetchcomplete', (event) => { tag.addEventListener('fetchcomplete', event => {
const act = assertNotUndefined(event.target.dataset.tagAction); const act = assertNotUndefined(event.target.dataset.tagAction);
actions[act](); actions[act]();
}); });

View file

@ -81,7 +81,7 @@ function setupTagsInput(tagBlock) {
// enter or comma // enter or comma
if (keyCode === 13 || (keyCode === 188 && !shiftKey)) { if (keyCode === 13 || (keyCode === 188 && !shiftKey)) {
event.preventDefault(); event.preventDefault();
inputField.value.split(',').forEach((t) => insertTag(t)); inputField.value.split(',').forEach(t => insertTag(t));
inputField.value = ''; inputField.value = '';
} }
} }
@ -129,7 +129,7 @@ function setupTagsInput(tagBlock) {
container.appendChild(inputField); container.appendChild(inputField);
tags = []; tags = [];
textarea.value.split(',').forEach((t) => insertTag(t)); textarea.value.split(',').forEach(t => insertTag(t));
textarea.value = tags.join(', '); textarea.value = tags.join(', ');
} }
} }
@ -143,7 +143,7 @@ function fancyEditorRequested(tagBlock) {
} }
function setupTagListener() { function setupTagListener() {
document.addEventListener('addtag', (event) => { document.addEventListener('addtag', event => {
if (event.target.value) event.target.value += ', '; if (event.target.value) event.target.value += ', ';
event.target.value += event.detail.name; event.target.value += event.detail.name;
}); });

View file

@ -38,7 +38,7 @@ function tagInputButtons(event: MouseEvent) {
} }
function setupTags() { function setupTags() {
$$<HTMLDivElement>('.js-tag-block').forEach((el) => { $$<HTMLDivElement>('.js-tag-block').forEach(el => {
setupTagsInput(el); setupTagsInput(el);
el.classList.remove('js-tag-block'); el.classList.remove('js-tag-block');
}); });
@ -48,7 +48,7 @@ function updateTagSauce({ target, detail }: FetchcompleteEvent) {
if (target.matches('#tags-form')) { if (target.matches('#tags-form')) {
const tagSauce = assertNotNull($<HTMLDivElement>('.js-tagsauce')); const tagSauce = assertNotNull($<HTMLDivElement>('.js-tagsauce'));
detail.text().then((text) => { detail.text().then(text => {
tagSauce.outerHTML = text; tagSauce.outerHTML = text;
setupTags(); setupTags();
initTagDropdown(); initTagDropdown();

View file

@ -57,7 +57,7 @@ function formRemote(event: Event, target: HTMLFormElement) {
method: (target.dataset.method || target.method).toUpperCase(), method: (target.dataset.method || target.method).toUpperCase(),
headers: headers(), headers: headers(),
body: new FormData(target), body: new FormData(target),
}).then((response) => { }).then(response => {
fire(target, 'fetchcomplete', response); fire(target, 'fetchcomplete', response);
if (response && response.status === 300) { if (response && response.status === 300) {
window.location.reload(); window.location.reload();
@ -66,7 +66,7 @@ function formRemote(event: Event, target: HTMLFormElement) {
} }
function formReset(_event: Event | null, target: HTMLElement) { function formReset(_event: Event | null, target: HTMLElement) {
$$<HTMLElement>('[disabled][data-disable-with][data-enable-with]', target).forEach((input) => { $$<HTMLElement>('[disabled][data-disable-with][data-enable-with]', target).forEach(input => {
const label = findFirstTextNode(input); const label = findFirstTextNode(input);
if (label) { if (label) {
label.nodeValue = ` ${input.dataset.enableWith}`; label.nodeValue = ` ${input.dataset.enableWith}`;
@ -85,7 +85,7 @@ function linkRemote(event: Event, target: HTMLAnchorElement) {
credentials: 'same-origin', credentials: 'same-origin',
method: (target.dataset.method || 'get').toUpperCase(), method: (target.dataset.method || 'get').toUpperCase(),
headers: headers(), headers: headers(),
}).then((response) => fire(target, 'fetchcomplete', response)); }).then(response => fire(target, 'fetchcomplete', response));
} }
delegate(document, 'click', { delegate(document, 'click', {

View file

@ -11,7 +11,7 @@ const MATROSKA_MAGIC = 0x1a45dfa3;
function scrapeUrl(url) { function scrapeUrl(url) {
return fetchJson('POST', '/images/scrape', { url }) return fetchJson('POST', '/images/scrape', { url })
.then(handleError) .then(handleError)
.then((response) => response.json()); .then(response => response.json());
} }
function elementForEmbeddedImage({ camo_url, type }) { function elementForEmbeddedImage({ camo_url, type }) {
@ -34,7 +34,7 @@ function setupImageUpload() {
const [fileField, remoteUrl, scraperError] = $$('.js-scraper', form); const [fileField, remoteUrl, scraperError] = $$('.js-scraper', form);
const descrEl = $('.js-image-descr-input', form); const descrEl = $('.js-image-descr-input', form);
const tagsEl = $('.js-image-tags-input', form); const tagsEl = $('.js-image-tags-input', form);
const sourceEl = $$('.js-source-url', form).find((input) => input.value === ''); const sourceEl = $$('.js-source-url', form).find(input => input.value === '');
const fetchButton = $('#js-scraper-preview'); const fetchButton = $('#js-scraper-preview');
if (!fetchButton) return; if (!fetchButton) return;
@ -80,7 +80,7 @@ function setupImageUpload() {
const reader = new FileReader(); const reader = new FileReader();
reader.addEventListener('load', (event) => { reader.addEventListener('load', event => {
showImages([ showImages([
{ {
camo_url: event.target.result, camo_url: event.target.result,
@ -107,7 +107,7 @@ function setupImageUpload() {
disableFetch(); disableFetch();
scrapeUrl(remoteUrl.value) scrapeUrl(remoteUrl.value)
.then((data) => { .then(data => {
if (data === null) { if (data === null) {
scraperError.innerText = 'No image found at that address.'; scraperError.innerText = 'No image found at that address.';
showError(); showError();
@ -136,7 +136,7 @@ function setupImageUpload() {
}); });
// Fetch on "enter" in url field // Fetch on "enter" in url field
remoteUrl.addEventListener('keydown', (event) => { remoteUrl.addEventListener('keydown', event => {
if (event.keyCode === 13) { if (event.keyCode === 13) {
// Hit enter // Hit enter
fetchButton.click(); fetchButton.click();

View file

@ -80,7 +80,7 @@ describe('Draggable Utilities', () => {
expect(dataTransferItem.type).toEqual('text/plain'); expect(dataTransferItem.type).toEqual('text/plain');
let stringValue: string | undefined; let stringValue: string | undefined;
dataTransferItem.getAsString((value) => { dataTransferItem.getAsString(value => {
stringValue = value; stringValue = value;
}); });
expect(stringValue).toEqual(''); expect(stringValue).toEqual('');

View file

@ -60,7 +60,7 @@ describe('Event utils', () => {
const mockButton = document.createElement('button'); const mockButton = document.createElement('button');
const mockHandler = vi.fn(); const mockHandler = vi.fn();
mockButton.addEventListener('click', (e) => leftClick(mockHandler)(e, mockButton)); mockButton.addEventListener('click', e => leftClick(mockHandler)(e, mockButton));
fireEvent.click(mockButton, { button: 0 }); fireEvent.click(mockButton, { button: 0 });
@ -72,7 +72,7 @@ describe('Event utils', () => {
const mockHandler = vi.fn(); const mockHandler = vi.fn();
const mockButtonNumber = getRandomArrayItem([1, 2, 3, 4, 5]); const mockButtonNumber = getRandomArrayItem([1, 2, 3, 4, 5]);
mockButton.addEventListener('click', (e) => leftClick(mockHandler)(e, mockButton)); mockButton.addEventListener('click', e => leftClick(mockHandler)(e, mockButton));
fireEvent.click(mockButton, { button: mockButtonNumber }); fireEvent.click(mockButton, { button: mockButtonNumber });

View file

@ -101,7 +101,7 @@ describe('Image utils', () => {
const mockImage = new Image(); const mockImage = new Image();
mockImage.src = mockImageUri; mockImage.src = mockImageUri;
if (imgClasses) { if (imgClasses) {
imgClasses.forEach((videoClass) => { imgClasses.forEach(videoClass => {
mockImage.classList.add(videoClass); mockImage.classList.add(videoClass);
}); });
} }
@ -109,7 +109,7 @@ describe('Image utils', () => {
const mockVideo = document.createElement('video'); const mockVideo = document.createElement('video');
if (videoClasses) { if (videoClasses) {
videoClasses.forEach((videoClass) => { videoClasses.forEach(videoClass => {
mockVideo.classList.add(videoClass); mockVideo.classList.add(videoClass);
}); });
} }
@ -161,7 +161,7 @@ describe('Image utils', () => {
expect(result).toBe(true); expect(result).toBe(true);
}); });
['data-size', 'data-uris'].forEach((missingAttributeName) => { ['data-size', 'data-uris'].forEach(missingAttributeName => {
it(`should return early if the ${missingAttributeName} attribute is missing`, () => { it(`should return early if the ${missingAttributeName} attribute is missing`, () => {
const { mockElement } = createMockElements({ const { mockElement } = createMockElements({
extension: 'webm', extension: 'webm',

View file

@ -25,37 +25,37 @@ export function $$<E extends Element = Element>(
} }
export function showEl<E extends HTMLElement>(...elements: E[] | ConcatArray<E>[]) { export function showEl<E extends HTMLElement>(...elements: E[] | ConcatArray<E>[]) {
([] as E[]).concat(...elements).forEach((el) => el.classList.remove('hidden')); ([] as E[]).concat(...elements).forEach(el => el.classList.remove('hidden'));
} }
export function hideEl<E extends HTMLElement>(...elements: E[] | ConcatArray<E>[]) { export function hideEl<E extends HTMLElement>(...elements: E[] | ConcatArray<E>[]) {
([] as E[]).concat(...elements).forEach((el) => el.classList.add('hidden')); ([] as E[]).concat(...elements).forEach(el => el.classList.add('hidden'));
} }
export function toggleEl<E extends HTMLElement>(...elements: E[] | ConcatArray<E>[]) { export function toggleEl<E extends HTMLElement>(...elements: E[] | ConcatArray<E>[]) {
([] as E[]).concat(...elements).forEach((el) => el.classList.toggle('hidden')); ([] as E[]).concat(...elements).forEach(el => el.classList.toggle('hidden'));
} }
export function clearEl<E extends HTMLElement>(...elements: E[] | ConcatArray<E>[]) { export function clearEl<E extends HTMLElement>(...elements: E[] | ConcatArray<E>[]) {
([] as E[]).concat(...elements).forEach((el) => { ([] as E[]).concat(...elements).forEach(el => {
while (el.firstChild) el.removeChild(el.firstChild); while (el.firstChild) el.removeChild(el.firstChild);
}); });
} }
export function disableEl<E extends PhilomenaInputElements>(...elements: E[] | ConcatArray<E>[]) { export function disableEl<E extends PhilomenaInputElements>(...elements: E[] | ConcatArray<E>[]) {
([] as E[]).concat(...elements).forEach((el) => { ([] as E[]).concat(...elements).forEach(el => {
el.disabled = true; el.disabled = true;
}); });
} }
export function enableEl<E extends PhilomenaInputElements>(...elements: E[] | ConcatArray<E>[]) { export function enableEl<E extends PhilomenaInputElements>(...elements: E[] | ConcatArray<E>[]) {
([] as E[]).concat(...elements).forEach((el) => { ([] as E[]).concat(...elements).forEach(el => {
el.disabled = false; el.disabled = false;
}); });
} }
export function removeEl<E extends HTMLElement>(...elements: E[] | ConcatArray<E>[]) { export function removeEl<E extends HTMLElement>(...elements: E[] | ConcatArray<E>[]) {
([] as E[]).concat(...elements).forEach((el) => el.parentNode?.removeChild(el)); ([] as E[]).concat(...elements).forEach(el => el.parentNode?.removeChild(el));
} }
export function makeEl<Tag extends keyof HTMLElementTagNameMap>( export function makeEl<Tag extends keyof HTMLElementTagNameMap>(
@ -78,7 +78,7 @@ export function onLeftClick(
callback: (e: MouseEvent) => boolean | void, callback: (e: MouseEvent) => boolean | void,
context: Pick<GlobalEventHandlers, 'addEventListener' | 'removeEventListener'> = document, context: Pick<GlobalEventHandlers, 'addEventListener' | 'removeEventListener'> = document,
): VoidFunction { ): VoidFunction {
const handler: typeof callback = (event) => { const handler: typeof callback = event => {
if (event.button === 0) callback(event); if (event.button === 0) callback(event);
}; };
context.addEventListener('click', handler); context.addEventListener('click', handler);
@ -106,5 +106,5 @@ export function escapeCss(css: string): string {
} }
export function findFirstTextNode<N extends Node>(of: Node): N { export function findFirstTextNode<N extends Node>(of: Node): N {
return Array.prototype.filter.call(of.childNodes, (el) => el.nodeType === Node.TEXT_NODE)[0]; return Array.prototype.filter.call(of.childNodes, el => el.nodeType === Node.TEXT_NODE)[0];
} }

View file

@ -56,7 +56,7 @@ function dragEnd(event: DragEvent, target: HTMLElement) {
clearDragSource(); clearDragSource();
if (target.parentNode) { if (target.parentNode) {
$$('.over', target.parentNode).forEach((t) => t.classList.remove('over')); $$('.over', target.parentNode).forEach(t => t.classList.remove('over'));
} }
} }

View file

@ -48,7 +48,7 @@ export function delegate<K extends keyof PhilomenaAvailableEventsMap, Target ext
event: K, event: K,
selectors: Record<string, (e: PhilomenaAvailableEventsMap[K], target: Target) => void | boolean>, selectors: Record<string, (e: PhilomenaAvailableEventsMap[K], target: Target) => void | boolean>,
) { ) {
node.addEventListener(event, (e) => { node.addEventListener(event, e => {
for (const selector in selectors) { for (const selector in selectors) {
const evtTarget = e.target as EventTarget | Target | null; const evtTarget = e.target as EventTarget | Target | null;
if (evtTarget && 'closest' in evtTarget && typeof evtTarget.closest === 'function') { if (evtTarget && 'closest' in evtTarget && typeof evtTarget.closest === 'function') {

View file

@ -117,7 +117,7 @@ export function spoilerThumb(img: HTMLDivElement, spoilerUri: string, reason: st
switch (window.booru.spoilerType) { switch (window.booru.spoilerType) {
case 'click': case 'click':
img.addEventListener('click', (event) => { img.addEventListener('click', event => {
if (showThumb(img)) event.preventDefault(); if (showThumb(img)) event.preventDefault();
}); });
img.addEventListener('mouseleave', () => hideThumb(img, spoilerUri, reason)); img.addEventListener('mouseleave', () => hideThumb(img, spoilerUri, reason));

View file

@ -133,7 +133,7 @@ export class LocalAutocompleter {
} }
// Add if not filtering or no associations are filtered // Add if not filtering or no associations are filtered
if (unfilter || hiddenTags.findIndex((ht) => result.associations.includes(ht)) === -1) { if (unfilter || hiddenTags.findIndex(ht => result.associations.includes(ht)) === -1) {
results[result.name] = result; results[result.name] = result;
} }
} }

View file

@ -30,7 +30,7 @@ function sortTags(hidden: boolean, a: TagData, b: TagData): number {
export function getHiddenTags(): TagData[] { export function getHiddenTags(): TagData[] {
return unique(window.booru.hiddenTagList) return unique(window.booru.hiddenTagList)
.map((tagId) => getTag(tagId)) .map(tagId => getTag(tagId))
.sort(sortTags.bind(null, true)); .sort(sortTags.bind(null, true));
} }
@ -38,8 +38,8 @@ export function getSpoileredTags(): TagData[] {
if (window.booru.spoilerType === 'off') return []; if (window.booru.spoilerType === 'off') return [];
return unique(window.booru.spoileredTagList) return unique(window.booru.spoileredTagList)
.filter((tagId) => window.booru.ignoredTagList.indexOf(tagId) === -1) .filter(tagId => window.booru.ignoredTagList.indexOf(tagId) === -1)
.map((tagId) => getTag(tagId)) .map(tagId => getTag(tagId))
.sort(sortTags.bind(null, false)); .sort(sortTags.bind(null, false));
} }
@ -49,7 +49,7 @@ export function imageHitsTags(img: HTMLElement, matchTags: TagData[]): TagData[]
return []; return [];
} }
const imageTags = JSON.parse(imageTagsString); const imageTags = JSON.parse(imageTagsString);
return matchTags.filter((t) => imageTags.indexOf(t.id) !== -1); return matchTags.filter(t => imageTags.indexOf(t.id) !== -1);
} }
export function imageHitsComplex(img: HTMLElement, matchComplex: AstMatcher) { export function imageHitsComplex(img: HTMLElement, matchComplex: AstMatcher) {
@ -63,7 +63,7 @@ export function displayTags(tags: TagData[]): string {
extras; extras;
if (otherTags.length > 0) { if (otherTags.length > 0) {
extras = otherTags.map((tag) => escapeHtml(tag.name)).join(', '); extras = otherTags.map(tag => escapeHtml(tag.name)).join(', ');
list += `<span title="${extras}">, ${extras}</span>`; list += `<span title="${extras}">, ${extras}</span>`;
} }

View file

@ -68,7 +68,7 @@ export function mockStorageImpl(): MockStorageImplApi {
delete tempStorage[key]; delete tempStorage[key];
}, },
}); });
const forceStorageError: MockStorageImplApi['forceStorageError'] = (func) => { const forceStorageError: MockStorageImplApi['forceStorageError'] = func => {
shouldThrow = true; shouldThrow = true;
const value = func(); const value = func();
if (!(value instanceof Promise)) { if (!(value instanceof Promise)) {
@ -80,7 +80,7 @@ export function mockStorageImpl(): MockStorageImplApi {
shouldThrow = false; shouldThrow = false;
}); });
}; };
const setStorageValue: MockStorageImplApi['setStorageValue'] = (value) => { const setStorageValue: MockStorageImplApi['setStorageValue'] = value => {
tempStorage = value; tempStorage = value;
}; };
const clearStorage = () => setStorageValue({}); const clearStorage = () => setStorageValue({});

View file

@ -11,13 +11,13 @@ export default defineConfig(({ command, mode }: ConfigEnv): UserConfig => {
const isDev = command !== 'build' && mode !== 'test'; const isDev = command !== 'build' && mode !== 'test';
const targets = new Map(); const targets = new Map();
fs.readdirSync(path.resolve(__dirname, 'css/themes/')).forEach((name) => { fs.readdirSync(path.resolve(__dirname, 'css/themes/')).forEach(name => {
const m = name.match(/([-a-z]+).css/); const m = name.match(/([-a-z]+).css/);
if (m) targets.set(`css/${m[1]}`, `./css/themes/${m[1]}.css`); if (m) targets.set(`css/${m[1]}`, `./css/themes/${m[1]}.css`);
}); });
fs.readdirSync(path.resolve(__dirname, 'css/options/')).forEach((name) => { fs.readdirSync(path.resolve(__dirname, 'css/options/')).forEach(name => {
const m = name.match(/([-a-z]+).css/); const m = name.match(/([-a-z]+).css/);
if (m) targets.set(`css/options/${m[1]}`, `./css/options/${m[1]}.css`); if (m) targets.set(`css/options/${m[1]}`, `./css/options/${m[1]}.css`);