1
0
Fork 0
forked from forgejo/forgejo

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');
}