Skip to content

Commit 0f397ae

Browse files
authored
Refactor language menu and dom utils (#32450)
1. Make `queryElem*` functions could correctly handle TS types 2. Remove some legacy jQuery $ calls (introduce fomanticQuery for Fomantic UI only) 3. Fix some TS typing problems
1 parent 35bcd66 commit 0f397ae

File tree

10 files changed

+70
-62
lines changed

10 files changed

+70
-62
lines changed

templates/base/footer_content.tmpl

+4-4
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,12 @@
1717
{{end}}
1818
</div>
1919
<div class="right-links" role="group" aria-label="{{ctx.Locale.Tr "aria.footer.links"}}">
20-
<div class="ui dropdown upward language">
20+
<div class="ui dropdown upward">
2121
<span class="flex-text-inline">{{svg "octicon-globe" 14}} {{ctx.Locale.LangName}}</span>
2222
<div class="menu language-menu">
23-
{{range .AllLangs}}
24-
<a lang="{{.Lang}}" data-url="{{AppSubUrl}}/?lang={{.Lang}}" class="item {{if eq ctx.Locale.Lang .Lang}}active selected{{end}}">{{.Name}}</a>
25-
{{end}}
23+
{{range .AllLangs -}}
24+
<a lang="{{.Lang}}" data-url="{{AppSubUrl}}/?lang={{.Lang}}" class="item {{if eq ctx.Locale.Lang .Lang}}selected{{end}}">{{.Name}}</a>
25+
{{end -}}
2626
</div>
2727
</div>
2828
<a href="{{AssetUrlPrefix}}/licenses.txt">{{ctx.Locale.Tr "licenses"}}</a>

web_src/css/home.css

+1-1
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@
7373
margin-left: 5px;
7474
}
7575

