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

Remove jQuery .text() #30506

Merged
merged 23 commits into from
Jun 10, 2024
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .eslintrc.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ rules:
jquery/no-sizzle: [2]
jquery/no-slide: [2]
jquery/no-submit: [2]
jquery/no-text: [0]
jquery/no-text: [2]
jquery/no-toggle: [2]
jquery/no-trigger: [0]
jquery/no-trim: [2]
Expand Down Expand Up @@ -477,7 +477,7 @@ rules:
no-jquery/no-slide: [2]
no-jquery/no-sub: [2]
no-jquery/no-support: [2]
no-jquery/no-text: [0]
no-jquery/no-text: [2]
no-jquery/no-trigger: [0]
no-jquery/no-trim: [2]
no-jquery/no-type: [2]
Expand Down
82 changes: 43 additions & 39 deletions web_src/js/features/common-global.js
Original file line number Diff line number Diff line change
Expand Up @@ -302,51 +302,55 @@ async function linkAction(e) {
}

export function initGlobalLinkActions() {
function showDeletePopup(e) {
e.preventDefault();
const $this = $(this);
const dataArray = $this.data();
let filter = '';
if (this.getAttribute('data-modal-id')) {
filter += `#${this.getAttribute('data-modal-id')}`;
}
for (const el of document.querySelectorAll('.delete-button')) {
el.addEventListener('click', (e) => {
e.preventDefault();
const btn = e.currentTarget;
wxiaoguang marked this conversation as resolved.
Show resolved Hide resolved

const $dialog = $(`.delete.modal${filter}`);
$dialog.find('.name').text($this.data('name'));
for (const [key, value] of Object.entries(dataArray)) {
if (key && key.startsWith('data')) {
$dialog.find(`.${key}`).text(value);
}
}
// eslint-disable-next-line github/no-dataset -- code depends on the camel-casing
const dataObj = btn.dataset;

$dialog.modal({
closable: false,
onApprove: async () => {
if ($this.data('type') === 'form') {
$($this.data('form')).trigger('submit');
return;
const modalId = btn.getAttribute('data-modal-id');
const modal = document.querySelector(`.delete.modal${modalId ? `#${modalId}` : ''}`);
const modalNameEl = modal.querySelector('.name');
if (modalNameEl) modalNameEl.textContent = btn.getAttribute('name');
wxiaoguang marked this conversation as resolved.
Show resolved Hide resolved

for (const [key, value] of Object.entries(dataObj)) {
if (key?.startsWith('data')) {
const nameEl = modal.querySelector(`.${key}`);
if (nameEl) nameEl.textContent = value;
}
const postData = new FormData();
for (const [key, value] of Object.entries(dataArray)) {
if (key && key.startsWith('data')) {
postData.append(key.slice(4), value);
}

$(modal).modal({
closable: false,
onApprove: async () => {
if (modal.getAttribute('data-type') === 'form') {
const form = document.querySelector(btn.getAttribute('data-form'));
if (form) form.submit();
return;
}
if (key === 'id') {
postData.append('id', value);
const postData = new FormData();
for (const [key, value] of Object.entries(dataObj)) {
// data-dataxxx (HTML) -> dataxxx
// data-data-xxx (HTML) -> dataXxx
if (key?.startsWith('data')) {
postData.append(key.slice(4), value);
}
if (key === 'id') {
postData.append('id', value);
}
}
}

const response = await POST($this.data('url'), {data: postData});
if (response.ok) {
const data = await response.json();
window.location.href = data.redirect;
}
},
}).modal('show');
const response = await POST(btn.getAttribute('data-url'), {data: postData});
if (response.ok) {
const data = await response.json();
window.location.href = data.redirect;
}
},
}).modal('show');
});
}

// Helpers.
$('.delete-button').on('click', showDeletePopup);
}

function initGlobalShowModal() {
Expand Down Expand Up @@ -382,7 +386,7 @@ function initGlobalShowModal() {
} else if ($attrTarget[0].matches('input, textarea')) {
$attrTarget.val(attrib.value); // FIXME: add more supports like checkbox
} else {
$attrTarget.text(attrib.value); // FIXME: it should be more strict here, only handle div/span/p
$attrTarget[0].textContent = attrib.value; // FIXME: it should be more strict here, only handle div/span/p
}
}

Expand Down
10 changes: 5 additions & 5 deletions web_src/js/features/imagediff.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,20 +79,20 @@ export function initImageDiff() {
path: this.getAttribute('data-path-after'),
mime: this.getAttribute('data-mime-after'),
$images: $container.find('img.image-after'), // matches 3 <img>
$boundsInfo: $container.find('.bounds-info-after'),
boundsInfo: this.querySelector('.bounds-info-after'),
}, {
path: this.getAttribute('data-path-before'),
mime: this.getAttribute('data-mime-before'),
$images: $container.find('img.image-before'), // matches 3 <img>
$boundsInfo: $container.find('.bounds-info-before'),
boundsInfo: this.querySelector('.bounds-info-before'),
}];

await Promise.all(imageInfos.map(async (info) => {
const [success] = await Promise.all(Array.from(info.$images, (img) => {
return loadElem(img, info.path);
}));
// only the first images is associated with $boundsInfo
if (!success) info.$boundsInfo.text('(image error)');
// only the first images is associated with boundsInfo
if (!success && info.boundsInfo) info.boundsInfo.textContent = '(image error)';
if (info.mime === 'image/svg+xml') {
const resp = await GET(info.path);
const text = await resp.text();
Expand All @@ -102,7 +102,7 @@ export function initImageDiff() {
this.setAttribute('width', bounds.width);
this.setAttribute('height', bounds.height);
});
hideElem(info.$boundsInfo);
hideElem(info.boundsInfo);
}
}
}));
Expand Down
14 changes: 7 additions & 7 deletions web_src/js/features/notification.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,17 +47,13 @@ async function receiveUpdateCount(event) {
}

export function initNotificationCount() {
const $notificationCount = $('.notification_count');

if (!$notificationCount.length) {
return;
}
if (!document.querySelector('.notification_count')) return;

let usingPeriodicPoller = false;
const startPeriodicPoller = (timeout, lastCount) => {
if (timeout <= 0 || !Number.isFinite(timeout)) return;
usingPeriodicPoller = true;
lastCount = lastCount ?? $notificationCount.text();
lastCount = lastCount ?? getCurrentCount();
setTimeout(async () => {
await updateNotificationCountWithCallback(startPeriodicPoller, timeout, lastCount);
}, timeout);
Expand Down Expand Up @@ -121,8 +117,12 @@ export function initNotificationCount() {
startPeriodicPoller(notificationSettings.MinTimeout);
}

function getCurrentCount() {
return document.querySelector('.notification_count').textContent;
}

async function updateNotificationCountWithCallback(callback, timeout, lastCount) {
const currentCount = $('.notification_count').text();
const currentCount = getCurrentCount();
silverwind marked this conversation as resolved.
Show resolved Hide resolved
if (lastCount !== currentCount) {
callback(notificationSettings.MinTimeout, currentCount);
return;
Expand Down
37 changes: 19 additions & 18 deletions web_src/js/features/repo-editor.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,21 @@ function getCursorPosition($e) {
return pos;
}

function joinTreePath(fileNameEl) {
const parts = [];

for (const el of document.querySelectorAll('.breadcrumb span.section')) {
const link = el.querySelector('a');
parts.push(link ? link.textContent : el.textContent);
}

if (fileNameEl.value) {
parts.push(fileNameEl.value);
}

document.querySelector('#tree_path').value = parts.join('/');
}

export function initRepoEditor() {
initEditorForm();

Expand All @@ -72,23 +87,9 @@ export function initRepoEditor() {
hideElem('.quick-pull-branch-name');
document.querySelector('.quick-pull-branch-name input').required = false;
}
$('#commit-button').text(this.getAttribute('button_text'));
$('#commit-button')[0].textContent = this.getAttribute('button_text');
});

const joinTreePath = ($fileNameEl) => {
const parts = [];
$('.breadcrumb span.section').each(function () {
const $element = $(this);
if ($element.find('a').length) {
parts.push($element.find('a').text());
} else {
parts.push($element.text());
}
});
if ($fileNameEl.val()) parts.push($fileNameEl.val());
$('#tree_path').val(parts.join('/'));
};

const $editFilename = $('#file-name');
$editFilename.on('input', function () {
const parts = $(this).val().split('/');
Expand All @@ -108,7 +109,7 @@ export function initRepoEditor() {
}
}

joinTreePath($(this));
joinTreePath(this);
});

$editFilename.on('keydown', function (e) {
Expand All @@ -118,12 +119,12 @@ export function initRepoEditor() {
if (e.code === 'Backspace' && getCursorPosition($(this)) === 0 && $section.length > 0) {
e.preventDefault();
const $divider = $('.breadcrumb .breadcrumb-divider');
const value = $section.last().find('a').text();
const value = $section.last().find('a')[0].textContent;
$(this).val(value + $(this).val());
this.setSelectionRange(value.length, value.length);
$section.last().remove();
$divider.last().remove();
joinTreePath($(this));
joinTreePath(this);
}
});

Expand Down
7 changes: 4 additions & 3 deletions web_src/js/features/repo-issue-edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -189,11 +189,12 @@ export function initRepoIssueCommentEdit() {
// Quote reply
$(document).on('click', '.quote-reply', async function (event) {
event.preventDefault();
const target = $(this).data('target');
const quote = $(`#${target}`).text().replace(/\n/g, '\n> ');
const target = this.getAttribute('data-target');
const quote = document.querySelector(`#${target}`).textContent.replace(/\n/g, '\n> ');
const content = `> ${quote}\n\n`;

let editor;
if ($(this).hasClass('quote-reply-diff')) {
if (this.classList.contains('quote-reply-diff')) {
const $replyBtn = $(this).closest('.comment-code-cloud').find('button.comment-form-reply');
editor = await handleReply($replyBtn);
} else {
Expand Down
22 changes: 12 additions & 10 deletions web_src/js/features/repo-issue.js
Original file line number Diff line number Diff line change
Expand Up @@ -278,11 +278,12 @@ export function initRepoPullRequestUpdate() {

$('.update-button > .dropdown').dropdown({
onChange(_text, _value, $choice) {
const url = $choice[0].getAttribute('data-do');
const choiceEl = $choice[0];
const url = choiceEl.getAttribute('data-do');
if (url) {
const buttonText = pullUpdateButton.querySelector('.button-text');
if (buttonText) {
buttonText.textContent = $choice.text();
buttonText.textContent = choiceEl.textContent;
}
pullUpdateButton.setAttribute('data-do', url);
}
Expand Down Expand Up @@ -567,14 +568,15 @@ export function initRepoPullRequestReview() {
export function initRepoIssueReferenceIssue() {
// Reference issue
$(document).on('click', '.reference-issue', function (event) {
const $this = $(this);
const content = $(`#${$this.data('target')}`).text();
const poster = $this.data('poster-username');
const reference = toAbsoluteUrl($this.data('reference'));
const $modal = $($this.data('modal'));
$modal.find('textarea[name="content"]').val(`${content}\n\n_Originally posted by @${poster} in ${reference}_`);
$modal.modal('show');

const target = this.getAttribute('data-target');
const content = document.querySelector(`#${target}`)?.textContent ?? '';
const poster = this.getAttribute('data-poster-username');
const reference = toAbsoluteUrl(this.getAttribute('data-reference'));
const modalSelector = this.getAttribute('data-modal');
const modal = document.querySelector(modalSelector);
const textarea = modal.querySelector('textarea[name="content"]');
textarea.value = `${content}\n\n_Originally posted by @${poster} in ${reference}_`;
$(modal).modal('show');
event.preventDefault();
});
}
Expand Down
4 changes: 2 additions & 2 deletions web_src/js/features/repo-legacy.js
Original file line number Diff line number Diff line change
Expand Up @@ -272,9 +272,9 @@ export function initRepoCommentForm() {
}

$list.find('.selected').html(`
<a class="item muted sidebar-item-link" href=${$(this).data('href')}>
<a class="item muted sidebar-item-link" href=${htmlEscape(this.getAttribute('href'))}>
${icon}
${htmlEscape($(this).text())}
${htmlEscape(this.textContent)}
</a>
`);

Expand Down
34 changes: 17 additions & 17 deletions web_src/js/features/repo-settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,35 +8,35 @@ const {appSubUrl, csrfToken} = window.config;

export function initRepoSettingsCollaboration() {
// Change collaborator access mode
$('.page-content.repository .ui.dropdown.access-mode').each((_, el) => {
const $dropdown = $(el);
const $text = $dropdown.find('> .text');
$dropdown.dropdown({
$('.page-content.repository .ui.dropdown.access-mode').each((_, dropdownEl) => {
const textEl = dropdownEl.querySelector(':scope > .text');
$(dropdownEl).dropdown({
async action(_text, value) {
const lastValue = el.getAttribute('data-last-value');
const lastValue = dropdownEl.getAttribute('data-last-value');
try {
el.setAttribute('data-last-value', value);
$dropdown.dropdown('hide');
dropdownEl.setAttribute('data-last-value', value);
$(dropdownEl).dropdown('hide');
const data = new FormData();
data.append('uid', el.getAttribute('data-uid'));
data.append('uid', dropdownEl.getAttribute('data-uid'));
data.append('mode', value);
await POST(el.getAttribute('data-url'), {data});
await POST(dropdownEl.getAttribute('data-url'), {data});
} catch {
$text.text('(error)'); // prevent from misleading users when error occurs
el.setAttribute('data-last-value', lastValue);
textEl.textContent = '(error)'; // prevent from misleading users when error occurs
dropdownEl.setAttribute('data-last-value', lastValue);
}
},
onChange(_value, text, _$choice) {
$text.text(text); // update the text when using keyboard navigating
onChange(_value, text) {
textEl.textContent = text; // update the text when using keyboard navigating
},
onHide() {
// set to the really selected value, defer to next tick to make sure `action` has finished its work because the calling order might be onHide -> action
// set to the really selected value, defer to next tick to make sure `action` has finished
// its work because the calling order might be onHide -> action
setTimeout(() => {
const $item = $dropdown.dropdown('get item', el.getAttribute('data-last-value'));
const $item = $(dropdownEl).dropdown('get item', dropdownEl.getAttribute('data-last-value'));
if ($item) {
$dropdown.dropdown('set selected', el.getAttribute('data-last-value'));
$(dropdownEl).dropdown('set selected', dropdownEl.getAttribute('data-last-value'));
} else {
$text.text('(none)'); // prevent from misleading users when the access mode is undefined
textEl.textContent = '(none)'; // prevent from misleading users when the access mode is undefined
}
}, 0);
},
Expand Down