Improve async/await usage, and sort init calls in index.js (#17386)

* clean up async/await, and sort init calls in `index.js
* use `const _promise` to indicate that we do not need await an async function
This commit is contained in:
wxiaoguang 2021-11-09 17:27:25 +08:00 committed by GitHub
parent 3a693bd18c
commit bb71ceeeb2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 223 additions and 211 deletions

View File

@ -135,11 +135,11 @@ export function initGlobalCommon() {
});
}
export async function initGlobalDropzone() {
export function initGlobalDropzone() {
// Dropzone
for (const el of document.querySelectorAll('.dropzone')) {
const $dropzone = $(el);
await createDropzone(el, {
const _promise = createDropzone(el, {
url: $dropzone.data('upload-url'),
headers: {'X-Csrf-Token': csrfToken},
maxFiles: $dropzone.data('max-file'),

View File

@ -2,7 +2,7 @@ import {htmlEscape} from 'escape-goat';
const {appSubUrl} = window.config;
export function initSearchUserBox() {
export function initCompSearchUserBox() {
const $searchUserBox = $('#search-user-box');
$searchUserBox.search({
minCharacters: 2,

View File

@ -1,6 +1,6 @@
const {csrfToken} = window.config;
export function initWebHookEditor() {
export function initCompWebHookEditor() {
if ($('.new.webhook').length === 0) {
return;
}

View File

@ -1,24 +0,0 @@
export function initDiffShowMore() {
$('#diff-files, #diff-file-boxes').on('click', '#diff-show-more-files, #diff-show-more-files-stats', (e) => {
e.preventDefault();
if ($(e.target).hasClass('disabled')) {
return;
}
$('#diff-show-more-files, #diff-show-more-files-stats').addClass('disabled');
const url = $('#diff-show-more-files, #diff-show-more-files-stats').data('href');
$.ajax({
type: 'GET',
url,
}).done((resp) => {
if (!resp || resp.html === '' || resp.empty) {
$('#diff-show-more-files, #diff-show-more-files-stats').removeClass('disabled');
return;
}
$('#diff-too-many-files-stats').remove();
$('#diff-files').append($(resp).find('#diff-files li'));
$('#diff-incomplete').replaceWith($(resp).find('#diff-file-boxes').children());
});
});
}

View File

@ -3,7 +3,6 @@ export default async function createDropzone(el, opts) {
import(/* webpackChunkName: "dropzone" */'dropzone'),
import(/* webpackChunkName: "dropzone" */'dropzone/dist/dropzone.css'),
]);
Dropzone.autoDiscover = false;
return new Dropzone(el, opts);
}

View File

@ -2,7 +2,7 @@ import Vue from 'vue';
import ActivityHeatmap from '../components/ActivityHeatmap.vue';
export default async function initHeatmap() {
export default function initHeatmap() {
const el = document.getElementById('user-heatmap');
if (!el) return;
@ -24,7 +24,7 @@ export default async function initHeatmap() {
new View().$mount(el);
} catch (err) {
console.error(err);
console.error('Heatmap failed to load', err);
el.textContent = 'Heatmap failed to load';
}
}

View File

@ -29,7 +29,7 @@ function getDefaultSvgBoundsIfUndefined(svgXml, src) {
}
}
export default async function initImageDiff() {
export default function initImageDiff() {
function createContext(image1, image2) {
const size1 = {
width: image1 && image1.width || 0,

View File

@ -1,40 +0,0 @@
const {csrfToken} = window.config;
export async function initLastCommitLoader() {
const entryMap = {};
const entries = $('table#repo-files-table tr.notready')
.map((_, v) => {
entryMap[$(v).attr('data-entryname')] = $(v);
return $(v).attr('data-entryname');
})
.get();
if (entries.length === 0) {
return;
}
const lastCommitLoaderURL = $('table#repo-files-table').data('lastCommitLoaderUrl');
if (entries.length > 200) {
$.post(lastCommitLoaderURL, {
_csrf: csrfToken,
}, (data) => {
$('table#repo-files-table').replaceWith(data);
});
return;
}
$.post(lastCommitLoaderURL, {
_csrf: csrfToken,
'f': entries,
}, (data) => {
$(data).find('tr').each((_, row) => {
if (row.className === 'commit-list') {
$('table#repo-files-table .commit-list').replaceWith(row);
return;
}
entryMap[$(row).attr('data-entryname')].replaceWith(row);
});
});
}

View File

@ -40,7 +40,7 @@ async function receiveUpdateCount(event) {
}
}
export async function initNotificationCount() {
export function initNotificationCount() {
const notificationCount = $('.notification_count');
if (!notificationCount.length) {
@ -66,7 +66,7 @@ export async function initNotificationCount() {
return;
}
if (event.data.type === 'notification-count') {
receiveUpdateCount(event.data);
const _promise = receiveUpdateCount(event.data);
} else if (event.data.type === 'error') {
console.error(event.data);
} else if (event.data.type === 'logout') {

View File

@ -1,6 +1,47 @@
const {csrfToken} = window.config;
export function initRepoCommitButton() {
$('.commit-button').on('click', function (e) {
e.preventDefault();
$(this).parent().find('.commit-body').toggle();
});
}
export function initRepoCommitLastCommitLoader() {
const entryMap = {};
const entries = $('table#repo-files-table tr.notready')
.map((_, v) => {
entryMap[$(v).attr('data-entryname')] = $(v);
return $(v).attr('data-entryname');
})
.get();
if (entries.length === 0) {
return;
}
const lastCommitLoaderURL = $('table#repo-files-table').data('lastCommitLoaderUrl');
if (entries.length > 200) {
$.post(lastCommitLoaderURL, {
_csrf: csrfToken,
}, (data) => {
$('table#repo-files-table').replaceWith(data);
});
return;
}
$.post(lastCommitLoaderURL, {
_csrf: csrfToken,
'f': entries,
}, (data) => {
$(data).find('tr').each((_, row) => {
if (row.className === 'commit-list') {
$('table#repo-files-table .commit-list').replaceWith(row);
return;
}
entryMap[$(row).attr('data-entryname')].replaceWith(row);
});
});
}

View File

@ -79,3 +79,28 @@ export function initRepoDiffConversationNav() {
window.location.href = `#${anchor}`;
});
}
export function initRepoDiffShowMore() {
$('#diff-files, #diff-file-boxes').on('click', '#diff-show-more-files, #diff-show-more-files-stats', (e) => {
e.preventDefault();
if ($(e.target).hasClass('disabled')) {
return;
}
$('#diff-show-more-files, #diff-show-more-files-stats').addClass('disabled');
const url = $('#diff-show-more-files, #diff-show-more-files-stats').data('href');
$.ajax({
type: 'GET',
url,
}).done((resp) => {
if (!resp || resp.html === '' || resp.empty) {
$('#diff-show-more-files, #diff-show-more-files-stats').removeClass('disabled');
return;
}
$('#diff-too-many-files-stats').remove();
$('#diff-files').append($(resp).find('#diff-files li'));
$('#diff-incomplete').replaceWith($(resp).find('#diff-file-boxes').children());
});
});
}

