From 0f4b0cf8922ef1016fc8230fb0f9df883f03d1e0 Mon Sep 17 00:00:00 2001
From: wxiaoguang <wxiaoguang@gmail.com>
Date: Tue, 26 Nov 2024 23:36:55 +0800
Subject: [PATCH] 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
---
 routers/web/admin/emails.go                   |   2 +-
 routers/web/devtest/devtest.go                |   4 +-
 templates/admin/emails/list.tmpl              |  55 ++----
 templates/devtest/devtest-footer.tmpl         |   3 +
 templates/devtest/devtest-header.tmpl         |   2 +
 .../devtest/{list.tmpl => devtest-list.tmpl}  |   6 +-
 templates/devtest/fetch-action.tmpl           |   5 +-
 templates/devtest/flex-list.tmpl              |   5 +-
 templates/devtest/fomantic-dropdown.tmpl      |   5 +-
 templates/devtest/fomantic-modal.tmpl         |  28 ++-
 templates/devtest/gitea-ui.tmpl               |   5 +-
 templates/devtest/global-button.tmpl          |  16 ++
 templates/devtest/label.tmpl                  |   5 +-
 templates/devtest/tmplerr.tmpl                |   4 +-
 templates/devtest/toast.tmpl                  |   8 +-
 web_src/js/features/admin/emails.ts           |  13 --
 web_src/js/features/common-button.ts          | 176 +++++++++---------
 web_src/js/features/common-fetch-action.ts    |  37 ++--
 web_src/js/features/comp/ConfirmModal.ts      |   4 +-
 web_src/js/features/repo-issue-list.ts        |   2 +-
 web_src/js/index.ts                           |   4 -
 web_src/js/utils/dom.ts                       |   2 +-
 22 files changed, 200 insertions(+), 191 deletions(-)
 create mode 100644 templates/devtest/devtest-footer.tmpl
 create mode 100644 templates/devtest/devtest-header.tmpl
 rename templates/devtest/{list.tmpl => devtest-list.tmpl} (65%)
 create mode 100644 templates/devtest/global-button.tmpl
 delete mode 100644 web_src/js/features/admin/emails.ts

