Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 3 commits into from Mar 25, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions web_src/js/components/DiffCommitSelector.vue
Expand Up @@ -103,7 +103,7 @@ export default {
this.menuVisible = !this.menuVisible;
// load our commits when the menu is not yet visible (it'll be toggled after loading)
// 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;
try {
await this.fetchCommits();
Expand Down Expand Up @@ -216,7 +216,7 @@ export default {
<div
v-if="lastReviewCommitSha != null" role="menuitem"
class="vertical item"
:class="{disabled: commitsSinceLastReview === 0}"
:class="{disabled: !commitsSinceLastReview}"
@keydown.enter="changesSinceLastReviewClick()"
@click="changesSinceLastReviewClick()"
>
Expand Down
2 changes: 1 addition & 1 deletion web_src/js/components/RepoActionView.vue
Expand Up @@ -453,7 +453,7 @@ export function initRepositoryActionView() {
{{ locale.showFullScreen }}
</a>
<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>
{{ locale.downloadLogs }}
</a>
Expand Down
8 changes: 5 additions & 3 deletions web_src/js/components/RepoBranchTagSelector.vue
Expand Up @@ -19,17 +19,19 @@ const sfc = {
});

// 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;
},
showNoResults() {
return this.filteredItems.length === 0 && !this.showCreateNewBranch;
return !this.filteredItems.length && !this.showCreateNewBranch;
},
showCreateNewBranch() {
if (this.disableCreateBranch || !this.searchTerm) {
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() {
return `${this.repoLink}/branches/_new/${this.branchNameSubURL}`;
Expand Down
4 changes: 1 addition & 3 deletions web_src/js/features/admin/common.js
Expand Up @@ -6,9 +6,7 @@ import {POST} from '../../modules/fetch.js';
const {appSubUrl} = window.config;

export function initAdminCommon() {
if ($('.page-content.admin').length === 0) {
return;
}
if (!$('.page-content.admin').length) return;

// check whether appUrl(ROOT_URL) is correct, if not, show an error message
checkAppUrl();
Expand Down
2 changes: 1 addition & 1 deletion web_src/js/features/common-global.js
Expand Up @@ -19,7 +19,7 @@ const {appUrl, appSubUrl, csrfToken, i18n} = window.config;
export function initGlobalFormDirtyLeaveConfirm() {
// 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'.
if ($('.user.signin').length === 0) {
if (!$('.user.signin').length) {
$('form:not(.ignore-dirty)').areYouSure();
}
}
Expand Down
2 changes: 1 addition & 1 deletion web_src/js/features/comp/SearchUserBox.js
Expand Up @@ -34,7 +34,7 @@ export function initCompSearchUserBox() {
}
});

if (allowEmailInput && items.length === 0 && looksLikeEmailAddressCheck.test(searchQuery)) {
if (allowEmailInput && !items.length && looksLikeEmailAddressCheck.test(searchQuery)) {
const resultItem = {
title: searchQuery,
description: allowEmailDescription,
Expand Down
3 changes: 1 addition & 2 deletions web_src/js/features/repo-diff.js
Expand Up @@ -212,8 +212,7 @@ function initRepoDiffShowMore() {

export function initRepoDiffView() {
initRepoDiffConversationForm();
const $diffFileList = $('#diff-file-list');
if ($diffFileList.length === 0) return;
if (!$('#diff-file-list').length) return;
initDiffFileTree();
initDiffCommitSelect();
initRepoDiffShowMore();
Expand Down
10 changes: 4 additions & 6 deletions web_src/js/features/repo-editor.js
Expand Up @@ -39,11 +39,9 @@ function initEditPreviewTab($form) {
}

function initEditorForm() {
if ($('.repository .edit.form').length === 0) {
return;
}

initEditPreviewTab($('.repository .edit.form'));
const $form = $('.repository .edit.form');
if (!$form) return;
initEditPreviewTab($form);
}

function getCursorPosition($e) {
Expand Down Expand Up @@ -165,7 +163,7 @@ export function initRepoEditor() {

commitButton?.addEventListener('click', (e) => {
// A modal which asks if an empty file should be committed
if ($editArea.val().length === 0) {
if (!$editArea.val()) {
$('#edit-empty-content-modal').modal({
onApprove() {
$('.edit.form').trigger('submit');
Expand Down
2 changes: 1 addition & 1 deletion web_src/js/features/repo-findfile.js
Expand Up @@ -77,7 +77,7 @@ function filterRepoFiles(filter) {

const filterResult = filterRepoFilesWeighted(files, filter);

toggleElem(repoFindFileNoResult, filterResult.length === 0);
toggleElem(repoFindFileNoResult, !filterResult.length);
for (const r of filterResult) {
const row = document.createElement('tr');
const cell = document.createElement('td');
Expand Down
4 changes: 2 additions & 2 deletions web_src/js/features/repo-home.js
Expand Up @@ -151,11 +151,11 @@ export function initRepoTopicBar() {

$.fn.form.settings.rules.validateTopic = function (_values, regExp) {
const $topics = $topicDropdown.children('a.ui.label');
const status = $topics.length === 0 || $topics.last().attr('data-value').match(regExp);
const status = !$topics.length || $topics.last().attr('data-value').match(regExp);
if (!status) {
$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({
Expand Down
14 changes: 6 additions & 8 deletions web_src/js/features/repo-issue.js
Expand Up @@ -362,7 +362,7 @@ export async function updateIssuesMeta(url, action, issue_ids, id) {
}

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) {
e.preventDefault();
Expand All @@ -377,15 +377,15 @@ export function initRepoIssueComments() {

$(document).on('click', (event) => {
const $urlTarget = $(':target');
if ($urlTarget.length === 0) return;
if (!$urlTarget.length) return;

const urlTargetId = $urlTarget.attr('id');
if (!urlTargetId) return;
if (!/^(issue|pull)(comment)?-\d+$/.test(urlTargetId)) return;

const $target = $(event.target);

if ($target.closest(`#${urlTargetId}`).length === 0) {
if (!$target.closest(`#${urlTargetId}`).length) {
const scrollPosition = $(window).scrollTop();
window.location.hash = '';
$(window).scrollTop(scrollPosition);
Expand Down Expand Up @@ -478,9 +478,7 @@ export function initRepoPullRequestReview() {
}

// The following part is only for diff views
if ($('.repository.pull.diff').length === 0) {
return;
}
if (!$('.repository.pull.diff').length) return;

const $reviewBtn = $('.js-btn-review');
const $panel = $reviewBtn.parent().find('.review-box-panel');
Expand Down Expand Up @@ -529,7 +527,7 @@ export function initRepoPullRequestReview() {

const $td = $ntr.find(`.add-comment-${side}`);
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 {
const response = await GET($(this).closest('[data-new-comment-url]').attr('data-new-comment-url'));
const html = await response.text();
Expand Down Expand Up @@ -626,7 +624,7 @@ export function initRepoIssueTitleEdit() {
};

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());
await pullrequest_targetbranch_change(pullrequest_target_update_url);
} else {
Expand Down
12 changes: 4 additions & 8 deletions web_src/js/features/repo-legacy.js
Expand Up @@ -50,9 +50,7 @@ function reloadConfirmDraftComment() {

export function initRepoCommentForm() {
const $commentForm = $('.comment.form');
if ($commentForm.length === 0) {
return;
}
if (!$commentForm.length) return;

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
Expand Down Expand Up @@ -202,7 +200,7 @@ export function initRepoCommentForm() {
$($(this).data('id-selector')).addClass('gt-hidden');
}
});
if (listIds.length === 0) {
if (!listIds.length) {
$noSelect.removeClass('gt-hidden');
} else {
$noSelect.addClass('gt-hidden');
Expand Down Expand Up @@ -329,7 +327,7 @@ async function onEditContent(event) {
let comboMarkdownEditor;

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 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
Expand Down Expand Up @@ -482,9 +480,7 @@ async function onEditContent(event) {
}

export function initRepository() {
if ($('.page-content.repository').length === 0) {
return;
}
if (!$('.page-content.repository').length) return;

initRepoBranchTagSelector('.js-branch-tag-selector');

Expand Down
2 changes: 1 addition & 1 deletion web_src/js/features/repo-settings.js
Expand Up @@ -71,7 +71,7 @@ export function initRepoSettingSearchTeamBox() {
}

export function initRepoSettingGitHook() {
if ($('.edit.githook').length === 0) return;
if (!$('.edit.githook').length) return;
const filename = document.querySelector('.hook-filename').textContent;
const _promise = createMonaco($('#content')[0], filename, {language: 'shell'});
}
Expand Down
2 changes: 1 addition & 1 deletion web_src/js/features/user-settings.js
@@ -1,7 +1,7 @@
import {hideElem, showElem} from '../utils/dom.js';

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');
if (!usernameInput) return;
Expand Down