clean up byId function

This commit is contained in:
kruschen 2024-09-03 20:37:32 +00:00
parent 6c983419e7
commit 1644b0594f
2 changed files with 4 additions and 20 deletions

View file

@ -1083,7 +1083,7 @@ function enterStandardView() {
byId("heightmap3DView").classList.remove("pressed");
byId("viewStandard").classList.add("pressed");
if (!byId("canvas3d")) return;
if (!byId("canvas3d",{throwOnNull:false})) return;
ThreeD.stop();
byId("canvas3d").remove();
if (byId("options3dUpdate").offsetParent) $("#options3d").dialog("close");

View file

@ -10,26 +10,10 @@ export type ElementMap = {
// add more types as needed
};
type ElementMapKeys = keyof ElementMap;
interface ByIdOptions {
throwOnNull?: boolean;
// add more options as needed
}
// function definition with overloads to account for different options
export function byId<K extends ElementMapKeys>(id: string, options?: ByIdOptions & {throwOnNull: true}): ElementMap[K];
export function byId<K extends ElementMapKeys>(id: string, options: ByIdOptions & {throwOnNull: boolean}): ElementMap[K]|null;
/**
* Retrieves an element from the DOM by its ID.
* @template K - The key of the element in the ElementMap.
* @param {string} id - The ID of the element to retrieve.
* @param {ByIdOptions} [options] - The options for retrieving the element.
* @param {boolean} [options.throwOnNull=true] - Whether to throw an error if the element is not found.
* @returns {ElementMap[K] | null} The retrieved element or null if not found.
* @throws {Error} If the element is not found and options.throwOnNull is true.
*/
export function byId<K extends ElementMapKeys>(id: string, options: ByIdOptions = {throwOnNull: true}) {
export function byId<K extends keyof ElementMap>(id: string): ElementMap[K];
export function byId<K extends keyof ElementMap>(id: string, options?: {throwOnNull: false}): ElementMap[K] | null;
export function byId<K extends keyof ElementMap>(id: string, options = {throwOnNull: true}) {
const element = document.getElementById(id);
if (!element && options.throwOnNull) {
throw new Error(`Element ${id} not found`);