mirror of
https://github.com/go-gitea/gitea.git
synced 2026-12-04 15:54:57 +00:00
refactor: use modern HTML template element and make template-based modal dialog work with morph (#40443)
If an element is being morphed, then it can't contain direct modal dialog, because "show-modal" moves the dialog into body, then a duplicate dialog will be morphed into the element. So, we need to use template-based modal dialog when morphing. --------- Co-authored-by: silverwind <me@silverwind.io>
This commit is contained in:
1 parent
b1c5fedd17
commit
410c7cc55e
13 files changed
+97
-70
No files matched your search
@@ -1,15 +1,18 @@
|
||||
{{template "devtest/devtest-header"}}
|
||||
<div class="page-content devtest ui container">
|
||||
<div class="modal-buttons flex-text-block tw-flex-wrap"></div>
|
||||
<dialog id="test-modal-form-1" class="modal-dialog">
|
||||
<div class="header">Form dialog (layout 1)</div>
|
||||
<form class="content" method="post" action="?mock_response_delay=1">
|
||||
<div class="ui input tw-w-full"><input name="user_input"></div>
|
||||
{{template "base/modal_actions_confirm" (dict "ModalButtonTypes" "confirm")}}
|
||||
</form>
|
||||
</dialog>
|
||||
|
||||
<dialog id="test-modal-form-2" class="modal-dialog">
|
||||
<template id="test-modal-form-1" data-devtest-modal>
|
||||
<dialog class="modal-dialog">
|
||||
<div class="header">Form dialog (layout 1)</div>
|
||||
<form class="content" method="post" action="?mock_response_delay=1">
|
||||
<div class="ui input tw-w-full"><input name="user_input"></div>
|
||||
{{template "base/modal_actions_confirm" (dict "ModalButtonTypes" "confirm")}}
|
||||
</form>
|
||||
</dialog>
|
||||
</template>
|
||||
|
||||
<dialog id="test-modal-form-2" class="modal-dialog" data-devtest-modal>
|
||||
<div class="header">Form dialog (layout 2)</div>
|
||||
<form method="post" action="?mock_response_delay=1">
|
||||
<div class="content">
|
||||
@@ -19,7 +22,7 @@
|
||||
</form>
|
||||
</dialog>
|
||||
|
||||
<dialog id="test-modal-form-3" class="modal-dialog">
|
||||
<dialog id="test-modal-form-3" class="modal-dialog" data-devtest-modal>
|
||||
<div class="header">Form dialog (layout 3)</div>
|
||||
<form method="post" action="?mock_response_delay=1">
|
||||
<div class="content">
|
||||
@@ -29,7 +32,7 @@
|
||||
</form>
|
||||
</dialog>
|
||||
|
||||
<dialog id="test-modal-form-4" class="modal-dialog">
|
||||
<dialog id="test-modal-form-4" class="modal-dialog" data-devtest-modal>
|
||||
<div class="header">Form dialog (layout 4)</div>
|
||||
<div class="content">
|
||||
<div class="ui input tw-w-full"><input name="user_input"></div>
|
||||
@@ -39,7 +42,7 @@
|
||||
</form>
|
||||
</dialog>
|
||||
|
||||
<dialog id="test-modal-form-5" class="modal-dialog">
|
||||
<dialog id="test-modal-form-5" class="modal-dialog" data-devtest-modal>
|
||||
<div class="header">Form dialog (layout 5)</div>
|
||||
<div class="content">
|
||||
<form method="post" action="?mock_response_delay=1">
|
||||
@@ -49,7 +52,7 @@
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<dialog class="modal-dialog" id="test-modal-default">
|
||||
<dialog class="modal-dialog" id="test-modal-default" data-devtest-modal>
|
||||
<div class="header">{{svg "octicon-file"}} Default dialog <span>title</span></div>
|
||||
<div class="content">
|
||||
very long aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
|
||||
@@ -57,13 +60,13 @@
|
||||
{{template "base/modal_actions_confirm"}}
|
||||
</dialog>
|
||||
|
||||
<dialog class="modal-dialog" id="test-modal-confirm">
|
||||
<dialog class="modal-dialog" id="test-modal-confirm" data-devtest-modal>
|
||||
<div class="header">Confirm dialog</div>
|
||||
<div class="content">hello, this is the modal dialog content</div>
|
||||
{{template "base/modal_actions_confirm" (dict "ModalButtonTypes" "confirm")}}
|
||||
</dialog>
|
||||
|
||||
<dialog class="modal-dialog" id="test-modal-danger">
|
||||
<dialog class="modal-dialog" id="test-modal-danger" data-devtest-modal>
|
||||
<div class="header">dangerous action dialog <button type="button" class="close-modal"></button></div>
|
||||
<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")}}
|
||||
@@ -79,7 +82,7 @@
|
||||
data-modal-a.text-content="fill with attr"
|
||||
>test-modal-fill-values</button>
|
||||
|
||||
<dialog id="test-modal-fill-values" class="modal-dialog" data-skip-button>
|
||||
<dialog id="test-modal-fill-values" class="modal-dialog">
|
||||
<div class="header">Modal dialog (fill values)</div>
|
||||
<form class="content">
|
||||
<div id="fill-by-id"></div>
|
||||
|
||||
@@ -13,12 +13,6 @@
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.modal-backdrop:has(> [open]) {
|
||||
.modal-backdrop.active {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.modal-backdrop > .modal-dialog {
|
||||
position: static;
|
||||
margin-top: auto;
|
||||
margin-bottom: auto;
|
||||
}
|
||||
@@ -3,10 +3,12 @@
|
||||
}
|
||||
|
||||
.modal-dialog {
|
||||
position: static;
|
||||
margin-top: auto;
|
||||
margin-bottom: auto;
|
||||
text-align: left;
|
||||
background: var(--color-body);
|
||||
border: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
color: inherit;
|
||||
box-shadow: 1px 3px 3px 0 var(--color-shadow), 1px 3px 15px 2px var(--color-shadow);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {assignElementProperty, type ElementWithAssignableProperties} from './common-button.ts';
|
||||
import {assignElementProperty, type ElementWithAssignableProperties, initGlobalButtons} from './common-button.ts';
|
||||
import {hideModal} from '../modules/modal.ts';
|
||||
|
||||
test('assignElementProperty', () => {
|
||||
const elForm = document.createElement('form');
|
||||
@@ -25,3 +26,26 @@ test('assignElementProperty', () => {
|
||||
assignElementProperty(elInput, 'read-only', 'true');
|
||||
expect(elInput.readOnly).toBe(true);
|
||||
});
|
||||
|
||||
test('onShowModalClick opens and fills a cloned template dialog', () => {
|
||||
document.body.innerHTML = `
|
||||
<button class="show-modal" data-modal="#modal-template" data-modal-input.value="filled">Open</button>
|
||||
<template id="modal-template">
|
||||
<dialog class="modal-dialog"><input value="original"></dialog>
|
||||
</template>
|
||||
`;
|
||||
initGlobalButtons();
|
||||
const original = document.querySelector('template')!.content.querySelector('dialog')!;
|
||||
|
||||
document.querySelector('button')!.click();
|
||||
|
||||
const modal = document.querySelector<HTMLDialogElement>('dialog.modal-dialog')!;
|
||||
const backdrop = modal.parentElement!;
|
||||
expect(modal.open).toBe(true);
|
||||
expect(modal).not.toBe(original);
|
||||
expect(modal.querySelector('input')!.value).toBe('filled');
|
||||
expect(original.querySelector('input')!.value).toBe('original');
|
||||
hideModal(modal);
|
||||
expect(document.body.contains(modal)).toBe(false);
|
||||
expect(document.body.contains(backdrop)).toBe(false);
|
||||
});
|
||||
@@ -90,7 +90,13 @@ function onShowModalClick(el: HTMLElement, e: MouseEvent) {
|
||||
// to make the template variables get correctly escaped in the URL.
|
||||
e.preventDefault();
|
||||
const modalSelector = el.getAttribute('data-modal')!;
|
||||
const elModal = document.querySelector<HTMLDialogElement>(modalSelector);
|
||||
const elTarget = document.querySelector(modalSelector);
|
||||
let elModal: HTMLDialogElement | null = null;
|
||||
if (elTarget instanceof HTMLDialogElement) {
|
||||
elModal = elTarget;
|
||||
} else if (elTarget instanceof HTMLTemplateElement) {
|
||||
elModal = elTarget.content.querySelector('dialog.modal-dialog')?.cloneNode(true) as HTMLDialogElement;
|
||||
}
|
||||
if (!elModal) throw new Error('no modal for this action');
|
||||
|
||||
const modalAttrPrefix = 'data-modal-';
|
||||
|
||||
@@ -33,7 +33,6 @@ export function confirmModal(modal: HTMLDialogElement | ConfirmModalOptions): Pr
|
||||
resolve(true);
|
||||
},
|
||||
onHidden() {
|
||||
modal.remove();
|
||||
resolve(false);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import {showSuccessToast, showInfoToast, showWarningToast, showErrorToast} from './toast.ts';
|
||||
import {registerGlobalInitFunc} from './observer.ts';
|
||||
import {showModal} from './modal.ts';
|
||||
import {createElementFromHTML} from '../utils/dom.ts';
|
||||
import {html} from '../utils/html.ts';
|
||||
import {showGlobalErrorMessage} from './errors.ts';
|
||||
@@ -25,9 +24,8 @@ function initDevtestPage() {
|
||||
|
||||
const modalButtons = document.querySelector('.modal-buttons');
|
||||
if (modalButtons) {
|
||||
for (const el of document.querySelectorAll<HTMLDialogElement>('.modal-dialog:not([data-skip-button])')) {
|
||||
const btn = createElementFromHTML(html`<button class="ui button">${el.id}</button`);
|
||||
btn.addEventListener('click', () => showModal(el));
|
||||
for (const el of document.querySelectorAll<HTMLDialogElement>('[data-devtest-modal]')) {
|
||||
const btn = createElementFromHTML(html`<button class="ui button show-modal" data-modal="#${el.id}">${el.id}</button`);
|
||||
modalButtons.append(btn);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -326,7 +326,7 @@ async function handleFetchActionSuccessSync(el: Element, successSync: string, re
|
||||
if (res.targets.length > 1) throw new Error(`Fetch-sync command "${successSync}" found multiple target elements, which is not supported`);
|
||||
const target = res.targets[0];
|
||||
if (res.cmdMorph) {
|
||||
Idiomorph.morph(target, respText, {morphStyle: res.cmdInnerHTML ? 'innerHTML' : 'outerHTML'});
|
||||
morphByResult(target, res, respText);
|
||||
} else if (res.cmdInnerHTML) {
|
||||
target.innerHTML = respText;
|
||||
} else {
|
||||
@@ -335,6 +335,14 @@ async function handleFetchActionSuccessSync(el: Element, successSync: string, re
|
||||
await fetchActionReloadOutdatedElements();
|
||||
}
|
||||
|
||||
function morphByResult(target: Element, res: PseudoSelectorCommandResult, respText: string) {
|
||||
const respElem = createElementFromHTML(respText);
|
||||
if (respElem.querySelector('.modal-dialog')) {
|
||||
throw new Error(`Morph with embedded modal dialog is not supported, please use "template" to wrap the dialog.`);
|
||||
}
|
||||
Idiomorph.morph(target, respElem, {morphStyle: res.cmdInnerHTML ? 'innerHTML' : 'outerHTML'});
|
||||
}
|
||||
|
||||
async function fetchActionReloadOutdatedElements() {
|
||||
const outdatedElems: HTMLElement[] = [];
|
||||
for (const outdated of document.querySelectorAll<HTMLElement>('[data-fetch-trigger~="fetch-reload"]')) {
|
||||
@@ -422,8 +430,8 @@ export function initGlobalFetchAction() {
|
||||
// "$" prefix means it is our private command (for special logic), the selectors are run one by one from current element.
|
||||
// * "$this": replace the current element with the response
|
||||
// * "$innerHTML": replace innerHTML of the current element with the response, instead of replacing the whole element (outerHTML)
|
||||
// * "$morph": use morph algorithm to update the target element
|
||||
// * "$body #the-id .the-class": query the selector one by one from body
|
||||
// * "$morph": use morph algorithm to update the target element by the returned (single) element
|
||||
// * "$body .the-class": query the selector one by one from body
|
||||
// * "$closest(tr) td": pseudo command can help to find the target element in a more flexible way
|
||||
//
|
||||
// * data-modal-confirm: a "confirm modal dialog" will be shown before taking action.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {hideAll} from 'tippy.js';
|
||||
import {hideAll as hideTippyAll} from 'tippy.js';
|
||||
import {generateElemId, queryElems} from '../utils/dom.ts';
|
||||
import {hideToastsAll} from './toast.ts';
|
||||
|
||||
@@ -8,7 +8,7 @@ type ModalOpts = {
|
||||
onHidden?: () => void,
|
||||
};
|
||||
|
||||
const modalStates = new WeakMap<Element, {opts: ModalOpts, opener: Element | null}>();
|
||||
const modalStates = new WeakMap<Element, {opts: ModalOpts, opener: Element | null, wasInDocument: boolean}>();
|
||||
|
||||
const topModal = () => Array.from(document.querySelectorAll<HTMLDialogElement>('.modal-dialog[open]')).at(-1);
|
||||
|
||||
@@ -76,29 +76,34 @@ function createModalBackdrop(elModal: HTMLDialogElement): HTMLElement {
|
||||
return elBackdrop;
|
||||
}
|
||||
|
||||
// ATTENTION: showModal will move the document-connected modal element (or adapt the node) to "body" level.
|
||||
// If there will be changes to the original modal element (e.g.: morph),
|
||||
// caller must guarantee that there is no duplicate/conflict by wrapping the modal with a "template" element.
|
||||
export function showModal(elModal: HTMLDialogElement, opts: ModalOpts = {}) {
|
||||
if (elModal.open) return;
|
||||
|
||||
modalStates.set(elModal, {opts, opener: document.activeElement, wasInDocument: elModal.isConnected && document.contains(elModal)});
|
||||
const elBackdrop = elModal.parentElement?.matches('.modal-backdrop') ? elModal.parentElement : createModalBackdrop(elModal);
|
||||
modalStates.set(elModal, {opts, opener: document.activeElement});
|
||||
elModal.querySelector('.close-modal')?.setAttribute('aria-label', 'Close');
|
||||
|
||||
// Avoid "cancel" buttons submitting the form, otherwise "Enter" in the form clicks this "cancel" button before the "ok" button
|
||||
queryElems(elModal, 'form button.cancel:not([type])', (button) => button.setAttribute('type', 'button'));
|
||||
|
||||
hideToastsAll();
|
||||
hideAll();
|
||||
hideTippyAll();
|
||||
blockPage(elBackdrop);
|
||||
|
||||
elBackdrop.classList.add('active');
|
||||
elModal.show(); // not showModal: popups and toasts mounted on body must stay usable above it, see https://github.com/whatwg/html/issues/9936
|
||||
opts.onShow?.();
|
||||
}
|
||||
|
||||
export function hideModal(elModal: HTMLDialogElement) {
|
||||
if (!elModal.open) return;
|
||||
const {opts, opener} = modalStates.get(elModal)!;
|
||||
const {opts, opener, wasInDocument} = modalStates.get(elModal)!;
|
||||
const elBackdrop = elModal.parentElement!;
|
||||
elModal.close();
|
||||
elBackdrop.classList.remove('active');
|
||||
blockPage(topModal()?.parentElement);
|
||||
|
||||
// don't leave the focus in the closed dialog when the opener is gone
|
||||
@@ -108,5 +113,6 @@ export function hideModal(elModal: HTMLDialogElement) {
|
||||
hideToastsAll();
|
||||
queryElems(elModal, 'form', (form: HTMLFormElement) => form.reset());
|
||||
opts.onHidden?.();
|
||||
if (!wasInDocument) elModal.remove();
|
||||
if (!elBackdrop.contains(elModal)) elBackdrop.remove();
|
||||
}
|
||||
@@ -113,7 +113,7 @@ test('shows current shortcuts with ? and closes with Escape or the close button'
|
||||
expect(document.querySelector('#global-shortcut-help')).toBeNull();
|
||||
press('g');
|
||||
expect(press('?', {shiftKey: true}).defaultPrevented).toBe(true);
|
||||
const modal = document.querySelector<HTMLDialogElement>('#global-shortcut-help')!;
|
||||
let modal = document.querySelector<HTMLDialogElement>('#global-shortcut-help')!;
|
||||
expect(modal.open).toBe(true);
|
||||
expect(modal.querySelector('.shortcut-list tr:nth-child(2) td:last-child')!.textContent).toBe('Issues');
|
||||
expect(modal.querySelector('.shortcut-list')!.textContent).toContain('Search code');
|
||||
@@ -127,6 +127,7 @@ test('shows current shortcuts with ? and closes with Escape or the close button'
|
||||
input.setAttribute('placeholder', '<b>Updated search</b>');
|
||||
press('?');
|
||||
expect(document.querySelectorAll('.modal-dialog')).toHaveLength(1);
|
||||
modal = document.querySelector<HTMLDialogElement>('.modal-dialog')!;
|
||||
expect(modal.querySelector('.shortcut-list')!.textContent).toContain('<b>Updated search</b>');
|
||||
expect(modal.querySelector('.shortcut-list b')).toBeNull();
|
||||
expect(modal.querySelectorAll('.shortcut-list tr')).toHaveLength(3);
|
||||
|
||||
@@ -69,26 +69,22 @@ function getShortcutTextContent(elem: Element): string {
|
||||
}
|
||||
|
||||
function showShortcutHelp() {
|
||||
let modal = document.querySelector<HTMLDialogElement>('#global-shortcut-help');
|
||||
if (!modal) {
|
||||
modal = createElementFromHTML<HTMLDialogElement>(html`
|
||||
<dialog id="global-shortcut-help" class="modal-dialog">
|
||||
<div class="header">
|
||||
Keyboard Shortcuts
|
||||
<button type="button" class="close-modal"></button>
|
||||
</div>
|
||||
<div class="scrolling content">
|
||||
<table class="ui very basic compact unstackable table">
|
||||
<tbody class="shortcut-list"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</dialog>
|
||||
`);
|
||||
}
|
||||
const modal = createElementFromHTML<HTMLDialogElement>(html`
|
||||
<dialog id="global-shortcut-help" class="modal-dialog">
|
||||
<div class="header">
|
||||
Keyboard Shortcuts
|
||||
<button type="button" class="close-modal"></button>
|
||||
</div>
|
||||
<div class="scrolling content">
|
||||
<table class="ui very basic compact unstackable table">
|
||||
<tbody class="shortcut-list"><tr><td><kbd>?</kbd></td><td>Keyboard Shortcuts</td></tr></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</dialog>
|
||||
`);
|
||||
|
||||
const seenShortcuts = new Set<string>();
|
||||
const list = modal.querySelector<HTMLElement>('.shortcut-list')!;
|
||||
list.replaceChildren(createElementFromHTML(html`<tr><td><kbd>?</kbd></td><td>Keyboard Shortcuts</td></tr>`));
|
||||
for (const elem of document.querySelectorAll<HTMLElement>('[data-shortcut-keys]')) {
|
||||
const target = elem.matches('kbd') ? elemFromKbd(elem) : elem;
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
} from './dom.ts';
|
||||
|
||||
test('createElementFromHTML', () => {
|
||||
expect(createElementFromHTML('<div></div>').ownerDocument).toBe(document);
|
||||
expect(createElementFromHTML('<a>foo<span>bar</span></a>').outerHTML).toEqual('<a>foo<span>bar</span></a>');
|
||||
expect(createElementFromHTML('<tr data-x="1"><td>foo</td></tr>').outerHTML).toEqual('<tr data-x="1"><td>foo</td></tr>');
|
||||
expect(createElementFromHTML('<TR data-x="1"><td>foo</td></TR>').outerHTML).toEqual('<tr data-x="1"><td>foo</td></tr>');
|
||||
|
||||
+3
-14
@@ -254,20 +254,9 @@ export function isElemVisible(el: HTMLElement): boolean {
|
||||
export function createElementFromHTML<T extends Element>(htmlString: string): T {
|
||||
htmlString = htmlString.trim();
|
||||
if (!htmlString.startsWith('<')) throw new Error(`Invalid HTML element string: ${htmlString}`);
|
||||
const isLetter = (code: number) => (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
|
||||
const startsWithTag = (s: string, tag: string) => {
|
||||
return s.substring(1, 1 + tag.length).toLowerCase() === tag.toLowerCase() &&
|
||||
!isLetter(s[1 + tag.length].charCodeAt(0));
|
||||
};
|
||||
// There is no way to create some elements without a proper parent, jQuery's approach: https://github.com/jquery/jquery/blob/main/src/manipulation/wrapMap.js
|
||||
if (startsWithTag(htmlString, 'tr')) {
|
||||
const container = document.createElement('table');
|
||||
container.innerHTML = htmlString;
|
||||
return container.querySelector<T>('tr')!;
|
||||
}
|
||||
const div = document.createElement('div');
|
||||
div.innerHTML = htmlString;
|
||||
return div.firstChild as T;
|
||||
const template = document.createElement('template');
|
||||
template.innerHTML = htmlString;
|
||||
return document.adoptNode(template.content.firstElementChild!) as T;
|
||||
}
|
||||
|
||||
export function createElementFromAttrs<T extends HTMLElement>(tagName: string, attrs: Record<string, string | number | boolean | null | undefined> | null, ...children: (Node | string)[]): T {
|
||||
|
||||
Reference in new issue
Block a user