Skip to content

Commit

Permalink
EES-2701 glossary plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
amyb-hiveit committed Aug 10, 2023
1 parent 0828d3d commit 484b445
Show file tree
Hide file tree
Showing 29 changed files with 570 additions and 38 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useCommentsContext } from '@admin/contexts/CommentsContext';
import EditableBlockWrapper from '@admin/components/editable/EditableBlockWrapper';
import EditableContentForm from '@admin/components/editable/EditableContentForm';
import styles from '@admin/components/editable/EditableContentBlock.module.scss';
import glossaryService from '@admin/services/glossaryService';
import { UserDetails } from '@admin/services/types/user';
import {
ImageUploadCancelHandler,
Expand Down Expand Up @@ -195,10 +196,13 @@ const EditableContentBlock = ({
ref={ref}
onClick={isEditable ? onEditing : undefined}
>
<ContentHtml
html={content || '<p>This section is empty</p>'}
sanitizeOptions={sanitizeOptions}
/>
<div inert="">
<ContentHtml
getGlossaryEntry={glossaryService.getEntry}
html={content || '<p>This section is empty</p>'}
sanitizeOptions={sanitizeOptions}
/>
</div>
{lockedBy && (
<span className={styles.lockedMessage}>
{`${lockedBy.displayName} is editing`}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { useConfig } from '@admin/contexts/ConfigContext';
import glossaryQueries from '@admin/queries/glossaryQueries';
import { GlossaryItem } from '@admin/types/ckeditor';
import Button from '@common/components/Button';
import FormComboBox from '@common/components/form/FormComboBox';
import ButtonGroup from '@common/components/ButtonGroup';
import { Form, FormFieldTextInput } from '@common/components/form';
import useDebouncedCallback from '@common/hooks/useDebouncedCallback';
import { GlossaryEntry } from '@common/services/types/glossary';
import Yup from '@common/validation/yup';
import React, { useMemo, useState } from 'react';
import { Formik } from 'formik';
import { useQuery } from '@tanstack/react-query';
import LoadingSpinner from '@common/components/LoadingSpinner';

interface FormValues {
slug: string;
text: string;
}

interface Props {
onCancel: () => void;
onSubmit: (item: GlossaryItem) => void;
}

export default function GlossaryItemInsertForm({ onCancel, onSubmit }: Props) {
const config = useConfig();

const { data: glossary = [], isLoading } = useQuery(glossaryQueries.list);

const allGlossaryEntries = useMemo(() => glossary.flatMap(g => g.entries), [
glossary,
]);

const [searchResults, setSearchResults] = useState<GlossaryEntry[]>([]);
const [selectedEntry, setSelectedEntry] = useState<GlossaryEntry>();

const [search] = useDebouncedCallback((value: string) => {
if (value.length < 3) {
setSearchResults([]);
return;
}
const nextSearchResults = value.length
? allGlossaryEntries.filter(element => {
return element.title.toLowerCase().includes(value.toLowerCase());
})
: [];
setSearchResults(nextSearchResults);
}, 400);

return (
<LoadingSpinner loading={isLoading} hideText text="Loading glossary">
<Formik<FormValues>
initialValues={{
slug: '',
text: '',
}}
validationSchema={Yup.object({
slug: Yup.string().required('Select a glossary entry'),
text: Yup.string().when('slug', {
is: (val: string) => val,
then: s => s.required('Enter link text'),
}),
})}
onSubmit={values =>
onSubmit({
text: values.text,
url: `${config.PublicAppUrl}/glossary#${values.slug}`,
})
}
>
{form => (
<Form id="glossaryForm">
<FormComboBox
hideSearchIcon={!!selectedEntry}
id="glossarySearch"
inputLabel="Glossary entry"
options={searchResults.map(result => result.title)}
inputValue={selectedEntry?.title}
onInputChange={event => {
search(event.target.value);
}}
onSelect={selectedIndex => {
form.setFieldValue('text', searchResults[selectedIndex].title);
form.setFieldValue('slug', searchResults[selectedIndex].slug);
setSelectedEntry(searchResults[selectedIndex]);
}}
/>
{form.values.slug && (
<>
<p className="govuk-!-margin-top-1">Slug: {form.values.slug}</p>

<FormFieldTextInput
formGroupClass="govuk-!-margin-top-5 govuk-!-margin-bottom-2"
id="text"
label="Link text"
name="text"
/>
</>
)}

<ButtonGroup className="govuk-!-margin-top-5">
<Button
type="submit"
onClick={event => {
// Have to prevent default here as the form is nested,
// despite being in a modal, so otherwise it submits
// the parent EditableContentForm.
event.preventDefault();
form.submitForm();
}}
>
Insert
</Button>
<Button variant="secondary" onClick={onCancel}>
Cancel
</Button>
</ButtonGroup>
</Form>
)}
</Formik>
</LoadingSpinner>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
import GlossaryItemInsertForm from '@admin/components/editable/GlossaryItemInsertForm';
import { TestConfigContextProvider } from '@admin/contexts/ConfigContext';
import _glossaryService from '@admin/services/glossaryService';
import baseRender from '@common-test/render';
import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import noop from 'lodash/noop';
import React, { ReactElement } from 'react';

jest.mock('@admin/services/glossaryService');

const glossaryService = _glossaryService as jest.Mocked<
typeof _glossaryService
>;

describe('GlossaryItemInsertForm ', () => {
beforeEach(() => {
glossaryService.listEntries.mockResolvedValue([
{
heading: 'A',
entries: [
{ body: 'body text', slug: 'aardvark', title: 'Aardvark' },
{ body: 'body text', slug: 'antelope', title: 'Antelope' },
{ body: 'body text', slug: 'ant', title: 'Ant' },
],
},
{
heading: 'D',
entries: [{ body: 'body text', slug: 'dog', title: 'Dog' }],
},
{
heading: 'P',
entries: [{ body: 'body text', slug: 'partridge', title: 'Partridge' }],
},
]);
});

test('does not search if search term is less than 3 characters', async () => {
render(<GlossaryItemInsertForm onCancel={noop} onSubmit={noop} />);

await waitFor(() => {
expect(screen.getByText('Glossary entry')).toBeInTheDocument();
});

userEvent.type(screen.getByLabelText('Glossary entry'), 'an');

expect(screen.queryAllByRole('option')).toHaveLength(0);
});

test('shows search results', async () => {
render(<GlossaryItemInsertForm onCancel={noop} onSubmit={noop} />);

await waitFor(() => {
expect(screen.getByText('Glossary entry')).toBeInTheDocument();
});

userEvent.type(screen.getByLabelText('Glossary entry'), 'ant');

await waitFor(() => {
expect(screen.getByText('Antelope')).toBeInTheDocument();
});

const options = screen.getAllByRole('option');
expect(options).toHaveLength(2);
expect(options[0]).toHaveTextContent('Antelope');
expect(options[1]).toHaveTextContent('Ant');
});

test('selecting a search result shows the edit form', async () => {
render(<GlossaryItemInsertForm onCancel={noop} onSubmit={noop} />);

await waitFor(() => {
expect(screen.getByText('Glossary entry')).toBeInTheDocument();
});

userEvent.type(screen.getByLabelText('Glossary entry'), 'ant');

await waitFor(() => {
expect(screen.getByText('Antelope')).toBeInTheDocument();
});

const options = screen.getAllByRole('option');
userEvent.click(options[0]);

expect(screen.getByLabelText('Link text')).toHaveValue('Antelope');
expect(screen.getByText('Slug: antelope')).toBeInTheDocument();
});

test('successfully submitting form', async () => {
const handleSubmit = jest.fn();
render(<GlossaryItemInsertForm onCancel={noop} onSubmit={handleSubmit} />);

await waitFor(() => {
expect(screen.getByText('Glossary entry')).toBeInTheDocument();
});

userEvent.type(screen.getByLabelText('Glossary entry'), 'ant');

await waitFor(() => {
expect(screen.getByText('Antelope')).toBeInTheDocument();
});

const options = screen.getAllByRole('option');
userEvent.click(options[0]);

expect(handleSubmit).not.toHaveBeenCalled();

userEvent.click(screen.getByRole('button', { name: 'Insert' }));

await waitFor(() => {
expect(handleSubmit).toHaveBeenCalledWith({
text: 'Antelope',
url: 'http://localhost/glossary#antelope',
});
});
});

test('successfully submits the form after editing the link text', async () => {
const handleSubmit = jest.fn();
render(<GlossaryItemInsertForm onCancel={noop} onSubmit={handleSubmit} />);

await waitFor(() => {
expect(screen.getByText('Glossary entry')).toBeInTheDocument();
});

userEvent.type(screen.getByLabelText('Glossary entry'), 'ant');

await waitFor(() => {
expect(screen.getByText('Antelope')).toBeInTheDocument();
});

const options = screen.getAllByRole('option');
userEvent.click(options[0]);

userEvent.type(screen.getByLabelText('Link text'), ' edited');

expect(handleSubmit).not.toHaveBeenCalled();

userEvent.click(screen.getByRole('button', { name: 'Insert' }));

await waitFor(() => {
expect(handleSubmit).toHaveBeenCalledWith({
text: 'Antelope edited',
url: 'http://localhost/glossary#antelope',
});
});
});

test('shows a validation error if submit without selecting a glossary entry', async () => {
const handleSubmit = jest.fn();
render(<GlossaryItemInsertForm onCancel={noop} onSubmit={handleSubmit} />);

await waitFor(() => {
expect(screen.getByText('Glossary entry')).toBeInTheDocument();
});

userEvent.click(screen.getByRole('button', { name: 'Insert' }));

await waitFor(() => {
expect(screen.getByText('There is a problem')).toBeInTheDocument();
expect(
screen.getByRole('link', {
name: 'Select a glossary entry',
}),
).toBeInTheDocument();
});

expect(handleSubmit).not.toHaveBeenCalled();
});

test('shows a validation error if submit without link text', async () => {
const handleSubmit = jest.fn();
render(<GlossaryItemInsertForm onCancel={noop} onSubmit={handleSubmit} />);

await waitFor(() => {
expect(screen.getByText('Glossary entry')).toBeInTheDocument();
});

userEvent.type(screen.getByLabelText('Glossary entry'), 'ant');

await waitFor(() => {
expect(screen.getByText('Antelope')).toBeInTheDocument();
});

const options = screen.getAllByRole('option');
userEvent.click(options[0]);

userEvent.clear(screen.getByLabelText('Link text'));

userEvent.click(screen.getByRole('button', { name: 'Insert' }));

await waitFor(() => {
expect(screen.getByText('There is a problem')).toBeInTheDocument();
expect(
screen.getByRole('link', {
name: 'Enter link text',
}),
).toBeInTheDocument();
});

expect(handleSubmit).not.toHaveBeenCalled();
});

function render(element: ReactElement) {
baseRender(
<TestConfigContextProvider>{element}</TestConfigContextProvider>,
);
}
});
Loading

0 comments on commit 484b445

Please sign in to comment.