Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: list history versions in the history page sidebar #19421

Merged
merged 19 commits into from Feb 6, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -4,11 +4,10 @@ import { ContentLayout, HeaderLayout, Main, Typography } from '@strapi/design-sy
import { Link } from '@strapi/design-system/v2';
import { ArrowLeft } from '@strapi/icons';
import { useIntl } from 'react-intl';
import { NavLink, useNavigate } from 'react-router-dom';
import { NavLink } from 'react-router-dom';

const VersionDetails = () => {
const { formatMessage } = useIntl();
const navigate = useNavigate();
const headerId = React.useId();

return (
Expand All @@ -19,13 +18,9 @@ const VersionDetails = () => {
navigationAction={
<Link
startIcon={<ArrowLeft />}
onClick={(e) => {
e.preventDefault();
navigate(-1);
}}
as={NavLink}
// @ts-expect-error - types are not inferred correctly through the as prop.
to=""
to=".."
>
{formatMessage({
id: 'global.back',
Expand Down
@@ -1,19 +1,253 @@
import * as React from 'react';

import { Box, Typography } from '@strapi/design-system';
import { Box, Flex, Typography } from '@strapi/design-system';
import { LoadingIndicatorPage, useQueryParams } from '@strapi/helper-plugin';
import { Contracts } from '@strapi/plugin-content-manager/_internal/shared';
import { formatDistanceToNowStrict } from 'date-fns';
import * as locales from 'date-fns/locale';
import { stringify } from 'qs';
import { type MessageDescriptor, useIntl } from 'react-intl';
import { Link, useNavigate } from 'react-router-dom';

import { useGetHistoryVersionsQuery } from '../services/historyVersion';

import type { Entity, UID } from '@strapi/types';

/* -------------------------------------------------------------------------------------------------
* BlueChunks
* -----------------------------------------------------------------------------------------------*/

const BlueChunks = (chunks: React.ReactNode) => (
<Typography textColor="primary600">{chunks}</Typography>
);
remidej marked this conversation as resolved.
Show resolved Hide resolved

/* -------------------------------------------------------------------------------------------------
* VersionCard
* -----------------------------------------------------------------------------------------------*/

type Color = React.ComponentProps<typeof Box>['color'];
remidej marked this conversation as resolved.
Show resolved Hide resolved

interface StatusData {
background: Color;
border: Color;
text: Color;
message: MessageDescriptor;
}

interface VersionCardProps {
version: Contracts.HistoryVersions.GetHistoryVersions.Response['data'][number];
isCurrent: boolean;
}

const VersionCard = ({ version, isCurrent }: VersionCardProps) => {
const { formatDate, formatMessage, locale } = useIntl();
const [{ query }] = useQueryParams<{ id?: string }>();

const isActive = query.id === version.id.toString();

const getStatusData = (): StatusData => {
switch (version.status) {
case 'draft':
return {
background: 'secondary100',
border: 'secondary200',
text: 'secondary700',
message: {
id: 'content-manager.containers.List.draft',
defaultMessage: 'Draft',
},
};
case 'modified':
return {
background: 'alternative100',
border: 'alternative200',
text: 'alternative700',
message: {
// TODO: check the translation key once D&P v5 is done
id: 'content-manager.containers.List.modified',
defaultMessage: 'Modified',
},
};
case 'published':
default:
return {
background: 'success100',
border: 'success200',
text: 'success700',
message: {
id: 'content-manager.containers.List.published',
defaultMessage: 'Published',
},
};
}
};

const statusData = getStatusData();

const distanceToNow = formatDistanceToNowStrict(new Date(version.createdAt), {
addSuffix: true,
// @ts-expect-error - I don't know how to fix this
locale: locales[locale],
remidej marked this conversation as resolved.
Show resolved Hide resolved
});

const author =
version.createdBy?.username || `${version.createdBy?.firstname} ${version.createdBy?.lastname}`;
remidej marked this conversation as resolved.
Show resolved Hide resolved

return (
<Flex
direction="column"
alignItems="flex-start"
gap={3}
hasRadius
borderWidth="1px"
borderStyle="solid"
borderColor={isActive ? 'primary600' : 'neutral200'}
paddingTop={5}
paddingBottom={5}
paddingLeft={5}
paddingRight={5}
as={Link}
to={`?${stringify({ ...query, id: version.id })}`}
style={{ textDecoration: 'none' }}
>
<Flex direction="column" gap={1} alignItems="flex-start">
<Typography as="h3" fontWeight="semiBold">
{formatDate(version.createdAt, {
day: 'numeric',
month: 'numeric',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
})}
</Typography>
<Typography as="p" textColor="neutral600">
{formatMessage(
{
id: 'todo',
defaultMessage:
'{distanceToNow}{isAnonymous, select, true {} other { by {author}}}{isCurrent, select, true { <b>(current)</b>} other {}}',
markkaylor marked this conversation as resolved.
Show resolved Hide resolved
},
{
distanceToNow,
author,
isAnonymous: version.createdBy ? 'false' : 'true',
remidej marked this conversation as resolved.
Show resolved Hide resolved
isCurrent: isCurrent ? 'true' : 'false',
remidej marked this conversation as resolved.
Show resolved Hide resolved
b: BlueChunks,
}
)}
</Typography>
</Flex>
{version.status && (
<Box
background={statusData.background}
borderStyle="solid"
borderWidth="1px"
borderColor={statusData.border}
hasRadius
paddingLeft="6px"
paddingRight="6px"
paddingTop="2px"
paddingBottom="2px"
>
<Typography variant="pi" fontWeight="bold" textColor={statusData.text}>
{formatMessage(statusData.message)}
</Typography>
</Box>
)}
</Flex>
);
};

/* -------------------------------------------------------------------------------------------------
* VersionsList
* -----------------------------------------------------------------------------------------------*/

interface VersionsListProps {
contentType: UID.ContentType;
documentId?: Entity.ID;
locale?: string;
}

const VersionsList = ({ contentType, documentId, locale }: VersionsListProps) => {
remidej marked this conversation as resolved.
Show resolved Hide resolved
const { formatMessage } = useIntl();
const navigate = useNavigate();

// Parse state from query params
const [{ query }] = useQueryParams<{ page?: number; id?: number }>();
const page = query.page ? Number(query.page) : 1;

const response = useGetHistoryVersionsQuery({
contentType,
...(documentId ? { documentId } : {}),
...(locale ? { locale } : {}),
});

// Make sure the user lands on a selected history version
React.useEffect(() => {
const versions = response.data?.data;

if (!response.isLoading && !query.id && versions?.[0]) {
navigate({ search: stringify({ ...query, id: versions[0].id }) }, { replace: true });
}
}, [response.isLoading, navigate, query.id, response.data?.data, query]);

if (response.isLoading) {
return <LoadingIndicatorPage />;
}

const VersionsList = () => {
return (
<Box
<Flex
direction="column"
alignItems="stretch"
width="320px"
minHeight="100vh"
remidej marked this conversation as resolved.
Show resolved Hide resolved
height="100vh"
background="neutral0"
borderColor="neutral200"
borderWidth="0 0 0 1px"
borderStyle="solid"
as="aside"
>
<Typography>Sidebar</Typography>
</Box>
<Flex
direction="row"
justifyContent="space-between"
padding={4}
borderColor="neutral200"
borderWidth="0 0 1px"
borderStyle="solid"
as="header"
>
<Typography as="h2" variant="omega" fontWeight="semiBold">
{formatMessage({
id: 'content-manager.history.sidebar.title',
defaultMessage: 'Versions',
})}
</Typography>
<Box background="neutral150" hasRadius padding={1}>
<Typography variant="sigma" textColor="neutral600">
{response.data?.meta.pagination?.total}
</Typography>
</Box>
</Flex>
<Flex
direction="column"
gap={4}
paddingTop={4}
paddingLeft={4}
paddingRight={4}
paddingBottom={4}
as="ul"
alignItems="stretch"
flex={1}
overflow="scroll"
>
{response.data?.data.map((version, index) => (
<li key={version.id}>
<VersionCard version={version} isCurrent={page === 1 && index === 0} />
</li>
))}
</Flex>
</Flex>
);
};

Expand Down
@@ -0,0 +1,68 @@
import * as React from 'react';

import { within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { render as renderRTL, screen, waitFor } from '@tests/utils';
import { useLocation } from 'react-router-dom';

import { VersionsList } from '../VersionsList';

const user = userEvent.setup();

const LocationDisplay = () => {
const location = useLocation();

return <span data-testid="location">{location.search}</span>;
};

const render = (props: React.ComponentProps<typeof VersionsList>) =>
renderRTL(<VersionsList {...props} />, {
renderOptions: {
wrapper({ children }) {
return (
<>
{children}
<LocationDisplay />
</>
);
},
},
});

describe('VersionsList', () => {
it('renders a list of history versions', async () => {
render({ contentType: 'api::article.article', documentId: 'document-id' });

await waitFor(() => {
expect(screen.queryByTestId('loader')).not.toBeInTheDocument();
});

// Redirects to the first version
expect(screen.getByText('?id=26')).toBeInTheDocument();

// Shows sidebar header and total count
const header = screen.getByRole('banner');
expect(within(header).getByText('Versions')).toBeInTheDocument();
expect(screen.getByText('14')).toBeInTheDocument();
expect(screen.getByText('Versions')).toBeInTheDocument();

// Displays the right info for each version
const versions = screen.getAllByRole('link');
expect(within(versions[0]).getByText(/current/i)).toBeInTheDocument();
expect(within(versions[1]).queryByText(/current/i)).not.toBeInTheDocument();
expect(within(versions[1]).getByText(/draft/i)).toBeInTheDocument();
expect(within(versions[1]).getByText(/by/i)).toBeInTheDocument();
expect(within(versions[1]).getByText('1/31/2024, 03:58 PM')).toBeInTheDocument();
expect(within(versions[1]).getByText(/by Kai Doe/i)).toBeInTheDocument();

// Redirects to 2nd version on click
await user.click(versions[1]);
expect(screen.queryByText('?id=26')).not.toBeInTheDocument();
expect(screen.getByText('?id=25')).toBeInTheDocument();

// Redirects to 1st version again on click
await user.click(versions[0]);
expect(screen.queryByText('?id=25')).not.toBeInTheDocument();
expect(screen.getByText('?id=26')).toBeInTheDocument();
});
});