diff --git a/routers/web/admin/emails.go b/routers/web/admin/emails.go
index 49338fbd7c..e9c97d8b8f 100644
--- a/routers/web/admin/emails.go
+++ b/routers/web/admin/emails.go
@@ -154,7 +154,7 @@ func ActivateEmail(ctx *context.Context) {
 
 // DeleteEmail serves a POST request for delete a user's email
 func DeleteEmail(ctx *context.Context) {
-	u, err := user_model.GetUserByID(ctx, ctx.FormInt64("Uid"))
+	u, err := user_model.GetUserByID(ctx, ctx.FormInt64("uid"))
 	if err != nil || u == nil {
 		ctx.ServerError("GetUserByID", err)
 		return
diff --git a/routers/web/devtest/devtest.go b/routers/web/devtest/devtest.go
index 8c343197d9..0068c9fe88 100644
--- a/routers/web/devtest/devtest.go
+++ b/routers/web/devtest/devtest.go
@@ -24,12 +24,12 @@ func List(ctx *context.Context) {
 	var subNames []string
 	for _, tmplName := range templateNames {
 		subName := strings.TrimSuffix(tmplName, ".tmpl")
-		if subName != "list" {
+		if !strings.HasPrefix(subName, "devtest-") {
 			subNames = append(subNames, subName)
 		}
 	}
 	ctx.Data["SubNames"] = subNames
-	ctx.HTML(http.StatusOK, "devtest/list")
+	ctx.HTML(http.StatusOK, "devtest/devtest-list")
 }
 
 func FetchActionTest(ctx *context.Context) {
diff --git a/templates/admin/emails/list.tmpl b/templates/admin/emails/list.tmpl
index 835b77ea17..0dc1fb9d03 100644
--- a/templates/admin/emails/list.tmpl
+++ b/templates/admin/emails/list.tmpl
@@ -50,10 +50,10 @@
 							<td>{{svg (Iif .IsPrimary "octicon-check" "octicon-x")}}</td>
 							<td>
 								{{if .CanChange}}
-									<a class="link-email-action" href data-uid="{{.UID}}"
-										data-email="{{.Email}}"
-										data-primary="{{if .IsPrimary}}1{{else}}0{{end}}"
-										data-activate="{{if .IsActivated}}0{{else}}1{{end}}">
+									<a class="show-modal" href data-modal="#change-email-modal" data-modal-uid="{{.UID}}"
+										data-modal-email="{{.Email}}"
+										data-modal-primary="{{if .IsPrimary}}1{{else}}0{{end}}"
+										data-modal-activate="{{if .IsActivated}}0{{else}}1{{end}}">
 										{{svg (Iif .IsActivated "octicon-check" "octicon-x")}}
 									</a>
 								{{else}}
@@ -61,9 +61,10 @@
 								{{end}}
 							</td>
 							<td>
-								<div class="tw-flex tw-gap-2">
-									<a class="delete-button" href="" data-url="{{$.Link}}/delete" data-id="{{.ID}}" data-data-uid="{{.UID}}">{{svg "octicon-trash"}}</a>
-								</div>
+								<a class="link-action negative" href data-url="{{$.Link}}/delete?id={{.ID}}&uid={{.UID}}"
+									data-modal-confirm-header="{{ctx.Locale.Tr "admin.emails.delete"}}"
+									data-modal-confirm-content="{{ctx.Locale.Tr "admin.emails.delete_desc"}}"
+								>{{svg "octicon-trash"}}</a>
 							</td>
 						</tr>
 					{{end}}
@@ -77,40 +78,24 @@
 			<div class="header">
 				{{ctx.Locale.Tr "admin.emails.change_email_header"}}
 			</div>
-			<div class="content">
+			<form class="content ui form" action="{{AppSubUrl}}/-/admin/emails/activate" method="post">
 				<p class="center">{{ctx.Locale.Tr "admin.emails.change_email_text"}}</p>
 
-				<form class="ui form" id="email-action-form" action="{{AppSubUrl}}/-/admin/emails/activate" method="post">
-					{{$.CsrfTokenHtml}}
+				{{$.CsrfTokenHtml}}
 
-					<input type="hidden" id="query-sort" name="sort" value="{{.SortType}}">
-					<input type="hidden" id="query-keyword" name="q" value="{{.Keyword}}">
-					<input type="hidden" id="query-primary" name="is_primary" value="{{.IsPrimary}}" required>
-					<input type="hidden" id="query-activated" name="is_activated" value="{{.IsActivated}}" required>
+				<input type="hidden" name="sort" value="{{.SortType}}">
+				<input type="hidden" name="q" value="{{.Keyword}}">
+				<input type="hidden" name="is_primary" value="{{.IsPrimary}}">
+				<input type="hidden" name="is_activated" value="{{.IsActivated}}">
 
-					<input type="hidden" id="form-uid" name="uid" value="" required>
-					<input type="hidden" id="form-email" name="email" value="" required>
-					<input type="hidden" id="form-primary" name="primary" value="" required>
-					<input type="hidden" id="form-activate" name="activate" value="" required>
+				<input type="hidden" name="uid">
+				<input type="hidden" name="email">
+				<input type="hidden" name="primary">
+				<input type="hidden" name="activate">
 
-					<div class="center">
-						{{template "base/modal_actions_confirm" .}}
-					</div>
-				</form>
-			</div>
+				{{template "base/modal_actions_confirm" .}}
+			</form>
 		</div>
-
 	</div>
 
-<div class="ui g-modal-confirm delete modal">
-	<div class="header">
-		{{svg "octicon-trash"}}
-		{{ctx.Locale.Tr "admin.emails.delete"}}
-	</div>
-	<div class="content">
-		{{ctx.Locale.Tr "admin.emails.delete_desc"}}
-	</div>
-	{{template "base/modal_actions_confirm" .}}
-</div>
-
 {{template "admin/layout_footer" .}}
diff --git a/templates/devtest/devtest-footer.tmpl b/templates/devtest/devtest-footer.tmpl
new file mode 100644
index 0000000000..1c755508a5
--- /dev/null
+++ b/templates/devtest/devtest-footer.tmpl
@@ -0,0 +1,3 @@
+{{/* TODO: the devtest.js is isolated from index.js, so no module is shared and many index.js functions do not work in devtest.ts */}}
+<script src="{{AssetUrlPrefix}}/js/devtest.js?v={{AssetVersion}}"></script>
+{{template "base/footer" dict}}
diff --git a/templates/devtest/devtest-header.tmpl b/templates/devtest/devtest-header.tmpl
new file mode 100644
index 0000000000..a5910b96e6
--- /dev/null
+++ b/templates/devtest/devtest-header.tmpl
@@ -0,0 +1,2 @@
+{{template "base/head" dict}}
+<link rel="stylesheet" href="{{AssetUrlPrefix}}/css/devtest.css?v={{AssetVersion}}">
diff --git a/templates/devtest/list.tmpl b/templates/devtest/devtest-list.tmpl
similarity index 65%
rename from templates/devtest/list.tmpl
rename to templates/devtest/devtest-list.tmpl
index 90b1fcc9d0..71ee6807f0 100644
--- a/templates/devtest/list.tmpl
+++ b/templates/devtest/devtest-list.tmpl
@@ -1,5 +1,4 @@
-{{template "base/head" .}}
-
+{{template "devtest/devtest-header"}}
 <ul>
 	{{range .SubNames}}
 	<li><a href="{{AppSubUrl}}/devtest/{{.}}">{{.}}</a></li>
@@ -11,5 +10,4 @@ ul {
 	line-height: 2em;
 }
 </style>
-
-{{template "base/footer" .}}
+{{template "devtest/devtest-footer"}}
diff --git a/templates/devtest/fetch-action.tmpl b/templates/devtest/fetch-action.tmpl
index 66f41fc6de..4ee824f04b 100644
--- a/templates/devtest/fetch-action.tmpl
+++ b/templates/devtest/fetch-action.tmpl
@@ -1,4 +1,4 @@
-{{template "base/head" .}}
+{{template "devtest/devtest-header"}}
 <div class="page-content devtest ui container">
 	{{template "base/alert" .}}
 	<div>
@@ -11,6 +11,7 @@
 			<button class="link-action" data-url="fetch-action-test?k=1">test action</button>
 			<button class="link-action" data-url="fetch-action-test?k=1" data-modal-confirm="confirm?">test with confirm</button>
 			<button class="ui red button link-action" data-url="fetch-action-test?k=1" data-modal-confirm="confirm?">test with risky confirm</button>
+			<button class="ui button link-action" data-url="fetch-action-test?k=1" data-modal-confirm-header="confirm header" data-modal-confirm-content="confirm content">test with confirm header</button>
 		</div>
 	</div>
 	<div>
@@ -41,4 +42,4 @@
 		border: 1px red dashed; /* show the border for demo purpose */
 	}
 </style>
-{{template "base/footer" .}}
+{{template "devtest/devtest-footer"}}
diff --git a/templates/devtest/flex-list.tmpl b/templates/devtest/flex-list.tmpl
index 015ab1e154..11d71d56a9 100644
--- a/templates/devtest/flex-list.tmpl
+++ b/templates/devtest/flex-list.tmpl
@@ -1,5 +1,4 @@
-{{template "base/head" .}}
-<link rel="stylesheet" href="{{AssetUrlPrefix}}/css/devtest.css?v={{AssetVersion}}">
+{{template "devtest/devtest-header"}}
 <div class="page-content devtest">
 	<div class="ui container">
 		<h1>Flex List (standalone)</h1>
@@ -112,4 +111,4 @@
 		</div>
 	</div>
 </div>
-{{template "base/footer" .}}
+{{template "devtest/devtest-footer"}}
diff --git a/templates/devtest/fomantic-dropdown.tmpl b/templates/devtest/fomantic-dropdown.tmpl
index 0b9d227220..d41a161e86 100644
--- a/templates/devtest/fomantic-dropdown.tmpl
+++ b/templates/devtest/fomantic-dropdown.tmpl
@@ -1,5 +1,4 @@
-{{template "base/head" .}}
-<link rel="stylesheet" href="{{AssetUrlPrefix}}/css/devtest.css?v={{AssetVersion}}">
+{{template "devtest/devtest-header"}}
 <div class="page-content devtest ui container">
 	<div>
 		<h2>Dropdown</h2>
@@ -128,4 +127,4 @@
 		</div>
 	</div>
 </div>
-{{template "base/footer" .}}
+{{template "devtest/devtest-footer"}}
diff --git a/templates/devtest/fomantic-modal.tmpl b/templates/devtest/fomantic-modal.tmpl
index f31cdc1983..2fbe2bd97d 100644
--- a/templates/devtest/fomantic-modal.tmpl
+++ b/templates/devtest/fomantic-modal.tmpl
@@ -1,9 +1,9 @@
-{{template "base/head" .}}
+{{template "devtest/devtest-header"}}
 <div class="page-content devtest ui container">
 	{{template "base/alert" .}}
 	<div class="modal-buttons flex-text-block tw-flex-wrap"></div>
 	<script type="module">
-		for (const el of $('.ui.modal')) {
+		for (const el of $('.ui.modal:not([data-skip-button])')) {
 			const $btn = $('<button class="ui button">').text(`${el.id}`).on('click', () => {
 				$(el).modal({onApprove() {alert('confirmed')}}).modal('show');
 			});
@@ -69,5 +69,27 @@
 		<div class="content">hello, this is the modal dialog content, this is a dangerous operation</div>
 		{{template "base/modal_actions_confirm" (dict "ModalButtonDangerText" "I know and must do  this is dangerous operation")}}
 	</div>
+
+	<div class="divider"></div>
+
+	<button class="show-modal" data-modal="#test-modal-fill-values"
+		data-modal-fill-by-id="value for id"
+		data-modal-fill-by-name="value for name"
+		data-modal-fill-by-class="value for class"
+		data-modal-p="value for tag"
+		data-modal-a.text-content="fill with attr"
+	>test-modal-fill-values</button>
+
+	<div id="test-modal-fill-values" class="ui mini modal" data-skip-button>
+		<div class="header">Modal dialog (fill values)</div>
+		<form class="content">
+			<div id="fill-by-id"></div>
+			<input name="fill-by-name">
+			<div class="fill-by-class"></div>
+			<p></p>
+			<a href="#">link</a>
+			{{template "base/modal_actions_confirm" dict}}
+		</form>
+	</div>
 </div>
-{{template "base/footer" .}}
+{{template "devtest/devtest-footer"}}
diff --git a/templates/devtest/gitea-ui.tmpl b/templates/devtest/gitea-ui.tmpl
index 56874917b2..303421fe13 100644
--- a/templates/devtest/gitea-ui.tmpl
+++ b/templates/devtest/gitea-ui.tmpl
@@ -1,5 +1,4 @@
-{{template "base/head" .}}
-<link rel="stylesheet" href="{{AssetUrlPrefix}}/css/devtest.css?v={{AssetVersion}}">
+{{template "devtest/devtest-header"}}
 <div class="page-content devtest ui container">
 	<div>
 		<h1>Link</h1>
@@ -193,4 +192,4 @@
 		<button class="{{if true}}tw-bg-red{{end}} tw-p-5 tw-border tw-rounded hover:tw-bg-blue active:tw-bg-yellow">Button</button>
 	</div>
 </div>
-{{template "base/footer" .}}
+{{template "devtest/devtest-footer"}}
diff --git a/templates/devtest/global-button.tmpl b/templates/devtest/global-button.tmpl
new file mode 100644
index 0000000000..9df303d722
--- /dev/null
+++ b/templates/devtest/global-button.tmpl
@@ -0,0 +1,16 @@
+{{template "devtest/devtest-header"}}
+<div class="page-content devtest ui container">
+	<div>
+		<h1>Show/Hide panel</h1>
+		<div>
+			<!-- to test Space/Enter also works on non-button buttons with children -->
+			<div tabindex="0" class="ui button show-panel toggle" data-panel="#devtest-panel-show-hide"><span>Toggle panel 1</span></div>
+			<span tabindex="0" class="ui button show-panel" data-panel="#devtest-panel-show-hide"><span>Show panel 1</span></span>
+		</div>
+		<div id="devtest-panel-show-hide">
+			<div>Panel 1 content</div>
+			<div class="ui button hide-panel" data-panel-closest="div">Hide panel 1</div>
+		</div>
+	</div>
+</div>
+{{template "devtest/devtest-footer"}}
diff --git a/templates/devtest/label.tmpl b/templates/devtest/label.tmpl
index c4b52a3e23..6c48f0c504 100644
--- a/templates/devtest/label.tmpl
+++ b/templates/devtest/label.tmpl
@@ -1,5 +1,4 @@
-{{template "base/head" .}}
-<link rel="stylesheet" href="{{AssetUrlPrefix}}/css/devtest.css?v={{AssetVersion}}">
+{{template "devtest/devtest-header"}}
 <div class="page-content devtest ui container">
 	<div>
 		<h1>Label</h1>
@@ -24,4 +23,4 @@
 		</div>
 	</div>
 </div>
-{{template "base/footer" .}}
+{{template "devtest/devtest-footer"}}
diff --git a/templates/devtest/tmplerr.tmpl b/templates/devtest/tmplerr.tmpl
index dd938c895e..b3a2ffa08e 100644
--- a/templates/devtest/tmplerr.tmpl
+++ b/templates/devtest/tmplerr.tmpl
@@ -1,4 +1,4 @@
-{{template "base/head" .}}
+{{template "devtest/devtest-header"}}
 <div class="page-content devtest">
 	<div class="tw-flex">
 		<div class="tw-w-4/5">
@@ -9,4 +9,4 @@
 		</div>
 	</div>
 </div>
-{{template "base/footer" .}}
+{{template "devtest/devtest-footer"}}
diff --git a/templates/devtest/toast.tmpl b/templates/devtest/toast.tmpl
index 412f23964a..597b415469 100644
--- a/templates/devtest/toast.tmpl
+++ b/templates/devtest/toast.tmpl
@@ -1,5 +1,4 @@
-{{template "base/head" .}}
-
+{{template "devtest/devtest-header"}}
 <div>
 	<h1>Toast</h1>
 	<div>
@@ -9,7 +8,4 @@
 		<button class="ui button toast-test-button" data-toast-level="error" data-toast-message="very looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong message">Show Error Toast (long)</button>
 	</div>
 </div>
-
-<script src="{{AssetUrlPrefix}}/js/devtest.js?v={{AssetVersion}}"></script>
-
-{{template "base/footer" .}}
+{{template "devtest/devtest-footer"}}
diff --git a/web_src/js/features/admin/emails.ts b/web_src/js/features/admin/emails.ts
deleted file mode 100644
index 8e97b67bf9..0000000000
--- a/web_src/js/features/admin/emails.ts
+++ /dev/null
@@ -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();
-  });
-}
diff --git a/web_src/js/features/common-button.ts b/web_src/js/features/common-button.ts
index 4aca5ef8f5..acce992b90 100644
--- a/web_src/js/features/common-button.ts
+++ b/web_src/js/features/common-button.ts
@@ -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));
 }
