Skip to content

Commit

Permalink
fix: send XBlock visibility status to the LMS
Browse files Browse the repository at this point in the history
  • Loading branch information
Agrendalath committed Sep 16, 2024
1 parent 8b6e1b0 commit 2815e3d
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
"core-js": "3.22.2",
"history": "5.3.0",
"js-cookie": "3.0.1",
"lodash": "^4.17.21",
"lodash.camelcase": "4.3.0",
"prop-types": "15.8.1",
"query-string": "7.1.3",
Expand Down
27 changes: 27 additions & 0 deletions src/courseware/course/sequence/Unit.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import React, {
Suspense, useCallback, useContext, useEffect, useLayoutEffect, useState,
} from 'react';
import { useDispatch } from 'react-redux';
import { throttle } from 'lodash';
import { processEvent } from '../../../course-home/data/thunks';
import { useEventListener } from '../../../generic/hooks';
import { useModel } from '../../../generic/model-store';
Expand Down Expand Up @@ -113,6 +114,25 @@ const Unit = ({
}
}, [userNeedsIntegritySignature]);

// Send visibility status to the iframe. It's used to mark XBlocks as viewed.
const updateIframeVisibility = () => {
const iframeElement = document.getElementById('unit-iframe');
if (iframeElement) {
const rect = iframeElement.getBoundingClientRect();
const visibleInfo = {
type: 'unit.visibilityStatus',
data: {
topPosition: rect.top,
viewportHeight: window.innerHeight,
},
};
iframeElement.contentWindow.postMessage(visibleInfo, `${getConfig().LMS_BASE_URL}`);
}
};

// Throttle the update function to prevent it from sending too many messages to the iframe.
const throttledUpdateVisibility = throttle(updateIframeVisibility, 100);

const receiveMessage = useCallback(({ data }) => {
const {
type,
Expand Down Expand Up @@ -233,6 +253,13 @@ const Unit = ({
dispatch(processEvent(e.data, fetchCourse));
}
};

// Update the visibility of the iframe in case the element is already visible.
updateIframeVisibility();

// Add event listeners to update the visibility of the iframe when the window is scrolled or resized.
window.addEventListener('scroll', throttledUpdateVisibility);
window.addEventListener('resize', throttledUpdateVisibility);
}}
/>
</div>
Expand Down

0 comments on commit 2815e3d

Please sign in to comment.