refactor: layers basic typization

This commit is contained in:
Azgaar 2022-07-05 20:33:28 +03:00
parent 7c2c624417
commit 1847772d74
15 changed files with 337 additions and 194 deletions

View file

@ -1,5 +1,21 @@
import {ERROR} from "../config/logging";
interface IPromptStringOptions {
default: string;
required?: boolean;
}
interface IPromptNumberOptions {
default: number;
step?: number;
min?: number;
max?: number;
required?: boolean;
}
const isNumerical = (options: {default: number | string}): options is IPromptNumberOptions =>
typeof options.default === "number";
// prompt replacer (prompt does not work in Electron)
const $prompt: HTMLElement = document.getElementById("prompt")!;
const $form: HTMLFormElement = $prompt.querySelector("#promptForm")!;
@ -10,16 +26,23 @@ const $cancel: HTMLButtonElement = $prompt.querySelector("#promptCancel")!;
const defaultText = "Please provide an input";
const defaultOptions = {default: 1, step: 0.01, min: 0, max: 100, required: true};
export function prompt(promptText = defaultText, options = defaultOptions, callback: (value: number | string) => void) {
if (options.default === undefined)
return ERROR && console.error("Prompt: options object does not have default value defined");
export function prompt(
promptText: string = defaultText,
options: IPromptStringOptions | IPromptNumberOptions = defaultOptions,
callback?: (value: string | number) => void
): void {
const numerical = isNumerical(options);
if (numerical) {
$input.type = "number";
if (options.step !== undefined) $input.step = String(options.step);
if (options.min !== undefined) $input.min = String(options.min);
if (options.max !== undefined) $input.max = String(options.max);
if (callback) callback("rw");
} else {
$input.type = "text";
}
$text.innerHTML = promptText;
$input.type = typeof options.default === "number" ? "number" : "text";
if (options.step !== undefined) $input.step = String(options.step);
if (options.min !== undefined) $input.min = String(options.min);
if (options.max !== undefined) $input.max = String(options.max);
$input.required = options.required === false ? false : true;
$input.placeholder = "type a " + $input.type;
@ -32,8 +55,15 @@ export function prompt(promptText = defaultText, options = defaultOptions, callb
event.preventDefault();
$prompt.style.display = "none";
const value = $input.type === "number" ? Number($input.value) : $input.value;
if (callback) callback(value);
if (callback) {
if (isNumerical(options)) {
const value = Number($input.value);
callback(value);
} else {
const value = $input.value;
callback(value);
}
}
},
{once: true}
);