You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
99 lines
2.3 KiB
TypeScript
99 lines
2.3 KiB
TypeScript
import Big from "big.js";
|
|
import { fromUnixTime, intlFormat } from "date-fns";
|
|
import { JSX } from "solid-js";
|
|
|
|
export const sleep = (timeout: number) =>
|
|
new Promise((res) => setTimeout(res, timeout));
|
|
|
|
// Source: https://stackoverflow.com/a/34591063
|
|
export const roundToStep = (value: number, step = 1.0) => {
|
|
const inv = new Big(1.0).div(step);
|
|
return inv.mul(value).round().div(inv).toNumber();
|
|
};
|
|
|
|
export const getDisplayDate = function (date: Date) {
|
|
return intlFormat(
|
|
date,
|
|
{
|
|
day: "2-digit",
|
|
month: "2-digit",
|
|
year: "numeric",
|
|
},
|
|
{
|
|
locale: "de-CH",
|
|
}
|
|
);
|
|
};
|
|
|
|
export const getDisplayDateFromUnix = function (unix: number) {
|
|
return getDisplayDate(fromUnixTime(unix));
|
|
};
|
|
|
|
export const resetInput =
|
|
(defaultValue: any, eventName = "input") =>
|
|
(evt: FocusEvent) => {
|
|
const el = evt.target as HTMLInputElement | null;
|
|
if (!el) {
|
|
return;
|
|
}
|
|
|
|
if (el.value !== "") {
|
|
return;
|
|
}
|
|
|
|
el.value = defaultValue;
|
|
const event = new Event(eventName, { bubbles: true });
|
|
el.dispatchEvent(event);
|
|
};
|
|
|
|
// https://dev.to/codebubb/how-to-shuffle-an-array-in-javascript-2ikj
|
|
export const shuffle = (list: any[]) => {
|
|
for (let i = list.length - 1; i > 0; i--) {
|
|
const j = Math.floor(Math.random() * (i + 1));
|
|
const temp = list[i];
|
|
list[i] = list[j];
|
|
list[j] = temp;
|
|
}
|
|
|
|
return list;
|
|
};
|
|
|
|
export const getDomain = () =>
|
|
import.meta.env.SSR ? process.env.DOMAIN || "localhost" : location.hostname;
|
|
|
|
export const getHost = () => `https://${getDomain()}`;
|
|
|
|
export const onClickFocus: JSX.EventHandlerUnion<
|
|
HTMLAnchorElement,
|
|
MouseEvent
|
|
> = (evt) => {
|
|
const el = evt.currentTarget!;
|
|
const id = el.getAttribute("href");
|
|
if (id == null) {
|
|
return;
|
|
}
|
|
const targetEl = document.querySelector<HTMLElement>(id);
|
|
if (targetEl == null) {
|
|
return;
|
|
}
|
|
|
|
targetEl.focus();
|
|
};
|
|
|
|
export const externalLink = { target: "_blank", rel: "noopener" };
|
|
|
|
export const createOptionalNumberInputHandler = (
|
|
onInput: (v: number | undefined) => void
|
|
) => {
|
|
return (e: InputEvent & { currentTarget: HTMLInputElement }) => {
|
|
if (e.currentTarget.validity.badInput) {
|
|
return;
|
|
}
|
|
|
|
const value =
|
|
e.currentTarget.value == "" ? undefined : e.currentTarget.valueAsNumber;
|
|
|
|
onInput(value);
|
|
};
|
|
};
|