Fix a number of Typescript issues (#31877)

Typescript error count is reduced from 633 to 540 with this. No runtime
changes except in test code.
This commit is contained in:
silverwind 2024-08-28 18:32:38 +02:00 committed by GitHub
parent 39d2fdefaf
commit 7207d93f01
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 141 additions and 79 deletions

View file

@ -3,23 +3,23 @@ import type {ColorInput} from 'tinycolor2';
// Returns relative luminance for a SRGB color - https://en.wikipedia.org/wiki/Relative_luminance
// Keep this in sync with modules/util/color.go
function getRelativeLuminance(color: ColorInput) {
function getRelativeLuminance(color: ColorInput): number {
const {r, g, b} = tinycolor(color).toRgb();
return (0.2126729 * r + 0.7151522 * g + 0.072175 * b) / 255;
}
function useLightText(backgroundColor: ColorInput) {
function useLightText(backgroundColor: ColorInput): boolean {
return getRelativeLuminance(backgroundColor) < 0.453;
}
// Given a background color, returns a black or white foreground color that the highest
// contrast ratio. In the future, the APCA contrast function, or CSS `contrast-color` will be better.
// https://github.com/color-js/color.js/blob/eb7b53f7a13bb716ec8b28c7a56f052cd599acd9/src/contrast/APCA.js#L42
export function contrastColor(backgroundColor: ColorInput) {
export function contrastColor(backgroundColor: ColorInput): string {
return useLightText(backgroundColor) ? '#fff' : '#000';
}
function resolveColors(obj: Record<string, string>) {
function resolveColors(obj: Record<string, string>): Record<string, string> {
const styles = window.getComputedStyle(document.documentElement);
const getColor = (name: string) => styles.getPropertyValue(name).trim();
return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, getColor(value)]));

View file

@ -266,10 +266,8 @@ export function initSubmitEventPolyfill() {
/**
* Check if an element is visible, equivalent to jQuery's `:visible` pseudo.
* Note: This function doesn't account for all possible visibility scenarios.
* @param {HTMLElement} element The element to check.
* @returns {boolean} True if the element is visible.
*/
export function isElemVisible(element: HTMLElement) {
export function isElemVisible(element: HTMLElement): boolean {
if (!element) return false;
return Boolean(element.offsetWidth || element.offsetHeight || element.getClientRects().length);

View file

@ -1,6 +1,11 @@
export async function pngChunks(blob) {
type PngChunk = {
name: string,
data: Uint8Array,
}
export async function pngChunks(blob: Blob): Promise<PngChunk[]> {
const uint8arr = new Uint8Array(await blob.arrayBuffer());
const chunks = [];
const chunks: PngChunk[] = [];
if (uint8arr.length < 12) return chunks;
const view = new DataView(uint8arr.buffer);
if (view.getBigUint64(0) !== 9894494448401390090n) return chunks;
@ -19,9 +24,14 @@ export async function pngChunks(blob) {
return chunks;
}
type ImageInfo = {
width?: number,
dppx?: number,
}
// decode a image and try to obtain width and dppx. It will never throw but instead
// return default values.
export async function imageInfo(blob) {
export async function imageInfo(blob: Blob): Promise<ImageInfo> {
let width = 0, dppx = 1; // dppx: 1 dot per pixel for non-HiDPI screens
if (blob.type === 'image/png') { // only png is supported currently

View file

@ -2,17 +2,17 @@ import emojis from '../../../assets/emoji.json';
const maxMatches = 6;
function sortAndReduce(map) {
function sortAndReduce(map: Map<string, number>) {
const sortedMap = new Map(Array.from(map.entries()).sort((a, b) => a[1] - b[1]));
return Array.from(sortedMap.keys()).slice(0, maxMatches);
}
export function matchEmoji(queryText) {
export function matchEmoji(queryText: string): string[] {
const query = queryText.toLowerCase().replaceAll('_', ' ');
if (!query) return emojis.slice(0, maxMatches).map((e) => e.aliases[0]);
// results is a map of weights, lower is better
const results = new Map();
const results = new Map<string, number>();
for (const {aliases} of emojis) {
const mainAlias = aliases[0];
for (const [aliasIndex, alias] of aliases.entries()) {
@ -27,7 +27,7 @@ export function matchEmoji(queryText) {
return sortAndReduce(results);
}
export function matchMention(queryText) {
export function matchMention(queryText: string): string[] {
const query = queryText.toLowerCase();
// results is a map of weights, lower is better

View file

@ -1,16 +1,17 @@
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc.js';
import {getCurrentLocale} from '../utils.ts';
import type {ConfigType} from 'dayjs';
dayjs.extend(utc);
/**
* Returns an array of millisecond-timestamps of start-of-week days (Sundays)
*
* @param startConfig The start date. Can take any type that `Date` accepts.
* @param endConfig The end date. Can take any type that `Date` accepts.
* @param startDate The start date. Can take any type that dayjs accepts.
* @param endDate The end date. Can take any type that dayjs accepts.
*/
export function startDaysBetween(startDate, endDate) {
export function startDaysBetween(startDate: ConfigType, endDate: ConfigType): number[] {
const start = dayjs.utc(startDate);
const end = dayjs.utc(endDate);
@ -21,7 +22,7 @@ export function startDaysBetween(startDate, endDate) {
current = current.add(1, 'day');
}
const startDays = [];
const startDays: number[] = [];
while (current.isBefore(end)) {
startDays.push(current.valueOf());
current = current.add(1, 'week');
@ -30,7 +31,7 @@ export function startDaysBetween(startDate, endDate) {
return startDays;
}
export function firstStartDateAfterDate(inputDate) {
export function firstStartDateAfterDate(inputDate: Date): number {
if (!(inputDate instanceof Date)) {
throw new Error('Invalid date');
}
@ -41,7 +42,14 @@ export function firstStartDateAfterDate(inputDate) {
return resultDate.valueOf();
}
export function fillEmptyStartDaysWithZeroes(startDays, data) {
type DayData = {
week: number,
additions: number,
deletions: number,
commits: number,
}
export function fillEmptyStartDaysWithZeroes(startDays: number[], data: DayData): DayData[] {
const result = {};
for (const startDay of startDays) {
@ -51,11 +59,11 @@ export function fillEmptyStartDaysWithZeroes(startDays, data) {
return Object.values(result);
}
let dateFormat;
let dateFormat: Intl.DateTimeFormat;
// format a Date object to document's locale, but with 24h format from user's current locale because this
// option is a personal preference of the user, not something that the document's locale should dictate.
export function formatDatetime(date) {
export function formatDatetime(date: Date | number): string {
if (!dateFormat) {
// TODO: replace `hour12` with `Intl.Locale.prototype.getHourCycles` once there is broad browser support
dateFormat = new Intl.DateTimeFormat(getCurrentLocale(), {

View file

@ -1,12 +1,12 @@
export function pathEscapeSegments(s) {
export function pathEscapeSegments(s: string): string {
return s.split('/').map(encodeURIComponent).join('/');
}
function stripSlash(url) {
function stripSlash(url: string): string {
return url.endsWith('/') ? url.slice(0, -1) : url;
}
export function isUrl(url) {
export function isUrl(url: string): boolean {
try {
return stripSlash((new URL(url).href)).trim() === stripSlash(url).trim();
} catch {