MDL-67788 core_h5p: add tracking to player
[moodle.git] / h5p / js / embed.js
CommitLineData
35b62d00
SA
1// This file is part of Moodle - http://moodle.org/
2//
3// Moodle is free software: you can redistribute it and/or modify
4// it under the terms of the GNU General Public License as published by
5// the Free Software Foundation, either version 3 of the License, or
6// (at your option) any later version.
7//
8// Moodle is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11// GNU General Public License for more details.
12//
13// You should have received a copy of the GNU General Public License
14// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
15
16/* global H5PEmbedCommunicator:true */
17/**
18 * When embedded the communicator helps talk to the parent page.
19 * This is a copy of the H5P.communicator, which we need to communicate in this context
20 *
21 * @type {H5PEmbedCommunicator}
22 * @module core_h5p
23 * @copyright 2019 Joubel AS <contact@joubel.com>
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26H5PEmbedCommunicator = (function() {
27 /**
28 * @class
29 * @private
30 */
31 function Communicator() {
32 var self = this;
33
34 // Maps actions to functions.
35 var actionHandlers = {};
36
37 // Register message listener.
38 window.addEventListener('message', function receiveMessage(event) {
39 if (window.parent !== event.source || event.data.context !== 'h5p') {
40 return; // Only handle messages from parent and in the correct context.
41 }
42
43 if (actionHandlers[event.data.action] !== undefined) {
44 actionHandlers[event.data.action](event.data);
45 }
46 }, false);
47
48 /**
49 * Register action listener.
50 *
51 * @param {string} action What you are waiting for
52 * @param {function} handler What you want done
53 */
54 self.on = function(action, handler) {
55 actionHandlers[action] = handler;
56 };
57
58 /**
59 * Send a message to the all mighty father.
60 *
61 * @param {string} action
62 * @param {Object} [data] payload
63 */
64 self.send = function(action, data) {
65 if (data === undefined) {
66 data = {};
67 }
68 data.context = 'h5p';
69 data.action = action;
70
71 // Parent origin can be anything.
72 window.parent.postMessage(data, '*');
73 };
8685c313
FR
74
75 /**
76 * Send a xAPI statement to LMS.
77 *
78 * @param {string} component
79 * @param {Object} statements
80 */
81 self.post = function(component, statements) {
82 require(['core/ajax'], function(ajax) {
83 var data = {
84 component: component,
85 requestjson: JSON.stringify(statements)
86 };
87 ajax.call([
88 {
89 methodname: 'core_xapi_statement_post',
90 args: data
91 }
92 ]);
93 });
94 };
35b62d00
SA
95 }
96
97 return (window.postMessage && window.addEventListener ? new Communicator() : undefined);
98})();
99
100document.onreadystatechange = function() {
101 // Wait for instances to be initialize.
102 if (document.readyState !== 'complete') {
103 return;
104 }
105
106 // Check for H5P iFrame.
107 var iFrame = document.querySelector('.h5p-iframe');
108 if (!iFrame || !iFrame.contentWindow) {
109 return;
110 }
111 var H5P = iFrame.contentWindow.H5P;
112
113 // Check for H5P instances.
114 if (!H5P || !H5P.instances || !H5P.instances[0]) {
115 return;
116 }
117
118 var resizeDelay;
119 var instance = H5P.instances[0];
120 var parentIsFriendly = false;
121
122 // Handle that the resizer is loaded after the iframe.
123 H5PEmbedCommunicator.on('ready', function() {
124 H5PEmbedCommunicator.send('hello');
125 });
126
127 // Handle hello message from our parent window.
128 H5PEmbedCommunicator.on('hello', function() {
129 // Initial setup/handshake is done.
130 parentIsFriendly = true;
131
132 // Hide scrollbars for correct size.
133 iFrame.contentDocument.body.style.overflow = 'hidden';
134
135 document.body.classList.add('h5p-resizing');
136
137 // Content need to be resized to fit the new iframe size.
138 H5P.trigger(instance, 'resize');
139 });
140
141 // When resize has been prepared tell parent window to resize.
142 H5PEmbedCommunicator.on('resizePrepared', function() {
143 H5PEmbedCommunicator.send('resize', {
144 scrollHeight: iFrame.contentDocument.body.scrollHeight
145 });
146 });
147
148 H5PEmbedCommunicator.on('resize', function() {
149 H5P.trigger(instance, 'resize');
150 });
151
152 H5P.on(instance, 'resize', function() {
153 if (H5P.isFullscreen) {
154 return; // Skip iframe resize.
155 }
156
157 // Use a delay to make sure iframe is resized to the correct size.
158 clearTimeout(resizeDelay);
159 resizeDelay = setTimeout(function() {
160 // Only resize if the iframe can be resized.
161 if (parentIsFriendly) {
162 H5PEmbedCommunicator.send('prepareResize',
163 {
164 scrollHeight: iFrame.contentDocument.body.scrollHeight,
165 clientHeight: iFrame.contentDocument.body.clientHeight
166 }
167 );
168 } else {
169 H5PEmbedCommunicator.send('hello');
170 }
171 }, 0);
172 });
173
8685c313
FR
174 // Get emitted xAPI data.
175 H5P.externalDispatcher.on('xAPI', function(event) {
176 var moodlecomponent = H5P.getMoodleComponent();
177 if (moodlecomponent == undefined) {
178 return;
179 }
180 // Skip malformed events.
181 var hasStatement = event && event.data && event.data.statement;
182 if (!hasStatement) {
183 return;
184 }
185
186 var statement = event.data.statement;
187 var validVerb = statement.verb && statement.verb.id;
188 if (!validVerb) {
189 return;
190 }
191
192 var isCompleted = statement.verb.id === 'http://adlnet.gov/expapi/verbs/answered'
193 || statement.verb.id === 'http://adlnet.gov/expapi/verbs/completed';
194
195 var isChild = statement.context && statement.context.contextActivities &&
196 statement.context.contextActivities.parent &&
197 statement.context.contextActivities.parent[0] &&
198 statement.context.contextActivities.parent[0].id;
199
200 if (isCompleted && !isChild) {
201 var statements = H5P.getXAPIStatements(this.contentId, statement);
202 H5PEmbedCommunicator.post(moodlecomponent, statements);
203 }
204 });
205
35b62d00
SA
206 // Trigger initial resize for instance.
207 H5P.trigger(instance, 'resize');
208};