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
25 changes: 25 additions & 0 deletions example-publish-button-slot.config.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { DIRECT_PLUGIN, PLUGIN_OPERATIONS } from '@openedx/frontend-plugin-framework';
import HidePublishButtonForStaff from './src/plugin-slots/CourseUnitPublishButtonSlot/example';

// Load environment variables from .env file
const config = {
...process.env,
pluginSlots: {
// Example: Hide the Publish button for staff users
'org.openedx.frontend.authoring.course_unit_publish_button.v1': {
plugins: [
{
op: PLUGIN_OPERATIONS.Replace,
widget: {
id: 'hide_publish_for_staff',
type: DIRECT_PLUGIN,
RenderWidget: HidePublishButtonForStaff,
},
},
],
},
},
};

export default config;

1 change: 1 addition & 0 deletions src/CourseAuthoringContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
courseId: string;
};


Check failure on line 29 in src/CourseAuthoringContext.tsx

View workflow job for this annotation

GitHub Actions / tests

More than 1 blank line not allowed
export const CourseAuthoringProvider = ({
children,
courseId,
Expand Down
36 changes: 35 additions & 1 deletion src/course-team/data/api.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { camelCaseObject, getConfig } from '@edx/frontend-platform';
import { getAuthenticatedHttpClient } from '@edx/frontend-platform/auth';
import { getAuthenticatedHttpClient, getAuthenticatedUser } from '@edx/frontend-platform/auth';

import { USER_ROLES } from '../../constants';

const getApiBaseUrl = () => getConfig().STUDIO_BASE_URL;
export const getCourseTeamApiUrl = (courseId) => `${getApiBaseUrl()}/api/contentstore/v1/course_team/${courseId}`;
export const getCourseRunApiUrl = (courseId) => `${getApiBaseUrl()}/api/v1/course_runs/${courseId}/`;
export const updateCourseTeamUserApiUrl = (courseId, email) => `${getApiBaseUrl()}/course_team/${courseId}/${email}`;

/**
Expand All @@ -19,6 +20,39 @@
return camelCaseObject(data);
}

/**
* Get the current user's role for a course using the course_runs API.
* This uses the existing /api/v1/course_runs/{course_id}/ endpoint.
* @param {string} courseId
* @returns {Promise<{ role: ('instructor'|'staff'|null) }>}
*/
export async function getCourseUserRole(courseId) {
try {
const { data } = await getAuthenticatedHttpClient()
.get(getCourseRunApiUrl(courseId));

const camelCaseData = camelCaseObject(data);
const currentUser = getAuthenticatedUser();
const currentUsername = currentUser?.username;

// The course_runs API returns a 'team' array with user roles
const currentUserInTeam = camelCaseData?.team?.find(
(member) => member.user === currentUsername

Check failure on line 40 in src/course-team/data/api.js

View workflow job for this annotation

GitHub Actions / tests

Missing trailing comma
);

// Return the role in the same format as before
return {
role: currentUserInTeam?.role || null,
};
} catch (error) {
// If there's an error (e.g., 404, 403), return null role
console.error('Error fetching user role from course_runs API:', error);

Check warning on line 49 in src/course-team/data/api.js

View workflow job for this annotation

GitHub Actions / tests

Unexpected console statement
return {
role: null,
};
}
}

/**
* Create course team user.
* @param {string} courseId
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { fetchCourseSectionVerticalData } from '../../../data/thunk';
import { courseSectionVerticalMock } from '../../../__mocks__';
import messages from '../../messages';
import ActionButtons from './ActionButtons';
import { getCourseRunApiUrl } from '../../../../course-team/data/api';

let store;
let axiosMock;
Expand All @@ -38,6 +39,7 @@ describe('<ActionButtons />', () => {
authenticatedUser: {
userId: 3,
username: 'abc123',
email: 'abc123@example.com',
administrator: true,
roles: [],
},
Expand All @@ -54,6 +56,11 @@ describe('<ActionButtons />', () => {
enable_copy_paste_units: true,
},
});
axiosMock
.onGet(getCourseRunApiUrl('course-v1:edX+DemoX+Demo_Course'))
.reply(200, {
team: [{ user: 'abc123', role: 'instructor' }],
});
axiosMock
.onPost(getClipboardUrl())
.reply(200, clipboardUnit);
Expand Down
72 changes: 61 additions & 11 deletions src/course-unit/sidebar/components/sidebar-footer/ActionButtons.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,30 @@
import { useEffect, useMemo, useState } from 'react';
import { useSelector } from 'react-redux';
import { Button } from '@openedx/paragon';
import { useIntl } from '@edx/frontend-platform/i18n';

import { Divider } from '../../../../generic/divider';
import { getCanEdit, getCourseUnitData } from '../../../data/selectors';
import { getCanEdit, getCourseSectionVertical, getCourseUnitData } from '../../../data/selectors';
import { useClipboard } from '../../../../generic/clipboard';
import { getCourseUserRole } from '../../../../course-team/data/api';
import messages from '../../messages';
import CourseUnitPublishButtonSlot from '../../../../plugin-slots/CourseUnitPublishButtonSlot';

interface ActionButtonsProps {
openDiscardModal: () => void,
handlePublishing: () => void,
}

type CourseRole = 'staff' | 'instructor' | null;

const extractCourseKeyFromOutlineUrl = (outlineUrl?: string): string | null => {
if (!outlineUrl) {
return null;
}
const match = outlineUrl.match(/\/course\/([^?]+)/);
return match?.[1] ?? null;
};

const ActionButtons = ({
openDiscardModal,
handlePublishing,
Expand All @@ -23,21 +36,58 @@
hasChanges,
enableCopyPasteUnits,
} = useSelector(getCourseUnitData);
const courseSectionVertical = useSelector(getCourseSectionVertical);
const canEdit = useSelector(getCanEdit);
const { copyToClipboard } = useClipboard();

const [courseRole, setCourseRole] = useState<CourseRole>(null);

const courseKey = useMemo(
() => extractCourseKeyFromOutlineUrl(courseSectionVertical?.outlineUrl),
[courseSectionVertical?.outlineUrl],
);

useEffect(() => {
// Only needed when the Publish button will render.
if (!(!published || hasChanges)) {
return;
}

if (!courseKey) {
return;
}

let cancelled = false;

(async () => {
try {
const { role } = await getCourseUserRole(courseKey) as any;
setCourseRole(role);
if (cancelled) return;

Check failure on line 66 in src/course-unit/sidebar/components/sidebar-footer/ActionButtons.tsx

View workflow job for this annotation

GitHub Actions / tests

Unnecessary return statement

Check failure on line 66 in src/course-unit/sidebar/components/sidebar-footer/ActionButtons.tsx

View workflow job for this annotation

GitHub Actions / tests

Expected { after 'if' condition
} catch (error: any) {
if (cancelled) return;

Check failure on line 68 in src/course-unit/sidebar/components/sidebar-footer/ActionButtons.tsx

View workflow job for this annotation

GitHub Actions / tests

Expected { after 'if' condition
setCourseRole(null);
}
})();

return () => {

Check failure on line 73 in src/course-unit/sidebar/components/sidebar-footer/ActionButtons.tsx

View workflow job for this annotation

GitHub Actions / tests

Arrow function expected no return value
cancelled = true;
};
}, [courseKey, hasChanges, published]);

const publishButtonText = courseRole
? intl.formatMessage(messages.actionButtonPublishTitle, { role: courseRole })
: 'Publish';

return (
<>
{(!published || hasChanges) && (
<Button
size="sm"
className="mt-3.5"
variant="outline-primary"
onClick={handlePublishing}
>
{intl.formatMessage(messages.actionButtonPublishTitle)}
</Button>
)}
<CourseUnitPublishButtonSlot
courseRole={courseRole}
published={published}
hasChanges={hasChanges}
publishButtonText={publishButtonText}
onPublish={handlePublishing}
/>
{(published && hasChanges) && (
<Button
size="sm"
Expand Down
3 changes: 2 additions & 1 deletion src/course-unit/sidebar/messages.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ const messages = defineMessages({
},
actionButtonPublishTitle: {
id: 'course-authoring.course-unit.action-buttons.publish.title',
defaultMessage: 'Publish',
defaultMessage: 'Publish {role}',
description: 'Publish button text with optional role parameter. If role is provided, displays "Publish {role}", otherwise just "Publish".',
},
actionButtonDiscardChangesTitle: {
id: 'course-authoring.course-unit.action-button.discard-changes.title',
Expand Down
64 changes: 64 additions & 0 deletions src/plugin-slots/CourseUnitPublishButtonSlot/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { PluginSlot } from '@openedx/frontend-plugin-framework';
import PropTypes from 'prop-types';
import { Button } from '@openedx/paragon';

interface CourseUnitPublishButtonSlotProps {
courseRole: 'staff' | 'instructor' | null;
published: boolean;
hasChanges: boolean;
publishButtonText: string;
onPublish: () => void;
}

const CourseUnitPublishButtonSlot = ({
courseRole,
published,
hasChanges,
publishButtonText,
onPublish,
}: CourseUnitPublishButtonSlotProps) => {
if (!(!published || hasChanges)) {
return null;
}

const shouldHideByDefault = courseRole === 'staff' || courseRole === null;

const defaultComponent = (
<Button
size="sm"
className="mt-3.5"
variant="outline-primary"
onClick={onPublish}
style={{ display: shouldHideByDefault ? 'none' : undefined }}
>
{publishButtonText}
</Button>
);

return (
<PluginSlot
id="org.openedx.frontend.authoring.course_unit_publish_button.v1"
idAliases={['course_unit_publish_button_slot']}
pluginProps={{
courseRole: courseRole ?? null,
published: published ?? false,
hasChanges: hasChanges ?? false,
publishButtonText: publishButtonText ?? 'Publish',
onPublish: onPublish ?? (() => {}),
}}
>
{defaultComponent}
</PluginSlot>
);
};

CourseUnitPublishButtonSlot.propTypes = {
courseRole: PropTypes.oneOf(['staff', 'instructor', null]),
published: PropTypes.bool.isRequired,
hasChanges: PropTypes.bool.isRequired,
publishButtonText: PropTypes.string.isRequired,
onPublish: PropTypes.func.isRequired,
};

export default CourseUnitPublishButtonSlot;

Check failure on line 64 in src/plugin-slots/CourseUnitPublishButtonSlot/index.tsx

View workflow job for this annotation

GitHub Actions / tests

Too many blank lines at the end of file. Max of 0 allowed
1 change: 1 addition & 0 deletions src/plugin-slots/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
## Course Unit page
* [`org.openedx.frontend.authoring.course_unit_header_actions.v1`](./CourseUnitHeaderActionsSlot/)
* [`org.openedx.frontend.authoring.course_unit_sidebar.v1`](./CourseAuthoringUnitSidebarSlot/)
* [`org.openedx.frontend.authoring.course_unit_publish_button.v1`](./CourseUnitPublishButtonSlot/) - Publish button slot with role-based control

## Other Slots
* [`org.openedx.frontend.authoring.additional_course_content_plugin.v1`](./AdditionalCourseContentPluginSlot/)
Expand Down
Loading