71 lines
1.6 KiB
TypeScript
71 lines
1.6 KiB
TypeScript
'use client'
|
|
|
|
import { useEffect, useRef, useState } from 'react'
|
|
import { Scorm2004API } from 'scorm-again/scorm2004'
|
|
import { settings, type ScormPlayerProps } from './scorm-player'
|
|
|
|
export function Scorm2004Player({
|
|
scormState,
|
|
scormContentPath,
|
|
className,
|
|
onCommit,
|
|
setValue
|
|
}: ScormPlayerProps) {
|
|
const [iframeLoaded, setIframeLoaded] = useState(false)
|
|
const scormApiRef = useRef<Scorm2004API | null>(null)
|
|
|
|
useEffect(() => {
|
|
const scormApi = new Scorm2004API(settings)
|
|
scormApi.loadFromFlattenedJSON(scormState)
|
|
|
|
scormApi.on('LMSCommit', function () {
|
|
onCommit?.(scormApi.renderCommitCMI(true))
|
|
})
|
|
|
|
scormApi.on('LMSSetValue.*', function (element: any, value: any) {
|
|
setValue?.(element, value)
|
|
})
|
|
|
|
scormApiRef.current = scormApi
|
|
window.API_1484_11 = scormApi
|
|
setIframeLoaded(true)
|
|
|
|
return () => {
|
|
scormApiRef.current = null
|
|
}
|
|
}, [])
|
|
|
|
useEffect(() => {
|
|
if (!scormApiRef.current) {
|
|
return
|
|
}
|
|
|
|
const scormApi = scormApiRef.current
|
|
let unloaded = false
|
|
|
|
function unload() {
|
|
if (unloaded || scormApi.isTerminated()) {
|
|
return false
|
|
}
|
|
|
|
scormApi.SetValue('cmi.exit', 'suspend')
|
|
scormApi.Commit()
|
|
scormApi.Terminate()
|
|
|
|
unloaded = true
|
|
}
|
|
|
|
window.addEventListener('beforeunload', unload)
|
|
window.addEventListener('unload', unload)
|
|
|
|
return () => {
|
|
window.removeEventListener('beforeunload', unload)
|
|
window.removeEventListener('unload', unload)
|
|
}
|
|
}, [])
|
|
|
|
if (iframeLoaded) {
|
|
return <iframe src={`/proxy/${scormContentPath}`} className={className} />
|
|
}
|
|
}
|