-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.html
1485 lines (1248 loc) · 51.7 KB
/
test.html
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head>
<meta charset="utf-8">
<meta name="generator" content="quarto-1.3.450">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<title>Test for YESCDS2</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
div.columns{display: flex; gap: min(4vw, 1.5em);}
div.column{flex: auto; overflow-x: auto;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
ul.task-list li input[type="checkbox"] {
width: 0.8em;
margin: 0 0.8em 0.2em -1em; /* quarto-specific, see https://github.com/quarto-dev/quarto-cli/issues/4556 */
vertical-align: middle;
}
</style>
<script src="test_files/libs/clipboard/clipboard.min.js"></script>
<script src="test_files/libs/quarto-html/quarto.js"></script>
<script src="test_files/libs/quarto-html/popper.min.js"></script>
<script src="test_files/libs/quarto-html/tippy.umd.min.js"></script>
<script src="test_files/libs/quarto-html/anchor.min.js"></script>
<link href="test_files/libs/quarto-html/tippy.css" rel="stylesheet">
<link href="test_files/libs/quarto-html/quarto-syntax-highlighting.css" rel="stylesheet" id="quarto-text-highlighting-styles">
<script src="test_files/libs/bootstrap/bootstrap.min.js"></script>
<link href="test_files/libs/bootstrap/bootstrap-icons.css" rel="stylesheet">
<link href="test_files/libs/bootstrap/bootstrap.min.css" rel="stylesheet" id="quarto-bootstrap" data-mode="light">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/min/vs/editor/editor.main.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<style type="text/css">
.monaco-editor pre {
background-color: unset !important;
}
.qwebr-editor-toolbar {
width: 100%;
display: flex;
justify-content: space-between;
box-sizing: border-box;
}
.qwebr-editor-toolbar-left-buttons, .qwebr-editor-toolbar-right-buttons {
display: flex;
}
.qwebr-non-interactive-loading-container.qwebr-cell-needs-evaluation, .qwebr-non-interactive-loading-container.qwebr-cell-evaluated {
justify-content: center;
display: flex;
background-color: rgba(250, 250, 250, 0.65);
border: 1px solid rgba(233, 236, 239, 0.65);
border-radius: 0.5rem;
margin-top: 15px;
margin-bottom: 15px;
}
.qwebr-r-project-logo {
color: #2767B0; /* R Project's blue color */
}
.qwebr-icon-status-spinner {
color: #7894c4;
}
.qwebr-icon-run-code {
color: #0d9c29
}
.qwebr-output-code-stdout {
color: #111;
}
.qwebr-output-code-stderr {
color: #db4133;
}
.qwebr-editor {
border: 1px solid #EEEEEE;
}
.qwebr-editor-toolbar {
background-color: #EEEEEE;
padding: 0.2rem 0.5rem;
}
.qwebr-button {
background-color: #EEEEEE;
display: inline-block;
font-weight: 400;
line-height: 1;
text-decoration: none;
text-align: center;
color: #000;
border-color: #dee2e6;
border: 1px solid rgba(0,0,0,0);
padding: 0.375rem 0.75rem;
font-size: .9rem;
border-radius: 0.25rem;
transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
.qwebr-button:hover {
color: #000;
background-color: #d9dce0;
border-color: #c8ccd0;
}
.qwebr-button:disabled,.qwebr-button.disabled,fieldset:disabled .qwebr-button {
pointer-events: none;
opacity: .65
}
.qwebr-button-reset {
color: #696969; /*#4682b4;*/
}
.qwebr-button-copy {
color: #696969;
}
/* Custom styling for RevealJS Presentations*/
/* Reset the style of the interactive area */
.reveal div.qwebr-interactive-area {
display: block;
box-shadow: none;
max-width: 100%;
max-height: 100%;
margin: 0;
padding: 0;
}
/* Provide space to entries */
.reveal div.qwebr-output-code-area pre div {
margin: 1px 2px 1px 10px;
}
/* Collapse the inside code tags to avoid extra space between line outputs */
.reveal pre div code.qwebr-output-code-stdout, .reveal pre div code.qwebr-output-code-stderr {
padding: 0;
display: contents;
}
.reveal pre div code.qwebr-output-code-stdout {
color: #111;
}
.reveal pre div code.qwebr-output-code-stderr {
color: #db4133;
}
/* Create a border around console and output (does not effect graphs) */
.reveal div.qwebr-console-area {
border: 1px solid #EEEEEE;
box-shadow: 2px 2px 10px #EEEEEE;
}
/* Cap output height and allow text to scroll */
/* TODO: Is there a better way to fit contents/max it parallel to the monaco editor size? */
.reveal div.qwebr-output-code-area pre {
max-height: 400px;
overflow: scroll;
}
</style>
<script type="module">
// Document level settings ----
// Determine if we need to install R packages
globalThis.qwebrInstallRPackagesList = ['ggplot2', 'parody', 'DT'];
// Specify possible locations to search for the repository
globalThis.qwebrPackageRepoURLS = ['https://repo.r-wasm.org', 'https://webr.bioconductor.org', 'https://repo.r-wasm.org/'];
// Check to see if we have an empty array, if we do set to skip the installation.
globalThis.qwebrSetupRPackages = !(qwebrInstallRPackagesList.indexOf("") !== -1);
globalThis.qwebrAutoloadRPackages = true;
// Display a startup message?
globalThis.qwebrShowStartupMessage = true;
globalThis.qwebrShowHeaderMessage = false;
// Describe the webR settings that should be used
globalThis.qwebrCustomizedWebROptions = {
"baseURL": "https://webr.r-wasm.org/v0.2.2/",
"serviceWorkerUrl": "",
"homedir": "/home/web_user",
"channelType": "ChannelType.Automatic"
};
// Store cell data
globalThis.qwebrCellDetails = [{"id":1,"code":"seer_2018 = read.csv(\"https://raw.githubusercontent.com/vjcitn/YESCDS/main/SEER_2018.csv\")\neso = seer_2018[seer_2018$CancerSite==\"Breast\" & seer_2018$Sex ==\"Female\",]\nplot(eso$Year, eso$rate.2.2018, col=factor(eso$Race))\nlegend(2010,12,col=1:3,legend=c(\"all\", \"black\", \"white\"),pch=1)\ntable(eso$Race)","options":{"message":"true","output":"true","comment":"","read-only":"false","autorun":"false","context":"interactive","classes":"","label":"unnamed-chunk-1","fig-width":7,"dpi":72,"out-width":"700px","out-height":"","results":"markup","warning":"true","fig-height":5,"fig-cap":""}}];
</script>
<script type="module">
// Declare startupMessageQWebR globally
globalThis.qwebrStartupMessage = document.createElement("p");
// Function to set the button text
globalThis.qwebrSetInteractiveButtonState = function(buttonText, enableCodeButton = true) {
document.querySelectorAll(".qwebr-button-run").forEach((btn) => {
btn.innerHTML = buttonText;
btn.disabled = !enableCodeButton;
});
}
// Function to update the status message in non-interactive cells
globalThis.qwebrUpdateStatusMessage = function(message) {
document.querySelectorAll(".qwebr-status-text.qwebr-cell-needs-evaluation").forEach((elem) => {
elem.innerText = message;
});
}
// Function to update the status message
globalThis.qwebrUpdateStatusHeader = function(message) {
qwebrStartupMessage.innerHTML = `
<i class="fa-solid fa-spinner fa-spin qwebr-icon-status-spinner"></i>
<span>${message}</span>`;
}
// Function that attaches the document status message and diagnostics
function displayStartupMessage(showStartupMessage, showHeaderMessage) {
if (!showStartupMessage) {
return;
}
// Get references to header elements
const headerHTML = document.getElementById("title-block-header");
const headerRevealJS = document.getElementById("title-slide");
// Create the outermost div element for metadata
const quartoTitleMeta = document.createElement("div");
quartoTitleMeta.classList.add("quarto-title-meta");
// Create the first inner div element
const firstInnerDiv = document.createElement("div");
firstInnerDiv.setAttribute("id", "qwebr-status-message-area");
// Create the second inner div element for "WebR Status" heading and contents
const secondInnerDiv = document.createElement("div");
secondInnerDiv.setAttribute("id", "qwebr-status-message-title");
secondInnerDiv.classList.add("quarto-title-meta-heading");
secondInnerDiv.innerText = "WebR Status";
// Create another inner div for contents
const secondInnerDivContents = document.createElement("div");
secondInnerDivContents.setAttribute("id", "qwebr-status-message-body");
secondInnerDivContents.classList.add("quarto-title-meta-contents");
// Describe the WebR state
qwebrStartupMessage.innerText = "🟡 Loading...";
qwebrStartupMessage.setAttribute("id", "qwebr-status-message-text");
// Add `aria-live` to auto-announce the startup status to screen readers
qwebrStartupMessage.setAttribute("aria-live", "assertive");
// Append the startup message to the contents
secondInnerDivContents.appendChild(qwebrStartupMessage);
// Add a status indicator for COOP and COEP Headers if needed
if (showHeaderMessage) {
const crossOriginMessage = document.createElement("p");
crossOriginMessage.innerText = `${crossOriginIsolated ? '🟢' : '🟡'} COOP & COEP Headers`;
crossOriginMessage.setAttribute("id", "qwebr-coop-coep-header");
secondInnerDivContents.appendChild(crossOriginMessage);
}
// Combine the inner divs and contents
firstInnerDiv.appendChild(secondInnerDiv);
firstInnerDiv.appendChild(secondInnerDivContents);
quartoTitleMeta.appendChild(firstInnerDiv);
// Determine where to insert the quartoTitleMeta element
if (headerHTML || headerRevealJS) {
// Append to the existing "title-block-header" element or "title-slide" div
(headerHTML || headerRevealJS).appendChild(quartoTitleMeta);
} else {
// If neither headerHTML nor headerRevealJS is found, insert after "webr-monaco-editor-init" script
const monacoScript = document.getElementById("qwebr-monaco-editor-init");
const header = document.createElement("header");
header.setAttribute("id", "title-block-header");
header.appendChild(quartoTitleMeta);
monacoScript.after(header);
}
}
displayStartupMessage(qwebrShowStartupMessage, qwebrShowHeaderMessage);
</script>
<script type="module">
// Supported Evaluation Types for Context
globalThis.EvalTypes = Object.freeze({
Interactive: 'interactive',
Setup: 'setup',
Output: 'output',
});
// Function that dispatches the creation request
globalThis.qwebrCreateHTMLElement = function (
cellData
) {
// Extract key components
const evalType = cellData.options.context;
const qwebrCounter = cellData.id;
// We make an assumption that insertion points are defined by the Lua filter as:
// qwebr-insertion-location-{qwebrCounter}
const elementLocator = document.getElementById(`qwebr-insertion-location-${qwebrCounter}`);
// Figure out the routine to use to insert the element.
let qwebrElement;
switch ( evalType ) {
case EvalTypes.Interactive:
qwebrElement = qwebrCreateInteractiveElement(qwebrCounter, cellData.options);
break;
case EvalTypes.Output:
qwebrElement = qwebrCreateNonInteractiveOutputElement(qwebrCounter, cellData.options);
break;
case EvalTypes.Setup:
qwebrElement = qwebrCreateNonInteractiveSetupElement(qwebrCounter, cellData.options);
break;
default:
qwebrElement = document.createElement('div');
qwebrElement.textContent = 'Error creating `quarto-webr` element';
}
// Insert the dynamically generated object at the document location.
elementLocator.appendChild(qwebrElement);
};
// Function that setups the interactive element creation
globalThis.qwebrCreateInteractiveElement = function (qwebrCounter, qwebrOptions) {
// Create main div element
var mainDiv = document.createElement('div');
mainDiv.id = 'qwebr-interactive-area-' + qwebrCounter;
mainDiv.className = `qwebr-interactive-area`;
if (qwebrOptions.classes) {
mainDiv.className += " " + qwebrOptions.classes
}
// Add a unique cell identifier that users can customize
if (qwebrOptions.label) {
mainDiv.setAttribute('data-id', qwebrOptions.label);
}
// Create toolbar div
var toolbarDiv = document.createElement('div');
toolbarDiv.className = 'qwebr-editor-toolbar';
toolbarDiv.id = 'qwebr-editor-toolbar-' + qwebrCounter;
// Create a div to hold the left buttons
var leftButtonsDiv = document.createElement('div');
leftButtonsDiv.className = 'qwebr-editor-toolbar-left-buttons';
// Create a div to hold the right buttons
var rightButtonsDiv = document.createElement('div');
rightButtonsDiv.className = 'qwebr-editor-toolbar-right-buttons';
// Create Run Code button
var runCodeButton = document.createElement('button');
runCodeButton.className = 'btn btn-default qwebr-button qwebr-button-run';
runCodeButton.disabled = true;
runCodeButton.type = 'button';
runCodeButton.id = 'qwebr-button-run-' + qwebrCounter;
runCodeButton.textContent = '🟡 Loading webR...';
runCodeButton.title = `Run code (Shift + Enter)`;
// Append buttons to the leftButtonsDiv
leftButtonsDiv.appendChild(runCodeButton);
// Create Reset button
var resetButton = document.createElement('button');
resetButton.className = 'btn btn-light btn-xs qwebr-button qwebr-button-reset';
resetButton.type = 'button';
resetButton.id = 'qwebr-button-reset-' + qwebrCounter;
resetButton.title = 'Start over';
resetButton.innerHTML = '<i class="fa-solid fa-arrows-rotate"></i>';
// Create Copy button
var copyButton = document.createElement('button');
copyButton.className = 'btn btn-light btn-xs qwebr-button qwebr-button-copy';
copyButton.type = 'button';
copyButton.id = 'qwebr-button-copy-' + qwebrCounter;
copyButton.title = 'Copy code';
copyButton.innerHTML = '<i class="fa-regular fa-copy"></i>';
// Append buttons to the rightButtonsDiv
rightButtonsDiv.appendChild(resetButton);
rightButtonsDiv.appendChild(copyButton);
// Create console area div
var consoleAreaDiv = document.createElement('div');
consoleAreaDiv.id = 'qwebr-console-area-' + qwebrCounter;
consoleAreaDiv.className = 'qwebr-console-area';
// Create editor div
var editorDiv = document.createElement('div');
editorDiv.id = 'qwebr-editor-' + qwebrCounter;
editorDiv.className = 'qwebr-editor';
// Create output code area div
var outputCodeAreaDiv = document.createElement('div');
outputCodeAreaDiv.id = 'qwebr-output-code-area-' + qwebrCounter;
outputCodeAreaDiv.className = 'qwebr-output-code-area';
outputCodeAreaDiv.setAttribute('aria-live', 'assertive');
// Create pre element inside output code area
var preElement = document.createElement('pre');
preElement.style.visibility = 'hidden';
outputCodeAreaDiv.appendChild(preElement);
// Create output graph area div
var outputGraphAreaDiv = document.createElement('div');
outputGraphAreaDiv.id = 'qwebr-output-graph-area-' + qwebrCounter;
outputGraphAreaDiv.className = 'qwebr-output-graph-area';
// Append buttons to the toolbar
toolbarDiv.appendChild(leftButtonsDiv);
toolbarDiv.appendChild(rightButtonsDiv);
// Append all elements to the main div
mainDiv.appendChild(toolbarDiv);
consoleAreaDiv.appendChild(editorDiv);
consoleAreaDiv.appendChild(outputCodeAreaDiv);
mainDiv.appendChild(consoleAreaDiv);
mainDiv.appendChild(outputGraphAreaDiv);
return mainDiv;
}
// Function that adds output structure for non-interactive output
globalThis.qwebrCreateNonInteractiveOutputElement = function(qwebrCounter, qwebrOptions) {
// Create main div element
var mainDiv = document.createElement('div');
mainDiv.id = 'qwebr-noninteractive-area-' + qwebrCounter;
mainDiv.className = `qwebr-noninteractive-area`;
if (qwebrOptions.classes) {
mainDiv.className += " " + qwebrOptions.classes
}
// Add a unique cell identifier that users can customize
if (qwebrOptions.label) {
mainDiv.setAttribute('data-id', qwebrOptions.label);
}
// Create a status container div
var statusContainer = createLoadingContainer(qwebrCounter);
// Create output code area div
var outputCodeAreaDiv = document.createElement('div');
outputCodeAreaDiv.id = 'qwebr-output-code-area-' + qwebrCounter;
outputCodeAreaDiv.className = 'qwebr-output-code-area';
outputCodeAreaDiv.setAttribute('aria-live', 'assertive');
// Create pre element inside output code area
var preElement = document.createElement('pre');
preElement.style.visibility = 'hidden';
outputCodeAreaDiv.appendChild(preElement);
// Create output graph area div
var outputGraphAreaDiv = document.createElement('div');
outputGraphAreaDiv.id = 'qwebr-output-graph-area-' + qwebrCounter;
outputGraphAreaDiv.className = 'qwebr-output-graph-area';
// Append all elements to the main div
mainDiv.appendChild(statusContainer);
mainDiv.appendChild(outputCodeAreaDiv);
mainDiv.appendChild(outputGraphAreaDiv);
return mainDiv;
};
// Function that adds a stub in the page to indicate a setup cell was used.
globalThis.qwebrCreateNonInteractiveSetupElement = function(qwebrCounter, qwebrOptions) {
// Create main div element
var mainDiv = document.createElement('div');
mainDiv.id = `qwebr-noninteractive-setup-area-${qwebrCounter}`;
mainDiv.className = `qwebr-noninteractive-setup-area`;
if (qwebrOptions.classes) {
mainDiv.className += " " + qwebrOptions.classes
}
// Add a unique cell identifier that users can customize
if (qwebrOptions.label) {
mainDiv.setAttribute('data-id', qwebrOptions.label);
}
// Create a status container div
var statusContainer = createLoadingContainer(qwebrCounter);
// Append status onto the main div
mainDiv.appendChild(statusContainer);
return mainDiv;
}
// Function to create loading container with specified ID
globalThis.createLoadingContainer = function(qwebrCounter) {
// Create a status container
const container = document.createElement('div');
container.id = `qwebr-non-interactive-loading-container-${qwebrCounter}`;
container.className = 'qwebr-non-interactive-loading-container qwebr-cell-needs-evaluation';
// Create an R project logo to indicate its a code space
const rProjectIcon = document.createElement('i');
rProjectIcon.className = 'fa-brands fa-r-project fa-3x qwebr-r-project-logo';
// Setup a loading icon from font awesome
const spinnerIcon = document.createElement('i');
spinnerIcon.className = 'fa-solid fa-spinner fa-spin fa-1x qwebr-icon-status-spinner';
// Add a section for status text
const statusText = document.createElement('p');
statusText.id = `qwebr-status-text-${qwebrCounter}`;
statusText.className = `qwebr-status-text qwebr-cell-needs-evaluation`;
statusText.innerText = 'Loading webR...';
// Incorporate an inner container
const innerContainer = document.createElement('div');
// Append elements to the inner container
innerContainer.appendChild(spinnerIcon);
innerContainer.appendChild(statusText);
// Append elements to the main container
container.appendChild(rProjectIcon);
container.appendChild(innerContainer);
return container;
}
</script>
<script type="module">
// Function to install a single package
async function qwebrInstallRPackage(packageName) {
await mainWebR.evalRVoid(`webr::install('${packageName}');`);
}
// Function to load a single package
async function qwebrLoadRPackage(packageName) {
await mainWebR.evalRVoid(`require('${packageName}', quietly = TRUE)`);
}
// Generic function to process R packages
async function qwebrProcessRPackagesWithStatus(packages, processType, displayStatusMessageUpdate = true) {
// Switch between contexts
const messagePrefix = processType === 'install' ? 'Installing' : 'Loading';
// Modify button state
qwebrSetInteractiveButtonState(`🟡 ${messagePrefix} package ...`, false);
// Iterate over packages
for (let i = 0; i < packages.length; i++) {
const activePackage = packages[i];
const formattedMessage = `${messagePrefix} package ${i + 1} out of ${packages.length}: ${activePackage}`;
// Display the update in header
if (displayStatusMessageUpdate) {
qwebrUpdateStatusHeader(formattedMessage);
}
// Display the update in non-active areas
qwebrUpdateStatusMessage(formattedMessage);
// Run package installation
if (processType === 'install') {
await qwebrInstallRPackage(activePackage);
} else {
await qwebrLoadRPackage(activePackage);
}
}
// Clean slate
if (processType === 'load') {
await mainWebR.flush();
}
}
// Start a timer
const initializeWebRTimerStart = performance.now();
// Encase with a dynamic import statement
globalThis.qwebrInstance = import(qwebrCustomizedWebROptions.baseURL + "webr.mjs").then(
async ({ WebR, ChannelType }) => {
// Populate WebR options with defaults or new values based on `webr` meta
globalThis.mainWebR = new WebR(qwebrCustomizedWebROptions);
// Initialization WebR
await mainWebR.init();
// Setup a shelter
globalThis.mainWebRCodeShelter = await new mainWebR.Shelter();
// Setup a pager to allow processing help documentation
await mainWebR.evalRVoid('webr::pager_install()');
// Override the existing install.packages() to use webr::install()
await mainWebR.evalRVoid('webr::shim_install()');
// Specify the repositories to pull from
// Note: webR does not use the `repos` option, but instead uses `webr_pkg_repos`
// inside of `install()`. However, other R functions still pull from `repos`.
await mainWebR.evalRVoid(`
options(
webr_pkg_repos = c(${qwebrPackageRepoURLS.map(repoURL => `'${repoURL}'`).join(',')}),
repos = c(${qwebrPackageRepoURLS.map(repoURL => `'${repoURL}'`).join(',')})
)
`);
// Check to see if any packages need to be installed
if (qwebrSetupRPackages) {
// Obtain only a unique list of packages
const uniqueRPackageList = Array.from(new Set(qwebrInstallRPackagesList));
// Install R packages one at a time (either silently or with a status update)
await qwebrProcessRPackagesWithStatus(uniqueRPackageList, 'install', qwebrShowStartupMessage);
if (qwebrAutoloadRPackages) {
// Load R packages one at a time (either silently or with a status update)
await qwebrProcessRPackagesWithStatus(uniqueRPackageList, 'load', qwebrShowStartupMessage);
}
}
}
);
// Stop timer
const initializeWebRTimerEnd = performance.now();
</script>
<script type="module">
// Function to verify a given JavaScript Object is empty
globalThis.qwebrIsObjectEmpty = function (arr) {
return Object.keys(arr).length === 0;
}
// Global version of the Escape HTML function that converts HTML
// characters to their HTML entities.
globalThis.qwebrEscapeHTMLCharacters = function(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
};
// Passthrough results
globalThis.qwebrIdentity = function(x) {
return x;
};
// Append a comment
globalThis.qwebrPrefixComment = function(x, comment) {
return `${comment}${x}`;
};
// Function to parse the pager results
globalThis.qwebrParseTypePager = async function (msg) {
// Split out the event data
const { path, title, deleteFile } = msg.data;
// Process the pager data by reading the information from disk
const paged_data = await mainWebR.FS.readFile(path).then((data) => {
// Obtain the file content
let content = new TextDecoder().decode(data);
// Remove excessive backspace characters until none remain
while(content.match(/.[\b]/)){
content = content.replace(/.[\b]/g, '');
}
// Returned cleaned data
return content;
});
// Unlink file if needed
if (deleteFile) {
await mainWebR.FS.unlink(path);
}
// Return extracted data with spaces
return paged_data;
}
// Function to run the code using webR and parse the output
globalThis.qwebrComputeEngine = async function(
codeToRun,
elements,
options) {
// Call into the R compute engine that persists within the document scope.
// To be prepared for all scenarios, the following happens:
// 1. We setup a canvas device to write to by making a namespace call into the {webr} package
// 2. We use values inside of the options array to set the figure size.
// 3. We capture the output stream information (STDOUT and STERR)
// 4. While parsing the results, we disable image creation.
// Create a canvas variable for graphics
let canvas = undefined;
// Create a pager variable for help/file contents
let pager = [];
// Handle how output is processed
let showMarkup = options.results === "markup" && options.output !== "asis";
let processOutput;
if (showMarkup) {
processOutput = qwebrEscapeHTMLCharacters;
} else {
processOutput = qwebrIdentity;
}
// ----
// Convert from Inches to Pixels by using DPI (dots per inch)
// for bitmap devices (dpi * inches = pixels)
let fig_width = options["fig-width"] * options["dpi"]
let fig_height = options["fig-height"] * options["dpi"]
// Initialize webR
await mainWebR.init();
// Setup a webR canvas by making a namespace call into the {webr} package
await mainWebR.evalRVoid(`webr::canvas(width=${fig_width}, height=${fig_height})`);
const result = await mainWebRCodeShelter.captureR(codeToRun, {
withAutoprint: true,
captureStreams: true,
captureConditions: false//,
// env: webR.objs.emptyEnv, // maintain a global environment for webR v0.2.0
});
// -----
// Start attempting to parse the result data
processResultOutput:try {
// Stop creating images
await mainWebR.evalRVoid("dev.off()");
// Avoid running through output processing
if (options.results === "hide" || options.output === "false") {
break processResultOutput;
}
// Merge output streams of STDOUT and STDErr (messages and errors are combined.)
// Require both `warning` and `message` to be true to display `STDErr`.
const out = result.output
.filter(
evt => evt.type === "stdout" ||
( evt.type === "stderr" && (options.warning === "true" && options.message === "true"))
)
.map((evt, index) => {
const className = `qwebr-output-code-${evt.type}`;
const outputResult = qwebrPrefixComment(processOutput(evt.data), options.comment);
return `<code id="${className}-editor-${elements.id}-result-${index + 1}" class="${className}">${outputResult}</code>`;
})
.join("\n");
// Clean the state
// We're now able to process both graphics and pager events.
// As a result, we cannot maintain a true 1-to-1 output order
// without individually feeding each line
const msgs = await mainWebR.flush();
// Output each image event stored
msgs.forEach((msg) => {
// Determine if old canvas can be used or a new canvas is required.
if (msg.type === 'canvas'){
// Add image to the current canvas
if (msg.data.event === 'canvasImage') {
canvas.getContext('2d').drawImage(msg.data.image, 0, 0);
} else if (msg.data.event === 'canvasNewPage') {
// Generate a new canvas element
canvas = document.createElement("canvas");
canvas.setAttribute("width", 2 * fig_width);
canvas.setAttribute("height", 2 * fig_height);
canvas.style.width = options["out-width"] ? options["out-width"] : `${fig_width}px`;
if (options["out-height"]) {
canvas.style.height = options["out-height"];
}
canvas.style.display = "block";
canvas.style.margin = "auto";
}
}
});
// Use `map` to process the filtered "pager" events asynchronously
const pager = await Promise.all(
msgs.filter(msg => msg.type === 'pager').map(
async (msg) => {
return await qwebrParseTypePager(msg);
}
)
);
// Nullify the output area of content
elements.outputCodeDiv.innerHTML = "";
elements.outputGraphDiv.innerHTML = "";
// Design an output object for messages
const pre = document.createElement("pre");
if (/\S/.test(out)) {
// Display results as HTML elements to retain output styling
const div = document.createElement("div");
div.innerHTML = out;
pre.appendChild(div);
} else {
// If nothing is present, hide the element.
pre.style.visibility = "hidden";
}
elements.outputCodeDiv.appendChild(pre);
// Place the graphics on the canvas
if (canvas) {
// Create figure element
const figureElement = document.createElement('figure');
// Append canvas to figure
figureElement.appendChild(canvas);
if (options['fig-cap']) {
// Create figcaption element
const figcaptionElement = document.createElement('figcaption');
figcaptionElement.innerText = options['fig-cap'];
// Append figcaption to figure
figureElement.appendChild(figcaptionElement);
}
elements.outputGraphDiv.appendChild(figureElement);
}
// Display the pager data
if (pager) {
// Use the `pre` element to preserve whitespace.
pager.forEach((paged_data, index) => {
let pre_pager = document.createElement("pre");
pre_pager.innerText = paged_data;
pre_pager.classList.add("qwebr-output-code-pager");
pre_pager.setAttribute("id", `qwebr-output-code-pager-editor-${elements.id}-result-${index + 1}`);
elements.outputCodeDiv.appendChild(pre_pager);
});
}
} finally {
// Clean up the remaining code
mainWebRCodeShelter.purge();
}
}
// Function to execute the code (accepts code as an argument)
globalThis.qwebrExecuteCode = async function (
codeToRun,
id,
options = {}) {
// If options are not passed, we fall back on the bare minimum to handle the computation
if (qwebrIsObjectEmpty(options)) {
options = {
"context": "interactive",
"fig-width": 7, "fig-height": 5,
"out-width": "700px", "out-height": "",
"dpi": 72,
"results": "markup",
"warning": "true", "message": "true",
};
}
// Next, we access the compute areas values
const elements = {
runButton: document.getElementById(`qwebr-button-run-${id}`),
outputCodeDiv: document.getElementById(`qwebr-output-code-area-${id}`),
outputGraphDiv: document.getElementById(`qwebr-output-graph-area-${id}`),
id: id,
}
// Disallowing execution of other code cells
document.querySelectorAll(".qwebr-button-run").forEach((btn) => {
btn.disabled = true;
});
if (options.context == EvalTypes.Interactive) {
// Emphasize the active code cell
elements.runButton.innerHTML = '<i class="fa-solid fa-spinner fa-spin qwebr-icon-status-spinner"></i> <span>Run Code</span>';
}
// Evaluate the code and parse the output into the document
await qwebrComputeEngine(codeToRun, elements, options);
// Switch to allowing execution of code
document.querySelectorAll(".qwebr-button-run").forEach((btn) => {
btn.disabled = false;
});
if (options.context == EvalTypes.Interactive) {
// Revert to the initial code cell state
elements.runButton.innerHTML = '<i class="fa-solid fa-play qwebr-icon-run-code"></i> <span>Run Code</span>';
}
}
</script>
</head>
<body>
<div id="quarto-content" class="page-columns page-rows-contents page-layout-article">
<div id="quarto-margin-sidebar" class="sidebar margin-sidebar">
<nav id="TOC" role="doc-toc" class="toc-active" data-toc-expanded="3">
<h2 id="toc-title">Sections</h2>
<ul>
<li><a href="#a-view-of-breast-cancer-incidence-as-recorded-in-seer" id="toc-a-view-of-breast-cancer-incidence-as-recorded-in-seer" class="nav-link active" data-scroll-target="#a-view-of-breast-cancer-incidence-as-recorded-in-seer">A view of breast cancer incidence as recorded in SEER</a></li>
</ul>
</nav>
</div>
<main class="content" id="quarto-document-content">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/min/vs/loader.js"></script>
<script type="module" id="qwebr-monaco-editor-init">
// Configure the Monaco Editor's loader
require.config({
paths: {
'vs': 'https://cdn.jsdelivr.net/npm/[email protected]/min/vs'
}
});
</script>
<script type="module">
// Global dictionary to store Monaco Editor instances
globalThis.qwebrEditorInstances = {};
// Function that builds and registers a Monaco Editor instance
globalThis.qwebrCreateMonacoEditorInstance = function (cellData) {
const initialCode = cellData.code;
const qwebrCounter = cellData.id;
const qwebrOptions = cellData.options;
// Retrieve the previously created document elements
let runButton = document.getElementById(`qwebr-button-run-${qwebrCounter}`);
let resetButton = document.getElementById(`qwebr-button-reset-${qwebrCounter}`);
let copyButton = document.getElementById(`qwebr-button-copy-${qwebrCounter}`);
let editorDiv = document.getElementById(`qwebr-editor-${qwebrCounter}`);
// Load the Monaco Editor and create an instance
let editor;
require(['vs/editor/editor.main'], function () {
editor = monaco.editor.create(editorDiv, {
value: initialCode,
language: 'r',
theme: 'vs-light',
automaticLayout: true, // Works wonderfully with RevealJS
scrollBeyondLastLine: false,
minimap: {
enabled: false
},
fontSize: '17.5pt', // Bootstrap is 1 rem
renderLineHighlight: "none", // Disable current line highlighting
hideCursorInOverviewRuler: true, // Remove cursor indictor in right hand side scroll bar
readOnly: qwebrOptions['read-only'] ?? false
});
// Store the official counter ID to be used in keyboard shortcuts
editor.__qwebrCounter = qwebrCounter;
// Store the official div container ID
editor.__qwebrEditorId = `qwebr-editor-${qwebrCounter}`;
// Store the initial code value and options
editor.__qwebrinitialCode = initialCode;
editor.__qwebrOptions = qwebrOptions;
// Set at the model level the preferred end of line (EOL) character to LF.
// This prevent `\r\n` from being given to the webR engine if the user is on Windows.
// See details in: https://github.com/coatless/quarto-webr/issues/94
// Associated error text:
// Error: <text>:1:7 unexpected input
// Retrieve the underlying model
const model = editor.getModel();
// Set EOL for the model
model.setEOL(monaco.editor.EndOfLineSequence.LF);