diff --git a/src/app.test.ts b/src/app.test.ts index 6d140d2380..df20dbf0dc 100644 --- a/src/app.test.ts +++ b/src/app.test.ts @@ -9,6 +9,7 @@ import { } from '@openedx/frontend-base'; import { learningApp } from './index'; +import { courseInfoStripApp } from './widgets/CourseInfoStrip'; import { coursewareSearchApp } from './widgets/CoursewareSearch'; import { coursewareTabApp } from './widgets/CoursewareTab'; import { datesTabApp } from './widgets/DatesTab'; @@ -35,6 +36,7 @@ describe('learningApp', () => { expect(learningApp.appId).toBe('org.openedx.frontend.app.learning'); expect(learningApp.slots).toEqual([ ...(learningHeaderApp.slots ?? []), + ...(courseInfoStripApp.slots ?? []), ...(coursewareSearchApp.slots ?? []), ...(discussionsSidebarApp.slots ?? []), ...(outlineTabApp.slots ?? []), diff --git a/src/pathways/data/__fixtures__/pathways.ts b/src/pathways/data/__fixtures__/pathways.ts new file mode 100644 index 0000000000..7ea458891e --- /dev/null +++ b/src/pathways/data/__fixtures__/pathways.ts @@ -0,0 +1,70 @@ +import type { PathwayData, PathwaysByCourse } from '../types'; + +export const dataEngineering: PathwayData = { + pathway: { + id: 'pathway-1', + content: { displayName: 'Data Engineering Fundamentals' }, + itemCount: 6, + category: 'bootcamp', + categoryLabel: 'Bootcamp', + }, + progress: { completedItemCount: 0 }, + 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], +}; 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..85aa5d64f9 --- /dev/null +++ b/src/pathways/data/api.ts @@ -0,0 +1,8 @@ +import type { 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 => ({}); diff --git a/src/pathways/data/apiHooks.test.tsx b/src/pathways/data/apiHooks.test.tsx new file mode 100644 index 0000000000..3d500d9561 --- /dev/null +++ b/src/pathways/data/apiHooks.test.tsx @@ -0,0 +1,81 @@ +import { renderHook, waitFor } from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; + +import { getPathwaysByCourse } from './api'; +import { useCoursePathways } from './apiHooks'; +import { + courseIdWithPathways, + courseIdWithoutPathways, + dataEngineering, + machineLearning, + pathwaysByCourse, +} from './__fixtures__/pathways'; + +jest.mock('./api', () => ({ + getPathwaysByCourse: jest.fn(), +})); + +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(() => { + 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(); + }); + }); +}); diff --git a/src/pathways/data/apiHooks.ts b/src/pathways/data/apiHooks.ts new file mode 100644 index 0000000000..d8ebf43321 --- /dev/null +++ b/src/pathways/data/apiHooks.ts @@ -0,0 +1,17 @@ +import { appId } from '@src/constants'; +import { skipToken, useQuery } from '@tanstack/react-query'; + +import { getPathwaysByCourse } from './api'; +import type { PathwayData } from './types'; + +export const coursePathwaysQueryKeys = { + all: [appId, 'coursePathways'] as const, + course: (courseId: string) => [...coursePathwaysQueryKeys.all, courseId] 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!] ?? [], +}); diff --git a/src/pathways/data/types.ts b/src/pathways/data/types.ts new file mode 100644 index 0000000000..ff235c0cf8 --- /dev/null +++ b/src/pathways/data/types.ts @@ -0,0 +1,22 @@ +// 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 type PathwaysByCourse = Record; diff --git a/src/pathways/pathways-strip/CoursePathwaysStrip.scss b/src/pathways/pathways-strip/CoursePathwaysStrip.scss new file mode 100644 index 0000000000..cdcf8c0f3f --- /dev/null +++ b/src/pathways/pathways-strip/CoursePathwaysStrip.scss @@ -0,0 +1,54 @@ +.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; + + // 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, right after the last visible label and separated from it by a vertical line + .course-pathways-strip-trigger { + flex-shrink: 0; + margin-inline-start: 0.75rem; + 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..44c23f439a --- /dev/null +++ b/src/pathways/pathways-strip/CoursePathwaysStrip.test.tsx @@ -0,0 +1,116 @@ +import { render, screen } from '@testing-library/react'; +import { IntlProvider } from '@openedx/frontend-base'; + +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('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); + }); +}); diff --git a/src/pathways/pathways-strip/CoursePathwaysStrip.tsx b/src/pathways/pathways-strip/CoursePathwaysStrip.tsx new file mode 100644 index 0000000000..d69ae78714 --- /dev/null +++ b/src/pathways/pathways-strip/CoursePathwaysStrip.tsx @@ -0,0 +1,58 @@ +import { FormattedMessage } from '@openedx/frontend-base'; +import { Container } from '@openedx/paragon'; + +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; +} + +export interface CoursePathwaysStripProps { + courseId?: string; +} + +const PathwayLabel = ({ pathway }: PathwayLabelProps) => ( + // TODO Link to the pathway outline once its URL is known + + {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..fd8abb5772 --- /dev/null +++ b/src/pathways/pathways-strip/MorePathwaysPopover.test.tsx @@ -0,0 +1,48 @@ +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { IntlProvider } from '@openedx/frontend-base'; + +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', async () => { + renderComponent(); + const trigger = await screen.findByRole('button', { name: 'Show 2 more pathways' }); + expect(trigger).toHaveTextContent('2'); + }); + + it('uses the singular accessible label for a single pathway', async () => { + renderComponent([dataEngineering]); + expect(await screen.findByRole('button', { name: 'Show 1 more pathway' })).toBeInTheDocument(); + }); + + it('does not show the pathways until the trigger is clicked', async () => { + renderComponent(); + await screen.findByRole('button', { name: 'Show 2 more pathways' }); + 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.getByText('Data Engineering Fundamentals')).toBeInTheDocument(); + expect(screen.getByText('Introduction to Machine Learning')).toBeInTheDocument(); + }); + + 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..7a2ca2a47c --- /dev/null +++ b/src/pathways/pathways-strip/MorePathwaysPopover.tsx @@ -0,0 +1,47 @@ +import { useState } from 'react'; +import { useIntl } from '@openedx/frontend-base'; +import { + Badge, Button, ModalPopup, useToggle, +} from '@openedx/paragon'; +import { ArrowDropDown } from '@openedx/paragon/icons'; + +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) => ( + // TODO Link to the pathway outline once its URL is known +
  • {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..a083627bd0 --- /dev/null +++ b/src/pathways/pathways-strip/hooks.test.tsx @@ -0,0 +1,201 @@ +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); + }) +); + +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(); + }); + + 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 + jest.spyOn(window, 'getComputedStyle').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..c30986b0b2 --- /dev/null +++ b/src/pathways/pathways-strip/hooks.ts @@ -0,0 +1,60 @@ +import { useLayoutEffect, useRef, useState } from 'react'; + +import type { PathwayData } from '../data/types'; + +// Width kept free after the last visible label for the "+N" popover trigger, including its +// 0.75rem (12px) start margin +const COUNTER_RESERVED_WIDTH = 86; + +/** + * 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..eaf51e9721 --- /dev/null +++ b/src/pathways/pathways-strip/messages.ts @@ -0,0 +1,16 @@ +import { defineMessages } from '@openedx/frontend-base'; + +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/slots.tsx b/src/slots.tsx index 8983d021a3..7461bb9b48 100644 --- a/src/slots.tsx +++ b/src/slots.tsx @@ -1,5 +1,6 @@ import { SlotOperation } from '@openedx/frontend-base'; +import { courseInfoStripApp } from './widgets/CourseInfoStrip'; import { coursewareSearchApp } from './widgets/CoursewareSearch'; import { coursewareTabApp } from './widgets/CoursewareTab'; import { datesTabApp } from './widgets/DatesTab'; @@ -11,6 +12,7 @@ import { progressTabApp } from './widgets/ProgressTab'; const slots: SlotOperation[] = [ ...(learningHeaderApp.slots ?? []), + ...(courseInfoStripApp.slots ?? []), ...(coursewareSearchApp.slots ?? []), ...(discussionsSidebarApp.slots ?? []), ...(outlineTabApp.slots ?? []), diff --git a/src/slots/CourseInfoStripSlot/README.md b/src/slots/CourseInfoStripSlot/README.md new file mode 100644 index 0000000000..dfbdc655f7 --- /dev/null +++ b/src/slots/CourseInfoStripSlot/README.md @@ -0,0 +1,66 @@ +# Course Info Strip Slot + +### Slot ID: `org.openedx.frontend.slot.learning.courseInfoStrip.v1` + +### Slot Props + +* `courseId?: string` - the ID of the current course. + +## Description + +This slot renders a strip between the header and the course tabs of every course page, with 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. Learning's [Course Info Strip widget](../../widgets/CourseInfoStrip/README.md) places it in the shell's header. + +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. + +## Examples + +### Default content + +![Course info strip slot with default content](./images/screenshot_default.png) + +### Replaced with a custom strip + +![Course info strip slot with a custom strip](./images/screenshot_custom.png) + +Add the following to your site config to replace the default strip with a custom one. The diff below is against this package's `site.config.dev.tsx`. + +```diff +-import { EnvironmentTypes, SiteConfig, footerApp, headerApp, shellApp } from '@openedx/frontend-base'; ++import { ++ EnvironmentTypes, SiteConfig, WidgetOperationTypes, footerApp, headerApp, shellApp, ++} from '@openedx/frontend-base'; + + import { learningApp } from './src'; + + import '@openedx/frontend-base/shell/style'; + ++const TrialStrip = () => ( ++
