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: add drag n drop functionality to section cards #17

Merged
merged 16 commits into from
Dec 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,15 @@
"email-validator": "2.0.4",
"file-saver": "^2.0.5",
"formik": "2.2.6",
"immutability-helper": "^3.1.1",
"jszip": "^3.10.1",
"lodash": "4.17.21",
"moment": "2.29.4",
"prop-types": "15.7.2",
"react": "17.0.2",
"react-datepicker": "^4.13.0",
"react-dnd": "14.0.5",
"react-dnd-html5-backend": "14.1.0",
"react-dom": "17.0.2",
"react-helmet": "^6.1.0",
"react-redux": "7.2.9",
Expand Down
116 changes: 81 additions & 35 deletions src/course-outline/CourseOutline.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { React, useEffect, useRef } from 'react';
import {
React, useState, useCallback, useEffect, useRef,
} from 'react';
import update from 'immutability-helper';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import PropTypes from 'prop-types';
import { useIntl } from '@edx/frontend-platform/i18n';
import {
Expand Down Expand Up @@ -80,17 +85,51 @@ const CourseOutline = ({ courseId }) => {
handleDuplicateSubsectionSubmit,
handleNewSectionSubmit,
handleNewSubsectionSubmit,
handleDragNDrop,
} = useCourseOutline({ courseId });

useEffect(() => {
scrollToElement(listRef);
}, [sectionsList]);
document.title = getPageHeadTitle(courseName, intl.formatMessage(messages.headingTitle));
const [sections, setSections] = useState(sectionsList);

const initialSections = [...sectionsList];
steff456 marked this conversation as resolved.
Show resolved Hide resolved

const {
isShow: isShowProcessingNotification,
title: processingNotificationTitle,
} = useSelector(getProcessingNotification);

const moveSection = useCallback((dragIndex, hoverIndex, dragElement) => {
setSections((prevSections) => {
const newList = update(prevSections, {
$splice: [
[dragIndex, 1],
[hoverIndex, 0, prevSections[dragIndex]],
],
});
// set listRef to element that was dragged to make sure scrolling
// uses the correct element while calculating visibility.
listRef.current = dragElement;
return newList;
});
}, []);

const finalizeSectionOrder = () => {
handleDragNDrop(sections.map((section) => section.id), () => {
setSections(() => initialSections);
});
};

useEffect(() => {
setSections(sectionsList);
}, [sectionsList]);

useEffect(() => {
// scrollToElement called in another useEffect to make sure sections are rendered first.
if (listRef.current) {
scrollToElement(listRef.current);
}
}, [sections]);

if (isLoading) {
// eslint-disable-next-line react/jsx-no-useless-fragment
return <></>;
Expand Down Expand Up @@ -150,38 +189,45 @@ const CourseOutline = ({ courseId }) => {
openEnableHighlightsModal={openEnableHighlightsModal}
/>
<div className="pt-4">
{sectionsList.length ? (
{sections.length ? (
<>
{sectionsList.map((section) => (
<SectionCard
key={section.id}
section={section}
savingStatus={savingStatus}
onOpenHighlightsModal={handleOpenHighlightsModal}
onOpenPublishModal={openPublishModal}
onOpenConfigureModal={openConfigureModal}
onOpenDeleteModal={openDeleteModal}
onEditSectionSubmit={handleEditSubmit}
onDuplicateSubmit={handleDuplicateSectionSubmit}
isSectionsExpanded={isSectionsExpanded}
onNewSubsectionSubmit={handleNewSubsectionSubmit}
ref={listRef}
>
{section.childInfo.children.map((subsection) => (
<SubsectionCard
key={subsection.id}
section={section}
subsection={subsection}
savingStatus={savingStatus}
onOpenPublishModal={openPublishModal}
onOpenDeleteModal={openDeleteModal}
onEditSubmit={handleEditSubmit}
onDuplicateSubmit={handleDuplicateSubsectionSubmit}
ref={listRef}
/>
))}
</SectionCard>
))}
<DndProvider
backend={HTML5Backend}
>
{sections.map((section, index) => (
<SectionCard
key={section.id}
index={index}
section={section}
savingStatus={savingStatus}
onOpenHighlightsModal={handleOpenHighlightsModal}
onOpenPublishModal={openPublishModal}
onOpenConfigureModal={openConfigureModal}
onOpenDeleteModal={openDeleteModal}
onEditSectionSubmit={handleEditSubmit}
onDuplicateSubmit={handleDuplicateSectionSubmit}
isSectionsExpanded={isSectionsExpanded}
onNewSubsectionSubmit={handleNewSubsectionSubmit}
moveSection={moveSection}
finalizeSectionOrder={finalizeSectionOrder}
ref={listRef}
>
{section.childInfo.children.map((subsection) => (
<SubsectionCard
key={subsection.id}
section={section}
subsection={subsection}
savingStatus={savingStatus}
onOpenPublishModal={openPublishModal}
onOpenDeleteModal={openDeleteModal}
onEditSubmit={handleEditSubmit}
onDuplicateSubmit={handleDuplicateSubsectionSubmit}
ref={listRef}
/>
))}
</SectionCard>
))}
</DndProvider>
<Button
data-testid="new-section-button"
className="mt-4"
Expand Down
53 changes: 53 additions & 0 deletions src/course-outline/CourseOutline.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
fetchCourseSectionQuery,
publishCourseItemQuery,
updateCourseSectionHighlightsQuery,
setSectionOrderListQuery,
} from './data/thunk';
import initializeStore from '../store';
import {
Expand Down Expand Up @@ -123,6 +124,10 @@ describe('<CourseOutline />', () => {
it('adds new section correctly', async () => {
const { findAllByTestId } = render(<RootWrapper />);
let element = await findAllByTestId('section-card');
window.HTMLElement.prototype.getBoundingClientRect = jest.fn(() => ({
top: 0,
bottom: 4000,
}));
expect(element.length).toBe(4);

axiosMock
Expand All @@ -146,6 +151,10 @@ describe('<CourseOutline />', () => {
const [section] = await findAllByTestId('section-card');
let subsections = await within(section).findAllByTestId('subsection-card');
expect(subsections.length).toBe(1);
window.HTMLElement.prototype.getBoundingClientRect = jest.fn(() => ({
top: 0,
bottom: 4000,
}));

axiosMock
.onPost(getXBlockBaseApiUrl())
Expand All @@ -159,6 +168,7 @@ describe('<CourseOutline />', () => {

subsections = await within(section).findAllByTestId('subsection-card');
expect(subsections.length).toBe(2);
expect(window.HTMLElement.prototype.scrollIntoView).toBeCalled();
});

it('render error alert after failed reindex correctly', async () => {
Expand Down Expand Up @@ -488,4 +498,47 @@ describe('<CourseOutline />', () => {

expect(getByRole('button', { name: '5 Section highlights' })).toBeInTheDocument();
});

it('check section list is ordered successfully', async () => {
const { getAllByTestId } = render(<RootWrapper />);
const courseBlockId = courseOutlineIndexMock.courseStructure.id;
let { children } = courseOutlineIndexMock.courseStructure.childInfo;
children = children.splice(2, 0, children.splice(0, 1)[0]);

axiosMock
.onPut(getEnableHighlightsEmailsApiUrl(courseBlockId), children)
.reply(200);

await executeThunk(setSectionOrderListQuery(courseBlockId, children, () => {}), store.dispatch);

await waitFor(() => {
expect(getAllByTestId('section-card')).toHaveLength(4);
const newSections = getAllByTestId('section-card');
for (let i; i < children.length; i++) {
expect(children[i].id === newSections[i].id);
}
});
});

it('check section list is restored to original order when API call fails', async () => {
const { getAllByTestId } = render(<RootWrapper />);
const courseBlockId = courseOutlineIndexMock.courseStructure.id;
const { children } = courseOutlineIndexMock.courseStructure.childInfo;
const newChildren = children.splice(2, 0, children.splice(0, 1)[0]);

axiosMock
.onPut(getEnableHighlightsEmailsApiUrl(courseBlockId), undefined)
.reply(500);

await executeThunk(setSectionOrderListQuery(courseBlockId, undefined, () => children), store.dispatch);

await waitFor(() => {
expect(getAllByTestId('section-card')).toHaveLength(4);
const newSections = getAllByTestId('section-card');
for (let i; i < children.length; i++) {
expect(children[i].id === newSections[i].id);
expect(newChildren[i].id !== newSections[i].id);
}
});
});
});
15 changes: 15 additions & 0 deletions src/course-outline/data/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -296,3 +296,18 @@ export async function addNewCourseItem(parentLocator, category, displayName) {

return data;
}

/**
* Set order for the list of the sections
* @param {string} courseId
* @param {Array<string>} children list of sections id's
* @returns {Promise<Object>}
*/
export async function setSectionOrderList(courseId, children) {
const { data } = await getAuthenticatedHttpClient()
.put(getEnableHighlightsEmailsApiUrl(courseId), {
children,
});

return data;
}
Loading