mirror of
https://github.com/shlinkio/shlink-web-client.git
synced 2025-12-23 18:50:08 +00:00
Merge pull request #1731 from acelaya-forks/redux-hooks
Set everything up to use hooks for redux actions and state
This commit is contained in:
commit
dad3990c23
@ -1,13 +1,11 @@
|
||||
import type { HttpClient } from '@shlinkio/shlink-js-sdk';
|
||||
import { ShlinkApiClient } from '@shlinkio/shlink-js-sdk';
|
||||
import type { GetState } from '../../container/types';
|
||||
import type { ServerWithId } from '../../servers/data';
|
||||
import { hasServerData } from '../../servers/data';
|
||||
import type { GetState } from '../../store';
|
||||
|
||||
const apiClients: Map<string, ShlinkApiClient> = new Map();
|
||||
|
||||
const isGetState = (getStateOrSelectedServer: GetState | ServerWithId): getStateOrSelectedServer is GetState =>
|
||||
typeof getStateOrSelectedServer === 'function';
|
||||
const getSelectedServerFromState = (getState: GetState): ServerWithId => {
|
||||
const { selectedServer } = getState();
|
||||
if (!hasServerData(selectedServer)) {
|
||||
@ -18,7 +16,7 @@ const getSelectedServerFromState = (getState: GetState): ServerWithId => {
|
||||
};
|
||||
|
||||
export const buildShlinkApiClient = (httpClient: HttpClient) => (getStateOrSelectedServer: GetState | ServerWithId) => {
|
||||
const { url: baseUrl, apiKey, forwardCredentials } = isGetState(getStateOrSelectedServer)
|
||||
const { url: baseUrl, apiKey, forwardCredentials } = typeof getStateOrSelectedServer === 'function'
|
||||
? getSelectedServerFromState(getStateOrSelectedServer)
|
||||
: getStateOrSelectedServer;
|
||||
const serverKey = `${apiKey}_${baseUrl}_${forwardCredentials ? 'forward' : 'no-forward'}`;
|
||||
@ -34,6 +32,7 @@ export const buildShlinkApiClient = (httpClient: HttpClient) => (getStateOrSelec
|
||||
{ requestCredentials: forwardCredentials ? 'include' : undefined },
|
||||
);
|
||||
apiClients.set(serverKey, apiClient);
|
||||
|
||||
return apiClient;
|
||||
};
|
||||
|
||||
|
||||
@ -1,6 +0,0 @@
|
||||
import type Bottle from 'bottlejs';
|
||||
import { buildShlinkApiClient } from './ShlinkApiClientBuilder';
|
||||
|
||||
export const provideServices = (bottle: Bottle) => {
|
||||
bottle.serviceFactory('buildShlinkApiClient', buildShlinkApiClient, 'HttpClient');
|
||||
};
|
||||
@ -1,61 +1,43 @@
|
||||
import { changeThemeInMarkup, getSystemPreferredTheme } from '@shlinkio/shlink-frontend-kit';
|
||||
import type { Settings } from '@shlinkio/shlink-web-component/settings';
|
||||
import { clsx } from 'clsx';
|
||||
import type { FC } from 'react';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useEffect } from 'react';
|
||||
import { Route, Routes, useLocation } from 'react-router';
|
||||
import { AppUpdateBanner } from '../common/AppUpdateBanner';
|
||||
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 type { ServersMap } from '../servers/data';
|
||||
import { EditServer } from '../servers/EditServer';
|
||||
import { useLoadRemoteServers } from '../servers/reducers/remoteServers';
|
||||
import { useSettings } from '../settings/reducers/settings';
|
||||
import { Settings } from '../settings/Settings';
|
||||
import { forceUpdate } from '../utils/helpers/sw';
|
||||
|
||||
type AppProps = {
|
||||
fetchServers: () => void;
|
||||
servers: ServersMap;
|
||||
settings: Settings;
|
||||
resetAppUpdate: () => void;
|
||||
appUpdated: boolean;
|
||||
};
|
||||
import { useAppUpdated } from './reducers/appUpdates';
|
||||
|
||||
type AppDeps = {
|
||||
MainHeader: FC;
|
||||
Home: FC;
|
||||
ShlinkWebComponentContainer: FC;
|
||||
CreateServer: FC;
|
||||
EditServer: FC;
|
||||
Settings: FC;
|
||||
ManageServers: FC;
|
||||
ShlinkVersionsContainer: FC;
|
||||
};
|
||||
|
||||
const App: FCWithDeps<AppProps, AppDeps> = (
|
||||
{ fetchServers, servers, settings, appUpdated, resetAppUpdate },
|
||||
) => {
|
||||
const App: FCWithDeps<any, AppDeps> = () => {
|
||||
const { appUpdated, resetAppUpdate } = useAppUpdated();
|
||||
const {
|
||||
MainHeader,
|
||||
Home,
|
||||
ShlinkWebComponentContainer,
|
||||
CreateServer,
|
||||
EditServer,
|
||||
Settings,
|
||||
ManageServers,
|
||||
ShlinkVersionsContainer,
|
||||
} = useDependencies(App);
|
||||
|
||||
useLoadRemoteServers();
|
||||
|
||||
const location = useLocation();
|
||||
const initialServers = useRef(servers);
|
||||
const isHome = location.pathname === '/';
|
||||
|
||||
useEffect(() => {
|
||||
// Try to fetch the remote servers if the list is empty during first render.
|
||||
// We use a ref because we don't care if the servers list becomes empty later.
|
||||
if (Object.keys(initialServers.current).length === 0) {
|
||||
fetchServers();
|
||||
}
|
||||
}, [fetchServers]);
|
||||
|
||||
const { settings } = useSettings();
|
||||
useEffect(() => {
|
||||
changeThemeInMarkup(settings.ui?.theme ?? getSystemPreferredTheme());
|
||||
}, [settings.ui?.theme]);
|
||||
@ -100,12 +82,8 @@ const App: FCWithDeps<AppProps, AppDeps> = (
|
||||
};
|
||||
|
||||
export const AppFactory = componentFactory(App, [
|
||||
'MainHeader',
|
||||
'Home',
|
||||
'ShlinkWebComponentContainer',
|
||||
'CreateServer',
|
||||
'EditServer',
|
||||
'Settings',
|
||||
'ManageServers',
|
||||
'ShlinkVersionsContainer',
|
||||
]);
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
import { createSlice } from '@reduxjs/toolkit';
|
||||
import { useCallback } from 'react';
|
||||
import { useAppDispatch, useAppSelector } from '../../store';
|
||||
|
||||
const { actions, reducer } = createSlice({
|
||||
name: 'shlink/appUpdates',
|
||||
@ -12,3 +14,12 @@ const { actions, reducer } = createSlice({
|
||||
export const { appUpdateAvailable, resetAppUpdate } = actions;
|
||||
|
||||
export const appUpdatesReducer = reducer;
|
||||
|
||||
export const useAppUpdated = () => {
|
||||
const dispatch = useAppDispatch();
|
||||
const appUpdateAvailable = useCallback(() => dispatch(actions.appUpdateAvailable()), [dispatch]);
|
||||
const resetAppUpdate = useCallback(() => dispatch(actions.resetAppUpdate()), [dispatch]);
|
||||
const appUpdated = useAppSelector((state) => state.appUpdated);
|
||||
|
||||
return { appUpdated, appUpdateAvailable, resetAppUpdate };
|
||||
};
|
||||
|
||||
@ -1,14 +0,0 @@
|
||||
import type Bottle from 'bottlejs';
|
||||
import type { ConnectDecorator } from '../../container/types';
|
||||
import { AppFactory } from '../App';
|
||||
import { appUpdateAvailable, resetAppUpdate } from '../reducers/appUpdates';
|
||||
|
||||
export const provideServices = (bottle: Bottle, connect: ConnectDecorator) => {
|
||||
// Components
|
||||
bottle.factory('App', AppFactory);
|
||||
bottle.decorator('App', connect(['servers', 'settings', 'appUpdated'], ['fetchServers', 'resetAppUpdate']));
|
||||
|
||||
// Actions
|
||||
bottle.serviceFactory('appUpdateAvailable', () => appUpdateAvailable);
|
||||
bottle.serviceFactory('resetAppUpdate', () => resetAppUpdate);
|
||||
};
|
||||
@ -2,19 +2,17 @@ import { faExternalLinkAlt, faPlus } from '@fortawesome/free-solid-svg-icons';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { Button, Card } from '@shlinkio/shlink-frontend-kit';
|
||||
import { clsx } from 'clsx';
|
||||
import type { FC } from 'react';
|
||||
import { useEffect } from 'react';
|
||||
import { ExternalLink } from 'react-external-link';
|
||||
import { useNavigate } from 'react-router';
|
||||
import type { ServersMap } from '../servers/data';
|
||||
import { useServers } from '../servers/reducers/servers';
|
||||
import { ServersListGroup } from '../servers/ServersListGroup';
|
||||
import { ShlinkLogo } from './img/ShlinkLogo';
|
||||
|
||||
export type HomeProps = {
|
||||
servers: ServersMap;
|
||||
};
|
||||
|
||||
export const Home = ({ servers }: HomeProps) => {
|
||||
export const Home: FC = () => {
|
||||
const navigate = useNavigate();
|
||||
const { servers } = useServers();
|
||||
const serversList = Object.values(servers);
|
||||
const hasServers = serversList.length > 0;
|
||||
|
||||
|
||||
@ -3,16 +3,10 @@ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { NavBar } from '@shlinkio/shlink-frontend-kit';
|
||||
import type { FC } from 'react';
|
||||
import { Link, useLocation } from 'react-router';
|
||||
import type { FCWithDeps } from '../container/utils';
|
||||
import { componentFactory, useDependencies } from '../container/utils';
|
||||
import { ServersDropdown } from '../servers/ServersDropdown';
|
||||
import { ShlinkLogo } from './img/ShlinkLogo';
|
||||
|
||||
type MainHeaderDeps = {
|
||||
ServersDropdown: FC;
|
||||
};
|
||||
|
||||
const MainHeader: FCWithDeps<unknown, MainHeaderDeps> = () => {
|
||||
const { ServersDropdown } = useDependencies(MainHeader);
|
||||
export const MainHeader: FC = () => {
|
||||
const { pathname } = useLocation();
|
||||
|
||||
const settingsPath = '/settings';
|
||||
@ -37,5 +31,3 @@ const MainHeader: FCWithDeps<unknown, MainHeaderDeps> = () => {
|
||||
</NavBar>
|
||||
);
|
||||
};
|
||||
|
||||
export const MainHeaderFactory = componentFactory(MainHeader, ['ServersDropdown']);
|
||||
|
||||
@ -1,16 +1,15 @@
|
||||
import { clsx } from 'clsx';
|
||||
import type { SelectedServer } from '../servers/data';
|
||||
import { isReachableServer } from '../servers/data';
|
||||
import { useSelectedServer } from '../servers/reducers/selectedServer';
|
||||
import { ShlinkVersions } from './ShlinkVersions';
|
||||
|
||||
export type ShlinkVersionsContainerProps = {
|
||||
selectedServer: SelectedServer;
|
||||
export const ShlinkVersionsContainer = () => {
|
||||
const { selectedServer } = useSelectedServer();
|
||||
return (
|
||||
<div
|
||||
className={clsx('text-center', { 'md:ml-(--aside-menu-width)': isReachableServer(selectedServer) })}
|
||||
>
|
||||
<ShlinkVersions selectedServer={selectedServer} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const ShlinkVersionsContainer = ({ selectedServer }: ShlinkVersionsContainerProps) => (
|
||||
<div
|
||||
className={clsx('text-center', { 'md:ml-(--aside-menu-width)': isReachableServer(selectedServer) })}
|
||||
>
|
||||
<ShlinkVersions selectedServer={selectedServer} />
|
||||
</div>
|
||||
);
|
||||
|
||||
@ -4,40 +4,36 @@ import {
|
||||
ShlinkSidebarVisibilityProvider,
|
||||
ShlinkWebComponent,
|
||||
} from '@shlinkio/shlink-web-component';
|
||||
import type { Settings } from '@shlinkio/shlink-web-component/settings';
|
||||
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 { isReachableServer } from '../servers/data';
|
||||
import type { WithSelectedServerProps } from '../servers/helpers/withSelectedServer';
|
||||
import { ServerError } from '../servers/helpers/ServerError';
|
||||
import { withSelectedServer } from '../servers/helpers/withSelectedServer';
|
||||
import { useSelectedServer } from '../servers/reducers/selectedServer';
|
||||
import { useSettings } from '../settings/reducers/settings';
|
||||
import { NotFound } from './NotFound';
|
||||
|
||||
type ShlinkWebComponentContainerProps = WithSelectedServerProps & {
|
||||
settings: Settings;
|
||||
};
|
||||
|
||||
type ShlinkWebComponentContainerDeps = {
|
||||
buildShlinkApiClient: ShlinkApiClientBuilder,
|
||||
TagColorsStorage: TagColorsStorage,
|
||||
ServerError: FC,
|
||||
TagColorsStorage: TagColorsStorage;
|
||||
buildShlinkApiClient: ShlinkApiClientBuilder;
|
||||
};
|
||||
|
||||
const ShlinkWebComponentContainer: FCWithDeps<
|
||||
ShlinkWebComponentContainerProps,
|
||||
any,
|
||||
ShlinkWebComponentContainerDeps
|
||||
// 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(({ selectedServer, settings }) => {
|
||||
> = withSelectedServer(memo(() => {
|
||||
const {
|
||||
buildShlinkApiClient,
|
||||
TagColorsStorage: tagColorsStorage,
|
||||
ServerError,
|
||||
} = useDependencies(ShlinkWebComponentContainer);
|
||||
const { selectedServer } = useSelectedServer();
|
||||
const { settings } = useSettings();
|
||||
|
||||
if (!isReachableServer(selectedServer)) {
|
||||
return <ServerError />;
|
||||
@ -65,5 +61,4 @@ const ShlinkWebComponentContainer: FCWithDeps<
|
||||
export const ShlinkWebComponentContainerFactory = componentFactory(ShlinkWebComponentContainer, [
|
||||
'buildShlinkApiClient',
|
||||
'TagColorsStorage',
|
||||
'ServerError',
|
||||
]);
|
||||
|
||||
@ -1,35 +0,0 @@
|
||||
import { FetchHttpClient } from '@shlinkio/shlink-js-sdk/fetch';
|
||||
import type Bottle from 'bottlejs';
|
||||
import type { ConnectDecorator } from '../../container/types';
|
||||
import { withoutSelectedServer } from '../../servers/helpers/withoutSelectedServer';
|
||||
import { ErrorHandler } from '../ErrorHandler';
|
||||
import { Home } from '../Home';
|
||||
import { MainHeaderFactory } from '../MainHeader';
|
||||
import { ScrollToTop } from '../ScrollToTop';
|
||||
import { ShlinkVersionsContainer } from '../ShlinkVersionsContainer';
|
||||
import { ShlinkWebComponentContainerFactory } from '../ShlinkWebComponentContainer';
|
||||
|
||||
export const provideServices = (bottle: Bottle, connect: ConnectDecorator) => {
|
||||
// Services
|
||||
bottle.constant('window', window);
|
||||
bottle.constant('console', console);
|
||||
bottle.constant('fetch', window.fetch.bind(window));
|
||||
bottle.service('HttpClient', FetchHttpClient, 'fetch');
|
||||
|
||||
// Components
|
||||
bottle.serviceFactory('ScrollToTop', () => ScrollToTop);
|
||||
|
||||
bottle.factory('MainHeader', MainHeaderFactory);
|
||||
|
||||
bottle.serviceFactory('Home', () => Home);
|
||||
bottle.decorator('Home', withoutSelectedServer);
|
||||
bottle.decorator('Home', connect(['servers'], ['resetSelectedServer']));
|
||||
|
||||
bottle.factory('ShlinkWebComponentContainer', ShlinkWebComponentContainerFactory);
|
||||
bottle.decorator('ShlinkWebComponentContainer', connect(['selectedServer', 'settings'], ['selectServer']));
|
||||
|
||||
bottle.serviceFactory('ShlinkVersionsContainer', () => ShlinkVersionsContainer);
|
||||
bottle.decorator('ShlinkVersionsContainer', connect(['selectedServer']));
|
||||
|
||||
bottle.serviceFactory('ErrorHandler', () => ErrorHandler);
|
||||
};
|
||||
24
src/container/context.ts
Normal file
24
src/container/context.ts
Normal file
@ -0,0 +1,24 @@
|
||||
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
|
||||
@ -1,42 +1,56 @@
|
||||
import type { IContainer } from 'bottlejs';
|
||||
import { useTimeoutToggle } from '@shlinkio/shlink-frontend-kit';
|
||||
import { FetchHttpClient } from '@shlinkio/shlink-js-sdk/fetch';
|
||||
import Bottle from 'bottlejs';
|
||||
import { connect as reduxConnect } from 'react-redux';
|
||||
import { provideServices as provideApiServices } from '../api/services/provideServices';
|
||||
import { provideServices as provideAppServices } from '../app/services/provideServices';
|
||||
import { provideServices as provideCommonServices } from '../common/services/provideServices';
|
||||
import { provideServices as provideServersServices } from '../servers/services/provideServices';
|
||||
import { provideServices as provideSettingsServices } from '../settings/services/provideServices';
|
||||
import { provideServices as provideUtilsServices } from '../utils/services/provideServices';
|
||||
import type { ConnectDecorator } from './types';
|
||||
|
||||
type LazyActionMap = Record<string, (...args: unknown[]) => unknown>;
|
||||
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';
|
||||
import { LocalStorage } from '../utils/services/LocalStorage';
|
||||
import { TagColorsStorage } from '../utils/services/TagColorsStorage';
|
||||
|
||||
const bottle = new Bottle();
|
||||
|
||||
export const { container } = bottle;
|
||||
|
||||
const lazyService = <T extends (...args: unknown[]) => unknown, K>(cont: IContainer, serviceName: string) =>
|
||||
(...args: any[]) => (cont[serviceName] as T)(...args) as K;
|
||||
bottle.constant('window', window);
|
||||
bottle.constant('console', console);
|
||||
bottle.constant('fetch', window.fetch.bind(window));
|
||||
bottle.service('HttpClient', FetchHttpClient, 'fetch');
|
||||
|
||||
const mapActionService = (map: LazyActionMap, actionName: string): LazyActionMap => ({
|
||||
...map,
|
||||
// Wrap actual action service in a function so that it is lazily created the first time it is called
|
||||
[actionName]: lazyService(container, actionName),
|
||||
});
|
||||
bottle.constant('localStorage', window.localStorage);
|
||||
bottle.service('Storage', LocalStorage, 'localStorage');
|
||||
bottle.service('TagColorsStorage', TagColorsStorage, 'Storage');
|
||||
|
||||
const pickProps = (propsToPick: string[]) => (obj: any) => Object.fromEntries(
|
||||
propsToPick.map((key) => [key, obj[key]]),
|
||||
);
|
||||
bottle.constant('csvToJson', csvToJson);
|
||||
bottle.constant('jsonToCsv', jsonToCsv);
|
||||
|
||||
const connect: ConnectDecorator = (propsFromState: string[] | null, actionServiceNames: string[] = []) =>
|
||||
reduxConnect(
|
||||
propsFromState ? pickProps(propsFromState) : null,
|
||||
actionServiceNames.reduce(mapActionService, {}),
|
||||
);
|
||||
bottle.serviceFactory('useTimeoutToggle', () => useTimeoutToggle);
|
||||
|
||||
provideAppServices(bottle, connect);
|
||||
provideCommonServices(bottle, connect);
|
||||
provideApiServices(bottle);
|
||||
provideServersServices(bottle, connect);
|
||||
provideUtilsServices(bottle);
|
||||
provideSettingsServices(bottle, connect);
|
||||
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,25 +0,0 @@
|
||||
import { configureStore } from '@reduxjs/toolkit';
|
||||
import type { IContainer } from 'bottlejs';
|
||||
import type { RLSOptions } from 'redux-localstorage-simple';
|
||||
import { load, save } from 'redux-localstorage-simple';
|
||||
import { initReducers } from '../reducers';
|
||||
import { migrateDeprecatedSettings } from '../settings/helpers';
|
||||
import type { ShlinkState } from './types';
|
||||
|
||||
const isProduction = process.env.NODE_ENV === 'production';
|
||||
const localStorageConfig: RLSOptions = {
|
||||
states: ['settings', 'servers'],
|
||||
namespace: 'shlink',
|
||||
namespaceSeparator: '.',
|
||||
debounce: 300,
|
||||
};
|
||||
const preloadedState = migrateDeprecatedSettings(load(localStorageConfig) as ShlinkState);
|
||||
|
||||
export const setUpStore = (container: IContainer) => configureStore({
|
||||
devTools: !isProduction,
|
||||
reducer: initReducers(container),
|
||||
preloadedState,
|
||||
middleware: (defaultMiddlewaresIncludingReduxThunk) =>
|
||||
defaultMiddlewaresIncludingReduxThunk({ immutableCheck: false, serializableCheck: false }) // State is too big for these
|
||||
.concat(save(localStorageConfig)),
|
||||
});
|
||||
@ -1,13 +0,0 @@
|
||||
import type { Settings } from '@shlinkio/shlink-web-component/settings';
|
||||
import type { SelectedServer, ServersMap } from '../servers/data';
|
||||
|
||||
export interface ShlinkState {
|
||||
servers: ServersMap;
|
||||
selectedServer: SelectedServer;
|
||||
settings: Settings;
|
||||
appUpdated: boolean;
|
||||
}
|
||||
|
||||
export type ConnectDecorator = (props: string[] | null, actions?: string[]) => any;
|
||||
|
||||
export type GetState = () => ShlinkState;
|
||||
@ -2,24 +2,30 @@ import { createRoot } from 'react-dom/client';
|
||||
import { Provider } from 'react-redux';
|
||||
import { BrowserRouter } from 'react-router';
|
||||
import pack from '../package.json';
|
||||
import { appUpdateAvailable } from './app/reducers/appUpdates';
|
||||
import { ErrorHandler } from './common/ErrorHandler';
|
||||
import { ScrollToTop } from './common/ScrollToTop';
|
||||
import { container } from './container';
|
||||
import { setUpStore } from './container/store';
|
||||
import { ContainerProvider } from './container/context';
|
||||
import { register as registerServiceWorker } from './serviceWorkerRegistration';
|
||||
import { setUpStore } from './store';
|
||||
import './tailwind.css';
|
||||
|
||||
const store = setUpStore(container);
|
||||
const { App, ScrollToTop, ErrorHandler, appUpdateAvailable } = container;
|
||||
const store = setUpStore();
|
||||
const { App } = container;
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<Provider store={store}>
|
||||
<BrowserRouter basename={pack.homepage}>
|
||||
<ErrorHandler>
|
||||
<ScrollToTop>
|
||||
<App />
|
||||
</ScrollToTop>
|
||||
</ErrorHandler>
|
||||
</BrowserRouter>
|
||||
</Provider>,
|
||||
<ContainerProvider value={container}>
|
||||
<Provider store={store}>
|
||||
<BrowserRouter basename={pack.homepage}>
|
||||
<ErrorHandler>
|
||||
<ScrollToTop>
|
||||
<App />
|
||||
</ScrollToTop>
|
||||
</ErrorHandler>
|
||||
</BrowserRouter>
|
||||
</Provider>
|
||||
</ContainerProvider>,
|
||||
);
|
||||
|
||||
// Learn more about service workers: https://cra.link/PWA
|
||||
|
||||
@ -7,19 +7,15 @@ import { NoMenuLayout } from '../common/NoMenuLayout';
|
||||
import type { FCWithDeps } from '../container/utils';
|
||||
import { componentFactory, useDependencies } from '../container/utils';
|
||||
import { useGoBack } from '../utils/helpers/hooks';
|
||||
import type { ServerData, ServersMap, ServerWithId } from './data';
|
||||
import type { ServerData } from './data';
|
||||
import { ensureUniqueIds } from './helpers';
|
||||
import { DuplicatedServersModal } from './helpers/DuplicatedServersModal';
|
||||
import type { ImportServersBtnProps } from './helpers/ImportServersBtn';
|
||||
import { ServerForm } from './helpers/ServerForm';
|
||||
import { useServers } from './reducers/servers';
|
||||
|
||||
const SHOW_IMPORT_MSG_TIME = 4000;
|
||||
|
||||
type CreateServerProps = {
|
||||
createServers: (servers: ServerWithId[]) => void;
|
||||
servers: ServersMap;
|
||||
};
|
||||
|
||||
type CreateServerDeps = {
|
||||
ImportServersBtn: FC<ImportServersBtnProps>;
|
||||
useTimeoutToggle: TimeoutToggle;
|
||||
@ -34,7 +30,8 @@ const ImportResult = ({ variant }: Pick<ResultProps, 'variant'>) => (
|
||||
</div>
|
||||
);
|
||||
|
||||
const CreateServer: FCWithDeps<CreateServerProps, CreateServerDeps> = ({ servers, createServers }) => {
|
||||
const CreateServer: FCWithDeps<any, CreateServerDeps> = () => {
|
||||
const { servers, createServers } = useServers();
|
||||
const { ImportServersBtn, useTimeoutToggle } = useDependencies(CreateServer);
|
||||
const navigate = useNavigate();
|
||||
const goBack = useGoBack();
|
||||
|
||||
@ -2,21 +2,14 @@ import { useToggle } from '@shlinkio/shlink-frontend-kit';
|
||||
import type { FC, PropsWithChildren } from 'react';
|
||||
import { useCallback } from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import type { FCWithDeps } from '../container/utils';
|
||||
import { componentFactory, useDependencies } from '../container/utils';
|
||||
import type { ServerWithId } from './data';
|
||||
import type { DeleteServerModalProps } from './DeleteServerModal';
|
||||
import { DeleteServerModal } from './DeleteServerModal';
|
||||
|
||||
export type DeleteServerButtonProps = PropsWithChildren<{
|
||||
server: ServerWithId;
|
||||
}>;
|
||||
|
||||
type DeleteServerButtonDeps = {
|
||||
DeleteServerModal: FC<DeleteServerModalProps>;
|
||||
};
|
||||
|
||||
const DeleteServerButton: FCWithDeps<DeleteServerButtonProps, DeleteServerButtonDeps> = ({ server, children }) => {
|
||||
const { DeleteServerModal } = useDependencies(DeleteServerButton);
|
||||
export const DeleteServerButton: FC<DeleteServerButtonProps> = ({ server, children }) => {
|
||||
const { flag: isModalOpen, setToTrue: showModal, setToFalse: hideModal } = useToggle();
|
||||
const navigate = useNavigate();
|
||||
const onClose = useCallback((confirmed: boolean) => {
|
||||
@ -35,5 +28,3 @@ const DeleteServerButton: FCWithDeps<DeleteServerButtonProps, DeleteServerButton
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export const DeleteServerButtonFactory = componentFactory(DeleteServerButton, ['DeleteServerModal']);
|
||||
|
||||
@ -3,6 +3,7 @@ import { CardModal } from '@shlinkio/shlink-frontend-kit';
|
||||
import type { FC } from 'react';
|
||||
import { useCallback } from 'react';
|
||||
import type { ServerWithId } from './data';
|
||||
import { useServers } from './reducers/servers';
|
||||
|
||||
export type DeleteServerModalProps = {
|
||||
server: ServerWithId;
|
||||
@ -10,11 +11,8 @@ export type DeleteServerModalProps = {
|
||||
open: boolean;
|
||||
};
|
||||
|
||||
type DeleteServerModalConnectProps = DeleteServerModalProps & {
|
||||
deleteServer: (server: ServerWithId) => void;
|
||||
};
|
||||
|
||||
export const DeleteServerModal: FC<DeleteServerModalConnectProps> = ({ server, onClose, open, deleteServer }) => {
|
||||
export const DeleteServerModal: FC<DeleteServerModalProps> = ({ server, onClose, open }) => {
|
||||
const { deleteServer } = useServers();
|
||||
const onClosed = useCallback((exitAction: ExitAction) => {
|
||||
if (exitAction === 'confirm') {
|
||||
deleteServer(server);
|
||||
|
||||
@ -1,26 +1,17 @@
|
||||
import { Button,useParsedQuery } from '@shlinkio/shlink-frontend-kit';
|
||||
import { Button, useParsedQuery } from '@shlinkio/shlink-frontend-kit';
|
||||
import type { FC } from 'react';
|
||||
import { NoMenuLayout } from '../common/NoMenuLayout';
|
||||
import type { FCWithDeps } from '../container/utils';
|
||||
import { componentFactory } from '../container/utils';
|
||||
import { useGoBack } from '../utils/helpers/hooks';
|
||||
import type { ServerData } from './data';
|
||||
import { isServerWithId } from './data';
|
||||
import { ServerForm } from './helpers/ServerForm';
|
||||
import type { WithSelectedServerProps } from './helpers/withSelectedServer';
|
||||
import { withSelectedServer } from './helpers/withSelectedServer';
|
||||
import { useSelectedServer } from './reducers/selectedServer';
|
||||
import { useServers } from './reducers/servers';
|
||||
|
||||
type EditServerProps = WithSelectedServerProps & {
|
||||
editServer: (serverId: string, serverData: ServerData) => void;
|
||||
};
|
||||
|
||||
type EditServerDeps = {
|
||||
ServerError: FC;
|
||||
};
|
||||
|
||||
const EditServer: FCWithDeps<EditServerProps, EditServerDeps> = withSelectedServer((
|
||||
{ editServer, selectedServer, selectServer },
|
||||
) => {
|
||||
export const EditServer: FC = withSelectedServer(() => {
|
||||
const { editServer } = useServers();
|
||||
const { selectServer, selectedServer } = useSelectedServer();
|
||||
const goBack = useGoBack();
|
||||
const { reconnect } = useParsedQuery<{ reconnect?: 'true' }>();
|
||||
|
||||
@ -49,5 +40,3 @@ const EditServer: FCWithDeps<EditServerProps, EditServerDeps> = withSelectedServ
|
||||
</NoMenuLayout>
|
||||
);
|
||||
});
|
||||
|
||||
export const EditServerFactory = componentFactory(EditServer, ['ServerError']);
|
||||
|
||||
@ -7,31 +7,26 @@ import { useMemo, useState } from 'react';
|
||||
import { NoMenuLayout } from '../common/NoMenuLayout';
|
||||
import type { FCWithDeps } from '../container/utils';
|
||||
import { componentFactory, useDependencies } from '../container/utils';
|
||||
import type { ServersMap } from './data';
|
||||
import type { ImportServersBtnProps } from './helpers/ImportServersBtn';
|
||||
import type { ManageServersRowProps } from './ManageServersRow';
|
||||
import { ManageServersRow } from './ManageServersRow';
|
||||
import { useServers } from './reducers/servers';
|
||||
import type { ServersExporter } from './services/ServersExporter';
|
||||
|
||||
type ManageServersProps = {
|
||||
servers: ServersMap;
|
||||
};
|
||||
|
||||
type ManageServersDeps = {
|
||||
ServersExporter: ServersExporter;
|
||||
ImportServersBtn: FC<ImportServersBtnProps>;
|
||||
useTimeoutToggle: TimeoutToggle;
|
||||
ManageServersRow: FC<ManageServersRowProps>;
|
||||
};
|
||||
|
||||
const SHOW_IMPORT_MSG_TIME = 4000;
|
||||
|
||||
const ManageServers: FCWithDeps<ManageServersProps, ManageServersDeps> = ({ servers }) => {
|
||||
const ManageServers: FCWithDeps<unknown, ManageServersDeps> = () => {
|
||||
const {
|
||||
ServersExporter: serversExporter,
|
||||
ImportServersBtn,
|
||||
useTimeoutToggle,
|
||||
ManageServersRow,
|
||||
} = useDependencies(ManageServers);
|
||||
const { servers } = useServers();
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const allServers = useMemo(() => Object.values(servers), [servers]);
|
||||
const filteredServers = useMemo(
|
||||
@ -93,5 +88,4 @@ export const ManageServersFactory = componentFactory(ManageServers, [
|
||||
'ServersExporter',
|
||||
'ImportServersBtn',
|
||||
'useTimeoutToggle',
|
||||
'ManageServersRow',
|
||||
]);
|
||||
|
||||
@ -3,22 +3,15 @@ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { Table, Tooltip, useTooltip } from '@shlinkio/shlink-frontend-kit';
|
||||
import type { FC } from 'react';
|
||||
import { Link } from 'react-router';
|
||||
import type { FCWithDeps } from '../container/utils';
|
||||
import { componentFactory, useDependencies } from '../container/utils';
|
||||
import type { ServerWithId } from './data';
|
||||
import type { ManageServersRowDropdownProps } from './ManageServersRowDropdown';
|
||||
import { ManageServersRowDropdown } from './ManageServersRowDropdown';
|
||||
|
||||
export type ManageServersRowProps = {
|
||||
server: ServerWithId;
|
||||
hasAutoConnect: boolean;
|
||||
};
|
||||
|
||||
type ManageServersRowDeps = {
|
||||
ManageServersRowDropdown: FC<ManageServersRowDropdownProps>;
|
||||
};
|
||||
|
||||
const ManageServersRow: FCWithDeps<ManageServersRowProps, ManageServersRowDeps> = ({ server, hasAutoConnect }) => {
|
||||
const { ManageServersRowDropdown } = useDependencies(ManageServersRow);
|
||||
export const ManageServersRow: FC<ManageServersRowProps> = ({ server, hasAutoConnect }) => {
|
||||
const { anchor, tooltip } = useTooltip();
|
||||
|
||||
return (
|
||||
@ -31,6 +24,7 @@ const ManageServersRow: FCWithDeps<ManageServersRowProps, ManageServersRowDeps>
|
||||
icon={checkIcon}
|
||||
className="text-lm-brand dark:text-dm-brand"
|
||||
{...anchor}
|
||||
data-testid="auto-connect"
|
||||
/>
|
||||
<Tooltip {...tooltip}>Auto-connect to this server</Tooltip>
|
||||
</>
|
||||
@ -47,5 +41,3 @@ const ManageServersRow: FCWithDeps<ManageServersRowProps, ManageServersRowDeps>
|
||||
</Table.Row>
|
||||
);
|
||||
};
|
||||
|
||||
export const ManageServersRowFactory = componentFactory(ManageServersRow, ['ManageServersRowDropdown']);
|
||||
|
||||
@ -6,29 +6,18 @@ import {
|
||||
faPlug as connectIcon,
|
||||
} from '@fortawesome/free-solid-svg-icons';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { RowDropdown,useToggle } from '@shlinkio/shlink-frontend-kit';
|
||||
import { RowDropdown, useToggle } from '@shlinkio/shlink-frontend-kit';
|
||||
import type { FC } from 'react';
|
||||
import type { FCWithDeps } from '../container/utils';
|
||||
import { componentFactory, useDependencies } from '../container/utils';
|
||||
import type { ServerWithId } from './data';
|
||||
import type { DeleteServerModalProps } from './DeleteServerModal';
|
||||
import { DeleteServerModal } from './DeleteServerModal';
|
||||
import { useServers } from './reducers/servers';
|
||||
|
||||
export type ManageServersRowDropdownProps = {
|
||||
server: ServerWithId;
|
||||
};
|
||||
|
||||
type ManageServersRowDropdownConnectProps = ManageServersRowDropdownProps & {
|
||||
setAutoConnect: (server: ServerWithId, autoConnect: boolean) => void;
|
||||
};
|
||||
|
||||
type ManageServersRowDropdownDeps = {
|
||||
DeleteServerModal: FC<DeleteServerModalProps>
|
||||
};
|
||||
|
||||
const ManageServersRowDropdown: FCWithDeps<ManageServersRowDropdownConnectProps, ManageServersRowDropdownDeps> = (
|
||||
{ server, setAutoConnect },
|
||||
) => {
|
||||
const { DeleteServerModal } = useDependencies(ManageServersRowDropdown);
|
||||
export const ManageServersRowDropdown: FC<ManageServersRowDropdownProps> = ({ server }) => {
|
||||
const { setAutoConnect } = useServers();
|
||||
const { flag: isModalOpen, setToTrue: showModal, setToFalse: hideModal } = useToggle();
|
||||
const serverUrl = `/server/${server.id}`;
|
||||
const { autoConnect: isAutoConnect } = server;
|
||||
@ -56,5 +45,3 @@ const ManageServersRowDropdown: FCWithDeps<ManageServersRowDropdownConnectProps,
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export const ManageServersRowDropdownFactory = componentFactory(ManageServersRowDropdown, ['DeleteServerModal']);
|
||||
|
||||
@ -1,16 +1,15 @@
|
||||
import { faPlus as plusIcon, faServer as serverIcon } from '@fortawesome/free-solid-svg-icons';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { Dropdown, NavBar } from '@shlinkio/shlink-frontend-kit';
|
||||
import type { SelectedServer, ServersMap } from './data';
|
||||
import type { FC } from 'react';
|
||||
import { getServerId } from './data';
|
||||
import { useSelectedServer } from './reducers/selectedServer';
|
||||
import { useServers } from './reducers/servers';
|
||||
|
||||
export interface ServersDropdownProps {
|
||||
servers: ServersMap;
|
||||
selectedServer: SelectedServer;
|
||||
}
|
||||
|
||||
export const ServersDropdown = ({ servers, selectedServer }: ServersDropdownProps) => {
|
||||
export const ServersDropdown: FC = () => {
|
||||
const { servers } = useServers();
|
||||
const serversList = Object.values(servers);
|
||||
const { selectedServer } = useSelectedServer();
|
||||
|
||||
return (
|
||||
<NavBar.Dropdown buttonContent={(
|
||||
|
||||
@ -26,18 +26,16 @@ const ServerListItem = ({ id, name }: { id: string; name: string }) => (
|
||||
);
|
||||
|
||||
export const ServersListGroup: FC<ServersListGroupProps> = ({ servers, borderless }) => (
|
||||
<>
|
||||
{servers.length > 0 && (
|
||||
<div
|
||||
data-testid="list"
|
||||
className={clsx(
|
||||
'w-full border-lm-border dark:border-dm-border',
|
||||
'md:max-h-56 md:overflow-y-auto -mb-1 scroll-thin',
|
||||
{ 'border-y': !borderless },
|
||||
)}
|
||||
>
|
||||
{servers.map(({ id, name }) => <ServerListItem key={id} id={id} name={name} />)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
servers.length > 0 && (
|
||||
<div
|
||||
data-testid="list"
|
||||
className={clsx(
|
||||
'w-full border-lm-border dark:border-dm-border',
|
||||
'md:max-h-56 md:overflow-y-auto -mb-1 scroll-thin',
|
||||
{ 'border-y': !borderless },
|
||||
)}
|
||||
>
|
||||
{servers.map(({ id, name }) => <ServerListItem key={id} id={id} name={name} />)}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
|
||||
@ -26,7 +26,7 @@ export const DuplicatedServersModal: FC<DuplicatedServersModalProps> = (
|
||||
cancelText={hasMultipleServers ? 'Ignore duplicates' : 'Discard'}
|
||||
>
|
||||
<p>{hasMultipleServers ? 'The next servers already exist:' : 'There is already a server with:'}</p>
|
||||
<ul className="list-disc mt-4">
|
||||
<ul className="list-disc my-4 pl-5">
|
||||
{duplicatedServers.map(({ url, apiKey }, index) => (!hasMultipleServers ? (
|
||||
<Fragment key={index}>
|
||||
<li>URL: <b>{url}</b></li>
|
||||
|
||||
@ -5,7 +5,8 @@ import type { ChangeEvent, PropsWithChildren } from 'react';
|
||||
import { useCallback, useRef, useState } from 'react';
|
||||
import type { FCWithDeps } from '../../container/utils';
|
||||
import { componentFactory, useDependencies } from '../../container/utils';
|
||||
import type { ServerData, ServersMap, ServerWithId } from '../data';
|
||||
import type { ServerData } from '../data';
|
||||
import { useServers } from '../reducers/servers';
|
||||
import type { ServersImporter } from '../services/ServersImporter';
|
||||
import { DuplicatedServersModal } from './DuplicatedServersModal';
|
||||
import { dedupServers, ensureUniqueIds } from './index';
|
||||
@ -17,24 +18,18 @@ export type ImportServersBtnProps = PropsWithChildren<{
|
||||
className?: string;
|
||||
}>;
|
||||
|
||||
type ImportServersBtnConnectProps = ImportServersBtnProps & {
|
||||
createServers: (servers: ServerWithId[]) => void;
|
||||
servers: ServersMap;
|
||||
};
|
||||
|
||||
type ImportServersBtnDeps = {
|
||||
ServersImporter: ServersImporter
|
||||
};
|
||||
|
||||
const ImportServersBtn: FCWithDeps<ImportServersBtnConnectProps, ImportServersBtnDeps> = ({
|
||||
createServers,
|
||||
servers,
|
||||
const ImportServersBtn: FCWithDeps<ImportServersBtnProps, ImportServersBtnDeps> = ({
|
||||
children,
|
||||
onImport,
|
||||
onError = () => {},
|
||||
tooltipPlacement = 'bottom',
|
||||
className = '',
|
||||
}) => {
|
||||
const { createServers, servers } = useServers();
|
||||
const { ServersImporter: serversImporter } = useDependencies(ImportServersBtn);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const { anchor, tooltip } = useTooltip({ placement: tooltipPlacement });
|
||||
|
||||
@ -2,24 +2,15 @@ import { Card, Message } from '@shlinkio/shlink-frontend-kit';
|
||||
import type { FC } from 'react';
|
||||
import { Link } from 'react-router';
|
||||
import { NoMenuLayout } from '../../common/NoMenuLayout';
|
||||
import type { FCWithDeps } from '../../container/utils';
|
||||
import { componentFactory, useDependencies } from '../../container/utils';
|
||||
import type { SelectedServer, ServersMap } from '../data';
|
||||
import { isServerWithId } from '../data';
|
||||
import type { DeleteServerButtonProps } from '../DeleteServerButton';
|
||||
import { DeleteServerButton } from '../DeleteServerButton';
|
||||
import { useSelectedServer } from '../reducers/selectedServer';
|
||||
import { useServers } from '../reducers/servers';
|
||||
import { ServersListGroup } from '../ServersListGroup';
|
||||
|
||||
type ServerErrorProps = {
|
||||
servers: ServersMap;
|
||||
selectedServer: SelectedServer;
|
||||
};
|
||||
|
||||
type ServerErrorDeps = {
|
||||
DeleteServerButton: FC<DeleteServerButtonProps>;
|
||||
};
|
||||
|
||||
const ServerError: FCWithDeps<ServerErrorProps, ServerErrorDeps> = ({ servers, selectedServer }) => {
|
||||
const { DeleteServerButton } = useDependencies(ServerError);
|
||||
export const ServerError: FC = () => {
|
||||
const { servers } = useServers();
|
||||
const { selectedServer } = useSelectedServer();
|
||||
|
||||
return (
|
||||
<NoMenuLayout>
|
||||
@ -54,5 +45,3 @@ const ServerError: FCWithDeps<ServerErrorProps, ServerErrorDeps> = ({ servers, s
|
||||
</NoMenuLayout>
|
||||
);
|
||||
};
|
||||
|
||||
export const ServerErrorFactory = componentFactory(ServerError, ['DeleteServerButton']);
|
||||
|
||||
@ -3,27 +3,14 @@ import type { FC } from 'react';
|
||||
import { useEffect } from 'react';
|
||||
import { useParams } from 'react-router';
|
||||
import { NoMenuLayout } from '../../common/NoMenuLayout';
|
||||
import type { FCWithDeps } from '../../container/utils';
|
||||
import { useDependencies } from '../../container/utils';
|
||||
import type { SelectedServer } from '../data';
|
||||
import { isNotFoundServer } from '../data';
|
||||
import { useSelectedServer } from '../reducers/selectedServer';
|
||||
import { ServerError } from './ServerError';
|
||||
|
||||
export type WithSelectedServerProps = {
|
||||
selectServer: (serverId: string) => void;
|
||||
selectedServer: SelectedServer;
|
||||
};
|
||||
|
||||
type WithSelectedServerPropsDeps = {
|
||||
ServerError: FC;
|
||||
};
|
||||
|
||||
export function withSelectedServer<T extends object>(
|
||||
WrappedComponent: FCWithDeps<WithSelectedServerProps & T, WithSelectedServerPropsDeps>,
|
||||
) {
|
||||
const ComponentWrapper: FCWithDeps<WithSelectedServerProps & T, WithSelectedServerPropsDeps> = (props) => {
|
||||
const { ServerError } = useDependencies(ComponentWrapper);
|
||||
export function withSelectedServer<T extends object>(WrappedComponent: FC<T>) {
|
||||
const ComponentWrapper: FC<T> = (props) => {
|
||||
const params = useParams<{ serverId: string }>();
|
||||
const { selectServer, selectedServer } = props;
|
||||
const { selectServer, selectedServer } = useSelectedServer();
|
||||
|
||||
useEffect(() => {
|
||||
if (params.serverId) {
|
||||
|
||||
@ -1,13 +1,10 @@
|
||||
import type { FC } from 'react';
|
||||
import { useEffect } from 'react';
|
||||
import { useSelectedServer } from '../reducers/selectedServer';
|
||||
|
||||
interface WithoutSelectedServerProps {
|
||||
resetSelectedServer: () => unknown;
|
||||
}
|
||||
|
||||
export function withoutSelectedServer<T extends object>(WrappedComponent: FC<WithoutSelectedServerProps & T>) {
|
||||
return (props: WithoutSelectedServerProps & T) => {
|
||||
const { resetSelectedServer } = props;
|
||||
export function withoutSelectedServer<T extends object>(WrappedComponent: FC<T>) {
|
||||
return (props: T) => {
|
||||
const { resetSelectedServer } = useSelectedServer();
|
||||
useEffect(() => {
|
||||
resetSelectedServer();
|
||||
}, [resetSelectedServer]);
|
||||
|
||||
@ -1,21 +1,46 @@
|
||||
import type { HttpClient } from '@shlinkio/shlink-js-sdk';
|
||||
import { useCallback, useEffect, useRef } from 'react';
|
||||
import pack from '../../../package.json';
|
||||
import { createAsyncThunk } from '../../utils/helpers/redux';
|
||||
import { useDependencies } from '../../container/context';
|
||||
import { useAppDispatch } from '../../store';
|
||||
import { createAsyncThunk } from '../../store/helpers';
|
||||
import { hasServerData } from '../data';
|
||||
import { ensureUniqueIds } from '../helpers';
|
||||
import { createServers } from './servers';
|
||||
import { createServers, useServers } from './servers';
|
||||
|
||||
const responseToServersList = (data: any) => ensureUniqueIds(
|
||||
{},
|
||||
(Array.isArray(data) ? data.filter(hasServerData) : []),
|
||||
);
|
||||
|
||||
export const fetchServers = (httpClient: HttpClient) => createAsyncThunk(
|
||||
export const fetchServers = createAsyncThunk(
|
||||
'shlink/remoteServers/fetchServers',
|
||||
async (_: void, { dispatch }): Promise<void> => {
|
||||
async (httpClient: HttpClient, { dispatch }): Promise<void> => {
|
||||
const resp = await httpClient.jsonRequest<any>(`${pack.homepage}/servers.json`);
|
||||
const result = responseToServersList(resp);
|
||||
|
||||
dispatch(createServers(result));
|
||||
},
|
||||
);
|
||||
|
||||
export const useRemoteServers = () => {
|
||||
const dispatch = useAppDispatch();
|
||||
const [httpClient] = useDependencies<[HttpClient]>('HttpClient');
|
||||
const dispatchFetchServer = useCallback(() => dispatch(fetchServers(httpClient)), [dispatch, httpClient]);
|
||||
|
||||
return { fetchServers: dispatchFetchServer };
|
||||
};
|
||||
|
||||
export const useLoadRemoteServers = () => {
|
||||
const { fetchServers } = useRemoteServers();
|
||||
const { servers } = useServers();
|
||||
const initialServers = useRef(servers);
|
||||
|
||||
useEffect(() => {
|
||||
// Try to fetch the remote servers if the list is empty during first render.
|
||||
// We use a ref because we don't care if the servers list becomes empty later.
|
||||
if (Object.keys(initialServers.current).length === 0) {
|
||||
fetchServers();
|
||||
}
|
||||
}, [fetchServers]);
|
||||
};
|
||||
|
||||
@ -1,8 +1,11 @@
|
||||
import { createAction, createSlice } from '@reduxjs/toolkit';
|
||||
import { memoizeWith } from '@shlinkio/data-manipulation';
|
||||
import type { ShlinkHealth } from '@shlinkio/shlink-web-component/api-contract';
|
||||
import { useCallback } from 'react';
|
||||
import type { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
|
||||
import { createAsyncThunk } from '../../utils/helpers/redux';
|
||||
import { useDependencies } from '../../container/context';
|
||||
import { useAppDispatch, useAppSelector } from '../../store';
|
||||
import { createAsyncThunk } from '../../store/helpers';
|
||||
import { versionToPrintable, versionToSemVer as toSemVer } from '../../utils/helpers/version';
|
||||
import type { SelectedServer, ServerWithId } from '../data';
|
||||
|
||||
@ -29,9 +32,14 @@ const initialState: SelectedServer = null;
|
||||
|
||||
export const resetSelectedServer = createAction<void>(`${REDUCER_PREFIX}/resetSelectedServer`);
|
||||
|
||||
export const selectServer = (buildShlinkApiClient: ShlinkApiClientBuilder) => createAsyncThunk(
|
||||
export type SelectServerOptions = {
|
||||
serverId: string;
|
||||
buildShlinkApiClient: ShlinkApiClientBuilder;
|
||||
};
|
||||
|
||||
export const selectServer = createAsyncThunk(
|
||||
`${REDUCER_PREFIX}/selectServer`,
|
||||
async (serverId: string, { dispatch, getState }): Promise<SelectedServer> => {
|
||||
async ({ serverId, buildShlinkApiClient }: SelectServerOptions, { dispatch, getState }): Promise<SelectedServer> => {
|
||||
dispatch(resetSelectedServer());
|
||||
|
||||
const { servers } = getState();
|
||||
@ -56,14 +64,29 @@ export const selectServer = (buildShlinkApiClient: ShlinkApiClientBuilder) => cr
|
||||
},
|
||||
);
|
||||
|
||||
type SelectServerThunk = ReturnType<typeof selectServer>;
|
||||
|
||||
export const selectedServerReducerCreator = (selectServerThunk: SelectServerThunk) => createSlice({
|
||||
export const { reducer: selectedServerReducer } = createSlice({
|
||||
name: REDUCER_PREFIX,
|
||||
initialState,
|
||||
initialState: initialState as SelectedServer,
|
||||
reducers: {},
|
||||
extraReducers: (builder) => {
|
||||
builder.addCase(resetSelectedServer, () => initialState);
|
||||
builder.addCase(selectServerThunk.fulfilled, (_, { payload }) => payload as any);
|
||||
builder.addCase(selectServer.fulfilled, (_, { payload }) => payload);
|
||||
},
|
||||
});
|
||||
|
||||
export const useSelectedServer = () => {
|
||||
const dispatch = useAppDispatch();
|
||||
const [buildShlinkApiClient] = useDependencies<[ShlinkApiClientBuilder]>('buildShlinkApiClient');
|
||||
const dispatchResetSelectedServer = useCallback(() => dispatch(resetSelectedServer()), [dispatch]);
|
||||
const dispatchSelectServer = useCallback(
|
||||
(serverId: string) => dispatch(selectServer({ serverId, buildShlinkApiClient })),
|
||||
[buildShlinkApiClient, dispatch],
|
||||
);
|
||||
const selectedServer = useAppSelector(({ selectedServer }) => selectedServer);
|
||||
|
||||
return {
|
||||
selectedServer,
|
||||
resetSelectedServer: dispatchResetSelectedServer,
|
||||
selectServer: dispatchSelectServer,
|
||||
};
|
||||
};
|
||||
|
||||
@ -1,21 +1,23 @@
|
||||
import type { PayloadAction } from '@reduxjs/toolkit';
|
||||
import { createSlice } from '@reduxjs/toolkit';
|
||||
import { useCallback } from 'react';
|
||||
import { useAppDispatch, useAppSelector } from '../../store';
|
||||
import type { ServerData, ServersMap, ServerWithId } from '../data';
|
||||
import { serversListToMap } from '../helpers';
|
||||
|
||||
interface EditServer {
|
||||
type EditServer = {
|
||||
serverId: string;
|
||||
serverData: Partial<ServerData>;
|
||||
}
|
||||
};
|
||||
|
||||
interface SetAutoConnect {
|
||||
type SetAutoConnect = {
|
||||
serverId: string;
|
||||
autoConnect: boolean;
|
||||
}
|
||||
};
|
||||
|
||||
const initialState: ServersMap = {};
|
||||
|
||||
export const { actions, reducer } = createSlice({
|
||||
export const { actions, reducer: serversReducer } = createSlice({
|
||||
name: 'shlink/servers',
|
||||
initialState,
|
||||
reducers: {
|
||||
@ -65,4 +67,19 @@ export const { actions, reducer } = createSlice({
|
||||
|
||||
export const { editServer, deleteServer, setAutoConnect, createServers } = actions;
|
||||
|
||||
export const serversReducer = reducer;
|
||||
export const useServers = () => {
|
||||
const dispatch = useAppDispatch();
|
||||
const servers = useAppSelector((state) => state.servers);
|
||||
const editServer = useCallback(
|
||||
(serverId: string, serverData: Partial<ServerData>) => dispatch(actions.editServer(serverId, serverData)),
|
||||
[dispatch],
|
||||
);
|
||||
const deleteServer = useCallback((server: ServerWithId) => dispatch(actions.deleteServer(server)), [dispatch]);
|
||||
const setAutoConnect = useCallback(
|
||||
(serverData: ServerWithId, autoConnect: boolean) => dispatch(actions.setAutoConnect(serverData, autoConnect)),
|
||||
[dispatch],
|
||||
);
|
||||
const createServers = useCallback((servers: ServerWithId[]) => dispatch(actions.createServers(servers)), [dispatch]);
|
||||
|
||||
return { servers, editServer, deleteServer, setAutoConnect, createServers };
|
||||
};
|
||||
|
||||
@ -1,73 +0,0 @@
|
||||
import type Bottle from 'bottlejs';
|
||||
import type { ConnectDecorator } from '../../container/types';
|
||||
import { CreateServerFactory } from '../CreateServer';
|
||||
import { DeleteServerButtonFactory } from '../DeleteServerButton';
|
||||
import { DeleteServerModal } from '../DeleteServerModal';
|
||||
import { EditServerFactory } from '../EditServer';
|
||||
import { ImportServersBtnFactory } from '../helpers/ImportServersBtn';
|
||||
import { ServerErrorFactory } from '../helpers/ServerError';
|
||||
import { withoutSelectedServer } from '../helpers/withoutSelectedServer';
|
||||
import { ManageServersFactory } from '../ManageServers';
|
||||
import { ManageServersRowFactory } from '../ManageServersRow';
|
||||
import { ManageServersRowDropdownFactory } from '../ManageServersRowDropdown';
|
||||
import { fetchServers } from '../reducers/remoteServers';
|
||||
import {
|
||||
resetSelectedServer,
|
||||
selectedServerReducerCreator,
|
||||
selectServer,
|
||||
} from '../reducers/selectedServer';
|
||||
import { createServers, deleteServer, editServer, setAutoConnect } from '../reducers/servers';
|
||||
import { ServersDropdown } from '../ServersDropdown';
|
||||
import { ServersExporter } from './ServersExporter';
|
||||
import { ServersImporter } from './ServersImporter';
|
||||
|
||||
export const provideServices = (bottle: Bottle, connect: ConnectDecorator) => {
|
||||
// Components
|
||||
bottle.factory('ManageServers', ManageServersFactory);
|
||||
bottle.decorator('ManageServers', withoutSelectedServer);
|
||||
bottle.decorator('ManageServers', connect(['selectedServer', 'servers'], ['resetSelectedServer']));
|
||||
|
||||
bottle.factory('ManageServersRow', ManageServersRowFactory);
|
||||
|
||||
bottle.factory('ManageServersRowDropdown', ManageServersRowDropdownFactory);
|
||||
bottle.decorator('ManageServersRowDropdown', connect(null, ['setAutoConnect']));
|
||||
|
||||
bottle.factory('CreateServer', CreateServerFactory);
|
||||
bottle.decorator('CreateServer', withoutSelectedServer);
|
||||
bottle.decorator('CreateServer', connect(['selectedServer', 'servers'], ['createServers', 'resetSelectedServer']));
|
||||
|
||||
bottle.factory('EditServer', EditServerFactory);
|
||||
bottle.decorator('EditServer', connect(['selectedServer'], ['editServer', 'selectServer', 'resetSelectedServer']));
|
||||
|
||||
bottle.serviceFactory('ServersDropdown', () => ServersDropdown);
|
||||
bottle.decorator('ServersDropdown', connect(['servers', 'selectedServer']));
|
||||
|
||||
bottle.serviceFactory('DeleteServerModal', () => DeleteServerModal);
|
||||
bottle.decorator('DeleteServerModal', connect(null, ['deleteServer']));
|
||||
|
||||
bottle.factory('DeleteServerButton', DeleteServerButtonFactory);
|
||||
|
||||
bottle.factory('ImportServersBtn', ImportServersBtnFactory);
|
||||
bottle.decorator('ImportServersBtn', connect(['servers'], ['createServers']));
|
||||
|
||||
bottle.factory('ServerError', ServerErrorFactory);
|
||||
bottle.decorator('ServerError', connect(['servers', 'selectedServer']));
|
||||
|
||||
// Services
|
||||
bottle.service('ServersImporter', ServersImporter, 'csvToJson');
|
||||
bottle.service('ServersExporter', ServersExporter, 'Storage', 'window', 'jsonToCsv');
|
||||
|
||||
// Actions
|
||||
bottle.serviceFactory('selectServer', selectServer, 'buildShlinkApiClient', 'loadMercureInfo');
|
||||
bottle.serviceFactory('createServers', () => createServers);
|
||||
bottle.serviceFactory('deleteServer', () => deleteServer);
|
||||
bottle.serviceFactory('editServer', () => editServer);
|
||||
bottle.serviceFactory('setAutoConnect', () => setAutoConnect);
|
||||
bottle.serviceFactory('fetchServers', fetchServers, 'HttpClient');
|
||||
|
||||
bottle.serviceFactory('resetSelectedServer', () => resetSelectedServer);
|
||||
|
||||
// Reducers
|
||||
bottle.serviceFactory('selectedServerReducerCreator', selectedServerReducerCreator, 'selectServer');
|
||||
bottle.serviceFactory('selectedServerReducer', (obj) => obj.reducer, 'selectedServerReducerCreator');
|
||||
};
|
||||
@ -1,20 +1,18 @@
|
||||
import type { Settings as AppSettings } from '@shlinkio/shlink-web-component/settings';
|
||||
import { ShlinkWebSettings } from '@shlinkio/shlink-web-component/settings';
|
||||
import type { FC } from 'react';
|
||||
import { NoMenuLayout } from '../common/NoMenuLayout';
|
||||
import { DEFAULT_SHORT_URLS_ORDERING } from './reducers/settings';
|
||||
import { DEFAULT_SHORT_URLS_ORDERING, useSettings } from './reducers/settings';
|
||||
|
||||
export type SettingsProps = {
|
||||
settings: AppSettings;
|
||||
setSettings: (newSettings: AppSettings) => void;
|
||||
export const Settings: FC = () => {
|
||||
const { settings, setSettings } = useSettings();
|
||||
|
||||
return (
|
||||
<NoMenuLayout>
|
||||
<ShlinkWebSettings
|
||||
settings={settings}
|
||||
onUpdateSettings={setSettings}
|
||||
defaultShortUrlsListOrdering={DEFAULT_SHORT_URLS_ORDERING}
|
||||
/>
|
||||
</NoMenuLayout>
|
||||
);
|
||||
};
|
||||
|
||||
export const Settings: FC<SettingsProps> = ({ settings, setSettings }) => (
|
||||
<NoMenuLayout>
|
||||
<ShlinkWebSettings
|
||||
settings={settings}
|
||||
onUpdateSettings={setSettings}
|
||||
defaultShortUrlsListOrdering={DEFAULT_SHORT_URLS_ORDERING}
|
||||
/>
|
||||
</NoMenuLayout>
|
||||
);
|
||||
|
||||
@ -1,12 +1,6 @@
|
||||
import type { ShlinkState } from '../../container/types';
|
||||
|
||||
export const migrateDeprecatedSettings = (state: Partial<ShlinkState>): Partial<ShlinkState> => {
|
||||
if (!state.settings) {
|
||||
return state;
|
||||
}
|
||||
|
||||
export const migrateDeprecatedSettings = (state: any): any => {
|
||||
// The "last180Days" interval had a typo, with a lowercase d
|
||||
if (state.settings.visits && (state.settings.visits.defaultInterval as any) === 'last180days') {
|
||||
if (state.settings?.visits?.defaultInterval === 'last180days') {
|
||||
state.settings.visits.defaultInterval = 'last180Days';
|
||||
}
|
||||
|
||||
|
||||
@ -3,6 +3,8 @@ import { createSlice } from '@reduxjs/toolkit';
|
||||
import { mergeDeepRight } from '@shlinkio/data-manipulation';
|
||||
import { getSystemPreferredTheme } from '@shlinkio/shlink-frontend-kit';
|
||||
import type { Settings, ShortUrlsListSettings } from '@shlinkio/shlink-web-component/settings';
|
||||
import { useCallback } from 'react';
|
||||
import { useAppDispatch, useAppSelector } from '../../store';
|
||||
import type { Defined } from '../../utils/types';
|
||||
|
||||
type ShortUrlsOrder = Defined<ShortUrlsListSettings['defaultOrdering']>;
|
||||
@ -41,3 +43,11 @@ const { reducer, actions } = createSlice({
|
||||
export const { setSettings } = actions;
|
||||
|
||||
export const settingsReducer = reducer;
|
||||
|
||||
export const useSettings = () => {
|
||||
const dispatch = useAppDispatch();
|
||||
const setSettings = useCallback((settings: Settings) => dispatch(actions.setSettings(settings)), [dispatch]);
|
||||
const settings = useAppSelector((state) => state.settings);
|
||||
|
||||
return { settings, setSettings };
|
||||
};
|
||||
|
||||
@ -1,15 +0,0 @@
|
||||
import type Bottle from 'bottlejs';
|
||||
import type { ConnectDecorator } from '../../container/types';
|
||||
import { withoutSelectedServer } from '../../servers/helpers/withoutSelectedServer';
|
||||
import { setSettings } from '../reducers/settings';
|
||||
import { Settings } from '../Settings';
|
||||
|
||||
export const provideServices = (bottle: Bottle, connect: ConnectDecorator) => {
|
||||
// Components
|
||||
bottle.serviceFactory('Settings', () => Settings);
|
||||
bottle.decorator('Settings', withoutSelectedServer);
|
||||
bottle.decorator('Settings', connect(['settings'], ['setSettings', 'resetSelectedServer']));
|
||||
|
||||
// Actions
|
||||
bottle.serviceFactory('setSettings', () => setSettings);
|
||||
};
|
||||
@ -1,10 +1,10 @@
|
||||
import type { AsyncThunkPayloadCreator } from '@reduxjs/toolkit';
|
||||
import { createAsyncThunk as baseCreateAsyncThunk } from '@reduxjs/toolkit';
|
||||
import type { ShlinkState } from '../../container/types';
|
||||
import type { RootState } from '.';
|
||||
|
||||
export const createAsyncThunk = <Returned, ThunkArg>(
|
||||
typePrefix: string,
|
||||
payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, { state: ShlinkState, serializedErrorType: any }>,
|
||||
payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, { state: RootState, serializedErrorType: any }>,
|
||||
) => baseCreateAsyncThunk(
|
||||
typePrefix,
|
||||
payloadCreator,
|
||||
32
src/store/index.ts
Normal file
32
src/store/index.ts
Normal file
@ -0,0 +1,32 @@
|
||||
import { configureStore } from '@reduxjs/toolkit';
|
||||
import { useDispatch, useSelector } from 'react-redux';
|
||||
import type { RLSOptions } from 'redux-localstorage-simple';
|
||||
import { load, save } from 'redux-localstorage-simple';
|
||||
import { migrateDeprecatedSettings } from '../settings/helpers';
|
||||
import { initReducers } from './reducers';
|
||||
|
||||
const localStorageConfig: RLSOptions = {
|
||||
states: ['settings', 'servers'],
|
||||
namespace: 'shlink',
|
||||
namespaceSeparator: '.',
|
||||
debounce: 300,
|
||||
};
|
||||
const getStateFromLocalStorage = () => migrateDeprecatedSettings(load(localStorageConfig));
|
||||
|
||||
const isProduction = process.env.NODE_ENV === 'production';
|
||||
export const setUpStore = (preloadedState = getStateFromLocalStorage()) => configureStore({
|
||||
devTools: !isProduction,
|
||||
reducer: initReducers(),
|
||||
preloadedState,
|
||||
middleware: (defaultMiddlewaresIncludingReduxThunk) =>
|
||||
defaultMiddlewaresIncludingReduxThunk().concat(save(localStorageConfig)),
|
||||
});
|
||||
|
||||
export type StoreType = ReturnType<typeof setUpStore>;
|
||||
export type AppDispatch = StoreType['dispatch'];
|
||||
export type GetState = StoreType['getState'];
|
||||
export type RootState = ReturnType<GetState>;
|
||||
|
||||
// Typed versions of useDispatch() and useSelector()
|
||||
export const useAppDispatch = useDispatch.withTypes<AppDispatch>();
|
||||
export const useAppSelector = useSelector.withTypes<RootState>();
|
||||
@ -1,12 +1,12 @@
|
||||
import { combineReducers } from '@reduxjs/toolkit';
|
||||
import type { IContainer } from 'bottlejs';
|
||||
import { appUpdatesReducer } from '../app/reducers/appUpdates';
|
||||
import { selectedServerReducer } from '../servers/reducers/selectedServer';
|
||||
import { serversReducer } from '../servers/reducers/servers';
|
||||
import { settingsReducer } from '../settings/reducers/settings';
|
||||
|
||||
export const initReducers = (container: IContainer) => combineReducers({
|
||||
export const initReducers = () => combineReducers({
|
||||
appUpdated: appUpdatesReducer,
|
||||
servers: serversReducer,
|
||||
selectedServer: container.selectedServerReducer,
|
||||
selectedServer: selectedServerReducer,
|
||||
settings: settingsReducer,
|
||||
});
|
||||
@ -8,7 +8,5 @@
|
||||
:root {
|
||||
--footer-height: 2.3rem;
|
||||
--footer-margin: .8rem;
|
||||
/* FIXME Remove this once updated to shlink-web-component 0.15.1 */
|
||||
--header-height: 52px;
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,16 +0,0 @@
|
||||
import { useTimeoutToggle } from '@shlinkio/shlink-frontend-kit';
|
||||
import type Bottle from 'bottlejs';
|
||||
import { csvToJson, jsonToCsv } from '../helpers/csvjson';
|
||||
import { LocalStorage } from './LocalStorage';
|
||||
import { TagColorsStorage } from './TagColorsStorage';
|
||||
|
||||
export const provideServices = (bottle: Bottle) => {
|
||||
bottle.constant('localStorage', window.localStorage);
|
||||
bottle.service('Storage', LocalStorage, 'localStorage');
|
||||
bottle.service('TagColorsStorage', TagColorsStorage, 'Storage');
|
||||
|
||||
bottle.constant('csvToJson', csvToJson);
|
||||
bottle.constant('jsonToCsv', jsonToCsv);
|
||||
|
||||
bottle.serviceFactory('useTimeoutToggle', () => useTimeoutToggle);
|
||||
};
|
||||
@ -1,23 +0,0 @@
|
||||
import type { FC, PropsWithChildren } from 'react';
|
||||
import { useMemo } from 'react';
|
||||
import { MemoryRouter, Route, Routes } from 'react-router';
|
||||
|
||||
export type MemoryRouterWithParamsProps = PropsWithChildren<{
|
||||
params: Record<string, string>;
|
||||
}>;
|
||||
|
||||
/**
|
||||
* Wrap any component using useParams() with MemoryRouterWithParams, in order to determine wat the hook should return
|
||||
*/
|
||||
export const MemoryRouterWithParams: FC<MemoryRouterWithParamsProps> = ({ children, params }) => {
|
||||
const pathname = useMemo(() => `/${Object.values(params).join('/')}`, [params]);
|
||||
const pathPattern = useMemo(() => `/:${Object.keys(params).join('/:')}`, [params]);
|
||||
|
||||
return (
|
||||
<MemoryRouter>
|
||||
<Routes location={{ pathname }}>
|
||||
<Route path={pathPattern} element={children} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
);
|
||||
};
|
||||
@ -1,8 +0,0 @@
|
||||
import { render } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import type { ReactElement } from 'react';
|
||||
|
||||
export const renderWithEvents = (element: ReactElement) => ({
|
||||
user: userEvent.setup(),
|
||||
...render(element),
|
||||
});
|
||||
29
test/__helpers__/setUpTest.tsx
Normal file
29
test/__helpers__/setUpTest.tsx
Normal file
@ -0,0 +1,29 @@
|
||||
import type { RenderOptions } from '@testing-library/react';
|
||||
import { render } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import type { PropsWithChildren, ReactElement } from 'react';
|
||||
import { Provider } from 'react-redux';
|
||||
import type { RootState } from '../../src/store';
|
||||
import { setUpStore } from '../../src/store';
|
||||
|
||||
export const renderWithEvents = (element: ReactElement, options?: RenderOptions) => ({
|
||||
user: userEvent.setup(),
|
||||
...render(element, options),
|
||||
});
|
||||
|
||||
export type RenderOptionsWithState = Omit<RenderOptions, 'wrapper'> & {
|
||||
initialState?: Partial<RootState>;
|
||||
};
|
||||
|
||||
export const renderWithStore = (
|
||||
element: ReactElement,
|
||||
{ initialState = {}, ...options }: RenderOptionsWithState = {},
|
||||
) => {
|
||||
const store = setUpStore(initialState);
|
||||
const Wrapper = ({ children }: PropsWithChildren) => <Provider store={store}>{children}</Provider>;
|
||||
|
||||
return {
|
||||
store,
|
||||
...renderWithEvents(element, { ...options, wrapper: Wrapper }),
|
||||
};
|
||||
};
|
||||
@ -1,50 +1,51 @@
|
||||
import { act, render, screen } from '@testing-library/react';
|
||||
import type { HttpClient } from '@shlinkio/shlink-js-sdk';
|
||||
import { act, screen } from '@testing-library/react';
|
||||
import { fromPartial } from '@total-typescript/shoehorn';
|
||||
import { MemoryRouter } from 'react-router';
|
||||
import { AppFactory } from '../../src/app/App';
|
||||
import { ContainerProvider } from '../../src/container/context';
|
||||
import type { ServerWithId } from '../../src/servers/data';
|
||||
import { checkAccessibility } from '../__helpers__/accessibility';
|
||||
import { renderWithStore } from '../__helpers__/setUpTest';
|
||||
|
||||
describe('<App />', () => {
|
||||
const App = AppFactory(
|
||||
fromPartial({
|
||||
MainHeader: () => <>MainHeader</>,
|
||||
Home: () => <>Home</>,
|
||||
ShlinkWebComponentContainer: () => <>ShlinkWebComponentContainer</>,
|
||||
CreateServer: () => <>CreateServer</>,
|
||||
EditServer: () => <>EditServer</>,
|
||||
Settings: () => <>SettingsComp</>,
|
||||
ManageServers: () => <>ManageServers</>,
|
||||
ShlinkVersionsContainer: () => <>ShlinkVersions</>,
|
||||
}),
|
||||
);
|
||||
const setUp = async (activeRoute = '/') => act(() => render(
|
||||
const setUp = async (activeRoute = '/') => act(() => renderWithStore(
|
||||
<MemoryRouter initialEntries={[{ pathname: activeRoute }]}>
|
||||
<App
|
||||
fetchServers={() => {}}
|
||||
servers={{}}
|
||||
settings={fromPartial({})}
|
||||
appUpdated={false}
|
||||
resetAppUpdate={() => {}}
|
||||
/>
|
||||
<ContainerProvider
|
||||
value={fromPartial({ HttpClient: fromPartial<HttpClient>({}), buildShlinkApiClient: vi.fn() })}
|
||||
>
|
||||
<App />
|
||||
</ContainerProvider>
|
||||
</MemoryRouter>,
|
||||
{
|
||||
initialState: {
|
||||
servers: {
|
||||
abc123: fromPartial<ServerWithId>({ id: 'abc123', name: 'abc123 server' }),
|
||||
def456: fromPartial<ServerWithId>({ id: 'def456', name: 'def456 server' }),
|
||||
},
|
||||
settings: fromPartial({}),
|
||||
appUpdated: false,
|
||||
},
|
||||
},
|
||||
));
|
||||
|
||||
it('passes a11y checks', () => checkAccessibility(setUp()));
|
||||
|
||||
it('renders children components', async () => {
|
||||
await setUp();
|
||||
|
||||
expect(screen.getByText('MainHeader')).toBeInTheDocument();
|
||||
expect(screen.getByText('ShlinkVersions')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['/settings/foo', 'SettingsComp'],
|
||||
['/settings/bar', 'SettingsComp'],
|
||||
['/settings/general', 'User interface'],
|
||||
['/settings/short-urls', 'Short URLs form'],
|
||||
['/manage-servers', 'ManageServers'],
|
||||
['/server/create', 'CreateServer'],
|
||||
['/server/abc123/edit', 'EditServer'],
|
||||
['/server/def456/edit', 'EditServer'],
|
||||
['/server/abc123/edit', 'Edit "abc123 server"'],
|
||||
['/server/def456/edit', 'Edit "def456 server"'],
|
||||
['/server/abc123/foo', 'ShlinkWebComponentContainer'],
|
||||
['/server/def456/bar', 'ShlinkWebComponentContainer'],
|
||||
['/other', 'Oops! We could not find requested route.'],
|
||||
|
||||
@ -1,15 +1,19 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { screen } from '@testing-library/react';
|
||||
import { fromPartial } from '@total-typescript/shoehorn';
|
||||
import { MemoryRouter } from 'react-router';
|
||||
import { Home } from '../../src/common/Home';
|
||||
import type { ServersMap, ServerWithId } from '../../src/servers/data';
|
||||
import { checkAccessibility } from '../__helpers__/accessibility';
|
||||
import { renderWithStore } from '../__helpers__/setUpTest';
|
||||
|
||||
describe('<Home />', () => {
|
||||
const setUp = (servers: ServersMap = {}) => render(
|
||||
const setUp = (servers: ServersMap = {}) => renderWithStore(
|
||||
<MemoryRouter>
|
||||
<Home servers={servers} />
|
||||
<Home />
|
||||
</MemoryRouter>,
|
||||
{
|
||||
initialState: { servers },
|
||||
},
|
||||
);
|
||||
|
||||
it('passes a11y checks', () => checkAccessibility(
|
||||
|
||||
@ -2,22 +2,21 @@ import { screen } from '@testing-library/react';
|
||||
import { fromPartial } from '@total-typescript/shoehorn';
|
||||
import { createMemoryHistory } from 'history';
|
||||
import { Router } from 'react-router';
|
||||
import { MainHeaderFactory } from '../../src/common/MainHeader';
|
||||
import { MainHeader } from '../../src/common/MainHeader';
|
||||
import { ContainerProvider } from '../../src/container/context';
|
||||
import { checkAccessibility } from '../__helpers__/accessibility';
|
||||
import { renderWithEvents } from '../__helpers__/setUpTest';
|
||||
import { renderWithStore } from '../__helpers__/setUpTest';
|
||||
|
||||
describe('<MainHeader />', () => {
|
||||
const MainHeader = MainHeaderFactory(fromPartial({
|
||||
// Fake this component as a li[role="menuitem"], as it gets rendered inside a ul[role="menu"]
|
||||
ServersDropdown: () => <li role="menuitem">ServersDropdown</li>,
|
||||
}));
|
||||
const setUp = (pathname = '') => {
|
||||
const history = createMemoryHistory();
|
||||
history.push(pathname);
|
||||
|
||||
return renderWithEvents(
|
||||
return renderWithStore(
|
||||
<Router location={history.location} navigator={history}>
|
||||
<MainHeader />
|
||||
<ContainerProvider value={fromPartial({ buildShlinkApiClient: vi.fn() })}>
|
||||
<MainHeader />
|
||||
</ContainerProvider>
|
||||
</Router>,
|
||||
);
|
||||
};
|
||||
@ -26,7 +25,7 @@ describe('<MainHeader />', () => {
|
||||
|
||||
it('renders ServersDropdown', () => {
|
||||
setUp();
|
||||
expect(screen.getByText('ServersDropdown')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Servers' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each([
|
||||
|
||||
@ -1,12 +1,18 @@
|
||||
import { render } from '@testing-library/react';
|
||||
import { fromPartial } from '@total-typescript/shoehorn';
|
||||
import { ShlinkVersionsContainer } from '../../src/common/ShlinkVersionsContainer';
|
||||
import { ContainerProvider } from '../../src/container/context';
|
||||
import type { ReachableServer, SelectedServer } from '../../src/servers/data';
|
||||
import { checkAccessibility } from '../__helpers__/accessibility';
|
||||
import { renderWithStore } from '../__helpers__/setUpTest';
|
||||
|
||||
describe('<ShlinkVersionsContainer />', () => {
|
||||
const setUp = (selectedServer: SelectedServer = null) => render(
|
||||
<ShlinkVersionsContainer selectedServer={selectedServer} />,
|
||||
const setUp = (selectedServer: SelectedServer = null) => renderWithStore(
|
||||
<ContainerProvider value={fromPartial({ buildShlinkApiClient: vi.fn() })}>
|
||||
<ShlinkVersionsContainer />
|
||||
</ContainerProvider>,
|
||||
{
|
||||
initialState: { selectedServer },
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
|
||||
@ -1,9 +1,11 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { screen } from '@testing-library/react';
|
||||
import { fromPartial } from '@total-typescript/shoehorn';
|
||||
import { MemoryRouter } from 'react-router';
|
||||
import { ShlinkWebComponentContainerFactory } from '../../src/common/ShlinkWebComponentContainer';
|
||||
import { ContainerProvider } from '../../src/container/context';
|
||||
import type { NonReachableServer, NotFoundServer, SelectedServer } from '../../src/servers/data';
|
||||
import { checkAccessibility } from '../__helpers__/accessibility';
|
||||
import { MemoryRouterWithParams } from '../__helpers__/MemoryRouterWithParams';
|
||||
import { renderWithStore } from '../__helpers__/setUpTest';
|
||||
|
||||
vi.mock('@shlinkio/shlink-web-component', () => ({
|
||||
ShlinkSidebarVisibilityProvider: ({ children }: any) => children,
|
||||
@ -15,12 +17,16 @@ describe('<ShlinkWebComponentContainer />', () => {
|
||||
const ShlinkWebComponentContainer = ShlinkWebComponentContainerFactory(fromPartial({
|
||||
buildShlinkApiClient: vi.fn().mockReturnValue(fromPartial({})),
|
||||
TagColorsStorage: fromPartial({}),
|
||||
ServerError: () => <>ServerError</>,
|
||||
}));
|
||||
const setUp = (selectedServer: SelectedServer) => render(
|
||||
<MemoryRouterWithParams params={{ serverId: 'abc123' }}>
|
||||
<ShlinkWebComponentContainer selectServer={vi.fn()} selectedServer={selectedServer} settings={{}} />
|
||||
</MemoryRouterWithParams>,
|
||||
const setUp = (selectedServer: SelectedServer) => renderWithStore(
|
||||
<MemoryRouter>
|
||||
<ContainerProvider value={fromPartial({ buildShlinkApiClient: vi.fn() })}>
|
||||
<ShlinkWebComponentContainer />
|
||||
</ContainerProvider>
|
||||
</MemoryRouter>,
|
||||
{
|
||||
initialState: { selectedServer, servers: {}, settings: {} },
|
||||
},
|
||||
);
|
||||
|
||||
it('passes a11y checks', () => checkAccessibility(setUp(fromPartial({ version: '3.0.0' }))));
|
||||
@ -29,18 +35,20 @@ describe('<ShlinkWebComponentContainer />', () => {
|
||||
setUp(null);
|
||||
|
||||
expect(screen.getByText('Loading...')).toBeInTheDocument();
|
||||
expect(screen.queryByText('ServerError')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('ShlinkWebComponent')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each([
|
||||
[fromPartial<NotFoundServer>({ serverNotFound: true })],
|
||||
[fromPartial<NonReachableServer>({ serverNotReachable: true })],
|
||||
])('shows error for non reachable servers', (selectedServer) => {
|
||||
[fromPartial<NotFoundServer>({ serverNotFound: true }), 'Could not find this Shlink server.'],
|
||||
[
|
||||
fromPartial<NonReachableServer>({ id: 'foo', serverNotReachable: true }),
|
||||
/Could not connect to this Shlink server/,
|
||||
],
|
||||
])('shows error for non reachable servers', (selectedServer, expectedError) => {
|
||||
setUp(selectedServer);
|
||||
|
||||
expect(screen.queryByText('Loading...')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('ServerError')).toBeInTheDocument();
|
||||
expect(screen.getByText(expectedError)).toBeInTheDocument();
|
||||
expect(screen.queryByText('ShlinkWebComponent')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
@ -48,7 +56,6 @@ describe('<ShlinkWebComponentContainer />', () => {
|
||||
setUp(fromPartial({ version: '3.0.0' }));
|
||||
|
||||
expect(screen.queryByText('Loading...')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('ServerError')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('ShlinkWebComponent')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
39
test/container/context.test.tsx
Normal file
39
test/container/context.test.tsx
Normal file
@ -0,0 +1,39 @@
|
||||
import { render } from '@testing-library/react';
|
||||
import { fromPartial } from '@total-typescript/shoehorn';
|
||||
import { ContainerProvider, useDependencies } from '../../src/container/context';
|
||||
|
||||
describe('context', () => {
|
||||
describe('useDependencies', () => {
|
||||
let lastDependencies: unknown[];
|
||||
|
||||
function TestComponent({ name}: { name: string }) {
|
||||
// eslint-disable-next-line react-compiler/react-compiler
|
||||
lastDependencies = useDependencies(name);
|
||||
return null;
|
||||
}
|
||||
|
||||
it('throws when used outside of ContainerProvider', () => {
|
||||
expect(() => render(<TestComponent name="foo" />)).toThrowError(
|
||||
'You cannot use "useDependencies" outside of a ContainerProvider',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when requested dependency is not found in container', () => {
|
||||
expect(() => render(
|
||||
<ContainerProvider value={fromPartial({})}>
|
||||
<TestComponent name="foo" />
|
||||
</ContainerProvider>,
|
||||
)).toThrowError('Dependency with name "foo" not found in container');
|
||||
});
|
||||
|
||||
it('gets dependency from container', () => {
|
||||
render(
|
||||
<ContainerProvider value={fromPartial({ foo: 'the dependency' })}>
|
||||
<TestComponent name="foo" />
|
||||
</ContainerProvider>,
|
||||
);
|
||||
|
||||
expect(lastDependencies).toEqual(['the dependency']);
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -5,7 +5,7 @@ import { Router } from 'react-router';
|
||||
import { CreateServerFactory } from '../../src/servers/CreateServer';
|
||||
import type { ServersMap } from '../../src/servers/data';
|
||||
import { checkAccessibility } from '../__helpers__/accessibility';
|
||||
import { renderWithEvents } from '../__helpers__/setUpTest';
|
||||
import { renderWithStore } from '../__helpers__/setUpTest';
|
||||
|
||||
type SetUpOptions = {
|
||||
serversImported?: boolean;
|
||||
@ -14,9 +14,8 @@ type SetUpOptions = {
|
||||
};
|
||||
|
||||
describe('<CreateServer />', () => {
|
||||
const createServersMock = vi.fn();
|
||||
const defaultServers: ServersMap = {
|
||||
foo: fromPartial({ url: 'https://existing_url.com', apiKey: 'existing_api_key' }),
|
||||
foo: fromPartial({ url: 'https://existing_url.com', apiKey: 'existing_api_key', id: 'foo' }),
|
||||
};
|
||||
const setUp = ({ serversImported = false, importFailed = false, servers = defaultServers }: SetUpOptions = {}) => {
|
||||
let callCount = 0;
|
||||
@ -33,10 +32,13 @@ describe('<CreateServer />', () => {
|
||||
|
||||
return {
|
||||
history,
|
||||
...renderWithEvents(
|
||||
...renderWithStore(
|
||||
<Router location={history.location} navigator={history}>
|
||||
<CreateServer createServers={createServersMock} servers={servers} />
|
||||
<CreateServer />
|
||||
</Router>,
|
||||
{
|
||||
initialState: { servers },
|
||||
},
|
||||
),
|
||||
};
|
||||
};
|
||||
@ -68,21 +70,23 @@ describe('<CreateServer />', () => {
|
||||
});
|
||||
|
||||
it('creates server data when form is submitted', async () => {
|
||||
const { user, history } = setUp();
|
||||
|
||||
expect(createServersMock).not.toHaveBeenCalled();
|
||||
const { user, history, store } = setUp();
|
||||
const expectedServerId = 'the_name-the_url.com';
|
||||
|
||||
await user.type(screen.getByLabelText(/^Name/), 'the_name');
|
||||
await user.type(screen.getByLabelText(/^URL/), 'https://the_url.com');
|
||||
await user.type(screen.getByLabelText(/^API key/), 'the_api_key');
|
||||
fireEvent.submit(screen.getByRole('form'));
|
||||
|
||||
expect(createServersMock).toHaveBeenCalledWith([expect.objectContaining({
|
||||
expect(store.getState().servers[expectedServerId]).not.toBeDefined();
|
||||
fireEvent.submit(screen.getByRole('form'));
|
||||
expect(store.getState().servers[expectedServerId]).toEqual(expect.objectContaining({
|
||||
id: expectedServerId,
|
||||
name: 'the_name',
|
||||
url: 'https://the_url.com',
|
||||
apiKey: 'the_api_key',
|
||||
})]);
|
||||
expect(history.location.pathname).toEqual(expect.stringMatching(/^\/server\//));
|
||||
}));
|
||||
|
||||
expect(history.location.pathname).toEqual(`/server/${expectedServerId}`);
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
@ -92,12 +96,12 @@ describe('<CreateServer />', () => {
|
||||
await user.type(screen.getByLabelText(/^Name/), 'the_name');
|
||||
await user.type(screen.getByLabelText(/^URL/), 'https://existing_url.com');
|
||||
await user.type(screen.getByLabelText(/^API key/), 'existing_api_key');
|
||||
|
||||
fireEvent.submit(screen.getByRole('form'));
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('dialog')).toBeInTheDocument());
|
||||
await user.click(screen.getByRole('button', { name: 'Discard' }));
|
||||
|
||||
expect(createServersMock).not.toHaveBeenCalled();
|
||||
expect(history.location.pathname).toEqual('/foo'); // Goes back to first route from history's initialEntries
|
||||
});
|
||||
});
|
||||
|
||||
@ -3,19 +3,14 @@ import { fromPartial } from '@total-typescript/shoehorn';
|
||||
import { createMemoryHistory } from 'history';
|
||||
import type { ReactNode } from 'react';
|
||||
import { Router } from 'react-router';
|
||||
import { DeleteServerButtonFactory } from '../../src/servers/DeleteServerButton';
|
||||
import type { DeleteServerModalProps } from '../../src/servers/DeleteServerModal';
|
||||
import { DeleteServerModal } from '../../src/servers/DeleteServerModal';
|
||||
import { DeleteServerButton } from '../../src/servers/DeleteServerButton';
|
||||
import { checkAccessibility } from '../__helpers__/accessibility';
|
||||
import { renderWithEvents } from '../__helpers__/setUpTest';
|
||||
import { renderWithStore } from '../__helpers__/setUpTest';
|
||||
|
||||
describe('<DeleteServerButton />', () => {
|
||||
const DeleteServerButton = DeleteServerButtonFactory(fromPartial({
|
||||
DeleteServerModal: (props: DeleteServerModalProps) => <DeleteServerModal {...props} deleteServer={vi.fn()} />,
|
||||
}));
|
||||
const setUp = (children: ReactNode = 'Remove this server') => {
|
||||
const history = createMemoryHistory({ initialEntries: ['/foo'] });
|
||||
const result = renderWithEvents(
|
||||
const result = renderWithStore(
|
||||
<Router location={history.location} navigator={history}>
|
||||
<DeleteServerButton server={fromPartial({})}>{children}</DeleteServerButton>
|
||||
</Router>,
|
||||
|
||||
@ -1,23 +1,23 @@
|
||||
import { screen } from '@testing-library/react';
|
||||
import { fromPartial } from '@total-typescript/shoehorn';
|
||||
import type { ServerWithId } from '../../src/servers/data';
|
||||
import { DeleteServerModal } from '../../src/servers/DeleteServerModal';
|
||||
import { checkAccessibility } from '../__helpers__/accessibility';
|
||||
import { renderWithEvents } from '../__helpers__/setUpTest';
|
||||
import { renderWithStore } from '../__helpers__/setUpTest';
|
||||
import { TestModalWrapper } from '../__helpers__/TestModalWrapper';
|
||||
|
||||
describe('<DeleteServerModal />', () => {
|
||||
const deleteServerMock = vi.fn();
|
||||
const serverName = 'the_server_name';
|
||||
const setUp = () => renderWithEvents(
|
||||
const server = fromPartial<ServerWithId>({ id: 'foo', name: serverName });
|
||||
const setUp = () => renderWithStore(
|
||||
<TestModalWrapper
|
||||
renderModal={(args) => (
|
||||
<DeleteServerModal
|
||||
{...args}
|
||||
server={fromPartial({ name: serverName })}
|
||||
deleteServer={deleteServerMock}
|
||||
/>
|
||||
)}
|
||||
renderModal={(args) => <DeleteServerModal {...args} server={server} />}
|
||||
/>,
|
||||
{
|
||||
initialState: {
|
||||
servers: { foo: server },
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
it('passes a11y checks', () => checkAccessibility(setUp()));
|
||||
@ -40,19 +40,21 @@ describe('<DeleteServerModal />', () => {
|
||||
[() => screen.getByRole('button', { name: 'Cancel' })],
|
||||
[() => screen.getByLabelText('Close dialog')],
|
||||
])('closes dialog when clicking cancel button', async (getButton) => {
|
||||
const { user } = setUp();
|
||||
const { user, store } = setUp();
|
||||
|
||||
expect(screen.getByRole('dialog')).toBeInTheDocument();
|
||||
await user.click(getButton());
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
expect(deleteServerMock).not.toHaveBeenCalled();
|
||||
|
||||
// No server has been deleted
|
||||
expect(Object.keys(store.getState().servers)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('deletes server when clicking accept button', async () => {
|
||||
const { user } = setUp();
|
||||
const { user, store } = setUp();
|
||||
|
||||
expect(deleteServerMock).not.toHaveBeenCalled();
|
||||
expect(Object.keys(store.getState().servers)).toHaveLength(1);
|
||||
await user.click(screen.getByRole('button', { name: 'Delete' }));
|
||||
expect(deleteServerMock).toHaveBeenCalledOnce();
|
||||
expect(Object.keys(store.getState().servers)).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
@ -1,30 +1,37 @@
|
||||
import { fireEvent, screen } from '@testing-library/react';
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react';
|
||||
import { fromPartial } from '@total-typescript/shoehorn';
|
||||
import { createMemoryHistory } from 'history';
|
||||
import { Router } from 'react-router';
|
||||
import { ContainerProvider } from '../../src/container/context';
|
||||
import type { ReachableServer, SelectedServer } from '../../src/servers/data';
|
||||
import { EditServerFactory } from '../../src/servers/EditServer';
|
||||
import { isServerWithId } from '../../src/servers/data';
|
||||
import { EditServer } from '../../src/servers/EditServer';
|
||||
import { checkAccessibility } from '../__helpers__/accessibility';
|
||||
import { renderWithEvents } from '../__helpers__/setUpTest';
|
||||
import { renderWithStore } from '../__helpers__/setUpTest';
|
||||
|
||||
describe('<EditServer />', () => {
|
||||
const ServerError = vi.fn();
|
||||
const editServerMock = vi.fn();
|
||||
const defaultSelectedServer = fromPartial<ReachableServer>({
|
||||
id: 'abc123',
|
||||
name: 'the_name',
|
||||
url: 'the_url',
|
||||
apiKey: 'the_api_key',
|
||||
});
|
||||
const EditServer = EditServerFactory(fromPartial({ ServerError }));
|
||||
const setUp = (selectedServer: SelectedServer = defaultSelectedServer) => {
|
||||
const history = createMemoryHistory({ initialEntries: ['/foo', '/bar'] });
|
||||
return {
|
||||
history,
|
||||
...renderWithEvents(
|
||||
...renderWithStore(
|
||||
<Router location={history.location} navigator={history}>
|
||||
<EditServer editServer={editServerMock} selectedServer={selectedServer} selectServer={vi.fn()} />
|
||||
<ContainerProvider value={fromPartial({ buildShlinkApiClient: vi.fn() })}>
|
||||
<EditServer />
|
||||
</ContainerProvider>
|
||||
</Router>,
|
||||
{
|
||||
initialState: {
|
||||
selectedServer,
|
||||
servers: isServerWithId(selectedServer) ? { [selectedServer.id]: selectedServer } : {},
|
||||
},
|
||||
},
|
||||
),
|
||||
};
|
||||
};
|
||||
@ -53,7 +60,7 @@ describe('<EditServer />', () => {
|
||||
});
|
||||
|
||||
it('edits server and redirects to it when form is submitted', async () => {
|
||||
const { user, history } = setUp();
|
||||
const { user, history, store } = setUp();
|
||||
|
||||
await user.type(screen.getByLabelText(/^Name/), ' edited');
|
||||
await user.type(screen.getByLabelText(/^URL/), ' edited');
|
||||
@ -61,12 +68,10 @@ describe('<EditServer />', () => {
|
||||
// await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
fireEvent.submit(screen.getByRole('form'));
|
||||
|
||||
expect(editServerMock).toHaveBeenCalledWith('abc123', {
|
||||
expect(store.getState().servers[defaultSelectedServer.id]).toEqual(expect.objectContaining({
|
||||
name: 'the_name edited',
|
||||
url: 'the_url edited',
|
||||
apiKey: 'the_api_key',
|
||||
forwardCredentials: false,
|
||||
});
|
||||
}));
|
||||
|
||||
// After saving we go back, to the first route from history's initialEntries
|
||||
expect(history.location.pathname).toEqual('/foo');
|
||||
@ -75,16 +80,15 @@ describe('<EditServer />', () => {
|
||||
it.each([
|
||||
{ forwardCredentials: true },
|
||||
{ forwardCredentials: false },
|
||||
])('edits advanced options - forward credentials', async (serverPartial) => {
|
||||
const { user } = setUp({ ...defaultSelectedServer, ...serverPartial });
|
||||
])('edits advanced options - forward credentials', async ({ forwardCredentials }) => {
|
||||
const { user, store } = setUp({ ...defaultSelectedServer, forwardCredentials });
|
||||
|
||||
await user.click(screen.getByText('Advanced options'));
|
||||
await user.click(screen.getByLabelText('Forward credentials to this server on every request.'));
|
||||
|
||||
fireEvent.submit(screen.getByRole('form'));
|
||||
|
||||
expect(editServerMock).toHaveBeenCalledWith('abc123', expect.objectContaining({
|
||||
forwardCredentials: !serverPartial.forwardCredentials,
|
||||
}));
|
||||
await waitFor(() => expect(store.getState().servers[defaultSelectedServer.id]).toEqual(expect.objectContaining({
|
||||
forwardCredentials: !forwardCredentials,
|
||||
})));
|
||||
});
|
||||
});
|
||||
|
||||
@ -5,7 +5,7 @@ import type { ServersMap, ServerWithId } from '../../src/servers/data';
|
||||
import { ManageServersFactory } from '../../src/servers/ManageServers';
|
||||
import type { ServersExporter } from '../../src/servers/services/ServersExporter';
|
||||
import { checkAccessibility } from '../__helpers__/accessibility';
|
||||
import { renderWithEvents } from '../__helpers__/setUpTest';
|
||||
import { renderWithStore } from '../__helpers__/setUpTest';
|
||||
|
||||
describe('<ManageServers />', () => {
|
||||
const exportServers = vi.fn();
|
||||
@ -15,15 +15,15 @@ describe('<ManageServers />', () => {
|
||||
ServersExporter: serversExporter,
|
||||
ImportServersBtn: () => <span>ImportServersBtn</span>,
|
||||
useTimeoutToggle,
|
||||
ManageServersRow: ({ hasAutoConnect }: { hasAutoConnect: boolean }) => (
|
||||
<tr><td>ManageServersRow {hasAutoConnect ? '[YES]' : '[NO]'}</td></tr>
|
||||
),
|
||||
}));
|
||||
const createServerMock = (value: string, autoConnect = false) => fromPartial<ServerWithId>(
|
||||
{ id: value, name: value, url: value, autoConnect },
|
||||
);
|
||||
const setUp = (servers: ServersMap = {}) => renderWithEvents(
|
||||
<MemoryRouter><ManageServers servers={servers} /></MemoryRouter>,
|
||||
const setUp = (servers: ServersMap = {}) => renderWithStore(
|
||||
<MemoryRouter><ManageServers /></MemoryRouter>,
|
||||
{
|
||||
initialState: { servers },
|
||||
},
|
||||
);
|
||||
|
||||
it('passes a11y checks', () => checkAccessibility(setUp({
|
||||
@ -42,20 +42,22 @@ describe('<ManageServers />', () => {
|
||||
await user.clear(screen.getByPlaceholderText('Search...'));
|
||||
await user.type(screen.getByPlaceholderText('Search...'), searchTerm);
|
||||
};
|
||||
// Add one for the header row
|
||||
const expectRows = (amount: number) => expect(screen.getAllByRole('row')).toHaveLength(amount + 1);
|
||||
|
||||
expect(screen.getAllByText(/^ManageServersRow/)).toHaveLength(3);
|
||||
expectRows(3);
|
||||
expect(screen.queryByText('No servers found.')).not.toBeInTheDocument();
|
||||
|
||||
await search('foo');
|
||||
await waitFor(() => expect(screen.getAllByText(/^ManageServersRow/)).toHaveLength(1));
|
||||
await waitFor(() => expectRows(1));
|
||||
expect(screen.queryByText('No servers found.')).not.toBeInTheDocument();
|
||||
|
||||
await search('Ba');
|
||||
await waitFor(() => expect(screen.getAllByText(/^ManageServersRow/)).toHaveLength(2));
|
||||
await waitFor(() => expectRows(2));
|
||||
expect(screen.queryByText('No servers found.')).not.toBeInTheDocument();
|
||||
|
||||
await search('invalid');
|
||||
await waitFor(() => expect(screen.queryByText(/^ManageServersRow/)).not.toBeInTheDocument());
|
||||
await waitFor(() => expectRows(1));
|
||||
expect(screen.getByText('No servers found.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@ -67,11 +69,9 @@ describe('<ManageServers />', () => {
|
||||
|
||||
expect(screen.getAllByRole('columnheader')).toHaveLength(expectedCols);
|
||||
if (server.autoConnect) {
|
||||
expect(screen.getByText(/\[YES]/)).toBeInTheDocument();
|
||||
expect(screen.queryByText(/\[NO]/)).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId('auto-connect')).toBeInTheDocument();
|
||||
} else {
|
||||
expect(screen.queryByText(/\[YES]/)).not.toBeInTheDocument();
|
||||
expect(screen.getByText(/\[NO]/)).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('auto-connect')).not.toBeInTheDocument();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@ -1,22 +1,19 @@
|
||||
import { Table } from '@shlinkio/shlink-frontend-kit';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { fromPartial } from '@total-typescript/shoehorn';
|
||||
import { screen } from '@testing-library/react';
|
||||
import { MemoryRouter } from 'react-router';
|
||||
import type { ServerWithId } from '../../src/servers/data';
|
||||
import { ManageServersRowFactory } from '../../src/servers/ManageServersRow';
|
||||
import { ManageServersRow } from '../../src/servers/ManageServersRow';
|
||||
import { checkAccessibility } from '../__helpers__/accessibility';
|
||||
import { renderWithStore } from '../__helpers__/setUpTest';
|
||||
|
||||
describe('<ManageServersRow />', () => {
|
||||
const ManageServersRow = ManageServersRowFactory(fromPartial({
|
||||
ManageServersRowDropdown: () => <span>ManageServersRowDropdown</span>,
|
||||
}));
|
||||
const server: ServerWithId = {
|
||||
name: 'My server',
|
||||
url: 'https://example.com',
|
||||
apiKey: '123',
|
||||
id: 'abc',
|
||||
};
|
||||
const setUp = (hasAutoConnect = false, autoConnect = false) => render(
|
||||
const setUp = (hasAutoConnect = false, autoConnect = false) => renderWithStore(
|
||||
<MemoryRouter>
|
||||
<Table header={<Table.Row />}>
|
||||
<ManageServersRow server={{ ...server, autoConnect }} hasAutoConnect={hasAutoConnect} />
|
||||
@ -34,9 +31,9 @@ describe('<ManageServersRow />', () => {
|
||||
expect(screen.getAllByRole('cell')).toHaveLength(expectedCols);
|
||||
});
|
||||
|
||||
it('renders a dropdown', () => {
|
||||
it('renders an options dropdown', () => {
|
||||
setUp();
|
||||
expect(screen.getByText('ManageServersRowDropdown')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Options' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each([
|
||||
|
||||
@ -3,23 +3,22 @@ import type { UserEvent } from '@testing-library/user-event';
|
||||
import { fromPartial } from '@total-typescript/shoehorn';
|
||||
import { MemoryRouter } from 'react-router';
|
||||
import type { ServerWithId } from '../../src/servers/data';
|
||||
import { ManageServersRowDropdownFactory } from '../../src/servers/ManageServersRowDropdown';
|
||||
import { ManageServersRowDropdown } from '../../src/servers/ManageServersRowDropdown';
|
||||
import { checkAccessibility } from '../__helpers__/accessibility';
|
||||
import { renderWithEvents } from '../__helpers__/setUpTest';
|
||||
import { renderWithStore } from '../__helpers__/setUpTest';
|
||||
|
||||
describe('<ManageServersRowDropdown />', () => {
|
||||
const ManageServersRowDropdown = ManageServersRowDropdownFactory(fromPartial({
|
||||
DeleteServerModal: ({ open }: { open: boolean }) => (
|
||||
<span>DeleteServerModal {open ? '[OPEN]' : '[CLOSED]'}</span>
|
||||
),
|
||||
}));
|
||||
const setAutoConnect = vi.fn();
|
||||
const setUp = (autoConnect = false) => {
|
||||
const server = fromPartial<ServerWithId>({ id: 'abc123', autoConnect });
|
||||
return renderWithEvents(
|
||||
return renderWithStore(
|
||||
<MemoryRouter>
|
||||
<ManageServersRowDropdown setAutoConnect={setAutoConnect} server={server} />
|
||||
<ManageServersRowDropdown server={server} />
|
||||
</MemoryRouter>,
|
||||
{
|
||||
initialState: {
|
||||
servers: { [server.id]: server },
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
const toggleDropdown = (user: UserEvent) => user.click(screen.getByRole('button'));
|
||||
@ -44,26 +43,24 @@ describe('<ManageServersRowDropdown />', () => {
|
||||
expect(screen.getByRole('menuitem', { name: 'Edit server' })).toHaveAttribute('href', '/server/abc123/edit');
|
||||
});
|
||||
|
||||
it('allows toggling auto-connect', async () => {
|
||||
const { user } = setUp();
|
||||
it.each([true, false])('allows toggling auto-connect', async (autoConnect) => {
|
||||
const { user, store } = setUp(autoConnect);
|
||||
|
||||
expect(setAutoConnect).not.toHaveBeenCalled();
|
||||
await toggleDropdown(user);
|
||||
await user.click(screen.getByRole('menuitem', { name: 'Auto-connect' }));
|
||||
expect(setAutoConnect).toHaveBeenCalledWith(expect.objectContaining({ id: 'abc123' }), true);
|
||||
await user.click(screen.getByRole('menuitem', { name: autoConnect ? 'Do not auto-connect' : 'Auto-connect' }));
|
||||
|
||||
expect(Object.values(store.getState().servers)[0].autoConnect).toEqual(!autoConnect);
|
||||
});
|
||||
|
||||
it('renders deletion modal', async () => {
|
||||
const { user } = setUp();
|
||||
|
||||
expect(screen.queryByText('DeleteServerModal [OPEN]')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('DeleteServerModal [CLOSED]')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
|
||||
await toggleDropdown(user);
|
||||
await user.click(screen.getByRole('menuitem', { name: 'Remove server' }));
|
||||
|
||||
expect(screen.getByText('DeleteServerModal [OPEN]')).toBeInTheDocument();
|
||||
expect(screen.queryByText('DeleteServerModal [CLOSED]')).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('dialog')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each([[true], [false]])('renders expected size and icon', (autoConnect) => {
|
||||
|
||||
@ -1,10 +1,11 @@
|
||||
import { screen } from '@testing-library/react';
|
||||
import { fromPartial } from '@total-typescript/shoehorn';
|
||||
import { MemoryRouter } from 'react-router';
|
||||
import { ContainerProvider } from '../../src/container/context';
|
||||
import type { ServersMap } from '../../src/servers/data';
|
||||
import { ServersDropdown } from '../../src/servers/ServersDropdown';
|
||||
import { checkAccessibility } from '../__helpers__/accessibility';
|
||||
import { renderWithEvents } from '../__helpers__/setUpTest';
|
||||
import { renderWithStore } from '../__helpers__/setUpTest';
|
||||
|
||||
describe('<ServersDropdown />', () => {
|
||||
const fallbackServers: ServersMap = {
|
||||
@ -12,12 +13,17 @@ describe('<ServersDropdown />', () => {
|
||||
'2b': fromPartial({ name: 'bar', id: '2b' }),
|
||||
'3c': fromPartial({ name: 'baz', id: '3c' }),
|
||||
};
|
||||
const setUp = (servers: ServersMap = fallbackServers) => renderWithEvents(
|
||||
const setUp = (servers: ServersMap = fallbackServers) => renderWithStore(
|
||||
<MemoryRouter>
|
||||
<ul role="menu">
|
||||
<ServersDropdown servers={servers} selectedServer={null} />
|
||||
</ul>
|
||||
<ContainerProvider value={fromPartial({ buildShlinkApiClient: vi.fn() })}>
|
||||
<ul role="menu">
|
||||
<ServersDropdown />
|
||||
</ul>
|
||||
</ContainerProvider>
|
||||
</MemoryRouter>,
|
||||
{
|
||||
initialState: { selectedServer: null, servers },
|
||||
},
|
||||
);
|
||||
|
||||
it('passes a11y checks', async () => {
|
||||
|
||||
@ -27,6 +27,7 @@ exports[`<ManageServersRow /> > renders auto-connect icon only if server is auto
|
||||
class="svg-inline--fa fa-check text-lm-brand dark:text-dm-brand"
|
||||
data-icon="check"
|
||||
data-prefix="fas"
|
||||
data-testid="auto-connect"
|
||||
role="img"
|
||||
viewBox="0 0 448 512"
|
||||
>
|
||||
@ -56,9 +57,32 @@ exports[`<ManageServersRow /> > renders auto-connect icon only if server is auto
|
||||
<td
|
||||
class="border-lm-border dark:border-dm-border p-2 block lg:table-cell not-last:border-b-1 lg:border-b-1 before:lg:hidden before:content-[attr(data-column)] before:font-bold before:mr-1 text-right max-lg:absolute right-0 -top-1 mx-lg:pt-0"
|
||||
>
|
||||
<span>
|
||||
ManageServersRowDropdown
|
||||
</span>
|
||||
<div
|
||||
class="relative inline-block"
|
||||
>
|
||||
<button
|
||||
aria-controls="_r_o_"
|
||||
aria-expanded="false"
|
||||
aria-haspopup="true"
|
||||
aria-label="Options"
|
||||
class="flex items-center rounded-md focus-ring cursor-pointer border border-lm-border dark:border-dm-border bg-lm-primary dark:bg-dm-primary group-[&]/card:bg-lm-input group-[&]/card:dark:bg-dm-input px-3 py-1.5 gap-x-2"
|
||||
type="button"
|
||||
>
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
class="svg-inline--fa fa-ellipsis-vertical fa-width-auto"
|
||||
data-icon="ellipsis-vertical"
|
||||
data-prefix="fas"
|
||||
role="img"
|
||||
viewBox="0 0 128 512"
|
||||
>
|
||||
<path
|
||||
d="M64 144a56 56 0 1 1 0-112 56 56 0 1 1 0 112zm0 224c30.9 0 56 25.1 56 56s-25.1 56-56 56-56-25.1-56-56 25.1-56 56-56zm56-112c0 30.9-25.1 56-56 56s-56-25.1-56-56 25.1-56 56-56 56 25.1 56 56z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
@ -108,9 +132,32 @@ exports[`<ManageServersRow /> > renders auto-connect icon only if server is auto
|
||||
<td
|
||||
class="border-lm-border dark:border-dm-border p-2 block lg:table-cell not-last:border-b-1 lg:border-b-1 before:lg:hidden before:content-[attr(data-column)] before:font-bold before:mr-1 text-right max-lg:absolute right-0 -top-1 mx-lg:pt-0"
|
||||
>
|
||||
<span>
|
||||
ManageServersRowDropdown
|
||||
</span>
|
||||
<div
|
||||
class="relative inline-block"
|
||||
>
|
||||
<button
|
||||
aria-controls="_r_t_"
|
||||
aria-expanded="false"
|
||||
aria-haspopup="true"
|
||||
aria-label="Options"
|
||||
class="flex items-center rounded-md focus-ring cursor-pointer border border-lm-border dark:border-dm-border bg-lm-primary dark:bg-dm-primary group-[&]/card:bg-lm-input group-[&]/card:dark:bg-dm-input px-3 py-1.5 gap-x-2"
|
||||
type="button"
|
||||
>
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
class="svg-inline--fa fa-ellipsis-vertical fa-width-auto"
|
||||
data-icon="ellipsis-vertical"
|
||||
data-prefix="fas"
|
||||
role="img"
|
||||
viewBox="0 0 128 512"
|
||||
>
|
||||
<path
|
||||
d="M64 144a56 56 0 1 1 0-112 56 56 0 1 1 0 112zm0 224c30.9 0 56 25.1 56 56s-25.1 56-56 56-56-25.1-56-56 25.1-56 56-56zm56-112c0 30.9-25.1 56-56 56s-56-25.1-56-56 25.1-56 56-56 56 25.1 56 56z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
|
||||
@ -6,7 +6,7 @@ exports[`<ManageServersRowDropdown /> > renders expected size and icon 1`] = `
|
||||
class="relative inline-block"
|
||||
>
|
||||
<button
|
||||
aria-controls="_r_1h_"
|
||||
aria-controls="_r_1v_"
|
||||
aria-expanded="false"
|
||||
aria-haspopup="true"
|
||||
aria-label="Options"
|
||||
@ -28,10 +28,6 @@ exports[`<ManageServersRowDropdown /> > renders expected size and icon 1`] = `
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<span>
|
||||
DeleteServerModal
|
||||
[CLOSED]
|
||||
</span>
|
||||
</div>
|
||||
`;
|
||||
|
||||
@ -41,7 +37,7 @@ exports[`<ManageServersRowDropdown /> > renders expected size and icon 2`] = `
|
||||
class="relative inline-block"
|
||||
>
|
||||
<button
|
||||
aria-controls="_r_1l_"
|
||||
aria-controls="_r_23_"
|
||||
aria-expanded="false"
|
||||
aria-haspopup="true"
|
||||
aria-label="Options"
|
||||
@ -63,9 +59,5 @@ exports[`<ManageServersRowDropdown /> > renders expected size and icon 2`] = `
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<span>
|
||||
DeleteServerModal
|
||||
[CLOSED]
|
||||
</span>
|
||||
</div>
|
||||
`;
|
||||
|
||||
@ -6,22 +6,19 @@ import type {
|
||||
import { ImportServersBtnFactory } from '../../../src/servers/helpers/ImportServersBtn';
|
||||
import type { ServersImporter } from '../../../src/servers/services/ServersImporter';
|
||||
import { checkAccessibility } from '../../__helpers__/accessibility';
|
||||
import { renderWithEvents } from '../../__helpers__/setUpTest';
|
||||
import { renderWithStore } from '../../__helpers__/setUpTest';
|
||||
|
||||
describe('<ImportServersBtn />', () => {
|
||||
const csvFile = new File([''], 'servers.csv', { type: 'text/csv' });
|
||||
const onImportMock = vi.fn();
|
||||
const createServersMock = vi.fn();
|
||||
const importServersFromFile = vi.fn().mockResolvedValue([]);
|
||||
const serversImporterMock = fromPartial<ServersImporter>({ importServersFromFile });
|
||||
const ImportServersBtn = ImportServersBtnFactory(fromPartial({ ServersImporter: serversImporterMock }));
|
||||
const setUp = (props: Partial<ImportServersBtnProps> = {}, servers: ServersMap = {}) => renderWithEvents(
|
||||
<ImportServersBtn
|
||||
servers={servers}
|
||||
{...props}
|
||||
createServers={createServersMock}
|
||||
onImport={onImportMock}
|
||||
/>,
|
||||
const setUp = (props: Partial<ImportServersBtnProps> = {}, servers: ServersMap = {}) => renderWithStore(
|
||||
<ImportServersBtn {...props} onImport={onImportMock} />,
|
||||
{
|
||||
initialState: { servers },
|
||||
},
|
||||
);
|
||||
|
||||
it('passes a11y checks', () => checkAccessibility(setUp()));
|
||||
@ -57,11 +54,8 @@ describe('<ImportServersBtn />', () => {
|
||||
it('imports servers when file input changes', async () => {
|
||||
const { user } = setUp();
|
||||
|
||||
const input = screen.getByTestId('csv-file-input');
|
||||
await user.upload(input, csvFile);
|
||||
|
||||
await user.upload(screen.getByTestId('csv-file-input'), csvFile);
|
||||
expect(importServersFromFile).toHaveBeenCalledTimes(1);
|
||||
expect(createServersMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
@ -78,26 +72,27 @@ describe('<ImportServersBtn />', () => {
|
||||
id: 'existingserver-s.test',
|
||||
};
|
||||
const newServer: ServerData = { name: 'newServer', url: 'http://s.test/newUrl', apiKey: 'newApiKey' };
|
||||
const { user } = setUp({}, { [existingServer.id]: existingServer });
|
||||
const { user, store } = setUp({}, { [existingServer.id]: existingServer });
|
||||
|
||||
importServersFromFile.mockResolvedValue([existingServer, newServer]);
|
||||
importServersFromFile.mockResolvedValue([existingServerData, newServer]);
|
||||
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
await user.upload(screen.getByTestId('csv-file-input'), csvFile);
|
||||
|
||||
// Once the file is uploaded, non-duplicated servers are immediately created
|
||||
expect(createServersMock).toHaveBeenCalledExactlyOnceWith([expect.objectContaining(newServer)]);
|
||||
const { servers } = store.getState();
|
||||
expect(Object.keys(servers)).toHaveLength(2);
|
||||
|
||||
expect(screen.getByRole('dialog')).toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: btnName }));
|
||||
|
||||
// If duplicated servers are saved, there's one extra call
|
||||
// If duplicated servers are saved, there's one extra server creation
|
||||
if (savesDuplicatedServers) {
|
||||
expect(createServersMock).toHaveBeenLastCalledWith([expect.objectContaining(existingServerData)]);
|
||||
const { servers } = store.getState();
|
||||
expect(Object.keys(servers)).toHaveLength(3);
|
||||
}
|
||||
|
||||
// On import is called only once, no matter what
|
||||
expect(onImportMock).toHaveBeenCalledOnce();
|
||||
expect(createServersMock).toHaveBeenCalledTimes(savesDuplicatedServers ? 2 : 1);
|
||||
});
|
||||
});
|
||||
|
||||
@ -1,16 +1,22 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { screen } from '@testing-library/react';
|
||||
import { fromPartial } from '@total-typescript/shoehorn';
|
||||
import { MemoryRouter } from 'react-router';
|
||||
import { ContainerProvider } from '../../../src/container/context';
|
||||
import type { NonReachableServer, NotFoundServer, SelectedServer } from '../../../src/servers/data';
|
||||
import { ServerErrorFactory } from '../../../src/servers/helpers/ServerError';
|
||||
import { ServerError } from '../../../src/servers/helpers/ServerError';
|
||||
import { checkAccessibility } from '../../__helpers__/accessibility';
|
||||
import { renderWithStore } from '../../__helpers__/setUpTest';
|
||||
|
||||
describe('<ServerError />', () => {
|
||||
const ServerError = ServerErrorFactory(fromPartial({ DeleteServerButton: () => null }));
|
||||
const setUp = (selectedServer: SelectedServer) => render(
|
||||
const setUp = (selectedServer: SelectedServer) => renderWithStore(
|
||||
<MemoryRouter>
|
||||
<ServerError servers={{}} selectedServer={selectedServer} />
|
||||
<ContainerProvider value={fromPartial({ buildShlinkApiClient: vi.fn() })}>
|
||||
<ServerError />
|
||||
</ContainerProvider>
|
||||
</MemoryRouter>,
|
||||
{
|
||||
initialState: { selectedServer, servers: {} },
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
|
||||
@ -79,9 +79,8 @@ describe('remoteServersReducer', () => {
|
||||
},
|
||||
])('tries to fetch servers from remote', async ({ serversArray, expectedNewServers }) => {
|
||||
jsonRequest.mockResolvedValue(serversArray);
|
||||
const doFetchServers = fetchServers(httpClient);
|
||||
|
||||
await doFetchServers()(dispatch, vi.fn(), {});
|
||||
await fetchServers(httpClient)(dispatch, vi.fn(), {});
|
||||
|
||||
expect(dispatch).toHaveBeenCalledTimes(3);
|
||||
expect(dispatch).toHaveBeenNthCalledWith(2, expect.objectContaining({ payload: expectedNewServers }));
|
||||
|
||||
@ -1,21 +1,19 @@
|
||||
import type { ShlinkApiClient } from '@shlinkio/shlink-js-sdk';
|
||||
import { fromPartial } from '@total-typescript/shoehorn';
|
||||
import type { ShlinkState } from '../../../src/container/types';
|
||||
import type { NonReachableServer, NotFoundServer, RegularServer } from '../../../src/servers/data';
|
||||
import {
|
||||
MAX_FALLBACK_VERSION,
|
||||
MIN_FALLBACK_VERSION,
|
||||
resetSelectedServer,
|
||||
selectedServerReducerCreator,
|
||||
selectServer as selectServerCreator,
|
||||
selectedServerReducer as reducer,
|
||||
selectServer,
|
||||
} from '../../../src/servers/reducers/selectedServer';
|
||||
import type { RootState } from '../../../src/store';
|
||||
|
||||
describe('selectedServerReducer', () => {
|
||||
const dispatch = vi.fn();
|
||||
const health = vi.fn();
|
||||
const buildApiClient = vi.fn().mockReturnValue(fromPartial<ShlinkApiClient>({ health }));
|
||||
const selectServer = selectServerCreator(buildApiClient);
|
||||
const { reducer } = selectedServerReducerCreator(selectServer);
|
||||
const buildShlinkApiClient = vi.fn().mockReturnValue(fromPartial<ShlinkApiClient>({ health }));
|
||||
|
||||
describe('reducer', () => {
|
||||
it('returns default when action is RESET_SELECTED_SERVER', () =>
|
||||
@ -23,7 +21,7 @@ describe('selectedServerReducer', () => {
|
||||
|
||||
it('returns selected server when action is SELECT_SERVER', () => {
|
||||
const payload = fromPartial<RegularServer>({ id: 'abc123' });
|
||||
expect(reducer(null, selectServer.fulfilled(payload, '', ''))).toEqual(payload);
|
||||
expect(reducer(null, selectServer.fulfilled(payload, '', { serverId: '', buildShlinkApiClient }))).toEqual(payload);
|
||||
});
|
||||
});
|
||||
|
||||
@ -50,10 +48,10 @@ describe('selectedServerReducer', () => {
|
||||
|
||||
health.mockResolvedValue({ version: serverVersion });
|
||||
|
||||
await selectServer(id)(dispatch, getState, {});
|
||||
await selectServer({ serverId: id, buildShlinkApiClient })(dispatch, getState, {});
|
||||
|
||||
expect(getState).toHaveBeenCalledTimes(1);
|
||||
expect(buildApiClient).toHaveBeenCalledTimes(1);
|
||||
expect(buildShlinkApiClient).toHaveBeenCalledTimes(1);
|
||||
expect(dispatch).toHaveBeenCalledTimes(3); // "Pending", "reset" and "fulfilled"
|
||||
expect(dispatch).toHaveBeenLastCalledWith(expect.objectContaining({ payload: expectedSelectedServer }));
|
||||
});
|
||||
@ -65,7 +63,7 @@ describe('selectedServerReducer', () => {
|
||||
|
||||
health.mockRejectedValue({});
|
||||
|
||||
await selectServer(id)(dispatch, getState, {});
|
||||
await selectServer({ serverId: id, buildShlinkApiClient })(dispatch, getState, {});
|
||||
|
||||
expect(health).toHaveBeenCalled();
|
||||
expect(dispatch).toHaveBeenLastCalledWith(expect.objectContaining({ payload: expectedSelectedServer }));
|
||||
@ -73,10 +71,10 @@ describe('selectedServerReducer', () => {
|
||||
|
||||
it('dispatches error when server is not found', async () => {
|
||||
const id = crypto.randomUUID();
|
||||
const getState = vi.fn(() => fromPartial<ShlinkState>({ servers: {} }));
|
||||
const getState = vi.fn(() => fromPartial<RootState>({ servers: {} }));
|
||||
const expectedSelectedServer: NotFoundServer = { serverNotFound: true };
|
||||
|
||||
await selectServer(id)(dispatch, getState, {});
|
||||
await selectServer({ serverId: id, buildShlinkApiClient })(dispatch, getState, {});
|
||||
|
||||
expect(getState).toHaveBeenCalled();
|
||||
expect(health).not.toHaveBeenCalled();
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
import { render } from '@testing-library/react';
|
||||
import { MemoryRouter } from 'react-router';
|
||||
import { Settings } from '../../src/settings/Settings';
|
||||
import { checkAccessibility } from '../__helpers__/accessibility';
|
||||
import { renderWithStore } from '../__helpers__/setUpTest';
|
||||
|
||||
describe('<Settings />', () => {
|
||||
const setUp = () => render(
|
||||
const setUp = () => renderWithStore(
|
||||
<MemoryRouter>
|
||||
<Settings settings={{}} setSettings={vi.fn()} />
|
||||
<Settings />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import { fromPartial } from '@total-typescript/shoehorn';
|
||||
import type { ShlinkState } from '../../../src/container/types';
|
||||
import { migrateDeprecatedSettings } from '../../../src/settings/helpers';
|
||||
import type { RootState } from '../../../src/store';
|
||||
|
||||
describe('settings-helpers', () => {
|
||||
describe('migrateDeprecatedSettings', () => {
|
||||
@ -9,7 +9,7 @@ describe('settings-helpers', () => {
|
||||
});
|
||||
|
||||
it('updates settings as expected', () => {
|
||||
const state = fromPartial<ShlinkState>({
|
||||
const state = fromPartial<RootState>({
|
||||
settings: {
|
||||
visits: {
|
||||
defaultInterval: 'last180days' as any,
|
||||
|
||||
@ -65,7 +65,7 @@ export default defineConfig({
|
||||
thresholds: {
|
||||
statements: 95,
|
||||
branches: 89, // FIXME Increase to 95 again. It dropped after updating to vitest 4
|
||||
functions: 95,
|
||||
functions: 93,
|
||||
lines: 95,
|
||||
},
|
||||
},
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user