adapt typescript to strict mode

This commit is contained in:
imperosol
2026-07-13 12:03:38 +02:00
parent 448e67738e
commit ac8a79468e
40 changed files with 386 additions and 242 deletions
@@ -25,7 +25,7 @@ export function limitedChoices(Alpine: AlpineType) {
Alpine.directive(
"limited-choices",
(el, { expression }, { evaluateLater, effect }) => {
const getMaxChoices = evaluateLater(expression);
const getMaxChoices = evaluateLater<string>(expression);
let maxChoices: number;
const inputs: HTMLInputElement[] = Array.from(
el.querySelectorAll("input[type='checkbox']"),
@@ -54,7 +54,7 @@ export function limitedChoices(Alpine: AlpineType) {
});
}
effect(() => {
getMaxChoices((value: string) => {
getMaxChoices((value) => {
const previousValue = maxChoices;
maxChoices = Number.parseInt(value, 10);
if (maxChoices < previousValue) {
+12 -6
View File
@@ -43,13 +43,19 @@ polyfillCountryFlagEmojis();
/**
* HTMX
*/
document.body.addEventListener("htmx:beforeRequest", (event: CustomEvent) => {
event.detail.target.ariaBusy = true;
});
document.body.addEventListener(
"htmx:beforeRequest" as keyof HTMLElementEventMap,
(event) => {
(event as CustomEvent).detail.target.ariaBusy = true;
},
);
document.body.addEventListener("htmx:beforeSwap", (event: CustomEvent) => {
event.detail.target.ariaBusy = null;
});
document.body.addEventListener(
"htmx:beforeSwap" as keyof HTMLElementEventMap,
(event) => {
(event as CustomEvent).detail.target.ariaBusy = null;
},
);
Object.assign(window, { htmx });
@@ -4,9 +4,9 @@ import type {
TomLoadCallback,
TomOption,
TomSettings,
} from "tom-select/dist/types/types";
import type { escape_html } from "tom-select/dist/types/utils";
import { inheritHtmlElement } from "#core:utils/web-components.ts";
} from "tom-select/src/types";
import type { escape_html } from "tom-select/src/utils";
import { inheritHtmlElement } from "#core:utils/web-components";
export class AutoCompleteSelectBase extends inheritHtmlElement("select") {
static observedAttributes = [
@@ -15,7 +15,7 @@ export class AutoCompleteSelectBase extends inheritHtmlElement("select") {
"max",
"min-characters-for-search",
];
public widget: TomSelect;
public widget!: TomSelect;
protected minCharNumberForSearch = 0;
protected delay: number | null = null;
@@ -24,8 +24,8 @@ export class AutoCompleteSelectBase extends inheritHtmlElement("select") {
protected attributeChangedCallback(
name: string,
_oldValue?: string,
newValue?: string,
_oldValue: string,
newValue: string,
) {
switch (name) {
case "delay": {
@@ -73,7 +73,7 @@ export class AutoCompleteSelectBase extends inheritHtmlElement("select") {
persist: false,
maxItems: this.node.multiple ? this.max : 1,
closeAfterSelect: true,
loadThrottle: this.delay,
loadThrottle: this.delay ?? undefined,
placeholder: this.placeholder,
shouldLoad: (query: string) => this.shouldLoad(query), // wraps the method to avoid shadowing `this` by the one from tom-select
render: {
@@ -103,7 +103,7 @@ export class AutoCompleteSelectBase extends inheritHtmlElement("select") {
}
export abstract class AjaxSelect extends AutoCompleteSelectBase {
protected filter?: (items: TomOption[]) => TomOption[] = null;
protected filter?: (items: TomOption[]) => TomOption[];
protected minCharNumberForSearch = 2;
/**
* A cache of researches that have been made using this input.
@@ -1,11 +1,12 @@
// @ts-expect-error TS2882
import "tom-select/dist/css/tom-select.default.css";
import type { TomOption } from "tom-select/dist/types/types";
import type { escape_html } from "tom-select/dist/types/utils";
import type { TomOption } from "tom-select/src/types";
import type { escape_html } from "tom-select/src/utils";
import {
AjaxSelect,
AutoCompleteSelectBase,
} from "#core:core/components/ajax-select-base.ts";
import { registerComponent } from "#core:utils/web-components.ts";
} from "#core:core/components/ajax-select-base";
import { registerComponent } from "#core:utils/web-components";
import {
type GroupSchema,
groupSearchGroup,
@@ -1,11 +1,13 @@
// @ts-expect-error 2307
// biome-ignore lint/correctness/noUndeclaredDependencies: shipped by easymde
import "codemirror/lib/codemirror.css";
// @ts-expect-error 2307
import "easymde/src/css/easymde.css";
// biome-ignore lint/correctness/noUndeclaredDependencies: Imported by EasyMDE
import type CodeMirror from "codemirror";
// biome-ignore lint/style/useNamingConvention: This is how they called their namespace
import EasyMDE from "easymde";
import { inheritHtmlElement, registerComponent } from "#core:utils/web-components.ts";
import { inheritHtmlElement, registerComponent } from "#core:utils/web-components";
import {
markdownRenderMarkdown,
type UploadUploadImageErrors,
@@ -25,11 +27,11 @@ const loadEasyMde = (textarea: HTMLTextAreaElement) => {
file: file,
},
});
if (!response.response.ok) {
if (response.response.status === 422) {
if (response.response !== undefined && !response.response.ok) {
if (response?.response.status === 422) {
onError(
(response.error as UploadUploadImageErrors[422]).detail
.map((err: Record<"ctx", Record<"error", string>>) => err.ctx.error)
.map((err) => err.ctx.error)
.join(" ; "),
);
} else if (response.response.status === 403) {
@@ -39,6 +41,10 @@ const loadEasyMde = (textarea: HTMLTextAreaElement) => {
}
return;
}
if (response.data === undefined) {
// this can't happen, it's just for the type checker to know
return;
}
onSuccess(response.data.href);
// Workaround function to add an image name to uploaded image
// Without this, you get ![](url) instead of ![name](url)
@@ -58,21 +64,18 @@ const loadEasyMde = (textarea: HTMLTextAreaElement) => {
});
easymde.codemirror.replaceSelection("\n");
},
previewRender: (plainText: string, preview: MarkdownInput) => {
previewRender: (plainText, preview) => {
/* This is wrapped this way to allow time for Alpine to be loaded on the page */
return Alpine.debounce((plainText: string, preview: MarkdownInput) => {
const func = async (
plainText: string,
preview: MarkdownInput,
): Promise<null> => {
return Alpine.debounce(() => {
const func = async () => {
preview.innerHTML = (
await markdownRenderMarkdown({ body: { text: plainText } })
).data as string;
return null;
};
func(plainText, preview);
func().then();
return null;
}, 300)(plainText, preview);
}, 300)();
},
forceSync: true, // Avoid validation error on generic create view
imageTexts: {
@@ -222,9 +225,11 @@ const loadEasyMde = (textarea: HTMLTextAreaElement) => {
});
const submits: HTMLInputElement[] = Array.from(
textarea.closest("form").querySelectorAll('input[type="submit"]'),
(textarea.closest("form") as HTMLFormElement).querySelectorAll(
'input[type="submit"]',
),
);
const parentDiv = textarea.parentElement.parentElement;
const parentDiv = textarea.parentElement?.parentElement as HTMLElement;
function checkMarkdownInput(event: Event) {
// an attribute is null if it does not exist, else a string
@@ -249,6 +254,7 @@ const loadEasyMde = (textarea: HTMLTextAreaElement) => {
};
@registerComponent("markdown-input")
// biome-ignore lint/correctness/noUnusedVariables: it is used in jinja
class MarkdownInput extends inheritHtmlElement("textarea") {
connectedCallback() {
super.connectedCallback();
@@ -2,7 +2,7 @@ import {
type InheritedHtmlElement,
inheritHtmlElement,
registerComponent,
} from "#core:utils/web-components.ts";
} from "#core:utils/web-components";
/**
* ElementOnce web components
@@ -28,7 +28,7 @@ export function elementOnce<K extends keyof HTMLElementTagNameMap>(tagName: K) {
clearNode() {
while (this.firstChild) {
this.removeChild(this.lastChild);
this.removeChild(this.lastChild as ChildNode);
}
}
@@ -130,7 +130,7 @@ startObserver(observer);
export class LinkOnce extends elementOnce("link") {
getElementQuerySelector(): string {
// We get href from node.attributes instead of node.href to avoid getting the domain part
return `link[href='${this.node.attributes.getNamedItem("href").nodeValue}']`;
return `link[href='${this.node.attributes.getNamedItem("href")?.nodeValue}']`;
}
}
@@ -142,6 +142,6 @@ export class LinkOnce extends elementOnce("link") {
export class ScriptOnce extends inheritHtmlElement("script") {
getElementQuerySelector(): string {
// We get href from node.attributes instead of node.src to avoid getting the domain part
return `script[src='${this.node.attributes.getNamedItem("src").nodeValue}']`;
return `script[src='${this.node.attributes.getNamedItem("src")?.nodeValue}']`;
}
}
@@ -1,4 +1,4 @@
import { inheritHtmlElement, registerComponent } from "#core:utils/web-components.ts";
import { inheritHtmlElement, registerComponent } from "#core:utils/web-components";
@registerComponent("nfc-input")
export class NfcInput extends inheritHtmlElement("input") {
@@ -26,9 +26,11 @@ export class NfcInput extends inheritHtmlElement("input") {
window.alert(gettext("Unsupported NFC card"));
});
ndef.addEventListener("reading", (event: NDEFReadingEvent) => {
ndef.addEventListener("reading", (event) => {
this.removeAttribute("scan");
this.node.value = event.serialNumber.replace(/:/g, "").toUpperCase();
this.node.value = (event as NDEFReadingEvent).serialNumber
.replace(/:/g, "")
.toUpperCase();
/* Auto submit form, we need another button to not trigger our previously defined click event */
const submit = document.createElement("button");
this.node.appendChild(submit);
@@ -1,6 +1,6 @@
import { html, render } from "lit-html";
import { unsafeHTML } from "lit-html/directives/unsafe-html.js";
import { registerComponent } from "#core:utils/web-components.ts";
import { registerComponent } from "#core:utils/web-components";
@registerComponent("ui-tab")
export class Tab extends HTMLElement {
@@ -19,7 +19,7 @@ export class Tab extends HTMLElement {
}
if (name === "title") {
this.description = newValue;
this.description = newValue ?? "";
}
this.dispatchEvent(new CustomEvent("ui-tab-updated", { bubbles: true }));
}
@@ -79,15 +79,15 @@ export class Tab extends HTMLElement {
@registerComponent("ui-tab-group")
export class TabGroup extends HTMLElement {
private node: HTMLDivElement;
private node!: HTMLDivElement;
connectedCallback() {
this.node = document.createElement("div");
this.node.classList.add("tabs", "shadow");
this.appendChild(this.node);
this.addEventListener("ui-tab-activated", (event: CustomEvent) => {
const target = event.detail as Tab;
this.addEventListener("ui-tab-activated", (event) => {
const target = (event as CustomEvent).detail as Tab;
for (const tab of this.getElementsByTagName("ui-tab") as HTMLCollectionOf<Tab>) {
if (tab !== target) {
tab.setActive(false);
@@ -26,19 +26,23 @@ document.addEventListener("alpine:init", () => {
* `counter/templates/counter/product_form.jinja`
*/
Alpine.data("dynamicFormSet", (config?: Config) => ({
formContainer: undefined as unknown as HTMLElement,
nbForms: 0,
template: undefined as unknown as HTMLTemplateElement,
init() {
this.formContainer = this.$refs.formContainer as HTMLElement;
this.nbForms = this.formContainer.children.length as number;
this.template = this.$refs.formTemplate as HTMLTemplateElement;
const prefix = config?.prefix ?? "form";
this.$root
.querySelector(`#id_${prefix}-TOTAL_FORMS`)
.setAttribute(":value", "nbForms");
(
this.$root.querySelector(`#id_${prefix}-TOTAL_FORMS`) as HTMLFormElement
).setAttribute(":value", "nbForms");
},
addForm() {
this.formContainer.appendChild(document.importNode(this.template.content, true));
const newForm = this.formContainer.lastElementChild;
const newForm = this.formContainer.lastElementChild as Element;
const inputs: NodeListOf<HTMLFormInputElement> = newForm.querySelectorAll(
"input, select, textarea",
);
@@ -59,7 +63,7 @@ document.addEventListener("alpine:init", () => {
this.nbForms -= 1;
// adjust the id of remaining forms
for (let i = 0; i < this.nbForms; i++) {
const form: HTMLDivElement = this.formContainer.children[i];
const form = this.formContainer.children[i];
const inputs: NodeListOf<HTMLFormInputElement> = form.querySelectorAll(
"input, select, textarea",
);
+6 -3
View File
@@ -1,5 +1,5 @@
function showMenu() {
const navbar = document.getElementById("navbar-content");
const navbar = document.getElementById("navbar-content") as HTMLElement;
const current = navbar.getAttribute("mobile-display");
navbar.setAttribute("mobile-display", current === "hidden" ? "revealed" : "hidden");
}
@@ -20,9 +20,12 @@ function navbarInit() {
item.removeAttribute("open");
}
});
item.addEventListener("click", (event: MouseEvent) => {
item.addEventListener("click", (event) => {
// Don't close when clicking on desktop mode
if ((event.target as HTMLElement).nodeName !== "SUMMARY" || event.detail === 0) {
if (
(event.target as HTMLElement).nodeName !== "SUMMARY" ||
(event as MouseEvent).detail === 0
) {
return;
}
@@ -1,3 +1,4 @@
// @ts-expect-error 2307 this dependency does exist, but it's a little bit wacky
import clip from "@arendjr/text-clipper";
/*
+8 -7
View File
@@ -70,15 +70,16 @@ function createTooltip(element: HTMLElement) {
function updateTooltip(element: HTMLElement, tooltip: HTMLElement, status: Status) {
// Update tooltip status and set it's attributes and content
tooltip.setAttribute("tooltip-status", status);
tooltip.innerText = element.getAttribute("tooltip");
tooltip.innerText = element.getAttribute("tooltip") as string;
for (const attributes of [
{ src: "tooltip-class", dst: "class", default: ["tooltip"] },
{ src: "tooltip-id", dst: "id", default: [] },
]) {
const populated = attributes.default;
if (element.hasAttribute(attributes.src)) {
populated.push(...element.getAttribute(attributes.src).split(" "));
const attr = element.getAttribute(attributes.src);
if (attr !== null) {
populated.push(...attr.split(" "));
}
tooltip.setAttribute(attributes.dst, populated.join(" "));
}
@@ -93,7 +94,7 @@ function getTooltip(element: HTMLElement) {
return tooltip;
}
function tooltipMouseover(event: MouseEvent) {
function tooltipMouseover(event: Event) {
// We get the closest tooltip to have a consistent behavior
// when hovering over a child element of a tooltip marked element
const target = (event.target as HTMLElement).closest("[tooltip]") as HTMLElement;
@@ -111,7 +112,7 @@ function tooltipMouseover(event: MouseEvent) {
});
}
function tooltipMouseout(event: MouseEvent) {
function tooltipMouseout(event: Event) {
// We get the closest tooltip to have a consistent behavior
// when hovering over a child element of a tooltip marked element
const target = (event.target as HTMLElement).closest("[tooltip]") as HTMLElement;
@@ -141,7 +142,7 @@ new MutationObserver((mutations: MutationRecord[]) => {
}
} else if (tooltips.has(target)) {
// Remove corresponding tooltip
tooltips.get(target).remove();
tooltips.get(target)?.remove();
tooltips.delete(target);
}
}
@@ -163,7 +164,7 @@ new MutationObserver((mutations: MutationRecord[]) => {
continue;
}
if (tooltips.has(target)) {
tooltips.get(target).remove();
tooltips.get(target)?.remove();
tooltips.delete(target);
}
}
+18 -23
View File
@@ -1,20 +1,13 @@
import cytoscape, {
type ElementDefinition,
type NodeSingular,
type Singular,
} from "cytoscape";
import cytoscape, { type ElementDefinition, type Singular } from "cytoscape";
import cxtmenu from "cytoscape-cxtmenu";
import klay, { type KlayLayoutOptions } from "cytoscape-klay";
import { History, initialUrlParams, updateQueryString } from "#core:utils/history.ts";
import { History, initialUrlParams, updateQueryString } from "#core:utils/history";
import { familyGetFamilyGraph, type UserProfileSchema } from "#openapi";
cytoscape.use(klay);
cytoscape.use(cxtmenu);
type GraphData = (
| { data: UserProfileSchema }
| { data: { source: number; target: number } }
)[];
type GraphData = { data: UserProfileSchema | { source: number; target: number } }[];
function isMobile() {
return window.innerWidth < 500;
@@ -27,10 +20,8 @@ async function getGraphData(
): Promise<GraphData> {
const data = (
await familyGetFamilyGraph({
path: {
// biome-ignore lint/style/useNamingConvention: api is snake_case
user_id: userId,
},
// biome-ignore lint/style/useNamingConvention: api is snake_case
path: { user_id: userId },
query: {
// biome-ignore lint/style/useNamingConvention: api is snake_case
godfathers_depth: godfathersDepth,
@@ -39,6 +30,10 @@ async function getGraphData(
},
})
).data;
if (data === undefined) {
console.error("Family graph request failed");
return [];
}
return [
...data.users.map((user) => {
return { data: user };
@@ -155,7 +150,7 @@ function createGraph(container: HTMLDivElement, data: GraphData, activeUserId: n
{
content: '<i class="fa fa-external-link fa-2x"></i>',
select: (el) => {
window.open(el.data().profile_url, "_blank").focus();
window.open(el.data().profile_url, "_blank")?.focus();
},
},
@@ -195,12 +190,12 @@ document.addEventListener("alpine:init", () => {
godfathersDepth: 0,
godchildrenDepth: 0,
reverse: initialUrlParams.get("reverse")?.toLowerCase?.() === "true",
graph: undefined as cytoscape.Core,
graphData: {},
graph: undefined as unknown as cytoscape.Core,
graphData: {} as GraphData,
isZoomEnabled: !isMobile(),
getInitialDepth(prop: string) {
const value = Number.parseInt(initialUrlParams.get(prop), 10);
const value = Number.parseInt(initialUrlParams.get(prop) as string, 10);
if (Number.isNaN(value) || value < config.depthMin || value > config.depthMax) {
return defaultDepth;
}
@@ -223,8 +218,8 @@ document.addEventListener("alpine:init", () => {
await delayedFetch();
});
}
this.$watch("reverse", async (value: number) => {
updateQueryString("reverse", value.toString(), History.Replace);
this.$watch("reverse", async (newValue, _oldValue) => {
updateQueryString("reverse", newValue.toString(), History.Replace);
await this.reverseGraph();
});
this.$watch("graphData", async () => {
@@ -259,9 +254,9 @@ document.addEventListener("alpine:init", () => {
},
async reverseGraph() {
this.graph.elements((el: NodeSingular) => {
el.position({ x: -el.position().x, y: -el.position().y });
});
this.graph
.elements()
.positions((el, _) => ({ x: -el.position().x, y: -el.position().y }));
this.graph.center(this.graph.elements());
},
+2 -2
View File
@@ -5,9 +5,9 @@ interface AlertParams {
export class AlertMessage {
public open: boolean;
public success: boolean;
public success!: boolean;
public content: string;
private timeoutId?: number;
private timeoutId: number | null;
private readonly defaultDuration: number;
constructor(params?: { defaultDuration: number }) {
+8 -5
View File
@@ -37,6 +37,10 @@ export const paginated = async <T>(
queryParams.query.page = 1;
const firstPage = (await endpoint(queryParams)).data;
if (firstPage === undefined) {
console.error(`Request to "${options?.url}" failed`);
return [];
}
const results = firstPage.results;
const nbElements = firstPage.count;
@@ -45,9 +49,9 @@ export const paginated = async <T>(
if (nbPages > 1) {
const promises: Promise<T[]>[] = [];
for (let i = 2; i <= nbPages; i++) {
const nextPage = structuredClone(queryParams);
const nextPage = structuredClone(queryParams) as Required<PaginatedRequest>;
nextPage.query.page = i;
promises.push(endpoint(nextPage).then((res) => res.data.results));
promises.push(endpoint(nextPage).then((res) => res.data?.results ?? []));
}
results.push(...(await Promise.all(promises)).flat());
}
@@ -61,8 +65,7 @@ interface Request extends TDataShape {
interface InterceptorOptions {
url: string;
}
type GenericEndpoint = <ThrowOnError extends boolean = false>(
export type GenericEndpoint = <ThrowOnError extends boolean = false>(
options?: Options<Request, ThrowOnError>,
) => RequestResult<unknown, unknown, ThrowOnError>;
@@ -71,7 +74,7 @@ type GenericEndpoint = <ThrowOnError extends boolean = false>(
**/
export const makeUrl = async (endpoint: GenericEndpoint) => {
let url = "";
const interceptor = (_request: undefined, options: InterceptorOptions) => {
const interceptor = (_request: Request, options: InterceptorOptions) => {
url = options.url;
throw new Error("We don't want to send the request");
};
+12 -9
View File
@@ -7,14 +7,14 @@ interface StringifyOptions<T extends object> {
titleRow?: readonly string[];
}
function getNested<T extends object>(obj: T, key: NestedKeyOf<T>) {
const path: (keyof object)[] = key.split(".") as (keyof unknown)[];
let res = obj[path.shift() as keyof T];
function getNested<T extends { [key: string]: unknown }>(obj: T, key: NestedKeyOf<T>) {
const path = key.split(".");
let res = obj[path.shift() as string] as { [key: string]: unknown } | undefined;
for (const node of path) {
if (res === null) {
if (res === undefined) {
break;
}
res = res[node];
res = res[node] as { [key: string]: unknown } | undefined;
}
return res;
}
@@ -29,18 +29,21 @@ function sanitizeCell(content: string): string {
}
export const csv = {
stringify: <T extends object>(objs: T[], options?: StringifyOptions<T>) => {
const columns = options.columns;
stringify: <T extends { [key: string]: unknown }>(
objs: T[],
options?: StringifyOptions<T>,
) => {
const columns = options?.columns;
const content = objs
.map((obj) => {
return columns
return (columns ?? [])
.map((col) => {
return sanitizeCell((getNested(obj, col) ?? "").toString());
})
.join(",");
})
.join("\n");
if (!options.titleRow) {
if (!options?.titleRow) {
return content;
}
const firstRow = options.titleRow.map(sanitizeCell).join(",");
+3 -2
View File
@@ -29,6 +29,7 @@ export function registerComponent(name: string, options?: ElementDefinitionOptio
export interface InheritedHtmlElement<K extends keyof HTMLElementTagNameMap>
extends HTMLElement {
readonly inheritedTagName: K;
// readonly initializedAttribute: "component-initialized";
node: HTMLElementTagNameMap[K];
}
@@ -47,8 +48,8 @@ export function inheritHtmlElement<K extends keyof HTMLElementTagNameMap>(tagNam
implements InheritedHtmlElement<K>
{
readonly inheritedTagName = tagName;
private readonly initializedAttribute = "component-initialized";
node: HTMLElementTagNameMap[K];
readonly initializedAttribute = "component-initialized";
node!: HTMLElementTagNameMap[K];
connectedCallback(autoAddNode?: boolean) {
// When nesting inherited elements, we might trigger the wrapping twice