54 lines
1.9 KiB
TypeScript
54 lines
1.9 KiB
TypeScript
// This file handles the "Add an instance" dialog
|
|
|
|
export function parseHost(host: string): { host: string, secure: boolean } | null {
|
|
let parsedInstance = URL.parse(host);
|
|
parsedInstance ??= URL.parse("https://" + host);
|
|
if (!parsedInstance?.host) return null;
|
|
return {
|
|
host: parsedInstance.host,
|
|
secure: parsedInstance.protocol === "https:"
|
|
};
|
|
}
|
|
|
|
export function initializeAddInstanceDialog(dialog: HTMLDialogElement): {
|
|
showAddInstanceDialog: () => void,
|
|
hideAddInstanceDialog: () => void,
|
|
} {
|
|
const showAddInstanceDialog = () => dialog.showModal();
|
|
const hideAddInstanceDialog = () => dialog.close();
|
|
|
|
const form = dialog.querySelector(".addInstanceForm");
|
|
if (!(form instanceof HTMLFormElement))
|
|
throw new Error(".addInstanceForm isn't a form");
|
|
|
|
const instanceHost = form.querySelector("#instanceHost");
|
|
if (!(instanceHost instanceof HTMLInputElement))
|
|
throw new Error("#instanceHost isn't an input");
|
|
|
|
instanceHost.addEventListener("input", e => {
|
|
if (parseHost(instanceHost.value) === null)
|
|
instanceHost.setCustomValidity("Invalid instance hostname or URL");
|
|
else
|
|
instanceHost.setCustomValidity("");
|
|
});
|
|
|
|
form.addEventListener("submit", async e => {
|
|
// A sane browser doesn't allow for submitting the form if the above validation fails
|
|
const { host, secure } = parseHost(instanceHost.value)!;
|
|
console.log(
|
|
await fetch(`/api/instance_info/${secure}/${encodeURI(host)}`).then(r => r.json())
|
|
);
|
|
form.reset();
|
|
});
|
|
|
|
const closeButton = form.querySelector(".close");
|
|
if (!(closeButton instanceof HTMLButtonElement))
|
|
throw new Error(".close isn't a button");
|
|
|
|
closeButton.addEventListener("click", e => hideAddInstanceDialog());
|
|
|
|
return {
|
|
showAddInstanceDialog,
|
|
hideAddInstanceDialog
|
|
};
|
|
}
|