Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
48 changes: 41 additions & 7 deletions src/container-comparison/CompareContainersWidget.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,6 @@ describe('CompareContainersWidget', () => {
expect(await screen.findByRole('button', { name: 'subsection block 00' })).toBeInTheDocument();
expect(await screen.findByRole('button', { name: 'subsection block 0' })).toBeInTheDocument();

const removedRows = await screen.findAllByText('This unit was removed');
// clicking on removed or added rows does not updated the page.
await user.click(removedRows[0]);
// Still in same page
expect(await screen.findByRole('button', { name: 'subsection block 00' })).toBeInTheDocument();
expect(await screen.findByRole('button', { name: 'subsection block 0' })).toBeInTheDocument();

// Back breadcrumb
const backbtns = await screen.findAllByRole('button', { name: 'Back' });
expect(backbtns.length).toEqual(2);
Expand All @@ -94,6 +87,47 @@ describe('CompareContainersWidget', () => {
expect(await screen.findByRole('button', { name: 'subsection block 0' })).toBeInTheDocument();
});

test('should show removed container diff state', async () => {
// mocks title
axiosMock.onGet(getLibraryContainerApiUrl(mockGetContainerMetadata.sectionId)).reply(200, { publishedDisplayName: 'Test Title' });
axiosMock.onGet(
getLibraryContainerApiUrl('lct:org1:Demo_course_generated:subsection:subsection-0'),
).reply(200, { publishedDisplayName: 'subsection block 0' });

const user = userEvent.setup();
render(<CompareContainersWidget
upstreamBlockId={mockGetContainerMetadata.sectionId}
downstreamBlockId={mockGetCourseContainerChildren.sectionId}
/>);
expect((await screen.findAllByText('Test Title')).length).toEqual(2);
// left i.e. before side block
const block = await screen.findByText('subsection block 00');
await user.click(block);

const removedRows = await screen.findAllByText('This unit was removed');
await user.click(removedRows[0]);

expect(await screen.findByText('This unit has been removed')).toBeInTheDocument();
});

test('should show new added container diff state', async () => {
// mocks title
axiosMock.onGet(getLibraryContainerApiUrl(mockGetContainerMetadata.sectionId)).reply(200, { publishedDisplayName: 'Test Title' });
axiosMock.onGet(
getLibraryContainerApiUrl('lct:org1:Demo_course_generated:subsection:subsection-0'),
).reply(200, { publishedDisplayName: 'subsection block 0' });

const user = userEvent.setup();
render(<CompareContainersWidget
upstreamBlockId={mockGetContainerMetadata.sectionId}
downstreamBlockId="block-v1:UNIX+UX1+2025_T3+type@section+block@0-new"
/>);
const blocks = await screen.findAllByText('This subsection will be added in the new version');
await user.click(blocks[0]);

expect(await screen.findByText(/this subsection is new/i)).toBeInTheDocument();
});

test('should show alert if the only change is a single text component with local overrides', async () => {
const url = getLibraryContainerApiUrl(mockGetContainerMetadata.sectionId);
axiosMock.onGet(url).reply(200, { publishedDisplayName: 'Test Title' });
Expand Down
93 changes: 75 additions & 18 deletions src/container-comparison/CompareContainersWidget.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ import {
Alert,
Breadcrumb, Button, Card, Icon, Stack,
} from '@openedx/paragon';
import { ArrowBack } from '@openedx/paragon/icons';
import { ArrowBack, Add, Delete } from '@openedx/paragon/icons';
import { FormattedMessage, useIntl } from '@edx/frontend-platform/i18n';

import { ContainerType } from '@src/generic/key-utils';
import { ContainerType, getBlockType } from '@src/generic/key-utils';
import ErrorAlert from '@src/generic/alert-error';
import { LoadingSpinner } from '@src/generic/Loading';
import { useContainer, useContainerChildren } from '@src/library-authoring/data/apiHooks';
Expand All @@ -16,7 +16,9 @@ import { BoldText } from '@src/utils';
import ChildrenPreview from './ChildrenPreview';
import ContainerRow from './ContainerRow';
import { useCourseContainerChildren } from './data/apiHooks';
import { ContainerChild, ContainerChildBase, WithState } from './types';
import {
ContainerChild, ContainerChildBase, ContainerState, WithState,
} from './types';
import { diffPreviewContainerChildren, isRowClickable } from './utils';
import messages from './messages';

Expand All @@ -30,6 +32,7 @@ interface Props extends ContainerInfoProps {
parent: ContainerInfoProps[];
onRowClick: (row: WithState<ContainerChild>) => void;
onBackBtnClick: () => void;
state?: ContainerState;
// This two props are used to show an alert for the changes to text components with local overrides.
// They may be removed in the future.
localUpdateAlertCount: number;
Expand All @@ -43,6 +46,7 @@ const CompareContainersWidgetInner = ({
upstreamBlockId,
downstreamBlockId,
parent,
state,
onRowClick,
onBackBtnClick,
localUpdateAlertCount,
Expand All @@ -62,17 +66,41 @@ const CompareContainersWidgetInner = ({
} = useContainer(upstreamBlockId);

const result = useMemo(() => {
if (!data || !libData) {
if ((!data || !libData) && !['added', 'removed'].includes(state || '')) {
return [undefined, undefined];
}
return diffPreviewContainerChildren(data.children, libData as ContainerChildBase[]);

let libChildren = libData as ContainerChildBase[] || [];
if (state === 'removed') {
// There is the case in which the item is removed, but it still exists
// in the library, in that case the query will bring its children,
// but we must put it empty so that the status of all the children of
// the downstream are 'removed'
libChildren = [];
}

return diffPreviewContainerChildren(data?.children || [], libChildren);
Comment thread
ChrisChV marked this conversation as resolved.
Outdated
}, [data, libData]);

const renderBeforeChildren = useCallback(() => {
if (!result[0]) {
if (!result[0] && state !== 'added') {
return <div className="m-auto"><LoadingSpinner /></div>;
}

if (state === 'added') {
return (
<Stack className="align-items-center justify-content-center bg-light-200 text-gray-800">
<Icon src={Add} className="big-icon" />
<FormattedMessage
{...messages.newContainer}
values={{
containerType: getBlockType(upstreamBlockId),
}}
/>
</Stack>
);
}

return result[0]?.map((child) => (
<ContainerRow
key={child.id}
Expand All @@ -87,10 +115,24 @@ const CompareContainersWidgetInner = ({
}, [result]);

const renderAfterChildren = useCallback(() => {
if (!result[1]) {
if (!result[1] && state !== 'removed') {
return <div className="m-auto"><LoadingSpinner /></div>;
}

if (state === 'removed') {
return (
<Stack className="align-items-center justify-content-center bg-light-200 text-gray-800">
<Icon src={Delete} className="big-icon" />
<FormattedMessage
{...messages.deletedContainer}
values={{
containerType: getBlockType(upstreamBlockId),
}}
/>
</Stack>
);
}

return result[1]?.map((child) => (
<ContainerRow
key={child.id}
Expand Down Expand Up @@ -134,12 +176,21 @@ const CompareContainersWidgetInner = ({
);
}, [parent]);

if (isError || isLibError || isContainerTitleError) {
let beforeTitle: string | undefined | null = data?.displayName;
let afterTitle = containerData?.publishedDisplayName;
if (!data && state === 'added') {
beforeTitle = containerData?.publishedDisplayName;
}
if (!containerData && state === 'removed') {
afterTitle = data?.displayName;
}

if (isError || (isLibError && state !== 'removed') || (isContainerTitleError && state !== 'removed')) {
return <ErrorAlert error={error || libError || containerTitleError} />;
}

return (
<div className="row justify-content-center">
<div className="compare-changes-widget row justify-content-center">
{localUpdateAlertCount > 0 && (
<Alert variant="info">
<FormattedMessage
Expand All @@ -153,15 +204,15 @@ const CompareContainersWidgetInner = ({
</Alert>
)}
<div className="col col-6 p-1">
<Card className="p-4">
<ChildrenPreview title={getTitleComponent(data?.displayName)} side="Before">
<Card className="compare-card p-4">
<ChildrenPreview title={getTitleComponent(beforeTitle)} side="Before">
{renderBeforeChildren()}
</ChildrenPreview>
</Card>
</div>
<div className="col col-6 p-1">
<Card className="p-4">
<ChildrenPreview title={getTitleComponent(containerData?.publishedDisplayName)} side="After">
<Card className="compare-card p-4">
<ChildrenPreview title={getTitleComponent(afterTitle)} side="After">
{renderAfterChildren()}
</ChildrenPreview>
</Card>
Expand All @@ -181,12 +232,14 @@ export const CompareContainersWidget = ({
isReadyToSyncIndividually = false,
}: ContainerInfoProps) => {
const [currentContainerState, setCurrentContainerState] = useState<ContainerInfoProps & {
parent: ContainerInfoProps[];
state?: ContainerState;
parent:(ContainerInfoProps & { state?: ContainerState })[];
}>({
upstreamBlockId,
downstreamBlockId,
parent: [],
});
upstreamBlockId,
downstreamBlockId,
parent: [],
state: 'modified',
});

const { data } = useCourseContainerChildren(downstreamBlockId, true);
let localUpdateAlertBlockName = '';
Expand All @@ -213,9 +266,11 @@ export const CompareContainersWidget = ({
setCurrentContainerState((prev) => ({
upstreamBlockId: row.id!,
downstreamBlockId: row.downstreamId!,
state: row.state,
parent: [...prev.parent, {
upstreamBlockId: prev.upstreamBlockId,
downstreamBlockId: prev.downstreamBlockId,
state: prev.state,
}],
}));
};
Expand All @@ -230,6 +285,7 @@ export const CompareContainersWidget = ({
return {
upstreamBlockId: prevParent!.upstreamBlockId,
downstreamBlockId: prevParent!.downstreamBlockId,
state: prevParent!.state,
parent: prev.parent.slice(0, -1),
};
});
Expand All @@ -240,6 +296,7 @@ export const CompareContainersWidget = ({
upstreamBlockId={currentContainerState.upstreamBlockId}
downstreamBlockId={currentContainerState.downstreamBlockId}
parent={currentContainerState.parent}
state={currentContainerState.state}
onRowClick={onRowClick}
onBackBtnClick={onBackBtnClick}
localUpdateAlertCount={localUpdateAlertCount}
Expand Down
14 changes: 0 additions & 14 deletions src/container-comparison/ContainerRow.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,20 +29,6 @@ describe('<ContainerRow />', () => {
)).toBeInTheDocument();
});

test('is not clickable when state !== modified', async () => {
const onClick = jest.fn();
render(<ContainerRow
title="Test title"
containerType="subsection"
side="Before"
state="removed"
onClick={onClick}
/>);
const titleDiv = await screen.findByText('Test title');
const card = titleDiv.closest('.clickable');
expect(card).toBe(null);
});

test('calls onClick when clicked', async () => {
const onClick = jest.fn();
const user = userEvent.setup();
Expand Down
7 changes: 4 additions & 3 deletions src/container-comparison/data/api.mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import * as unitApi from '@src/course-unit/data/api';
* This mock returns a fixed response for the given container ID.
*/
export async function mockGetCourseContainerChildren(containerId: string): Promise<CourseContainerChildrenData> {
const numChildren: number = 3;
let numChildren: number = 3;
let blockType: string;
let displayName: string;
let upstreamReadyToSyncChildrenInfo: UpstreamReadyToSyncChildrenInfo[] = [];
Expand Down Expand Up @@ -61,8 +61,9 @@ export async function mockGetCourseContainerChildren(containerId: string): Promi
case mockGetCourseContainerChildren.subsectionIdLoading:
return new Promise(() => { });
default:
blockType = 'unit';
displayName = 'subsection block 00';
blockType = 'section';
displayName = 'section block 00';
numChildren = 0;
break;
}
const children = Array(numChildren).fill(mockGetCourseContainerChildren.childTemplate).map((child, idx) => (
Expand Down
8 changes: 6 additions & 2 deletions src/container-comparison/data/apiHooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ export const containerComparisonQueryKeys = {
/**
* Key for a single container
*/
container: (usageKey: string, getUpstreamInfo: boolean) => {
container: (getUpstreamInfo: boolean, usageKey?: string) => {
if (usageKey === undefined) {
return [undefined, undefined, getUpstreamInfo.toString()];
}
const courseKey = getCourseKey(usageKey);
return [...containerComparisonQueryKeys.course(courseKey), usageKey, getUpstreamInfo.toString()];
},
Expand All @@ -21,6 +24,7 @@ export const useCourseContainerChildren = (usageKey?: string, getUpstreamInfo?:
useQuery({
enabled: !!usageKey,
queryFn: () => getCourseContainerChildren(usageKey!, getUpstreamInfo),
queryKey: containerComparisonQueryKeys.container(usageKey!, getUpstreamInfo || false),
// If we first get data with a valid `usageKey` and then the `usageKey` changes to undefinded, an error occurs.
Comment thread
ChrisChV marked this conversation as resolved.
Outdated
queryKey: containerComparisonQueryKeys.container(getUpstreamInfo || false, usageKey),
})
);
10 changes: 10 additions & 0 deletions src/container-comparison/index.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
.compare-changes-widget {
.compare-card {
min-height: 350px;
}

.big-icon {
height: 68px;
width: 68px;
}
}
10 changes: 10 additions & 0 deletions src/container-comparison/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,16 @@ const messages = defineMessages({
defaultMessage: 'The only change is to {count, plural, one {text block <b>{blockName}</b> which has been edited} other {<b>{count} text blocks</b> which have been edited}} in this course. Accepting will not remove local edits.',
description: 'Alert to show if the only change is on text components with local overrides.',
},
newContainer: {
id: 'course-authoring.container-comparison.new-container.text',
defaultMessage: 'This {containerType} is new',
description: 'Text to show in the comparison when a container is new.',
},
deletedContainer: {
id: 'course-authoring.container-comparison.deleted-container.text',
defaultMessage: 'This {containerType} has been removed',
description: 'Text to show in the comparison when a container is removed.',
},
});

export default messages;
2 changes: 1 addition & 1 deletion src/container-comparison/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ export function diffPreviewContainerChildren<A extends CourseContainerChildBase,
}

export function isRowClickable(state?: ContainerState, blockType?: ContainerType) {
return state === 'modified' && blockType && [
return state && blockType && ['modified', 'added', 'removed'].includes(state) && [
ContainerType.Section,
ContainerType.Subsection,
ContainerType.Unit,
Expand Down
1 change: 1 addition & 0 deletions src/course-outline/section-card/SectionCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ const SectionCard = ({
upstreamBlockVersionSynced: upstreamInfo.versionSynced,
isReadyToSyncIndividually: upstreamInfo.isReadyToSyncIndividually,
isContainer: true,
blockType: 'section',
};
}, [upstreamInfo]);

Expand Down
1 change: 1 addition & 0 deletions src/course-outline/subsection-card/SubsectionCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ const SubsectionCard = ({
upstreamBlockVersionSynced: upstreamInfo.versionSynced,
isReadyToSyncIndividually: upstreamInfo.isReadyToSyncIndividually,
isContainer: true,
blockType: 'subsection',
};
}, [upstreamInfo]);

Expand Down
1 change: 1 addition & 0 deletions src/course-outline/unit-card/UnitCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ const UnitCard = ({
upstreamBlockVersionSynced: upstreamInfo.versionSynced,
isReadyToSyncIndividually: upstreamInfo.isReadyToSyncIndividually,
isContainer: true,
blockType: 'unit',
};
}, [upstreamInfo]);

Expand Down
1 change: 1 addition & 0 deletions src/index.scss
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
@import "group-configurations/GroupConfigurations";
@import "optimizer-page/scan-results/ScanResults";
@import "legacy-libraries-migration/";
@import "container-comparison/";

// To apply the glow effect to the selected Section/Subsection, in the Course Outline
div.row:has(> div > div.highlight) {
Expand Down