76-
.page-footer .ui.dropdown.language .menu {
76+
.page-footer .ui.dropdown .menu.language-menu {
7777
max-height: min(500px, calc(100vh - 60px));
7878
overflow-y: auto;
7979
margin-bottom: 10px;

web_src/js/features/common-page.ts

+14-13
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
import $ from 'jquery';
21
import {GET} from '../modules/fetch.ts';
32
import {showGlobalErrorMessage} from '../bootstrap.ts';
3+
import {fomanticQuery} from '../modules/fomantic/base.ts';
4+
import {queryElems} from '../utils/dom.ts';
45

56
const {appUrl} = window.config;
67

@@ -17,18 +18,18 @@ export function initHeadNavbarContentToggle() {
1718
}
1819

1920
export function initFootLanguageMenu() {
20-
async function linkLanguageAction() {
21-
const $this = $(this);
22-
await GET($this.data('url'));
21+
document.querySelector('.ui.dropdown .menu.language-menu')?.addEventListener('click', async (e) => {
22+
const item = (e.target as HTMLElement).closest('.item');
23+
if (!item) return;
24+
e.preventDefault();
25+
await GET(item.getAttribute('data-url'));
2326
window.location.reload();
24-
}
25-
26-
$('.language-menu a[lang]').on('click', linkLanguageAction);
27+
});
2728
}
2829

2930
export function initGlobalDropdown() {
3031
// Semantic UI modules.
31-
const $uiDropdowns = $('.ui.dropdown');
32+
const $uiDropdowns = fomanticQuery('.ui.dropdown');
3233

3334
// do not init "custom" dropdowns, "custom" dropdowns are managed by their own code.
3435
$uiDropdowns.filter(':not(.custom)').dropdown();
@@ -46,14 +47,14 @@ export function initGlobalDropdown() {
4647
},
4748
onHide() {
4849
this._tippy?.enable();
50+
// eslint-disable-next-line unicorn/no-this-assignment
51+
const elDropdown = this;
4952

5053
// hide all tippy elements of items after a while. eg: use Enter to click "Copy Link" in the Issue Context Menu
5154
setTimeout(() => {
52-
const $dropdown = $(this);
55+
const $dropdown = fomanticQuery(elDropdown);
5356
if ($dropdown.dropdown('is hidden')) {
54-
$(this).find('.menu > .item').each((_, item) => {
55-
item._tippy?.hide();
56-
});
57+
queryElems(elDropdown, '.menu > .item', (el) => el._tippy?.hide());
5758
}
5859
}, 2000);
5960
},
@@ -71,7 +72,7 @@ export function initGlobalDropdown() {
7172
}
7273

7374
export function initGlobalTabularMenu() {
74-
$('.ui.menu.tabular:not(.custom) .item').tab({autoTabActivation: false});
75+
fomanticQuery('.ui.menu.tabular:not(.custom) .item').tab({autoTabActivation: false});
7576
}
7677

7778
/**

web_src/js/features/imagediff.ts

+17-15
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
import $ from 'jquery';
21
import {GET} from '../modules/fetch.ts';
32
import {hideElem, loadElem, queryElemChildren, queryElems} from '../utils/dom.ts';
43
import {parseDom} from '../utils.ts';
4+
import {fomanticQuery} from '../modules/fomantic/base.ts';
55

66
function getDefaultSvgBoundsIfUndefined(text, src) {
77
const defaultSize = 300;
88
const maxSize = 99999;
99

1010
const svgDoc = parseDom(text, 'image/svg+xml');
11-
const svg = svgDoc.documentElement;
11+
const svg = (svgDoc.documentElement as unknown) as SVGSVGElement;
1212
const width = svg?.width?.baseVal;
1313
const height = svg?.height?.baseVal;
1414
if (width === undefined || height === undefined) {
@@ -68,25 +68,27 @@ function createContext(imageAfter, imageBefore) {
6868
}
6969

7070
class ImageDiff {
71-
async init(containerEl) {
71+
containerEl: HTMLElement;
72+
diffContainerWidth: number;
73+
74+
async init(containerEl: HTMLElement) {
7275
this.containerEl = containerEl;
7376
containerEl.setAttribute('data-image-diff-loaded', 'true');
7477

75-
// the only jQuery usage in this file
76-
$(containerEl).find('.ui.menu.tabular .item').tab({autoTabActivation: false});
78+
fomanticQuery(containerEl).find('.ui.menu.tabular .item').tab({autoTabActivation: false});
7779

7880
// the container may be hidden by "viewed" checkbox, so use the parent's width for reference
7981
this.diffContainerWidth = Math.max(containerEl.closest('.diff-file-box').clientWidth - 300, 100);
8082

8183
const imageInfos = [{
8284
path: containerEl.getAttribute('data-path-after'),
8385
mime: containerEl.getAttribute('data-mime-after'),
84-
images: containerEl.querySelectorAll('img.image-after'), // matches 3 <img>
86+
images: containerEl.querySelectorAll<HTMLImageElement>('img.image-after'), // matches 3 <img>
8587
boundsInfo: containerEl.querySelector('.bounds-info-after'),
8688
}, {
8789
path: containerEl.getAttribute('data-path-before'),
8890
mime: containerEl.getAttribute('data-mime-before'),
89-
images: containerEl.querySelectorAll('img.image-before'), // matches 3 <img>
91+
images: containerEl.querySelectorAll<HTMLImageElement>('img.image-before'), // matches 3 <img>
9092
boundsInfo: containerEl.querySelector('.bounds-info-before'),
9193
}];
9294

@@ -102,8 +104,8 @@ class ImageDiff {
102104
const bounds = getDefaultSvgBoundsIfUndefined(text, info.path);
103105
if (bounds) {
104106
for (const el of info.images) {
105-
el.setAttribute('width', bounds.width);
106-
el.setAttribute('height', bounds.height);
107+
el.setAttribute('width', String(bounds.width));
108+
el.setAttribute('height', String(bounds.height));
107109
}
108110
hideElem(info.boundsInfo);
109111
}
@@ -151,7 +153,7 @@ class ImageDiff {
151153
const boundsInfoBeforeHeight = this.containerEl.querySelector('.bounds-info-before .bounds-info-height');
152154
if (boundsInfoBeforeHeight) {
153155
boundsInfoBeforeHeight.textContent = `${sizes.imageBefore.naturalHeight}px`;
154-
boundsInfoBeforeHeight.classList.add('red', heightChanged);
156+
boundsInfoBeforeHeight.classList.toggle('red', heightChanged);
155157
}
156158
}
157159

@@ -205,7 +207,7 @@ class ImageDiff {
205207
}
206208

207209
// extra height for inner "position: absolute" elements
208-
const swipe = this.containerEl.querySelector('.diff-swipe');
210+
const swipe = this.containerEl.querySelector<HTMLElement>('.diff-swipe');
209211
if (swipe) {
210212
swipe.style.width = `${sizes.maxSize.width * factor + 2}px`;
211213
swipe.style.height = `${sizes.maxSize.height * factor + 30}px`;
@@ -225,7 +227,7 @@ class ImageDiff {
225227
const rect = swipeFrame.getBoundingClientRect();
226228
const value = Math.max(0, Math.min(e.clientX - rect.left, width));
227229
swipeBar.style.left = `${value}px`;
228-
this.containerEl.querySelector('.swipe-container').style.width = `${swipeFrame.clientWidth - value}px`;
230+
this.containerEl.querySelector<HTMLElement>('.swipe-container').style.width = `${swipeFrame.clientWidth - value}px`;
229231
};
230232
const removeEventListeners = () => {
231233
document.removeEventListener('mousemove', onSwipeMouseMove);
@@ -264,11 +266,11 @@ class ImageDiff {
264266
overlayFrame.style.height = `${sizes.maxSize.height * factor + 2}px`;
265267
}
266268

267-
const rangeInput = this.containerEl.querySelector('input[type="range"]');
269+
const rangeInput = this.containerEl.querySelector<HTMLInputElement>('input[type="range"]');
268270

269271
function updateOpacity() {
270272
if (sizes.imageAfter) {
271-
sizes.imageAfter.parentNode.style.opacity = `${rangeInput.value / 100}`;
273+
sizes.imageAfter.parentNode.style.opacity = `${Number(rangeInput.value) / 100}`;
272274
}
273275
}
274276

@@ -278,7 +280,7 @@ class ImageDiff {
278280
}
279281

280282
export function initImageDiff() {
281-
for (const el of queryElems('.image-diff:not([data-image-diff-loaded])')) {
283+
for (const el of queryElems<HTMLImageElement>(document, '.image-diff:not([data-image-diff-loaded])')) {
282284
(new ImageDiff()).init(el); // it is async, but we don't need to await for it
283285
}
284286
}

web_src/js/features/repo-common.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ async function onDownloadArchive(e) {
3131
}
3232

3333
export function initRepoArchiveLinks() {
34-
queryElems('a.archive-link[href]', (el) => el.addEventListener('click', onDownloadArchive));
34+
queryElems(document, 'a.archive-link[href]', (el) => el.addEventListener('click', onDownloadArchive));
3535
}
3636

3737
export function initRepoActivityTopAuthorsChart() {

web_src/js/features/repo-editor.ts

+12-12
Original file line numberDiff line numberDiff line change
@@ -45,17 +45,17 @@ export function initRepoEditor() {
4545
const dropzoneUpload = document.querySelector('.page-content.repository.editor.upload .dropzone');
4646
if (dropzoneUpload) initDropzone(dropzoneUpload);
4747

48-
const editArea = document.querySelector('.page-content.repository.editor textarea#edit_area');
48+
const editArea = document.querySelector<HTMLTextAreaElement>('.page-content.repository.editor textarea#edit_area');
4949
if (!editArea) return;
5050

51-
for (const el of queryElems('.js-quick-pull-choice-option')) {
51+
for (const el of queryElems<HTMLInputElement>(document, '.js-quick-pull-choice-option')) {
5252
el.addEventListener('input', () => {
5353
if (el.value === 'commit-to-new-branch') {
5454
showElem('.quick-pull-branch-name');
55-
document.querySelector('.quick-pull-branch-name input').required = true;
55+
document.querySelector<HTMLInputElement>('.quick-pull-branch-name input').required = true;
5656
} else {
5757
hideElem('.quick-pull-branch-name');
58-
document.querySelector('.quick-pull-branch-name input').required = false;
58+
document.querySelector<HTMLInputElement>('.quick-pull-branch-name input').required = false;
5959
}
6060
document.querySelector('#commit-button').textContent = el.getAttribute('data-button-text');
6161
});
@@ -71,13 +71,13 @@ export function initRepoEditor() {
7171
if (filenameInput.value) {
7272
parts.push(filenameInput.value);
7373
}
74-
document.querySelector('#tree_path').value = parts.join('/');
74+
document.querySelector<HTMLInputElement>('#tree_path').value = parts.join('/');
7575
}
7676
filenameInput.addEventListener('input', function () {
7777
const parts = filenameInput.value.split('/');
7878
const links = Array.from(document.querySelectorAll('.breadcrumb span.section'));
7979
const dividers = Array.from(document.querySelectorAll('.breadcrumb .breadcrumb-divider'));
80-
let warningDiv = document.querySelector('.ui.warning.message.flash-message.flash-warning.space-related');
80+
let warningDiv = document.querySelector<HTMLDivElement>('.ui.warning.message.flash-message.flash-warning.space-related');
8181
let containSpace = false;
8282
if (parts.length > 1) {
8383
for (let i = 0; i < parts.length; ++i) {
@@ -110,14 +110,14 @@ export function initRepoEditor() {
110110
filenameInput.value = value;
111111
}
112112
this.setSelectionRange(0, 0);
113-
containSpace |= (trimValue !== value && trimValue !== '');
113+
containSpace = containSpace || (trimValue !== value && trimValue !== '');
114114
}
115115
}
116-
containSpace |= Array.from(links).some((link) => {
116+
containSpace = containSpace || Array.from(links).some((link) => {
117117
const value = link.querySelector('a').textContent;
118118
return value.trim() !== value;
119119
});
120-
containSpace |= parts[parts.length - 1].trim() !== parts[parts.length - 1];
120+
containSpace = containSpace || parts[parts.length - 1].trim() !== parts[parts.length - 1];
121121
if (containSpace) {
122122
if (!warningDiv) {
123123
warningDiv = document.createElement('div');
@@ -135,8 +135,8 @@ export function initRepoEditor() {
135135
joinTreePath();
136136
});
137137
filenameInput.addEventListener('keydown', function (e) {
138-
const sections = queryElems('.breadcrumb span.section');
139-
const dividers = queryElems('.breadcrumb .breadcrumb-divider');
138+
const sections = queryElems(document, '.breadcrumb span.section');
139+
const dividers = queryElems(document, '.breadcrumb .breadcrumb-divider');
140140
// Jump back to last directory once the filename is empty
141141
if (e.code === 'Backspace' && filenameInput.selectionStart === 0 && sections.length > 0) {
142142
e.preventDefault();
@@ -159,7 +159,7 @@ export function initRepoEditor() {
159159

160160
// Using events from https://github.com/codedance/jquery.AreYouSure#advanced-usage
161161
// to enable or disable the commit button
162-
const commitButton = document.querySelector('#commit-button');
162+
const commitButton = document.querySelector<HTMLButtonElement>('#commit-button');
163163
const $editForm = $('.ui.edit.form');
164164
const dirtyFileClass = 'dirty-file';
165165

web_src/js/features/repo-settings.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ const {appSubUrl, csrfToken} = window.config;
88

99
function initRepoSettingsCollaboration() {
1010
// Change collaborator access mode
11-
for (const dropdownEl of queryElems('.page-content.repository .ui.dropdown.access-mode')) {
11+
for (const dropdownEl of queryElems(document, '.page-content.repository .ui.dropdown.access-mode')) {
1212
const textEl = dropdownEl.querySelector(':scope > .text');
1313
$(dropdownEl).dropdown({
1414
async action(text, value) {

web_src/js/modules/fomantic/base.ts

+4
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import $ from 'jquery';
12
let ariaIdCounter = 0;
23

34
export function generateAriaId() {
@@ -16,3 +17,6 @@ export function linkLabelAndInput(label, input) {
1617
label.setAttribute('for', id);
1718
}
1819
}
20+
21+
// eslint-disable-next-line no-jquery/variable-pattern
22+
export const fomanticQuery = $;

web_src/js/modules/tippy.ts

+3-5
Original file line numberDiff line numberDiff line change
@@ -179,11 +179,9 @@ export function initGlobalTooltips() {
179179
}
180180

181181
export function showTemporaryTooltip(target: Element, content: Content) {
182-
// if the target is inside a dropdown, don't show the tooltip because when the dropdown
183-
// closes, the tippy would be pushed unsightly to the top-left of the screen like seen
184-
// on the issue comment menu.
185-
if (target.closest('.ui.dropdown > .menu')) return;
186-
182+
// if the target is inside a dropdown, the menu will be hidden soon
183+
// so display the tooltip on the dropdown instead
184+
target = target.closest('.ui.dropdown') || target;
187185
const tippy = target._tippy ?? attachTooltip(target, content);
188186
tippy.setContent(content);
189187
if (!tippy.state.isShown) tippy.show();

web_src/js/utils/dom.ts

+13-10
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import type $ from 'jquery';
55
type ElementArg = Element | string | NodeListOf<Element> | Array<Element> | ReturnType<typeof $>;
66
type ElementsCallback = (el: Element) => Promisable<any>;
77
type ElementsCallbackWithArgs = (el: Element, ...args: any[]) => Promisable<any>;
8-
type IterableElements = NodeListOf<Element> | Array<Element>;
8+
type ArrayLikeIterable<T> = ArrayLike<T> & Iterable<T>; // for NodeListOf and Array
99

1010
function elementsCall(el: ElementArg, func: ElementsCallbackWithArgs, ...args: any[]) {
1111
if (typeof el === 'string' || el instanceof String) {
@@ -15,7 +15,7 @@ function elementsCall(el: ElementArg, func: ElementsCallbackWithArgs, ...args: a
1515
func(el, ...args);
1616
} else if (el.length !== undefined) {
1717
// this works for: NodeList, HTMLCollection, Array, jQuery
18-
for (const e of (el as IterableElements)) {
18+
for (const e of (el as ArrayLikeIterable<Element>)) {
1919
func(e, ...args);
2020
}
2121
} else {
@@ -58,7 +58,7 @@ export function isElemHidden(el: ElementArg) {
5858
return res[0];
5959
}
6060

61-
function applyElemsCallback(elems: IterableElements, fn?: ElementsCallback) {
61+
function applyElemsCallback<T extends Element>(elems: ArrayLikeIterable<T>, fn?: ElementsCallback): ArrayLikeIterable<T> {
6262
if (fn) {
6363
for (const el of elems) {
6464
fn(el);
@@ -67,19 +67,22 @@ function applyElemsCallback(elems: IterableElements, fn?: ElementsCallback) {
6767
return elems;
6868
}
6969

70-
export function queryElemSiblings(el: Element, selector = '*', fn?: ElementsCallback) {
71-
return applyElemsCallback(Array.from(el.parentNode.children).filter((child: Element) => {
70+
export function queryElemSiblings<T extends Element>(el: Element, selector = '*', fn?: ElementsCallback): ArrayLikeIterable<T> {
71+
const elems = Array.from(el.parentNode.children) as T[];
72+
return applyElemsCallback<T>(elems.filter((child: Element) => {
7273
return child !== el && child.matches(selector);
7374
}), fn);
7475
}
7576

7677
// it works like jQuery.children: only the direct children are selected
77-
export function queryElemChildren(parent: Element | ParentNode, selector = '*', fn?: ElementsCallback) {
78-
return applyElemsCallback(parent.querySelectorAll(`:scope > ${selector}`), fn);
78+
export function queryElemChildren<T extends Element>(parent: Element | ParentNode, selector = '*', fn?: ElementsCallback): ArrayLikeIterable<T> {
79+
return applyElemsCallback<T>(parent.querySelectorAll(`:scope > ${selector}`), fn);
7980
}
8081

81-
export function queryElems(selector: string, fn?: ElementsCallback) {
82-
return applyElemsCallback(document.querySelectorAll(selector), fn);
82+
// it works like parent.querySelectorAll: all descendants are selected
83+
// in the future, all "queryElems(document, ...)" should be refactored to use a more specific parent
84+
export function queryElems<T extends Element>(parent: Element | ParentNode, selector: string, fn?: ElementsCallback): ArrayLikeIterable<T> {
85+
return applyElemsCallback<T>(parent.querySelectorAll(selector), fn);
8386
}
8487

8588
export function onDomReady(cb: () => Promisable<void>) {
@@ -92,7 +95,7 @@ export function onDomReady(cb: () => Promisable<void>) {
9295

9396
// checks whether an element is owned by the current document, and whether it is a document fragment or element node
9497
// if it is, it means it is a "normal" element managed by us, which can be modified safely.
95-
export function isDocumentFragmentOrElementNode(el: Element | Node) {
98+
export function isDocumentFragmentOrElementNode(el: Node) {
9699
try {
97100
return el.ownerDocument === document && el.nodeType === Node.ELEMENT_NODE || el.nodeType === Node.DOCUMENT_FRAGMENT_NODE;
98101
} catch {

0 commit comments

Comments
 (0)