Files
gitea-MIRROR/web_src/js/modules/observer.ts
Philip Peterson bdee24a7d0 refactor: use data-global-init for ComboMarkdownEditor (#40479)
## TL;DR:

For custom-init markdown editors, do nothing. For non-custom-init
markdown editors, change from an imperative scan to a declarative setup.

## Longer version

As part of the `data-global-init` migration effort, this moves
ComboMarkdownEditor's automatic setup onto `data-global-init`.

### Before

`initGlobalComboMarkdownEditor()` ran a one-off startup sweep of its
own: `queryElems(document, '.combo-markdown-editor:not(.custom-init)',
...)`. The editor template relied on that page-wide selector, with the
`custom-init` class as an exclusion, rather than declaring its own
setup.

### After

- The editor template marks its root element with
`data-global-init="initComboMarkdownEditor"`, and the sweep is replaced
by a registered handler, like other migrated components.
- The attribute goes only on editors without `CustomInit`. `CustomInit`
editors are unchanged: they get no attribute, and their page code sets
them up as before.
- Setup now goes through the shared observer, so the editor follows the
same rules as every other `data-global-init` component, including
elements added after page load.

### Why

- The template now names its own setup:
`data-global-init="initComboMarkdownEditor"` leads straight to the
registered handler. Before, nothing in the template said how the editor
was set up, and the `custom-init` class only meant something because of
a selector in `common-form.ts`.
- It follows the guidance in `modules/observer.ts`, which recommends
`registerGlobalInitFunc` over selector-based setup as "less efficient
and less maintainable", and removes one of the `queryElems(document,
...)` sweeps that `utils/dom.ts` marks for refactoring.
- The editor no longer needs its own page-wide query at startup: it's
picked up by the observer's single initial pass, like the other
`data-global-init` components (55 templates use it today).

### Notes

- Editors are now set up by the observer's initial sweep, which runs
after the page-specific init code rather than before it. Every direct
editor lookup (`getComboMarkdownEditor` in `repo-release.ts`,
`repo-issue-edit.ts`, `repo-issue.ts` and the monospace toggle in
`ComboMarkdownEditor.ts`) runs on a user action, so none is affected.
- This is the first step toward removing `CustomInit` entirely. That
also needs JS-only options moved into presets and setup made idempotent,
which are separate changes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2026-12-02 20:46:29 +00:00

118 lines
5.3 KiB
TypeScript

import {isDocumentFragmentOrElementNode} from '../utils/dom.ts';
import type {Promisable} from '../types.ts';
import type {InitPerformanceTracer} from './init.ts';
import {initAriaLabels} from './fomantic/base.ts';
let globalSelectorObserverInited = false;
type SelectorHandler<T extends Element> = {selector: string, handler: (el: T) => void};
const selectorHandlers: SelectorHandler<Element>[] = [];
type GlobalEventFunc<T extends HTMLElement, E extends Event> = (el: T, e: E) => Promisable<void>;
const globalEventFuncs: Record<string, GlobalEventFunc<HTMLElement, Event>> = {};
type GlobalInitFunc<T extends Element, R> = (el: T) => Promisable<R>;
const globalInitFuncs: Record<string, GlobalInitFunc<Element, unknown>> = {};
// It handles the global events for all `<div data-global-click="onSomeElemClick"></div>` elements.
export function registerGlobalEventFunc<T extends HTMLElement, E extends Event>(event: string, name: string, func: GlobalEventFunc<T, E>) {
globalEventFuncs[`${event}:${name}`] = func as GlobalEventFunc<HTMLElement, Event>;
}
// It handles the global init functions by a selector, for example:
// > registerGlobalSelectorObserver('.ui.dropdown:not(.custom)', (el) => { initDropdown(el, ...) });
// ATTENTION: For most cases, it's recommended to use registerGlobalInitFunc instead,
// Because this selector-based approach is less efficient and less maintainable.
// But if there are already a lot of elements on many pages, this selector-based approach is more convenient for exiting code.
export function registerGlobalSelectorFunc<T extends Element>(selector: string, handler: (el: T) => void) {
selectorHandlers.push({selector, handler: handler as (el: Element) => void});
// Then initAddedElementObserver will call this handler for all existing elements after all handlers are added.
// This approach makes the init stage only need to do one "querySelectorAll".
if (!globalSelectorObserverInited) return;
for (const el of document.querySelectorAll<T>(selector)) {
handler(el);
}
}
// It handles the global init functions for all `<div data-global-init="initSomeElem"></div>` elements.
export function registerGlobalInitFunc<T extends HTMLElement, R>(name: string, handler: GlobalInitFunc<T, R>) {
globalInitFuncs[name] = handler as GlobalInitFunc<Element, unknown>;
// The "global init" functions are managed internally and called by callGlobalInitFunc
// They must be ready before initGlobalSelectorObserver is called.
if (globalSelectorObserverInited) throw new Error('registerGlobalInitFunc() must be called before initGlobalSelectorObserver()');
}
function callGlobalInitFunc(el: Element) {
// TODO: GLOBAL-INIT-MULTIPLE-FUNCTIONS: maybe in the future we need to extend it to support multiple functions, for example: `data-global-init="func1 func2 func3"`
const initFunc = el.getAttribute('data-global-init')!;
const func = globalInitFuncs[initFunc];
if (!func) throw new Error(`Global init function "${initFunc}" not found`);
// when an element node is removed and added again, it should not be re-initialized again.
type GiteaGlobalInitElement = Partial<Element> & {_giteaGlobalInited: boolean};
if ((el as GiteaGlobalInitElement)._giteaGlobalInited) return;
(el as GiteaGlobalInitElement)._giteaGlobalInited = true;
func(el);
}
function attachGlobalEvents() {
// add global "[data-global-click]" event handler
document.addEventListener('click', (e) => {
const elem = (e.target as HTMLElement).closest<HTMLElement>('[data-global-click]');
if (!elem) return;
const funcName = elem.getAttribute('data-global-click');
const func = globalEventFuncs[`click:${funcName}`];
if (!func) throw new Error(`Global event function "click:${funcName}" not found`);
func(elem, e);
});
}
export function initGlobalSelectorObserver(perfTracer: InitPerformanceTracer | null): void {
if (globalSelectorObserverInited) throw new Error('initGlobalSelectorObserver() already called');
globalSelectorObserverInited = true;
attachGlobalEvents();
selectorHandlers.push({selector: '[data-global-init]', handler: callGlobalInitFunc});
const observer = new MutationObserver((mutationList) => {
const len = mutationList.length;
for (let i = 0; i < len; i++) {
const mutation = mutationList[i];
const len = mutation.addedNodes.length;
for (let i = 0; i < len; i++) {
const addedNode = mutation.addedNodes[i] as ParentNode;
if (!isDocumentFragmentOrElementNode(addedNode)) continue;
initAriaLabels(addedNode);
for (const {selector, handler} of selectorHandlers) {
if ((addedNode instanceof Element) && addedNode.matches(selector)) {
handler(addedNode);
}
for (const el of addedNode.querySelectorAll?.<HTMLElement>(selector) ?? []) {
handler(el);
}
}
}
}
});
initAriaLabels(document);
if (perfTracer) {
for (const {selector, handler} of selectorHandlers) {
perfTracer.recordCall(`initGlobalSelectorObserver ${selector}`, () => {
for (const el of document.querySelectorAll<HTMLElement>(selector)) {
handler(el);
}
});
}
} else {
for (const {selector, handler} of selectorHandlers) {
for (const el of document.querySelectorAll<HTMLElement>(selector)) {
handler(el);
}
}
}
observer.observe(document, {subtree: true, childList: true});
}