diff --git a/web_src/js/features/common-fetch-action.ts b/web_src/js/features/common-fetch-action.ts
index 76973d8ce7..0caa27c0e2 100644
--- a/web_src/js/features/common-fetch-action.ts
+++ b/web_src/js/features/common-fetch-action.ts
@@ -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);
 }
diff --git a/web_src/js/features/comp/ConfirmModal.ts b/web_src/js/features/comp/ConfirmModal.ts
index 93459ae1a0..bf645cdbdb 100644
--- a/web_src/js/features/comp/ConfirmModal.ts
+++ b/web_src/js/features/comp/ConfirmModal.ts
@@ -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>
diff --git a/web_src/js/features/repo-issue-list.ts b/web_src/js/features/repo-issue-list.ts
index caf517c5e0..931122db3c 100644
--- a/web_src/js/features/repo-issue-list.ts
+++ b/web_src/js/features/repo-issue-list.ts
@@ -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;
       }
     }
diff --git a/web_src/js/index.ts b/web_src/js/index.ts
index eeead37333..90e2d29225 100644
--- a/web_src/js/index.ts
+++ b/web_src/js/index.ts
@@ -34,7 +34,6 @@ import {
 } from './features/repo-issue.ts';
 import {initRepoEllipsisButton, initCommitStatuses} from './features/repo-commit.ts';
 import {initRepoTopicBar} from './features/repo-home.ts';
