Vencord/src/utils/misc.tsx

211 lines
6.5 KiB
TypeScript
Raw Normal View History

2022-10-21 19:17:06 -04:00
/*
* Vencord, a modification for Discord's desktop app
* Copyright (c) 2022 Vendicated and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { Clipboard, React, Toasts, useEffect, useState } from "@webpack/common";
2022-08-30 22:07:16 -04:00
/**
* Makes a lazy function. On first call, the value is computed.
* On subsequent calls, the same computed value will be returned
* @param factory Factory function
*/
2022-10-14 15:34:35 -04:00
export function makeLazy<T>(factory: () => T): () => T {
2022-08-30 22:07:16 -04:00
let cache: T;
2022-09-30 18:42:50 -04:00
return () => cache ?? (cache = factory());
}
2022-08-30 22:07:16 -04:00
type AwaiterRes<T> = [T, any, boolean];
interface AwaiterOpts<T> {
fallbackValue: T,
deps?: unknown[],
onError?(e: any): void,
}
2022-08-30 22:07:16 -04:00
/**
* Await a promise
* @param factory Factory
* @param fallbackValue The fallback value that will be used until the promise resolved
2022-08-31 14:47:07 -04:00
* @returns [value, error, isPending]
2022-08-30 22:07:16 -04:00
*/
export function useAwaiter<T>(factory: () => Promise<T>): AwaiterRes<T | null>;
export function useAwaiter<T>(factory: () => Promise<T>, providedOpts: AwaiterOpts<T>): AwaiterRes<T>;
export function useAwaiter<T>(factory: () => Promise<T>, providedOpts?: AwaiterOpts<T | null>): AwaiterRes<T | null> {
const opts: Required<AwaiterOpts<T | null>> = Object.assign({
fallbackValue: null,
deps: [],
onError: null,
}, providedOpts);
const [state, setState] = useState({
value: opts.fallbackValue,
2022-10-17 12:05:22 -04:00
error: null,
2022-08-31 14:47:07 -04:00
pending: true
});
2022-08-30 22:07:16 -04:00
useEffect(() => {
2022-08-31 14:47:07 -04:00
let isAlive = true;
if (!state.pending) setState({ ...state, pending: true });
2022-08-31 14:47:07 -04:00
factory()
.then(value => isAlive && setState({ value, error: null, pending: false }))
.catch(error => isAlive && (setState({ value: null, error, pending: false }), opts.onError?.(error)));
2022-08-31 14:47:07 -04:00
return () => void (isAlive = false);
}, opts.deps);
2022-08-30 22:07:16 -04:00
return [state.value, state.error, state.pending];
2022-10-08 14:36:57 -04:00
}
2022-08-30 22:07:16 -04:00
2022-11-25 13:25:35 -05:00
/**
* Returns a function that can be used to force rerender react components
*/
export function useForceUpdater() {
const [, set] = useState(0);
return () => set(s => s + 1);
}
2022-08-30 22:07:16 -04:00
/**
* A lazy component. The factory method is called on first render. For example useful
* for const Component = LazyComponent(() => findByDisplayName("...").default)
* @param factory Function returning a Component
* @returns Result of factory function
*/
2022-11-07 16:28:29 -05:00
export function LazyComponent<T = any>(factory: () => React.ComponentType<T>) {
const get = makeLazy(factory);
2022-11-07 16:28:29 -05:00
return (props: T & JSX.IntrinsicAttributes) => {
const Component = get();
return <Component {...props} />;
2022-08-30 22:07:16 -04:00
};
}
/**
2022-09-16 16:59:34 -04:00
* Recursively merges defaults into an object and returns the same object
2022-08-30 22:07:16 -04:00
* @param obj Object
* @param defaults Defaults
* @returns obj
*/
export function mergeDefaults<T>(obj: T, defaults: T): T {
for (const key in defaults) {
const v = defaults[key];
if (typeof v === "object" && !Array.isArray(v)) {
obj[key] ??= {} as any;
mergeDefaults(obj[key], v);
} else {
obj[key] ??= v;
}
}
return obj;
2022-09-01 15:41:00 -04:00
}
/**
* Join an array of strings in a human readable way (1, 2 and 3)
* @param elements Elements
*/
export function humanFriendlyJoin(elements: string[]): string;
/**
* Join an array of strings in a human readable way (1, 2 and 3)
* @param elements Elements
* @param mapper Function that converts elements to a string
*/
export function humanFriendlyJoin<T>(elements: T[], mapper: (e: T) => string): string;
export function humanFriendlyJoin(elements: any[], mapper: (e: any) => string = s => s): string {
const { length } = elements;
if (length === 0) return "";
if (length === 1) return mapper(elements[0]);
let s = "";
for (let i = 0; i < length; i++) {
s += mapper(elements[i]);
if (length - i > 2) s += ", ";
else if (length - i > 1) s += " and ";
}
return s;
}
2022-09-30 18:42:50 -04:00
/**
* Calls .join(" ") on the arguments
* classes("one", "two") => "one two"
*/
export function classes(...classes: Array<string | null | undefined>) {
return classes.filter(Boolean).join(" ");
2022-09-30 18:42:50 -04:00
}
2022-10-09 13:48:42 -04:00
2022-11-25 13:25:35 -05:00
/**
* Returns a promise that resolves after the specified amount of time
*/
2022-10-09 13:48:42 -04:00
export function sleep(ms: number): Promise<void> {
return new Promise(r => setTimeout(r, ms));
}
2022-10-11 23:35:34 -04:00
2022-10-12 16:22:21 -04:00
/**
* Wrap the text in ``` with an optional language
*/
export function makeCodeblock(text: string, language?: string) {
const chars = "```";
return `${chars}${language || ""}\n${text.replaceAll("```", "\\`\\`\\`")}\n${chars}`;
}
export function copyWithToast(text: string, toastMessage = "Copied to clipboard!") {
if (Clipboard.SUPPORTS_COPY) {
Clipboard.copy(text);
} else {
toastMessage = "Your browser does not support copying to clipboard";
}
Toasts.show({
message: toastMessage,
id: Toasts.genId(),
type: Toasts.Type.SUCCESS
});
}
/**
* Check if obj is a true object: of type "object" and not null or array
*/
export function isObject(obj: unknown): obj is object {
return typeof obj === "object" && obj !== null && !Array.isArray(obj);
2022-10-12 16:22:21 -04:00
}
/**
* Returns null if value is not a URL, otherwise return URL object.
* Avoids having to wrap url checks in a try/catch
*/
export function parseUrl(urlString: string): URL | null {
try {
return new URL(urlString);
} catch {
return null;
}
}
/**
* Checks whether an element is on screen
*/
export const checkIntersecting = (el: Element) => {
const elementBox = el.getBoundingClientRect();
const documentHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
return !(elementBox.bottom < 0 || elementBox.top - documentHeight >= 0);
};
export function identity<T>(value: T): T {
return value;
}
2023-04-14 20:27:11 -04:00
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent#mobile_tablet_or_desktop
// "In summary, we recommend looking for the string Mobi anywhere in the User Agent to detect a mobile device."
export const isMobile = navigator.userAgent.includes("Mobi");