Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions shell/header/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export default function Header() {
<Slot id="org.openedx.frontend.slot.header.mobile.v1" />
</nav>
</header>
<Slot id="org.openedx.frontend.slot.header.masqueradeBar.v1" />
<Slot id="org.openedx.frontend.slot.header.courseNavigationBar.v1" />
</>
);
Expand Down
11 changes: 11 additions & 0 deletions shell/header/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ import MobileNavLinks from './mobile/MobileNavLinks';

import messages from '../Shell.messages';
import CourseTabsNavigation from './course-navigation-bar/CourseTabsNavigation';
import MasqueradeBar from './masquerade-bar/MasqueradeBar';
import { isCourseNavigationRoute } from './course-navigation-bar/utils';
import { isMasqueradeBarRoute } from './masquerade-bar/utils';
import { appId } from './constants';
import './app.scss';

Expand Down Expand Up @@ -147,6 +149,15 @@ const config: App = {
condition: {
callback: () => isCourseNavigationRoute(),
}
},
{
slotId: 'org.openedx.frontend.slot.header.masqueradeBar.v1',
id: 'org.openedx.frontend.widget.header.masqueradeBar.v1',
op: WidgetOperationTypes.APPEND,
component: MasqueradeBar,
condition: {
callback: () => isMasqueradeBarRoute(),
}
}
]
};
Expand Down
1 change: 1 addition & 0 deletions shell/header/constants.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export const appId = 'org.openedx.frontend.app.header';
export const providesCourseNavigationRolesId = 'org.openedx.frontend.provides.courseNavigationRoles.v1';
export const providesMasqueradeBarRolesId = 'org.openedx.frontend.provides.masqueradeBarRoles.v1';
2 changes: 1 addition & 1 deletion shell/header/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export { default as headerApp } from './app';
export { providesCourseNavigationRolesId } from './constants';
export { providesCourseNavigationRolesId, providesMasqueradeBarRolesId } from './constants';
export { default as Header } from './Header';
export { default as HelpButton } from './HelpButton';
export { helpButtonSlotOperation, helpWidgetId } from './helpButtonSlotOperation';
123 changes: 123 additions & 0 deletions shell/header/masquerade-bar/MasqueradeBar.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import '@testing-library/jest-dom';
import { render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
import { IntlProvider } from 'react-intl';
import MasqueradeBar from './MasqueradeBar';
import * as api from './masquerade-widget/data/api';
import { getSiteConfig } from '@openedx/frontend-base';

jest.mock('./masquerade-widget/data/api');
jest.mock('@openedx/frontend-base', () => {
const actual = jest.requireActual('@openedx/frontend-base');
return {
...actual,
getSiteConfig: jest.fn().mockReturnValue({}),
};
});

const mockGetSiteConfig = getSiteConfig as jest.MockedFunction<typeof getSiteConfig>;

const mockGetMasqueradeOptions = api.getMasqueradeOptions as jest.MockedFunction<typeof api.getMasqueradeOptions>;

const COURSE_ID = 'course-v1:edX+DemoX+Demo';
const UNIT_ID = 'block-v1:edX+DemoX+Demo+type@vertical+block@abc123';

const defaultMasqueradeResponse: api.MasqueradeStatus = {
success: true,
active: {
courseKey: COURSE_ID,
groupId: null,
role: 'staff',
userName: null,
userPartitionId: null,
groupName: null,
},
available: [
{ name: 'Staff', role: 'staff' },
{ name: 'Specific Student...', role: 'student', userName: '' },
],
};

function renderMasqueradeBar(
path = `/course/${COURSE_ID}/unit/${UNIT_ID}`,
siteConfig: Record<string, unknown> = {},
) {
mockGetMasqueradeOptions.mockResolvedValue(defaultMasqueradeResponse);
mockGetSiteConfig.mockReturnValue(siteConfig as any);

const result = render(
<IntlProvider locale="en">
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="/course/:courseId/unit/:unitId" element={<MasqueradeBar />} />
<Route path="/course/:courseId" element={<MasqueradeBar />} />
</Routes>
</MemoryRouter>
</IntlProvider>,
);

return result;
}

describe('MasqueradeBar', () => {
afterEach(() => {
jest.restoreAllMocks();
});

it('renders the masquerade widget and does not display alerts by default', async () => {
renderMasqueradeBar();

await waitFor(() => expect(mockGetMasqueradeOptions).toHaveBeenCalledWith(COURSE_ID));
expect(screen.getByRole('toolbar', { name: /masquerade/i })).toBeInTheDocument();
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
});

it('displays masquerade error when API returns success: false', async () => {
mockGetMasqueradeOptions.mockResolvedValue({
...defaultMasqueradeResponse,
success: false,
});

renderMasqueradeBar();

await waitFor(() => expect(mockGetMasqueradeOptions).toHaveBeenCalled());
expect(screen.getByRole('toolbar', { name: /masquerade/i })).toBeInTheDocument();
});

it('displays Studio link when studioBaseUrl is configured', async () => {
renderMasqueradeBar(
`/course/${COURSE_ID}/unit/${UNIT_ID}`,
{ studioBaseUrl: 'http://localhost:18010' },
);

await waitFor(() => expect(mockGetMasqueradeOptions).toHaveBeenCalled());

expect(screen.getByText('View course in:')).toBeInTheDocument();
const studioLink = screen.getByRole('link', { name: 'Studio' });
expect(studioLink).toHaveAttribute('href', `http://localhost:18010/container/${UNIT_ID}`);
});

it('builds Studio URL with courseId when unitId is not in the route', async () => {
renderMasqueradeBar(
`/course/${COURSE_ID}`,
{ studioBaseUrl: 'http://localhost:18010' },
);

await waitFor(() => expect(mockGetMasqueradeOptions).toHaveBeenCalled());

const studioLink = screen.getByRole('link', { name: 'Studio' });
expect(studioLink).toHaveAttribute('href', `http://localhost:18010/course/${COURSE_ID}`);
});

it('does not display Studio link when studioBaseUrl is not configured', async () => {
renderMasqueradeBar(
`/course/${COURSE_ID}/unit/${UNIT_ID}`,
{},
);

await waitFor(() => expect(mockGetMasqueradeOptions).toHaveBeenCalled());

expect(screen.queryByText('View course in:')).not.toBeInTheDocument();
expect(screen.queryByText('Studio')).not.toBeInTheDocument();
});
});
58 changes: 58 additions & 0 deletions shell/header/masquerade-bar/MasqueradeBar.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import React, { useState } from 'react';
import { useParams } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { useIntl } from '@openedx/frontend-base';
import { Alert } from '@openedx/paragon';

import MasqueradeWidget, { useMasqueradeWidget } from './masquerade-widget';
import StudioLink from './StudioLink';

/**
* Inner component that has access to QueryClientProvider context.
* The hook needs useQueryClient which requires a provider above it.
*/
const MasqueradeBarContent: React.FC<{ courseId: string, unitId: string }> = ({
courseId,
unitId,
}) => {
const masquerade = useMasqueradeWidget(courseId);
const { formatMessage } = useIntl();

return (
<div role="toolbar" aria-label="Masquerade toolbar">
<div className="bg-primary text-white">
<div className="container-xl py-3 d-md-flex justify-content-end align-items-start">
<div className="align-items-center flex-grow-1 d-md-flex mx-1 my-1">
<MasqueradeWidget masquerade={masquerade} />
</div>
<StudioLink courseId={courseId} unitId={unitId} />
</div>
</div>
{masquerade.queryErrorMessage && (
<div className="container-xl mt-3">
<Alert variant="danger" dismissible={false}>
{formatMessage(masquerade.queryErrorMessage)}
</Alert>
</div>
)}
</div>
);
};

const MasqueradeBar: React.FC = () => {
const { courseId = '', unitId = '' } = useParams();

const [queryClient] = useState(() => new QueryClient({
defaultOptions: {
queries: { retry: false, refetchOnWindowFocus: false },
},
}));

return (
<QueryClientProvider client={queryClient}>
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not necessary.

<MasqueradeBarContent courseId={courseId} unitId={unitId} />
</QueryClientProvider>
);
};

export default MasqueradeBar;
44 changes: 44 additions & 0 deletions shell/header/masquerade-bar/StudioLink.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import React from 'react';
import { useIntl, FormattedMessage, getSiteConfig } from '@openedx/frontend-base';

import messages from './messages';

function getStudioUrl(courseId: string, unitId: string): string | undefined {
const urlBase = getSiteConfig().studioBaseUrl;
if (!urlBase) {
return undefined;
}
if (unitId) {
return `${urlBase}/container/${unitId}`;
}
if (courseId) {
return `${urlBase}/course/${courseId}`;
}
return undefined;
}

interface StudioLinkProps {
courseId: string,
unitId: string,
}

const StudioLink: React.FC<StudioLinkProps> = ({ courseId, unitId }) => {
const { formatMessage } = useIntl();
const url = getStudioUrl(courseId, unitId);

if (!url) {
return null;
}

return (
<>
<hr className="border-light" />
<span className="mr-2 mt-1 col-form-label"><FormattedMessage {...messages.titleViewCourseIn} /></span>
<span className="mx-1 my-1">
<a className="btn btn-inverse-outline-primary" href={url}>{formatMessage(messages.titleStudio)}</a>
</span>
</>
);
};

export default StudioLink;
1 change: 1 addition & 0 deletions shell/header/masquerade-bar/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from './MasqueradeBar';
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import React from 'react';

import type { MasqueradeOption } from './data/api';

export interface MasqueradeContextValue {
select: (option: MasqueradeOption) => void,
selectedOptionName: string | null,
showUserNameInput: boolean,
}

export const MasqueradeContext = React.createContext<MasqueradeContextValue | null>(null);

export function useMasqueradeContext(): MasqueradeContextValue {
const context = React.useContext(MasqueradeContext);
if (context === null) {
throw new Error('useMasqueradeContext must be used within a MasqueradeContext.Provider');
}
return context;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import React from 'react';
import { useIntl } from '@openedx/frontend-base';
import { Form, StatefulButton } from '@openedx/paragon';
import type { MessageDescriptor } from 'react-intl';

import messages from './messages';

interface Props {
userName: string,
setUserName: (value: string) => void,
onSubmit: () => void,
isPending?: boolean,
mutationErrorMessage: MessageDescriptor | string | null,
autoFocus?: boolean,
className?: string,
id?: string,
}

export const MasqueradeUserNameInput: React.FC<Props> = ({
userName,
setUserName,
onSubmit,
isPending = false,
mutationErrorMessage,
autoFocus,
className,
id,
}) => {
const intl = useIntl();
const isInvalid = Boolean(mutationErrorMessage);

const handleKeyDown = React.useCallback((event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === 'Enter') {
onSubmit();
}
}, [onSubmit]);

return (
<div className={className} id={id}>
<div className="d-flex align-items-start gap-2">
<Form.Group isInvalid={isInvalid} className="mb-0 flex-grow-1">
<Form.Control
value={userName}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setUserName(e.target.value)}
label={intl.formatMessage(messages.userNameLabel)}
aria-label={intl.formatMessage(messages.userNameLabel)}
onKeyDown={handleKeyDown}
autoFocus={autoFocus}
/>
{isInvalid && (
<Form.Control.Feedback type="invalid" hasIcon={false}>
{mutationErrorMessage && (
typeof mutationErrorMessage === 'string'
? mutationErrorMessage
: intl.formatMessage(mutationErrorMessage)
)}
</Form.Control.Feedback>
)}
</Form.Group>
<StatefulButton
variant="brand"
state={isPending ? 'pending' : 'default'}
labels={{
default: intl.formatMessage(messages.submit),
pending: intl.formatMessage(messages.submitting),
}}
onClick={onSubmit}
disabled={!userName.trim()}
/>
</div>
</div>
);
};
Loading