-import {initAdminEmails} from './features/admin/emails.ts';
 import {initAdminCommon} from './features/admin/common.ts';
 import {initRepoTemplateSearch} from './features/repo-template.ts';
 import {initRepoCodeView} from './features/repo-code.ts';
@@ -83,7 +82,6 @@ import {
   initGlobalButtonClickOnEnter,
   initGlobalButtons,
   initGlobalDeleteButton,
-  initGlobalShowModal,
 } from './features/common-button.ts';
 import {initGlobalEnterQuickSubmit, initGlobalFormDirtyLeaveConfirm} from './features/common-form.ts';
 
@@ -122,7 +120,6 @@ onDomReady(() => {
   callInitFunctions([
     initGlobalDropdown,
     initGlobalTabularMenu,
-    initGlobalShowModal,
     initGlobalFetchAction,
     initGlobalTooltips,
     initGlobalButtonClickOnEnter,
@@ -157,7 +154,6 @@ onDomReady(() => {
     initCopyContent,
 
     initAdminCommon,
-    initAdminEmails,
     initAdminUserListSearchForm,
     initAdminConfigs,
     initAdminSelfCheck,
diff --git a/web_src/js/utils/dom.ts b/web_src/js/utils/dom.ts
index da9ce71644..06c5e8b486 100644
--- a/web_src/js/utils/dom.ts
+++ b/web_src/js/utils/dom.ts
@@ -353,7 +353,7 @@ export function querySingleVisibleElem<T extends HTMLElement>(parent: Element, s
   return candidates.length ? candidates[0] as T : null;
 }
 
-export function addDelegatedEventListener<T extends HTMLElement>(parent: Node, type: string, selector: string, listener: (elem: T, e: Event) => void | Promise<any>, options?: boolean | AddEventListenerOptions) {
+export function addDelegatedEventListener<T extends HTMLElement, E extends Event>(parent: Node, type: string, selector: string, listener: (elem: T, e: E) => void | Promise<any>, options?: boolean | AddEventListenerOptions) {
   parent.addEventListener(type, (e: Event) => {
     const elem = (e.target as HTMLElement).closest(selector);
     if (!elem) return;