Compare commits

..

6 Commits

Author SHA1 Message Date
Kyle McCormick
08e11b6f27 Fix logout URL 2020-04-09 12:32:43 -04:00
Kyle McCormick
a6522f5983 Prefix a bunch of routes with /learning 2020-04-09 12:32:32 -04:00
Kyle McCormick
a21be5d83c Update .env.development for devstack 2020-04-08 16:43:46 -04:00
Kyle McCormick
521483b836 Temporary: Prefix React routes with /learning 2020-04-08 15:53:44 -04:00
Kyle McCormick
6a5e906cbe Switch to kdmccormick/devstack-frontends branch of frontend-build
Required doing some reformatting in InsturctorToolbar.jsx
to make the linter happy.

Also, add dev-build command.
2020-04-07 12:01:13 -04:00
Kyle McCormick
9b76cc4d97 Make React routes relative 2020-04-07 11:32:44 -04:00
65 changed files with 6180 additions and 3530 deletions

2
.env
View File

@@ -4,7 +4,6 @@ BASE_URL=null
CREDENTIALS_BASE_URL=null CREDENTIALS_BASE_URL=null
CSRF_TOKEN_API_PATH=null CSRF_TOKEN_API_PATH=null
ECOMMERCE_BASE_URL=null ECOMMERCE_BASE_URL=null
INSIGHTS_BASE_URL=
LANGUAGE_PREFERENCE_COOKIE_NAME=null LANGUAGE_PREFERENCE_COOKIE_NAME=null
LMS_BASE_URL=null LMS_BASE_URL=null
LOGIN_URL=null LOGIN_URL=null
@@ -14,5 +13,4 @@ ORDER_HISTORY_URL=null
REFRESH_ACCESS_TOKEN_ENDPOINT=null REFRESH_ACCESS_TOKEN_ENDPOINT=null
SEGMENT_KEY=null SEGMENT_KEY=null
SITE_NAME=null SITE_NAME=null
STUDIO_BASE_URL=
USER_INFO_COOKIE_NAME=null USER_INFO_COOKIE_NAME=null

View File

@@ -1,6 +1,7 @@
NODE_ENV='development' NODE_ENV='development'
PORT=2000
ACCESS_TOKEN_COOKIE_NAME='edx-jwt-cookie-header-payload' ACCESS_TOKEN_COOKIE_NAME='edx-jwt-cookie-header-payload'
BASE_URL='localhost:2000' BASE_URL='localhost:19000/learning'
CREDENTIALS_BASE_URL='http://localhost:18150' CREDENTIALS_BASE_URL='http://localhost:18150'
CSRF_TOKEN_API_PATH='/csrf/api/v1/token' CSRF_TOKEN_API_PATH='/csrf/api/v1/token'
ECOMMERCE_BASE_URL='http://localhost:18130' ECOMMERCE_BASE_URL='http://localhost:18130'
@@ -9,10 +10,8 @@ LMS_BASE_URL='http://localhost:18000'
LOGIN_URL='http://localhost:18000/login' LOGIN_URL='http://localhost:18000/login'
LOGOUT_URL='http://localhost:18000/logout' LOGOUT_URL='http://localhost:18000/logout'
MARKETING_SITE_BASE_URL='http://localhost:18000' MARKETING_SITE_BASE_URL='http://localhost:18000'
ORDER_HISTORY_URL='localhost:1996/orders' ORDER_HISTORY_URL='localhost:19000/orders'
PORT=2000
REFRESH_ACCESS_TOKEN_ENDPOINT='http://localhost:18000/login_refresh' REFRESH_ACCESS_TOKEN_ENDPOINT='http://localhost:18000/login_refresh'
SEGMENT_KEY=null SEGMENT_KEY=null
SITE_NAME='edX' SITE_NAME='edX'
STUDIO_BASE_URL='http://localhost:18010'
USER_INFO_COOKIE_NAME='edx-user-info' USER_INFO_COOKIE_NAME='edx-user-info'

View File

@@ -1,18 +1,15 @@
NODE_ENV='test'
ACCESS_TOKEN_COOKIE_NAME='edx-jwt-cookie-header-payload' ACCESS_TOKEN_COOKIE_NAME='edx-jwt-cookie-header-payload'
BASE_URL='localhost:2000' BASE_URL='localhost:1995'
CREDENTIALS_BASE_URL='http://localhost:18150' CREDENTIALS_BASE_URL='http://localhost:18150'
CSRF_TOKEN_API_PATH='/csrf/api/v1/token' CSRF_TOKEN_API_PATH='/csrf/api/v1/token'
ECOMMERCE_BASE_URL='http://localhost:18130' ECOMMERCE_BASE_URL='http://localhost:18130'
LANGUAGE_PREFERENCE_COOKIE_NAME='openedx-language-preference' LANGUAGE_PREFERENCE_COOKIE_NAME='openedx-language-preference'
LMS_BASE_URL='http://localhost:18000' LMS_BASE_URL='http://localhost:18000'
LOGIN_URL='http://localhost:18000/login' LOGIN_URL='http://localhost:18000/login'
LOGOUT_URL='http://localhost:18000/logout' LOGOUT_URL='http://localhost:18000/login'
MARKETING_SITE_BASE_URL='http://localhost:18000' MARKETING_SITE_BASE_URL='http://localhost:18000'
ORDER_HISTORY_URL='localhost:1996/orders' ORDER_HISTORY_URL='localhost:1996/orders'
PORT=2000
REFRESH_ACCESS_TOKEN_ENDPOINT='http://localhost:18000/login_refresh' REFRESH_ACCESS_TOKEN_ENDPOINT='http://localhost:18000/login_refresh'
SEGMENT_KEY=null SEGMENT_KEY=null
SITE_NAME='edX' SITE_NAME='edX'
STUDIO_BASE_URL='http://localhost:18010'
USER_INFO_COOKIE_NAME='edx-user-info' USER_INFO_COOKIE_NAME='edx-user-info'

0
LICENSE Normal file → Executable file
View File

0
Makefile Normal file → Executable file
View File

View File

@@ -3,8 +3,3 @@
oeps: {} oeps: {}
owner: edx/platform-core-tnl owner: edx/platform-core-tnl
openedx-release:
# The openedx-release key is described in OEP-10:
# https://open-edx-proposals.readthedocs.io/en/latest/oep-0010-proc-openedx-releases.html
# The FAQ might also be helpful: https://openedx.atlassian.net/wiki/spaces/COMM/pages/1331268879/Open+edX+Release+FAQ
ref: master

7915
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -12,6 +12,7 @@
], ],
"scripts": { "scripts": {
"build": "fedx-scripts webpack", "build": "fedx-scripts webpack",
"dev-build": "fedx-scripts webpack-dev",
"i18n_extract": "BABEL_ENV=i18n fedx-scripts babel src --quiet > /dev/null", "i18n_extract": "BABEL_ENV=i18n fedx-scripts babel src --quiet > /dev/null",
"is-es5": "es-check es5 ./dist/*.js", "is-es5": "es-check es5 ./dist/*.js",
"lint": "fedx-scripts eslint --ext .js --ext .jsx .", "lint": "fedx-scripts eslint --ext .js --ext .jsx .",
@@ -56,7 +57,7 @@
"regenerator-runtime": "^0.13.3" "regenerator-runtime": "^0.13.3"
}, },
"devDependencies": { "devDependencies": {
"@edx/frontend-build": "^3.0.0", "@edx/frontend-build": "github:edx/frontend-build#kdmccormick/devstack-frontends",
"codecov": "^3.6.1", "codecov": "^3.6.1",
"es-check": "^5.1.0", "es-check": "^5.1.0",
"glob": "^7.1.6", "glob": "^7.1.6",

View File

@@ -24,12 +24,6 @@ export default () => {
global.location.assign(`${getConfig().LMS_BASE_URL}/courses/${match.params.courseId}/course/`); global.location.assign(`${getConfig().LMS_BASE_URL}/courses/${match.params.courseId}/course/`);
}} }}
/> />
<Route
path={`${path}/dashboard`}
render={({ location }) => {
global.location.assign(`${getConfig().LMS_BASE_URL}/dashboard${location.search}`);
}}
/>
</Switch> </Switch>
</div> </div>
); );

View File

@@ -1,21 +0,0 @@
import React from 'react';
import PropTypes from 'prop-types';
import { Alert } from '../user-messages';
function AccessExpirationAlert(props) {
const {
rawHtml,
} = props;
return rawHtml && (
<Alert type="info">
<div dangerouslySetInnerHTML={{ __html: rawHtml }} />
</Alert>
);
}
AccessExpirationAlert.propTypes = {
rawHtml: PropTypes.string.isRequired,
};
export default AccessExpirationAlert;

View File

@@ -1,28 +0,0 @@
/* eslint-disable import/prefer-default-export */
import { useContext, useState, useEffect } from 'react';
import { UserMessagesContext } from '../user-messages';
import { useModel } from '../model-store';
export function useAccessExpirationAlert(courseId) {
const course = useModel('courses', courseId);
const { add, remove } = useContext(UserMessagesContext);
const [alertId, setAlertId] = useState(null);
const rawHtml = (course && course.courseExpiredMessage) || null;
useEffect(() => {
if (rawHtml && alertId === null) {
setAlertId(add({
code: 'clientAccessExpirationAlert',
topic: 'course',
rawHtml,
}));
} else if (!rawHtml && alertId !== null) {
remove(alertId);
setAlertId(null);
}
return () => {
if (alertId !== null) {
remove(alertId);
}
};
}, [alertId, courseId, rawHtml]);
}

View File

@@ -1,2 +0,0 @@
export { default as AccessExpirationAlert } from './AccessExpirationAlert';
export { useAccessExpirationAlert } from './hooks';

View File

