diff --git a/src/constants.ts b/src/constants.ts index 53614d1c4c..eb95ee3460 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -20,6 +20,9 @@ export const DECODE_ROUTES = { ], REDIRECT_HOME: 'home/:courseId', REDIRECT_SURVEY: 'survey/:courseId', + PATHWAY_OUTLINE: '/pathway/:pathwayId/outline', + PATHWAY_PROGRESS: '/pathway/:pathwayId/progress', + PATHWAY_ACHIEVEMENTS: '/pathway/:pathwayId/achievements', } as const satisfies Readonly<{ [k: string]: string | readonly string[] }>; export const ROUTES = { diff --git a/src/index.jsx b/src/index.jsx index 960b842c51..40b5323c02 100755 --- a/src/index.jsx +++ b/src/index.jsx @@ -35,6 +35,9 @@ import DecodePageRoute from './decode-page-route'; import { DECODE_ROUTES, ROUTES } from './constants'; import PreferencesUnsubscribe from './preferences-unsubscribe'; import PageNotFound from './generic/PageNotFound'; +import { PathwayOutline } from './pathways/PathwayOutline'; +import { PathwayProgress } from './pathways/pathway-progress/PathwayProgress'; +import { PathwayAchievements } from './pathways/pathways-achievements/PathwayAchievements'; const queryClient = createQueryClient(); @@ -133,6 +136,24 @@ subscribe(APP_READY, () => { )} /> ))} + + )} + /> + + )} + /> + + )} + /> diff --git a/src/index.scss b/src/index.scss index d65688336d..fa84cf3b79 100755 --- a/src/index.scss +++ b/src/index.scss @@ -465,3 +465,7 @@ @import "course-tabs/course-tabs-navigation.scss"; @import "courseware/course/sidebar/common/SidebarBase.scss"; @import "courseware/course/sidebar/sidebars/course-outline/CourseOutlineTray.scss"; +@import "pathways/pathways-strip/CoursePathwaysStrip.scss"; +@import "pathways/pathway-tabs/PathwayTabsNavigation.scss"; +@import "pathways/pathway-progress/progress-ring/PathwayProgressRing.scss"; +@import "pathways/pathway-progress/pathway-completion/PathwayProgressDonut.scss"; diff --git a/src/index.test.jsx b/src/index.test.jsx index 86589c7af6..9c52891394 100644 --- a/src/index.test.jsx +++ b/src/index.test.jsx @@ -49,6 +49,9 @@ jest.mock('./course-home/discussion-tab/DiscussionTab', () => 'Discussion Tab'); jest.mock('./course-home/progress-tab/ProgressTab', () => 'Progress Tab'); jest.mock('./courseware/course/course-exit', () => ({ CourseExit: 'Course Exit' })); jest.mock('./courseware', () => 'Courseware Container'); +jest.mock('./pathways/PathwayOutline', () => ({ PathwayOutline: 'Pathway Outline' })); +jest.mock('./pathways/pathway-progress/PathwayProgress', () => ({ PathwayProgress: 'Pathway Progress' })); +jest.mock('./pathways/pathways-achievements/PathwayAchievements', () => ({ PathwayAchievements: 'Pathway Achievements' })); describe('app registry', () => { let getElement; diff --git a/src/pathways/PathwayOutline.tsx b/src/pathways/PathwayOutline.tsx new file mode 100644 index 0000000000..c4e88ad1cd --- /dev/null +++ b/src/pathways/PathwayOutline.tsx @@ -0,0 +1,19 @@ +import { useParams } from 'react-router-dom'; +import { usePathway } from './data/apiHooks'; +import { TabPage } from './tab-page/TabPage'; + +export const PathwayOutline = () => { + const { pathwayId } = useParams(); + + const metadataQuery = usePathway(pathwayId); + + return ( + + Outline + + ); +}; diff --git a/src/pathways/data/__fixtures__/pathways.ts b/src/pathways/data/__fixtures__/pathways.ts new file mode 100644 index 0000000000..20c253a213 --- /dev/null +++ b/src/pathways/data/__fixtures__/pathways.ts @@ -0,0 +1,158 @@ +import type { + PathwayAchievementData, PathwayData, PathwayProgressData, PathwaysByCourse, +} from '../types'; + +export const dataEngineering: PathwayData = { + pathway: { + id: 'pathway-1', + content: { displayName: 'Data Engineering Fundamentals' }, + itemCount: 6, + category: 'bootcamp', + categoryLabel: 'Bootcamp', + }, + progress: { completedItemCount: 3 }, + provider: { name: 'MIT OpenCourseWare' }, +}; + +export const machineLearning: PathwayData = { + pathway: { + id: 'pathway-2', + content: { displayName: 'Introduction to Machine Learning' }, + itemCount: 12, + category: 'tutorial', + categoryLabel: 'Tutorial', + categoryBackgroundColor: '#FCE4F3', + categoryTextColor: '#9B1766', + }, + progress: { completedItemCount: 0 }, + provider: { name: 'Stanford' }, +}; + +export const loremIpsum: PathwayData = { + pathway: { + id: 'pathway-3', + content: { displayName: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod' }, + itemCount: 4, + category: 'tutorial', + categoryLabel: 'Tutorial', + }, + progress: { completedItemCount: 1 }, + provider: { name: 'Stanford' }, +}; + +export const sedUt: PathwayData = { + pathway: { + id: 'pathway-4', + content: { displayName: 'Sed ut perspiciatis unde omnis iste natus' }, + itemCount: 3, + category: 'tutorial', + categoryLabel: 'Tutorial', + }, + progress: { completedItemCount: 0 }, +}; + +export const nemoEnim: PathwayData = { + pathway: { + id: 'pathway-5', + content: { displayName: 'Nemo enim ipsam voluptatem' }, + itemCount: 5, + category: 'certificate', + categoryLabel: 'Certificate', + }, + progress: { completedItemCount: 2 }, +}; + +export const courseIdWithPathways = 'course-v1:edX+DemoX+Demo_Course'; +export const courseIdWithManyPathways = 'course-v1:edX+Many+Pathways'; +export const courseIdWithoutPathways = 'course-v1:edX+No+Pathways'; + +export const pathwaysByCourse: PathwaysByCourse = { + [courseIdWithPathways]: [dataEngineering, machineLearning], + [courseIdWithManyPathways]: [dataEngineering, machineLearning, loremIpsum, sedUt, nemoEnim], +}; + +export const dataEngineeringProgress: PathwayProgressData = { + id: 'pathway-1', + itemCount: 6, + completedItemCount: 3, + grades: [ + { + displayName: 'Introduction to Data Engineering', + progress: 100, + passGrade: 70, + currentGrade: 85, + detailsUrl: '/course/course-v1:edX+DE101+2026/progress', + }, + { + displayName: 'Data Pipelines', + progress: 40, + passGrade: 70, + currentGrade: 30, + detailsUrl: '/course/course-v1:edX+DE102+2026/progress', + }, + { + displayName: 'Data Warehousing', + progress: 65, + passGrade: 60, + currentGrade: 55, + detailsUrl: '/course/course-v1:edX+DE103+2026/progress', + }, + { + displayName: 'Stream Processing', + progress: 0, + passGrade: 70, + currentGrade: 0, + detailsUrl: '/course/course-v1:edX+DE104+2026/progress', + }, + { + displayName: 'Machine Learning Operations for Production Systems on Kubernetes', + progress: 20, + passGrade: 70, + currentGrade: 15, + detailsUrl: '/course/course-v1:edX+DE105+2026/progress', + }, + ], +}; + +export const dataEngineeringAchievements: PathwayAchievementData[] = [ + { + credentialId: 'a1b2c3d4e5f60718293a4b5c6d7e8f90', + displayName: 'Data Engineering Fundamentals', + providerName: 'MIT OpenCourseWare', + completedOn: '2026-08-11', + certificateUrl: '/certificates/a1b2c3d4e5f60718293a4b5c6d7e8f90', + isOverarching: true, + }, + { + credentialId: 'b2c3d4e5f60718293a4b5c6d7e8f90a1', + displayName: 'Introduction to Data Engineering with Python, SQL and Cloud Tools', + providerName: 'MIT OpenCourseWare', + completedOn: '2026-07-02', + certificateUrl: '/certificates/b2c3d4e5f60718293a4b5c6d7e8f90a1', + isOverarching: false, + }, + { + credentialId: 'c3d4e5f60718293a4b5c6d7e8f90a1b2', + displayName: 'Data Pipelines', + providerName: 'MIT OpenCourseWare', + completedOn: '2026-07-20', + certificateUrl: '/certificates/c3d4e5f60718293a4b5c6d7e8f90a1b2', + isOverarching: false, + }, + { + credentialId: 'd4e5f60718293a4b5c6d7e8f90a1b2c3', + displayName: 'Data Warehousing', + providerName: 'MIT OpenCourseWare', + completedOn: '2026-07-28', + certificateUrl: '/certificates/d4e5f60718293a4b5c6d7e8f90a1b2c3', + isOverarching: false, + }, + { + credentialId: 'e5f60718293a4b5c6d7e8f90a1b2c3d4', + displayName: 'Stream Processing', + providerName: 'MIT OpenCourseWare', + completedOn: '2026-08-05', + certificateUrl: '/certificates/e5f60718293a4b5c6d7e8f90a1b2c3d4', + isOverarching: false, + }, +]; diff --git a/src/pathways/data/api.test.ts b/src/pathways/data/api.test.ts new file mode 100644 index 0000000000..92fc447298 --- /dev/null +++ b/src/pathways/data/api.test.ts @@ -0,0 +1,10 @@ +import { getPathwaysByCourse } from './api'; + +describe('course-pathways api', () => { + describe('getPathwaysByCourse', () => { + // Until the backend exists, no course has pathways + it('returns an empty map', async () => { + await expect(getPathwaysByCourse(['course-v1:edX+DemoX+Demo_Course'])).resolves.toEqual({}); + }); + }); +}); diff --git a/src/pathways/data/api.ts b/src/pathways/data/api.ts new file mode 100644 index 0000000000..fa0771431f --- /dev/null +++ b/src/pathways/data/api.ts @@ -0,0 +1,40 @@ +import type { + PathwayAchievementData, PathwayData, PathwayProgressData, PathwaysByCourse, +} from './types'; + +// TODO The backend is missing. +// This endpoint should receive a list of course IDs and return a map +// containing the pathways in which the learner is enrolled for each course. +// The response must be mapped here to the `PathwayData` shape. +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export const getPathwaysByCourse = async (_courseIds: string[]): Promise => ({}); + +// TODO The backend is missing. +// This endpoint should receive a pathway ID and return that pathway, with the learner's +// progress in it. A missing pathway or a learner without access must make the request fail. +// The response must be mapped here to the `PathwayData` shape. +// Until then, every request fails. +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export const getPathway = async (_pathwayId: string): Promise => { + throw new Error('The pathway backend is missing'); +}; + +// TODO The backend is missing. +// This endpoint should receive a pathway ID and return the learner's progress in that pathway, +// with the grade of each of its items. +// The response must be mapped here to the `PathwayProgressData` shape. +// Until then, every request fails. +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export const getPathwayProgress = async (_pathwayId: string): Promise => { + throw new Error('The pathway progress backend is missing'); +}; + +// TODO The backend is missing. +// This endpoint should receive a pathway ID and return the achievements the learner +// has earned in that pathway: the certificate of the pathway itself and those of its items. +// The response must be mapped here to the `PathwayAchievementData` shape. +// Until then, every request fails. +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export const getPathwayAchievements = async (_pathwayId: string): Promise => { + throw new Error('The pathway achievements backend is missing'); +}; diff --git a/src/pathways/data/apiHooks.test.tsx b/src/pathways/data/apiHooks.test.tsx new file mode 100644 index 0000000000..4f8cd25d10 --- /dev/null +++ b/src/pathways/data/apiHooks.test.tsx @@ -0,0 +1,192 @@ +import { renderHook, waitFor } from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; + +import { + getPathway, getPathwayAchievements, getPathwayProgress, getPathwaysByCourse, +} from './api'; +import { + useCoursePathways, usePathway, usePathwayAchievements, usePathwayProgress, +} from './apiHooks'; +import { + courseIdWithPathways, + courseIdWithoutPathways, + dataEngineering, + dataEngineeringAchievements, + dataEngineeringProgress, + machineLearning, + pathwaysByCourse, +} from './__fixtures__/pathways'; + +jest.mock('./api', () => ({ + getPathway: jest.fn(), + getPathwayAchievements: jest.fn(), + getPathwayProgress: jest.fn(), + getPathwaysByCourse: jest.fn(), +})); + +const mockGetPathway = getPathway as jest.MockedFunction; +const mockGetPathwayAchievements = getPathwayAchievements as jest.MockedFunction; +const mockGetPathwayProgress = getPathwayProgress as jest.MockedFunction; +const mockGetPathwaysByCourse = getPathwaysByCourse as jest.MockedFunction; + +const buildWrapper = () => { + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + const wrapper = ({ children }) => ( + {children} + ); + return { wrapper }; +}; + +describe('course-pathways apiHooks', () => { + beforeEach(() => { + mockGetPathway.mockReset(); + mockGetPathwayAchievements.mockReset(); + mockGetPathwayProgress.mockReset(); + mockGetPathwaysByCourse.mockReset(); + }); + + describe('useCoursePathways', () => { + it('requests the pathways of the given course', async () => { + mockGetPathwaysByCourse.mockResolvedValue(pathwaysByCourse); + const { wrapper } = buildWrapper(); + const { result } = renderHook(() => useCoursePathways(courseIdWithPathways), { wrapper }); + + await waitFor(() => expect(result.current.isSuccess).toBe(true)); + expect(mockGetPathwaysByCourse).toHaveBeenCalledWith([courseIdWithPathways]); + }); + + it('returns only the pathways of the given course', async () => { + mockGetPathwaysByCourse.mockResolvedValue(pathwaysByCourse); + const { wrapper } = buildWrapper(); + const { result } = renderHook(() => useCoursePathways(courseIdWithPathways), { wrapper }); + + await waitFor(() => expect(result.current.isSuccess).toBe(true)); + expect(result.current.data).toEqual([dataEngineering, machineLearning]); + }); + + it('returns an empty list when the course has no pathways', async () => { + mockGetPathwaysByCourse.mockResolvedValue(pathwaysByCourse); + const { wrapper } = buildWrapper(); + const { result } = renderHook(() => useCoursePathways(courseIdWithoutPathways), { wrapper }); + + await waitFor(() => expect(result.current.isSuccess).toBe(true)); + expect(result.current.data).toEqual([]); + }); + + it('does not request anything without a course', () => { + const { wrapper } = buildWrapper(); + const { result } = renderHook(() => useCoursePathways(undefined), { wrapper }); + + expect(result.current.fetchStatus).toBe('idle'); + expect(result.current.data).toBeUndefined(); + expect(mockGetPathwaysByCourse).not.toHaveBeenCalled(); + }); + + it('exposes the error when the request fails', async () => { + mockGetPathwaysByCourse.mockRejectedValue(new Error('network error')); + const { wrapper } = buildWrapper(); + const { result } = renderHook(() => useCoursePathways(courseIdWithPathways), { wrapper }); + + await waitFor(() => expect(result.current.isError).toBe(true)); + expect(result.current.data).toBeUndefined(); + }); + }); + + describe('usePathway', () => { + const pathwayId = dataEngineering.pathway.id; + + it('returns the requested pathway', async () => { + mockGetPathway.mockResolvedValue(dataEngineering); + const { wrapper } = buildWrapper(); + const { result } = renderHook(() => usePathway(pathwayId), { wrapper }); + + await waitFor(() => expect(result.current.isSuccess).toBe(true)); + expect(mockGetPathway).toHaveBeenCalledWith(pathwayId); + expect(result.current.data).toEqual(dataEngineering); + }); + + it('does not request anything without a pathway', () => { + const { wrapper } = buildWrapper(); + const { result } = renderHook(() => usePathway(undefined), { wrapper }); + + expect(result.current.fetchStatus).toBe('idle'); + expect(result.current.data).toBeUndefined(); + expect(mockGetPathway).not.toHaveBeenCalled(); + }); + + it('exposes the error when the request fails', async () => { + mockGetPathway.mockRejectedValue(new Error('network error')); + const { wrapper } = buildWrapper(); + const { result } = renderHook(() => usePathway(pathwayId), { wrapper }); + + await waitFor(() => expect(result.current.isError).toBe(true)); + expect(result.current.data).toBeUndefined(); + }); + }); + + describe('usePathwayProgress', () => { + const pathwayId = dataEngineeringProgress.id; + + it('returns the progress in the requested pathway', async () => { + mockGetPathwayProgress.mockResolvedValue(dataEngineeringProgress); + const { wrapper } = buildWrapper(); + const { result } = renderHook(() => usePathwayProgress(pathwayId), { wrapper }); + + await waitFor(() => expect(result.current.isSuccess).toBe(true)); + expect(mockGetPathwayProgress).toHaveBeenCalledWith(pathwayId); + expect(result.current.data).toEqual(dataEngineeringProgress); + }); + + it('does not request anything without a pathway', () => { + const { wrapper } = buildWrapper(); + const { result } = renderHook(() => usePathwayProgress(undefined), { wrapper }); + + expect(result.current.fetchStatus).toBe('idle'); + expect(result.current.data).toBeUndefined(); + expect(mockGetPathwayProgress).not.toHaveBeenCalled(); + }); + + it('exposes the error when the request fails', async () => { + mockGetPathwayProgress.mockRejectedValue(new Error('network error')); + const { wrapper } = buildWrapper(); + const { result } = renderHook(() => usePathwayProgress(pathwayId), { wrapper }); + + await waitFor(() => expect(result.current.isError).toBe(true)); + expect(result.current.data).toBeUndefined(); + }); + }); + + describe('usePathwayAchievements', () => { + const pathwayId = dataEngineering.pathway.id; + + it('returns the achievements earned in the requested pathway', async () => { + mockGetPathwayAchievements.mockResolvedValue(dataEngineeringAchievements); + const { wrapper } = buildWrapper(); + const { result } = renderHook(() => usePathwayAchievements(pathwayId), { wrapper }); + + await waitFor(() => expect(result.current.isSuccess).toBe(true)); + expect(mockGetPathwayAchievements).toHaveBeenCalledWith(pathwayId); + expect(result.current.data).toEqual(dataEngineeringAchievements); + }); + + it('does not request anything without a pathway', () => { + const { wrapper } = buildWrapper(); + const { result } = renderHook(() => usePathwayAchievements(undefined), { wrapper }); + + expect(result.current.fetchStatus).toBe('idle'); + expect(result.current.data).toBeUndefined(); + expect(mockGetPathwayAchievements).not.toHaveBeenCalled(); + }); + + it('exposes the error when the request fails', async () => { + mockGetPathwayAchievements.mockRejectedValue(new Error('network error')); + const { wrapper } = buildWrapper(); + const { result } = renderHook(() => usePathwayAchievements(pathwayId), { wrapper }); + + await waitFor(() => expect(result.current.isError).toBe(true)); + expect(result.current.data).toBeUndefined(); + }); + }); +}); diff --git a/src/pathways/data/apiHooks.ts b/src/pathways/data/apiHooks.ts new file mode 100644 index 0000000000..39b7d93800 --- /dev/null +++ b/src/pathways/data/apiHooks.ts @@ -0,0 +1,44 @@ +import { appId } from '@src/constants'; +import { skipToken, useQuery } from '@tanstack/react-query'; + +import { + getPathway, getPathwayAchievements, getPathwayProgress, getPathwaysByCourse, +} from './api'; +import type { PathwayData } from './types'; + +export const coursePathwaysQueryKeys = { + all: [appId, 'coursePathways'] as const, + course: (courseId: string) => [...coursePathwaysQueryKeys.all, courseId] as const, +}; + +export const pathwayQueryKeys = { + all: [appId, 'pathway'] as const, + pathway: (pathwayId: string) => [...pathwayQueryKeys.all, pathwayId] as const, + progress: (pathwayId: string) => [...pathwayQueryKeys.pathway(pathwayId), 'progress'] as const, + achievements: (pathwayId: string) => [...pathwayQueryKeys.pathway(pathwayId), 'achievements'] as const, +}; + +// Pathways in which the learner is enrolled that include the given course. +export const useCoursePathways = (courseId?: string) => useQuery({ + queryKey: coursePathwaysQueryKeys.course(courseId!), + queryFn: courseId ? () => getPathwaysByCourse([courseId]) : skipToken, + select: (pathwaysByCourse): PathwayData[] => pathwaysByCourse[courseId!] ?? [], +}); + +// The given pathway, with the learner's progress in it. +export const usePathway = (pathwayId?: string) => useQuery({ + queryKey: pathwayQueryKeys.pathway(pathwayId!), + queryFn: pathwayId ? () => getPathway(pathwayId) : skipToken, +}); + +// The learner's progress in the given pathway. +export const usePathwayProgress = (pathwayId?: string) => useQuery({ + queryKey: pathwayQueryKeys.progress(pathwayId!), + queryFn: pathwayId ? () => getPathwayProgress(pathwayId) : skipToken, +}); + +// The achievements the learner has earned in the given pathway. +export const usePathwayAchievements = (pathwayId?: string) => useQuery({ + queryKey: pathwayQueryKeys.achievements(pathwayId!), + queryFn: pathwayId ? () => getPathwayAchievements(pathwayId) : skipToken, +}); diff --git a/src/pathways/data/types.ts b/src/pathways/data/types.ts new file mode 100644 index 0000000000..ea9a27c1dd --- /dev/null +++ b/src/pathways/data/types.ts @@ -0,0 +1,46 @@ +// The shape the UI needs. The API layer is in charge of mapping the backend response to it. +export interface PathwayData { + pathway: { + id: string; + content: { + displayName: string; + }; + itemCount: number; + category?: string; + categoryLabel?: string; + categoryBackgroundColor?: string; + categoryTextColor?: string; + }; + progress?: { + completedItemCount: number; + }; + provider?: { + name: string; + }; +} + +export interface GradeData { + displayName: string; + progress: number; + passGrade: number; + currentGrade: number; + detailsUrl: string; +} + +export interface PathwayProgressData { + id: string; + itemCount: number; + completedItemCount: number; + grades: GradeData[]; +} + +export interface PathwayAchievementData { + credentialId: string; + displayName: string; + providerName: string; + completedOn: string; + certificateUrl: string; + isOverarching: boolean; +} + +export type PathwaysByCourse = Record; diff --git a/src/pathways/pathway-progress/AchievementsInfo.test.tsx b/src/pathways/pathway-progress/AchievementsInfo.test.tsx new file mode 100644 index 0000000000..5bce970be8 --- /dev/null +++ b/src/pathways/pathway-progress/AchievementsInfo.test.tsx @@ -0,0 +1,31 @@ +import { render, screen } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import { IntlProvider } from '@edx/frontend-platform/i18n'; + +import { AchievementsInfo } from './AchievementsInfo'; + +const renderComponent = (hasAchievements: boolean) => render( + + + + + , +); + +describe('AchievementsInfo', () => { + it('links to the pathway achievements when the learner has some', () => { + renderComponent(true); + + expect(screen.getByText('Achievements available')).toBeInTheDocument(); + expect(screen.getByRole('link', { name: 'View achievements' })) + .toHaveAttribute('href', '/pathway/pathway-1/achievements'); + }); + + it('tells the learner there are no achievements yet, without a link', () => { + renderComponent(false); + + expect(screen.getByText('No achievements earned')).toBeInTheDocument(); + expect(screen.getByText('No certificates earned yet.')).toBeInTheDocument(); + expect(screen.queryByRole('link')).not.toBeInTheDocument(); + }); +}); diff --git a/src/pathways/pathway-progress/AchievementsInfo.tsx b/src/pathways/pathway-progress/AchievementsInfo.tsx new file mode 100644 index 0000000000..507ce83938 --- /dev/null +++ b/src/pathways/pathway-progress/AchievementsInfo.tsx @@ -0,0 +1,41 @@ +import { generatePath, Link } from 'react-router-dom'; + +import { FormattedMessage } from '@edx/frontend-platform/i18n'; +import { Button } from '@openedx/paragon'; + +import { DECODE_ROUTES } from '@src/constants'; + +import messages from './messages'; + +export interface AchievementsInfoProps { + pathwayId: string; + hasAchievements: boolean; +} + +export const AchievementsInfo = ({ pathwayId, hasAchievements }: AchievementsInfoProps) => { + const title = hasAchievements ? messages.achievementsInfoTitle : messages.achievementsInfoEmptyTitle; + const description = hasAchievements + ? messages.achievementsInfoDescription + : messages.achievementsInfoEmptyDescription; + + return ( +
+

+ +

+

+ +

+ {hasAchievements && ( + + )} +
+ ); +}; diff --git a/src/pathways/pathway-progress/PathwayGrades.test.tsx b/src/pathways/pathway-progress/PathwayGrades.test.tsx new file mode 100644 index 0000000000..58ab666f70 --- /dev/null +++ b/src/pathways/pathway-progress/PathwayGrades.test.tsx @@ -0,0 +1,59 @@ +import { render, screen, within } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import { IntlProvider } from '@edx/frontend-platform/i18n'; + +import { dataEngineeringProgress } from '@src/pathways/data/__fixtures__/pathways'; + +import { PathwayGrades } from './PathwayGrades'; + +const { grades } = dataEngineeringProgress; + +const renderComponent = () => render( + + + + + , +); + +const getRow = (displayName: string) => screen.getByRole('row', { name: new RegExp(displayName) }); + +describe('PathwayGrades', () => { + it('shows a row with the progress and grades of each course as percentages', () => { + renderComponent(); + + // The header row plus one row per grade. + expect(screen.getAllByRole('row')).toHaveLength(grades.length + 1); + + const row = within(getRow('Data Pipelines')); + expect(row.getByText('40%')).toBeInTheDocument(); + expect(row.getByText('70%')).toBeInTheDocument(); + expect(row.getByText('30%')).toBeInTheDocument(); + }); + + it('colors the current grade by whether it reaches the pass grade', () => { + renderComponent(); + + // 85% with a 70% pass grade + expect(within(getRow('Introduction to Data Engineering')).getByText('85%')).toHaveClass('text-success'); + // 30% with a 70% pass grade + expect(within(getRow('Data Pipelines')).getByText('30%')).toHaveClass('text-danger'); + }); + + it('shows no current grade for a course without progress', () => { + renderComponent(); + + const row = within(getRow('Stream Processing')); + expect(row.getByText('-')).toBeInTheDocument(); + expect(row.queryByText('0%', { selector: '.text-danger' })).not.toBeInTheDocument(); + }); + + it('links each course to its grade details', () => { + renderComponent(); + + grades.forEach(({ displayName, detailsUrl }) => { + expect(within(getRow(displayName)).getByRole('link', { name: 'View details' })) + .toHaveAttribute('href', detailsUrl); + }); + }); +}); diff --git a/src/pathways/pathway-progress/PathwayGrades.tsx b/src/pathways/pathway-progress/PathwayGrades.tsx new file mode 100644 index 0000000000..9b042fe2b3 --- /dev/null +++ b/src/pathways/pathway-progress/PathwayGrades.tsx @@ -0,0 +1,80 @@ +import { FormattedMessage, useIntl } from '@edx/frontend-platform/i18n'; +import { DataTable } from '@openedx/paragon'; + +import { GradeData } from '@src/pathways/data/types'; + +import { Link } from 'react-router-dom'; +import messages from './messages'; +import { PathwayProgressRing } from './progress-ring/PathwayProgressRing'; + +// The cells are defined outside of `PathwayGrades` so React does not remount them on every render. +const PercentCell = ({ value }: { value: number }) => { + const intl = useIntl(); + return <>{intl.formatNumber(value / 100, { style: 'percent' })}; +}; + +const ProgressCell = ({ value }: { value: number }) => ( + + + + +); + +// Green when the course is passed, red otherwise +const CurrentGradeCell = ({ value, row }: { value: number, row: { original: GradeData } }) => { + if (row.original.progress === 0) { + return <>-; + } + + return ( + = row.original.passGrade ? 'text-success' : 'text-danger'}> + + + ); +}; + +const DetailsCell = ({ row }: { row: { original: GradeData } }) => ( + + + +); + +export const PathwayGrades = ({ grades }: { grades: GradeData[] }) => { + const intl = useIntl(); + + return ( + + + + ); +}; diff --git a/src/pathways/pathway-progress/PathwayProgress.test.tsx b/src/pathways/pathway-progress/PathwayProgress.test.tsx new file mode 100644 index 0000000000..8d6e5b94b8 --- /dev/null +++ b/src/pathways/pathway-progress/PathwayProgress.test.tsx @@ -0,0 +1,73 @@ +import { MemoryRouter, Route, Routes } from 'react-router-dom'; + +import { DECODE_ROUTES } from '@src/constants'; +import { getPathway, getPathwayAchievements, getPathwayProgress } from '@src/pathways/data/api'; +import { + dataEngineering, dataEngineeringAchievements, dataEngineeringProgress, +} from '@src/pathways/data/__fixtures__/pathways'; +import { initializeMockApp, render, screen } from '@src/setupTest'; + +import { PathwayProgress } from './PathwayProgress'; + +// The header is not what is tested here, and it needs the whole platform setup to render. +jest.mock('@src/plugin-slots/HeaderSlot', () => () => null); + +jest.mock('@src/pathways/data/api', () => ({ + getPathway: jest.fn(), + getPathwayAchievements: jest.fn(), + getPathwayProgress: jest.fn(), +})); + +const mockGetPathway = getPathway as jest.MockedFunction; +const mockGetPathwayAchievements = getPathwayAchievements as jest.MockedFunction; +const mockGetPathwayProgress = getPathwayProgress as jest.MockedFunction; + +const pathwayId = dataEngineering.pathway.id; + +const renderComponent = () => render( + + + } /> + + , +); + +describe('PathwayProgress', () => { + beforeAll(() => { + initializeMockApp(); + }); + + beforeEach(() => { + mockGetPathway.mockResolvedValue(dataEngineering); + mockGetPathwayProgress.mockResolvedValue(dataEngineeringProgress); + mockGetPathwayAchievements.mockResolvedValue([]); + }); + + it('shows the completion, grades and achievements of the pathway in the URL', async () => { + renderComponent(); + + expect(await screen.findByRole('heading', { name: 'Bootcamp completion' })).toBeInTheDocument(); + expect(screen.getByRole('img', { name: '3 of 6 items completed' })).toBeInTheDocument(); + expect(screen.getByRole('row', { name: /Data Pipelines/ })).toBeInTheDocument(); + expect(screen.getByText('No achievements earned')).toBeInTheDocument(); + + expect(mockGetPathway).toHaveBeenCalledWith(pathwayId); + expect(mockGetPathwayProgress).toHaveBeenCalledWith(pathwayId); + expect(mockGetPathwayAchievements).toHaveBeenCalledWith(pathwayId); + }); + + it('links to the achievements when the learner has earned some', async () => { + mockGetPathwayAchievements.mockResolvedValue(dataEngineeringAchievements); + renderComponent(); + + expect(await screen.findByRole('link', { name: 'View achievements' })).toBeInTheDocument(); + }); + + it('shows an error instead of the progress when it cannot be loaded', async () => { + mockGetPathwayProgress.mockRejectedValue(new Error('network error')); + renderComponent(); + + expect(await screen.findByText('There was an error loading this pathway.')).toBeInTheDocument(); + expect(screen.queryByRole('heading', { name: 'Bootcamp completion' })).not.toBeInTheDocument(); + }); +}); diff --git a/src/pathways/pathway-progress/PathwayProgress.tsx b/src/pathways/pathway-progress/PathwayProgress.tsx new file mode 100644 index 0000000000..80340ab02f --- /dev/null +++ b/src/pathways/pathway-progress/PathwayProgress.tsx @@ -0,0 +1,63 @@ +import { useParams } from 'react-router-dom'; +import { FormattedMessage } from '@edx/frontend-platform/i18n'; +import { Col, Row, Stack } from '@openedx/paragon'; +import { usePathway, usePathwayAchievements, usePathwayProgress } from '../data/apiHooks'; +import { TabPage } from '../tab-page/TabPage'; +import messages from './messages'; +import { AchievementsInfo } from './AchievementsInfo'; +import { PathwayCompletion } from './pathway-completion/PathwayCompletion'; +import { PathwayGrades } from './PathwayGrades'; + +export const PathwayProgress = () => { + const { pathwayId } = useParams(); + + const metadataQuery = usePathway(pathwayId); + const pathwayProgress = usePathwayProgress(pathwayId); + const pathwayAchievements = usePathwayAchievements(pathwayId); + + const categoryLabel = metadataQuery.data?.pathway.categoryLabel; + + const { + itemCount, + completedItemCount, + grades, + } = pathwayProgress.data ?? {}; + + const hasAchievements = pathwayAchievements.data !== undefined && pathwayAchievements.data.length > 0; + + return ( + + +

+ +

+ + + + +

+ +

+ +
+ + + + + +
+
+
+ ); +}; diff --git a/src/pathways/pathway-progress/messages.ts b/src/pathways/pathway-progress/messages.ts new file mode 100644 index 0000000000..dee1b361f9 --- /dev/null +++ b/src/pathways/pathway-progress/messages.ts @@ -0,0 +1,66 @@ +import { defineMessages } from '@edx/frontend-platform/i18n'; + +const messages = defineMessages({ + progressTitle: { + id: 'learning.pathways.progress.title', + defaultMessage: 'Your Progress', + description: 'Title of the progress section in the progress page', + }, + gradesTitle: { + id: 'learning.pathways.progress.grades.title', + defaultMessage: 'Grades', + description: 'Title of the grades section in the progress page', + }, + gradesCourseColumn: { + id: 'learning.pathways.progress.grades.table.course', + defaultMessage: 'Course', + description: 'Label for the Course column in the grades table', + }, + gradesProgressColumn: { + id: 'learning.pathways.progress.grades.table.progress', + defaultMessage: 'Progress', + description: 'Label for the Progress column in the grades table', + }, + gradesPassGradeColumn: { + id: 'learning.pathways.progress.grades.table.pass-grade', + defaultMessage: 'Pass Grade', + description: 'Label for the Pass Grade column in the grades table', + }, + gradesCurrentGradeColumn: { + id: 'learning.pathways.progress.grades.table.current-grade', + defaultMessage: 'Current Grade', + description: 'Label for the Current Grade column in the grades table', + }, + gradesViewDetails: { + id: 'learning.pathways.progress.grades.table.view-details', + defaultMessage: 'View details', + description: 'Label for the Viewd details links in the grades table', + }, + achievementsInfoEmptyTitle: { + id: 'learning.pathways.progress.achievements-info.empty.title', + defaultMessage: 'No achievements earned', + description: 'Title of the empty state of the achievements info card', + }, + achievementsInfoEmptyDescription: { + id: 'learning.pathways.progress.achievements-info.empty.description', + defaultMessage: 'No certificates earned yet. ', + description: 'Description of the empty state of the achievements info card', + }, + achievementsInfoTitle: { + id: 'learning.pathways.progress.achievements-info.title', + defaultMessage: 'Achievements available', + description: 'Title of the achievements info card', + }, + achievementsInfoDescription: { + id: 'learning.pathways.progress.achievements-info.description', + defaultMessage: "Showcase your certificates on LinkedIn, or your resume today. Access your bootcamp's achievements below.", + description: 'Description of the achievements info card', + }, + achievementsInfoButton: { + id: 'learning.pathways.progress.achievements-info.button', + defaultMessage: 'View achievements', + description: 'Label of the button of the achievements info card', + }, +}); + +export default messages; diff --git a/src/pathways/pathway-progress/pathway-completion/PathwayCompletion.test.tsx b/src/pathways/pathway-progress/pathway-completion/PathwayCompletion.test.tsx new file mode 100644 index 0000000000..e19e87d52e --- /dev/null +++ b/src/pathways/pathway-progress/pathway-completion/PathwayCompletion.test.tsx @@ -0,0 +1,27 @@ +import { render, screen } from '@testing-library/react'; +import { IntlProvider } from '@edx/frontend-platform/i18n'; + +import { PathwayCompletion } from './PathwayCompletion'; + +const renderComponent = () => render( + + + , +); + +describe('PathwayCompletion', () => { + it('names the pathway category in its title and description', () => { + renderComponent(); + + expect(screen.getByRole('heading', { name: 'Bootcamp completion' })).toBeInTheDocument(); + expect( + screen.getByText('This represents how many courses you have completed in this Bootcamp.'), + ).toBeInTheDocument(); + }); + + it('shows the completed items out of the total', () => { + renderComponent(); + + expect(screen.getByRole('img', { name: '3 of 6 items completed' })).toBeInTheDocument(); + }); +}); diff --git a/src/pathways/pathway-progress/pathway-completion/PathwayCompletion.tsx b/src/pathways/pathway-progress/pathway-completion/PathwayCompletion.tsx new file mode 100644 index 0000000000..d12be21654 --- /dev/null +++ b/src/pathways/pathway-progress/pathway-completion/PathwayCompletion.tsx @@ -0,0 +1,31 @@ +import { FormattedMessage } from '@edx/frontend-platform/i18n'; +import messages from './messages'; +import { PathwayProgressDonut } from './PathwayProgressDonut'; + +export interface PathwayCompletionProps { + categoryLabel: string; + completed: number; + total: number; +} + +export const PathwayCompletion = ({ + categoryLabel, + completed, + total, +}: PathwayCompletionProps) => ( +
+
+
+

+ +

+

+ +

+
+
+ +
+
+
+); diff --git a/src/pathways/pathway-progress/pathway-completion/PathwayProgressDonut.scss b/src/pathways/pathway-progress/pathway-completion/PathwayProgressDonut.scss new file mode 100644 index 0000000000..b0d927bf4c --- /dev/null +++ b/src/pathways/pathway-progress/pathway-completion/PathwayProgressDonut.scss @@ -0,0 +1,21 @@ +.learning-pathway-progress-donut { + width: 100%; + max-width: 178px; + + .donut-count, + .donut-label { + fill: var(--pgn-color-primary-500); + font-family: var(--pgn-typography-font-family-sans-serif); + text-anchor: middle; + } + + .donut-count { + font-size: 8px; + font-weight: var(--pgn-typography-font-weight-bold); + } + + .donut-label { + font-size: 3.2px; + font-weight: var(--pgn-typography-font-weight-normal); + } +} diff --git a/src/pathways/pathway-progress/pathway-completion/PathwayProgressDonut.test.tsx b/src/pathways/pathway-progress/pathway-completion/PathwayProgressDonut.test.tsx new file mode 100644 index 0000000000..cda700d7f1 --- /dev/null +++ b/src/pathways/pathway-progress/pathway-completion/PathwayProgressDonut.test.tsx @@ -0,0 +1,52 @@ +import { render, screen } from '@testing-library/react'; +import { IntlProvider } from '@edx/frontend-platform/i18n'; + +import { PathwayProgressDonut } from './PathwayProgressDonut'; + +const renderComponent = (completed: number, total: number) => render( + + + , +); + +const getSegment = (container: HTMLElement) => container.querySelector('.progress-ring-segment'); + +describe('PathwayProgressDonut', () => { + it('shows the completed and total items in its center', () => { + renderComponent(1, 6); + + expect(screen.getByText('1/6')).toBeInTheDocument(); + expect(screen.getByText('completed')).toBeInTheDocument(); + }); + + it('describes the progress to assistive technologies', () => { + renderComponent(1, 6); + + expect(screen.getByRole('img', { name: '1 of 6 items completed' })).toBeInTheDocument(); + }); + + it('fills the share of the ring that is completed', () => { + const { container } = renderComponent(3, 6); + + expect(getSegment(container)).toHaveAttribute('stroke-dasharray', '50 50'); + }); + + it('does not fill the ring when nothing is completed', () => { + const { container } = renderComponent(0, 6); + + expect(getSegment(container)).toBeNull(); + }); + + it('does not fill the ring when the pathway has no items', () => { + const { container } = renderComponent(0, 0); + + expect(getSegment(container)).toBeNull(); + expect(screen.getByText('0/0')).toBeInTheDocument(); + }); + + it('does not fill more than the whole ring', () => { + const { container } = renderComponent(7, 6); + + expect(getSegment(container)).toHaveAttribute('stroke-dasharray', '100 0'); + }); +}); diff --git a/src/pathways/pathway-progress/pathway-completion/PathwayProgressDonut.tsx b/src/pathways/pathway-progress/pathway-completion/PathwayProgressDonut.tsx new file mode 100644 index 0000000000..5dc2bf9e3f --- /dev/null +++ b/src/pathways/pathway-progress/pathway-completion/PathwayProgressDonut.tsx @@ -0,0 +1,28 @@ +import { useIntl } from '@edx/frontend-platform/i18n'; + +import { PathwayProgressRing } from '../progress-ring/PathwayProgressRing'; +import messages from './messages'; + +export interface PathwayProgressDonutProps { + completed: number; + total: number; +} + +export const PathwayProgressDonut = ({ completed, total }: PathwayProgressDonutProps) => { + const intl = useIntl(); + const percentage = total > 0 ? (completed / total) * 100 : 0; + + return ( + + + + ); +}; diff --git a/src/pathways/pathway-progress/pathway-completion/messages.ts b/src/pathways/pathway-progress/pathway-completion/messages.ts new file mode 100644 index 0000000000..f7f36e7f15 --- /dev/null +++ b/src/pathways/pathway-progress/pathway-completion/messages.ts @@ -0,0 +1,26 @@ +import { defineMessages } from '@edx/frontend-platform/i18n'; + +const messages = defineMessages({ + completed: { + id: 'learning.pathways.progress.donut.completed', + defaultMessage: 'completed', + description: 'Label shown below the completed/total count in the center of the pathway progress donut chart', + }, + completedItems: { + id: 'learning.pathways.progress.donut.completedItems', + defaultMessage: '{completed} of {total} items completed', + description: 'Accessible label of the pathway progress donut chart', + }, + completionTitle: { + id: 'learning.pathways.progress.completion.title', + defaultMessage: '{categoryLabel} completion', + description: 'Title of the Completion section', + }, + completionDescription: { + id: 'learning.pathways.progress.completion.description', + defaultMessage: 'This represents how many courses you have completed in this {categoryLabel}.', + description: 'Description of the Completion section', + }, +}); + +export default messages; diff --git a/src/pathways/pathway-progress/progress-ring/PathwayProgressRing.scss b/src/pathways/pathway-progress/progress-ring/PathwayProgressRing.scss new file mode 100644 index 0000000000..6254a5b0ad --- /dev/null +++ b/src/pathways/pathway-progress/progress-ring/PathwayProgressRing.scss @@ -0,0 +1,27 @@ +.learning-pathway-progress-ring { + .progress-ring-track, + .progress-ring-segment { + fill: transparent; + stroke-width: 6px; + } + + .progress-ring-track { + stroke: var(--pgn-color-light-400); + } + + .progress-ring-segment { + stroke: var(--pgn-color-primary-500); + } + + // Small rings, shown next to a value, need a thicker stroke to stay visible. + &.learning-pathway-progress-ring-sm { + flex-shrink: 0; + width: 1.5rem; + height: 1.5rem; + + .progress-ring-track, + .progress-ring-segment { + stroke-width: 9px; + } + } +} diff --git a/src/pathways/pathway-progress/progress-ring/PathwayProgressRing.test.tsx b/src/pathways/pathway-progress/progress-ring/PathwayProgressRing.test.tsx new file mode 100644 index 0000000000..8f5351d468 --- /dev/null +++ b/src/pathways/pathway-progress/progress-ring/PathwayProgressRing.test.tsx @@ -0,0 +1,45 @@ +import { render, screen } from '@testing-library/react'; + +import { PathwayProgressRing } from './PathwayProgressRing'; + +const getSegment = (container: HTMLElement) => container.querySelector('.progress-ring-segment'); + +describe('PathwayProgressRing', () => { + it('fills the given share of the ring', () => { + const { container } = render(); + + expect(getSegment(container)).toHaveAttribute('stroke-dasharray', '25 75'); + }); + + it('does not fill the ring when the percentage is zero', () => { + const { container } = render(); + + expect(getSegment(container)).toBeNull(); + }); + + it('does not fill more than the whole ring', () => { + const { container } = render(); + + expect(getSegment(container)).toHaveAttribute('stroke-dasharray', '100 0'); + }); + + it('draws its children in the center of the ring', () => { + render( + + center + , + ); + + expect(screen.getByText('center')).toBeInTheDocument(); + }); + + it('passes the other props to the svg', () => { + const { container } = render( + , + ); + + const svg = container.querySelector('svg'); + expect(svg).toHaveClass('learning-pathway-progress-ring', 'extra'); + expect(svg).toHaveAttribute('aria-hidden', 'true'); + }); +}); diff --git a/src/pathways/pathway-progress/progress-ring/PathwayProgressRing.tsx b/src/pathways/pathway-progress/progress-ring/PathwayProgressRing.tsx new file mode 100644 index 0000000000..82373a71b6 --- /dev/null +++ b/src/pathways/pathway-progress/progress-ring/PathwayProgressRing.tsx @@ -0,0 +1,43 @@ +import classNames from 'classnames'; +import type { ReactNode, SVGProps } from 'react'; + +// A radius that gives a circumference of 100, so the stroke dash values are percentages. +const RADIUS = 15.91549430918954; +// Strokes start at 3 o'clock; shifting them back a quarter of the circle starts them at 12 o'clock. +const TOP_OFFSET = 25; + +export interface PathwayProgressRingProps extends Omit, 'children'> { + percentage: number; + // Drawn in the center of the ring, in the 42x42 coordinates of its viewBox. + children?: ReactNode; +} + +export const PathwayProgressRing = ({ + percentage, + className, + children, + ...props +}: PathwayProgressRingProps) => { + const filled = Math.min(Math.max(percentage, 0), 100); + + return ( + + + {filled > 0 && ( + + )} + {children} + + ); +}; diff --git a/src/pathways/pathway-tabs/PathwayTabLink.tsx b/src/pathways/pathway-tabs/PathwayTabLink.tsx new file mode 100644 index 0000000000..5ea2ef2f9d --- /dev/null +++ b/src/pathways/pathway-tabs/PathwayTabLink.tsx @@ -0,0 +1,20 @@ +import classNames from 'classnames'; +import { Link } from 'react-router-dom'; + +interface PathwayTabLinkProps { + slug: string; + activeTabSlug?: string; + url: string; + title: string; +} + +export const PathwayTabLink = ({ + slug, activeTabSlug, url, title, +}: PathwayTabLinkProps) => ( + + {title} + +); diff --git a/src/pathways/pathway-tabs/PathwayTabLinksList.test.tsx b/src/pathways/pathway-tabs/PathwayTabLinksList.test.tsx new file mode 100644 index 0000000000..dd8f921ef2 --- /dev/null +++ b/src/pathways/pathway-tabs/PathwayTabLinksList.test.tsx @@ -0,0 +1,33 @@ +import { render, screen } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; + +import { PathwayTabLinksList } from './PathwayTabLinksList'; + +const tabs = [ + { tabId: 'home', title: 'Home', url: '/pathway/pathway-1/home' }, + { tabId: 'progress', title: 'Progress', url: '/pathway/pathway-1/progress' }, + { tabId: 'achievements', title: 'Achievements', url: '/pathway/pathway-1/achievements' }, +]; + +describe('PathwayTabLinksList', () => { + it('renders a link for each tab', () => { + render(, { wrapper: MemoryRouter }); + + expect(screen.getAllByRole('link')).toHaveLength(3); + expect(screen.getByRole('link', { name: 'Progress' })).toHaveAttribute('href', '/pathway/pathway-1/progress'); + }); + + it('highlights only the active tab', () => { + render(, { wrapper: MemoryRouter }); + + expect(screen.getByRole('link', { name: 'Progress' })).toHaveClass('active'); + expect(screen.getByRole('link', { name: 'Home' })).not.toHaveClass('active'); + expect(screen.getByRole('link', { name: 'Achievements' })).not.toHaveClass('active'); + }); + + it('highlights no tab without an active tab', () => { + render(, { wrapper: MemoryRouter }); + + screen.getAllByRole('link').forEach((link) => expect(link).not.toHaveClass('active')); + }); +}); diff --git a/src/pathways/pathway-tabs/PathwayTabLinksList.tsx b/src/pathways/pathway-tabs/PathwayTabLinksList.tsx new file mode 100644 index 0000000000..395a29b5e6 --- /dev/null +++ b/src/pathways/pathway-tabs/PathwayTabLinksList.tsx @@ -0,0 +1,21 @@ +import { PathwayTabLink } from './PathwayTabLink'; +import type { PathwayTabMetadata } from './types'; + +interface PathwayTabLinksListProps { + tabs: PathwayTabMetadata[]; + activeTabSlug?: string; +} + +export const PathwayTabLinksList = ({ tabs, activeTabSlug }: PathwayTabLinksListProps) => ( + <> + {tabs.map(({ url, title, tabId }) => ( + + ))} + +); diff --git a/src/pathways/pathway-tabs/PathwayTabsNavigation.scss b/src/pathways/pathway-tabs/PathwayTabsNavigation.scss new file mode 100644 index 0000000000..81ab94068f --- /dev/null +++ b/src/pathways/pathway-tabs/PathwayTabsNavigation.scss @@ -0,0 +1,16 @@ +.learning-pathway-tabs-navigation { + border-bottom: var(--pgn-size-border-width) solid var(--pgn-color-nav-tabs-base-border-base); + + .nav a, + .nav button { + &:hover { + background-color: var(--pgn-color-light-400); + } + } + + .nav a { + &:not(.active):hover { + border-bottom: none; + } + } +} diff --git a/src/pathways/pathway-tabs/PathwayTabsNavigation.test.tsx b/src/pathways/pathway-tabs/PathwayTabsNavigation.test.tsx new file mode 100644 index 0000000000..2299c3b415 --- /dev/null +++ b/src/pathways/pathway-tabs/PathwayTabsNavigation.test.tsx @@ -0,0 +1,42 @@ +import { render, screen } from '@testing-library/react'; +import { IntlProvider } from '@edx/frontend-platform/i18n'; +import { MemoryRouter } from 'react-router-dom'; + +import { PathwayTabsNavigation } from './PathwayTabsNavigation'; + +const tabs = [ + { tabId: 'home', title: 'Home', url: '/pathway/pathway-1/home' }, + { tabId: 'progress', title: 'Progress', url: '/pathway/pathway-1/progress' }, +]; + +const renderComponent = (activeTabSlug?: string) => render( + + + + + , +); + +describe('PathwayTabsNavigation', () => { + it('renders the tab links inside a labelled navigation', () => { + renderComponent('home'); + + const navigation = screen.getByRole('navigation', { name: 'Pathway Material' }); + expect(navigation).toContainElement(screen.getByRole('link', { name: 'Home' })); + expect(navigation).toContainElement(screen.getByRole('link', { name: 'Progress' })); + }); + + it('renders the links through the pathway tab links slot', () => { + renderComponent('home'); + + const slot = screen.getByTestId('org.openedx.frontend.learning.pathway_tab_links.v1'); + expect(slot).toContainElement(screen.getByRole('link', { name: 'Home' })); + }); + + it('highlights the active tab', () => { + renderComponent('progress'); + + expect(screen.getByRole('link', { name: 'Progress' })).toHaveClass('active'); + expect(screen.getByRole('link', { name: 'Home' })).not.toHaveClass('active'); + }); +}); diff --git a/src/pathways/pathway-tabs/PathwayTabsNavigation.tsx b/src/pathways/pathway-tabs/PathwayTabsNavigation.tsx new file mode 100644 index 0000000000..4e49c5c6b7 --- /dev/null +++ b/src/pathways/pathway-tabs/PathwayTabsNavigation.tsx @@ -0,0 +1,28 @@ +import { useIntl } from '@edx/frontend-platform/i18n'; + +import Tabs from '@src/generic/tabs/Tabs'; +import { PathwayTabLinksSlot } from '@src/plugin-slots/PathwayTabLinksSlot'; +import type { PathwayTabMetadata } from './types'; +import messages from './messages'; + +export interface PathwayTabsNavigationProps { + tabs: PathwayTabMetadata[]; + activeTabSlug?: string; +} + +export const PathwayTabsNavigation = ({ tabs, activeTabSlug }: PathwayTabsNavigationProps) => { + const intl = useIntl(); + + return ( +
+
+ + + +
+
+ ); +}; diff --git a/src/pathways/pathway-tabs/hooks.test.tsx b/src/pathways/pathway-tabs/hooks.test.tsx new file mode 100644 index 0000000000..c46000c931 --- /dev/null +++ b/src/pathways/pathway-tabs/hooks.test.tsx @@ -0,0 +1,24 @@ +import { renderHook } from '@testing-library/react'; +import { IntlProvider } from '@edx/frontend-platform/i18n'; + +import { usePathwayTabs } from './hooks'; + +const wrapper = ({ children }) => {children}; + +describe('usePathwayTabs', () => { + it('returns the pathway tabs with their URLs', () => { + const { result } = renderHook(() => usePathwayTabs('pathway-1'), { wrapper }); + + expect(result.current).toEqual([ + { tabId: 'outline', title: 'Outline', url: '/pathway/pathway-1/outline' }, + { tabId: 'progress', title: 'Progress', url: '/pathway/pathway-1/progress' }, + { tabId: 'achievements', title: 'Achievements', url: '/pathway/pathway-1/achievements' }, + ]); + }); + + it('returns no tabs without a pathway', () => { + const { result } = renderHook(() => usePathwayTabs(undefined), { wrapper }); + + expect(result.current).toEqual([]); + }); +}); diff --git a/src/pathways/pathway-tabs/hooks.ts b/src/pathways/pathway-tabs/hooks.ts new file mode 100644 index 0000000000..c2e8b77853 --- /dev/null +++ b/src/pathways/pathway-tabs/hooks.ts @@ -0,0 +1,26 @@ +import { useMemo } from 'react'; +import { generatePath } from 'react-router-dom'; +import { useIntl } from '@edx/frontend-platform/i18n'; + +import { DECODE_ROUTES } from '@src/constants'; +import type { PathwayTabMetadata } from './types'; +import messages from './messages'; + +const PATHWAY_TABS = [ + // TODO: The Outline Tab title must be the category label + { tabId: 'outline', route: DECODE_ROUTES.PATHWAY_OUTLINE, message: messages.home }, + { tabId: 'progress', route: DECODE_ROUTES.PATHWAY_PROGRESS, message: messages.progress }, + { tabId: 'achievements', route: DECODE_ROUTES.PATHWAY_ACHIEVEMENTS, message: messages.achievements }, +]; + +export const usePathwayTabs = (pathwayId?: string): PathwayTabMetadata[] => { + const intl = useIntl(); + return useMemo(() => { + if (!pathwayId) { return []; } + return PATHWAY_TABS.map(({ tabId, route, message }) => ({ + tabId, + title: intl.formatMessage(message), + url: generatePath(route, { pathwayId }), + })); + }, [intl, pathwayId]); +}; diff --git a/src/pathways/pathway-tabs/messages.ts b/src/pathways/pathway-tabs/messages.ts new file mode 100644 index 0000000000..15dd8cac2c --- /dev/null +++ b/src/pathways/pathway-tabs/messages.ts @@ -0,0 +1,26 @@ +import { defineMessages } from '@edx/frontend-platform/i18n'; + +const messages = defineMessages({ + pathwayMaterial: { + id: 'learning.pathways.tabs.navigation.label', + defaultMessage: 'Pathway Material', + description: 'The accessible label for pathway tabs navigation', + }, + home: { + id: 'learning.pathways.tabs.home', + defaultMessage: 'Outline', + description: 'Title of the pathway tab that shows the pathway outline', + }, + progress: { + id: 'learning.pathways.tabs.progress', + defaultMessage: 'Progress', + description: 'Title of the pathway tab that shows the learner progress in the pathway', + }, + achievements: { + id: 'learning.pathways.tabs.achievements', + defaultMessage: 'Achievements', + description: 'Title of the pathway tab that shows the learner achievements in the pathway', + }, +}); + +export default messages; diff --git a/src/pathways/pathway-tabs/types.ts b/src/pathways/pathway-tabs/types.ts new file mode 100644 index 0000000000..759fbf01df --- /dev/null +++ b/src/pathways/pathway-tabs/types.ts @@ -0,0 +1,5 @@ +export interface PathwayTabMetadata { + tabId: string; + title: string; + url: string; +} diff --git a/src/pathways/pathways-achievements/CertificateCard.test.tsx b/src/pathways/pathways-achievements/CertificateCard.test.tsx new file mode 100644 index 0000000000..caed2e7b02 --- /dev/null +++ b/src/pathways/pathways-achievements/CertificateCard.test.tsx @@ -0,0 +1,39 @@ +import { render, screen } from '@testing-library/react'; +import { IntlProvider } from '@edx/frontend-platform/i18n'; + +import { dataEngineeringAchievements } from '@src/pathways/data/__fixtures__/pathways'; + +import { CertificateCard } from './CertificateCard'; + +const [pathwayCertificate, itemCertificate] = dataEngineeringAchievements; + +const renderComponent = (achievement: typeof pathwayCertificate) => render( + + + , +); + +describe('CertificateCard', () => { + it('shows the certificate details', () => { + renderComponent(itemCertificate); + + expect(screen.getByText(itemCertificate.displayName)).toBeInTheDocument(); + expect(screen.getByText(itemCertificate.providerName)).toBeInTheDocument(); + expect(screen.getByText(/^Completed on/)).toBeInTheDocument(); + expect(screen.getByText(itemCertificate.credentialId)).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'View certificate' })).toBeInTheDocument(); + }); + + it('names the pathway category in the certificate of the pathway itself', () => { + renderComponent(pathwayCertificate); + + expect(screen.getByText('Bootcamp certificate')).toBeInTheDocument(); + }); + + it('shows a generic label in the certificate of an item', () => { + renderComponent(itemCertificate); + + expect(screen.getByText('Certificate')).toBeInTheDocument(); + expect(screen.queryByText('Bootcamp certificate')).not.toBeInTheDocument(); + }); +}); diff --git a/src/pathways/pathways-achievements/CertificateCard.tsx b/src/pathways/pathways-achievements/CertificateCard.tsx new file mode 100644 index 0000000000..3f8d79c83a --- /dev/null +++ b/src/pathways/pathways-achievements/CertificateCard.tsx @@ -0,0 +1,67 @@ +import classNames from 'classnames'; +import { Button, Icon, Stack } from '@openedx/paragon'; +import { FormattedMessage } from '@edx/frontend-platform/i18n'; + +import { PathwayAchievementData } from '@src/pathways/data/types'; + +import messages from './messages'; +import { NewsModeIcon } from './NewsModeIcon'; + +export interface CertificateCardProps extends PathwayAchievementData { + categoryLabel?: string; +} + +export const CertificateCard = ({ + credentialId, + displayName, + providerName, + completedOn, + isOverarching, + categoryLabel, +}: CertificateCardProps) => { + const subtitle = isOverarching ? messages.pathwayCertificate : messages.itemCertificate; + + return ( +
+ + + + + + + + + + {displayName} + + + + + {providerName} + + + + + + + + + + + + {credentialId} + + + +
+ ); +}; diff --git a/src/pathways/pathways-achievements/NewsModeIcon.tsx b/src/pathways/pathways-achievements/NewsModeIcon.tsx new file mode 100644 index 0000000000..9f435e7318 --- /dev/null +++ b/src/pathways/pathways-achievements/NewsModeIcon.tsx @@ -0,0 +1,14 @@ +import type { SVGProps } from 'react'; + +export const NewsModeIcon = (props: SVGProps) => ( + + + +); diff --git a/src/pathways/pathways-achievements/PathwayAchievements.test.tsx b/src/pathways/pathways-achievements/PathwayAchievements.test.tsx new file mode 100644 index 0000000000..2a44503320 --- /dev/null +++ b/src/pathways/pathways-achievements/PathwayAchievements.test.tsx @@ -0,0 +1,67 @@ +import { MemoryRouter, Route, Routes } from 'react-router-dom'; + +import { DECODE_ROUTES } from '@src/constants'; +import { getPathway, getPathwayAchievements } from '@src/pathways/data/api'; +import { dataEngineering, dataEngineeringAchievements } from '@src/pathways/data/__fixtures__/pathways'; +import { initializeMockApp, render, screen } from '@src/setupTest'; + +import { PathwayAchievements } from './PathwayAchievements'; + +// The header is not what is tested here, and it needs the whole platform setup to render. +jest.mock('@src/plugin-slots/HeaderSlot', () => () => null); + +jest.mock('@src/pathways/data/api', () => ({ + getPathway: jest.fn(), + getPathwayAchievements: jest.fn(), +})); + +const mockGetPathway = getPathway as jest.MockedFunction; +const mockGetPathwayAchievements = getPathwayAchievements as jest.MockedFunction; + +const pathwayId = dataEngineering.pathway.id; + +const renderComponent = () => render( + + + } /> + + , +); + +describe('PathwayAchievements', () => { + beforeAll(() => { + initializeMockApp(); + }); + + beforeEach(() => { + mockGetPathway.mockResolvedValue(dataEngineering); + mockGetPathwayAchievements.mockResolvedValue(dataEngineeringAchievements); + }); + + it('shows a card for each achievement of the pathway in the URL', async () => { + renderComponent(); + + expect(await screen.findAllByRole('button', { name: 'View certificate' })) + .toHaveLength(dataEngineeringAchievements.length); + dataEngineeringAchievements.forEach(({ displayName }) => { + expect(screen.getByText(displayName)).toBeInTheDocument(); + }); + + expect(mockGetPathway).toHaveBeenCalledWith(pathwayId); + expect(mockGetPathwayAchievements).toHaveBeenCalledWith(pathwayId); + }); + + it('names the pathway category in the certificate of the pathway itself', async () => { + renderComponent(); + + expect(await screen.findByText('Bootcamp certificate')).toBeInTheDocument(); + }); + + it('shows an error instead of the achievements when they cannot be loaded', async () => { + mockGetPathwayAchievements.mockRejectedValue(new Error('network error')); + renderComponent(); + + expect(await screen.findByText('There was an error loading this pathway.')).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'View certificate' })).not.toBeInTheDocument(); + }); +}); diff --git a/src/pathways/pathways-achievements/PathwayAchievements.tsx b/src/pathways/pathways-achievements/PathwayAchievements.tsx new file mode 100644 index 0000000000..ddb63f73b8 --- /dev/null +++ b/src/pathways/pathways-achievements/PathwayAchievements.tsx @@ -0,0 +1,33 @@ +import { useParams } from 'react-router-dom'; +import { CardGrid } from '@openedx/paragon'; +import { usePathway, usePathwayAchievements } from '../data/apiHooks'; +import { TabPage } from '../tab-page/TabPage'; +import { CertificateCard } from './CertificateCard'; + +export const PathwayAchievements = () => { + const { pathwayId } = useParams(); + + const metadataQuery = usePathway(pathwayId); + const tabDataQuery = usePathwayAchievements(pathwayId); + + return ( + + + {tabDataQuery.data?.map((data) => ( + + ))} + + + ); +}; diff --git a/src/pathways/pathways-achievements/messages.ts b/src/pathways/pathways-achievements/messages.ts new file mode 100644 index 0000000000..504fe51cc9 --- /dev/null +++ b/src/pathways/pathways-achievements/messages.ts @@ -0,0 +1,31 @@ +import { defineMessages } from '@edx/frontend-platform/i18n'; + +const messages = defineMessages({ + pathwayCertificate: { + id: 'learning.pathways.certificate-card.pathway-certificate', + defaultMessage: '{categoryLabel} certificate', + description: 'Subtite of the Pathway certificate', + }, + itemCertificate: { + id: 'learning.pathways.certificate-card.item-certificate', + defaultMessage: 'Certificate', + description: 'Subtite of the Item certificate', + }, + completed: { + id: 'learning.pathways.certificate-card.completed', + defaultMessage: 'Completed on {date}', + description: 'Subtite of the Pathway certificate', + }, + viewCertificateButton: { + id: 'learning.pathways.certificate-card.view-certificate', + defaultMessage: 'View certificate', + description: 'Label for the View certificate button', + }, + credentialId: { + id: 'learning.pathways.certificate-card.credential-id', + defaultMessage: 'Credential ID', + description: 'Credential ID label of a pathway/item certificate', + }, +}); + +export default messages; diff --git a/src/pathways/pathways-strip/CoursePathwaysStrip.scss b/src/pathways/pathways-strip/CoursePathwaysStrip.scss new file mode 100644 index 0000000000..153d3f2768 --- /dev/null +++ b/src/pathways/pathways-strip/CoursePathwaysStrip.scss @@ -0,0 +1,58 @@ +.course-pathways-strip { + .course-pathways-strip-container { + position: relative; + flex: 1; + min-width: 0; + overflow: hidden; + } + + .course-pathways-strip-label { + flex-shrink: 0; + white-space: nowrap; + + &:hover, + &:focus { + text-decoration: underline; + } + + // Labels are separated by a vertical line + & + .course-pathways-strip-label { + margin-inline-start: 0.75rem; + padding-inline-start: 0.75rem; + border-inline-start: 1px solid var(--pgn-color-light-700); + } + } + + // "+N" trigger, separated from the labels by a vertical line + .course-pathways-strip-trigger { + flex-shrink: 0; + padding-top: 0; + padding-bottom: 0; + border-inline-start: 1px solid var(--pgn-color-light-700); + border-radius: 0; + + .badge { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 1.25rem; + height: 1.25rem; + padding: 0; + margin-inline-start: 0.5rem; + } + + .btn-icon-after { + margin-inline-start: 0; + } + } + + // Hidden copy of every label, only used to measure their natural width + .course-pathways-strip-measure { + position: absolute; + top: 0; + left: 0; + width: max-content; + visibility: hidden; + pointer-events: none; + } +} diff --git a/src/pathways/pathways-strip/CoursePathwaysStrip.test.tsx b/src/pathways/pathways-strip/CoursePathwaysStrip.test.tsx new file mode 100644 index 0000000000..f857cad282 --- /dev/null +++ b/src/pathways/pathways-strip/CoursePathwaysStrip.test.tsx @@ -0,0 +1,129 @@ +import { render, screen } from '@testing-library/react'; +import { IntlProvider } from '@edx/frontend-platform/i18n'; +import { MemoryRouter } from 'react-router-dom'; + +import { useCoursePathways } from '../data/apiHooks'; +import type { PathwayData } from '../data/types'; +import { + courseIdWithPathways, dataEngineering, loremIpsum, machineLearning, +} from '../data/__fixtures__/pathways'; +import { useVisiblePathways } from './hooks'; +import { MorePathwaysPopover } from './MorePathwaysPopover'; +import { CoursePathwaysStrip } from './CoursePathwaysStrip'; + +jest.mock('../data/apiHooks', () => ({ + useCoursePathways: jest.fn(), +})); + +jest.mock('./hooks', () => ({ + useVisiblePathways: jest.fn(), +})); + +jest.mock('./MorePathwaysPopover', () => ({ + MorePathwaysPopover: jest.fn(() =>
MorePathwaysPopover
), +})); + +const mockUseCoursePathways = useCoursePathways as jest.Mock; +const mockUseVisiblePathways = useVisiblePathways as jest.MockedFunction; + +const pathways = [dataEngineering, machineLearning, loremIpsum]; + +const mockPathways = (data?: PathwayData[]) => { + mockUseCoursePathways.mockReturnValue({ data }); +}; + +const mockSplit = (visiblePathways: PathwayData[], hiddenPathways: PathwayData[]) => { + mockUseVisiblePathways.mockReturnValue({ + containerRef: { current: null }, + measureRef: { current: null }, + visiblePathways, + hiddenPathways, + }); +}; + +const renderComponent = () => render( + + + + + , +); + +// The labels shown in the strip, leaving out the hidden copies used for measuring +const getVisibleLabels = (container: HTMLElement) => Array.from( + container.querySelectorAll('.course-pathways-strip-container > .course-pathways-strip-label'), +); + +describe('CoursePathwaysStrip', () => { + beforeEach(() => { + jest.clearAllMocks(); + mockPathways(pathways); + mockSplit(pathways, []); + }); + + it('renders nothing when the course has no pathways', () => { + mockPathways([]); + mockSplit([], []); + const { container } = renderComponent(); + expect(container).toBeEmptyDOMElement(); + }); + + it('renders nothing while the pathways are loading', () => { + mockPathways(undefined); + mockSplit([], []); + const { container } = renderComponent(); + expect(container).toBeEmptyDOMElement(); + }); + + it('gets the pathways of the course', () => { + renderComponent(); + expect(mockUseCoursePathways).toHaveBeenCalledWith(courseIdWithPathways); + expect(mockUseVisiblePathways).toHaveBeenCalledWith(pathways); + }); + + it('renders the "Course included in" label and every visible pathway', () => { + const { container } = renderComponent(); + expect(screen.getByText('Course included in')).toBeInTheDocument(); + expect(getVisibleLabels(container).map((label) => label.textContent)).toEqual([ + 'Data Engineering Fundamentals', + 'Introduction to Machine Learning', + 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod', + ]); + }); + + it('links every visible pathway to its outline', () => { + const { container } = renderComponent(); + expect(getVisibleLabels(container).map((label) => label.getAttribute('href'))).toEqual( + pathways.map((pathway) => `/pathway/${pathway.pathway.id}/outline`), + ); + }); + + it('does not render the popover when every pathway fits', () => { + renderComponent(); + expect(MorePathwaysPopover).not.toHaveBeenCalled(); + }); + + it('renders only the visible pathways and passes the hidden ones to the popover', () => { + mockSplit([dataEngineering, machineLearning], [loremIpsum]); + const { container } = renderComponent(); + + expect(getVisibleLabels(container).map((label) => label.textContent)).toEqual([ + 'Data Engineering Fundamentals', + 'Introduction to Machine Learning', + ]); + + expect(screen.getByText('MorePathwaysPopover')).toBeInTheDocument(); + expect(MorePathwaysPopover).toHaveBeenCalledWith({ pathways: [loremIpsum] }, expect.anything()); + }); + + it('renders every pathway in the hidden row used for measuring', () => { + mockSplit([dataEngineering], [machineLearning, loremIpsum]); + const { container } = renderComponent(); + const measureRow = container.querySelector('.course-pathways-strip-measure'); + expect(measureRow).toHaveAttribute('aria-hidden'); + expect(measureRow?.children).toHaveLength(pathways.length); + Array.from(measureRow?.children ?? []).forEach((label) => { + expect(label).toHaveAttribute('tabindex', '-1'); + }); + }); +}); diff --git a/src/pathways/pathways-strip/CoursePathwaysStrip.tsx b/src/pathways/pathways-strip/CoursePathwaysStrip.tsx new file mode 100644 index 0000000000..2c513654ec --- /dev/null +++ b/src/pathways/pathways-strip/CoursePathwaysStrip.tsx @@ -0,0 +1,64 @@ +import { FormattedMessage } from '@edx/frontend-platform/i18n'; +import { generatePath, Link } from 'react-router-dom'; + +import { DECODE_ROUTES } from '@src/constants'; + +import { useCoursePathways } from '../data/apiHooks'; +import type { PathwayData } from '../data/types'; +import { MorePathwaysPopover } from './MorePathwaysPopover'; +import { useVisiblePathways } from './hooks'; +import messages from './messages'; + +interface PathwayLabelProps { + pathway: PathwayData; + isMeasure?: boolean; +} + +export interface CoursePathwaysStripProps { + courseId?: string; +} + +const PathwayLabel = ({ pathway, isMeasure = false }: PathwayLabelProps) => ( + + {pathway.pathway.content.displayName} + +); + +export const CoursePathwaysStrip = ({ courseId }: CoursePathwaysStripProps) => { + const { data: pathways = [] } = useCoursePathways(courseId); + const { + containerRef, + measureRef, + visiblePathways, + hiddenPathways, + } = useVisiblePathways(pathways); + + if (!pathways.length) { + return null; + } + + return ( +
+
+ + + +
+ {visiblePathways.map((pathway) => ( + + ))} + {hiddenPathways.length > 0 && } +
+ {pathways.map((pathway) => ( + + ))} +
+
+
+
+ ); +}; diff --git a/src/pathways/pathways-strip/MorePathwaysPopover.test.tsx b/src/pathways/pathways-strip/MorePathwaysPopover.test.tsx new file mode 100644 index 0000000000..58f01a7dd0 --- /dev/null +++ b/src/pathways/pathways-strip/MorePathwaysPopover.test.tsx @@ -0,0 +1,52 @@ +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { IntlProvider } from '@edx/frontend-platform/i18n'; +import { MemoryRouter } from 'react-router-dom'; + +import type { PathwayData } from '../data/types'; +import { dataEngineering, machineLearning } from '../data/__fixtures__/pathways'; +import { MorePathwaysPopover } from './MorePathwaysPopover'; + +const renderComponent = (pathways: PathwayData[] = [dataEngineering, machineLearning]) => render( + + + + + , +); + +describe('MorePathwaysPopover', () => { + it('renders the trigger with the number of pathways and an accessible label', () => { + renderComponent(); + const trigger = screen.getByRole('button', { name: 'Show 2 more pathways' }); + expect(trigger).toHaveTextContent('2'); + }); + + it('uses the singular accessible label for a single pathway', () => { + renderComponent([dataEngineering]); + expect(screen.getByRole('button', { name: 'Show 1 more pathway' })).toBeInTheDocument(); + }); + + it('does not show the pathways until the trigger is clicked', () => { + renderComponent(); + expect(screen.queryByText('Data Engineering Fundamentals')).not.toBeInTheDocument(); + }); + + it('shows the pathways when the trigger is clicked', async () => { + const user = userEvent.setup(); + renderComponent(); + await user.click(screen.getByRole('button', { name: 'Show 2 more pathways' })); + expect(screen.getByRole('link', { name: 'Data Engineering Fundamentals' })) + .toHaveAttribute('href', `/pathway/${dataEngineering.pathway.id}/outline`); + expect(screen.getByRole('link', { name: 'Introduction to Machine Learning' })) + .toHaveAttribute('href', `/pathway/${machineLearning.pathway.id}/outline`); + }); + + it('closes the pathways list on Escape', async () => { + const user = userEvent.setup(); + renderComponent(); + await user.click(screen.getByRole('button', { name: 'Show 2 more pathways' })); + await user.keyboard('{Escape}'); + expect(screen.queryByText('Data Engineering Fundamentals')).not.toBeInTheDocument(); + }); +}); diff --git a/src/pathways/pathways-strip/MorePathwaysPopover.tsx b/src/pathways/pathways-strip/MorePathwaysPopover.tsx new file mode 100644 index 0000000000..6fbd7b6316 --- /dev/null +++ b/src/pathways/pathways-strip/MorePathwaysPopover.tsx @@ -0,0 +1,53 @@ +import { useState } from 'react'; +import { useIntl } from '@edx/frontend-platform/i18n'; +import { + Badge, Button, ModalPopup, useToggle, +} from '@openedx/paragon'; +import { ArrowDropDown } from '@openedx/paragon/icons'; +import { generatePath, Link } from 'react-router-dom'; + +import { DECODE_ROUTES } from '@src/constants'; + +import type { PathwayData } from '../data/types'; +import messages from './messages'; + +export const MorePathwaysPopover = ({ pathways }: { pathways: PathwayData[] }) => { + const { formatMessage } = useIntl(); + const [isOpen, open, close] = useToggle(false); + const [target, setTarget] = useState(null); + + return ( + <> + + +
+
    + {pathways.map((pathway) => ( +
  • + + {pathway.pathway.content.displayName} + +
  • + ))} +
+
+
+ + ); +}; diff --git a/src/pathways/pathways-strip/hooks.test.tsx b/src/pathways/pathways-strip/hooks.test.tsx new file mode 100644 index 0000000000..caa80c444a --- /dev/null +++ b/src/pathways/pathways-strip/hooks.test.tsx @@ -0,0 +1,206 @@ +import { act, render, screen } from '@testing-library/react'; + +import type { PathwayData } from '../data/types'; +import { useVisiblePathways } from './hooks'; + +const buildPathway = (id: string): PathwayData => ({ + pathway: { + id, + content: { displayName: `Pathway ${id}` }, + itemCount: 3, + }, +}); + +const pathways = ['1', '2', '3'].map(buildPathway); + +// jsdom has no layout, so the sizes the hook reads are taken from data attributes +const mockLayoutProperty = (property: 'clientWidth' | 'offsetWidth' | 'offsetLeft') => ( + jest.spyOn(HTMLElement.prototype, property, 'get').mockImplementation(function getSize(this: HTMLElement) { + return Number(this.dataset[property] ?? 0); + }) +); + +// setupTest.js already replaces getComputedStyle with a mock +const mockedGetComputedStyle = jest.mocked(window.getComputedStyle); +const originalGetComputedStyle = mockedGetComputedStyle.getMockImplementation(); + +let resizeCallback: () => void; +const disconnect = jest.fn(); + +const observe = jest.fn(); + +class MockResizeObserver { + constructor(callback: () => void) { + resizeCallback = callback; + } + + observe = observe; + + disconnect = disconnect; +} + +interface HarnessProps { + items?: PathwayData[]; + containerWidth: number; + labelOffsets: number[]; + labelWidths?: number[]; + labelsWidth: number; +} + +const Harness = ({ + items = pathways, containerWidth, labelOffsets, labelWidths = [], labelsWidth, +}: HarnessProps) => { + const { + containerRef, measureRef, visiblePathways, hiddenPathways, + } = useVisiblePathways(items); + return ( + <> +
+
+ {labelOffsets.map((offset, index) => ( + + ))} +
+
{visiblePathways.map(({ pathway }) => pathway.id).join(',')}
+
{hiddenPathways.map(({ pathway }) => pathway.id).join(',')}
+ + ); +}; + +const renderComponent = (props: HarnessProps) => render(); + +// A row wider than the strips used below: labels 400, 500 and 400 wide, ending at 400, 900 and 1300 +const overflowingRow = { + labelsWidth: 1300, + labelOffsets: [0, 400, 900], + labelWidths: [400, 500, 400], +}; + +describe('useVisiblePathways', () => { + const originalResizeObserver = globalThis.ResizeObserver; + + beforeEach(() => { + jest.clearAllMocks(); + globalThis.ResizeObserver = MockResizeObserver as unknown as typeof ResizeObserver; + mockLayoutProperty('clientWidth'); + mockLayoutProperty('offsetWidth'); + mockLayoutProperty('offsetLeft'); + }); + + afterEach(() => { + globalThis.ResizeObserver = originalResizeObserver; + jest.restoreAllMocks(); + mockedGetComputedStyle.mockImplementation(originalGetComputedStyle); + }); + + it('shows every pathway when all the labels fit', () => { + renderComponent({ containerWidth: 1000, labelsWidth: 900, labelOffsets: [0, 300, 600] }); + expect(screen.getByTestId('visible')).toHaveTextContent('1,2,3'); + expect(screen.getByTestId('hidden')).toBeEmptyDOMElement(); + }); + + it('moves the labels that do not fit to the hidden pathways', () => { + renderComponent({ ...overflowingRow, containerWidth: 1000 }); + expect(screen.getByTestId('visible')).toHaveTextContent('1,2'); + expect(screen.getByTestId('hidden')).toHaveTextContent('3'); + }); + + it('moves a label that would be cut to the hidden pathways instead of truncating it', () => { + // The third label starts within the strip but ends after the space kept for the "+N" trigger + renderComponent({ + containerWidth: 1000, + labelsWidth: 1300, + labelOffsets: [0, 400, 800], + labelWidths: [400, 400, 500], + }); + expect(screen.getByTestId('visible')).toHaveTextContent('1,2'); + expect(screen.getByTestId('hidden')).toHaveTextContent('3'); + }); + + it('moves every label to the hidden pathways when not even the first one fits', () => { + renderComponent({ + containerWidth: 500, + labelsWidth: 1300, + labelOffsets: [0, 600, 900], + labelWidths: [600, 300, 400], + }); + expect(screen.getByTestId('visible')).toBeEmptyDOMElement(); + expect(screen.getByTestId('hidden')).toHaveTextContent('1,2,3'); + }); + + it('measures the labels from the right edge in RTL', () => { + // jsdom does not compute the direction + mockedGetComputedStyle.mockReturnValue({ direction: 'rtl' } as CSSStyleDeclaration); + // The same row as [0, 720, 840] in LTR, mirrored: labels 700, 100 and 100 wide in a 940 wide row + renderComponent({ + containerWidth: 800, + labelsWidth: 940, + labelOffsets: [240, 120, 0], + labelWidths: [700, 100, 100], + }); + expect(screen.getByTestId('visible')).toHaveTextContent(/^1$/); + expect(screen.getByTestId('hidden')).toHaveTextContent('2,3'); + }); + + it('recalculates the split when the container is resized', () => { + renderComponent({ ...overflowingRow, containerWidth: 1000 }); + expect(screen.getByTestId('visible')).toHaveTextContent('1,2'); + + screen.getByTestId('container').dataset.clientWidth = '500'; + act(() => resizeCallback()); + + expect(screen.getByTestId('visible')).toHaveTextContent('1'); + expect(screen.getByTestId('hidden')).toHaveTextContent('2,3'); + }); + + it('recalculates the split when the labels are resized', () => { + renderComponent({ containerWidth: 1000, labelsWidth: 900, labelOffsets: [0, 300, 600] }); + expect(observe).toHaveBeenCalledWith(screen.getByTestId('measure')); + expect(screen.getByTestId('visible')).toHaveTextContent('1,2,3'); + + // e.g. the web font loads and every label gets wider + const measure = screen.getByTestId('measure'); + measure.dataset.offsetWidth = '1300'; + const labels = Array.from(measure.children) as HTMLElement[]; + overflowingRow.labelOffsets.forEach((offset, index) => { + labels[index].dataset.offsetLeft = String(offset); + labels[index].dataset.offsetWidth = String(overflowingRow.labelWidths[index]); + }); + act(() => resizeCallback()); + + expect(screen.getByTestId('visible')).toHaveTextContent('1,2'); + expect(screen.getByTestId('hidden')).toHaveTextContent('3'); + }); + + it('recalculates the split when the pathways change but not their count', () => { + const props = { containerWidth: 1000, labelsWidth: 900, labelOffsets: [0, 300, 600] }; + const { rerender } = renderComponent(props); + expect(screen.getByTestId('visible')).toHaveTextContent('1,2,3'); + + // Same count, but longer names + rerender( + , + ); + + expect(screen.getByTestId('visible')).toHaveTextContent('4,5'); + expect(screen.getByTestId('hidden')).toHaveTextContent('6'); + }); + + it('shows every pathway when ResizeObserver is not available', () => { + // @ts-expect-error ResizeObserver is removed to emulate an environment without it + delete globalThis.ResizeObserver; + renderComponent({ ...overflowingRow, containerWidth: 1000 }); + expect(screen.getByTestId('visible')).toHaveTextContent('1,2,3'); + expect(screen.getByTestId('hidden')).toBeEmptyDOMElement(); + }); + + it('disconnects the observer on unmount', () => { + const { unmount } = renderComponent({ containerWidth: 1000, labelsWidth: 900, labelOffsets: [0, 300, 600] }); + unmount(); + expect(disconnect).toHaveBeenCalled(); + }); +}); diff --git a/src/pathways/pathways-strip/hooks.ts b/src/pathways/pathways-strip/hooks.ts new file mode 100644 index 0000000000..7e0ee62db7 --- /dev/null +++ b/src/pathways/pathways-strip/hooks.ts @@ -0,0 +1,59 @@ +import { useLayoutEffect, useRef, useState } from 'react'; + +import type { PathwayData } from '../data/types'; + +// Width kept free at the end of the strip for the "+N" popover trigger +const COUNTER_RESERVED_WIDTH = 74; + +/** + * Splits the course pathways into the ones that fit in the strip and the ones that go to the + * "+N" popover. Only the labels that fit entirely are shown, so a label that would be cut goes to + * the popover, even if it is the first one. The split is recalculated whenever the strip resizes. + */ +export const useVisiblePathways = (pathways: PathwayData[]) => { + // Goes on the element whose width is available for the labels and the trigger + const containerRef = useRef(null); + // Goes on a hidden row that renders every label at its natural width + const measureRef = useRef(null); + const [visibleCount, setVisibleCount] = useState(pathways.length); + + useLayoutEffect(() => { + const container = containerRef.current; + const measure = measureRef.current; + if (!container || !measure || typeof ResizeObserver === 'undefined') { + setVisibleCount(pathways.length); + return undefined; + } + + const calculate = () => { + const available = container.clientWidth; + if (measure.offsetWidth <= available) { + setVisibleCount(pathways.length); + return; + } + // A label is visible if it ends before the space kept for the "+N" trigger + const limit = available - COUNTER_RESERVED_WIDTH; + const labels = Array.from(measure.children) as HTMLElement[]; + // In RTL the labels start at the right edge, so their start is measured from there + const isRtl = getComputedStyle(measure).direction === 'rtl'; + const endOf = (label: HTMLElement) => ( + isRtl ? measure.offsetWidth - label.offsetLeft : label.offsetLeft + label.offsetWidth + ); + setVisibleCount(labels.filter((label) => endOf(label) <= limit).length); + }; + + calculate(); + const observer = new ResizeObserver(calculate); + observer.observe(container); + // The labels change width without resizing the container, e.g. when the web font loads + observer.observe(measure); + return () => observer.disconnect(); + }, [pathways]); + + return { + containerRef, + measureRef, + visiblePathways: pathways.slice(0, visibleCount), + hiddenPathways: pathways.slice(visibleCount), + }; +}; diff --git a/src/pathways/pathways-strip/messages.ts b/src/pathways/pathways-strip/messages.ts new file mode 100644 index 0000000000..9977a11ec8 --- /dev/null +++ b/src/pathways/pathways-strip/messages.ts @@ -0,0 +1,16 @@ +import { defineMessages } from '@edx/frontend-platform/i18n'; + +const messages = defineMessages({ + includedIn: { + id: 'learning.coursePathways.includedIn', + defaultMessage: 'Course included in', + description: 'Label that precedes the pathways, in which the learner is enrolled, that include this course', + }, + morePathways: { + id: 'learning.coursePathways.morePathways', + defaultMessage: 'Show {count, plural, one {# more pathway} other {# more pathways}}', + description: 'Accessible label of the button that shows the pathways that do not fit in the course header', + }, +}); + +export default messages; diff --git a/src/pathways/tab-page/TabPage.tsx b/src/pathways/tab-page/TabPage.tsx new file mode 100644 index 0000000000..4613c294b5 --- /dev/null +++ b/src/pathways/tab-page/TabPage.tsx @@ -0,0 +1,93 @@ +import { type ReactNode } from 'react'; +import { Helmet } from 'react-helmet'; + +import { useIntl } from '@edx/frontend-platform/i18n'; +import { FooterSlot } from '@edx/frontend-component-footer'; +import { getConfig } from '@edx/frontend-platform'; + +import { deriveView, type TabStatus } from '@src/tab-page/utils'; +import PageLoading from '@src/generic/PageLoading'; +import HeaderSlot from '@src/plugin-slots/HeaderSlot'; + +import messages from './messages'; +import type { PathwayData } from '../data/types'; +import { usePathwayTabs } from '../pathway-tabs/hooks'; +import { PathwayTabsNavigation } from '../pathway-tabs/PathwayTabsNavigation'; + +export type PathwayStatus = TabStatus; + +export interface TabPageProps { + activeTabSlug: string; + pathwayId?: string; + pathwayStatus: PathwayStatus; + children?: ReactNode; +} + +export const TabPage = ({ + activeTabSlug, + pathwayId, + pathwayStatus, + children, +}: TabPageProps) => { + const intl = useIntl(); + const { + pathway, + provider, + } = pathwayStatus.metadataQuery.data ?? {}; + const title = pathway?.content.displayName ?? ''; + const tabs = usePathwayTabs(pathwayId); + const activeTabTitle = tabs.find((tab) => tab.tabId === activeTabSlug)?.title; + + const { + isLoading, isError, isDenied, errorDetails, + } = deriveView(pathwayStatus); + + if (isDenied) { + // TODO: For now, `isDenied` is always `false`. + // We need to wait for the backend to see how `isDenied` + // is determined—whether it’s based on a response code + // or a field in the returned data. + } + + const shouldRenderContent = !isLoading && !isError; + + const renderLoading = () => ( + + ); + + const renderError = () => { + const errorMessages = errorDetails?.length ? errorDetails : [intl.formatMessage(messages.failure)]; + return ( +
+ {errorMessages.map((errorMessage) =>

{errorMessage}

)} +
+ ); + }; + + const renderLoadedTabPage = () => ( + <> + + {`${activeTabTitle ? `${activeTabTitle} | ` : ''}${title} | ${getConfig().SITE_NAME}`} + +
+ +
+ {children} +
+
+ + ); + + return ( + <> + + {isLoading && renderLoading()} + {shouldRenderContent && renderLoadedTabPage()} + {isError && renderError()} + + + ); +}; diff --git a/src/pathways/tab-page/messages.ts b/src/pathways/tab-page/messages.ts new file mode 100644 index 0000000000..fd9eafd12b --- /dev/null +++ b/src/pathways/tab-page/messages.ts @@ -0,0 +1,16 @@ +import { defineMessages } from '@edx/frontend-platform/i18n'; + +const messages = defineMessages({ + failure: { + id: 'learning.pathways.loading.failure', + defaultMessage: 'There was an error loading this pathway.', + description: 'Can be because internet connection or any technical other reason', + }, + loading: { + id: 'learning.pathways.loading', + defaultMessage: 'Loading pathway page…', + description: 'When content of a pathway is still loading', + }, +}); + +export default messages; diff --git a/src/plugin-slots/CourseInfoStripSlot/README.md b/src/plugin-slots/CourseInfoStripSlot/README.md new file mode 100644 index 0000000000..1c3e74bdb1 --- /dev/null +++ b/src/plugin-slots/CourseInfoStripSlot/README.md @@ -0,0 +1,56 @@ +# Course Info Strip Slot + +### Slot ID: `org.openedx.frontend.learning.course_info_strip.v1` + +### Props: +* `courseId` - String identifier for the current course + +## Description + +This slot is used to replace/modify/hide the strip shown below the course header, which shows information +about the current course. For example, it can be used to tell the learner that their trial access to the +course ends soon, or that they are viewing an archived run of the course. + +By default, it lists the pathways that include the current course and in which the learner is enrolled. When +the pathways do not fit in the strip, the remaining ones are shown in a "+N" popover. The default strip is not +rendered when the course is not included in any of the learner's pathways. + +## Example + +### Default content +![Course info strip slot with default content](./screenshot_default.png) + +### Replaced with a custom strip +![Course info strip slot with a custom strip](./screenshot_custom.png) + +The following `env.config.jsx` will replace the default strip with a custom one. + +```js +import { DIRECT_PLUGIN, PLUGIN_OPERATIONS } from '@openedx/frontend-plugin-framework'; + +const config = { + pluginSlots: { + 'org.openedx.frontend.learning.course_info_strip.v1': { + keepDefault: false, + plugins: [ + { + op: PLUGIN_OPERATIONS.Insert, + widget: { + id: 'custom_course_info_strip', + type: DIRECT_PLUGIN, + RenderWidget: () => ( +
+ Your trial access to this course ends in 6 days. +
+ ), + }, + }, + ], + }, + }, +}; + +export default config; +``` + +To hide the strip, use `PLUGIN_OPERATIONS.Hide` with `widgetId: 'default_contents'`. diff --git a/src/plugin-slots/CourseInfoStripSlot/index.test.tsx b/src/plugin-slots/CourseInfoStripSlot/index.test.tsx new file mode 100644 index 0000000000..2ba52eaf3c --- /dev/null +++ b/src/plugin-slots/CourseInfoStripSlot/index.test.tsx @@ -0,0 +1,19 @@ +import { render, screen } from '@testing-library/react'; + +import { CourseInfoStripSlot } from './index'; + +jest.mock('@src/pathways/pathways-strip/CoursePathwaysStrip', () => ({ + CoursePathwaysStrip: ({ courseId }: { courseId?: string }) => ( +
{courseId}
+ ), +})); + +describe('CourseInfoStripSlot', () => { + it('renders the plugin slot with the course pathways strip as its default content', () => { + render(); + + const slot = screen.getByTestId('org.openedx.frontend.learning.course_info_strip.v1'); + expect(slot).toContainElement(screen.getByTestId('CoursePathwaysStrip')); + expect(screen.getByTestId('CoursePathwaysStrip')).toHaveTextContent('course-v1:edX+DemoX+Demo_Course'); + }); +}); diff --git a/src/plugin-slots/CourseInfoStripSlot/index.tsx b/src/plugin-slots/CourseInfoStripSlot/index.tsx new file mode 100644 index 0000000000..8ef5793d05 --- /dev/null +++ b/src/plugin-slots/CourseInfoStripSlot/index.tsx @@ -0,0 +1,16 @@ +import { PluginSlot } from '@openedx/frontend-plugin-framework'; + +import { CoursePathwaysStrip } from '@src/pathways/pathways-strip/CoursePathwaysStrip'; + +interface CourseInfoStripSlotProps { + courseId?: string; +} + +export const CourseInfoStripSlot = ({ courseId }: CourseInfoStripSlotProps) => ( + + + +); diff --git a/src/plugin-slots/CourseInfoStripSlot/screenshot_custom.png b/src/plugin-slots/CourseInfoStripSlot/screenshot_custom.png new file mode 100644 index 0000000000..976013821b Binary files /dev/null and b/src/plugin-slots/CourseInfoStripSlot/screenshot_custom.png differ diff --git a/src/plugin-slots/CourseInfoStripSlot/screenshot_default.png b/src/plugin-slots/CourseInfoStripSlot/screenshot_default.png new file mode 100644 index 0000000000..95c73b3521 Binary files /dev/null and b/src/plugin-slots/CourseInfoStripSlot/screenshot_default.png differ diff --git a/src/plugin-slots/PathwayTabLinksSlot/README.md b/src/plugin-slots/PathwayTabLinksSlot/README.md new file mode 100644 index 0000000000..7488af61b6 --- /dev/null +++ b/src/plugin-slots/PathwayTabLinksSlot/README.md @@ -0,0 +1,54 @@ +# Pathway Tab Links Slot + +### Slot ID: `org.openedx.frontend.learning.pathway_tab_links.v1` + +### Props: +* `tabs` - The tabs of the pathway, each with its `tabId`, `title` and `url` +* `activeTabSlug` - The slug of the currently active tab + +## Description + +This slot is used to replace/modify/hide the links in the pathway tab navigation. + +By default, it renders a link for each of the pathway tabs and highlights the active one. + +## Example + +### Added link to Pathway Tabs + +The following `env.config.jsx` will add a new pathway tab called "Custom Tab". + +```js +import { DIRECT_PLUGIN, PLUGIN_OPERATIONS } from '@openedx/frontend-plugin-framework'; + +import { PathwayTabLink } from '@src/pathways/pathway-tabs/PathwayTabLink'; + +const config = { + pluginSlots: { + 'org.openedx.frontend.learning.pathway_tab_links.v1': { + keepDefault: true, + plugins: [ + { + op: PLUGIN_OPERATIONS.Insert, + widget: { + id: 'custom_tab', + type: DIRECT_PLUGIN, + RenderWidget: ({ activeTabSlug }) => ( + + ), + }, + }, + ], + }, + }, +}; + +export default config; +``` + +To hide the default links, use `PLUGIN_OPERATIONS.Hide` with `widgetId: 'default_contents'`. diff --git a/src/plugin-slots/PathwayTabLinksSlot/index.test.tsx b/src/plugin-slots/PathwayTabLinksSlot/index.test.tsx new file mode 100644 index 0000000000..7731ca113a --- /dev/null +++ b/src/plugin-slots/PathwayTabLinksSlot/index.test.tsx @@ -0,0 +1,21 @@ +import { render, screen } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; + +import { PathwayTabLinksSlot } from './index'; + +const tabs = [ + { tabId: 'home', title: 'Home', url: '/pathway/pathway-1/home' }, + { tabId: 'progress', title: 'Progress', url: '/pathway/pathway-1/progress' }, +]; + +describe('PathwayTabLinksSlot', () => { + it('renders the plugin slot with the pathway tab links as its default content', () => { + render(, { wrapper: MemoryRouter }); + + const slot = screen.getByTestId('org.openedx.frontend.learning.pathway_tab_links.v1'); + expect(slot).toContainElement(screen.getByRole('link', { name: 'Home' })); + expect(screen.getByRole('link', { name: 'Home' })).toHaveAttribute('href', '/pathway/pathway-1/home'); + expect(screen.getByRole('link', { name: 'Progress' })).toHaveClass('active'); + expect(screen.getByRole('link', { name: 'Home' })).not.toHaveClass('active'); + }); +}); diff --git a/src/plugin-slots/PathwayTabLinksSlot/index.tsx b/src/plugin-slots/PathwayTabLinksSlot/index.tsx new file mode 100644 index 0000000000..1c30fdcce5 --- /dev/null +++ b/src/plugin-slots/PathwayTabLinksSlot/index.tsx @@ -0,0 +1,18 @@ +import { PluginSlot } from '@openedx/frontend-plugin-framework'; + +import { PathwayTabLinksList } from '@src/pathways/pathway-tabs/PathwayTabLinksList'; +import type { PathwayTabMetadata } from '@src/pathways/pathway-tabs/types'; + +interface PathwayTabLinksSlotProps { + tabs: PathwayTabMetadata[]; + activeTabSlug?: string; +} + +export const PathwayTabLinksSlot = ({ tabs, activeTabSlug }: PathwayTabLinksSlotProps) => ( + + + +); diff --git a/src/plugin-slots/README.md b/src/plugin-slots/README.md index 12ee5bce26..700ec1102b 100644 --- a/src/plugin-slots/README.md +++ b/src/plugin-slots/README.md @@ -6,6 +6,7 @@ * [`org.openedx.frontend.learning.content_iframe_loader.v1`](./ContentIFrameLoaderSlot/) * [`org.openedx.frontend.learning.course_breadcrumbs.v1`](./CourseBreadcrumbsSlot/) * [`org.openedx.frontend.learning.course_home_section_outline.v1`](./CourseHomeSectionOutlineSlot/) +* [`org.openedx.frontend.learning.course_info_strip.v1`](./CourseInfoStripSlot/) * [`org.openedx.frontend.learning.course_outline_mobile_sidebar_trigger.v1`](./CourseOutlineMobileSidebarTriggerSlot/) * [`org.openedx.frontend.learning.course_outline_sidebar_trigger.v1`](./CourseOutlineSidebarTriggerSlot) * [`org.openedx.frontend.learning.course_outline_sidebar.v1`](./CourseOutlineSidebarSlot/) @@ -15,6 +16,7 @@ * [`org.openedx.frontend.learning.learner_tools.v1`](./LearnerToolsSlot/) * [`org.openedx.frontend.learning.next_unit_top_nav_trigger.v1`](./NextUnitTopNavTriggerSlot/) * ~~`org.openedx.frontend.learning.notification_tray.v1`~~ _(deprecated / aliased to `upgrade_panel.v1` — see [ADR 0010](../../docs/decisions/0010-upgrade-widget-extraction.md))_ +* [`org.openedx.frontend.learning.pathway_tab_links.v1`](./PathwayTabLinksSlot/) * [`org.openedx.frontend.learning.right_sidebar_trigger.v1`](./RightSidebarTriggerSlot/) * [`org.openedx.frontend.learning.right_sidebar.v1`](./RightSidebarSlot/) * [`org.openedx.frontend.learning.upgrade_panel.v1`](../widgets/upgrade/) _(upgrade / upsell panel — see [ADR 0010](../../docs/decisions/0010-upgrade-widget-extraction.md))_ diff --git a/src/tab-page/TabPage.test.jsx b/src/tab-page/TabPage.test.jsx index 802a424878..cf468abecd 100644 --- a/src/tab-page/TabPage.test.jsx +++ b/src/tab-page/TabPage.test.jsx @@ -4,6 +4,7 @@ import { } from '../setupTest'; import { TabPage } from './index'; import { useToast } from '../generic/ToastContext'; +import { CourseInfoStripSlot } from '../plugin-slots/CourseInfoStripSlot'; // We should not test `LoadedTabPage` page here, as `TabPage` is used only for passing `passthroughProps`. jest.mock('./LoadedTabPage', () => function () { @@ -14,6 +15,10 @@ jest.mock('../product-tours/newUserCourseHomeTour/LaunchCourseHomeTourButton', ( return
; }); +jest.mock('../plugin-slots/CourseInfoStripSlot', () => ({ + CourseInfoStripSlot: jest.fn(() =>
), +})); + jest.mock('../generic/ToastContext', () => ({ ...jest.requireActual('../generic/ToastContext'), useToast: jest.fn(), @@ -56,6 +61,20 @@ describe('Tab Page', () => { expect(screen.getByTestId('LoadedTabPage')).toBeInTheDocument(); }); + it('renders the course info strip slot', () => { + render(, { wrapWithRouter: true }); + expect(screen.getByTestId('CourseInfoStripSlot')).toBeInTheDocument(); + expect(CourseInfoStripSlot).toHaveBeenCalledWith({ courseId: 'test-course' }, expect.anything()); + }); + + it('does not render the course info strip slot while the course is loading', () => { + render( + , + { wrapWithRouter: true }, + ); + expect(screen.queryByTestId('CourseInfoStripSlot')).not.toBeInTheDocument(); + }); + it('renders the screen-reader tour button on the outline tab', () => { render(, { wrapWithRouter: true }); expect(screen.getByTestId('sr-tour-button')).toBeInTheDocument(); diff --git a/src/tab-page/TabPage.tsx b/src/tab-page/TabPage.tsx index a2521bb1fc..77a1f7ce96 100644 --- a/src/tab-page/TabPage.tsx +++ b/src/tab-page/TabPage.tsx @@ -1,12 +1,11 @@ import React, { type ReactNode } from 'react'; import { useIntl } from '@edx/frontend-platform/i18n'; import { Navigate } from 'react-router-dom'; -import type { UseQueryResult } from '@tanstack/react-query'; import { Toast } from '@openedx/paragon'; import { FooterSlot } from '@edx/frontend-component-footer'; -import { getErrorDetail } from '@src/data/http-error'; import HeaderSlot from '../plugin-slots/HeaderSlot'; +import { CourseInfoStripSlot } from '../plugin-slots/CourseInfoStripSlot'; import PageLoading from '../generic/PageLoading'; import { getAccessDeniedRedirectUrl } from '../shared/access'; import type { CourseHomeMeta } from '../course-home/data/api'; @@ -15,17 +14,11 @@ import { useToast } from '../generic/ToastContext'; import genericMessages from '../generic/messages'; import messages from './messages'; import LoadedTabPage from './LoadedTabPage'; +import { deriveView, type TabStatus } from './utils'; import LaunchCourseHomeTourButton from '../product-tours/newUserCourseHomeTour/LaunchCourseHomeTourButton'; import { TourProvider } from '../product-tours/TourContext'; -// A tab hands TabPage its metadata + tab-data queries and lets TabPage derive the view; a tab -// whose data comes from more than one query passes them as `tabDataQueries`. -export type CourseStatus = { - metadataQuery: UseQueryResult; -} & ( - | { tabDataQuery?: UseQueryResult; tabDataQueries?: never } - | { tabDataQuery?: never; tabDataQueries: UseQueryResult[] } -); +export type CourseStatus = TabStatus; export interface TabPageProps { activeTabSlug: string; @@ -35,40 +28,6 @@ export interface TabPageProps { children?: ReactNode; } -interface TabView { - isLoading: boolean; - isError: boolean; - isDenied: boolean; - errorDetails?: string[]; -} - -const getErrorDetails = (queries: { error: unknown }[]): string[] => { - const details = queries.flatMap((query) => getErrorDetail(query.error) || []); - return [...new Set(details)]; -}; - -const deriveView = (courseStatus: CourseStatus): TabView => { - const view = { isLoading: false, isError: false, isDenied: false }; - - // Access is read from the metadata query, resolved before tabData is considered. - const { - metadataQuery, - tabDataQuery, - tabDataQueries = tabDataQuery ? [tabDataQuery] : [], - } = courseStatus; - if (metadataQuery.isError) { - return { ...view, isError: true, errorDetails: getErrorDetails([metadataQuery]) }; - } - if (metadataQuery.isPending) { return { ...view, isLoading: true }; } - if (tabDataQueries.some((query) => query.isPending)) { return { ...view, isLoading: true }; } - if (!metadataQuery.data?.courseAccess?.hasAccess) { return { ...view, isDenied: true }; } - const failedQueries = tabDataQueries.filter((query) => query.isError); - if (failedQueries.length > 0) { - return { ...view, isError: true, errorDetails: getErrorDetails(failedQueries) }; - } - return view; -}; - const TabPage = ({ activeTabSlug, courseId, @@ -88,7 +47,7 @@ const TabPage = ({ const { isLoading, isError, isDenied, errorDetails, - } = deriveView(courseStatus); + } = deriveView(courseStatus, (metadata) => !!metadata.courseAccess?.hasAccess); if (isDenied) { const redirectUrl = getAccessDeniedRedirectUrl(courseId, activeTabSlug, courseAccess, start); @@ -152,6 +111,7 @@ const TabPage = ({ {shouldRenderContent && renderToast()} {shouldRenderContent && renderSrOnlyTourButton()} + {shouldRenderContent && } {isLoading && renderLoading()} {shouldRenderContent && renderLoadedTabPage()} {isError && renderError()} diff --git a/src/tab-page/utils.ts b/src/tab-page/utils.ts new file mode 100644 index 0000000000..6bf9c2e928 --- /dev/null +++ b/src/tab-page/utils.ts @@ -0,0 +1,51 @@ +import type { UseQueryResult } from '@tanstack/react-query'; + +import { getErrorDetail } from '@src/data/http-error'; + +// A tab hands TabPage its metadata + tab-data queries and lets TabPage derive the view; a tab +// whose data comes from more than one query passes them as `tabDataQueries`. +export type TabStatus = { + metadataQuery: UseQueryResult; +} & ( + | { tabDataQuery?: UseQueryResult; tabDataQueries?: never } + | { tabDataQuery?: never; tabDataQueries: UseQueryResult[] } +); + +export interface TabView { + isLoading: boolean; + isError: boolean; + isDenied: boolean; + errorDetails?: string[]; +} + +const getErrorDetails = (queries: { error: unknown }[]): string[] => { + const details = queries.flatMap((query) => getErrorDetail(query.error) || []); + return [...new Set(details)]; +}; + +// `hasAccess` tells whether the resolved metadata grants access; pages without an access +// check omit it. +export const deriveView = ( + status: TabStatus, + hasAccess: (metadata: TMetadata) => boolean = () => true, +): TabView => { + const view = { isLoading: false, isError: false, isDenied: false }; + + // Access is read from the metadata query, resolved before tabData is considered. + const { + metadataQuery, + tabDataQuery, + tabDataQueries = tabDataQuery ? [tabDataQuery] : [], + } = status; + if (metadataQuery.isError) { + return { ...view, isError: true, errorDetails: getErrorDetails([metadataQuery]) }; + } + if (metadataQuery.isPending) { return { ...view, isLoading: true }; } + if (tabDataQueries.some((query) => query.isPending)) { return { ...view, isLoading: true }; } + if (!metadataQuery.data || !hasAccess(metadataQuery.data)) { return { ...view, isDenied: true }; } + const failedQueries = tabDataQueries.filter((query) => query.isError); + if (failedQueries.length > 0) { + return { ...view, isError: true, errorDetails: getErrorDetails(failedQueries) }; + } + return view; +};