0
0
Fork 0
mirror of https://github.com/go-gitea/gitea synced 2024-11-30 03:07:50 +01:00

Refactor all .length === 0 patterns in JS (#30045)

This pattern comes of often during review, so let's fix it once and for
all. Did not test, but changes are trivial enough imho.
This commit is contained in:
silverwind 2024-03-25 19:37:55 +01:00 committed by GitHub
parent f73d891fc4
commit 8fe26fb314
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 31 additions and 40 deletions

View file

@ -103,7 +103,7 @@ export default {
this.menuVisible = !this.menuVisible; this.menuVisible = !this.menuVisible;
// load our commits when the menu is not yet visible (it'll be toggled after loading) // load our commits when the menu is not yet visible (it'll be toggled after loading)
// and we got no commits // and we got no commits
if (this.commits.length === 0 && this.menuVisible && !this.isLoading) { if (!this.commits.length && this.menuVisible && !this.isLoading) {
this.isLoading = true; this.isLoading = true;
try { try {
await this.fetchCommits(); await this.fetchCommits();
@ -216,7 +216,7 @@ export default {
<div <div
v-if="lastReviewCommitSha != null" role="menuitem" v-if="lastReviewCommitSha != null" role="menuitem"
class="vertical item" class="vertical item"
:class="{disabled: commitsSinceLastReview === 0}" :class="{disabled: !commitsSinceLastReview}"
@keydown.enter="changesSinceLastReviewClick()" @keydown.enter="changesSinceLastReviewClick()"
@click="changesSinceLastReviewClick()" @click="changesSinceLastReviewClick()"
> >

View file

@ -453,7 +453,7 @@ export function initRepositoryActionView() {
{{ locale.showFullScreen }} {{ locale.showFullScreen }}
</a> </a>
<div class="divider"/> <div class="divider"/>
<a :class="['item', currentJob.steps.length === 0 ? 'disabled' : '']" :href="run.link+'/jobs/'+jobIndex+'/logs'" target="_blank"> <a :class="['item', !currentJob.steps.length ? 'disabled' : '']" :href="run.link+'/jobs/'+jobIndex+'/logs'" target="_blank">
<i class="icon"><SvgIcon name="octicon-download"/></i> <i class="icon"><SvgIcon name="octicon-download"/></i>
{{ locale.downloadLogs }} {{ locale.downloadLogs }}
</a> </a>

View file

@ -19,17 +19,19 @@ const sfc = {
}); });
// TODO: fix this anti-pattern: side-effects-in-computed-properties // TODO: fix this anti-pattern: side-effects-in-computed-properties
this.active = (items.length === 0 && this.showCreateNewBranch ? 0 : -1); this.active = !items.length && this.showCreateNewBranch ? 0 : -1;
return items; return items;
}, },
showNoResults() { showNoResults() {
return this.filteredItems.length === 0 && !this.showCreateNewBranch; return !this.filteredItems.length && !this.showCreateNewBranch;
}, },
showCreateNewBranch() { showCreateNewBranch() {
if (this.disableCreateBranch || !this.searchTerm) { if (this.disableCreateBranch || !this.searchTerm) {
return false; return false;
} }
return this.items.filter((item) => item.name.toLowerCase() === this.searchTerm.toLowerCase()).length === 0; return !this.items.filter((item) => {
return item.name.toLowerCase() === this.searchTerm.toLowerCase();
}).length;
}, },
formActionUrl() { formActionUrl() {
return `${this.repoLink}/branches/_new/${this.branchNameSubURL}`; return `${this.repoLink}/branches/_new/${this.branchNameSubURL}`;

View file

@ -6,9 +6,7 @@ import {POST} from '../../modules/fetch.js';
const {appSubUrl} = window.config; const {appSubUrl} = window.config;
export function initAdminCommon() { export function initAdminCommon() {
if ($('.page-content.admin').length === 0) { if (!$('.page-content.admin').length) return;
return;
}
// check whether appUrl(ROOT_URL) is correct, if not, show an error message // check whether appUrl(ROOT_URL) is correct, if not, show an error message
checkAppUrl(); checkAppUrl();

View file

@ -19,7 +19,7 @@ const {appUrl, appSubUrl, csrfToken, i18n} = window.config;
export function initGlobalFormDirtyLeaveConfirm() { export function initGlobalFormDirtyLeaveConfirm() {
// Warn users that try to leave a page after entering data into a form. // Warn users that try to leave a page after entering data into a form.
// Except on sign-in pages, and for forms marked as 'ignore-dirty'. // Except on sign-in pages, and for forms marked as 'ignore-dirty'.
if ($('.user.signin').length === 0) { if (!$('.user.signin').length) {
$('form:not(.ignore-dirty)').areYouSure(); $('form:not(.ignore-dirty)').areYouSure();
} }
} }

View file

@ -34,7 +34,7 @@ export function initCompSearchUserBox() {
} }
}); });
if (allowEmailInput && items.length === 0 && looksLikeEmailAddressCheck.test(searchQuery)) { if (allowEmailInput && !items.length && looksLikeEmailAddressCheck.test(searchQuery)) {
const resultItem = { const resultItem = {
title: searchQuery, title: searchQuery,
description: allowEmailDescription, description: allowEmailDescription,

View file

@ -212,8 +212,7 @@ function initRepoDiffShowMore() {
export function initRepoDiffView() { export function initRepoDiffView() {
initRepoDiffConversationForm(); initRepoDiffConversationForm();
const $diffFileList = $('#diff-file-list'); if (!$('#diff-file-list').length) return;
if ($diffFileList.length === 0) return;
initDiffFileTree(); initDiffFileTree();
initDiffCommitSelect(); initDiffCommitSelect();
initRepoDiffShowMore(); initRepoDiffShowMore();

View file

@ -39,11 +39,9 @@ function initEditPreviewTab($form) {
} }
function initEditorForm() { function initEditorForm() {
if ($('.repository .edit.form').length === 0) { const $form = $('.repository .edit.form');
return; if (!$form) return;
} initEditPreviewTab($form);
initEditPreviewTab($('.repository .edit.form'));
} }
function getCursorPosition($e) { function getCursorPosition($e) {
@ -165,7 +163,7 @@ export function initRepoEditor() {
commitButton?.addEventListener('click', (e) => { commitButton?.addEventListener('click', (e) => {
// A modal which asks if an empty file should be committed // A modal which asks if an empty file should be committed
if ($editArea.val().length === 0) { if (!$editArea.val()) {
$('#edit-empty-content-modal').modal({ $('#edit-empty-content-modal').modal({
onApprove() { onApprove() {
$('.edit.form').trigger('submit'); $('.edit.form').trigger('submit');

View file

@ -77,7 +77,7 @@ function filterRepoFiles(filter) {
const filterResult = filterRepoFilesWeighted(files, filter); const filterResult = filterRepoFilesWeighted(files, filter);
toggleElem(repoFindFileNoResult, filterResult.length === 0); toggleElem(repoFindFileNoResult, !filterResult.length);
for (const r of filterResult) { for (const r of filterResult) {
const row = document.createElement('tr'); const row = document.createElement('tr');
const cell = document.createElement('td'); const cell = document.createElement('td');

View file

@ -153,11 +153,11 @@ export function initRepoTopicBar() {
$.fn.form.settings.rules.validateTopic = function (_values, regExp) { $.fn.form.settings.rules.validateTopic = function (_values, regExp) {
const $topics = $topicDropdown.children('a.ui.label'); const $topics = $topicDropdown.children('a.ui.label');
const status = $topics.length === 0 || $topics.last()[0].getAttribute('data-value').match(regExp); const status = !$topics.length || $topics.last()[0].getAttribute('data-value').match(regExp);
if (!status) { if (!status) {
$topics.last().removeClass('green').addClass('red'); $topics.last().removeClass('green').addClass('red');
} }
return status && $topicDropdown.children('a.ui.label.red').length === 0; return status && !$topicDropdown.children('a.ui.label.red').length;
}; };
$topicForm.form({ $topicForm.form({

View file

@ -362,7 +362,7 @@ export async function updateIssuesMeta(url, action, issue_ids, id) {
} }
export function initRepoIssueComments() { export function initRepoIssueComments() {
if ($('.repository.view.issue .timeline').length === 0) return; if (!$('.repository.view.issue .timeline').length) return;
$('.re-request-review').on('click', async function (e) { $('.re-request-review').on('click', async function (e) {
e.preventDefault(); e.preventDefault();
@ -377,7 +377,7 @@ export function initRepoIssueComments() {
$(document).on('click', (event) => { $(document).on('click', (event) => {
const $urlTarget = $(':target'); const $urlTarget = $(':target');
if ($urlTarget.length === 0) return; if (!$urlTarget.length) return;
const urlTargetId = $urlTarget.attr('id'); const urlTargetId = $urlTarget.attr('id');
if (!urlTargetId) return; if (!urlTargetId) return;
@ -385,7 +385,7 @@ export function initRepoIssueComments() {
const $target = $(event.target); const $target = $(event.target);
if ($target.closest(`#${urlTargetId}`).length === 0) { if (!$target.closest(`#${urlTargetId}`).length) {
const scrollPosition = $(window).scrollTop(); const scrollPosition = $(window).scrollTop();
window.location.hash = ''; window.location.hash = '';
$(window).scrollTop(scrollPosition); $(window).scrollTop(scrollPosition);
@ -478,9 +478,7 @@ export function initRepoPullRequestReview() {
} }
// The following part is only for diff views // The following part is only for diff views
if ($('.repository.pull.diff').length === 0) { if (!$('.repository.pull.diff').length) return;
return;
}
const $reviewBtn = $('.js-btn-review'); const $reviewBtn = $('.js-btn-review');
const $panel = $reviewBtn.parent().find('.review-box-panel'); const $panel = $reviewBtn.parent().find('.review-box-panel');
@ -529,7 +527,7 @@ export function initRepoPullRequestReview() {
const $td = $ntr.find(`.add-comment-${side}`); const $td = $ntr.find(`.add-comment-${side}`);
const $commentCloud = $td.find('.comment-code-cloud'); const $commentCloud = $td.find('.comment-code-cloud');
if ($commentCloud.length === 0 && !$ntr.find('button[name="pending_review"]').length) { if (!$commentCloud.length && !$ntr.find('button[name="pending_review"]').length) {
try { try {
const response = await GET($(this).closest('[data-new-comment-url]').attr('data-new-comment-url')); const response = await GET($(this).closest('[data-new-comment-url]').attr('data-new-comment-url'));
const html = await response.text(); const html = await response.text();
@ -626,7 +624,7 @@ export function initRepoIssueTitleEdit() {
}; };
const pullrequest_target_update_url = $(this).attr('data-target-update-url'); const pullrequest_target_update_url = $(this).attr('data-target-update-url');
if ($editInput.val().length === 0 || $editInput.val() === $issueTitle.text()) { if (!$editInput.val().length || $editInput.val() === $issueTitle.text()) {
$editInput.val($issueTitle.text()); $editInput.val($issueTitle.text());
await pullrequest_targetbranch_change(pullrequest_target_update_url); await pullrequest_targetbranch_change(pullrequest_target_update_url);
} else { } else {

View file

@ -50,9 +50,7 @@ function reloadConfirmDraftComment() {
export function initRepoCommentForm() { export function initRepoCommentForm() {
const $commentForm = $('.comment.form'); const $commentForm = $('.comment.form');
if ($commentForm.length === 0) { if (!$commentForm.length) return;
return;
}
if ($commentForm.find('.field.combo-editor-dropzone').length) { if ($commentForm.find('.field.combo-editor-dropzone').length) {
// at the moment, if a form has multiple combo-markdown-editors, it must be an issue template form // at the moment, if a form has multiple combo-markdown-editors, it must be an issue template form
@ -202,7 +200,7 @@ export function initRepoCommentForm() {
$($(this).data('id-selector')).addClass('tw-hidden'); $($(this).data('id-selector')).addClass('tw-hidden');
} }
}); });
if (listIds.length === 0) { if (!listIds.length) {
$noSelect.removeClass('tw-hidden'); $noSelect.removeClass('tw-hidden');
} else { } else {
$noSelect.addClass('tw-hidden'); $noSelect.addClass('tw-hidden');
@ -329,7 +327,7 @@ async function onEditContent(event) {
let comboMarkdownEditor; let comboMarkdownEditor;
const setupDropzone = async ($dropzone) => { const setupDropzone = async ($dropzone) => {
if ($dropzone.length === 0) return null; if (!$dropzone.length) return null;
let disableRemovedfileEvent = false; // when resetting the dropzone (removeAllFiles), disable the "removedfile" event let disableRemovedfileEvent = false; // when resetting the dropzone (removeAllFiles), disable the "removedfile" event
let fileUuidDict = {}; // to record: if a comment has been saved, then the uploaded files won't be deleted from server when clicking the Remove in the dropzone let fileUuidDict = {}; // to record: if a comment has been saved, then the uploaded files won't be deleted from server when clicking the Remove in the dropzone
@ -482,9 +480,7 @@ async function onEditContent(event) {
} }
export function initRepository() { export function initRepository() {
if ($('.page-content.repository').length === 0) { if (!$('.page-content.repository').length) return;
return;
}
initRepoBranchTagSelector('.js-branch-tag-selector'); initRepoBranchTagSelector('.js-branch-tag-selector');

View file

@ -71,7 +71,7 @@ export function initRepoSettingSearchTeamBox() {
} }
export function initRepoSettingGitHook() { export function initRepoSettingGitHook() {
if ($('.edit.githook').length === 0) return; if (!$('.edit.githook').length) return;
const filename = document.querySelector('.hook-filename').textContent; const filename = document.querySelector('.hook-filename').textContent;
const _promise = createMonaco($('#content')[0], filename, {language: 'shell'}); const _promise = createMonaco($('#content')[0], filename, {language: 'shell'});
} }

View file

@ -1,7 +1,7 @@
import {hideElem, showElem} from '../utils/dom.js'; import {hideElem, showElem} from '../utils/dom.js';
export function initUserSettings() { export function initUserSettings() {
if (document.querySelectorAll('.user.settings.profile').length === 0) return; if (!document.querySelectorAll('.user.settings.profile').length) return;
const usernameInput = document.getElementById('username'); const usernameInput = document.getElementById('username');
if (!usernameInput) return; if (!usernameInput) return;