View File

@ -24,7 +24,7 @@ function initEditPreviewTab($form) {
_csrf: csrfToken,
mode,
context,
text: $form.find(`.tab[data-tab="${$tabMenu.data('write')}"] textarea`).val()
text: $form.find(`.tab[data-tab="${$tabMenu.data('write')}"] textarea`).val(),
}, (data) => {
const $previewPanel = $form.find(`.tab[data-tab="${$tabMenu.data('preview')}"]`);
$previewPanel.html(data);
@ -42,7 +42,7 @@ function initEditDiffTab($form) {
$.post($this.data('url'), {
_csrf: csrfToken,
context: $this.data('context'),
content: $form.find(`.tab[data-tab="${$tabMenu.data('write')}"] textarea`).val()
content: $form.find(`.tab[data-tab="${$tabMenu.data('write')}"] textarea`).val(),
}, (data) => {
const $diffPreviewPanel = $form.find(`.tab[data-tab="${$tabMenu.data('diff')}"]`);
$diffPreviewPanel.html(data);
@ -75,7 +75,7 @@ function getCursorPosition($e) {
return pos;
}
export async function initRepoEditor() {
export function initRepoEditor() {
initEditorForm();
$('.js-quick-pull-choice-option').on('change', function () {
@ -134,47 +134,49 @@ export async function initRepoEditor() {
const $editArea = $('.repository.editor textarea#edit_area');
if (!$editArea.length) return;
const editor = await createCodeEditor($editArea[0], $editFilename[0], previewFileModes);
(async () => {
const editor = await createCodeEditor($editArea[0], $editFilename[0], previewFileModes);
// Using events from https://github.com/codedance/jquery.AreYouSure#advanced-usage
// to enable or disable the commit button
const $commitButton = $('#commit-button');
const $editForm = $('.ui.edit.form');
const dirtyFileClass = 'dirty-file';
// Using events from https://github.com/codedance/jquery.AreYouSure#advanced-usage
// to enable or disable the commit button
const $commitButton = $('#commit-button');
const $editForm = $('.ui.edit.form');
const dirtyFileClass = 'dirty-file';
// Disabling the button at the start
if ($('input[name="page_has_posted"]').val() !== 'true') {
$commitButton.prop('disabled', true);
}
// Registering a custom listener for the file path and the file content
$editForm.areYouSure({
silent: true,
dirtyClass: dirtyFileClass,
fieldSelector: ':input:not(.commit-form-wrapper :input)',
change() {
const dirty = $(this).hasClass(dirtyFileClass);
$commitButton.prop('disabled', !dirty);
// Disabling the button at the start
if ($('input[name="page_has_posted"]').val() !== 'true') {
$commitButton.prop('disabled', true);
}
});
// Update the editor from query params, if available,
// only after the dirtyFileClass initialization
const params = new URLSearchParams(window.location.search);
const value = params.get('value');
if (value) {
editor.setValue(value);
}
// Registering a custom listener for the file path and the file content
$editForm.areYouSure({
silent: true,
dirtyClass: dirtyFileClass,
fieldSelector: ':input:not(.commit-form-wrapper :input)',
change() {
const dirty = $(this).hasClass(dirtyFileClass);
$commitButton.prop('disabled', !dirty);
},
});
$commitButton.on('click', (event) => {
// A modal which asks if an empty file should be committed
if ($editArea.val().length === 0) {
$('#edit-empty-content-modal').modal({
onApprove() {
$('.edit.form').trigger('submit');
}
}).modal('show');
event.preventDefault();
// Update the editor from query params, if available,
// only after the dirtyFileClass initialization
const params = new URLSearchParams(window.location.search);
const value = params.get('value');
if (value) {
editor.setValue(value);
}
});
$commitButton.on('click', (event) => {
// A modal which asks if an empty file should be committed
if ($editArea.val().length === 0) {
$('#edit-empty-content-modal').modal({
onApprove() {
$('.edit.form').trigger('submit');
},
}).modal('show');
event.preventDefault();
}
});
})();
}

View File

@ -1,4 +1,4 @@
export default async function initGitGraph() {
export default function initRepoGraphGit() {
const graphContainer = document.getElementById('git-graph-container');
if (!graphContainer) return;

View File

@ -104,7 +104,7 @@ function showContentHistoryMenu(issueBaseUrl, $item, commentId) {
});
}
export function initIssueContentHistory() {
export function initRepoIssueContentHistory() {
const issueIndex = $('#issueIndex').val();
const $itemIssue = $('.timeline-item.comment.first');
if (!issueIndex || !$itemIssue.length) return;

View File

@ -259,7 +259,7 @@ export function initRepoCommentForm() {
}
export async function initRepository() {
export function initRepository() {
if ($('.repository').length === 0) {
return;
}
@ -363,7 +363,7 @@ export async function initRepository() {
if ($editContentZone.html().length === 0) {
$editContentZone.html($('#edit-content-form').html());
$textarea = $editContentZone.find('textarea');
attachTribute($textarea.get(), {mentions: true, emoji: true});
await attachTribute($textarea.get(), {mentions: true, emoji: true});
let dz;
const $dropzone = $editContentZone.find('.dropzone');

View File

@ -8,7 +8,7 @@ const $lfsSettings = $('#lfs_settings');
const $lfsEndpoint = $('#lfs_endpoint');
const $items = $('#migrate_items').find('input[type=checkbox]');
export default function initMigration() {
export default function initRepoMigration() {
checkAuth();
setLFSSettingsVisibility();

View File

@ -1,10 +1,6 @@
const {csrfToken} = window.config;
export default async function initProject() {
if (!$('.repository.projects').length) {
return;
}
async function initRepoProjectSortable() {
const {Sortable} = await import(/* webpackChunkName: "sortable" */'sortablejs');
const boardColumns = document.getElementsByClassName('board-column');
@ -60,6 +56,16 @@ export default async function initProject() {
},
);
}
}
export default function initRepoProject() {
if (!$('.repository.projects').length) {
return;
}
(async () => {
await initRepoProjectSortable();
})();
$('.edit-project-board').each(function () {
const projectHeader = $(this).closest('.board-column-header');

View File

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

View File

@ -3,7 +3,7 @@ const {appSubUrl, csrfToken, notificationSettings, enableTimeTracking} = window.
let updateTimeInterval = null; // holds setInterval id when active
export async function initStopwatch() {
export function initStopwatch() {
if (!enableTimeTracking) {
return;
}
@ -135,7 +135,7 @@ async function updateStopwatchData(data) {
$('.stopwatch-cancel').attr('action', `${issueUrl}/times/stopwatch/cancel`);
$('.stopwatch-issue').text(`${repo_owner_name}/${repo_name}#${issue_index}`);
$('.stopwatch-time').text(prettyMilliseconds(seconds * 1000));
updateStopwatchTime(seconds);
await updateStopwatchTime(seconds);
btnEl.removeClass('hidden');
}

View File

@ -7,27 +7,25 @@ import {initDashboardRepoList} from './components/DashboardRepoList.js';
import attachTribute from './features/tribute.js';
import initGlobalCopyToClipboardListener from './features/clipboard.js';
import initContextPopups from './features/contextpopup.js';
import initGitGraph from './features/gitgraph.js';
import initRepoGraphGit from './features/repo-graph.js';
import initHeatmap from './features/heatmap.js';
import initImageDiff from './features/imagediff.js';
import initMigration from './features/migration.js';
import initProject from './features/projects.js';
import initRepoMigration from './features/repo-migration.js';
import initRepoProject from './features/repo-projects.js';
import initServiceWorker from './features/serviceworker.js';
import initTableSort from './features/tablesort.js';
import {initAdminUserListSearchForm} from './features/admin-users.js';
import {initMarkupAnchors} from './markup/anchors.js';
import {initNotificationCount, initNotificationsTable} from './features/notification.js';
import {initLastCommitLoader} from './features/lastcommitloader.js';
import {initIssueContentHistory} from './features/issue-content-history.js';
import {initRepoIssueContentHistory} from './features/repo-issue-content.js';
import {initStopwatch} from './features/stopwatch.js';
import {initDiffShowMore} from './features/diff.js';
import {initCommentContent, initMarkupContent} from './markup/content.js';
import {initUserAuthLinkAccountView, initUserAuthOauth2} from './features/user-auth.js';
import {
initRepoDiffConversationForm,
initRepoDiffFileViewToggle,
initRepoDiffReviewButton,
initRepoDiffReviewButton, initRepoDiffShowMore,
} from './features/repo-diff.js';
import {
initRepoIssueDue,
@ -38,7 +36,7 @@ import {
initRepoPullRequestMergeInstruction,
initRepoPullRequestReview,
} from './features/repo-issue.js';
import {initRepoCommitButton} from './features/repo-commit.js';
import {initRepoCommitButton, initRepoCommitLastCommitLoader} from './features/repo-commit.js';
import {
initFootLanguageMenu,
initGlobalButtonClickOnEnter,
@ -68,9 +66,9 @@ import {initOrgTeamSearchRepoBox, initOrgTeamSettings} from './features/org-team
import {initUserAuthU2fAuth, initUserAuthU2fRegister} from './features/user-auth-u2f.js';
import {initRepoRelease, initRepoReleaseEditor} from './features/repo-release.js';
import {initRepoEditor} from './features/repo-editor.js';
import {initSearchUserBox} from './features/comp/SearchUserBox.js';
import {initCompSearchUserBox} from './features/comp/SearchUserBox.js';
import {initInstall} from './features/install.js';
import {initWebHookEditor} from './features/comp/WebHookEditor.js';
import {initCompWebHookEditor} from './features/comp/WebHookEditor.js';
import {initCommonIssue} from './features/common-issue.js';
import {initRepoBranchButton} from './features/repo-branch.js';
import {initCommonOrganization} from './features/common-organization.js';
@ -82,85 +80,90 @@ $.fn.tab.settings.silent = true;
initVueEnv();
$(document).ready(async () => {
$(document).ready(() => {
initGlobalCommon();
initGlobalDropzone();
initGlobalLinkActions();
initGlobalButtons();
initRepoBranchButton();
initCommonIssue();
initSearchUserBox();
initRepoSettingSearchTeamBox();
initOrgTeamSearchRepoBox();
initGlobalButtonClickOnEnter();
initMarkupAnchors();
initCommentContent();
initRepoCommentForm();
initInstall();
initRepoArchiveLinks();
initRepository();
initMigration();
initRepoWikiForm();
initRepoEditor();
initCommonOrganization();
initWebHookEditor();
initAdminCommon();
initRepoCodeView();
initRepoActivityTopAuthorsChart();
initDashboardRepoList();
initOrgTeamSettings();
initGlobalButtons();
initGlobalCopyToClipboardListener();
initGlobalDropzone();
initGlobalEnterQuickSubmit();
initGlobalFormDirtyLeaveConfirm();
initGlobalLinkActions();
attachTribute(document.querySelectorAll('#content, .emoji-input'));
initCommonIssue();
initCommonOrganization();
initCompSearchUserBox();
initCompWebHookEditor();
initInstall();
initHeadNavbarContentToggle();
initFootLanguageMenu();
initCommentContent();
initContextPopups();
initHeatmap();
initImageDiff();
initMarkupAnchors();
initMarkupContent();
initServiceWorker();
initSshKeyFormParser();
initStopwatch();
initTableSort();
initAdminCommon();
initAdminEmails();
initAdminUserListSearchForm();
initDashboardRepoList();
initNotificationCount();
initNotificationsTable();
initOrgTeamSearchRepoBox();
initOrgTeamSettings();
initRepoActivityTopAuthorsChart();
initRepoArchiveLinks();
initRepoBranchButton();
initRepoCodeView();
initRepoCommentForm();
initRepoCommitButton();
initRepoCommitLastCommitLoader();
initRepoDiffConversationForm();
initRepoDiffFileViewToggle();
initRepoDiffReviewButton();
initRepoDiffShowMore();
initRepoEditor();
initRepoGraphGit();
initRepoIssueContentHistory();
initRepoIssueDue();
initRepoIssueList();
initRepoIssueReferenceRepositorySearch();
initRepoIssueTimeTracking();
initRepoIssueWipTitle();
initRepoMigration();
initRepoMigrationStatusChecker();
initRepoProject();
initRepoPullRequestMergeInstruction();
initRepoPullRequestReview();
initRepoRelease();
initRepoReleaseEditor();
initRepoSettingGitHook();
initRepoSettingSearchTeamBox();
initRepoSettingsCollaboration();
initRepoTemplateSearch();
initRepoTopicBar();
initRepoWikiForm();
initRepository();
initUserAuthLinkAccountView();
initUserAuthOauth2();
initUserAuthU2fAuth();
initUserAuthU2fRegister();
initRepoIssueList();
initRepoIssueTimeTracking();
initRepoIssueDue();
initRepoIssueWipTitle();
initRepoPullRequestReview();
initRepoMigrationStatusChecker();
initRepoTemplateSearch();
initRepoIssueReferenceRepositorySearch();
initContextPopups();
initTableSort();
initNotificationsTable();
initLastCommitLoader();
initRepoPullRequestMergeInstruction();
initRepoDiffFileViewToggle();
initRepoReleaseEditor();
initRepoRelease();
initDiffShowMore();
initIssueContentHistory();
initAdminUserListSearchForm();
initGlobalCopyToClipboardListener();
initUserAuthOauth2();
initRepoDiffReviewButton();
initRepoCommitButton();
initAdminEmails();
initGlobalEnterQuickSubmit();
initSshKeyFormParser();
initGlobalFormDirtyLeaveConfirm();
initUserSettings();
initRepoSettingsCollaboration();
initUserAuthLinkAccountView();
initRepoDiffConversationForm();
// parallel init of async loaded features
await Promise.all([
attachTribute(document.querySelectorAll('#content, .emoji-input')),
initGitGraph(),
initHeatmap(),
initProject(),
initServiceWorker(),
initNotificationCount(),
initStopwatch(),
initMarkupContent(),
initRepoSettingGitHook(),
initImageDiff(),
]);
});

View File

@ -2,8 +2,8 @@ import {renderMermaid} from './mermaid.js';
import {initMarkupTasklist} from './tasklist.js';
// code that runs for all markup content
export async function initMarkupContent() {
await renderMermaid(document.querySelectorAll('code.language-mermaid'));
export function initMarkupContent() {
const _promise = renderMermaid(document.querySelectorAll('code.language-mermaid'));
}
// code that only runs for comments