Remove jQuery AJAX from the `repo-issue.js` file (#29776)

Removed all jQuery AJAX calls and replaced with our fetch wrapper.

Tested the following functionalities and they work as before:
- due-date update
- comment deletion
- branch update by merge or rebase
- allow edits from maintainers button
- reviewer addition or deletion
- WIP toggle button
- new diff code comment button
- issue title edit button

# Demo using `fetch` instead of jQuery AJAX
## Updating the due-date of an issue

![due_date](https://github.com/go-gitea/gitea/assets/20454870/7de395d3-63e8-49e8-9a13-8d14fc26810d)

## Deleting a comment

![comment_delete](https://github.com/go-gitea/gitea/assets/20454870/2814e695-44e3-4548-9ee7-7b437bef4b01)

## Updating a branch in a pull request

![branch_update](https://github.com/go-gitea/gitea/assets/20454870/137da77e-acc4-4984-a1bc-be58583bf52a)

## Checking and unchecking the "Allow edits from maintainers" checkbox

![allow_edits](https://github.com/go-gitea/gitea/assets/20454870/8d4829af-5813-432d-90ef-da057f8cdafc)

## Requesting review and removing review request

![reviewer_addition](https://github.com/go-gitea/gitea/assets/20454870/08f210e0-be3f-41af-b271-214a1dd2d0ba)

## Toggling the WIP status of a pull request

![wip](https://github.com/go-gitea/gitea/assets/20454870/dea5e668-1c89-4f3d-a5d6-4c26aefc4814)

## Clicking the new code comment button on the diff page

![code_comment](https://github.com/go-gitea/gitea/assets/20454870/1d17174e-3bba-4cf8-81fe-c3a2c21f80b9)

## Editing the issue title and target branch

![issue_title](https://github.com/go-gitea/gitea/assets/20454870/7099888e-81c0-47d4-9371-8e4469e9e519)

---------

Signed-off-by: Yarden Shoham <git@yardenshoham.com>
Co-authored-by: silverwind <me@silverwind.io>
This commit is contained in:
Yarden Shoham 2024-03-14 23:36:17 +02:00 committed by GitHub
parent ce085b26fc
commit 0679e60c77
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 113 additions and 83 deletions

View File

@ -6,8 +6,9 @@ import {setFileFolding} from './file-fold.js';
import {getComboMarkdownEditor, initComboMarkdownEditor} from './comp/ComboMarkdownEditor.js'; import {getComboMarkdownEditor, initComboMarkdownEditor} from './comp/ComboMarkdownEditor.js';
import {toAbsoluteUrl} from '../utils.js'; import {toAbsoluteUrl} from '../utils.js';
import {initDropzone} from './common-global.js'; import {initDropzone} from './common-global.js';
import {POST, GET} from '../modules/fetch.js';
const {appSubUrl, csrfToken} = window.config; const {appSubUrl} = window.config;
export function initRepoIssueTimeTracking() { export function initRepoIssueTimeTracking() {
$(document).on('click', '.issue-add-time', () => { $(document).on('click', '.issue-add-time', () => {
@ -40,7 +41,7 @@ export function initRepoIssueTimeTracking() {
}); });
} }
function updateDeadline(deadlineString) { async function updateDeadline(deadlineString) {
hideElem($('#deadline-err-invalid-date')); hideElem($('#deadline-err-invalid-date'));
$('#deadline-loader').addClass('loading'); $('#deadline-loader').addClass('loading');
@ -56,23 +57,21 @@ function updateDeadline(deadlineString) {
realDeadline = new Date(newDate); realDeadline = new Date(newDate);
} }
$.ajax(`${$('#update-issue-deadline-form').attr('action')}`, { try {
data: JSON.stringify({ const response = await POST($('#update-issue-deadline-form').attr('action'), {
due_date: realDeadline, data: {due_date: realDeadline}
}), });
headers: {
'X-Csrf-Token': csrfToken, if (response.ok) {
},
contentType: 'application/json',
type: 'POST',
success() {
window.location.reload(); window.location.reload();
}, } else {
error() { throw new Error('Invalid response');
}
} catch (error) {
console.error(error);
$('#deadline-loader').removeClass('loading'); $('#deadline-loader').removeClass('loading');
showElem($('#deadline-err-invalid-date')); showElem($('#deadline-err-invalid-date'));
}, }
});
} }
export function initRepoIssueDue() { export function initRepoIssueDue() {
@ -156,12 +155,12 @@ export function initRepoIssueSidebarList() {
export function initRepoIssueCommentDelete() { export function initRepoIssueCommentDelete() {
// Delete comment // Delete comment
$(document).on('click', '.delete-comment', function () { $(document).on('click', '.delete-comment', async function () {
const $this = $(this); const $this = $(this);
if (window.confirm($this.data('locale'))) { if (window.confirm($this.data('locale'))) {
$.post($this.data('url'), { try {
_csrf: csrfToken, const response = await POST($this.data('url'));
}).done(() => { if (!response.ok) throw new Error('Failed to delete comment');
const $conversationHolder = $this.closest('.conversation-holder'); const $conversationHolder = $this.closest('.conversation-holder');
// Check if this was a pending comment. // Check if this was a pending comment.
@ -186,7 +185,9 @@ export function initRepoIssueCommentDelete() {
} }
$conversationHolder.remove(); $conversationHolder.remove();
} }
}); } catch (error) {
console.error(error);
}
} }
return false; return false;
}); });
@ -226,15 +227,26 @@ export function initRepoIssueCodeCommentCancel() {
export function initRepoPullRequestUpdate() { export function initRepoPullRequestUpdate() {
// Pull Request update button // Pull Request update button
const $pullUpdateButton = $('.update-button > button'); const $pullUpdateButton = $('.update-button > button');
$pullUpdateButton.on('click', function (e) { $pullUpdateButton.on('click', async function (e) {
e.preventDefault(); e.preventDefault();
const $this = $(this); const $this = $(this);
const redirect = $this.data('redirect'); const redirect = $this.data('redirect');
$this.addClass('loading'); $this.addClass('loading');
$.post($this.data('do'), { let response;
_csrf: csrfToken try {
}).done((data) => { response = await POST($this.data('do'));
if (data.redirect) { } catch (error) {
console.error(error);
} finally {
$this.removeClass('loading');
}
let data;
try {
data = await response?.json(); // the response is probably not a JSON
} catch (error) {
console.error(error);
}
if (data?.redirect) {
window.location.href = data.redirect; window.location.href = data.redirect;
} else if (redirect) { } else if (redirect) {
window.location.href = redirect; window.location.href = redirect;
@ -242,7 +254,6 @@ export function initRepoPullRequestUpdate() {
window.location.reload(); window.location.reload();
} }
}); });
});
$('.update-button > .dropdown').dropdown({ $('.update-button > .dropdown').dropdown({
onChange(_text, _value, $choice) { onChange(_text, _value, $choice) {
@ -267,20 +278,24 @@ export function initRepoPullRequestAllowMaintainerEdit() {
const promptError = $checkbox.attr('data-prompt-error'); const promptError = $checkbox.attr('data-prompt-error');
$checkbox.checkbox({ $checkbox.checkbox({
'onChange': () => { 'onChange': async () => {
const checked = $checkbox.checkbox('is checked'); const checked = $checkbox.checkbox('is checked');
let url = $checkbox.attr('data-url'); let url = $checkbox.attr('data-url');
url += '/set_allow_maintainer_edit'; url += '/set_allow_maintainer_edit';
$checkbox.checkbox('set disabled'); $checkbox.checkbox('set disabled');
$.ajax({url, type: 'POST', try {
data: {_csrf: csrfToken, allow_maintainer_edit: checked}, const response = await POST(url, {
error: () => { data: {allow_maintainer_edit: checked},
showTemporaryTooltip($checkbox[0], promptError);
},
complete: () => {
$checkbox.checkbox('set enabled');
},
}); });
if (!response.ok) {
throw new Error('Failed to update maintainer edit permission');
}
} catch (error) {
console.error(error);
showTemporaryTooltip($checkbox[0], promptError);
} finally {
$checkbox.checkbox('set enabled');
}
}, },
}); });
} }
@ -329,17 +344,15 @@ export function initRepoIssueWipTitle() {
}); });
} }
export async function updateIssuesMeta(url, action, issueIds, elementId) { export async function updateIssuesMeta(url, action, issue_ids, id) {
return $.ajax({ try {
type: 'POST', const response = await POST(url, {data: new URLSearchParams({action, issue_ids, id})});
url, if (!response.ok) {
data: { throw new Error('Failed to update issues meta');
_csrf: csrfToken, }
action, } catch (error) {
issue_ids: issueIds, console.error(error);
id: elementId, }
},
});
} }
export function initRepoIssueComments() { export function initRepoIssueComments() {
@ -511,7 +524,9 @@ 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 === 0 && !ntr.find('button[name="pending_review"]').length) {
const html = await $.get($(this).closest('[data-new-comment-url]').attr('data-new-comment-url')); try {
const response = await GET($(this).closest('[data-new-comment-url]').attr('data-new-comment-url'));
const html = await response.text();
td.html(html); td.html(html);
td.find("input[name='line']").val(idx); td.find("input[name='line']").val(idx);
td.find("input[name='side']").val(side === 'left' ? 'previous' : 'proposed'); td.find("input[name='side']").val(side === 'left' ? 'previous' : 'proposed');
@ -520,6 +535,9 @@ export function initRepoPullRequestReview() {
initDropzone(td.find('.dropzone')[0]); initDropzone(td.find('.dropzone')[0]);
const editor = await initComboMarkdownEditor(td.find('.combo-markdown-editor')); const editor = await initComboMarkdownEditor(td.find('.combo-markdown-editor'));
editor.focus(); editor.focus();
} catch (error) {
console.error(error);
}
} }
}); });
} }
@ -547,11 +565,19 @@ export function initRepoIssueWipToggle() {
const title = toggleWip.getAttribute('data-title'); const title = toggleWip.getAttribute('data-title');
const wipPrefix = toggleWip.getAttribute('data-wip-prefix'); const wipPrefix = toggleWip.getAttribute('data-wip-prefix');
const updateUrl = toggleWip.getAttribute('data-update-url'); const updateUrl = toggleWip.getAttribute('data-update-url');
await $.post(updateUrl, {
_csrf: csrfToken, try {
title: title?.startsWith(wipPrefix) ? title.slice(wipPrefix.length).trim() : `${wipPrefix.trim()} ${title}`, const params = new URLSearchParams();
}); params.append('title', title?.startsWith(wipPrefix) ? title.slice(wipPrefix.length).trim() : `${wipPrefix.trim()} ${title}`);
const response = await POST(updateUrl, {data: params});
if (!response.ok) {
throw new Error('Failed to toggle WIP status');
}
window.location.reload(); window.location.reload();
} catch (error) {
console.error(error);
}
}); });
} }
@ -576,39 +602,43 @@ export function initRepoIssueTitleEdit() {
$('#edit-title').on('click', editTitleToggle); $('#edit-title').on('click', editTitleToggle);
$('#cancel-edit-title').on('click', editTitleToggle); $('#cancel-edit-title').on('click', editTitleToggle);
$('#save-edit-title').on('click', editTitleToggle).on('click', function () { $('#save-edit-title').on('click', editTitleToggle).on('click', async function () {
const pullrequest_targetbranch_change = function (update_url) { const pullrequest_targetbranch_change = async function (update_url) {
const targetBranch = $('#pull-target-branch').data('branch'); const targetBranch = $('#pull-target-branch').data('branch');
const $branchTarget = $('#branch_target'); const $branchTarget = $('#branch_target');
if (targetBranch === $branchTarget.text()) { if (targetBranch === $branchTarget.text()) {
window.location.reload(); window.location.reload();
return false; return false;
} }
$.post(update_url, { try {
_csrf: csrfToken, await POST(update_url, {data: new URLSearchParams({target_branch: targetBranch})});
target_branch: targetBranch } catch (error) {
}).always(() => { console.error(error);
} finally {
window.location.reload(); window.location.reload();
}); }
}; };
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 === 0 || $editInput.val() === $issueTitle.text()) {
$editInput.val($issueTitle.text()); $editInput.val($issueTitle.text());
pullrequest_targetbranch_change(pullrequest_target_update_url); await pullrequest_targetbranch_change(pullrequest_target_update_url);
} else { } else {
$.post($(this).attr('data-update-url'), { try {
_csrf: csrfToken, const params = new URLSearchParams();
title: $editInput.val() params.append('title', $editInput.val());
}, (data) => { const response = await POST($(this).attr('data-update-url'), {data: params});
const data = await response.json();
$editInput.val(data.title); $editInput.val(data.title);
$issueTitle.text(data.title); $issueTitle.text(data.title);
if (pullrequest_target_update_url) { if (pullrequest_target_update_url) {
pullrequest_targetbranch_change(pullrequest_target_update_url); // it will reload the window await pullrequest_targetbranch_change(pullrequest_target_update_url); // it will reload the window
} else { } else {
window.location.reload(); window.location.reload();
} }
}); } catch (error) {
console.error(error);
}
} }
return false; return false;
}); });