mirror of
https://github.com/shlinkio/shlink-web-client.git
synced 2026-07-18 01:31:50 +00:00
Do not inject components into other components
This commit is contained in:
@@ -4,33 +4,22 @@ import type { FC } from 'react';
|
||||
import { useEffect } from 'react';
|
||||
import { Route, Routes, useLocation } from 'react-router';
|
||||
import { AppUpdateBanner } from '../common/AppUpdateBanner';
|
||||
import { Home } from '../common/Home';
|
||||
import { MainHeader } from '../common/MainHeader';
|
||||
import { NotFound } from '../common/NotFound';
|
||||
import { ShlinkVersionsContainer } from '../common/ShlinkVersionsContainer';
|
||||
import type { FCWithDeps } from '../container/utils';
|
||||
import { componentFactory, useDependencies } from '../container/utils';
|
||||
import { ShlinkWebComponentContainer } from '../common/ShlinkWebComponentContainer';
|
||||
import { CreateServer } from '../servers/CreateServer';
|
||||
import { EditServer } from '../servers/EditServer';
|
||||
import { ManageServers } from '../servers/ManageServers';
|
||||
import { useLoadRemoteServers } from '../servers/reducers/remoteServers';
|
||||
import { useSettings } from '../settings/reducers/settings';
|
||||
import { Settings } from '../settings/Settings';
|
||||
import { forceUpdate } from '../utils/helpers/sw';
|
||||
import { useAppUpdated } from './reducers/appUpdates';
|
||||
|
||||
type AppDeps = {
|
||||
Home: FC;
|
||||
ShlinkWebComponentContainer: FC;
|
||||
CreateServer: FC;
|
||||
ManageServers: FC;
|
||||
};
|
||||
|
||||
const App: FCWithDeps<any, AppDeps> = () => {
|
||||
export const App: FC = () => {
|
||||
const { appUpdated, resetAppUpdate } = useAppUpdated();
|
||||
const {
|
||||
Home,
|
||||
ShlinkWebComponentContainer,
|
||||
CreateServer,
|
||||
ManageServers,
|
||||
} = useDependencies(App);
|
||||
|
||||
useLoadRemoteServers();
|
||||
|
||||
@@ -80,10 +69,3 @@ const App: FCWithDeps<any, AppDeps> = () => {
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const AppFactory = componentFactory(App, [
|
||||
'Home',
|
||||
'ShlinkWebComponentContainer',
|
||||
'CreateServer',
|
||||
'ManageServers',
|
||||
]);
|
||||
|
||||
@@ -6,11 +6,12 @@ import type { FC } from 'react';
|
||||
import { useEffect } from 'react';
|
||||
import { ExternalLink } from 'react-external-link';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { withoutSelectedServer } from '../servers/helpers/withoutSelectedServer';
|
||||
import { useServers } from '../servers/reducers/servers';
|
||||
import { ServersListGroup } from '../servers/ServersListGroup';
|
||||
import { ShlinkLogo } from './img/ShlinkLogo';
|
||||
|
||||
export const Home: FC = () => {
|
||||
export const Home: FC = withoutSelectedServer(() => {
|
||||
const navigate = useNavigate();
|
||||
const { servers } = useServers();
|
||||
const serversList = Object.values(servers);
|
||||
@@ -66,4 +67,4 @@ export const Home: FC = () => {
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
});
|
||||
|
||||
@@ -4,10 +4,10 @@ import {
|
||||
ShlinkSidebarVisibilityProvider,
|
||||
ShlinkWebComponent,
|
||||
} from '@shlinkio/shlink-web-component';
|
||||
import type { FC } from 'react';
|
||||
import { memo } from 'react';
|
||||
import type { ShlinkApiClientBuilder } from '../api/services/ShlinkApiClientBuilder';
|
||||
import type { FCWithDeps } from '../container/utils';
|
||||
import { componentFactory, useDependencies } from '../container/utils';
|
||||
import { withDependencies } from '../container/context';
|
||||
import { isReachableServer } from '../servers/data';
|
||||
import { ServerError } from '../servers/helpers/ServerError';
|
||||
import { withSelectedServer } from '../servers/helpers/withSelectedServer';
|
||||
@@ -15,23 +15,21 @@ import { useSelectedServer } from '../servers/reducers/selectedServer';
|
||||
import { useSettings } from '../settings/reducers/settings';
|
||||
import { NotFound } from './NotFound';
|
||||
|
||||
type ShlinkWebComponentContainerDeps = {
|
||||
export type ShlinkWebComponentContainerProps = {
|
||||
TagColorsStorage: TagColorsStorage;
|
||||
buildShlinkApiClient: ShlinkApiClientBuilder;
|
||||
};
|
||||
|
||||
const ShlinkWebComponentContainer: FCWithDeps<
|
||||
any,
|
||||
ShlinkWebComponentContainerDeps
|
||||
const ShlinkWebComponentContainerBase: FC<
|
||||
ShlinkWebComponentContainerProps
|
||||
// FIXME Using `memo` here to solve a flickering effect in charts.
|
||||
// memo is probably not the right solution. The root cause is the withSelectedServer HOC, but I couldn't fix the
|
||||
// extra rendering there.
|
||||
// This should be revisited at some point.
|
||||
> = withSelectedServer(memo(() => {
|
||||
const {
|
||||
buildShlinkApiClient,
|
||||
TagColorsStorage: tagColorsStorage,
|
||||
} = useDependencies(ShlinkWebComponentContainer);
|
||||
> = withSelectedServer(memo(({
|
||||
buildShlinkApiClient,
|
||||
TagColorsStorage: tagColorsStorage,
|
||||
}) => {
|
||||
const { selectedServer } = useSelectedServer();
|
||||
const { settings } = useSettings();
|
||||
|
||||
@@ -58,7 +56,7 @@ const ShlinkWebComponentContainer: FCWithDeps<
|
||||
);
|
||||
}));
|
||||
|
||||
export const ShlinkWebComponentContainerFactory = componentFactory(ShlinkWebComponentContainer, [
|
||||
export const ShlinkWebComponentContainer = withDependencies(ShlinkWebComponentContainerBase, [
|
||||
'buildShlinkApiClient',
|
||||
'TagColorsStorage',
|
||||
]);
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
import type { IContainer } from 'bottlejs';
|
||||
import { createContext, useContext } from 'react';
|
||||
|
||||
const ContainerContext = createContext<IContainer | null>(null);
|
||||
|
||||
export const ContainerProvider = ContainerContext.Provider;
|
||||
|
||||
export const useDependencies = <T extends unknown[]>(...names: string[]): T => {
|
||||
const container = useContext(ContainerContext);
|
||||
if (!container) {
|
||||
throw new Error('You cannot use "useDependencies" outside of a ContainerProvider');
|
||||
}
|
||||
|
||||
return names.map((name) => {
|
||||
const dependency = container[name];
|
||||
if (!dependency) {
|
||||
throw new Error(`Dependency with name "${name}" not found in container`);
|
||||
}
|
||||
|
||||
return dependency;
|
||||
}) as T;
|
||||
};
|
||||
|
||||
// TODO Create Higher Order Component that can pull dependencies from the container
|
||||
60
src/container/context.tsx
Normal file
60
src/container/context.tsx
Normal file
@@ -0,0 +1,60 @@
|
||||
import type { IContainer } from 'bottlejs';
|
||||
import { type ComponentType, createContext, useContext } from 'react';
|
||||
|
||||
const ContainerContext = createContext<IContainer | null>(null);
|
||||
|
||||
export const ContainerProvider = ContainerContext.Provider;
|
||||
|
||||
const useContainer = (wrapperName: string): IContainer => {
|
||||
const container = useContext(ContainerContext);
|
||||
if (!container) {
|
||||
throw new Error(`You cannot use "${wrapperName}" outside of a ContainerProvider`);
|
||||
}
|
||||
|
||||
return container;
|
||||
};
|
||||
|
||||
/**
|
||||
* Hook used to extract dependencies from the container in other hooks.
|
||||
*/
|
||||
export const useDependencies = <T extends unknown[]>(...names: string[]): T => {
|
||||
const container = useContainer('useDependencies');
|
||||
|
||||
return names.map((name) => {
|
||||
const dependency = container[name];
|
||||
if (!dependency) {
|
||||
throw new Error(`Dependency with name "${name}" not found in container`);
|
||||
}
|
||||
|
||||
return dependency;
|
||||
}) as T;
|
||||
};
|
||||
|
||||
/**
|
||||
* Higher Order Component used to inject services into components as props.
|
||||
*/
|
||||
export function withDependencies<
|
||||
Props extends Record<string, unknown>,
|
||||
DependencyName extends string & keyof Props,
|
||||
>(
|
||||
Component: ComponentType<Props>,
|
||||
dependencyNames: DependencyName[],
|
||||
): ComponentType<Omit<Props, DependencyName>> {
|
||||
function Wrapper(props: Omit<Props, DependencyName>) {
|
||||
const container = useContainer('withDependencies');
|
||||
|
||||
// Inject services, unless they have been overridden by props passed from
|
||||
// the parent component.
|
||||
const dependencies: Partial<Record<DependencyName, unknown>> = {};
|
||||
for (const dependency of dependencyNames) {
|
||||
if (!(dependency in props)) {
|
||||
dependencies[dependency] = container[dependency];
|
||||
}
|
||||
}
|
||||
|
||||
const propsWithServices = { ...dependencies, ...props } as Props;
|
||||
return <Component {...propsWithServices} />;
|
||||
}
|
||||
|
||||
return Wrapper;
|
||||
}
|
||||
@@ -2,13 +2,6 @@ import { useTimeoutToggle } from '@shlinkio/shlink-frontend-kit';
|
||||
import { FetchHttpClient } from '@shlinkio/shlink-js-sdk/fetch';
|
||||
import Bottle from 'bottlejs';
|
||||
import { buildShlinkApiClient } from '../api/services/ShlinkApiClientBuilder';
|
||||
import { AppFactory } from '../app/App';
|
||||
import { Home } from '../common/Home';
|
||||
import { ShlinkWebComponentContainerFactory } from '../common/ShlinkWebComponentContainer';
|
||||
import { CreateServerFactory } from '../servers/CreateServer';
|
||||
import { ImportServersBtnFactory } from '../servers/helpers/ImportServersBtn';
|
||||
import { withoutSelectedServer } from '../servers/helpers/withoutSelectedServer';
|
||||
import { ManageServersFactory } from '../servers/ManageServers';
|
||||
import { ServersExporter } from '../servers/services/ServersExporter';
|
||||
import { ServersImporter } from '../servers/services/ServersImporter';
|
||||
import { csvToJson, jsonToCsv } from '../utils/helpers/csvjson';
|
||||
@@ -35,22 +28,5 @@ bottle.serviceFactory('useTimeoutToggle', () => useTimeoutToggle);
|
||||
|
||||
bottle.serviceFactory('buildShlinkApiClient', buildShlinkApiClient, 'HttpClient');
|
||||
|
||||
// Components
|
||||
bottle.factory('App', AppFactory);
|
||||
|
||||
bottle.serviceFactory('Home', () => Home);
|
||||
bottle.decorator('Home', withoutSelectedServer);
|
||||
|
||||
bottle.factory('ShlinkWebComponentContainer', ShlinkWebComponentContainerFactory);
|
||||
|
||||
bottle.factory('ManageServers', ManageServersFactory);
|
||||
bottle.decorator('ManageServers', withoutSelectedServer);
|
||||
|
||||
bottle.factory('CreateServer', CreateServerFactory);
|
||||
bottle.decorator('CreateServer', withoutSelectedServer);
|
||||
|
||||
bottle.factory('ImportServersBtn', ImportServersBtnFactory);
|
||||
|
||||
// Services
|
||||
bottle.service('ServersImporter', ServersImporter, 'csvToJson');
|
||||
bottle.service('ServersExporter', ServersExporter, 'Storage', 'window', 'jsonToCsv');
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
import type { IContainer } from 'bottlejs';
|
||||
import type { FC } from 'react';
|
||||
import { useMemo } from 'react';
|
||||
|
||||
export type FCWithDeps<Props, Deps> = FC<Props> & Partial<Deps>;
|
||||
|
||||
export function useDependencies<Deps>(obj: Deps): Omit<Required<Deps>, keyof FC> {
|
||||
return useMemo(() => obj as Omit<Required<Deps>, keyof FC>, [obj]);
|
||||
}
|
||||
|
||||
export function componentFactory<Deps, CompType = Omit<Partial<Deps>, keyof FC>>(
|
||||
Component: CompType,
|
||||
deps: ReadonlyArray<keyof CompType>,
|
||||
) {
|
||||
return (container: IContainer, console = globalThis.console) => {
|
||||
deps.forEach((dep) => {
|
||||
const resolvedDependency = container[dep as string];
|
||||
if (!resolvedDependency && process.env.NODE_ENV !== 'production') {
|
||||
console.error(`[Debug] Could not find "${dep as string}" dependency in container`);
|
||||
}
|
||||
|
||||
Component[dep] = resolvedDependency;
|
||||
});
|
||||
|
||||
return Component;
|
||||
};
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { createRoot } from 'react-dom/client';
|
||||
import { Provider } from 'react-redux';
|
||||
import { BrowserRouter } from 'react-router';
|
||||
import pack from '../package.json';
|
||||
import { App } from './app/App';
|
||||
import { appUpdateAvailable } from './app/reducers/appUpdates';
|
||||
import { ErrorHandler } from './common/ErrorHandler';
|
||||
import { ScrollToTop } from './common/ScrollToTop';
|
||||
@@ -12,7 +13,6 @@ import { setUpStore } from './store';
|
||||
import './tailwind.css';
|
||||
|
||||
const store = setUpStore();
|
||||
const { App } = container;
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<ContainerProvider value={container}>
|
||||
|
||||
@@ -1,23 +1,22 @@
|
||||
import type { ResultProps,TimeoutToggle } from '@shlinkio/shlink-frontend-kit';
|
||||
import { Button, Result,useToggle } from '@shlinkio/shlink-frontend-kit';
|
||||
import type { ResultProps, TimeoutToggle } from '@shlinkio/shlink-frontend-kit';
|
||||
import { Button, Result, useToggle } from '@shlinkio/shlink-frontend-kit';
|
||||
import type { FC } from 'react';
|
||||
import { useCallback, useState } from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { NoMenuLayout } from '../common/NoMenuLayout';
|
||||
import type { FCWithDeps } from '../container/utils';
|
||||
import { componentFactory, useDependencies } from '../container/utils';
|
||||
import { withDependencies } from '../container/context';
|
||||
import { useGoBack } from '../utils/helpers/hooks';
|
||||
import type { ServerData } from './data';
|
||||
import { ensureUniqueIds } from './helpers';
|
||||
import { DuplicatedServersModal } from './helpers/DuplicatedServersModal';
|
||||
import type { ImportServersBtnProps } from './helpers/ImportServersBtn';
|
||||
import { ImportServersBtn } from './helpers/ImportServersBtn';
|
||||
import { ServerForm } from './helpers/ServerForm';
|
||||
import { withoutSelectedServer } from './helpers/withoutSelectedServer';
|
||||
import { useServers } from './reducers/servers';
|
||||
|
||||
const SHOW_IMPORT_MSG_TIME = 4000;
|
||||
|
||||
type CreateServerDeps = {
|
||||
ImportServersBtn: FC<ImportServersBtnProps>;
|
||||
export type CreateServerProps = {
|
||||
useTimeoutToggle: TimeoutToggle;
|
||||
};
|
||||
|
||||
@@ -30,15 +29,12 @@ const ImportResult = ({ variant }: Pick<ResultProps, 'variant'>) => (
|
||||
</div>
|
||||
);
|
||||
|
||||
const CreateServer: FCWithDeps<any, CreateServerDeps> = () => {
|
||||
const CreateServerBase: FC<CreateServerProps> = withoutSelectedServer(({ useTimeoutToggle }) => {
|
||||
const { servers, createServers } = useServers();
|
||||
const { ImportServersBtn, useTimeoutToggle } = useDependencies(CreateServer);
|
||||
const navigate = useNavigate();
|
||||
const goBack = useGoBack();
|
||||
const hasServers = !!Object.keys(servers).length;
|
||||
// eslint-disable-next-line react-compiler/react-compiler
|
||||
const [serversImported, setServersImported] = useTimeoutToggle({ delay: SHOW_IMPORT_MSG_TIME });
|
||||
// eslint-disable-next-line react-compiler/react-compiler
|
||||
const [errorImporting, setErrorImporting] = useTimeoutToggle({ delay: SHOW_IMPORT_MSG_TIME });
|
||||
const { flag: isConfirmModalOpen, toggle: toggleConfirmModal } = useToggle();
|
||||
const [serverData, setServerData] = useState<ServerData>();
|
||||
@@ -83,6 +79,6 @@ const CreateServer: FCWithDeps<any, CreateServerDeps> = () => {
|
||||
/>
|
||||
</NoMenuLayout>
|
||||
);
|
||||
};
|
||||
});
|
||||
|
||||
export const CreateServerFactory = componentFactory(CreateServer, ['ImportServersBtn', 'useTimeoutToggle']);
|
||||
export const CreateServer = withDependencies(CreateServerBase, ['useTimeoutToggle']);
|
||||
|
||||
@@ -5,27 +5,24 @@ import { Button, Result, SearchInput, SimpleCard, Table } from '@shlinkio/shlink
|
||||
import type { FC } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { NoMenuLayout } from '../common/NoMenuLayout';
|
||||
import type { FCWithDeps } from '../container/utils';
|
||||
import { componentFactory, useDependencies } from '../container/utils';
|
||||
import type { ImportServersBtnProps } from './helpers/ImportServersBtn';
|
||||
import { withDependencies } from '../container/context';
|
||||
import { ImportServersBtn } from './helpers/ImportServersBtn';
|
||||
import { withoutSelectedServer } from './helpers/withoutSelectedServer';
|
||||
import { ManageServersRow } from './ManageServersRow';
|
||||
import { useServers } from './reducers/servers';
|
||||
import type { ServersExporter } from './services/ServersExporter';
|
||||
|
||||
type ManageServersDeps = {
|
||||
export type ManageServersProps = {
|
||||
ServersExporter: ServersExporter;
|
||||
ImportServersBtn: FC<ImportServersBtnProps>;
|
||||
useTimeoutToggle: TimeoutToggle;
|
||||
};
|
||||
|
||||
const SHOW_IMPORT_MSG_TIME = 4000;
|
||||
|
||||
const ManageServers: FCWithDeps<unknown, ManageServersDeps> = () => {
|
||||
const {
|
||||
ServersExporter: serversExporter,
|
||||
ImportServersBtn,
|
||||
useTimeoutToggle,
|
||||
} = useDependencies(ManageServers);
|
||||
const ManageServersBase: FC<ManageServersProps> = withoutSelectedServer(({
|
||||
ServersExporter: serversExporter,
|
||||
useTimeoutToggle,
|
||||
}) => {
|
||||
const { servers } = useServers();
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const allServers = useMemo(() => Object.values(servers), [servers]);
|
||||
@@ -34,7 +31,7 @@ const ManageServers: FCWithDeps<unknown, ManageServersDeps> = () => {
|
||||
[allServers, searchTerm],
|
||||
);
|
||||
const hasAutoConnect = allServers.some(({ autoConnect }) => !!autoConnect);
|
||||
// eslint-disable-next-line react-compiler/react-compiler
|
||||
|
||||
const [errorImporting, setErrorImporting] = useTimeoutToggle({ delay: SHOW_IMPORT_MSG_TIME });
|
||||
|
||||
return (
|
||||
@@ -82,10 +79,6 @@ const ManageServers: FCWithDeps<unknown, ManageServersDeps> = () => {
|
||||
)}
|
||||
</NoMenuLayout>
|
||||
);
|
||||
};
|
||||
});
|
||||
|
||||
export const ManageServersFactory = componentFactory(ManageServers, [
|
||||
'ServersExporter',
|
||||
'ImportServersBtn',
|
||||
'useTimeoutToggle',
|
||||
]);
|
||||
export const ManageServers = withDependencies(ManageServersBase, ['ServersExporter', 'useTimeoutToggle']);
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { faFileUpload as importIcon } from '@fortawesome/free-solid-svg-icons';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { Button, Tooltip, useToggle , useTooltip } from '@shlinkio/shlink-frontend-kit';
|
||||
import type { ChangeEvent, PropsWithChildren } from 'react';
|
||||
import { Button, Tooltip, useToggle, useTooltip } from '@shlinkio/shlink-frontend-kit';
|
||||
import type { ChangeEvent, FC, PropsWithChildren } from 'react';
|
||||
import { useCallback, useRef, useState } from 'react';
|
||||
import type { FCWithDeps } from '../../container/utils';
|
||||
import { componentFactory, useDependencies } from '../../container/utils';
|
||||
import { withDependencies } from '../../container/context';
|
||||
import type { ServerData } from '../data';
|
||||
import { useServers } from '../reducers/servers';
|
||||
import type { ServersImporter } from '../services/ServersImporter';
|
||||
@@ -16,21 +15,20 @@ export type ImportServersBtnProps = PropsWithChildren<{
|
||||
onError?: (error: Error) => void;
|
||||
tooltipPlacement?: 'top' | 'bottom';
|
||||
className?: string;
|
||||
|
||||
// Injected
|
||||
ServersImporter: ServersImporter
|
||||
}>;
|
||||
|
||||
type ImportServersBtnDeps = {
|
||||
ServersImporter: ServersImporter
|
||||
};
|
||||
|
||||
const ImportServersBtn: FCWithDeps<ImportServersBtnProps, ImportServersBtnDeps> = ({
|
||||
const ImportServersBtnBase: FC<ImportServersBtnProps> = ({
|
||||
children,
|
||||
onImport,
|
||||
onError = () => {},
|
||||
tooltipPlacement = 'bottom',
|
||||
className = '',
|
||||
ServersImporter: serversImporter,
|
||||
}) => {
|
||||
const { createServers, servers } = useServers();
|
||||
const { ServersImporter: serversImporter } = useDependencies(ImportServersBtn);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const { anchor, tooltip } = useTooltip({ placement: tooltipPlacement });
|
||||
const [duplicatedServers, setDuplicatedServers] = useState<ServerData[]>([]);
|
||||
@@ -106,4 +104,4 @@ const ImportServersBtn: FCWithDeps<ImportServersBtnProps, ImportServersBtnDeps>
|
||||
);
|
||||
};
|
||||
|
||||
export const ImportServersBtnFactory = componentFactory(ImportServersBtn, ['ServersImporter']);
|
||||
export const ImportServersBtn = withDependencies(ImportServersBtnBase, ['ServersImporter']);
|
||||
|
||||
Reference in New Issue
Block a user