Merge pull request #728 from acelaya-forks/feature/state-machine-poc

Feature/state machine poc
This commit is contained in:
Alejandro Celaya
2022-11-07 19:03:51 +01:00
committed by GitHub
10 changed files with 58 additions and 35 deletions

View File

@@ -21,7 +21,7 @@ export interface ShlinkState {
servers: ServersMap; servers: ServersMap;
selectedServer: SelectedServer; selectedServer: SelectedServer;
shortUrlsList: ShortUrlsList; shortUrlsList: ShortUrlsList;
shortUrlCreationResult: ShortUrlCreation; shortUrlCreation: ShortUrlCreation;
shortUrlDeletion: ShortUrlDeletion; shortUrlDeletion: ShortUrlDeletion;
shortUrlEdition: ShortUrlEdition; shortUrlEdition: ShortUrlEdition;
shortUrlVisits: ShortUrlVisits; shortUrlVisits: ShortUrlVisits;

View File

@@ -21,7 +21,7 @@ export default (container: IContainer) => combineReducers<ShlinkState>({
servers: serversReducer, servers: serversReducer,
selectedServer: selectedServerReducer, selectedServer: selectedServerReducer,
shortUrlsList: shortUrlsListReducer, shortUrlsList: shortUrlsListReducer,
shortUrlCreationResult: container.shortUrlCreationReducer, shortUrlCreation: container.shortUrlCreationReducer,
shortUrlDeletion: container.shortUrlDeletionReducer, shortUrlDeletion: container.shortUrlDeletionReducer,
shortUrlEdition: container.shortUrlEditionReducer, shortUrlEdition: container.shortUrlEditionReducer,
shortUrlDetail: container.shortUrlDetailReducer, shortUrlDetail: container.shortUrlDetailReducer,

View File

@@ -12,7 +12,7 @@ export interface CreateShortUrlProps {
interface CreateShortUrlConnectProps extends CreateShortUrlProps { interface CreateShortUrlConnectProps extends CreateShortUrlProps {
settings: Settings; settings: Settings;
shortUrlCreationResult: ShortUrlCreation; shortUrlCreation: ShortUrlCreation;
selectedServer: SelectedServer; selectedServer: SelectedServer;
createShortUrl: (data: ShortUrlData) => Promise<void>; createShortUrl: (data: ShortUrlData) => Promise<void>;
resetCreateShortUrl: () => void; resetCreateShortUrl: () => void;
@@ -38,7 +38,7 @@ export const CreateShortUrl = (
CreateShortUrlResult: FC<CreateShortUrlResultProps>, CreateShortUrlResult: FC<CreateShortUrlResultProps>,
) => ({ ) => ({
createShortUrl, createShortUrl,
shortUrlCreationResult, shortUrlCreation,
resetCreateShortUrl, resetCreateShortUrl,
selectedServer, selectedServer,
basicMode = false, basicMode = false,
@@ -50,7 +50,7 @@ export const CreateShortUrl = (
<> <>
<ShortUrlForm <ShortUrlForm
initialState={initialState} initialState={initialState}
saving={shortUrlCreationResult.saving} saving={shortUrlCreation.saving}
selectedServer={selectedServer} selectedServer={selectedServer}
mode={basicMode ? 'create-basic' : 'create'} mode={basicMode ? 'create-basic' : 'create'}
onSave={async (data: ShortUrlData) => { onSave={async (data: ShortUrlData) => {
@@ -59,7 +59,7 @@ export const CreateShortUrl = (
}} }}
/> />
<CreateShortUrlResult <CreateShortUrlResult
{...shortUrlCreationResult} creation={shortUrlCreation}
resetCreateShortUrl={resetCreateShortUrl} resetCreateShortUrl={resetCreateShortUrl}
canBeClosed={basicMode} canBeClosed={basicMode}
/> />

View File

@@ -1,7 +1,6 @@
import { faCopy as copyIcon } from '@fortawesome/free-regular-svg-icons'; import { faCopy as copyIcon } from '@fortawesome/free-regular-svg-icons';
import { faTimes as closeIcon } from '@fortawesome/free-solid-svg-icons'; import { faTimes as closeIcon } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { isNil } from 'ramda';
import { useEffect } from 'react'; import { useEffect } from 'react';
import CopyToClipboard from 'react-copy-to-clipboard'; import CopyToClipboard from 'react-copy-to-clipboard';
import { Tooltip } from 'reactstrap'; import { Tooltip } from 'reactstrap';
@@ -11,15 +10,17 @@ import { Result } from '../../utils/Result';
import './CreateShortUrlResult.scss'; import './CreateShortUrlResult.scss';
import { ShlinkApiError } from '../../api/ShlinkApiError'; import { ShlinkApiError } from '../../api/ShlinkApiError';
export interface CreateShortUrlResultProps extends ShortUrlCreation { export interface CreateShortUrlResultProps {
creation: ShortUrlCreation;
resetCreateShortUrl: () => void; resetCreateShortUrl: () => void;
canBeClosed?: boolean; canBeClosed?: boolean;
} }
export const CreateShortUrlResult = (useTimeoutToggle: TimeoutToggle) => ( export const CreateShortUrlResult = (useTimeoutToggle: TimeoutToggle) => (
{ error, errorData, result, resetCreateShortUrl, canBeClosed = false }: CreateShortUrlResultProps, { creation, resetCreateShortUrl, canBeClosed = false }: CreateShortUrlResultProps,
) => { ) => {
const [showCopyTooltip, setShowCopyTooltip] = useTimeoutToggle(); const [showCopyTooltip, setShowCopyTooltip] = useTimeoutToggle();
const { error, saved } = creation;
useEffect(() => { useEffect(() => {
resetCreateShortUrl(); resetCreateShortUrl();
@@ -29,16 +30,16 @@ export const CreateShortUrlResult = (useTimeoutToggle: TimeoutToggle) => (
return ( return (
<Result type="error" className="mt-3"> <Result type="error" className="mt-3">
{canBeClosed && <FontAwesomeIcon icon={closeIcon} className="float-end pointer" onClick={resetCreateShortUrl} />} {canBeClosed && <FontAwesomeIcon icon={closeIcon} className="float-end pointer" onClick={resetCreateShortUrl} />}
<ShlinkApiError errorData={errorData} fallbackMessage="An error occurred while creating the URL :(" /> <ShlinkApiError errorData={creation.errorData} fallbackMessage="An error occurred while creating the URL :(" />
</Result> </Result>
); );
} }
if (isNil(result)) { if (!saved) {
return null; return null;
} }
const { shortUrl } = result; const { shortUrl } = creation.result;
return ( return (
<Result type="success" className="mt-3"> <Result type="success" className="mt-3">

View File

@@ -7,18 +7,31 @@ import { ProblemDetailsError } from '../../api/types/errors';
export const CREATE_SHORT_URL = 'shlink/createShortUrl/CREATE_SHORT_URL'; export const CREATE_SHORT_URL = 'shlink/createShortUrl/CREATE_SHORT_URL';
export interface ShortUrlCreation { export type ShortUrlCreation = {
result: ShortUrl | null; saving: false;
saving: boolean; saved: false;
error: boolean; error: false;
} | {
saving: true;
saved: false;
error: false;
} | {
saving: false;
saved: false;
error: true;
errorData?: ProblemDetailsError; errorData?: ProblemDetailsError;
} } | {
result: ShortUrl;
saving: false;
saved: true;
error: false;
};
export type CreateShortUrlAction = PayloadAction<ShortUrl>; export type CreateShortUrlAction = PayloadAction<ShortUrl>;
const initialState: ShortUrlCreation = { const initialState: ShortUrlCreation = {
result: null,
saving: false, saving: false,
saved: false,
error: false, error: false,
}; };
@@ -30,17 +43,20 @@ export const shortUrlCreationReducerCreator = (buildShlinkApiClient: ShlinkApiCl
const { reducer, actions } = createSlice({ const { reducer, actions } = createSlice({
name: 'shortUrlCreationReducer', name: 'shortUrlCreationReducer',
initialState, initialState: initialState as ShortUrlCreation, // Without this casting it infers type ShortUrlCreationWaiting
reducers: { reducers: {
resetCreateShortUrl: () => initialState, resetCreateShortUrl: () => initialState,
}, },
extraReducers: (builder) => { extraReducers: (builder) => {
builder.addCase(createShortUrl.pending, (state) => ({ ...state, saving: true, error: false })); builder.addCase(createShortUrl.pending, () => ({ saving: true, saved: false, error: false }));
builder.addCase( builder.addCase(
createShortUrl.rejected, createShortUrl.rejected,
(state, { error }) => ({ ...state, saving: false, error: true, errorData: parseApiError(error) }), (_, { error }) => ({ saving: false, saved: false, error: true, errorData: parseApiError(error) }),
);
builder.addCase(
createShortUrl.fulfilled,
(_, { payload: result }) => ({ result, saving: false, saved: true, error: false }),
); );
builder.addCase(createShortUrl.fulfilled, (_, { payload: result }) => ({ result, saving: false, error: false }));
}, },
}); });

View File

@@ -10,8 +10,8 @@ export const SHORT_URL_EDITED = 'shlink/shortUrlEdition/SHORT_URL_EDITED';
export interface ShortUrlEdition { export interface ShortUrlEdition {
shortUrl?: ShortUrl; shortUrl?: ShortUrl;
saving: boolean; saving: boolean;
error: boolean;
saved: boolean; saved: boolean;
error: boolean;
errorData?: ProblemDetailsError; errorData?: ProblemDetailsError;
} }

View File

@@ -36,7 +36,7 @@ const provideServices = (bottle: Bottle, connect: ConnectDecorator) => {
bottle.serviceFactory('CreateShortUrl', CreateShortUrl, 'ShortUrlForm', 'CreateShortUrlResult'); bottle.serviceFactory('CreateShortUrl', CreateShortUrl, 'ShortUrlForm', 'CreateShortUrlResult');
bottle.decorator( bottle.decorator(
'CreateShortUrl', 'CreateShortUrl',
connect(['shortUrlCreationResult', 'selectedServer', 'settings'], ['createShortUrl', 'resetCreateShortUrl']), connect(['shortUrlCreation', 'selectedServer', 'settings'], ['createShortUrl', 'resetCreateShortUrl']),
); );
bottle.serviceFactory('EditShortUrl', EditShortUrl, 'ShortUrlForm'); bottle.serviceFactory('EditShortUrl', EditShortUrl, 'ShortUrlForm');

View File

@@ -13,7 +13,7 @@ describe('<CreateShortUrl />', () => {
const CreateShortUrl = createShortUrlsCreator(ShortUrlForm, CreateShortUrlResult); const CreateShortUrl = createShortUrlsCreator(ShortUrlForm, CreateShortUrlResult);
const setUp = () => render( const setUp = () => render(
<CreateShortUrl <CreateShortUrl
shortUrlCreationResult={shortUrlCreationResult} shortUrlCreation={shortUrlCreationResult}
createShortUrl={createShortUrl} createShortUrl={createShortUrl}
selectedServer={null} selectedServer={null}
resetCreateShortUrl={() => {}} resetCreateShortUrl={() => {}}

View File

@@ -4,34 +4,39 @@ import { CreateShortUrlResult as createResult } from '../../../src/short-urls/he
import { ShortUrl } from '../../../src/short-urls/data'; import { ShortUrl } from '../../../src/short-urls/data';
import { TimeoutToggle } from '../../../src/utils/helpers/hooks'; import { TimeoutToggle } from '../../../src/utils/helpers/hooks';
import { renderWithEvents } from '../../__helpers__/setUpTest'; import { renderWithEvents } from '../../__helpers__/setUpTest';
import { ShortUrlCreation } from '../../../src/short-urls/reducers/shortUrlCreation';
describe('<CreateShortUrlResult />', () => { describe('<CreateShortUrlResult />', () => {
const copyToClipboard = jest.fn(); const copyToClipboard = jest.fn();
const useTimeoutToggle = jest.fn(() => [false, copyToClipboard]) as TimeoutToggle; const useTimeoutToggle = jest.fn(() => [false, copyToClipboard]) as TimeoutToggle;
const CreateShortUrlResult = createResult(useTimeoutToggle); const CreateShortUrlResult = createResult(useTimeoutToggle);
const setUp = (result: ShortUrl | null = null, error = false) => renderWithEvents( const setUp = (creation: ShortUrlCreation) => renderWithEvents(
<CreateShortUrlResult resetCreateShortUrl={() => {}} result={result} error={error} saving={false} />, <CreateShortUrlResult resetCreateShortUrl={() => {}} creation={creation} />,
); );
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);
it('renders an error when error is true', () => { it('renders an error when error is true', () => {
setUp(Mock.all<ShortUrl>(), true); setUp({ error: true, saved: false, saving: false });
expect(screen.getByText('An error occurred while creating the URL :(')).toBeInTheDocument(); expect(screen.getByText('An error occurred while creating the URL :(')).toBeInTheDocument();
}); });
it('renders nothing when no result is provided', () => { it.each([[true], [false]])('renders nothing when not saved yet', (saving) => {
const { container } = setUp(); const { container } = setUp({ error: false, saved: false, saving });
expect(container.firstChild).toBeNull(); expect(container.firstChild).toBeNull();
}); });
it('renders a result message when result is provided', () => { it('renders a result message when result is provided', () => {
setUp(Mock.of<ShortUrl>({ shortUrl: 'https://doma.in/abc123' })); setUp(
{ result: Mock.of<ShortUrl>({ shortUrl: 'https://doma.in/abc123' }), saving: false, saved: true, error: false },
);
expect(screen.getByText(/The short URL is/)).toHaveTextContent('Great! The short URL is https://doma.in/abc123'); expect(screen.getByText(/The short URL is/)).toHaveTextContent('Great! The short URL is https://doma.in/abc123');
}); });
it('Invokes tooltip timeout when copy to clipboard button is clicked', async () => { it('Invokes tooltip timeout when copy to clipboard button is clicked', async () => {
const { user } = setUp(Mock.of<ShortUrl>({ shortUrl: 'https://doma.in/abc123' })); const { user } = setUp(
{ result: Mock.of<ShortUrl>({ shortUrl: 'https://doma.in/abc123' }), saving: false, saved: true, error: false },
);
expect(copyToClipboard).not.toHaveBeenCalled(); expect(copyToClipboard).not.toHaveBeenCalled();
await user.click(screen.getByRole('button')); await user.click(screen.getByRole('button'));

View File

@@ -22,16 +22,16 @@ describe('shortUrlCreationReducer', () => {
it('returns loading on CREATE_SHORT_URL_START', () => { it('returns loading on CREATE_SHORT_URL_START', () => {
expect(reducer(undefined, action(createShortUrl.pending.toString()))).toEqual({ expect(reducer(undefined, action(createShortUrl.pending.toString()))).toEqual({
result: null,
saving: true, saving: true,
saved: false,
error: false, error: false,
}); });
}); });
it('returns error on CREATE_SHORT_URL_ERROR', () => { it('returns error on CREATE_SHORT_URL_ERROR', () => {
expect(reducer(undefined, action(createShortUrl.rejected.toString()))).toEqual({ expect(reducer(undefined, action(createShortUrl.rejected.toString()))).toEqual({
result: null,
saving: false, saving: false,
saved: false,
error: true, error: true,
}); });
}); });
@@ -40,14 +40,15 @@ describe('shortUrlCreationReducer', () => {
expect(reducer(undefined, action(createShortUrl.fulfilled.toString(), { payload: shortUrl }))).toEqual({ expect(reducer(undefined, action(createShortUrl.fulfilled.toString(), { payload: shortUrl }))).toEqual({
result: shortUrl, result: shortUrl,
saving: false, saving: false,
saved: true,
error: false, error: false,
}); });
}); });
it('returns default state on RESET_CREATE_SHORT_URL', () => { it('returns default state on RESET_CREATE_SHORT_URL', () => {
expect(reducer(undefined, action(resetCreateShortUrl.toString()))).toEqual({ expect(reducer(undefined, action(resetCreateShortUrl.toString()))).toEqual({
result: null,
saving: false, saving: false,
saved: false,
error: false, error: false,
}); });
}); });