@@ -1,16 +1,17 @@
import React from 'react'; import React from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { injectIntl, intlShape } from '@edx/frontend-platform/i18n'; import { injectIntl, intlShape } from '@edx/frontend-platform/i18n';
import { getConfig } from '@edx/frontend-platform';
import classNames from 'classnames'; import classNames from 'classnames';
import messages from './messages'; import messages from './messages';
import Tabs from '../tabs/Tabs'; import Tabs from '../tabs/Tabs';
function CourseTabsNavigation({ function CourseTabsNavigation({
activeTabSlug, className, tabs, intl, activeTabSlug, tabs, intl,
}) { }) {
return ( return (
<div className={classNames('course-tabs-navigation', className)}> <div className="course-tabs-navigation">
<div className="container-fluid"> <div className="container-fluid">
<Tabs <Tabs
className="nav-underline-tabs" className="nav-underline-tabs"
@@ -20,7 +21,7 @@ function CourseTabsNavigation({
<a <a
key={slug} key={slug}
className={classNames('nav-item flex-shrink-0 nav-link', { active: slug === activeTabSlug })} className={classNames('nav-item flex-shrink-0 nav-link', { active: slug === activeTabSlug })}
href={url} href={`${getConfig().LMS_BASE_URL}${url}`}
> >
{title} {title}
</a> </a>
@@ -33,7 +34,6 @@ function CourseTabsNavigation({
CourseTabsNavigation.propTypes = { CourseTabsNavigation.propTypes = {
activeTabSlug: PropTypes.string, activeTabSlug: PropTypes.string,
className: PropTypes.string,
tabs: PropTypes.arrayOf(PropTypes.shape({ tabs: PropTypes.arrayOf(PropTypes.shape({
title: PropTypes.string.isRequired, title: PropTypes.string.isRequired,
priority: PropTypes.number.isRequired, priority: PropTypes.number.isRequired,
@@ -45,7 +45,6 @@ CourseTabsNavigation.propTypes = {
CourseTabsNavigation.defaultProps = { CourseTabsNavigation.defaultProps = {
activeTabSlug: undefined, activeTabSlug: undefined,
className: null,
}; };
export default injectIntl(CourseTabsNavigation); export default injectIntl(CourseTabsNavigation);

View File

@@ -68,13 +68,7 @@ export default function Header({
} }
Header.propTypes = { Header.propTypes = {
courseOrg: PropTypes.string, courseOrg: PropTypes.string.isRequired,
courseNumber: PropTypes.string, courseNumber: PropTypes.string.isRequired,
courseTitle: PropTypes.string, courseTitle: PropTypes.string.isRequired,
};
Header.defaultProps = {
courseOrg: null,
courseNumber: null,
courseTitle: null,
}; };

View File

@@ -1,8 +1,11 @@
import React from 'react'; import React from 'react';
import { useSelector } from 'react-redux'; import PropTypes from 'prop-types';
import { Button } from '@edx/paragon'; import { Button } from '@edx/paragon';
import { AlertList } from '../user-messages'; import AlertList from '../user-messages/AlertList';
import { Header, CourseTabsNavigation } from '../course-header';
import { useLogistrationAlert } from '../logistration-alert';
import { useEnrollmentAlert } from '../enrollment-alert';
import CourseDates from './CourseDates'; import CourseDates from './CourseDates';
import Section from './Section'; import Section from './Section';
@@ -15,12 +18,15 @@ import { useModel } from '../model-store';
const { EnrollmentAlert, StaffEnrollmentAlert } = React.lazy(() => import('../enrollment-alert')); const { EnrollmentAlert, StaffEnrollmentAlert } = React.lazy(() => import('../enrollment-alert'));
const LogistrationAlert = React.lazy(() => import('../logistration-alert')); const LogistrationAlert = React.lazy(() => import('../logistration-alert'));
export default function CourseHome() { export default function CourseHome({
const { courseId,
courseId, }) {
} = useSelector(state => state.courseware); useLogistrationAlert();
useEnrollmentAlert(courseId);
const { const {
org,
number,
title, title,
start, start,
end, end,
@@ -28,45 +34,64 @@ export default function CourseHome() {
enrollmentEnd, enrollmentEnd,
enrollmentMode, enrollmentMode,
isEnrolled, isEnrolled,
tabs,
sectionIds, sectionIds,
} = useModel('courses', courseId); } = useModel('courses', courseId);
return ( return (
<> <>
<AlertList <Header
topic="outline" courseOrg={org}
className="mb-3" courseNumber={number}
customAlerts={{ courseTitle={title}
clientEnrollmentAlert: EnrollmentAlert,
clientStaffEnrollmentAlert: StaffEnrollmentAlert,
clientLogistrationAlert: LogistrationAlert,
}}
/> />
<div className="d-flex justify-content-between mb-3"> <main className="d-flex flex-column flex-grow-1">
<h2>{title}</h2> <div className="container-fluid">
<Button className="btn-primary" type="button">Resume Course</Button> <CourseTabsNavigation tabs={tabs} className="mb-3" activeTabSlug="courseware" />
</div> <AlertList
<div className="row"> topic="outline"
<div className="col col-8"> className="mb-3"
{sectionIds.map((sectionId) => ( customAlerts={{
<Section clientEnrollmentAlert: EnrollmentAlert,
key={sectionId} clientStaffEnrollmentAlert: StaffEnrollmentAlert,
id={sectionId} clientLogistrationAlert: LogistrationAlert,
courseId={courseId} }}
/>
))}
</div>
<div className="col col-4">
<CourseDates
start={start}
end={end}
enrollmentStart={enrollmentStart}
enrollmentEnd={enrollmentEnd}
enrollmentMode={enrollmentMode}
isEnrolled={isEnrolled}
/> />
</div> </div>
</div> <div className="flex-grow-1">
<div className="container-fluid">
<div className="d-flex justify-content-between mb-3">
<h2>{title}</h2>
<Button className="btn-primary" type="button">Resume Course</Button>
</div>
<div className="row">
<div className="col col-8">
{sectionIds.map((sectionId) => (
<Section
key={sectionId}
id={sectionId}
courseId={courseId}
/>
))}
</div>
<div className="col col-4">
<CourseDates
start={start}
end={end}
enrollmentStart={enrollmentStart}
enrollmentEnd={enrollmentEnd}
enrollmentMode={enrollmentMode}
isEnrolled={isEnrolled}
/>
</div>
</div>
</div>
</div>
</main>
</> </>
); );
} }
CourseHome.propTypes = {
courseId: PropTypes.string.isRequired,
};

View File

@@ -0,0 +1,54 @@
import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import { useDispatch, useSelector } from 'react-redux';
import { injectIntl, intlShape } from '@edx/frontend-platform/i18n';
import messages from './messages';
import PageLoading from '../PageLoading';
import CourseHome from './CourseHome';
import { fetchCourse } from '../data';
function CourseHomeContainer(props) {
const {
intl,
match,
} = props;
const dispatch = useDispatch();
useEffect(() => {
// The courseId from the URL is the course we WANT to load.
dispatch(fetchCourse(match.params.courseId));
}, [match.params.courseId]);
// The courseId from the store is the course we HAVE loaded. If the URL changes,
// we don't want the application to adjust to it until it has actually loaded the new data.
const {
courseId,
courseStatus,
} = useSelector(state => state.courseware);
return (
<>
{courseStatus === 'loaded' ? (
<CourseHome
courseId={courseId}
/>
) : (
<PageLoading
srMessage={intl.formatMessage(messages['learn.loading.outline'])}
/>
)}
</>
);
}
CourseHomeContainer.propTypes = {
intl: intlShape.isRequired,
match: PropTypes.shape({
params: PropTypes.shape({
courseId: PropTypes.string.isRequired,
}).isRequired,
}).isRequired,
};
export default injectIntl(CourseHomeContainer);

View File

@@ -7,7 +7,7 @@ export default function SequenceLink({ id, courseId }) {
const sequence = useModel('sequences', id); const sequence = useModel('sequences', id);
return ( return (
<div className="ml-4"> <div className="ml-4">
<Link to={`/course/${courseId}/${id}`}>{sequence.title}</Link> <Link to={`/learning/course/${courseId}/${id}`}>{sequence.title}</Link>
</div> </div>
); );
} }

View File

@@ -1 +1 @@
export { default } from './CourseHome'; export { default } from './CourseHomeContainer';

View File

@@ -0,0 +1,11 @@
import { defineMessages } from '@edx/frontend-platform/i18n';
const messages = defineMessages({
'learn.loading.outline': {
id: 'learn.loading.learning.sequence',
defaultMessage: 'Loading learning sequence...',
description: 'Message when learning sequence is being loaded',
},
});
export default messages;

View File

@@ -2,30 +2,28 @@ import React, { useEffect, useCallback } from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { useSelector, useDispatch } from 'react-redux'; import { useSelector, useDispatch } from 'react-redux';
import { history } from '@edx/frontend-platform'; import { history } from '@edx/frontend-platform';
import { getLocale } from '@edx/frontend-platform/i18n';
import { useRouteMatch, Redirect } from 'react-router';
import { useRouteMatch, Redirect } from 'react-router';
import { import {
fetchCourse, fetchCourse,
fetchSequence, fetchSequence,
getResumeBlock,
} from '../data'; } from '../data';
import { import {
checkBlockCompletion, checkBlockCompletion,
saveSequencePosition, saveSequencePosition,
} from './data/thunks'; } from './data/thunks';
import { useModel } from '../model-store'; import { useModel } from '../model-store';
import { TabPage } from '../tab-page';
import Course from './course'; import Course from './course';
import { sequenceIdsSelector, firstSequenceIdSelector } from './data/selectors'; import { sequenceIdsSelector, firstSequenceIdSelector } from './data/selectors';
function useUnitNavigationHandler(courseId, sequenceId, unitId) { function useUnitNavigationHandler(courseId, sequenceId, unitId) {
const dispatch = useDispatch(); const dispatch = useDispatch();
return useCallback((nextUnitId) => { return useCallback((nextUnitId) => {
dispatch(checkBlockCompletion(courseId, sequenceId, unitId)); dispatch(checkBlockCompletion(courseId, sequenceId, unitId));
history.push(`/course/${courseId}/${sequenceId}/${nextUnitId}`); history.push(`/learning/course/${courseId}/${sequenceId}/${nextUnitId}`);
}, [courseId, sequenceId, unitId]); }, [courseId, sequenceId]);
} }
function usePreviousSequence(sequenceId) { function usePreviousSequence(sequenceId) {
@@ -57,13 +55,8 @@ function useNextSequenceHandler(courseId, sequenceId) {
const sequenceStatus = useSelector(state => state.courseware.sequenceStatus); const sequenceStatus = useSelector(state => state.courseware.sequenceStatus);
return useCallback(() => { return useCallback(() => {
if (nextSequence !== null) { if (nextSequence !== null) {
if (nextSequence.unitIds.length > 0) { const nextUnitId = nextSequence.unitIds[0];
const nextUnitId = nextSequence.unitIds[0]; history.push(`/learning/course/${courseId}/${nextSequence.id}/${nextUnitId}`);
history.push(`/course/${courseId}/${nextSequence.id}/${nextUnitId}`);
} else {
// Some sequences have no units. This will show a blank page with prev/next buttons.
history.push(`/course/${courseId}/${nextSequence.id}`);
}
} }
}, [courseStatus, sequenceStatus, sequenceId]); }, [courseStatus, sequenceStatus, sequenceId]);
} }
@@ -74,13 +67,8 @@ function usePreviousSequenceHandler(courseId, sequenceId) {
const sequenceStatus = useSelector(state => state.courseware.sequenceStatus); const sequenceStatus = useSelector(state => state.courseware.sequenceStatus);
return useCallback(() => { return useCallback(() => {
if (previousSequence !== null) { if (previousSequence !== null) {
if (previousSequence.unitIds.length > 0) { const previousUnitId = previousSequence.unitIds[previousSequence.unitIds.length - 1];
const previousUnitId = previousSequence.unitIds[previousSequence.unitIds.length - 1]; history.push(`/learning/course/${courseId}/${previousSequence.id}/${previousUnitId}`);
history.push(`/course/${courseId}/${previousSequence.id}/${previousUnitId}`);
} else {
// Some sequences have no units. This will show a blank page with prev/next buttons.
history.push(`/course/${courseId}/${previousSequence.id}`);
}
} }
}, [courseStatus, sequenceStatus, sequenceId]); }, [courseStatus, sequenceStatus, sequenceId]);
} }
@@ -102,14 +90,8 @@ function useContentRedirect(courseStatus, sequenceStatus) {
const firstSequenceId = useSelector(firstSequenceIdSelector); const firstSequenceId = useSelector(firstSequenceIdSelector);
useEffect(() => { useEffect(() => {
if (courseStatus === 'loaded' && !sequenceId) { if (courseStatus === 'loaded' && !sequenceId) {
getResumeBlock(courseId).then((data) => { // This is a replace because we don't want this change saved in the browser's history.
// This is a replace because we don't want this change saved in the browser's history. history.replace(`/learning/course/${courseId}/${firstSequenceId}`);
if (data.sectionId && data.unitId) {
history.replace(`/course/${courseId}/${data.sectionId}/${data.unitId}`);
} else {
history.replace(`/course/${courseId}/${firstSequenceId}`);
}
});
} }
}, [courseStatus, sequenceId]); }, [courseStatus, sequenceId]);
@@ -120,7 +102,7 @@ function useContentRedirect(courseStatus, sequenceStatus) {
const unitIndex = sequence.position || 0; const unitIndex = sequence.position || 0;
const nextUnitId = sequence.unitIds[unitIndex]; const nextUnitId = sequence.unitIds[unitIndex];
// This is a replace because we don't want this change saved in the browser's history. // This is a replace because we don't want this change saved in the browser's history.
history.replace(`/course/${courseId}/${sequence.id}/${nextUnitId}`); history.replace(`/learning/course/${courseId}/${sequence.id}/${nextUnitId}`);
} }
} }
}, [sequenceStatus, sequenceId, unitId]); }, [sequenceStatus, sequenceId, unitId]);
@@ -180,32 +162,12 @@ export default function CoursewareContainer() {
useExamRedirect(sequenceId); useExamRedirect(sequenceId);
useSavedSequencePosition(courseId, sequenceId, routeUnitId); useSavedSequencePosition(courseId, sequenceId, routeUnitId);
const course = useModel('courses', courseId);
if (courseStatus === 'denied') { if (courseStatus === 'denied') {
switch (course.canLoadCourseware.errorCode) { return <Redirect to={`/learning/redirect/course-home/${courseId}`} />;
case 'audit_expired':
return <Redirect to={`/redirect/dashboard?access_response_error=${course.canLoadCourseware.additionalContextUserMessage}`} />;
case 'course_not_started':
// eslint-disable-next-line no-case-declarations
const startDate = (new Intl.DateTimeFormat(getLocale())).format(new Date(course.start));
return <Redirect to={`/redirect/dashboard?notlive=${startDate}`} />;
case 'survey_required': // TODO: Redirect to the course survey
case 'unfulfilled_milestones':
return <Redirect to="/redirect/dashboard" />;
case 'authentication_required':
case 'enrollment_required':
default:
return <Redirect to={`/redirect/course-home/${courseId}`} />;
}
} }
return ( return (
<TabPage <main className="flex-grow-1 d-flex flex-column">
activeTabSlug="courseware"
courseId={courseId}
unitId={routeUnitId}
>
<Course <Course
courseId={courseId} courseId={courseId}
sequenceId={sequenceId} sequenceId={sequenceId}
@@ -214,7 +176,7 @@ export default function CoursewareContainer() {
previousSequenceHandler={previousSequenceHandler} previousSequenceHandler={previousSequenceHandler}
unitNavigationHandler={unitNavigationHandler} unitNavigationHandler={unitNavigationHandler}
/> />
</TabPage> </main>
); );
} }

View File

@@ -1,26 +1,30 @@
import React from 'react'; import React from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { injectIntl, intlShape } from '@edx/frontend-platform/i18n';
import { AlertList } from '../../user-messages'; import { useSelector } from 'react-redux';
import { useAccessExpirationAlert } from '../../access-expiration-alert'; import AlertList from '../../user-messages/AlertList';
import { useOfferAlert } from '../../offer-alert'; import { useLogistrationAlert } from '../../logistration-alert';
import { useEnrollmentAlert } from '../../enrollment-alert';
import PageLoading from '../../PageLoading';
import InstructorToolbar from './InstructorToolbar';
import Sequence from './sequence'; import Sequence from './sequence';
import CourseBreadcrumbs from './CourseBreadcrumbs'; import CourseBreadcrumbs from './CourseBreadcrumbs';
import { Header, CourseTabsNavigation } from '../../course-header';
import CourseSock from './course-sock'; import CourseSock from './course-sock';
import ContentTools from './tools/ContentTools'; import Calculator from './calculator';
import messages from './messages';
import { useModel } from '../../model-store'; import { useModel } from '../../model-store';
// Note that we import from the component files themselves in the enrollment-alert package. // Note that we import from the component files themselves in the enrollment-alert package.
// This is because Reacy.lazy() requires that we import() from a file with a Component as it's // This is because Reacy.lazy() requires that we import() from a file with a Component as it's
// default export. // default export.
// See React.lazy docs here: https://reactjs.org/docs/code-splitting.html#reactlazy // See React.lazy docs here: https://reactjs.org/docs/code-splitting.html#reactlazy
const AccessExpirationAlert = React.lazy(() => import('../../access-expiration-alert/AccessExpirationAlert'));
const EnrollmentAlert = React.lazy(() => import('../../enrollment-alert/EnrollmentAlert')); const EnrollmentAlert = React.lazy(() => import('../../enrollment-alert/EnrollmentAlert'));
const StaffEnrollmentAlert = React.lazy(() => import('../../enrollment-alert/StaffEnrollmentAlert')); const StaffEnrollmentAlert = React.lazy(() => import('../../enrollment-alert/StaffEnrollmentAlert'));
const LogistrationAlert = React.lazy(() => import('../../logistration-alert')); const LogistrationAlert = React.lazy(() => import('../../logistration-alert'));
const OfferAlert = React.lazy(() => import('../../offer-alert/OfferAlert'));
function Course({ function Course({
courseId, courseId,
@@ -29,53 +33,80 @@ function Course({
nextSequenceHandler, nextSequenceHandler,
previousSequenceHandler, previousSequenceHandler,
unitNavigationHandler, unitNavigationHandler,
intl,
}) { }) {
const course = useModel('courses', courseId); const course = useModel('courses', courseId);
const sequence = useModel('sequences', sequenceId); const sequence = useModel('sequences', sequenceId);
const section = useModel('sections', sequence ? sequence.sectionId : null); const section = useModel('sections', sequence ? sequence.sectionId : null);
useOfferAlert(courseId); useLogistrationAlert();
useAccessExpirationAlert(courseId); useEnrollmentAlert(courseId);
const { const courseStatus = useSelector(state => state.courseware.courseStatus);
canShowUpgradeSock,
verifiedMode,
} = course;
if (courseStatus === 'loading') {
return (
<PageLoading
srMessage={intl.formatMessage(messages['learn.loading.learning.sequence'])}
/>
);
}
if (courseStatus === 'loaded') {
const {
org, number, title, isStaff, tabs, verifiedMode, showCalculator,
} = course;
return (
<>
<Header
courseOrg={org}
courseNumber={number}
courseTitle={title}
/>
{isStaff && (
<InstructorToolbar
unitId={unitId}
/>
)}
<CourseTabsNavigation tabs={tabs} activeTabSlug="courseware" />
<div className="container-fluid">
<AlertList
className="my-3"
topic="course"
customAlerts={{
clientEnrollmentAlert: EnrollmentAlert,
clientStaffEnrollmentAlert: StaffEnrollmentAlert,
clientLogistrationAlert: LogistrationAlert,
}}
/>
<CourseBreadcrumbs
courseId={courseId}
sectionId={section ? section.id : null}
sequenceId={sequenceId}
/>
<AlertList topic="sequence" />
</div>
<div className="flex-grow-1 d-flex flex-column">
<Sequence
unitId={unitId}
sequenceId={sequenceId}
courseId={courseId}
unitNavigationHandler={unitNavigationHandler}
nextSequenceHandler={nextSequenceHandler}
previousSequenceHandler={previousSequenceHandler}
/>
{verifiedMode && <CourseSock verifiedMode={verifiedMode} />}
{showCalculator && <Calculator />}
</div>
</>
);
}
// courseStatus 'failed' and any other unexpected course status.
return ( return (
<> <p className="text-center py-5 mx-auto" style={{ maxWidth: '30em' }}>
<AlertList {intl.formatMessage(messages['learn.course.load.failure'])}
className="my-3" </p>
topic="course"
customAlerts={{
clientEnrollmentAlert: EnrollmentAlert,
clientStaffEnrollmentAlert: StaffEnrollmentAlert,
clientLogistrationAlert: LogistrationAlert,
clientAccessExpirationAlert: AccessExpirationAlert,
clientOfferAlert: OfferAlert,
}}
// courseId is provided because EnrollmentAlert and StaffEnrollmentAlert require it.
customProps={{
courseId,
}}
/>
<CourseBreadcrumbs
courseId={courseId}
sectionId={section ? section.id : null}
sequenceId={sequenceId}
/>
<AlertList topic="sequence" />
<Sequence
unitId={unitId}
sequenceId={sequenceId}
courseId={courseId}
unitNavigationHandler={unitNavigationHandler}
nextSequenceHandler={nextSequenceHandler}
previousSequenceHandler={previousSequenceHandler}
/>
{canShowUpgradeSock && verifiedMode && <CourseSock verifiedMode={verifiedMode} />}
<ContentTools course={course} />
</>
); );
} }
@@ -86,6 +117,7 @@ Course.propTypes = {
nextSequenceHandler: PropTypes.func.isRequired, nextSequenceHandler: PropTypes.func.isRequired,
previousSequenceHandler: PropTypes.func.isRequired, previousSequenceHandler: PropTypes.func.isRequired,
unitNavigationHandler: PropTypes.func.isRequired, unitNavigationHandler: PropTypes.func.isRequired,
intl: intlShape.isRequired,
}; };
Course.defaultProps = { Course.defaultProps = {
@@ -94,4 +126,4 @@ Course.defaultProps = {
unitId: null, unitId: null,
}; };
export default Course; export default injectIntl(Course);

View File

@@ -1,68 +1,38 @@
import React from 'react'; import React from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { Collapsible } from '@edx/paragon';
import { getConfig } from '@edx/frontend-platform';
function getInsightsUrl(courseId) {
const urlBase = getConfig().INSIGHTS_BASE_URL;
let urlFull;
if (urlBase) {
urlFull = `${urlBase}/courses`;
// This shouldn't actually be missing, at present,
// but we're providing a reasonable fallback,
// in case of either error or extension.
if (courseId) {
urlFull += `/${courseId}`;
}
}
return urlFull;
}
function getStudioUrl(courseId, unitId) {
const urlBase = getConfig().STUDIO_BASE_URL;
let urlFull;
if (urlBase) {
if (unitId) {
urlFull = `${urlBase}/container/${unitId}`;
} else if (courseId) {
urlFull = `{$urlBase}/course/${courseId}`;
}
}
return urlFull;
}
function InstructorToolbar(props) { function InstructorToolbar(props) {
const { // TODO: Only render this toolbar if the user is course staff
courseId, if (!props.activeUnitLmsWebUrl) {
unitId, return null;
} = props; }
const urlInsights = getInsightsUrl(courseId);
const urlLms = props.activeUnitLmsWebUrl;
const urlStudio = getStudioUrl(courseId, unitId);
return ( return (
<div className="bg-primary text-light"> <div className="bg-primary text-light">
<div className="container-fluid py-3 d-md-flex justify-content-end align-items-center"> <div className="container-fluid py-3 d-md-flex justify-content-end align-items-center">
<div className="flex-grow-1"> <div className="flex-grow-1">
&nbsp; <Collapsible.Advanced className="mr-5 mb-md-0">
You are currently previewing the new learning sequence experience.
<Collapsible.Trigger className="d-inline-block ml-2" style={{ cursor: 'pointer' }}>
<Collapsible.Visible whenClosed>
<span style={{ borderBottom: 'solid 1px white' }}>More info</span> &rarr;
</Collapsible.Visible>
</Collapsible.Trigger>
<Collapsible.Body>
This preview is to allow for early content testing, especially for custom content blocks, with the goal of ensuring it renders as expected in the next experience. You can learn more through the following <a className="text-white" style={{ textDecoration: 'underline' }} href="https://partners.edx.org/announcements/author-preview-learning-sequence-experience-update" target="blank" rel="noopener">Partner Portal post</a>. Please report any issues or provide <a className="text-white" style={{ textDecoration: 'underline' }} target="blank" rel="noopener" href="https://forms.gle/R6jMYJNTCj1vgC1D6">feedback using the linked form</a>.
<Collapsible.Trigger className="d-inline-block ml-2" style={{ cursor: 'pointer' }}>
<Collapsible.Visible whenOpen>
<span style={{ borderBottom: 'solid 1px white' }}>Close</span> &times;
</Collapsible.Visible>
</Collapsible.Trigger>
</Collapsible.Body>
</Collapsible.Advanced>
</div>
<div className="flex-shrink-0">
<a className="btn d-block btn-outline-light" href={props.activeUnitLmsWebUrl}>View unit in the existing experience</a>
</div> </div>
{urlLms && (
<div className="flex-shrink-0">
<a className="btn d-block btn-outline-light" href={urlLms}>View in the existing experience</a>
</div>
)}
&nbsp;
{urlStudio && (
<div className="flex-shrink-0">
<a className="btn d-block btn-outline-light" href={urlStudio}>View in Studio</a>
</div>
)}
&nbsp;
{urlInsights && (
<div className="flex-shrink-0">
<a className="btn d-block btn-outline-light" href={urlInsights}>View in Insights</a>
</div>
)}
</div> </div>
</div> </div>
); );
@@ -70,14 +40,10 @@ function InstructorToolbar(props) {
InstructorToolbar.propTypes = { InstructorToolbar.propTypes = {
activeUnitLmsWebUrl: PropTypes.string, activeUnitLmsWebUrl: PropTypes.string,
courseId: PropTypes.string,
unitId: PropTypes.string,
}; };
InstructorToolbar.defaultProps = { InstructorToolbar.defaultProps = {
activeUnitLmsWebUrl: undefined, activeUnitLmsWebUrl: undefined,
courseId: undefined,
unitId: undefined,
}; };
const mapStateToProps = (state, props) => { const mapStateToProps = (state, props) => {

View File

@@ -1,10 +1,10 @@
.content-tools { .calculator {
position: fixed; position: fixed;
left: 0; left: 0;
right: 0; right: 0;
bottom: 0; bottom: 0;
z-index: 100; z-index: 100;
.trigger { .calculator-trigger {
cursor: pointer; cursor: pointer;
display: inline-block; display: inline-block;
position: relative; position: relative;
@@ -16,12 +16,12 @@
border-top-right-radius: .3rem; border-top-right-radius: .3rem;
border-bottom-left-radius: 0; border-bottom-left-radius: 0;
border-bottom-right-radius: 0; border-bottom-right-radius: 0;
text-overflow: ellipsis;
overflow: hidden;
padding-left: .75rem;
white-space: nowrap;
&:before { &:before {
border-radius: .5rem; border-radius: .5rem;
} }
} }
.calculator-content {
background-color: #f1f1f1;
box-shadow: 0 -1px 0 0 #ddd;
}
} }

View File

@@ -41,8 +41,8 @@ class Calculator extends Component {
render() { render() {
return ( return (
<Collapsible.Advanced className="calculator"> <Collapsible.Advanced className="calculator">
<div className="text-right"> <div className="container-fluid text-right">
<Collapsible.Trigger tag="a" className="trigger btn"> <Collapsible.Trigger tag="a" className="calculator-trigger btn">
<Collapsible.Visible whenOpen> <Collapsible.Visible whenOpen>
<FontAwesomeIcon icon={faTimesCircle} aria-hidden="true" className="mr-2" /> <FontAwesomeIcon icon={faTimesCircle} aria-hidden="true" className="mr-2" />
</Collapsible.Visible> </Collapsible.Visible>

View File

@@ -32,152 +32,128 @@ export default class CourseSock extends Component {
</button> </button>
</div> </div>
{this.state.showUpsell && ( {this.state.showUpsell && (
<> <div className="d-flex justify-content-around">
<h2 className="mt-3 mb-4"> <div className="mt-3">
<h2 className="font-weight-lighter">
<FormattedMessage <FormattedMessage
id="coursesock.upsell.verifiedcert" id="coursesock.upsell.verifiedcert"
defaultMessage="edX Verified Certificate" defaultMessage="edX Verified Certificate"
/> />
</h2> </h2>
<div className="row flex-row-reverse"> <h3>
<div className="col-md-4 col-lg-6 d-flex flex-column"> <FormattedMessage
<div> id="coursesock.upsell.why"
<img alt="Example Certificate" src={VerifiedCert} className="d-block img-thumbnail mb-3 ml-md-auto" /> defaultMessage="Why upgrade?"
</div> />
<div className="position-relative flex-grow-1 d-flex flex-column justify-content-end align-items-md-end"> </h3>
<div style={{ position: 'sticky', bottom: '4rem' }}> <ul>
<a <li><FormattedMessage
href={this.verifiedMode.upgradeUrl} id="coursesock.upsell.reason1"
className="btn btn-success btn-lg btn-upgrade focusable mb-3" defaultMessage="Official proof of completion"
data-creative="original_sock" />
data-position="sock" </li>
> <li><FormattedMessage
<FormattedMessage id="coursesock.upsell.reason2"
id="coursesock.upsell.upgrade" defaultMessage="Easily shareable certificate"
defaultMessage="Upgrade ({symbol}{price} {currency})" />
values={{ </li>
symbol: this.verifiedMode.currencySymbol, <li><FormattedMessage
price: this.verifiedMode.price, id="coursesock.upsell.reason3"
currency: this.verifiedMode.currency, defaultMessage="Proven motivator to complete the course"
}} />
/> </li>
</a> <li><FormattedMessage
</div> id="coursesock.upsell.reason4"
</div> defaultMessage="Certificate purchases help edX continue to offer free courses"
</div> />
<div className="col-md-8 col-lg-6"> </li>
<h3 className="h5"> </ul>
<FormattedMessage <h3><FormattedMessage
id="coursesock.upsell.why" id="coursesock.upsell.howtitle"
defaultMessage="Why upgrade?" defaultMessage="How it works"
/> />
</h3> </h3>
<ul> <ul>
<li> <li><FormattedMessage
<FormattedMessage id="coursesock.upsell.how1"
id="coursesock.upsell.reason1" defaultMessage="Pay the Verified Certificate upgrade fee"
defaultMessage="Official proof of completion" />
/> </li>
</li> <li><FormattedMessage
<li> id="coursesock.upsell.how2"
<FormattedMessage defaultMessage="Verify your identity with a webcam and government-issued ID"
id="coursesock.upsell.reason2" />
defaultMessage="Easily shareable certificate" </li>
/> <li><FormattedMessage
</li> id="coursesock.upsell.how3"
<li> defaultMessage="Study hard and pass the course"
<FormattedMessage />
id="coursesock.upsell.reason3" </li>
defaultMessage="Proven motivator to complete the course" <li><FormattedMessage
/> id="coursesock.upsell.how4"
</li> defaultMessage="Share your certificate with friends, employers, and others"
<li> />
<FormattedMessage </li>
id="coursesock.upsell.reason4" </ul>
defaultMessage="Certificate purchases help edX continue to offer free courses" <h3><FormattedMessage
/> id="coursesock.upsell.storytitle"
</li> defaultMessage="edX Learner Stories"
</ul> />
<h3 className="h5"> </h3>
<FormattedMessage <div className="d-flex align-items-center my-4">
id="coursesock.upsell.howtitle" <img style={{ maxWidth: '4rem' }} alt="Christina Fong" src={LearnerQuote1} />
defaultMessage="How it works" <div className="w-50 px-4">
/> <FormattedMessage
</h3> id="coursesock.upsell.story1"
<ul> defaultMessage="My certificate has helped me showcase my knowledge on my
<li> resume - I feel like this certificate could really help me land
<FormattedMessage my dream job!"
id="coursesock.upsell.how1" />
defaultMessage="Pay the Verified Certificate upgrade fee" <br />
/> <strong>&mdash; <FormattedMessage
</li> id="coursesock.upsell.learner"
<li> description="Name of learner"
<FormattedMessage defaultMessage="{ name }, edX Learner"
id="coursesock.upsell.how2" values={{ name: 'Christina Fong' }}
defaultMessage="Verify your identity with a webcam and government-issued ID" />
/> </strong>
</li>
<li>
<FormattedMessage
id="coursesock.upsell.how3"
defaultMessage="Study hard and pass the course"
/>
</li>
<li>
<FormattedMessage
id="coursesock.upsell.how4"
defaultMessage="Share your certificate with friends, employers, and others"
/>
</li>
</ul>
<h3 className="h5">
<FormattedMessage
id="coursesock.upsell.storytitle"
defaultMessage="edX Learner Stories"
/>
</h3>
<div className="media my-3">
<img className="mr-3" style={{ maxWidth: '4rem' }} alt="Christina Fong" src={LearnerQuote1} />
<div className="media-body">
<FormattedMessage
id="coursesock.upsell.story1"
defaultMessage="My certificate has helped me showcase my knowledge on my
resume - I feel like this certificate could really help me land
my dream job!"
/>
<p className="font-weight-bold">
&mdash; <FormattedMessage
id="coursesock.upsell.learner"
description="Name of learner"
defaultMessage="{ name }, edX Learner"
values={{ name: 'Christina Fong' }}
/>
</p>
</div>
</div>
<div className="media my-3">
<img className="mr-3" style={{ maxWidth: '4rem' }} alt="Chery Troell" src={LearnerQuote2} />
<div className="media-body">
<FormattedMessage
id="coursesock.upsell.story2"
defaultMessage="I wanted to include a verified certificate on my resume and my profile to
illustrate that I am working towards this goal I have and that I have
achieved something while I was unemployed."
/>
<p className="font-weight-bold">
&mdash; <FormattedMessage
id="coursesock.upsell.learner"
description="Name of learner"
defaultMessage="{ name }, edX Learner"
values={{ name: 'Cheryl Troell' }}
/>
</p>
</div>
</div>
</div> </div>
</div> </div>
</> <div className="d-flex align-items-center my-2">
<img style={{ maxWidth: '4rem' }} alt="Chery Troell" src={LearnerQuote2} />
<div className="w-50 px-4">
<FormattedMessage
id="coursesock.upsell.story2"
defaultMessage="I wanted to include a verified certificate on my resume and my profile to
illustrate that I am working towards this goal I have and that I have
achieved something while I was unemployed."
/>
<br />
<strong>&mdash; <FormattedMessage
id="coursesock.upsell.learner"
description="Name of learner"
defaultMessage="{ name }, edX Learner"
values={{ name: 'Cheryl Troell' }}
/>
</strong>
</div>
</div>
</div>
<div className="d-flex flex-column justify-content-between">
<img alt="Example Certificate" src={VerifiedCert} />
<a href={this.verifiedMode.upgradeUrl} className="btn btn-success btn-lg btn-upgrade focusable" data-creative="original_sock" data-position="sock">
<FormattedMessage
id="coursesock.upsell.upgrade"
defaultMessage="Upgrade ({symbol}{price} {currency})"
values={{
symbol: this.verifiedMode.currencySymbol,
price: this.verifiedMode.price,
currency: this.verifiedMode.currency,
}}
/>
</a>
</div>
</div>
)} )}
</div> </div>
); );

View File

@@ -0,0 +1,16 @@
import { defineMessages } from '@edx/frontend-platform/i18n';
const messages = defineMessages({
'learn.loading.learning.sequence': {
id: 'learn.loading.learning.sequence',
defaultMessage: 'Loading learning sequence...',
description: 'Message when learning sequence is being loaded',
},
'learn.course.load.failure': {
id: 'learn.course.load.failure',
defaultMessage: 'There was an error loading this course.',
description: 'Message when a course fails to load',
},
});
export default messages;

View File

@@ -1,19 +1,20 @@
/* eslint-disable no-use-before-define */ /* eslint-disable no-use-before-define */
import React, { import React, {
useEffect, useContext, useState, useEffect, useContext, Suspense, useState,
} from 'react'; } from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { sendTrackEvent } from '@edx/frontend-platform/analytics'; import { sendTrackEvent } from '@edx/frontend-platform/analytics';
import { injectIntl, intlShape } from '@edx/frontend-platform/i18n'; import { injectIntl, intlShape } from '@edx/frontend-platform/i18n';
import { useSelector } from 'react-redux';
import { useSelector } from 'react-redux';
import Unit from './Unit';
import { SequenceNavigation, UnitNavigation } from './sequence-navigation';
import PageLoading from '../../../PageLoading'; import PageLoading from '../../../PageLoading';
import { UserMessagesContext, ALERT_TYPES } from '../../../user-messages'; import messages from './messages';
import UserMessagesContext from '../../../user-messages/UserMessagesContext';
import { useModel } from '../../../model-store'; import { useModel } from '../../../model-store';
import messages from './messages'; const ContentLock = React.lazy(() => import('./content-lock'));
import { SequenceNavigation, UnitNavigation } from './sequence-navigation';
import SequenceContent from './SequenceContent';
function Sequence({ function Sequence({
unitId, unitId,
@@ -77,7 +78,7 @@ function Sequence({
code: null, code: null,
dismissible: false, dismissible: false,
text: sequence.bannerText, text: sequence.bannerText,
type: ALERT_TYPES.INFO, type: 'info',
topic: 'sequence', topic: 'sequence',
}); });
} }
@@ -131,13 +132,29 @@ function Sequence({
}} }}
/> />
<div className="unit-container flex-grow-1"> <div className="unit-container flex-grow-1">
<SequenceContent {gated && (
courseId={courseId} <Suspense
gated={gated} fallback={(
sequenceId={sequenceId} <PageLoading
unitId={unitId} srMessage={intl.formatMessage(messages['learn.loading.content.lock'])}
unitLoadedHandler={handleUnitLoaded} />
/> )}
>
<ContentLock
courseId={courseId}
sequenceTitle={sequence.title}
prereqSectionName={sequence.gatedContent.gatedSectionName}
prereqId={sequence.gatedContent.prereqId}
/>
</Suspense>
)}
{!gated && unitId !== null && (
<Unit
key={unitId}
id={unitId}
onLoaded={handleUnitLoaded}
/>
)}
{unitHasLoaded && ( {unitHasLoaded && (
<UnitNavigation <UnitNavigation
sequenceId={sequenceId} sequenceId={sequenceId}

View File

@@ -1,72 +0,0 @@
import React, { Suspense, useEffect } from 'react';
import PropTypes from 'prop-types';
import { injectIntl, intlShape } from '@edx/frontend-platform/i18n';
import PageLoading from '../../../PageLoading';
import { useModel } from '../../../model-store';
import messages from './messages';
import Unit from './Unit';
const ContentLock = React.lazy(() => import('./content-lock'));
function SequenceContent({
gated, intl, courseId, sequenceId, unitId, unitLoadedHandler,
}) {
const sequence = useModel('sequences', sequenceId);
// Go back to the top of the page whenever the unit or sequence changes.
useEffect(() => {
global.scrollTo(0, 0);
}, [sequenceId, unitId]);
if (gated) {
return (
<Suspense
fallback={(
<PageLoading
srMessage={intl.formatMessage(messages['learn.loading.content.lock'])}
/>
)}
>
<ContentLock
courseId={courseId}
sequenceTitle={sequence.title}
prereqSectionName={sequence.gatedContent.gatedSectionName}
prereqId={sequence.gatedContent.prereqId}
/>
</Suspense>
);
}
if (unitId === null) {
return (
<div>
{intl.formatMessage(messages['learn.sequence.no.content'])}
</div>
);
}
return (
<Unit
courseId={courseId}
key={unitId}
id={unitId}
onLoaded={unitLoadedHandler}
/>
);
}
SequenceContent.propTypes = {
gated: PropTypes.bool.isRequired,
courseId: PropTypes.string.isRequired,
sequenceId: PropTypes.string.isRequired,
unitId: PropTypes.string,
unitLoadedHandler: PropTypes.func.isRequired,
intl: intlShape.isRequired,
};
SequenceContent.defaultProps = {
unitId: null,
};
export default injectIntl(SequenceContent);

View File

@@ -1,78 +1,25 @@
import React, { import React, { useRef, useEffect, useState } from 'react';
Suspense,
useEffect,
useRef,
useState,
useLayoutEffect,
} from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { getConfig } from '@edx/frontend-platform'; import { getConfig } from '@edx/frontend-platform';
import { injectIntl, intlShape } from '@edx/frontend-platform/i18n';
import messages from './messages';
import BookmarkButton from '../bookmark/BookmarkButton'; import BookmarkButton from '../bookmark/BookmarkButton';
import { useModel } from '../../../model-store'; import { useModel } from '../../../model-store';
import PageLoading from '../../../PageLoading';
const LockPaywall = React.lazy(() => import('./lock-paywall')); export default function Unit({
/**
* We discovered an error in Firefox where - upon iframe load - React would cease to call any
* useEffect hooks until the user interacts with the page again. This is particularly confusing
* when navigating between sequences, as the UI partially updates leaving the user in a nebulous
* state.
*
* We were able to solve this error by using a layout effect to update some component state, which
* executes synchronously on render. Somehow this forces React to continue it's lifecycle
* immediately, rather than waiting for user interaction. This layout effect could be anywhere in
* the parent tree, as far as we can tell - we chose to add a conspicuously 'load bearing' (that's
* a joke) one here so it wouldn't be accidentally removed elsewhere.
*
* If we remove this hook when one of these happens:
* 1. React figures out that there's an issue here and fixes a bug.
* 2. We cease to use an iframe for unit rendering.
* 3. Firefox figures out that there's an issue in their iframe loading and fixes a bug.
* 4. We stop supporting Firefox.
* 5. An enterprising engineer decides to create a repo that reproduces the problem, submits it to
* Firefox/React for review, and they kindly help us figure out what in the world is happening
* so we can fix it.
*
* This hook depends on the unit id just to make sure it re-evaluates whenever the ID changes. If
* we change whether or not the Unit component is re-mounted when the unit ID changes, this may
* become important, as this hook will otherwise only evaluate the useLayoutEffect once.
*/
function useLoadBearingHook(id) {
const setValue = useState(0)[1];
useLayoutEffect(() => {
setValue(currentValue => currentValue + 1);
}, [id]);
}
function Unit({
courseId,
onLoaded, onLoaded,
id, id,
intl,
}) { }) {
const iframeRef = useRef(null);
const iframeUrl = `${getConfig().LMS_BASE_URL}/xblock/${id}?show_title=0&show_bookmark_button=0`; const iframeUrl = `${getConfig().LMS_BASE_URL}/xblock/${id}?show_title=0&show_bookmark_button=0`;
const [iframeHeight, setIframeHeight] = useState(0); const [iframeHeight, setIframeHeight] = useState(0);
const [hasLoaded, setHasLoaded] = useState(false); const [hasLoaded, setHasLoaded] = useState(false);
const unit = useModel('units', id); const unit = useModel('units', id);
const course = useModel('courses', courseId);
const {
contentTypeGatingEnabled,
enrollmentMode,
} = course;
// Do not remove this hook. See function description.
useLoadBearingHook(id);
// We use this ref so that we can hold a reference to the currently active event listener.
const messageEventListenerRef = useRef(null);
useEffect(() => { useEffect(() => {
function receiveMessage(event) { global.onmessage = (event) => {
const { type, payload } = event.data; const { type, payload } = event.data;
if (type === 'plugin.resize') { if (type === 'plugin.resize') {
setIframeHeight(payload.height); setIframeHeight(payload.height);
if (!hasLoaded && iframeHeight === 0 && payload.height > 0) { if (!hasLoaded && iframeHeight === 0 && payload.height > 0) {
@@ -82,19 +29,8 @@ function Unit({
} }
} }
} }
} };
// If we currently have an event listener, remove it. }, []);
if (messageEventListenerRef.current !== null) {
global.removeEventListener('message', messageEventListenerRef.current);
messageEventListenerRef.current = null;
}
// Now add our new receiveMessage handler as the event listener.
global.addEventListener('message', receiveMessage);
// And then save it to our ref for next time.
messageEventListenerRef.current = receiveMessage;
// When the component finally unmounts, use the ref to remove the correct handler.
return () => global.removeEventListener('message', messageEventListenerRef.current);
}, [id, setIframeHeight, hasLoaded, iframeHeight, setHasLoaded, onLoaded]);
return ( return (
<div className="unit"> <div className="unit">
@@ -104,28 +40,11 @@ function Unit({
isBookmarked={unit.bookmarked} isBookmarked={unit.bookmarked}
isProcessing={unit.bookmarkedUpdateState === 'loading'} isProcessing={unit.bookmarkedUpdateState === 'loading'}
/> />
{ contentTypeGatingEnabled && unit.graded && enrollmentMode === 'audit' && (
<Suspense
fallback={(
<PageLoading
srMessage={intl.formatMessage(messages['learn.loading.content.lock'])}
/>
)}
>
<LockPaywall
courseId={courseId}
/>
</Suspense>
)}
{!hasLoaded && (
<PageLoading
srMessage={intl.formatMessage(messages['learn.loading.learning.sequence'])}
/>
)}
<div className="unit-iframe-wrapper"> <div className="unit-iframe-wrapper">
<iframe <iframe
id="unit-iframe" id="unit-iframe"
title={unit.title} title={unit.title}
ref={iframeRef}
src={iframeUrl} src={iframeUrl}
allowFullScreen allowFullScreen
height={iframeHeight} height={iframeHeight}
@@ -138,14 +57,10 @@ function Unit({
} }
Unit.propTypes = { Unit.propTypes = {
courseId: PropTypes.string.isRequired,
id: PropTypes.string.isRequired, id: PropTypes.string.isRequired,
intl: intlShape.isRequired,
onLoaded: PropTypes.func, onLoaded: PropTypes.func,
}; };
Unit.defaultProps = { Unit.defaultProps = {
onLoaded: undefined, onLoaded: undefined,
}; };
export default injectIntl(Unit);

View File

@@ -12,7 +12,7 @@ function ContentLock({
intl, courseId, prereqSectionName, prereqId, sequenceTitle, intl, courseId, prereqSectionName, prereqId, sequenceTitle,
}) { }) {
const handleClick = useCallback(() => { const handleClick = useCallback(() => {
history.push(`/course/${courseId}/${prereqId}`); history.push(`/learning/course/${courseId}/${prereqId}`);
}); });
return ( return (

View File

@@ -1,61 +0,0 @@
import React from 'react';
import PropTypes from 'prop-types';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faLock } from '@fortawesome/free-solid-svg-icons';
import { injectIntl, intlShape } from '@edx/frontend-platform/i18n';
import messages from './messages';
import VerifiedCert from './assets/edx-verified-mini-cert.png';
import { useModel } from '../../../../model-store';
function LockPaywall({
intl,
courseId,
}) {
const course = useModel('courses', courseId);
const {
verifiedMode,
} = course;
if (!verifiedMode) {
return null;
}
const {
currencySymbol,
price,
upgradeUrl,
} = verifiedMode;
return (
<div className="border border-gray rounded d-flex justify-content-between mt-2 p-3">
<div>
<h4 className="font-weight-bold mb-2">
<FontAwesomeIcon icon={faLock} className="text-black mr-2 ml-1" style={{ fontSize: '2rem' }} />
<span>{intl.formatMessage(messages['learn.lockPaywall.title'])}</span>
</h4>
<p className="mb-0">
<span>{intl.formatMessage(messages['learn.lockPaywall.content'])}</span>
&nbsp;
<a href={upgradeUrl}>
{intl.formatMessage(messages['learn.lockPaywall.upgrade.link'], {
currencySymbol,
price,
})}
</a>
</p>
</div>
<div>
<img
alt={intl.formatMessage(messages['learn.lockPaywall.example.alt'])}
src={VerifiedCert}
className="border-0"
style={{ height: '70px' }}
/>
</div>
</div>
);
}
LockPaywall.propTypes = {
intl: intlShape.isRequired,
courseId: PropTypes.string.isRequired,
};
export default injectIntl(LockPaywall);

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.9 KiB

View File

@@ -1 +0,0 @@
export { default } from './LockPaywall';

View File

@@ -1,26 +0,0 @@
import { defineMessages } from '@edx/frontend-platform/i18n';
const messages = defineMessages({
'learn.lockPaywall.title': {
id: 'learn.lockPaywall.title',
defaultMessage: 'Verified Track Access',
description: 'Heading for message shown to indicate that a piece of content is unavailable to audit track users.',
},
'learn.lockPaywall.content': {
id: 'learn.lockPaywall.content',
defaultMessage: 'Graded assessments are available to Verified Track learners.',
description: 'Message shown to indicate that a piece of content is unavailable to audit track users.',
},
'learn.lockPaywall.upgrade.link': {
id: 'learn.lockPaywall.upgrade.link',
defaultMessage: 'Upgrade to unlock ({currencySymbol}{price})',
description: 'A link users can click that navigates their browser to the upgrade payment page.',
},
'learn.lockPaywall.example.alt': {
id: 'learn.lockPaywall.example.alt',
defaultMessage: 'Example Certificate',
description: 'Alternate text displayed when the example certificate image cannot be displayed.',
},
});
export default messages;

View File

@@ -16,11 +16,6 @@ const messages = defineMessages({
defaultMessage: 'There was an error loading this course.', defaultMessage: 'There was an error loading this course.',
description: 'Message when a course fails to load', description: 'Message when a course fails to load',
}, },
'learn.sequence.no.content': {
id: 'learn.sequence.no.content',
defaultMessage: 'There is no content here.',
description: 'Message shown when there is no content to show a user inside a learning sequence.',
},
}); });
export default messages; export default messages;

View File

@@ -1,33 +0,0 @@
import React from 'react';
import PropTypes from 'prop-types';
import Calculator from './calculator';
import NotesVisibility from './notes/NotesVisibility';
import './tools.scss';
export default function ContentTools({
course,
}) {
return (
<div className="content-tools">
<div className="d-flex justify-content-end align-items-end m-0">
{course.showCalculator && (
<Calculator />
)}
{course.notes.enabled && (
<NotesVisibility course={course} />
)}
</div>
</div>
);
}
ContentTools.propTypes = {
course: PropTypes.shape({
notes: PropTypes.shape({
enabled: PropTypes.bool,
}),
showCalculator: PropTypes.bool,
}).isRequired,
};

View File

@@ -1,7 +0,0 @@
.calculator {
flex-grow: 1;
.calculator-content {
background-color: #f1f1f1;
box-shadow: 0 -1px 0 0 #ddd;
}
}

View File

@@ -1,6 +0,0 @@
import { getConfig } from '@edx/frontend-platform';
export default function toggleNotes() {
const iframe = document.getElementById('unit-iframe');
iframe.contentWindow.postMessage('tools.toggleNotes', getConfig().LMS_BASE_URL);
}

View File

@@ -1,65 +0,0 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { getConfig } from '@edx/frontend-platform';
import { getAuthenticatedHttpClient } from '@edx/frontend-platform/auth';
import {
injectIntl, intlShape,
} from '@edx/frontend-platform/i18n';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPencilAlt } from '@fortawesome/free-solid-svg-icons';
import toggleNotes from '../data/api';
import messages from './messages';
class NotesVisibility extends Component {
constructor(props) {
super(props);
this.state = {
visible: props.course.notes.visible,
};
this.visibilityUrl = `${getConfig().LMS_BASE_URL}/courses/${props.course.id}/edxnotes/visibility/`;
}
handleClick = () => {
const data = { visibility: this.state.visible };
getAuthenticatedHttpClient().put(
this.visibilityUrl,
data,
).then(() => {
this.setState((state) => ({ visible: !state.visible }));
toggleNotes();
});
}
render() {
const message = this.state.visible ? 'notes.button.hide' : 'notes.button.show';
return (
<button
className={`trigger btn ${this.state.visible ? 'text-secondary' : 'text-success'} mx-2 `}
role="switch"
type="button"
onClick={this.handleClick}
onKeyDown={this.handleClick}
tabIndex="-1"
aria-checked={this.state.visible ? 'true' : 'false'}
>
<FontAwesomeIcon icon={faPencilAlt} aria-hidden="true" className="mr-2" />
{this.props.intl.formatMessage(messages[message])}
</button>
);
}
}
NotesVisibility.propTypes = {
intl: intlShape.isRequired,
course: PropTypes.shape({
id: PropTypes.string,
notes: PropTypes.shape({
enabled: PropTypes.bool,
visible: PropTypes.bool,
}),
}).isRequired,
};
export default injectIntl(NotesVisibility);

View File

@@ -1,16 +0,0 @@
import { defineMessages } from '@edx/frontend-platform/i18n';
const messages = defineMessages({
'notes.button.show': {
id: 'notes.button.show',
defaultMessage: 'Show Notes',
description: 'Message for toggling notes visibility',
},
'notes.button.hide': {
id: 'notes.button.hide',
defaultMessage: 'Hide Notes',
description: 'Message for toggling notes visibility',
},
});
export default messages;

View File

@@ -3,30 +3,11 @@ import { getConfig, camelCaseObject } from '@edx/frontend-platform';
import { getAuthenticatedHttpClient, getAuthenticatedUser } from '@edx/frontend-platform/auth'; import { getAuthenticatedHttpClient, getAuthenticatedUser } from '@edx/frontend-platform/auth';
import { logError } from '@edx/frontend-platform/logging'; import { logError } from '@edx/frontend-platform/logging';
function overrideTabUrls(id, tabs) {
// "LMS tab slug" to "MFE URL slug" for overridden tabs
const tabOverrides = {};
return tabs.map((tab) => {
let url;
if (tabOverrides[tab.slug]) {
url = `/course/${id}/${tabOverrides[tab.slug]}`;
} else {
url = `${getConfig().LMS_BASE_URL}${tab.url}`;
}
return { ...tab, url };
});
}
function normalizeMetadata(metadata) { function normalizeMetadata(metadata) {
return { return {
canShowUpgradeSock: metadata.can_show_upgrade_sock,
contentTypeGatingEnabled: metadata.content_type_gating_enabled,
// TODO: TNL-7185: return course expired _date_, instead of _message_
courseExpiredMessage: metadata.course_expired_message,
id: metadata.id, id: metadata.id,
title: metadata.name, title: metadata.name,
number: metadata.number, number: metadata.number,
offerHtml: metadata.offer_html,
org: metadata.org, org: metadata.org,
enrollmentStart: metadata.enrollment_start, enrollmentStart: metadata.enrollment_start,
enrollmentEnd: metadata.enrollment_end, enrollmentEnd: metadata.enrollment_end,
@@ -34,12 +15,11 @@ function normalizeMetadata(metadata) {
start: metadata.start, start: metadata.start,
enrollmentMode: metadata.enrollment.mode, enrollmentMode: metadata.enrollment.mode,
isEnrolled: metadata.enrollment.is_active, isEnrolled: metadata.enrollment.is_active,
canLoadCourseware: camelCaseObject(metadata.can_load_courseware), canLoadCourseware: metadata.can_load_courseware,
isStaff: metadata.is_staff, isStaff: metadata.is_staff,
verifiedMode: camelCaseObject(metadata.verified_mode), verifiedMode: camelCaseObject(metadata.verified_mode),
tabs: overrideTabUrls(metadata.id, camelCaseObject(metadata.tabs)), tabs: camelCaseObject(metadata.tabs),
showCalculator: metadata.show_calculator, showCalculator: metadata.show_calculator,
notes: camelCaseObject(metadata.notes),
}; };
} }
@@ -83,10 +63,8 @@ function normalizeBlocks(courseId, blocks) {
break; break;
case 'vertical': case 'vertical':
models.units[block.id] = { models.units[block.id] = {
graded: block.graded,
id: block.id, id: block.id,
title: block.display_name, title: block.display_name,
lmsWebUrl: block.lms_web_url,
}; };
break; break;
default: default:
@@ -130,13 +108,12 @@ export async function getCourseBlocks(courseId) {
url.searchParams.append('course_id', courseId); url.searchParams.append('course_id', courseId);
url.searchParams.append('username', username); url.searchParams.append('username', username);
url.searchParams.append('depth', 3); url.searchParams.append('depth', 3);
url.searchParams.append('requested_fields', 'children,show_gated_sections,graded'); url.searchParams.append('requested_fields', 'children,show_gated_sections');
const { data } = await getAuthenticatedHttpClient().get(url.href, {}); const { data } = await getAuthenticatedHttpClient().get(url.href, {});
return normalizeBlocks(courseId, data.blocks); return normalizeBlocks(courseId, data.blocks);
} }
function normalizeSequenceMetadata(sequence) { function normalizeSequenceMetadata(sequence) {
return { return {
sequence: { sequence: {
@@ -168,9 +145,3 @@ export async function getSequenceMetadata(sequenceId) {
return normalizeSequenceMetadata(data); return normalizeSequenceMetadata(data);
} }
export async function getResumeBlock(courseId) {
const url = new URL(`${getConfig().LMS_BASE_URL}/api/courseware/resume/${courseId}`);
const { data } = await getAuthenticatedHttpClient().get(url.href, {});
return camelCaseObject(data);
}

View File

@@ -3,5 +3,4 @@ export {
fetchSequence, fetchSequence,
} from './thunks'; } from './thunks';
export { getResumeBlock } from './api';
export { reducer } from './slice'; export { reducer } from './slice';

View File

@@ -68,7 +68,7 @@ export function fetchCourse(courseId) {
} }
if (fetchedMetadata) { if (fetchedMetadata) {
if (courseMetadataResult.value.canLoadCourseware.hasAccess && fetchedBlocks) { if (courseMetadataResult.value.canLoadCourseware && fetchedBlocks) {
// User has access // User has access
dispatch(fetchCourseSuccess({ courseId })); dispatch(fetchCourseSuccess({ courseId }));
return; return;

View File

@@ -1,37 +1,24 @@
import React from 'react'; import React from 'react';
import { getConfig } from '@edx/frontend-platform';
import { injectIntl, intlShape } from '@edx/frontend-platform/i18n'; import { injectIntl, intlShape } from '@edx/frontend-platform/i18n';
import PropTypes from 'prop-types';
import { Button } from '@edx/paragon';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSpinner } from '@fortawesome/free-solid-svg-icons';
import { Alert } from '../user-messages';
import Alert from '../user-messages/Alert';
import messages from './messages'; import messages from './messages';
import { useEnrollClickHandler } from './hooks';
function EnrollmentAlert({ intl, courseId }) {
const { enrollClickHandler, loading } = useEnrollClickHandler(
courseId,
intl.formatMessage(messages['learning.enrollment.success']),
);
function EnrollmentAlert({ intl }) {
return ( return (
<Alert type="error"> <Alert type="error">
{intl.formatMessage(messages['learning.enrollment.alert'])} {intl.formatMessage(messages['learning.enrollment.alert'])}
{' '} {' '}
<Button disabled={loading} className="btn-link p-0 border-0 align-top" onClick={enrollClickHandler}> <a href={`${getConfig().LMS_BASE_URL}/api/enrollment/v1/enrollment`}>
{intl.formatMessage(messages['learning.enrollment.enroll.now'])} {intl.formatMessage(messages['learning.enrollment.enroll.now'])}
</Button> </a>
{' '}
{loading && <FontAwesomeIcon icon={faSpinner} spin />}
</Alert> </Alert>
); );
} }
EnrollmentAlert.propTypes = { EnrollmentAlert.propTypes = {
intl: intlShape.isRequired, intl: intlShape.isRequired,
courseId: PropTypes.string.isRequired,
}; };
export default injectIntl(EnrollmentAlert); export default injectIntl(EnrollmentAlert);

View File

@@ -1,37 +1,24 @@
import React from 'react'; import React from 'react';
import { getConfig } from '@edx/frontend-platform';
import { injectIntl, intlShape } from '@edx/frontend-platform/i18n'; import { injectIntl, intlShape } from '@edx/frontend-platform/i18n';
import PropTypes from 'prop-types';
import { Button } from '@edx/paragon';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSpinner } from '@fortawesome/free-solid-svg-icons';
import { Alert } from '../user-messages';
import Alert from '../user-messages/Alert';
import messages from './messages'; import messages from './messages';
import { useEnrollClickHandler } from './hooks';
function StaffEnrollmentAlert({ intl, courseId }) {
const { enrollClickHandler, loading } = useEnrollClickHandler(
courseId,
intl.formatMessage(messages['learning.enrollment.success']),
);
function StaffEnrollmentAlert({ intl }) {
return ( return (
<Alert type="info" dismissible> <Alert type="info" dismissible>
{intl.formatMessage(messages['learning.staff.enrollment.alert'])} {intl.formatMessage(messages['learning.staff.enrollment.alert'])}
{' '} {' '}
<Button disabled={loading} className="btn-link p-0 border-0 align-top" onClick={enrollClickHandler}> <a href={`${getConfig().LMS_BASE_URL}/api/enrollment/v1/enrollment`}>
{intl.formatMessage(messages['learning.enrollment.enroll.now'])} {intl.formatMessage(messages['learning.enrollment.enroll.now'])}
</Button> </a>
{' '}
{loading && <FontAwesomeIcon icon={faSpinner} spin />}
</Alert> </Alert>
); );
} }
StaffEnrollmentAlert.propTypes = { StaffEnrollmentAlert.propTypes = {
intl: intlShape.isRequired, intl: intlShape.isRequired,
courseId: PropTypes.string.isRequired,
}; };
export default injectIntl(StaffEnrollmentAlert); export default injectIntl(StaffEnrollmentAlert);

View File

@@ -1,9 +0,0 @@
/* eslint-disable import/prefer-default-export */
import { getAuthenticatedHttpClient } from '@edx/frontend-platform/auth';
import { getConfig } from '@edx/frontend-platform';
export async function postCourseEnrollment(courseId) {
const url = `${getConfig().LMS_BASE_URL}/api/enrollment/v1/enrollment`;
const { data } = await getAuthenticatedHttpClient().post(url, { course_details: { course_id: courseId } });
return data;
}

View File

@@ -1,10 +1,7 @@
/* eslint-disable import/prefer-default-export */ /* eslint-disable import/prefer-default-export */
import { import { useContext, useState, useEffect } from 'react';
useContext, useState, useEffect, useCallback, import UserMessagesContext from '../user-messages/UserMessagesContext';
} from 'react';
import { UserMessagesContext, ALERT_TYPES } from '../user-messages';
import { useModel } from '../model-store'; import { useModel } from '../model-store';
import { postCourseEnrollment } from './data/api';
export function useEnrollmentAlert(courseId) { export function useEnrollmentAlert(courseId) {
const course = useModel('courses', courseId); const course = useModel('courses', courseId);
@@ -14,11 +11,17 @@ export function useEnrollmentAlert(courseId) {
useEffect(() => { useEffect(() => {
if (course && course.isEnrolled !== undefined) { if (course && course.isEnrolled !== undefined) {
if (!course.isEnrolled && alertId === null) { if (!course.isEnrolled && alertId === null) {
const code = course.isStaff ? 'clientStaffEnrollmentAlert' : 'clientEnrollmentAlert'; if (course.isStaff) {
setAlertId(add({ setAlertId(add({
code, code: 'clientStaffEnrollmentAlert',
topic: 'course', topic: 'course',
})); }));
} else {
setAlertId(add({
code: 'clientEnrollmentAlert',
topic: 'course',
}));
}
} else if (course.isEnrolled && alertId !== null) { } else if (course.isEnrolled && alertId !== null) {
remove(alertId); remove(alertId);
setAlertId(null); setAlertId(null);
@@ -31,24 +34,3 @@ export function useEnrollmentAlert(courseId) {
}; };
}, [course, isEnrolled]); }, [course, isEnrolled]);
} }
export function useEnrollClickHandler(courseId, successText) {
const [loading, setLoading] = useState(false);
const { addFlash } = useContext(UserMessagesContext);
const enrollClickHandler = useCallback(() => {
setLoading(true);
postCourseEnrollment(courseId).then(() => {
addFlash({
dismissible: true,
flash: true,
text: successText,
type: ALERT_TYPES.SUCCESS,
topic: 'course',
});
setLoading(false);
global.location.reload();
});
}, [courseId]);
return { enrollClickHandler, loading };
}

View File

@@ -16,11 +16,6 @@ const messages = defineMessages({
defaultMessage: 'Enroll Now', defaultMessage: 'Enroll Now',
description: 'A link prompting the user to click on it to enroll in the currently viewed course.', description: 'A link prompting the user to click on it to enroll in the currently viewed course.',
}, },
'learning.enrollment.success': {
id: 'learning.enrollment.success',
defaultMessage: "You've successfully enrolled in this course!",
description: 'A message telling the user that their course enrollment was successful.',
},
}); });
export default messages; export default messages;

View File

@@ -3,7 +3,6 @@ import 'regenerator-runtime/runtime';
import { import {
APP_INIT_ERROR, APP_READY, subscribe, initialize, APP_INIT_ERROR, APP_READY, subscribe, initialize,
mergeConfig,
} from '@edx/frontend-platform'; } from '@edx/frontend-platform';
import { AppProvider, ErrorPage } from '@edx/frontend-platform/react'; import { AppProvider, ErrorPage } from '@edx/frontend-platform/react';
import React from 'react'; import React from 'react';
@@ -14,14 +13,13 @@ import { messages as headerMessages } from '@edx/frontend-component-header';
import Footer, { messages as footerMessages } from '@edx/frontend-component-footer'; import Footer, { messages as footerMessages } from '@edx/frontend-component-footer';
import appMessages from './i18n'; import appMessages from './i18n';
import { UserMessagesProvider } from './user-messages'; import UserMessagesProvider from './user-messages/UserMessagesProvider';
import './index.scss'; import './index.scss';
import './assets/favicon.ico'; import './assets/favicon.ico';
import CourseHome from './course-home';
import CoursewareContainer from './courseware'; import CoursewareContainer from './courseware';
import CourseHomeContainer from './course-home';
import CoursewareRedirect from './CoursewareRedirect'; import CoursewareRedirect from './CoursewareRedirect';
import { TabContainer } from './tab-page';
import store from './store'; import store from './store';
@@ -30,17 +28,13 @@ subscribe(APP_READY, () => {
<AppProvider store={store}> <AppProvider store={store}>
<UserMessagesProvider> <UserMessagesProvider>
<Switch> <Switch>
<Route path="/redirect" component={CoursewareRedirect} /> <Route path="/learning/redirect" component={CoursewareRedirect} />
<Route path="/course/:courseId/home"> <Route path="/learning/course/:courseId/home" component={CourseHomeContainer} />
<TabContainer tab="courseware">
<CourseHome />
</TabContainer>
</Route>
<Route <Route
path={[ path={[
'/course/:courseId/:sequenceId/:unitId', '/learning/course/:courseId/:sequenceId/:unitId',
'/course/:courseId/:sequenceId', '/learning/course/:courseId/:sequenceId',
'/course/:courseId', '/learning/course/:courseId',
]} ]}
component={CoursewareContainer} component={CoursewareContainer}
/> />
@@ -57,14 +51,6 @@ subscribe(APP_INIT_ERROR, (error) => {
}); });
initialize({ initialize({
handlers: {
config: () => {
mergeConfig({
INSIGHTS_BASE_URL: process.env.INSIGHTS_BASE_URL || null,
STUDIO_BASE_URL: process.env.STUDIO_BASE_URL || null,
}, 'LearnerAppConfig');
},
},
// TODO: Remove this once the course blocks api supports unauthenticated // TODO: Remove this once the course blocks api supports unauthenticated
// access and we are prepared to support public courses in this app. // access and we are prepared to support public courses in this app.
requireAuthenticatedUser: true, requireAuthenticatedUser: true,

View File

@@ -32,7 +32,7 @@ $primary: #1176B2;
flex-grow: 1; flex-grow: 1;
} }
header { header {
flex: 0 0 auto; flex: 0;
.logo { .logo {
display: block; display: block;
@@ -108,6 +108,7 @@ $primary: #1176B2;
@media (min-width: map-get($grid-breakpoints, 'sm')) { @media (min-width: map-get($grid-breakpoints, 'sm')) {
max-width: 1440px; max-width: 1440px;
width: 100%; width: 100%;
padding: 0 $grid-gutter-width;
margin-right: auto; margin-right: auto;
margin-left: auto; margin-left: auto;
} }
@@ -185,7 +186,7 @@ $primary: #1176B2;
.sequence-navigation-tabs { .sequence-navigation-tabs {
.btn { .btn {
flex-basis: 100%; flex-basis: 100%;
min-width: 2rem; min-width: 4rem;
} }
} }
.sequence-navigation-dropdown { .sequence-navigation-dropdown {

View File

@@ -3,7 +3,7 @@ import { getConfig } from '@edx/frontend-platform';
import { injectIntl, intlShape, FormattedMessage } from '@edx/frontend-platform/i18n'; import { injectIntl, intlShape, FormattedMessage } from '@edx/frontend-platform/i18n';
import { getLoginRedirectUrl } from '@edx/frontend-platform/auth'; import { getLoginRedirectUrl } from '@edx/frontend-platform/auth';
import { Alert } from '../user-messages'; import Alert from '../user-messages/Alert';
import messages from './messages'; import messages from './messages';
function LogistrationAlert({ intl }) { function LogistrationAlert({ intl }) {

View File

@@ -1,7 +1,7 @@
/* eslint-disable import/prefer-default-export */ /* eslint-disable import/prefer-default-export */
import { useContext, useState, useEffect } from 'react'; import { useContext, useState, useEffect } from 'react';
import { AppContext } from '@edx/frontend-platform/react'; import { AppContext } from '@edx/frontend-platform/react';
import { UserMessagesContext, ALERT_TYPES } from '../user-messages'; import UserMessagesContext from '../user-messages/UserMessagesContext';
export function useLogistrationAlert() { export function useLogistrationAlert() {
const { authenticatedUser } = useContext(AppContext); const { authenticatedUser } = useContext(AppContext);
@@ -12,7 +12,7 @@ export function useLogistrationAlert() {
setAlertId(add({ setAlertId(add({
code: 'clientLogistrationAlert', code: 'clientLogistrationAlert',
dismissible: false, dismissible: false,
type: ALERT_TYPES.ERROR, type: 'error',
topic: 'course', topic: 'course',
})); }));
} else if (authenticatedUser !== null && alertId !== null) { } else if (authenticatedUser !== null && alertId !== null) {

View File

@@ -1,21 +0,0 @@
import React from 'react';
import PropTypes from 'prop-types';
import { Alert } from '../user-messages';
function OfferAlert(props) {
const {
rawHtml,
} = props;
return rawHtml && (
<Alert type="info">
<div dangerouslySetInnerHTML={{ __html: rawHtml }} />
</Alert>
);
}
OfferAlert.propTypes = {
rawHtml: PropTypes.string.isRequired,
};
export default OfferAlert;

View File

@@ -1,28 +0,0 @@
/* eslint-disable import/prefer-default-export */
import { useContext, useState, useEffect } from 'react';
import { UserMessagesContext } from '../user-messages';
import { useModel } from '../model-store';
export function useOfferAlert(courseId) {
const course = useModel('courses', courseId);
const { add, remove } = useContext(UserMessagesContext);
const [alertId, setAlertId] = useState(null);
const rawHtml = (course && course.offerHtml) || null;
useEffect(() => {
if (rawHtml && alertId === null) {
setAlertId(add({
code: 'clientOfferAlert',
topic: 'course',
rawHtml,
}));
} else if (!rawHtml && alertId !== null) {
remove(alertId);
setAlertId(null);
}
return () => {
if (alertId !== null) {
remove(alertId);
}
};
}, [alertId, courseId, rawHtml]);
}

View File

@@ -1,2 +0,0 @@
export { default as OfferAlert } from './OfferAlert';
export { useOfferAlert } from './hooks';

View File

@@ -1,60 +0,0 @@
import React from 'react';
import PropTypes from 'prop-types';
import { Header, CourseTabsNavigation } from '../course-header';
import { useModel } from '../model-store';
import { useEnrollmentAlert } from '../enrollment-alert';
import InstructorToolbar from '../courseware/course/InstructorToolbar';
function LoadedTabPage({
activeTabSlug,
children,
courseId,
unitId,
}) {
useEnrollmentAlert(courseId);
const {
isStaff,
number,
org,
tabs,
title,
} = useModel('courses', courseId);
return (
<>
<Header
courseOrg={org}
courseNumber={number}
courseTitle={title}
/>
{isStaff && (
<InstructorToolbar
courseId={courseId}
unitId={unitId}
/>
)}
<main className="d-flex flex-column flex-grow-1">
<CourseTabsNavigation tabs={tabs} className="mb-3" activeTabSlug={activeTabSlug} />
<div className="container-fluid">
{children}
</div>
</main>
</>
);
}
LoadedTabPage.propTypes = {
activeTabSlug: PropTypes.string.isRequired,
children: PropTypes.node,
courseId: PropTypes.string.isRequired,
unitId: PropTypes.string,
};
LoadedTabPage.defaultProps = {
children: null,
unitId: null,
};
export default LoadedTabPage;

View File

@@ -1,42 +0,0 @@
import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import { useDispatch, useSelector } from 'react-redux';
import { useParams } from 'react-router-dom';
import { fetchCourse } from '../data';
import TabPage from './TabPage';
export default function TabContainer(props) {
const {
children,
tab,
} = props;
const { courseId: courseIdFromUrl } = useParams();
const dispatch = useDispatch();
useEffect(() => {
// The courseId from the URL is the course we WANT to load.
dispatch(fetchCourse(courseIdFromUrl));
}, [courseIdFromUrl]);
// The courseId from the store is the course we HAVE loaded. If the URL changes,
// we don't want the application to adjust to it until it has actually loaded the new data.
const {
courseId,
} = useSelector(state => state.courseware);
return (
<TabPage
activeTabSlug={tab}
courseId={courseId}
>
{children}
</TabPage>
);
}
TabContainer.propTypes = {
children: PropTypes.node.isRequired,
tab: PropTypes.string.isRequired,
};

View File

@@ -1,52 +0,0 @@
import React from 'react';
import { injectIntl, intlShape } from '@edx/frontend-platform/i18n';
import { useSelector } from 'react-redux';
import { Header } from '../course-header';
import { useLogistrationAlert } from '../logistration-alert';
import PageLoading from '../PageLoading';
import messages from './messages';
import LoadedTabPage from './LoadedTabPage';
function TabPage({
intl,
...passthroughProps
}) {
useLogistrationAlert();
const courseStatus = useSelector(state => state.courseware.courseStatus);
if (courseStatus === 'loading') {
return (
<>
<Header />
<PageLoading
srMessage={intl.formatMessage(messages['learn.loading'])}
/>
</>
);
}
if (courseStatus === 'loaded') {
return (
<LoadedTabPage {...passthroughProps} />
);
}
// courseStatus 'failed' and any other unexpected course status.
return (
<>
<Header />
<p className="text-center py-5 mx-auto" style={{ maxWidth: '30em' }}>
{intl.formatMessage(messages['learn.loading.failure'])}
</p>
</>
);
}
TabPage.propTypes = {
intl: intlShape.isRequired,
};
export default injectIntl(TabPage);

View File

@@ -1,2 +0,0 @@
export { default as TabContainer } from './TabContainer';
export { default as TabPage } from './TabPage';

View File

@@ -1,16 +0,0 @@
import { defineMessages } from '@edx/frontend-platform/i18n';
const messages = defineMessages({
'learn.loading': {
id: 'learn.loading',
defaultMessage: 'Loading course page...',
description: 'Message when course page is being loaded',
},
'learn.loading.failure': {
id: 'learn.loading.failure',
defaultMessage: 'There was an error loading this course.',
description: 'Message when a course page fails to load',
},
});
export default messages;

View File

@@ -7,29 +7,27 @@ import {
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { Button } from '@edx/paragon'; import { Button } from '@edx/paragon';
import { ALERT_TYPES } from './UserMessagesProvider';
function getAlertClass(type) { function getAlertClass(type) {
if (type === ALERT_TYPES.ERROR) { if (type === 'error') {
return 'alert-warning'; return 'alert-warning';
} }
if (type === ALERT_TYPES.DANGER) { if (type === 'danger') {
return 'alert-danger'; return 'alert-danger';
} }
if (type === ALERT_TYPES.SUCCESS) { if (type === 'success') {
return 'alert-success'; return 'alert-success';
} }
return 'alert-info'; return 'alert-info';
} }
function getAlertIcon(type) { function getAlertIcon(type) {
if (type === ALERT_TYPES.ERROR) { if (type === 'error') {
return faExclamationTriangle; return faExclamationTriangle;
} }
if (type === ALERT_TYPES.DANGER) { if (type === 'danger') {
return faMinusCircle; return faMinusCircle;
} }
if (type === ALERT_TYPES.SUCCESS) { if (type === 'success') {
return faCheckCircle; return faCheckCircle;
} }
return faInfoCircle; return faInfoCircle;
@@ -55,7 +53,7 @@ function Alert({
Alert.propTypes = { Alert.propTypes = {
type: PropTypes.oneOf([ALERT_TYPES.ERROR, ALERT_TYPES.DANGER, ALERT_TYPES.INFO, ALERT_TYPES.SUCCESS]).isRequired, type: PropTypes.oneOf(['error', 'danger', 'info', 'success']).isRequired,
dismissible: PropTypes.bool, dismissible: PropTypes.bool,
children: PropTypes.node, children: PropTypes.node,
onDismiss: PropTypes.func, onDismiss: PropTypes.func,

View File

@@ -4,9 +4,7 @@ import PropTypes from 'prop-types';
import UserMessagesContext from './UserMessagesContext'; import UserMessagesContext from './UserMessagesContext';
import Alert from './Alert'; import Alert from './Alert';
export default function AlertList({ export default function AlertList({ topic, className, customAlerts }) {
topic, className, customAlerts, customProps,
}) {
const { remove, messages } = useContext(UserMessagesContext); const { remove, messages } = useContext(UserMessagesContext);
const getAlertComponent = useCallback( const getAlertComponent = useCallback(
(code) => (customAlerts[code] !== undefined ? customAlerts[code] : Alert), (code) => (customAlerts[code] !== undefined ? customAlerts[code] : Alert),
@@ -28,8 +26,6 @@ export default function AlertList({
type={message.type} type={message.type}
dismissible={message.dismissible} dismissible={message.dismissible}
onDismiss={() => remove(message.id)} onDismiss={() => remove(message.id)}
rawHtml={message.rawHtml}
{...customProps}
> >
{message.text} {message.text}
</AlertComponent> </AlertComponent>
@@ -50,13 +46,10 @@ AlertList.propTypes = {
PropTypes.node, PropTypes.node,
]), ]),
), ),
// eslint-disable-next-line react/forbid-prop-types
customProps: PropTypes.object,
}; };
AlertList.defaultProps = { AlertList.defaultProps = {
topic: null, topic: null,
className: null, className: null,
customAlerts: {}, customAlerts: {},
customProps: {},
}; };

View File

@@ -1,61 +1,8 @@
import React, { useState, useRef, useEffect } from 'react'; import React, { useState, useRef } from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import UserMessagesContext from './UserMessagesContext'; import UserMessagesContext from './UserMessagesContext';
export const ALERT_TYPES = {
ERROR: 'error',
DANGER: 'danger',
SUCCESS: 'success',
INFO: 'info',
};
// NOTE: This storage key is not namespaced. That means that it's shared for the current fully
// qualified domain. Namespacing could be added by adding an optional prop to UserMessagesProvider
// to set a namespace, but we'll cross that bridge when we need it.
const FLASH_MESSAGES_LOCAL_STORAGE_KEY = 'UserMessagesProvider.flashMessages';
function getFlashMessages() {
let flashMessages = [];
try {
if (global.localStorage) {
const rawItem = global.localStorage.getItem(FLASH_MESSAGES_LOCAL_STORAGE_KEY);
if (rawItem) {
// Only try to parse and set flashMessages from the raw item if it exists.
const parsed = JSON.parse(rawItem);
if (Array.isArray(parsed)) {
flashMessages = parsed;
}
}
}
} catch (e) {
// If this fails for some reason, just return the empty array.
}
return flashMessages;
}
function addFlashMessage(message) {
try {
if (global.localStorage) {
const flashMessages = getFlashMessages();
flashMessages.push(message);
global.localStorage.setItem(FLASH_MESSAGES_LOCAL_STORAGE_KEY, JSON.stringify(flashMessages));
}
} catch (e) {
// If this fails, just bail.
}
}
function clearFlashMessages() {
try {
if (global.localStorage) {
global.localStorage.removeItem(FLASH_MESSAGES_LOCAL_STORAGE_KEY);
}
} catch (e) {
// If this fails, just bail.
}
}
export default function UserMessagesProvider({ children }) { export default function UserMessagesProvider({ children }) {
// Note: The callbacks (add, remove, clear) below interact with useState in very subtle ways. // Note: The callbacks (add, remove, clear) below interact with useState in very subtle ways.
// When we call setMessages, we always do so with the function-based form of the handler, making // When we call setMessages, we always do so with the function-based form of the handler, making
@@ -73,47 +20,28 @@ export default function UserMessagesProvider({ children }) {
// its very nature. // its very nature.
const refId = useRef(nextId); const refId = useRef(nextId);
/** const add = ({
* Flash messages are a special kind of message that appears once on page refresh. code, dismissible, text, type, topic, ...others
*/ }) => {
function addFlash(message) {
addFlashMessage(message);
}
function add(message) {
const {
code, dismissible, text, type, topic, ...others
} = message;
const id = refId.current; const id = refId.current;
setMessages(currentMessages => [...currentMessages, { setMessages(currentMessages => [...currentMessages, {
code, dismissible, text, type, topic, ...others, id, code, dismissible, text, type, topic, ...others, id,
}]); }]);
refId.current += 1; refId.current += 1;
setNextId(refId.current); setNextId(refId.current);
return refId.current;
};
return id; const remove = id => {
}
function remove(id) {
setMessages(currentMessages => currentMessages.filter(message => message.id !== id)); setMessages(currentMessages => currentMessages.filter(message => message.id !== id));
} };
function clear(topic = null) { const clear = (topic = null) => {
setMessages(currentMessages => (topic === null ? [] : currentMessages.filter(message => message.topic !== topic))); setMessages(currentMessages => (topic === null ? [] : currentMessages.filter(message => message.topic !== topic)));
} };
useEffect(() => {
const flashMessages = getFlashMessages();
flashMessages.forEach(flashMessage => add(flashMessage));
// We only allow flash messages to persist through one refresh, then we clear them out.
// If we want persistent messages, then add a 'persist' key to the messages and handle that
// as a separate local storage item.
clearFlashMessages();
}, []);
const value = { const value = {
add, add,
addFlash,
remove, remove,
clear, clear,
messages, messages,

View File

@@ -1,4 +0,0 @@
export { default as UserMessagesProvider, ALERT_TYPES } from './UserMessagesProvider';
export { default as UserMessagesContext } from './UserMessagesContext';
export { default as AlertList } from './AlertList';
export { default as Alert } from './Alert';