2023-11-23 06:43:22 +01:00
|
|
|
/*
|
|
|
|
* Vencord, a Discord client mod
|
|
|
|
* Copyright (c) 2023 Vendicated and contributors
|
|
|
|
* SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
*/
|
|
|
|
|
2023-11-25 02:55:59 +01:00
|
|
|
import { ComponentType } from "react";
|
|
|
|
|
2023-11-23 06:43:22 +01:00
|
|
|
import { makeLazy } from "./lazy";
|
|
|
|
|
2024-05-02 23:18:12 -03:00
|
|
|
export const NoopComponent = () => null;
|
2023-11-23 06:43:22 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* A lazy component. The factory method is called on first render.
|
2024-05-02 23:18:12 -03:00
|
|
|
* @param factory Function returning a component
|
2023-11-23 06:43:22 +01:00
|
|
|
* @param attempts How many times to try to get the component before giving up
|
|
|
|
* @returns Result of factory function
|
|
|
|
*/
|
|
|
|
export function LazyComponent<T extends object = any>(factory: () => React.ComponentType<T>, attempts = 5) {
|
|
|
|
const get = makeLazy(factory, attempts);
|
2024-05-02 23:18:12 -03:00
|
|
|
|
2023-11-25 01:32:21 +01:00
|
|
|
const LazyComponent = (props: T) => {
|
2024-05-04 23:56:02 -03:00
|
|
|
let Component = (() => {
|
|
|
|
console.error(`LazyComponent factory failed:\n\n${factory}`);
|
2024-05-02 23:18:12 -03:00
|
|
|
|
2024-05-05 02:52:41 -03:00
|
|
|
return null;
|
|
|
|
}) as React.ComponentType<T>;
|
2024-05-04 23:56:02 -03:00
|
|
|
|
|
|
|
// @ts-ignore
|
|
|
|
if (!get.$$vencordLazyFailed()) {
|
|
|
|
const result = get();
|
2024-05-05 02:52:41 -03:00
|
|
|
if (result != null) Component = result;
|
2024-05-04 23:56:02 -03:00
|
|
|
}
|
2024-05-02 23:18:12 -03:00
|
|
|
|
2023-11-23 06:43:22 +01:00
|
|
|
return <Component {...props} />;
|
|
|
|
};
|
2023-11-25 01:32:21 +01:00
|
|
|
|
2024-05-02 23:18:12 -03:00
|
|
|
LazyComponent.$$vencordGetter = get;
|
2023-11-25 01:32:21 +01:00
|
|
|
|
2023-11-25 02:55:59 +01:00
|
|
|
return LazyComponent as ComponentType<T>;
|
2023-11-23 06:43:22 +01:00
|
|
|
}
|