Merge pull request #190 from acelaya-forks/feature/edit-meta

Feature/edit meta
This commit is contained in:
Alejandro Celaya 2020-01-19 21:15:25 +01:00 committed by GitHub
commit e89b68fe1e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
19 changed files with 446 additions and 54 deletions

View file

@ -4,13 +4,14 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org).
## [Unreleased]
## 2.3.0 - 2020-01-19
#### Added
* [#174](https://github.com/shlinkio/shlink-web-client/issues/174) Added complete support for Shlink v2.x together with currently supported Shlink versions.
* [#164](https://github.com/shlinkio/shlink-web-client/issues/164) Added max visits control on those URLs which have `maxVisits`.
* [#178](https://github.com/shlinkio/shlink-web-client/issues/178) Short URLs list can now be filtered by date range.
* [#46](https://github.com/shlinkio/shlink-web-client/issues/46) Allowed short URL's metadata to be edited (`maxVisits`, `validSince` and `validUntil`).
#### Changed

View file

@ -6,6 +6,7 @@ import shortUrlsListParamsReducer from '../short-urls/reducers/shortUrlsListPara
import shortUrlCreationReducer from '../short-urls/reducers/shortUrlCreation';
import shortUrlDeletionReducer from '../short-urls/reducers/shortUrlDeletion';
import shortUrlTagsReducer from '../short-urls/reducers/shortUrlTags';
import shortUrlMetaReducer from '../short-urls/reducers/shortUrlMeta';
import shortUrlVisitsReducer from '../visits/reducers/shortUrlVisits';
import shortUrlDetailReducer from '../visits/reducers/shortUrlDetail';
import tagsListReducer from '../tags/reducers/tagsList';
@ -20,6 +21,7 @@ export default combineReducers({
shortUrlCreationResult: shortUrlCreationReducer,
shortUrlDeletion: shortUrlDeletionReducer,
shortUrlTags: shortUrlTagsReducer,
shortUrlMeta: shortUrlMetaReducer,
shortUrlVisits: shortUrlVisitsReducer,
shortUrlDetail: shortUrlDetailReducer,
tagsList: tagsListReducer,

View file

@ -2,7 +2,7 @@ import { faAngleDoubleDown as downIcon, faAngleDoubleUp as upIcon } from '@forta
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { assoc, dissoc, isEmpty, isNil, pipe, replace, trim } from 'ramda';
import React from 'react';
import { Collapse } from 'reactstrap';
import { Collapse, FormGroup, Input } from 'reactstrap';
import * as PropTypes from 'prop-types';
import DateInput from '../utils/DateInput';
import Checkbox from '../utils/Checkbox';
@ -40,9 +40,8 @@ const CreateShortUrl = (TagsSelector, CreateShortUrlResult) => class CreateShort
const changeTags = (tags) => this.setState({ tags: tags.map(normalizeTag) });
const renderOptionalInput = (id, placeholder, type = 'text', props = {}) => (
<div className="form-group">
<input
className="form-control"
<FormGroup>
<Input
id={id}
type={type}
placeholder={placeholder}
@ -50,7 +49,7 @@ const CreateShortUrl = (TagsSelector, CreateShortUrlResult) => class CreateShort
onChange={(e) => this.setState({ [id]: e.target.value })}
{...props}
/>
</div>
</FormGroup>
);
const renderDateInput = (id, placeholder, props = {}) => (
<div className="form-group">

View file

@ -0,0 +1,100 @@
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { Modal, ModalBody, ModalFooter, ModalHeader, FormGroup, Input, UncontrolledTooltip } from 'reactstrap';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faInfoCircle as infoIcon } from '@fortawesome/free-solid-svg-icons';
import { ExternalLink } from 'react-external-link';
import moment from 'moment';
import { pipe } from 'ramda';
import { shortUrlType } from '../reducers/shortUrlsList';
import { shortUrlEditMetaType } from '../reducers/shortUrlMeta';
import DateInput from '../../utils/DateInput';
import { formatIsoDate } from '../../utils/utils';
const propTypes = {
isOpen: PropTypes.bool.isRequired,
toggle: PropTypes.func.isRequired,
shortUrl: shortUrlType.isRequired,
shortUrlMeta: shortUrlEditMetaType,
editShortUrlMeta: PropTypes.func,
resetShortUrlMeta: PropTypes.func,
};
const dateOrUndefined = (shortUrl, dateName) => {
const date = shortUrl && shortUrl.meta && shortUrl.meta[dateName];
return date && moment(date);
};
const EditMetaModal = (
{ isOpen, toggle, shortUrl, shortUrlMeta, editShortUrlMeta, resetShortUrlMeta }
) => {
const { saving, error } = shortUrlMeta;
const url = shortUrl && (shortUrl.shortUrl || '');
const [ validSince, setValidSince ] = useState(dateOrUndefined(shortUrl, 'validSince'));
const [ validUntil, setValidUntil ] = useState(dateOrUndefined(shortUrl, 'validUntil'));
const [ maxVisits, setMaxVisits ] = useState(shortUrl && shortUrl.meta && shortUrl.meta.maxVisits);
const close = pipe(resetShortUrlMeta, toggle);
const doEdit = () => editShortUrlMeta(shortUrl.shortCode, {
maxVisits: maxVisits && parseInt(maxVisits),
validSince: validSince && formatIsoDate(validSince),
validUntil: validUntil && formatIsoDate(validUntil),
}).then(close);
return (
<Modal isOpen={isOpen} toggle={close} centered>
<ModalHeader toggle={close}>
<FontAwesomeIcon icon={infoIcon} id="metaTitleInfo" /> Edit metadata for <ExternalLink href={url} />
<UncontrolledTooltip target="metaTitleInfo" placement="bottom">
<p>Using these metadata properties, you can limit when and how many times your short URL can be visited.</p>
<p>If any of the params is not met, the URL will behave as if it was an invalid short URL.</p>
</UncontrolledTooltip>
</ModalHeader>
<form onSubmit={(e) => e.preventDefault() || doEdit()}>
<ModalBody>
<FormGroup>
<DateInput
placeholderText="Enabled since..."
selected={validSince}
maxDate={validUntil}
isClearable
onChange={setValidSince}
/>
</FormGroup>
<FormGroup>
<DateInput
placeholderText="Enabled until..."
selected={validUntil}
minDate={validSince}
isClearable
onChange={setValidUntil}
/>
</FormGroup>
<FormGroup className="mb-0">
<Input
type="number"
placeholder="Maximum number of visits allowed"
min={1}
value={maxVisits || ''}
onChange={(e) => setMaxVisits(e.target.value)}
/>
</FormGroup>
{error && (
<div className="p-2 mt-2 bg-danger text-white text-center">
Something went wrong while saving the metadata :(
</div>
)}
</ModalBody>
<ModalFooter>
<button className="btn btn-link" type="button" onClick={close}>Cancel</button>
<button className="btn btn-primary" type="submit" disabled={saving}>{saving ? 'Saving...' : 'Save'}</button>
</ModalFooter>
</form>
</Modal>
);
};
EditMetaModal.propTypes = propTypes;
export default EditMetaModal;

View file

@ -9,7 +9,6 @@ const EditTagsModal = (TagsSelector) => class EditTagsModal extends React.Compon
static propTypes = {
isOpen: PropTypes.bool.isRequired,
toggle: PropTypes.func.isRequired,
url: PropTypes.string.isRequired,
shortUrl: shortUrlType.isRequired,
shortUrlTags: shortUrlTagsType,
editShortUrlTags: PropTypes.func,
@ -51,12 +50,13 @@ const EditTagsModal = (TagsSelector) => class EditTagsModal extends React.Compon
}
render() {
const { isOpen, toggle, url, shortUrlTags } = this.props;
const { isOpen, toggle, shortUrl, shortUrlTags } = this.props;
const url = shortUrl && (shortUrl.shortUrl || '');
return (
<Modal isOpen={isOpen} toggle={toggle} centered onClosed={() => this.refreshShortUrls()}>
<ModalHeader toggle={toggle}>
Edit tags for <ExternalLink href={url}>{url}</ExternalLink>
Edit tags for <ExternalLink href={url} />
</ModalHeader>
<ModalBody>
<TagsSelector tags={this.state.tags} onChange={(tags) => this.setState({ tags })} />

View file

@ -3,7 +3,7 @@ import PropTypes from 'prop-types';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faInfoCircle as infoIcon } from '@fortawesome/free-solid-svg-icons';
import { UncontrolledTooltip } from 'reactstrap';
import { shortUrlMetaType } from '../reducers/shortUrlsList';
import { shortUrlMetaType } from '../reducers/shortUrlMeta';
import './ShortUrlVisitsCount.scss';
const propTypes = {

View file

@ -5,6 +5,7 @@ import {
faEllipsisV as menuIcon,
faQrcode as qrIcon,
faMinusCircle as deleteIcon,
faEdit as editIcon,
} from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import React from 'react';
@ -20,7 +21,11 @@ import PreviewModal from './PreviewModal';
import QrCodeModal from './QrCodeModal';
import './ShortUrlsRowMenu.scss';
const ShortUrlsRowMenu = (DeleteShortUrlModal, EditTagsModal) => class ShortUrlsRowMenu extends React.Component {
const ShortUrlsRowMenu = (
DeleteShortUrlModal,
EditTagsModal,
EditMetaModal
) => class ShortUrlsRowMenu extends React.Component {
static propTypes = {
onCopyToClipboard: PropTypes.func,
selectedServer: serverType,
@ -32,6 +37,7 @@ const ShortUrlsRowMenu = (DeleteShortUrlModal, EditTagsModal) => class ShortUrls
isQrModalOpen: false,
isPreviewModalOpen: false,
isTagsModalOpen: false,
isMetaModalOpen: false,
isDeleteModalOpen: false,
};
toggle = () => this.setState(({ isOpen }) => ({ isOpen: !isOpen }));
@ -45,6 +51,7 @@ const ShortUrlsRowMenu = (DeleteShortUrlModal, EditTagsModal) => class ShortUrls
const toggleQrCode = toggleModal('isQrModalOpen');
const togglePreview = toggleModal('isPreviewModalOpen');
const toggleTags = toggleModal('isTagsModalOpen');
const toggleMeta = toggleModal('isMetaModalOpen');
const toggleDelete = toggleModal('isDeleteModalOpen');
return (
@ -54,21 +61,21 @@ const ShortUrlsRowMenu = (DeleteShortUrlModal, EditTagsModal) => class ShortUrls
</DropdownToggle>
<DropdownMenu right>
<DropdownItem tag={Link} to={`/server/${selectedServer ? selectedServer.id : ''}/short-code/${shortUrl.shortCode}/visits`}>
<FontAwesomeIcon icon={pieChartIcon} /> &nbsp;Visit stats
<FontAwesomeIcon icon={pieChartIcon} fixedWidth /> Visit stats
</DropdownItem>
<DropdownItem onClick={toggleTags}>
<FontAwesomeIcon icon={tagsIcon} /> &nbsp;Edit tags
<FontAwesomeIcon icon={tagsIcon} fixedWidth /> Edit tags
</DropdownItem>
<EditTagsModal
url={completeShortUrl}
shortUrl={shortUrl}
isOpen={this.state.isTagsModalOpen}
toggle={toggleTags}
/>
<EditTagsModal shortUrl={shortUrl} isOpen={this.state.isTagsModalOpen} toggle={toggleTags} />
<DropdownItem onClick={toggleMeta}>
<FontAwesomeIcon icon={editIcon} fixedWidth /> Edit metadata
</DropdownItem>
<EditMetaModal shortUrl={shortUrl} isOpen={this.state.isMetaModalOpen} toggle={toggleMeta} />
<DropdownItem className="short-urls-row-menu__dropdown-item--danger" onClick={toggleDelete}>
<FontAwesomeIcon icon={deleteIcon} /> &nbsp;Delete short URL
<FontAwesomeIcon icon={deleteIcon} fixedWidth /> Delete short URL
</DropdownItem>
<DeleteShortUrlModal shortUrl={shortUrl} isOpen={this.state.isDeleteModalOpen} toggle={toggleDelete} />
@ -77,14 +84,14 @@ const ShortUrlsRowMenu = (DeleteShortUrlModal, EditTagsModal) => class ShortUrls
{showPreviewBtn && (
<React.Fragment>
<DropdownItem onClick={togglePreview}>
<FontAwesomeIcon icon={pictureIcon} /> &nbsp;Preview
<FontAwesomeIcon icon={pictureIcon} fixedWidth /> Preview
</DropdownItem>
<PreviewModal url={completeShortUrl} isOpen={this.state.isPreviewModalOpen} toggle={togglePreview} />
</React.Fragment>
)}
<DropdownItem onClick={toggleQrCode}>
<FontAwesomeIcon icon={qrIcon} /> &nbsp;QR code
<FontAwesomeIcon icon={qrIcon} fixedWidth /> QR code
</DropdownItem>
<QrCodeModal url={completeShortUrl} isOpen={this.state.isQrModalOpen} toggle={toggleQrCode} />
@ -92,7 +99,7 @@ const ShortUrlsRowMenu = (DeleteShortUrlModal, EditTagsModal) => class ShortUrls
<CopyToClipboard text={completeShortUrl} onCopy={onCopyToClipboard}>
<DropdownItem>
<FontAwesomeIcon icon={copyIcon} /> &nbsp;Copy to clipboard
<FontAwesomeIcon icon={copyIcon} fixedWidth /> Copy to clipboard
</DropdownItem>
</CopyToClipboard>
</DropdownMenu>

View file

@ -0,0 +1,52 @@
import { createAction, handleActions } from 'redux-actions';
import PropTypes from 'prop-types';
/* eslint-disable padding-line-between-statements */
export const EDIT_SHORT_URL_META_START = 'shlink/shortUrlMeta/EDIT_SHORT_URL_META_START';
export const EDIT_SHORT_URL_META_ERROR = 'shlink/shortUrlMeta/EDIT_SHORT_URL_META_ERROR';
export const SHORT_URL_META_EDITED = 'shlink/shortUrlMeta/SHORT_URL_META_EDITED';
export const RESET_EDIT_SHORT_URL_META = 'shlink/shortUrlMeta/RESET_EDIT_SHORT_URL_META';
/* eslint-enable padding-line-between-statements */
export const shortUrlMetaType = PropTypes.shape({
validSince: PropTypes.string,
validUntil: PropTypes.string,
maxVisits: PropTypes.number,
});
export const shortUrlEditMetaType = PropTypes.shape({
shortCode: PropTypes.string,
meta: shortUrlMetaType.isRequired,
saving: PropTypes.bool.isRequired,
error: PropTypes.bool.isRequired,
});
const initialState = {
shortCode: null,
meta: {},
saving: false,
error: false,
};
export default handleActions({
[EDIT_SHORT_URL_META_START]: (state) => ({ ...state, saving: true, error: false }),
[EDIT_SHORT_URL_META_ERROR]: (state) => ({ ...state, saving: false, error: true }),
[SHORT_URL_META_EDITED]: (state, { shortCode, meta }) => ({ shortCode, meta, saving: false, error: false }),
[RESET_EDIT_SHORT_URL_META]: () => initialState,
}, initialState);
export const editShortUrlMeta = (buildShlinkApiClient) => (shortCode, meta) => async (dispatch, getState) => {
dispatch({ type: EDIT_SHORT_URL_META_START });
const { updateShortUrlMeta } = await buildShlinkApiClient(getState);
try {
await updateShortUrlMeta(shortCode, meta);
dispatch({ shortCode, meta, type: SHORT_URL_META_EDITED });
} catch (e) {
dispatch({ type: EDIT_SHORT_URL_META_ERROR });
throw e;
}
};
export const resetShortUrlMeta = createAction(RESET_EDIT_SHORT_URL_META);

View file

@ -3,6 +3,7 @@ import { assoc, assocPath, propEq, reject } from 'ramda';
import PropTypes from 'prop-types';
import { SHORT_URL_TAGS_EDITED } from './shortUrlTags';
import { SHORT_URL_DELETED } from './shortUrlDeletion';
import { SHORT_URL_META_EDITED, shortUrlMetaType } from './shortUrlMeta';
/* eslint-disable padding-line-between-statements */
export const LIST_SHORT_URLS_START = 'shlink/shortUrlsList/LIST_SHORT_URLS_START';
@ -10,12 +11,6 @@ export const LIST_SHORT_URLS_ERROR = 'shlink/shortUrlsList/LIST_SHORT_URLS_ERROR
export const LIST_SHORT_URLS = 'shlink/shortUrlsList/LIST_SHORT_URLS';
/* eslint-enable padding-line-between-statements */
export const shortUrlMetaType = PropTypes.shape({
validSince: PropTypes.string,
validUntil: PropTypes.string,
maxVisits: PropTypes.number,
});
export const shortUrlType = PropTypes.shape({
shortCode: PropTypes.string,
shortUrl: PropTypes.string,
@ -31,23 +26,25 @@ const initialState = {
error: false,
};
const setPropFromActionOnMatchingShortUrl = (prop) => (state, { shortCode, [prop]: propValue }) => assocPath(
[ 'shortUrls', 'data' ],
state.shortUrls.data.map(
(shortUrl) => shortUrl.shortCode === shortCode ? assoc(prop, propValue, shortUrl) : shortUrl
),
state
);
export default handleActions({
[LIST_SHORT_URLS_START]: (state) => ({ ...state, loading: true, error: false }),
[LIST_SHORT_URLS]: (state, { shortUrls }) => ({ loading: false, error: false, shortUrls }),
[LIST_SHORT_URLS_ERROR]: () => ({ loading: false, error: true, shortUrls: {} }),
[SHORT_URL_TAGS_EDITED]: (state, action) => { // eslint-disable-line object-shorthand
const { data } = state.shortUrls;
return assocPath([ 'shortUrls', 'data' ], data.map((shortUrl) =>
shortUrl.shortCode === action.shortCode
? assoc('tags', action.tags, shortUrl)
: shortUrl), state);
},
[SHORT_URL_DELETED]: (state, action) => assocPath(
[SHORT_URL_DELETED]: (state, { shortCode }) => assocPath(
[ 'shortUrls', 'data' ],
reject(propEq('shortCode', action.shortCode), state.shortUrls.data),
reject(propEq('shortCode', shortCode), state.shortUrls.data),
state,
),
[SHORT_URL_TAGS_EDITED]: setPropFromActionOnMatchingShortUrl('tags'),
[SHORT_URL_META_EDITED]: setPropFromActionOnMatchingShortUrl('meta'),
}, initialState);
export const listShortUrls = (buildShlinkApiClient) => (params = {}) => async (dispatch, getState) => {

View file

@ -8,11 +8,13 @@ import ShortUrlsRowMenu from '../helpers/ShortUrlsRowMenu';
import CreateShortUrl from '../CreateShortUrl';
import DeleteShortUrlModal from '../helpers/DeleteShortUrlModal';
import EditTagsModal from '../helpers/EditTagsModal';
import EditMetaModal from '../helpers/EditMetaModal';
import CreateShortUrlResult from '../helpers/CreateShortUrlResult';
import { listShortUrls } from '../reducers/shortUrlsList';
import { createShortUrl, resetCreateShortUrl } from '../reducers/shortUrlCreation';
import { deleteShortUrl, resetDeleteShortUrl, shortUrlDeleted } from '../reducers/shortUrlDeletion';
import { editShortUrlTags, resetShortUrlsTags, shortUrlTagsEdited } from '../reducers/shortUrlTags';
import { editShortUrlMeta, resetShortUrlMeta } from '../reducers/shortUrlMeta';
import { resetShortUrlParams } from '../reducers/shortUrlsListParams';
const provideServices = (bottle, connect) => {
@ -33,7 +35,7 @@ const provideServices = (bottle, connect) => {
bottle.serviceFactory('ShortUrlsRow', ShortUrlsRow, 'ShortUrlsRowMenu', 'ColorGenerator', 'stateFlagTimeout');
bottle.serviceFactory('ShortUrlsRowMenu', ShortUrlsRowMenu, 'DeleteShortUrlModal', 'EditTagsModal');
bottle.serviceFactory('ShortUrlsRowMenu', ShortUrlsRowMenu, 'DeleteShortUrlModal', 'EditTagsModal', 'EditMetaModal');
bottle.serviceFactory('CreateShortUrlResult', CreateShortUrlResult, 'stateFlagTimeout');
bottle.serviceFactory('CreateShortUrl', CreateShortUrl, 'TagsSelector', 'CreateShortUrlResult');
@ -54,6 +56,9 @@ const provideServices = (bottle, connect) => {
[ 'editShortUrlTags', 'resetShortUrlsTags', 'shortUrlTagsEdited' ]
));
bottle.serviceFactory('EditMetaModal', () => EditMetaModal);
bottle.decorator('EditMetaModal', connect([ 'shortUrlMeta' ], [ 'editShortUrlMeta', 'resetShortUrlMeta' ]));
// Actions
bottle.serviceFactory('editShortUrlTags', editShortUrlTags, 'buildShlinkApiClient');
bottle.serviceFactory('resetShortUrlsTags', () => resetShortUrlsTags);
@ -68,6 +73,9 @@ const provideServices = (bottle, connect) => {
bottle.serviceFactory('deleteShortUrl', deleteShortUrl, 'buildShlinkApiClient');
bottle.serviceFactory('resetDeleteShortUrl', () => resetDeleteShortUrl);
bottle.serviceFactory('shortUrlDeleted', () => shortUrlDeleted);
bottle.serviceFactory('editShortUrlMeta', editShortUrlMeta, 'buildShlinkApiClient');
bottle.serviceFactory('resetShortUrlMeta', () => resetShortUrlMeta);
};
export default provideServices;

View file

@ -23,7 +23,7 @@ export default class ShlinkApiClient {
listShortUrls = pipe(
(options = {}) => reject(isNil, options),
(options = {}) => this._performRequest('/short-urls', 'GET', options).then((resp) => resp.data.shortUrls)
(options) => this._performRequest('/short-urls', 'GET', options).then((resp) => resp.data.shortUrls)
);
createShortUrl = (options) => {
@ -49,6 +49,10 @@ export default class ShlinkApiClient {
this._performRequest(`/short-urls/${shortCode}/tags`, 'PUT', {}, { tags })
.then((resp) => resp.data.tags);
updateShortUrlMeta = (shortCode, meta) =>
this._performRequest(`/short-urls/${shortCode}`, 'PATCH', {}, meta)
.then(() => meta);
listTags = () =>
this._performRequest('/tags', 'GET')
.then((resp) => resp.data.tags.data);

View file

@ -70,3 +70,5 @@ export const versionIsValidSemVer = (version) => {
};
export const formatDate = (format = 'YYYY-MM-DD') => (date) => date && date.format ? date.format(format) : date;
export const formatIsoDate = (date) => date && date.format ? date.format() : date;

View file

@ -0,0 +1,84 @@
import React from 'react';
import { shallow } from 'enzyme';
import { FormGroup, Modal, ModalHeader } from 'reactstrap';
import each from 'jest-each';
import EditMetaModal from '../../../src/short-urls/helpers/EditMetaModal';
describe('<EditMetaModal />', () => {
let wrapper;
const editShortUrlMeta = jest.fn(() => Promise.resolve());
const resetShortUrlMeta = jest.fn();
const toggle = jest.fn();
const createWrapper = (shortUrl, shortUrlMeta) => {
wrapper = shallow(
<EditMetaModal
isOpen={true}
shortUrl={shortUrl}
shortUrlMeta={shortUrlMeta}
toggle={toggle}
editShortUrlMeta={editShortUrlMeta}
resetShortUrlMeta={resetShortUrlMeta}
/>
);
return wrapper;
};
afterEach(() => {
wrapper && wrapper.unmount();
jest.clearAllMocks();
});
it('properly renders form with components', () => {
const wrapper = createWrapper({}, { saving: false, error: false, meta: {} });
const error = wrapper.find('.bg-danger');
const form = wrapper.find('form');
const formGroup = form.find(FormGroup);
expect(form).toHaveLength(1);
expect(formGroup).toHaveLength(3);
expect(error).toHaveLength(0);
});
each([
[ true, 'Saving...' ],
[ false, 'Save' ],
]).it('renders submit button on expected state', (saving, expectedText) => {
const wrapper = createWrapper({}, { saving, error: false, meta: {} });
const button = wrapper.find('[type="submit"]');
expect(button.prop('disabled')).toEqual(saving);
expect(button.text()).toContain(expectedText);
});
it('renders error message on error', () => {
const wrapper = createWrapper({}, { saving: false, error: true, meta: {} });
const error = wrapper.find('.bg-danger');
expect(error).toHaveLength(1);
});
it('saves meta when form is submit', () => {
const preventDefault = jest.fn();
const wrapper = createWrapper({}, { saving: false, error: false, meta: {} });
const form = wrapper.find('form');
form.simulate('submit', { preventDefault });
expect(preventDefault).toHaveBeenCalled();
expect(editShortUrlMeta).toHaveBeenCalled();
});
each([
[ '.btn-link', 'onClick' ],
[ Modal, 'toggle' ],
[ ModalHeader, 'toggle' ],
]).it('resets meta when modal is toggled in any way', (componentToFind, propToCall) => {
const wrapper = createWrapper({}, { saving: false, error: false, meta: {} });
const component = wrapper.find(componentToFind);
component.prop(propToCall)();
expect(resetShortUrlMeta).toHaveBeenCalled();
});
});

View file

@ -17,7 +17,6 @@ describe('<EditTagsModal />', () => {
wrapper = shallow(
<EditTagsModal
isOpen={true}
url={''}
shortUrl={{
tags: [],
shortCode,
@ -36,10 +35,7 @@ describe('<EditTagsModal />', () => {
afterEach(() => {
wrapper && wrapper.unmount();
editShortUrlTags.mockClear();
shortUrlTagsEdited.mockReset();
resetShortUrlsTags.mockReset();
toggle.mockReset();
jest.clearAllMocks();
});
it('resets tags when component is mounted', () => {

View file

@ -10,6 +10,7 @@ describe('<ShortUrlsRowMenu />', () => {
let wrapper;
const DeleteShortUrlModal = () => '';
const EditTagsModal = () => '';
const EditMetaModal = () => '';
const onCopyToClipboard = jest.fn();
const selectedServer = { id: 'abc123' };
const shortUrl = {
@ -17,7 +18,7 @@ describe('<ShortUrlsRowMenu />', () => {
shortUrl: 'https://doma.in/abc123',
};
const createWrapper = (serverVersion = '1.21.1') => {
const ShortUrlsRowMenu = createShortUrlsRowMenu(DeleteShortUrlModal, EditTagsModal);
const ShortUrlsRowMenu = createShortUrlsRowMenu(DeleteShortUrlModal, EditTagsModal, EditMetaModal);
wrapper = shallow(
<ShortUrlsRowMenu
@ -46,12 +47,12 @@ describe('<ShortUrlsRowMenu />', () => {
});
each([
[ '1.20.3', 6, 2 ],
[ '1.21.0', 6, 2 ],
[ '1.21.1', 6, 2 ],
[ '2.0.0', 5, 1 ],
[ '2.0.1', 5, 1 ],
[ '2.1.0', 5, 1 ],
[ '1.20.3', 7, 2 ],
[ '1.21.0', 7, 2 ],
[ '1.21.1', 7, 2 ],
[ '2.0.0', 6, 1 ],
[ '2.0.1', 6, 1 ],
[ '2.1.0', 6, 1 ],
]).it('renders correct amount of menu items depending on the version', (version, expectedNonDividerItems, expectedDividerItems) => {
const wrapper = createWrapper(version);
const items = wrapper.find(DropdownItem);

View file

@ -0,0 +1,93 @@
import moment from 'moment';
import reducer, {
EDIT_SHORT_URL_META_START,
EDIT_SHORT_URL_META_ERROR,
SHORT_URL_META_EDITED,
RESET_EDIT_SHORT_URL_META,
editShortUrlMeta,
resetShortUrlMeta,
} from '../../../src/short-urls/reducers/shortUrlMeta';
describe('shortUrlMetaReducer', () => {
const meta = {
maxVisits: 50,
startDate: moment('2020-01-01').format(),
};
const shortCode = 'abc123';
describe('reducer', () => {
it('returns loading on EDIT_SHORT_URL_META_START', () => {
expect(reducer({}, { type: EDIT_SHORT_URL_META_START })).toEqual({
saving: true,
error: false,
});
});
it('returns error on EDIT_SHORT_URL_META_ERROR', () => {
expect(reducer({}, { type: EDIT_SHORT_URL_META_ERROR })).toEqual({
saving: false,
error: true,
});
});
it('returns provided tags and shortCode on SHORT_URL_META_EDITED', () => {
expect(reducer({}, { type: SHORT_URL_META_EDITED, meta, shortCode })).toEqual({
meta,
shortCode,
saving: false,
error: false,
});
});
it('goes back to initial state on RESET_EDIT_SHORT_URL_META', () => {
expect(reducer({}, { type: RESET_EDIT_SHORT_URL_META })).toEqual({
meta: {},
shortCode: null,
saving: false,
error: false,
});
});
});
describe('editShortUrlMeta', () => {
const updateShortUrlMeta = jest.fn().mockResolvedValue({});
const buildShlinkApiClient = jest.fn().mockResolvedValue({ updateShortUrlMeta });
const dispatch = jest.fn();
afterEach(jest.clearAllMocks);
it('dispatches metadata on success', async () => {
await editShortUrlMeta(buildShlinkApiClient)(shortCode, meta)(dispatch);
expect(buildShlinkApiClient).toHaveBeenCalledTimes(1);
expect(updateShortUrlMeta).toHaveBeenCalledTimes(1);
expect(updateShortUrlMeta).toHaveBeenCalledWith(shortCode, meta);
expect(dispatch).toHaveBeenCalledTimes(2);
expect(dispatch).toHaveBeenNthCalledWith(1, { type: EDIT_SHORT_URL_META_START });
expect(dispatch).toHaveBeenNthCalledWith(2, { type: SHORT_URL_META_EDITED, meta, shortCode });
});
it('dispatches error on failure', async () => {
const error = new Error();
updateShortUrlMeta.mockRejectedValue(error);
try {
await editShortUrlMeta(buildShlinkApiClient)(shortCode, meta)(dispatch);
} catch (e) {
expect(e).toBe(error);
}
expect(buildShlinkApiClient).toHaveBeenCalledTimes(1);
expect(updateShortUrlMeta).toHaveBeenCalledTimes(1);
expect(updateShortUrlMeta).toHaveBeenCalledWith(shortCode, meta);
expect(dispatch).toHaveBeenCalledTimes(2);
expect(dispatch).toHaveBeenNthCalledWith(1, { type: EDIT_SHORT_URL_META_START });
expect(dispatch).toHaveBeenNthCalledWith(2, { type: EDIT_SHORT_URL_META_ERROR });
});
});
describe('resetShortUrlMeta', () => {
it('creates expected action', () => expect(resetShortUrlMeta()).toEqual({ type: RESET_EDIT_SHORT_URL_META }));
});
});

View file

@ -1,10 +1,11 @@
import reducer, {
EDIT_SHORT_URL_TAGS,
EDIT_SHORT_URL_TAGS_ERROR,
EDIT_SHORT_URL_TAGS_START, editShortUrlTags,
EDIT_SHORT_URL_TAGS_START,
RESET_EDIT_SHORT_URL_TAGS,
resetShortUrlsTags,
SHORT_URL_TAGS_EDITED,
editShortUrlTags,
shortUrlTagsEdited,
} from '../../../src/short-urls/reducers/shortUrlTags';

View file

@ -6,6 +6,7 @@ import reducer, {
} from '../../../src/short-urls/reducers/shortUrlsList';
import { SHORT_URL_TAGS_EDITED } from '../../../src/short-urls/reducers/shortUrlTags';
import { SHORT_URL_DELETED } from '../../../src/short-urls/reducers/shortUrlDeletion';
import { SHORT_URL_META_EDITED } from '../../../src/short-urls/reducers/shortUrlMeta';
describe('shortUrlsListReducer', () => {
describe('reducer', () => {
@ -52,6 +53,31 @@ describe('shortUrlsListReducer', () => {
});
});
it('Updates meta on matching URL on SHORT_URL_META_EDITED', () => {
const shortCode = 'abc123';
const meta = {
maxVisits: 5,
validSince: '2020-05-05',
};
const state = {
shortUrls: {
data: [
{ shortCode, meta: { maxVisits: 10 } },
{ shortCode: 'foo', meta: null },
],
},
};
expect(reducer(state, { type: SHORT_URL_META_EDITED, shortCode, meta })).toEqual({
shortUrls: {
data: [
{ shortCode, meta },
{ shortCode: 'foo', meta: null },
],
},
});
});
it('Removes matching URL on SHORT_URL_DELETED', () => {
const shortCode = 'abc123';
const state = {

View file

@ -102,6 +102,25 @@ describe('ShlinkApiClient', () => {
});
});
describe('updateShortUrlMeta', () => {
it('properly updates short URL meta', async () => {
const expectedMeta = {
maxVisits: 50,
validSince: '2025-01-01T10:00:00+01:00',
};
const axiosSpy = jest.fn(createAxiosMock());
const { updateShortUrlMeta } = new ShlinkApiClient(axiosSpy);
const result = await updateShortUrlMeta('abc123', expectedMeta);
expect(expectedMeta).toEqual(result);
expect(axiosSpy).toHaveBeenCalledWith(expect.objectContaining({
url: '/short-urls/abc123',
method: 'PATCH',
}));
});
});
describe('listTags', () => {
it('properly returns list of tags', async () => {
const expectedTags = [ 'foo', 'bar' ];