Refactor some frontend problems (#32646)
1. correct the modal usage on "admin email list" page (then `web_src/js/features/admin/emails.ts` is removed) 2. use `addDelegatedEventListener` instead of `jQuery().on` 3. more jQuery related changes and remove jQuery from `web_src/js/features/common-button.ts` 4. improve `confirmModal` to make it support header, and remove incorrect double-escaping 5. fix more typescript related types 6. fine tune devtest pages and add more tests
This commit is contained in:
parent
722e703c6b
commit
0f4b0cf892
22 changed files with 200 additions and 191 deletions
|
@ -1,13 +0,0 @@
|
|||
import $ from 'jquery';
|
||||
|
||||
export function initAdminEmails(): void {
|
||||
$('.link-email-action').on('click', (e) => {
|
||||
const $this = $(this);
|
||||
$('#form-uid').val($this.data('uid'));
|
||||
$('#form-email').val($this.data('email'));
|
||||
$('#form-primary').val($this.data('primary'));
|
||||
$('#form-activate').val($this.data('activate'));
|
||||
$('#change-email-modal').modal('show');
|
||||
e.preventDefault();
|
||||
});
|
||||
}
|
|
@ -1,13 +1,13 @@
|
|||
import $ from 'jquery';
|
||||
import {POST} from '../modules/fetch.ts';
|
||||
import {hideElem, showElem, toggleElem} from '../utils/dom.ts';
|
||||
import {showErrorToast} from '../modules/toast.ts';
|
||||
import {addDelegatedEventListener, hideElem, queryElems, showElem, toggleElem} from '../utils/dom.ts';
|
||||
import {fomanticQuery} from '../modules/fomantic/base.ts';
|
||||
import {camelize} from 'vue';
|
||||
|
||||
export function initGlobalButtonClickOnEnter(): void {
|
||||
$(document).on('keypress', 'div.ui.button,span.ui.button', (e) => {
|
||||
if (e.code === ' ' || e.code === 'Enter') {
|
||||
$(e.target).trigger('click');
|
||||
addDelegatedEventListener(document, 'keypress', 'div.ui.button, span.ui.button', (el, e: KeyboardEvent) => {
|
||||
if (e.code === 'Space' || e.code === 'Enter') {
|
||||
e.preventDefault();
|
||||
el.click();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
@ -40,7 +40,7 @@ export function initGlobalDeleteButton(): void {
|
|||
}
|
||||
}
|
||||
|
||||
$(modal).modal({
|
||||
fomanticQuery(modal).modal({
|
||||
closable: false,
|
||||
onApprove: async () => {
|
||||
// if `data-type="form"` exists, then submit the form by the selector provided by `data-form="..."`
|
||||
|
@ -73,87 +73,93 @@ export function initGlobalDeleteButton(): void {
|
|||
}
|
||||
}
|
||||
|
||||
function onShowPanelClick(e) {
|
||||
// a '.show-panel' element can show a panel, by `data-panel="selector"`
|
||||
// if it has "toggle" class, it toggles the panel
|
||||
const el = e.currentTarget;
|
||||
e.preventDefault();
|
||||
const sel = el.getAttribute('data-panel');
|
||||
if (el.classList.contains('toggle')) {
|
||||
toggleElem(sel);
|
||||
} else {
|
||||
showElem(sel);
|
||||
}
|
||||
}
|
||||
|
||||
function onHidePanelClick(e) {
|
||||
// a `.hide-panel` element can hide a panel, by `data-panel="selector"` or `data-panel-closest="selector"`
|
||||
const el = e.currentTarget;
|
||||
e.preventDefault();
|
||||
let sel = el.getAttribute('data-panel');
|
||||
if (sel) {
|
||||
hideElem(sel);
|
||||
return;
|
||||
}
|
||||
sel = el.getAttribute('data-panel-closest');
|
||||
if (sel) {
|
||||
hideElem(el.parentNode.closest(sel));
|
||||
return;
|
||||
}
|
||||
throw new Error('no panel to hide'); // should never happen, otherwise there is a bug in code
|
||||
}
|
||||
|
||||
function onShowModalClick(e) {
|
||||
// A ".show-modal" button will show a modal dialog defined by its "data-modal" attribute.
|
||||
// Each "data-modal-{target}" attribute will be filled to target element's value or text-content.
|
||||
// * First, try to query '#target'
|
||||
// * Then, try to query '[name=target]'
|
||||
// * Then, try to query '.target'
|
||||
// * Then, try to query 'target' as HTML tag
|
||||
// If there is a ".{attr}" part like "data-modal-form.action", then the form's "action" attribute will be set.
|
||||
const el = e.currentTarget;
|
||||
e.preventDefault();
|
||||
const modalSelector = el.getAttribute('data-modal');
|
||||
const elModal = document.querySelector(modalSelector);
|
||||
if (!elModal) throw new Error('no modal for this action');
|
||||
|
||||
const modalAttrPrefix = 'data-modal-';
|
||||
for (const attrib of el.attributes) {
|
||||
if (!attrib.name.startsWith(modalAttrPrefix)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const attrTargetCombo = attrib.name.substring(modalAttrPrefix.length);
|
||||
const [attrTargetName, attrTargetAttr] = attrTargetCombo.split('.');
|
||||
// try to find target by: "#target" -> "[name=target]" -> ".target" -> "<target> tag"
|
||||
const attrTarget = elModal.querySelector(`#${attrTargetName}`) ||
|
||||
elModal.querySelector(`[name=${attrTargetName}]`) ||
|
||||
elModal.querySelector(`.${attrTargetName}`) ||
|
||||
elModal.querySelector(`${attrTargetName}`);
|
||||
if (!attrTarget) {
|
||||
if (!window.config.runModeIsProd) throw new Error(`attr target "${attrTargetCombo}" not found for modal`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (attrTargetAttr) {
|
||||
attrTarget[camelize(attrTargetAttr)] = attrib.value;
|
||||
} else if (attrTarget.matches('input, textarea')) {
|
||||
attrTarget.value = attrib.value; // FIXME: add more supports like checkbox
|
||||
} else {
|
||||
attrTarget.textContent = attrib.value; // FIXME: it should be more strict here, only handle div/span/p
|
||||
}
|
||||
}
|
||||
|
||||
fomanticQuery(elModal).modal('setting', {
|
||||
onApprove: () => {
|
||||
// "form-fetch-action" can handle network errors gracefully,
|
||||
// so keep the modal dialog to make users can re-submit the form if anything wrong happens.
|
||||
if (elModal.querySelector('.form-fetch-action')) return false;
|
||||
},
|
||||
}).modal('show');
|
||||
}
|
||||
|
||||
export function initGlobalButtons(): void {
|
||||
// There are many "cancel button" elements in modal dialogs, Fomantic UI expects they are button-like elements but never submit a form.
|
||||
// However, Gitea misuses the modal dialog and put the cancel buttons inside forms, so we must prevent the form submission.
|
||||
// There are a few cancel buttons in non-modal forms, and there are some dynamically created forms (eg: the "Edit Issue Content")
|
||||
$(document).on('click', 'form button.ui.cancel.button', (e) => {
|
||||
e.preventDefault();
|
||||
});
|
||||
addDelegatedEventListener(document, 'click', 'form button.ui.cancel.button', (_ /* el */, e) => e.preventDefault());
|
||||
|
||||
$('.show-panel').on('click', function (e) {
|
||||
// a '.show-panel' element can show a panel, by `data-panel="selector"`
|
||||
// if it has "toggle" class, it toggles the panel
|
||||
e.preventDefault();
|
||||
const sel = this.getAttribute('data-panel');
|
||||
if (this.classList.contains('toggle')) {
|
||||
toggleElem(sel);
|
||||
} else {
|
||||
showElem(sel);
|
||||
}
|
||||
});
|
||||
|
||||
$('.hide-panel').on('click', function (e) {
|
||||
// a `.hide-panel` element can hide a panel, by `data-panel="selector"` or `data-panel-closest="selector"`
|
||||
e.preventDefault();
|
||||
let sel = this.getAttribute('data-panel');
|
||||
if (sel) {
|
||||
hideElem($(sel));
|
||||
return;
|
||||
}
|
||||
sel = this.getAttribute('data-panel-closest');
|
||||
if (sel) {
|
||||
hideElem($(this).closest(sel));
|
||||
return;
|
||||
}
|
||||
// should never happen, otherwise there is a bug in code
|
||||
showErrorToast('Nothing to hide');
|
||||
});
|
||||
}
|
||||
|
||||
export function initGlobalShowModal() {
|
||||
// A ".show-modal" button will show a modal dialog defined by its "data-modal" attribute.
|
||||
// Each "data-modal-{target}" attribute will be filled to target element's value or text-content.
|
||||
// * First, try to query '#target'
|
||||
// * Then, try to query '.target'
|
||||
// * Then, try to query 'target' as HTML tag
|
||||
// If there is a ".{attr}" part like "data-modal-form.action", then the form's "action" attribute will be set.
|
||||
$('.show-modal').on('click', function (e) {
|
||||
e.preventDefault();
|
||||
const modalSelector = this.getAttribute('data-modal');
|
||||
const $modal = $(modalSelector);
|
||||
if (!$modal.length) {
|
||||
throw new Error('no modal for this action');
|
||||
}
|
||||
const modalAttrPrefix = 'data-modal-';
|
||||
for (const attrib of this.attributes) {
|
||||
if (!attrib.name.startsWith(modalAttrPrefix)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const attrTargetCombo = attrib.name.substring(modalAttrPrefix.length);
|
||||
const [attrTargetName, attrTargetAttr] = attrTargetCombo.split('.');
|
||||
// try to find target by: "#target" -> ".target" -> "target tag"
|
||||
let $attrTarget = $modal.find(`#${attrTargetName}`);
|
||||
if (!$attrTarget.length) $attrTarget = $modal.find(`.${attrTargetName}`);
|
||||
if (!$attrTarget.length) $attrTarget = $modal.find(`${attrTargetName}`);
|
||||
if (!$attrTarget.length) continue; // TODO: show errors in dev mode to remind developers that there is a bug
|
||||
|
||||
if (attrTargetAttr) {
|
||||
$attrTarget[0][attrTargetAttr] = attrib.value;
|
||||
} else if ($attrTarget[0].matches('input, textarea')) {
|
||||
$attrTarget.val(attrib.value); // FIXME: add more supports like checkbox
|
||||
} else {
|
||||
$attrTarget[0].textContent = attrib.value; // FIXME: it should be more strict here, only handle div/span/p
|
||||
}
|
||||
}
|
||||
|
||||
$modal.modal('setting', {
|
||||
onApprove: () => {
|
||||
// "form-fetch-action" can handle network errors gracefully,
|
||||
// so keep the modal dialog to make users can re-submit the form if anything wrong happens.
|
||||
if ($modal.find('.form-fetch-action').length) return false;
|
||||
},
|
||||
}).modal('show');
|
||||
});
|
||||
queryElems(document, '.show-panel', (el) => el.addEventListener('click', onShowPanelClick));
|
||||
queryElems(document, '.hide-panel', (el) => el.addEventListener('click', onHidePanelClick));
|
||||
queryElems(document, '.show-modal', (el) => el.addEventListener('click', onShowModalClick));
|
||||
}
|
||||
|
|
|
@ -1,14 +1,14 @@
|
|||
import {request} from '../modules/fetch.ts';
|
||||
import {showErrorToast} from '../modules/toast.ts';
|
||||
import {submitEventSubmitter} from '../utils/dom.ts';
|
||||
import {htmlEscape} from 'escape-goat';
|
||||
import {addDelegatedEventListener, submitEventSubmitter} from '../utils/dom.ts';
|
||||
import {confirmModal} from './comp/ConfirmModal.ts';
|
||||
import type {RequestOpts} from '../types.ts';
|
||||
|
||||
const {appSubUrl, i18n} = window.config;
|
||||
|
||||
// fetchActionDoRedirect does real redirection to bypass the browser's limitations of "location"
|
||||
// more details are in the backend's fetch-redirect handler
|
||||
function fetchActionDoRedirect(redirect) {
|
||||
function fetchActionDoRedirect(redirect: string) {
|
||||
const form = document.createElement('form');
|
||||
const input = document.createElement('input');
|
||||
form.method = 'post';
|
||||
|
@ -21,7 +21,7 @@ function fetchActionDoRedirect(redirect) {
|
|||
form.submit();
|
||||
}
|
||||
|
||||
async function fetchActionDoRequest(actionElem, url, opt) {
|
||||
async function fetchActionDoRequest(actionElem: HTMLElement, url: string, opt: RequestOpts) {
|
||||
try {
|
||||
const resp = await request(url, opt);
|
||||
if (resp.status === 200) {
|
||||
|
@ -55,11 +55,8 @@ async function fetchActionDoRequest(actionElem, url, opt) {
|
|||
actionElem.classList.remove('is-loading', 'loading-icon-2px');
|
||||
}
|
||||
|
||||
async function formFetchAction(e) {
|
||||
if (!e.target.classList.contains('form-fetch-action')) return;
|
||||
|
||||
async function formFetchAction(formEl: HTMLFormElement, e: SubmitEvent) {
|
||||
e.preventDefault();
|
||||
const formEl = e.target;
|
||||
if (formEl.classList.contains('is-loading')) return;
|
||||
|
||||
formEl.classList.add('is-loading');
|
||||
|
@ -77,7 +74,7 @@ async function formFetchAction(e) {
|
|||
}
|
||||
|
||||
let reqUrl = formActionUrl;
|
||||
const reqOpt = {method: formMethod.toUpperCase()};
|
||||
const reqOpt = {method: formMethod.toUpperCase(), body: null};
|
||||
if (formMethod.toLowerCase() === 'get') {
|
||||
const params = new URLSearchParams();
|
||||
for (const [key, value] of formData) {
|
||||
|
@ -95,34 +92,36 @@ async function formFetchAction(e) {
|
|||
await fetchActionDoRequest(formEl, reqUrl, reqOpt);
|
||||
}
|
||||
|
||||
async function linkAction(e) {
|
||||
async function linkAction(el: HTMLElement, e: Event) {
|
||||
// A "link-action" can post AJAX request to its "data-url"
|
||||
// Then the browser is redirected to: the "redirect" in response, or "data-redirect" attribute, or current URL by reloading.
|
||||
// If the "link-action" has "data-modal-confirm" attribute, a confirm modal dialog will be shown before taking action.
|
||||
const el = e.target.closest('.link-action');
|
||||
if (!el) return;
|
||||
|
||||
e.preventDefault();
|
||||
const url = el.getAttribute('data-url');
|
||||
const doRequest = async () => {
|
||||
el.disabled = true;
|
||||
if ('disabled' in el) el.disabled = true; // el could be A or BUTTON, but A doesn't have disabled attribute
|
||||
await fetchActionDoRequest(el, url, {method: 'POST'});
|
||||
el.disabled = false;
|
||||
if ('disabled' in el) el.disabled = false;
|
||||
};
|
||||
|
||||
const modalConfirmContent = htmlEscape(el.getAttribute('data-modal-confirm') || '');
|
||||
const modalConfirmContent = el.getAttribute('data-modal-confirm') ||
|
||||
el.getAttribute('data-modal-confirm-content') || '';
|
||||
if (!modalConfirmContent) {
|
||||
await doRequest();
|
||||
return;
|
||||
}
|
||||
|
||||
const isRisky = el.classList.contains('red') || el.classList.contains('negative');
|
||||
if (await confirmModal(modalConfirmContent, {confirmButtonColor: isRisky ? 'red' : 'primary'})) {
|
||||
if (await confirmModal({
|
||||
header: el.getAttribute('data-modal-confirm-header') || '',
|
||||
content: modalConfirmContent,
|
||||
confirmButtonColor: isRisky ? 'red' : 'primary',
|
||||
})) {
|
||||
await doRequest();
|
||||
}
|
||||
}
|
||||
|
||||
export function initGlobalFetchAction() {
|
||||
document.addEventListener('submit', formFetchAction);
|
||||
document.addEventListener('click', linkAction);
|
||||
addDelegatedEventListener(document, 'click', '.form-fetch-action', formFetchAction);
|
||||
addDelegatedEventListener(document, 'click', '.link-action', linkAction);
|
||||
}
|
||||
|
|
|
@ -5,10 +5,12 @@ import {fomanticQuery} from '../../modules/fomantic/base.ts';
|
|||
|
||||
const {i18n} = window.config;
|
||||
|
||||
export function confirmModal(content, {confirmButtonColor = 'primary'} = {}) {
|
||||
export function confirmModal({header = '', content = '', confirmButtonColor = 'primary'} = {}) {
|
||||
return new Promise((resolve) => {
|
||||
const headerHtml = header ? `<div class="header">${htmlEscape(header)}</div>` : '';
|
||||
const modal = createElementFromHTML(`
|
||||
<div class="ui g-modal-confirm modal">
|
||||
${headerHtml}
|
||||
<div class="content">${htmlEscape(content)}</div>
|
||||
<div class="actions">
|
||||
<button class="ui cancel button">${svg('octicon-x')} ${htmlEscape(i18n.modal_cancel)}</button>
|
||||
|
|
|
@ -76,7 +76,7 @@ function initRepoIssueListCheckboxes() {
|
|||
// for delete
|
||||
if (action === 'delete') {
|
||||
const confirmText = e.target.getAttribute('data-action-delete-confirm');
|
||||
if (!await confirmModal(confirmText, {confirmButtonColor: 'red'})) {
|
||||
if (!await confirmModal({content: confirmText, confirmButtonColor: 'red'})) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue