From 33dd0013920e4859ae97fcd3da3ddd483460499d Mon Sep 17 00:00:00 2001 From: silverwind Date: Sat, 13 Jul 2024 14:02:44 +0200 Subject: [PATCH 1/7] Add types to request,toast,bootstrap --- types.d.ts | 4 ++++ web_src/js/bootstrap.ts | 25 ++++++++----------------- web_src/js/modules/fetch.ts | 21 ++++++++++++++------- web_src/js/modules/toast.ts | 26 +++++++++++++++++++++----- web_src/js/svg.ts | 2 ++ web_src/js/types.ts | 2 ++ 6 files changed, 51 insertions(+), 29 deletions(-) diff --git a/types.d.ts b/types.d.ts index ddfe90407fc3..62148a6f8296 100644 --- a/types.d.ts +++ b/types.d.ts @@ -10,6 +10,10 @@ interface Window { $: typeof import('@types/jquery'), jQuery: typeof import('@types/jquery'), htmx: typeof import('htmx.org'), + _globalHandlerErrors: Array & { + _inited: boolean, + push: (e: any) => any, + }, } declare module 'htmx.org/dist/htmx.esm.js' { diff --git a/web_src/js/bootstrap.ts b/web_src/js/bootstrap.ts index 26627dfdedbb..9e41673b86c8 100644 --- a/web_src/js/bootstrap.ts +++ b/web_src/js/bootstrap.ts @@ -1,12 +1,13 @@ // DO NOT IMPORT window.config HERE! // to make sure the error handler always works, we should never import `window.config`, because // some user's custom template breaks it. +import type {Intent} from './types.ts'; // This sets up the URL prefix used in webpack's chunk loading. // This file must be imported before any lazy-loading is being attempted. __webpack_public_path__ = `${window.config?.assetUrlPrefix ?? '/assets'}/`; -function shouldIgnoreError(err) { +function shouldIgnoreError(err: Error) { const ignorePatterns = [ '/assets/js/monaco.', // https://github.com/go-gitea/gitea/issues/30861 , https://github.com/microsoft/monaco-editor/issues/4496 ]; @@ -16,14 +17,14 @@ function shouldIgnoreError(err) { return false; } -export function showGlobalErrorMessage(msg, msgType = 'error') { +export function showGlobalErrorMessage(msg: string, msgType: Intent = 'error') { const msgContainer = document.querySelector('.page-content') ?? document.body; const msgCompact = msg.replace(/\W/g, '').trim(); // compact the message to a data attribute to avoid too many duplicated messages - let msgDiv = msgContainer.querySelector(`.js-global-error[data-global-error-msg-compact="${msgCompact}"]`); + let msgDiv = msgContainer.querySelector(`.js-global-error[data-global-error-msg-compact="${msgCompact}"]`); if (!msgDiv) { const el = document.createElement('div'); el.innerHTML = `
`; - msgDiv = el.childNodes[0]; + msgDiv = el.childNodes[0] as HTMLDivElement; } // merge duplicated messages into "the message (count)" format const msgCount = Number(msgDiv.getAttribute(`data-global-error-msg-count`)) + 1; @@ -33,18 +34,7 @@ export function showGlobalErrorMessage(msg, msgType = 'error') { msgContainer.prepend(msgDiv); } -/** - * @param {ErrorEvent|PromiseRejectionEvent} event - Event - * @param {string} event.message - Only present on ErrorEvent - * @param {string} event.error - Only present on ErrorEvent - * @param {string} event.type - Only present on ErrorEvent - * @param {string} event.filename - Only present on ErrorEvent - * @param {number} event.lineno - Only present on ErrorEvent - * @param {number} event.colno - Only present on ErrorEvent - * @param {string} event.reason - Only present on PromiseRejectionEvent - * @param {number} event.promise - Only present on PromiseRejectionEvent - */ -function processWindowErrorEvent({error, reason, message, type, filename, lineno, colno}) { +function processWindowErrorEvent({error, reason, message, type, filename, lineno, colno}: ErrorEvent & PromiseRejectionEvent) { const err = error ?? reason; const assetBaseUrl = String(new URL(__webpack_public_path__, window.location.origin)); const {runModeIsProd} = window.config ?? {}; @@ -90,7 +80,8 @@ function initGlobalErrorHandler() { } // then, change _globalHandlerErrors to an object with push method, to process further error // events directly - window._globalHandlerErrors = {_inited: true, push: (e) => processWindowErrorEvent(e)}; + // @ts-expect-error -- this should be refactored to not use a fake array + window._globalHandlerErrors = {_inited: true, push: (e: ErrorEvent & PromiseRejectionEvent) => processWindowErrorEvent(e)}; } initGlobalErrorHandler(); diff --git a/web_src/js/modules/fetch.ts b/web_src/js/modules/fetch.ts index b70a4cb3048b..baecaf06d54e 100644 --- a/web_src/js/modules/fetch.ts +++ b/web_src/js/modules/fetch.ts @@ -5,11 +5,18 @@ const {csrfToken} = window.config; // safe HTTP methods that don't need a csrf token const safeMethods = new Set(['GET', 'HEAD', 'OPTIONS', 'TRACE']); +type RequestData = string | FormData | URLSearchParams; + +type RequestOpts = { + data?: RequestData, +} & RequestInit; + // fetch wrapper, use below method name functions and the `data` option to pass in data // which will automatically set an appropriate headers. For json content, only object // and array types are currently supported. -export function request(url, {method = 'GET', data, headers = {}, ...other} = {}) { - let body, contentType; +export function request(url: string, {method = 'GET', data, headers = {}, ...other}: RequestOpts = {}) { + let body: RequestData; + let contentType: string; if (data instanceof FormData || data instanceof URLSearchParams) { body = data; } else if (isObject(data) || Array.isArray(data)) { @@ -34,8 +41,8 @@ export function request(url, {method = 'GET', data, headers = {}, ...other} = {} }); } -export const GET = (url, opts) => request(url, {method: 'GET', ...opts}); -export const POST = (url, opts) => request(url, {method: 'POST', ...opts}); -export const PATCH = (url, opts) => request(url, {method: 'PATCH', ...opts}); -export const PUT = (url, opts) => request(url, {method: 'PUT', ...opts}); -export const DELETE = (url, opts) => request(url, {method: 'DELETE', ...opts}); +export const GET = (url: string, opts?: RequestOpts) => request(url, {method: 'GET', ...opts}); +export const POST = (url: string, opts?: RequestOpts) => request(url, {method: 'POST', ...opts}); +export const PATCH = (url: string, opts?: RequestOpts) => request(url, {method: 'PATCH', ...opts}); +export const PUT = (url: string, opts?: RequestOpts) => request(url, {method: 'PUT', ...opts}); +export const DELETE = (url: string, opts?: RequestOpts) => request(url, {method: 'DELETE', ...opts}); diff --git a/web_src/js/modules/toast.ts b/web_src/js/modules/toast.ts index cded48e6c2cf..1270cac54d16 100644 --- a/web_src/js/modules/toast.ts +++ b/web_src/js/modules/toast.ts @@ -2,8 +2,19 @@ import {htmlEscape} from 'escape-goat'; import {svg} from '../svg.ts'; import {animateOnce, showElem} from '../utils/dom.ts'; import Toastify from 'toastify-js'; // don't use "async import", because when network error occurs, the "async import" also fails and nothing is shown +import type {Intent} from '../types.ts'; +import type {SvgName} from '../svg.ts'; +import type {Options as ToastifyOption} from 'toastify-js'; -const levels = { +type ToastLevels = { + [intent: string]: { + icon: SvgName, + background: string, + duration: number, + } +} + +const levels: ToastLevels = { info: { icon: 'octicon-check', background: 'var(--color-green)', @@ -21,8 +32,13 @@ const levels = { }, }; +type ToastOpts = { + useHtmlBody?: boolean, + preventDuplicates?: boolean, +} & ToastifyOption; + // See https://github.com/apvarun/toastify-js#api for options -function showToast(message, level, {gravity, position, duration, useHtmlBody, preventDuplicates = true, ...other} = {}) { +function showToast(message: string, level: Intent, {gravity, position, duration, useHtmlBody, preventDuplicates = true, ...other}: ToastOpts = {}) { const body = useHtmlBody ? String(message) : htmlEscape(message); const key = `${level}-${body}`; @@ -59,14 +75,14 @@ function showToast(message, level, {gravity, position, duration, useHtmlBody, pr return toast; } -export function showInfoToast(message, opts) { +export function showInfoToast(message: string, opts?: ToastOpts) { return showToast(message, 'info', opts); } -export function showWarningToast(message, opts) { +export function showWarningToast(message: string, opts?: ToastOpts) { return showToast(message, 'warning', opts); } -export function showErrorToast(message, opts) { +export function showErrorToast(message: string, opts?: ToastOpts) { return showToast(message, 'error', opts); } diff --git a/web_src/js/svg.ts b/web_src/js/svg.ts index a0fe52a7be20..24487213a81c 100644 --- a/web_src/js/svg.ts +++ b/web_src/js/svg.ts @@ -146,6 +146,8 @@ const svgs = { 'octicon-x-circle-fill': octiconXCircleFill, }; +export type SvgName = keyof typeof svgs; + // TODO: use a more general approach to access SVG icons. // At the moment, developers must check, pick and fill the names manually, // most of the SVG icons in assets couldn't be used directly. diff --git a/web_src/js/types.ts b/web_src/js/types.ts index f69aa9276802..771e14a938eb 100644 --- a/web_src/js/types.ts +++ b/web_src/js/types.ts @@ -21,3 +21,5 @@ export type Config = { mermaidMaxSourceCharacters: number, i18n: Record, } + +export type Intent = 'error' | 'warning' | 'info'; From e93543e086a8174b04569b6ebaf5f256462e4f10 Mon Sep 17 00:00:00 2001 From: silverwind Date: Sat, 13 Jul 2024 14:07:38 +0200 Subject: [PATCH 2/7] more precise type --- types.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types.d.ts b/types.d.ts index 62148a6f8296..3da7cbe05039 100644 --- a/types.d.ts +++ b/types.d.ts @@ -12,7 +12,7 @@ interface Window { htmx: typeof import('htmx.org'), _globalHandlerErrors: Array & { _inited: boolean, - push: (e: any) => any, + push: (e: ErrorEvent & PromiseRejectionEvent) => void | number, }, } From 58ae194d1ca9f476ca924494636fc2f3be2475a1 Mon Sep 17 00:00:00 2001 From: silverwind Date: Sat, 13 Jul 2024 14:10:36 +0200 Subject: [PATCH 3/7] don't rename --- web_src/js/modules/toast.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/web_src/js/modules/toast.ts b/web_src/js/modules/toast.ts index 1270cac54d16..4478f7cf6f24 100644 --- a/web_src/js/modules/toast.ts +++ b/web_src/js/modules/toast.ts @@ -4,7 +4,7 @@ import {animateOnce, showElem} from '../utils/dom.ts'; import Toastify from 'toastify-js'; // don't use "async import", because when network error occurs, the "async import" also fails and nothing is shown import type {Intent} from '../types.ts'; import type {SvgName} from '../svg.ts'; -import type {Options as ToastifyOption} from 'toastify-js'; +import type {Options} from 'toastify-js'; type ToastLevels = { [intent: string]: { @@ -35,7 +35,7 @@ const levels: ToastLevels = { type ToastOpts = { useHtmlBody?: boolean, preventDuplicates?: boolean, -} & ToastifyOption; +} & Options; // See https://github.com/apvarun/toastify-js#api for options function showToast(message: string, level: Intent, {gravity, position, duration, useHtmlBody, preventDuplicates = true, ...other}: ToastOpts = {}) { From 490500daa3b141819838f5c97340755372bbb38b Mon Sep 17 00:00:00 2001 From: silverwind Date: Sat, 13 Jul 2024 14:20:48 +0200 Subject: [PATCH 4/7] use correct index signature --- web_src/js/modules/toast.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web_src/js/modules/toast.ts b/web_src/js/modules/toast.ts index 4478f7cf6f24..264ccbbdce77 100644 --- a/web_src/js/modules/toast.ts +++ b/web_src/js/modules/toast.ts @@ -7,7 +7,7 @@ import type {SvgName} from '../svg.ts'; import type {Options} from 'toastify-js'; type ToastLevels = { - [intent: string]: { + [intent in Intent]: { icon: SvgName, background: string, duration: number, From 45e563f5b3bd1660db8d4a959f5567671e15ea0a Mon Sep 17 00:00:00 2001 From: silverwind Date: Sat, 13 Jul 2024 14:23:25 +0200 Subject: [PATCH 5/7] move request types to types.ts --- web_src/js/modules/fetch.ts | 7 +------ web_src/js/types.ts | 6 ++++++ 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/web_src/js/modules/fetch.ts b/web_src/js/modules/fetch.ts index baecaf06d54e..90ff7184986c 100644 --- a/web_src/js/modules/fetch.ts +++ b/web_src/js/modules/fetch.ts @@ -1,16 +1,11 @@ import {isObject} from '../utils.ts'; +import type {RequestData, RequestOpts} from '../types.ts'; const {csrfToken} = window.config; // safe HTTP methods that don't need a csrf token const safeMethods = new Set(['GET', 'HEAD', 'OPTIONS', 'TRACE']); -type RequestData = string | FormData | URLSearchParams; - -type RequestOpts = { - data?: RequestData, -} & RequestInit; - // fetch wrapper, use below method name functions and the `data` option to pass in data // which will automatically set an appropriate headers. For json content, only object // and array types are currently supported. diff --git a/web_src/js/types.ts b/web_src/js/types.ts index 771e14a938eb..57c922519de3 100644 --- a/web_src/js/types.ts +++ b/web_src/js/types.ts @@ -1,3 +1,9 @@ +export type RequestData = string | FormData | URLSearchParams; + +export type RequestOpts = { + data?: RequestData, +} & RequestInit; + export type MentionValue = { key: string, value: string, From 7bedf6bbc7e91c3c1427cab157fe0119553de761 Mon Sep 17 00:00:00 2001 From: silverwind Date: Sat, 13 Jul 2024 14:24:57 +0200 Subject: [PATCH 6/7] move to end --- web_src/js/types.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/web_src/js/types.ts b/web_src/js/types.ts index 57c922519de3..3bd1c072a8a9 100644 --- a/web_src/js/types.ts +++ b/web_src/js/types.ts @@ -1,9 +1,3 @@ -export type RequestData = string | FormData | URLSearchParams; - -export type RequestOpts = { - data?: RequestData, -} & RequestInit; - export type MentionValue = { key: string, value: string, @@ -29,3 +23,9 @@ export type Config = { } export type Intent = 'error' | 'warning' | 'info'; + +export type RequestData = string | FormData | URLSearchParams; + +export type RequestOpts = { + data?: RequestData, +} & RequestInit; From 2dcac2aa67779bd05add127a2c20eb59a163dc16 Mon Sep 17 00:00:00 2001 From: silverwind Date: Sat, 13 Jul 2024 14:38:02 +0200 Subject: [PATCH 7/7] add types to svg.js --- web_src/js/svg.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/web_src/js/svg.ts b/web_src/js/svg.ts index 24487213a81c..6a4bfafc9244 100644 --- a/web_src/js/svg.ts +++ b/web_src/js/svg.ts @@ -153,12 +153,12 @@ export type SvgName = keyof typeof svgs; // most of the SVG icons in assets couldn't be used directly. // retrieve an HTML string for given SVG icon name, size and additional classes -export function svg(name, size = 16, className = '') { +export function svg(name: SvgName, size = 16, className = '') { if (!(name in svgs)) throw new Error(`Unknown SVG icon: ${name}`); if (size === 16 && !className) return svgs[name]; const document = parseDom(svgs[name], 'image/svg+xml'); - const svgNode = document.firstChild; + const svgNode = document.firstChild as SVGElement; if (size !== 16) { svgNode.setAttribute('width', String(size)); svgNode.setAttribute('height', String(size)); @@ -167,7 +167,7 @@ export function svg(name, size = 16, className = '') { return serializeXml(svgNode); } -export function svgParseOuterInner(name) { +export function svgParseOuterInner(name: SvgName) { const svgStr = svgs[name]; if (!svgStr) throw new Error(`Unknown SVG icon: ${name}`); @@ -181,7 +181,7 @@ export function svgParseOuterInner(name) { const svgInnerHtml = svgStr.slice(p1 + 1, p2); const svgOuterHtml = svgStr.slice(0, p1 + 1) + svgStr.slice(p2); const svgDoc = parseDom(svgOuterHtml, 'image/svg+xml'); - const svgOuter = svgDoc.firstChild; + const svgOuter = svgDoc.firstChild as SVGElement; return {svgOuter, svgInnerHtml}; }