Skip to content

Commit 930ca92

Browse files
authored
Add types to fetch,toast,bootstrap,svg (#31627)
Reduce `tsc` error count by 53. None of the changes has any runtime effect.
1 parent cabcca3 commit 930ca92

File tree

6 files changed

+56
-33
lines changed

6 files changed

+56
-33
lines changed

types.d.ts

+4
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ interface Window {
1010
$: typeof import('@types/jquery'),
1111
jQuery: typeof import('@types/jquery'),
1212
htmx: typeof import('htmx.org'),
13+
_globalHandlerErrors: Array<ErrorEvent & PromiseRejectionEvent> & {
14+
_inited: boolean,
15+
push: (e: ErrorEvent & PromiseRejectionEvent) => void | number,
16+
},
1317
}
1418

1519
declare module 'htmx.org/dist/htmx.esm.js' {

web_src/js/bootstrap.ts

+8-17
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
// DO NOT IMPORT window.config HERE!
22
// to make sure the error handler always works, we should never import `window.config`, because
33
// some user's custom template breaks it.
4+
import type {Intent} from './types.ts';
45

56
// This sets up the URL prefix used in webpack's chunk loading.
67
// This file must be imported before any lazy-loading is being attempted.
78
__webpack_public_path__ = `${window.config?.assetUrlPrefix ?? '/assets'}/`;
89

9-
function shouldIgnoreError(err) {
10+
function shouldIgnoreError(err: Error) {
1011
const ignorePatterns = [
1112
'/assets/js/monaco.', // https://github.com/go-gitea/gitea/issues/30861 , https://github.com/microsoft/monaco-editor/issues/4496
1213
];
@@ -16,14 +17,14 @@ function shouldIgnoreError(err) {
1617
return false;
1718
}
1819

19-
export function showGlobalErrorMessage(msg, msgType = 'error') {
20+
export function showGlobalErrorMessage(msg: string, msgType: Intent = 'error') {
2021
const msgContainer = document.querySelector('.page-content') ?? document.body;
2122
const msgCompact = msg.replace(/\W/g, '').trim(); // compact the message to a data attribute to avoid too many duplicated messages
22-
let msgDiv = msgContainer.querySelector(`.js-global-error[data-global-error-msg-compact="${msgCompact}"]`);
23+
let msgDiv = msgContainer.querySelector<HTMLDivElement>(`.js-global-error[data-global-error-msg-compact="${msgCompact}"]`);
2324
if (!msgDiv) {
2425
const el = document.createElement('div');
2526
el.innerHTML = `<div class="ui container js-global-error tw-my-[--page-spacing]"><div class="ui ${msgType} message tw-text-center tw-whitespace-pre-line"></div></div>`;
26-
msgDiv = el.childNodes[0];
27+
msgDiv = el.childNodes[0] as HTMLDivElement;
2728
}
2829
// merge duplicated messages into "the message (count)" format
2930
const msgCount = Number(msgDiv.getAttribute(`data-global-error-msg-count`)) + 1;
@@ -33,18 +34,7 @@ export function showGlobalErrorMessage(msg, msgType = 'error') {
3334
msgContainer.prepend(msgDiv);
3435
}
3536

36-
/**
37-
* @param {ErrorEvent|PromiseRejectionEvent} event - Event
38-
* @param {string} event.message - Only present on ErrorEvent
39-
* @param {string} event.error - Only present on ErrorEvent
40-
* @param {string} event.type - Only present on ErrorEvent
41-
* @param {string} event.filename - Only present on ErrorEvent
42-
* @param {number} event.lineno - Only present on ErrorEvent
43-
* @param {number} event.colno - Only present on ErrorEvent
44-
* @param {string} event.reason - Only present on PromiseRejectionEvent
45-
* @param {number} event.promise - Only present on PromiseRejectionEvent
46-
*/
47-
function processWindowErrorEvent({error, reason, message, type, filename, lineno, colno}) {
37+
function processWindowErrorEvent({error, reason, message, type, filename, lineno, colno}: ErrorEvent & PromiseRejectionEvent) {
4838
const err = error ?? reason;
4939
const assetBaseUrl = String(new URL(__webpack_public_path__, window.location.origin));
5040
const {runModeIsProd} = window.config ?? {};
@@ -90,7 +80,8 @@ function initGlobalErrorHandler() {
9080
}
9181
// then, change _globalHandlerErrors to an object with push method, to process further error
9282
// events directly
93-
window._globalHandlerErrors = {_inited: true, push: (e) => processWindowErrorEvent(e)};
83+
// @ts-expect-error -- this should be refactored to not use a fake array
84+
window._globalHandlerErrors = {_inited: true, push: (e: ErrorEvent & PromiseRejectionEvent) => processWindowErrorEvent(e)};
9485
}
9586

9687
initGlobalErrorHandler();

web_src/js/modules/fetch.ts

+9-7
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {isObject} from '../utils.ts';
2+
import type {RequestData, RequestOpts} from '../types.ts';
23

34
const {csrfToken} = window.config;
45

@@ -8,8 +9,9 @@ const safeMethods = new Set(['GET', 'HEAD', 'OPTIONS', 'TRACE']);
89
// fetch wrapper, use below method name functions and the `data` option to pass in data
910
// which will automatically set an appropriate headers. For json content, only object
1011
// and array types are currently supported.
11-
export function request(url, {method = 'GET', data, headers = {}, ...other} = {}) {
12-
let body, contentType;
12+
export function request(url: string, {method = 'GET', data, headers = {}, ...other}: RequestOpts = {}) {
13+
let body: RequestData;
14+
let contentType: string;
1315
if (data instanceof FormData || data instanceof URLSearchParams) {
1416
body = data;
1517
} else if (isObject(data) || Array.isArray(data)) {
@@ -34,8 +36,8 @@ export function request(url, {method = 'GET', data, headers = {}, ...other} = {}
3436
});
3537
}
3638

37-
export const GET = (url, opts) => request(url, {method: 'GET', ...opts});
38-
export const POST = (url, opts) => request(url, {method: 'POST', ...opts});
39-
export const PATCH = (url, opts) => request(url, {method: 'PATCH', ...opts});
40-
export const PUT = (url, opts) => request(url, {method: 'PUT', ...opts});
41-
export const DELETE = (url, opts) => request(url, {method: 'DELETE', ...opts});
39+
export const GET = (url: string, opts?: RequestOpts) => request(url, {method: 'GET', ...opts});
40+
export const POST = (url: string, opts?: RequestOpts) => request(url, {method: 'POST', ...opts});
41+
export const PATCH = (url: string, opts?: RequestOpts) => request(url, {method: 'PATCH', ...opts});
42+
export const PUT = (url: string, opts?: RequestOpts) => request(url, {method: 'PUT', ...opts});
43+
export const DELETE = (url: string, opts?: RequestOpts) => request(url, {method: 'DELETE', ...opts});

web_src/js/modules/toast.ts

+21-5
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,19 @@ import {htmlEscape} from 'escape-goat';
22
import {svg} from '../svg.ts';
33
import {animateOnce, showElem} from '../utils/dom.ts';
44
import Toastify from 'toastify-js'; // don't use "async import", because when network error occurs, the "async import" also fails and nothing is shown
5+
import type {Intent} from '../types.ts';
6+
import type {SvgName} from '../svg.ts';
7+
import type {Options} from 'toastify-js';
58

6-
const levels = {
9+
type ToastLevels = {
10+
[intent in Intent]: {
11+
icon: SvgName,
12+
background: string,
13+
duration: number,
14+
}
15+
}
16+
17+
const levels: ToastLevels = {
718
info: {
819
icon: 'octicon-check',
920
background: 'var(--color-green)',
@@ -21,8 +32,13 @@ const levels = {
2132
},
2233
};
2334

35+
type ToastOpts = {
36+
useHtmlBody?: boolean,
37+
preventDuplicates?: boolean,
38+
} & Options;
39+
2440
// See https://github.com/apvarun/toastify-js#api for options
25-
function showToast(message, level, {gravity, position, duration, useHtmlBody, preventDuplicates = true, ...other} = {}) {
41+
function showToast(message: string, level: Intent, {gravity, position, duration, useHtmlBody, preventDuplicates = true, ...other}: ToastOpts = {}) {
2642
const body = useHtmlBody ? String(message) : htmlEscape(message);
2743
const key = `${level}-${body}`;
2844

@@ -59,14 +75,14 @@ function showToast(message, level, {gravity, position, duration, useHtmlBody, pr
5975
return toast;
6076
}
6177

62-
export function showInfoToast(message, opts) {
78+
export function showInfoToast(message: string, opts?: ToastOpts) {
6379
return showToast(message, 'info', opts);
6480
}
6581

66-
export function showWarningToast(message, opts) {
82+
export function showWarningToast(message: string, opts?: ToastOpts) {
6783
return showToast(message, 'warning', opts);
6884
}
6985

70-
export function showErrorToast(message, opts) {
86+
export function showErrorToast(message: string, opts?: ToastOpts) {
7187
return showToast(message, 'error', opts);
7288
}

web_src/js/svg.ts

+6-4
Original file line numberDiff line numberDiff line change
@@ -146,17 +146,19 @@ const svgs = {
146146
'octicon-x-circle-fill': octiconXCircleFill,
147147
};
148148

149+
export type SvgName = keyof typeof svgs;
150+
149151
// TODO: use a more general approach to access SVG icons.
150152
// At the moment, developers must check, pick and fill the names manually,
151153
// most of the SVG icons in assets couldn't be used directly.
152154

153155
// retrieve an HTML string for given SVG icon name, size and additional classes
154-
export function svg(name, size = 16, className = '') {
156+
export function svg(name: SvgName, size = 16, className = '') {
155157
if (!(name in svgs)) throw new Error(`Unknown SVG icon: ${name}`);
156158
if (size === 16 && !className) return svgs[name];
157159

158160
const document = parseDom(svgs[name], 'image/svg+xml');
159-
const svgNode = document.firstChild;
161+
const svgNode = document.firstChild as SVGElement;
160162
if (size !== 16) {
161163
svgNode.setAttribute('width', String(size));
162164
svgNode.setAttribute('height', String(size));
@@ -165,7 +167,7 @@ export function svg(name, size = 16, className = '') {
165167
return serializeXml(svgNode);
166168
}
167169

168-
export function svgParseOuterInner(name) {
170+
export function svgParseOuterInner(name: SvgName) {
169171
const svgStr = svgs[name];
170172
if (!svgStr) throw new Error(`Unknown SVG icon: ${name}`);
171173

@@ -179,7 +181,7 @@ export function svgParseOuterInner(name) {
179181
const svgInnerHtml = svgStr.slice(p1 + 1, p2);
180182
const svgOuterHtml = svgStr.slice(0, p1 + 1) + svgStr.slice(p2);
181183
const svgDoc = parseDom(svgOuterHtml, 'image/svg+xml');
182-
const svgOuter = svgDoc.firstChild;
184+
const svgOuter = svgDoc.firstChild as SVGElement;
183185
return {svgOuter, svgInnerHtml};
184186
}
185187

web_src/js/types.ts

+8
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,11 @@ export type Config = {
2121
mermaidMaxSourceCharacters: number,
2222
i18n: Record<string, string>,
2323
}
24+
25+
export type Intent = 'error' | 'warning' | 'info';
26+
27+
export type RequestData = string | FormData | URLSearchParams;
28+
29+
export type RequestOpts = {
30+
data?: RequestData,
31+
} & RequestInit;

0 commit comments

Comments
 (0)