-
Notifications
You must be signed in to change notification settings - Fork 2
/
learnitdown_init.R
404 lines (367 loc) · 14 KB
/
learnitdown_init.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
#' Initialize learnitdown features in an R Markdown document
#'
#' This function must be called in a script run by `before_chapter_script` entry
#' in `_bookdown.yml` to create required `style.css` and `header.html` files.
#'
#' @param shiny Do we use Shiny applications and do we want to pass parameters
#' and or launch the application on a click?
#' @param h5p Do we use H5P served from a Wordpress site in the same domain as
#' our R Markdown document? The H5P integration plugin, and the H5PxAPIkatchu
#' Wordpress plugins must be installed in order to serve H5P apps and to record
#' the H5P events through the xAPI interface.
#' @param use.query Do we collect user/course/institution data through the URL
#' query string (the part after the question mark in the URL).
#' @param iframe.links If our document is displayed in an iframe, external link
#' should better target their parent window. With this option, external links
#' with no defined target are automatically retargeted when the page loads.
#' @param details.css Do we want to enhance the `<details>` section with a
#' summary surrounded by a light gray box in order to better evidence it.
#' @param baseurl The URL where the site is server from (for H5P integration),
#' it is also the base URL for the associated Wordpress server with H5P plugin.
#' Provide it **without** the trailing /!
#' @param institutions The list of possible institutions that have specific
#' sections in this document.
#' @param courses The list of courses with specific sections in this document.
#' @param style The path to the 'style.css' file.
#' @param style0 The path to a file with additional content to add to the
#' 'style.css' file.
#' @param header The path to the 'header.html' file.
#' @param header0 The path to a file with additional content to add to
#' 'header.html'.
#' @param hide.code.msg The message to display for hidden code.
#'
#' @return A list with `css` and `html` components with the content that was
#' added to respective files is returned invisibly for debugging purposes '(the
#' function is mainly used for its side effect of creating `style.css` and
#' `header.html` files for the bookdown format).
#' @export
#'
#' @examples
#' # This is better placed in a setup R chunk or an R inline expression on its
#' # own line. To see the code injected, use `cat()` at the R prompt:
#' odir <- setwd(tempdir())
#' dir.create("temp")
#' setwd("temp")
#' # Create fake style0.css and header0.html files to see what happens
#' cat("\n/* Content from style0.css */\n", file = "style0.css")
#' cat("\n<!-- Content from header0.html -->\n", file = "header0.html")
#' # Create style.css and header.html files
#' (learnitdown_init())
#' cat(readLines('style.css'), sep = "\n")
#' cat(readLines('header.html'), sep = "\n")
#' setwd("..")
#' unlink("temp")
#' setwd(odir)
#' rm(odir)
#'
learnitdown_init <- function(shiny = TRUE, h5p = TRUE, use.query = FALSE,
iframe.links = TRUE, details.css = TRUE, baseurl = "https://example.org",
institutions = c("institution1", "institution2"),
courses = c("course1", "course2", "course3"),
style = "style.css", style0 = "style0.css",
header = "header.html", header0 = "header0.html",
hide.code.msg = "See code") {
# Process style.css
# Add styles for institution/noinstitution & course/nocourse
if (!length(institutions)) institutions <- "institution" # At least one item
institutions_css <- paste(paste0(".", institutions), collapse = ", ")
institutions_array <- paste0("let institutions = [",
paste0("'", institutions, "'", collapse = ", "), ", 'noinstitution'];")
if (!length(courses)) courses <- "course" # At least one item
courses_css <- paste(paste0(".", courses), collapse = ", ")
courses_array <- paste0("let courses = [",
paste0("'", courses, "'", collapse = ", "), ", 'nocourse'];")
# Construct style and script string
res_css <- paste0("
", institutions_css , " {
display: none;
}
.noinstitution {
display: block;
}
", courses_css, " {
display: none;
}
.nocourse {
display: block;
}
")
# Add enhanced details summary (light gray box)
if (isTRUE(details.css))
res_css <- paste0(res_css, "
summary {
background: #f5f5f5;
border: 1px solid #ccc;
}
")
# Add style for grayed out Shiny app screenshot
res_css <- paste0(res_css, "
.shiny-img {
filter: brightness(80%);
}
")
# Possibly add content form style0
if (file.exists(style0))
res_css <- paste0(res_css, "\n", paste(readLines(style0), collapse = "\n"))
# Close style
#res_css <- paste0(res_css, "
#")
# Write results to style file
cat(res_css, file = style, sep = "\n")
# Process header.html
# Get parameters from either localStorage or URL and store them in variables
if (isTRUE(use.query)) {
res_header <- "<script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\\[\\]]/g, \"\\\\$&\");
var regex = new RegExp(\"[?&]\" + name + \"(=([^&#]*)|&|#|$)\"),
results = regex.exec(url);
if (!results) {
// Try to get the value from local storage
if (window.localStorage) {
return localStorage.getItem(name);
} else {
return '';
}
}
var value = '';
if (results[2]) {
value = decodeURIComponent(results[2].replace(/\\+/g, \" \"));
if (window.localStorage) {
localStorage.setItem(name, value);
}
return value;
}
}
"
} else {
res_header <- "<script>
function getParameterByName(name, url) {
name = name.replace(/[\\[\\]]/g,\"\\\\$&\");
// Try to get the value from local storage
if (window.localStorage) {
return localStorage.getItem(name);
} else {
return '';
}
}
"
}
res_header <- paste0(res_header, "
// Collect parameters and store their values (as passed by Moodle/Wordpress)
var login = getParameterByName('login');
var email = getParameterByName('email');
var displayname = getParameterByName('displayname');
var firstname = getParameterByName('firstname');
var lastname = getParameterByName('lastname');
var iemail = getParameterByName('iemail');
var iid = getParameterByName('iid');
var ifirstname = getParameterByName('ifirstname');
var ilastname = getParameterByName('ilastname');
var institution = getParameterByName('institution');
var icourse = getParameterByName('icourse');
var ictitle = getParameterByName('ictitle');
var iurl = getParameterByName('iurl');
var iref = getParameterByName('iref');
")
# Add Javascript for institution/noinstitution & course/nocourse toggle
res_header <- paste0(res_header, "
", institutions_array, "\n", courses_array, "
function toggleDisplay(item, target) {
var style = item == target ? 'block' : 'none';
var elems = document.getElementsByClassName(item);
for (i = 0; i < elems.length; i++) {
var elem = elems[i];
elem.style.display = style;
}
}
function toggleInstitution(name) {
// Disable all institutions except that one
// Since they are already all hidden, just reenable it and hide noinstitution
toggleDisplay('noinstitution', name);
toggleDisplay(name, name);
}
function toggleCourse(name) {
// Disable all courses except that one
// Since they are already all hidden, just reenable it and hide nocourse
toggleDisplay('nocourse', name);
toggleDisplay(name, name);
}
function processParameters() {
// Content related to an institution
if (institution !== null) {
toggleInstitution(institution);
}
// Content relative to a course
if (icourse !== null) {
toggleCourse(icourse);
}
// Process other parameters too here...
// ...
}
")
# Show/hide R code as details (for hidden-code class)
res_header <- paste0(res_header, "
function hideCode() {
//var codes = document.querySelectorAll('pre:not([class])');
var codes = document.getElementsByClassName('hidden-code');
var code, i, d, s, p;
for (i = 0; i < codes.length; i++) {
// We want to place the parent div into details instead
code = codes[i].parentNode;
p = code.parentNode;
d = document.createElement('details');
s = document.createElement('summary');
s.innerText = '", as.character(hide.code.msg)[1], "';
//<details><summary>hide.code.msg</summary></details>
d.appendChild(s);
// move the code into <details>
p.replaceChild(d, code);
d.appendChild(code);
}
}
")
# Possibly retarget links
if (isTRUE(iframe.links)) {
res_header <- paste0(res_header, "
function retargetLinks() {
// If displayed in an iframe, open external links into parent
// Adapted from Yihui Xie blog
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
if (/^(https?:)?\\/\\//.test(links[i].getAttribute('href')) &&
(links[i].target == null || links[i].target == '')) {
links[i].target = '_parent';
}
}
};
window.onload = function() {processParameters(); hideCode(); retargetLinks();};
")
} else {
res_header <- paste0(res_header, "
window.onload = function() {processParameters(); hideCode();};
")
}
# Handle parameters
# TODO...
# Pass URL arguments to iframe 'app' (embedded shiny apps) & 'h5p'
if (isTRUE(shiny) || isTRUE(h5p))
res_header <- paste0(res_header, "
function encodeQueryParam(name, first = false) {
var value = localStorage.getItem(name);
if (value === null || value == '') return '';
var sep = first ? '' : '&';
return sep + encodeURIComponent(name) + '=' + encodeURIComponent(value);
}
function encodeQueryString() {
// We got data from localStorage. So, if no data, no query string!
if (!window.localStorage) return('');
query = encodeQueryParam('login', true);
query += encodeQueryParam('email') + encodeQueryParam('displayname');
query += encodeQueryParam('firstname') + encodeQueryParam('lastname');
query += encodeQueryParam('iemail') + encodeQueryParam('iid');
query += encodeQueryParam('ifirstname') + encodeQueryParam('ilastname');
query += encodeQueryParam('institution');
query += encodeQueryParam('icourse') + encodeQueryParam('ictitle');
query += encodeQueryParam('iurl') + encodeQueryParam('iref');
// Detect if we have the Sepia or Night theme
// TODO: refine this because it is *always* detected
//if (document.getElementsByClassName('color-theme-1')) {
// if (query == '') {
// query = 'theme=Sepia';
// } else {
// query += '&theme=Sepia';
// }
//}
//if (document.getElementsByClassName('color-theme-22')) {
// if (query == '') {
// query = 'theme=Night';
// } else {
// query += '&theme=Night';
// }
//}
return query;
}
//var params = window.location.toString().split('?')[1];
var params = encodeQueryString();
if (params !== undefined && params != '') {
var apps = document.getElementsByClassName('app');
for (i = 0; i < apps.length; i++) {
var appitem = apps[i];
appitem.src = appitem.src + '?' + params;
}
//var h5ps = document.getElementsByClassName('h5p');
//for (i = 0; i < h5ps.length; i++) {
// var h5pitem = h5ps[i];
// h5pitem.src = h5pitem.src + '&' + params;
//}
}
")
# Launch the Shiny app on click with URL parameters + theme
if (isTRUE(shiny))
res_header <- paste0(res_header, "
launchApp = function(id, src) {
//var params = window.location.toString().split('?')[1];
var params = encodeQueryString();
if (params !== undefined && params != '') {
if (src.includes('?')) {
// There is already a search string => append parameters to it
src = src + '&' + params;
} else {
// Add a search string
src = src + '?' + params;
}
}
var img = document.getElementById('img' + id);
var app = document.getElementById(id);
app.src = src;
app.style.display='block';
img.style.display='none';
}
")
# Add Javascript code required to record H5P events
if (isTRUE(h5p))
res_header <- paste0(res_header, "
var H5PIntegration = parent.H5PIntegration;
var wpAJAXurl = '", gsub("/", "\\\\/", baseurl), "\\/wp-admin\\/admin-ajax.php';
var debugEnabled = '0';
var captureAllH5pContentTypes = '1';
var h5pContentTypes = [''];
")
# finalize this script section
res_header <- paste0(res_header, "</script>
")
# Add further code for H5P integration
if (isTRUE(h5p))
res_header <- paste0(res_header, "
<link rel='stylesheet' id='h5p-core-styles-h5p-css' href='", baseurl, "/wp-content/plugins/h5p/h5p-php-library/styles/h5p.css' media='all' />
<link rel='stylesheet' id='h5p-core-styles-h5p-confirmation-dialog-css' href='", baseurl, "/wp-content/plugins/h5p/h5p-php-library/styles/h5p-confirmation-dialog.css' media='all' />
<link rel='stylesheet' id='h5p-core-styles-h5p-core-button-css' href='", baseurl, "/wp-content/plugins/h5p/h5p-php-library/styles/h5p-core-button.css' media='all' />
<script src='", baseurl, "/wp-includes/js/wp-embed.min.js'></script>
<!--
<script src='", baseurl, "/wp-includes/js/jquery/jquery.js?ver=1.12.4-wp'></script>
<script src='", baseurl, "/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.4.1'></script>
-->
<!--
<script src='", baseurl, "/wp-content/plugins/h5pxapikatchu/js/h5pxapikatchu-variables.js'></script>
-->
<script src='", baseurl, "/wp-content/plugins/h5p/h5p-php-library/js/jquery.js'></script>
<script src='", baseurl, "/wp-content/plugins/h5p/h5p-php-library/js/h5p.js'></script>
<script src='", baseurl, "/wp-content/plugins/h5p/h5p-php-library/js/h5p-event-dispatcher.js'></script>
<script src='", baseurl, "/wp-content/plugins/h5p/h5p-php-library/js/h5p-x-api-event.js'></script>
<script src='", baseurl, "/wp-content/plugins/h5p/h5p-php-library/js/h5p-x-api.js'></script>
<script src='", baseurl, "/wp-content/plugins/h5p/h5p-php-library/js/h5p-content-type.js'></script>
<script src='", baseurl, "/wp-content/plugins/h5p/h5p-php-library/js/h5p-confirmation-dialog.js'></script>
<script src='", baseurl, "/wp-content/plugins/h5p/h5p-php-library/js/h5p-action-bar.js'></script>
<script src='", baseurl, "/wp-content/plugins/h5p/h5p-php-library/js/request-queue.js'></script>
")
# Possibly add content form header0
if (file.exists(header0))
res_header <- paste0(res_header, "\n",
paste(readLines(header0), collapse = "\n"))
# Write results to header.html file
cat(res_header, file = header, sep = "\n")
# Return invisibly a list with css and html components
invisible(list(style = res_css, html = res_header))
}