++ Your trial access to this course ends in 6 days. ++
++); ++ + const siteConfig: SiteConfig = { + // ... + apps: [ + shellApp, + headerApp, + footerApp, + learningApp, ++ { ++ appId: 'org.example.app.myPlugin', ++ slots: [ ++ { ++ slotId: 'org.openedx.frontend.slot.learning.courseInfoStrip.v1', ++ id: 'org.example.widget.trialStrip', ++ op: WidgetOperationTypes.REPLACE, ++ relatedId: 'defaultContent', ++ component: TrialStrip, ++ }, ++ ], ++ }, + ], + }; +``` + +To hide the strip, use `WidgetOperationTypes.REMOVE` with `relatedId: 'defaultContent'`. diff --git a/src/slots/CourseInfoStripSlot/images/screenshot_custom.png b/src/slots/CourseInfoStripSlot/images/screenshot_custom.png new file mode 100644 index 0000000000..976013821b Binary files /dev/null and b/src/slots/CourseInfoStripSlot/images/screenshot_custom.png differ diff --git a/src/slots/CourseInfoStripSlot/images/screenshot_default.png b/src/slots/CourseInfoStripSlot/images/screenshot_default.png new file mode 100644 index 0000000000..95c73b3521 Binary files /dev/null and b/src/slots/CourseInfoStripSlot/images/screenshot_default.png differ diff --git a/src/slots/CourseInfoStripSlot/index.test.tsx b/src/slots/CourseInfoStripSlot/index.test.tsx new file mode 100644 index 0000000000..f778897c49 --- /dev/null +++ b/src/slots/CourseInfoStripSlot/index.test.tsx @@ -0,0 +1,37 @@ +import { WidgetOperationTypes } from '@openedx/frontend-base'; +import { screen } from '@testing-library/react'; + +import { render } from '@src/tests/render'; +import { addSlotOperations } from '@src/tests/slots'; + +import CourseInfoStripSlot, { courseInfoStripSlotId } from '.'; + +jest.mock('@src/pathways/pathways-strip/CoursePathwaysStrip', () => ({ + CoursePathwaysStrip: ({ courseId }: { courseId?: string }) => `Course pathways strip: ${courseId}`, +})); + +describe('CourseInfoStripSlot', () => { + const courseId = 'course-v1:edX+DemoX+Demo_Course'; + + it('renders the course pathways strip by default', () => { + render(); + + expect(screen.getByText(`Course pathways strip: ${courseId}`)).toBeInTheDocument(); + }); + + it('passes its props to a widget that replaces the default content', () => { + const Widget = jest.fn(() => null); + addSlotOperations([{ + slotId: courseInfoStripSlotId, + id: 'org.example.widget', + op: WidgetOperationTypes.REPLACE, + relatedId: 'defaultContent', + component: Widget, + }]); + + render(); + + expect(screen.queryByText(`Course pathways strip: ${courseId}`)).not.toBeInTheDocument(); + expect(Widget.mock.calls[0][0]).toEqual({ courseId }); + }); +}); diff --git a/src/slots/CourseInfoStripSlot/index.tsx b/src/slots/CourseInfoStripSlot/index.tsx new file mode 100644 index 0000000000..5d4207127c --- /dev/null +++ b/src/slots/CourseInfoStripSlot/index.tsx @@ -0,0 +1,17 @@ +import { Slot } from '@openedx/frontend-base'; + +import { CoursePathwaysStrip } from '@src/pathways/pathways-strip/CoursePathwaysStrip'; + +export const courseInfoStripSlotId = 'org.openedx.frontend.slot.learning.courseInfoStrip.v1'; + +export interface CourseInfoStripSlotProps { + courseId?: string; +} + +const CourseInfoStripSlot = ({ courseId }: CourseInfoStripSlotProps) => ( + + + +); + +export default CourseInfoStripSlot; diff --git a/src/slots/README.md b/src/slots/README.md index 26fcae63c8..5e954d9246 100644 --- a/src/slots/README.md +++ b/src/slots/README.md @@ -14,6 +14,14 @@ Each tab's section starts with the slot that holds the whole tab (`outlineTab`, For the operations Learning applies to other apps' slots (the shell's header and course bar), see `src/slots.tsx` and the [widgets](../widgets/README.md). See frontend-base's [ADR 0009](https://github.com/openedx/frontend-base/blob/main/docs/decisions/0009-slot-naming-and-lifecycle.rst) for slot naming and lifecycle. +## All course pages + +This slot sits in the shell's header, inside Learning's [Course Info Strip widget](../widgets/CourseInfoStrip/README.md). + +| Slot | ID | Constant | +|---|---|---| +| [Course Info Strip](./CourseInfoStripSlot/README.md) | `courseInfoStrip` | `courseInfoStripSlotId` | + ## Course Outline tab | Slot | ID | Constant | diff --git a/src/slots/index.ts b/src/slots/index.ts index 4674d483c4..f12eea4b9c 100644 --- a/src/slots/index.ts +++ b/src/slots/index.ts @@ -23,6 +23,7 @@ export { courseHomeSectionOutlineSlotId, type CourseHomeSectionOutlineSlotProps, } from './CourseHomeSectionOutlineSlot'; +export { courseInfoStripSlotId, type CourseInfoStripSlotProps } from './CourseInfoStripSlot'; export { courseOutlineMobileSidebarTriggerSlotId, type CourseOutlineMobileSidebarTriggerSlotProps, diff --git a/src/style.scss b/src/style.scss index 056c863666..7e6def1cbe 100644 --- a/src/style.scss +++ b/src/style.scss @@ -12,6 +12,7 @@ @use "./courseware/course/course-exit/CourseRecommendations"; @use "./courseware/course/sidebar/common/SidebarBase"; @use "./courseware/course/sidebar/sidebars/course-outline/CourseOutlineTray"; +@use "./pathways/pathways-strip/CoursePathwaysStrip"; @use "./product-tours/newUserCourseHomeTour/NewUserCourseHomeTourModal"; @use "./shared/streak-celebration/StreakCelebrationModal"; @use "./widgets/DiscussionsSidebar/Discussions"; diff --git a/src/widgets/CourseInfoStrip/CourseInfoStripWidget.test.tsx b/src/widgets/CourseInfoStrip/CourseInfoStripWidget.test.tsx new file mode 100644 index 0000000000..c66460208e --- /dev/null +++ b/src/widgets/CourseInfoStrip/CourseInfoStripWidget.test.tsx @@ -0,0 +1,65 @@ +import { QueryClientProvider } from '@tanstack/react-query'; +import { render, screen } from '@testing-library/react'; +import { type ComponentType } from 'react'; +import { MemoryRouter, Outlet, Route, Routes } from 'react-router-dom'; + +import { courseHomeMetaQuery } from '@src/course-home/data/apiHooks'; +import { createTestQueryClient, seedQueryData } from '@src/tests/queryClient'; + +import { LazyCourseInfoStripWidget } from './app'; +import CourseInfoStripWidget from './CourseInfoStripWidget'; + +jest.mock('@src/slots/CourseInfoStripSlot', () => ({ courseId }: { courseId?: string }) => ( + `Course info strip slot: ${courseId}` +)); + +const courseId = 'course-v1:edX+DemoX+Demo_Course'; + +// The widget renders in the shell's header: a layout route above the page, not inside it. +const renderInHeader = ( + { metadata, Widget = CourseInfoStripWidget }: { metadata?: Record; Widget?: ComponentType } = {}, +) => { + const queryClient = createTestQueryClient(); + if (metadata) { + seedQueryData(queryClient, courseHomeMetaQuery(courseId).queryKey, metadata); + } + const result = render( + + + +
}> + } /> + +
+
+
, + ); + return { ...result, queryClient }; +}; + +describe('CourseInfoStripWidget', () => { + it('renders the course info strip slot for the course in the page route', () => { + renderInHeader({ metadata: { courseAccess: { hasAccess: true } } }); + + expect(screen.getByText(`Course info strip slot: ${courseId}`)).toBeInTheDocument(); + }); + + it('renders nothing and requests nothing while the frame has not loaded the metadata', () => { + const { container, queryClient } = renderInHeader(); + + expect(container.querySelector('header')).toBeEmptyDOMElement(); + expect(queryClient.getQueryState(courseHomeMetaQuery(courseId).queryKey)?.fetchStatus).toBe('idle'); + }); + + it('renders nothing for a learner without access to the course', () => { + const { container } = renderInHeader({ metadata: { courseAccess: { hasAccess: false } } }); + + expect(container.querySelector('header')).toBeEmptyDOMElement(); + }); + + it('loads its code on first render', async () => { + renderInHeader({ metadata: { courseAccess: { hasAccess: true } }, Widget: LazyCourseInfoStripWidget }); + + expect(await screen.findByText(`Course info strip slot: ${courseId}`)).toBeInTheDocument(); + }); +}); diff --git a/src/widgets/CourseInfoStrip/CourseInfoStripWidget.tsx b/src/widgets/CourseInfoStrip/CourseInfoStripWidget.tsx new file mode 100644 index 0000000000..3bc8cfb8b5 --- /dev/null +++ b/src/widgets/CourseInfoStrip/CourseInfoStripWidget.tsx @@ -0,0 +1,17 @@ +import { useParams } from 'react-router-dom'; + +import { useCourseHomeMeta } from '@src/course-home/data/apiHooks'; +import CourseInfoStripSlot from '@src/slots/CourseInfoStripSlot'; + +const CourseInfoStripWidget = () => { + const { courseId } = useParams(); + const { data } = useCourseHomeMeta(courseId, { enabled: false }); + + if (!data?.courseAccess?.hasAccess) { + return null; + } + + return ; +}; + +export default CourseInfoStripWidget; diff --git a/src/widgets/CourseInfoStrip/README.md b/src/widgets/CourseInfoStrip/README.md new file mode 100644 index 0000000000..703d2af3fe --- /dev/null +++ b/src/widgets/CourseInfoStrip/README.md @@ -0,0 +1,54 @@ +# Course Info Strip Widget + +### Widget ID: `org.openedx.frontend.widget.learning.courseInfoStrip.v1` + +### Slot ID (owned by the shell): `org.openedx.frontend.slot.header.masqueradeBar.v1` + +### Props: none + +## Description + +The strip with information about the current course, between the shell's header and its course bar: above the masquerade bar when it shows, and above the course tabs. The widget renders Learning's [Course Info Strip slot](../../slots/CourseInfoStripSlot/README.md), whose default content lists the learner's pathways that include the course. Learning inserts it on its course routes only (condition: `org.openedx.frontend.role.learningCourse` active). + +The widget renders nothing until the course page has loaded the course's metadata, and nothing for a learner without access to the course. + +The widget takes the course ID from the URL. Its code loads on first render, in a chunk of its own. + +To change what the strip shows, use the [Course Info Strip slot](../../slots/CourseInfoStripSlot/README.md). To remove the strip altogether, remove this widget. + +## Examples + +### Remove the widget + +The diff below is against this package's `site.config.dev.tsx`. + +```diff +-import { EnvironmentTypes, SiteConfig, footerApp, headerApp, shellApp } from '@openedx/frontend-base'; ++import { ++ EnvironmentTypes, SiteConfig, WidgetOperationTypes, footerApp, headerApp, shellApp, ++} from '@openedx/frontend-base'; + + import { learningApp } from './src'; + + import '@openedx/frontend-base/shell/style'; + + const siteConfig: SiteConfig = { + // ... + apps: [ + shellApp, + headerApp, + footerApp, + learningApp, ++ { ++ appId: 'org.example.app.myPlugin', ++ slots: [ ++ { ++ slotId: 'org.openedx.frontend.slot.header.masqueradeBar.v1', ++ op: WidgetOperationTypes.REMOVE, ++ relatedId: 'org.openedx.frontend.widget.learning.courseInfoStrip.v1', ++ }, ++ ], ++ }, + ], + }; +``` diff --git a/src/widgets/CourseInfoStrip/app.test.tsx b/src/widgets/CourseInfoStrip/app.test.tsx new file mode 100644 index 0000000000..25e3b86fec --- /dev/null +++ b/src/widgets/CourseInfoStrip/app.test.tsx @@ -0,0 +1,22 @@ +import { WidgetOperationTypes } from '@openedx/frontend-base'; + +import { learningCourseRole } from '@src/constants'; +import slots from '@src/slots'; + +import courseInfoStripApp, { courseInfoStripWidgetId, LazyCourseInfoStripWidget } from './app'; + +describe('courseInfoStripApp', () => { + it("prepends the strip to the shell's masquerade bar on Learning course routes", () => { + expect(courseInfoStripApp.slots).toEqual([{ + slotId: 'org.openedx.frontend.slot.header.masqueradeBar.v1', + id: courseInfoStripWidgetId, + op: WidgetOperationTypes.PREPEND, + component: LazyCourseInfoStripWidget, + condition: { active: [learningCourseRole] }, + }]); + }); + + it("is part of Learning's slot operations", () => { + expect(slots).toEqual(expect.arrayContaining(courseInfoStripApp.slots ?? [])); + }); +}); diff --git a/src/widgets/CourseInfoStrip/app.tsx b/src/widgets/CourseInfoStrip/app.tsx new file mode 100644 index 0000000000..a88bd450be --- /dev/null +++ b/src/widgets/CourseInfoStrip/app.tsx @@ -0,0 +1,29 @@ +import { App, WidgetOperationTypes } from '@openedx/frontend-base'; +import { lazy, Suspense } from 'react'; + +import { learningCourseRole } from '@src/constants'; + +export const courseInfoStripWidgetId = 'org.openedx.frontend.widget.learning.courseInfoStrip.v1'; + +const CourseInfoStripWidget = lazy(() => import(/* webpackChunkName: "learning-course-info-strip" */ './CourseInfoStripWidget')); + +export const LazyCourseInfoStripWidget = () => ( + + + +); + +const app: App = { + appId: 'org.openedx.frontend.app.learning.courseInfoStrip', + slots: [ + { + slotId: 'org.openedx.frontend.slot.header.masqueradeBar.v1', + id: courseInfoStripWidgetId, + op: WidgetOperationTypes.PREPEND, + component: LazyCourseInfoStripWidget, + condition: { active: [learningCourseRole] }, + }, + ], +}; + +export default app; diff --git a/src/widgets/CourseInfoStrip/index.ts b/src/widgets/CourseInfoStrip/index.ts new file mode 100644 index 0000000000..35e2260572 --- /dev/null +++ b/src/widgets/CourseInfoStrip/index.ts @@ -0,0 +1 @@ +export { default as courseInfoStripApp, courseInfoStripWidgetId } from './app'; diff --git a/src/widgets/README.md b/src/widgets/README.md index a6e15d515b..d37023b50c 100644 --- a/src/widgets/README.md +++ b/src/widgets/README.md @@ -13,6 +13,7 @@ Learning's app declares these in its `slots` (see `src/slots.tsx`), so every sit | [Course info](./LearningHeader/README.md#course-info) | `courseInfo` | the shell's header, `org.openedx.frontend.slot.header.primaryLinks.v1` | | [Help](./LearningHeader/README.md#help) | `org.openedx.frontend.widget.header.help.v1` | the shell's header, `org.openedx.frontend.slot.header.secondaryLinks.v1` | | [Dashboard menu item](./LearningHeader/README.md#dashboard) | `headerLinkDashboard` | the shell's header, `org.openedx.frontend.slot.header.authenticatedMenu.v1` | +| [Course info strip](./CourseInfoStrip/README.md) | `courseInfoStrip` | the shell's header, `org.openedx.frontend.slot.header.masqueradeBar.v1` | | [Courseware search](./CoursewareSearch/README.md) | `coursewareSearch` | the shell's course bar, `org.openedx.frontend.slot.header.courseNavigationBar.extraContent.v1` | | [Discussions sidebar](./DiscussionsSidebar/README.md) | `discussionsSidebar` (exported as `discussionsSidebarWidgetId`) | Learning's [auxiliary sidebar](../slots/AuxiliarySidebarSlot/README.md) and [its trigger slot](../slots/AuxiliarySidebarTriggerSlot/README.md) |