-
Notifications
You must be signed in to change notification settings - Fork 14
/
index.html
1653 lines (1527 loc) · 77.4 KB
/
index.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 lang="en">
<head>
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" rel="stylesheet" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/tippy.js/6.3.7/tippy.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/tippy.js/6.3.7/themes/light-border.min.css" rel="stylesheet"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
<title>Juncture Digital Homepage</title>
<style>
[v-cloak] { display: none; }
#header, #footer { display: none; }
</style>
</head>
<body>
<div id="app" v-cloak ref="app" :class="layouts.join(' ')">
<div id="header" ref="header">
<component v-bind:is="headerComponent" :active="true" :scroll-top="scrollTop"
:site-config="siteConfig"
:essay-config="essayConfig"
:content-source="contentSource"
:path="path"
:logins-enabled="loginsEnabled"
:is-juncture="isJuncture"
:is-authenticated="authenticatedUser !== null && loginsEnabled"
:is-admin="isAdminUser"
:version="junctureVersion"
:do-action-callback="doActionCallback"
component-name="ve-header"
@do-action="doAction"
@authenticate="authenticate"
@logout="logout"
></component>
</div>
<div id="tabs-bar" ref="tabsBar">
<span v-for="viewer in viewersEnabled" :key="`tab-${viewer}`"
:class="{'active-tab': selectedViewer === viewer}"
:data-tab="viewer"
@click="selectedViewer = viewer; viewerIsOpen = true">
<i v-if="viewerData[viewer]" :class="viewerData[viewer].icon"></i>
</span>
</div>
<div id="essay" ref="essay" @scroll="onScroll">
<component v-bind:is="mainComponent"
:html="html"
:path="path"
:anchor="anchor"
:entities="entities"
:params="params"
:available-viewers="availableViewers"
:scroll-top="scrollTop"
:site-config="siteConfig"
:essay-config="essayConfig"
:content-source="contentSource"
:logins-enabled="loginsEnabled"
:is-juncture="isJuncture"
:is-authenticated="authenticatedUser !== null && loginsEnabled"
:is-admin="isAdminUser"
:do-action-callback="doActionCallback"
:version="junctureVersion"
@set-entities="entities = $event"
@set-params="params = $event"
@set-items="items = $event"
@set-active="active = $event"
@scroll-to-anchor="scrollToAnchor"
@load-essay="loadEssay"
@do-action="doAction"
></component>
</div>
<div v-if="essayConfig" id="viewer" ref="viewer" :style="viewerStyle">
<i v-if="!isVerticalLayout && viewerIsOpen" class="far fa-times-circle" style="position:absolute; top:0; right:0; z-index:500; font-size:26px;" @click="viewerIsOpen = !viewerIsOpen"></i>
<component v-for="viewer in viewersEnabled" :key="viewer" v-bind:is="viewer"
:items="items"
:entities="entities"
:viewer-is-active="viewer === selectedViewer"
:active-segment="active"
:height="viewerHeight"
:actions="actions"
:hover-item="hoverItem"
:content-source="contentSource"
:gh-token:="ghToken"
:md-dir="mdDir"
:is-authenticated="authenticatedUser !== null && loginsEnabled"
:component-name="viewer"
@update-component-data="updateComponentData"
@set-hover-item="hoverItem = $event"
></component>
</div>
<div v-if="essayConfig && path === '/'" id="footer" ref="footer">
<component v-bind:is="footerComponent" :site-config="siteConfig" :content-source="contentSource"></component>
</div>
<div ref="markdownViewer" id="markdown-viewer" style="display: none;">
<div style="padding:20px; width:50vw; height:50vh; overflow-y:scroll;">
<h3>Markdown</h3>
<div>
<pre v-highlightjs="markdown"><code class="markdown"></code></pre>
</div>
</div>
</div>
<div id="create-site-form" class="modal-form" style="display: none;">
<form v-on:submit.prevent>
<h1>Create new Juncture site</h1>
<input :value="authenticatedUser && authenticatedUser.acct" class="form-name" type="text" readonly>
<input v-model="newRepo" placeholder="Repository name to update or create" class="form-email" required>
<div v-html="formProcessingMessage"></div>
<div class="form-controls">
<button v-if="formProcessingStatus === 'ready'" class="form-cancel" formnovalidate @click="hideForm">Cancel</button>
<button v-if="formProcessingStatus === 'ready'" class="form-submit" @click="doSiteCreate">Create site</button>
<button v-if="formProcessingStatus === 'done'" class="form-submit" @click="loadNewSite">Close</button>
</div>
</form>
</div>
<div id="add-page-form" class="modal-form" style="display: none;">
<form v-on:submit.prevent>
<h1>Add new page</h1>
<input :value="authenticatedUser && authenticatedUser.acct" class="form-name" type="text" readonly>
<input v-if="contentSource.acct !== 'jstor-labs' && contentSource.repo !== 'juncture'" :value="contentSource.repo" class="form-name" type="text" readonly>
<select v-else v-model="selectedRepo" class="form-name">
<option v-for="repo in reposForAcct" :key="repo.name" :value="repo.name" v-text="repo.name"></option>
</select>
<input v-model="newPage" placeholder="Name of new page" class="form-email" required>
<div v-html="formProcessingMessage"></div>
<div class="form-controls">
<button v-if="formProcessingStatus === 'ready'" class="form-cancel" formnovalidate @click="hideForm">Cancel</button>
<button v-if="formProcessingStatus === 'ready'" class="form-submit" @click="doPageAdd">Add page</button>
<button v-if="formProcessingStatus === 'done'" class="form-submit" @click="gotoAddedPage">Close</button>
</div>
</form>
</div>
<div id="update-site-form" class="modal-form" style="display: none;">
<form v-on:submit.prevent>
<h1>Update Juncture site</h1>
<input :value="contentSource.acct" class="form-name" type="text" readonly>
<input :value="contentSource.repo" class="form-name" type="text" readonly>
<div style="display:float; padding:6px 0"><span>Version:</span>
<select v-model="selectedRelease">
<option v-for="release in releases" :key="release.name" :value="release" selected v-text="release.name"></option>
</select>
</div>
<div v-html="formProcessingMessage"></div>
<div class="form-controls">
<button v-if="formProcessingStatus === 'ready'" class="form-cancel" formnovalidate @click="hideForm">Cancel</button>
<button v-if="formProcessingStatus === 'ready'" class="form-submit" @click="doSiteUpdate">Update site</button>
<button v-if="formProcessingStatus === 'done'" class="form-submit" @click="hideForm">Close</button>
</div>
</form>
</div>
</div>
<!-- <script src="https://raw.githubusercontent.com/JSTOR-Labs/juncture/main/js/md5.min.js"></script> -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/markdown-it-footnote/3.0.2/markdown-it-footnote.min.js" integrity="sha512-9VOGZLBYkfqGR+OigfgoF3RUvDJRvQ9BAVgOKYmrvXlX7k+yBm5iJCpZEMpqmg2b1Cld1fiy2p0nEbDAcz9Q4w==" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/markdown-it-attrs.browser.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/markdown-it/12.0.6/markdown-it.min.js" integrity="sha512-7U8vY7c6UQpBNQOnBg3xKX502NAckvk70H1nWvh6W7izA489jEz+RCN3ntT1VMdXewaSKkOrEBegp/h6SPXrjw==" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/src/httpVueLoader.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/yamljs/0.3.0/yaml.min.js" integrity="sha512-f/K0Q5lZ1SrdNdjc2BO2I5kTx8E5Uw1EU3PhSUB9fYPohap5rPWEmQRCjtpDxNmQB4/+MMI/Cf+nvh1VSiwrTA==" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.9.2/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tippy.js/6.3.7/tippy.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/highlight.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-auth.js"></script>
<!-- This is used for deep linking of Single Page Apps when hosted with GitHub Pages -->
<script type="text/javascript">
(function(l) {
if (l.search[1] === '/' ) {
let decoded = l.search.slice(1).split('&').map(s => s.replace(/~and~/g, '&')).join('?')
window.history.replaceState(null, null, l.pathname.slice(0, -1) + decoded + l.hash)
}
}(window.location))
</script>
<script>
/* md5 function from https://stackoverflow.com/questions/14733374/how-to-generate-an-md5-file-hash-in-javascript*/
function md5cycle(f,h){var i=f[0],n=f[1],r=f[2],g=f[3];i=ff(i,n,r,g,h[0],7,-680876936),g=ff(g,i,n,r,h[1],12,-389564586),r=ff(r,g,i,n,h[2],17,606105819),n=ff(n,r,g,i,h[3],22,-1044525330),i=ff(i,n,r,g,h[4],7,-176418897),g=ff(g,i,n,r,h[5],12,1200080426),r=ff(r,g,i,n,h[6],17,-1473231341),n=ff(n,r,g,i,h[7],22,-45705983),i=ff(i,n,r,g,h[8],7,1770035416),g=ff(g,i,n,r,h[9],12,-1958414417),r=ff(r,g,i,n,h[10],17,-42063),n=ff(n,r,g,i,h[11],22,-1990404162),i=ff(i,n,r,g,h[12],7,1804603682),g=ff(g,i,n,r,h[13],12,-40341101),r=ff(r,g,i,n,h[14],17,-1502002290),i=gg(i,n=ff(n,r,g,i,h[15],22,1236535329),r,g,h[1],5,-165796510),g=gg(g,i,n,r,h[6],9,-1069501632),r=gg(r,g,i,n,h[11],14,643717713),n=gg(n,r,g,i,h[0],20,-373897302),i=gg(i,n,r,g,h[5],5,-701558691),g=gg(g,i,n,r,h[10],9,38016083),r=gg(r,g,i,n,h[15],14,-660478335),n=gg(n,r,g,i,h[4],20,-405537848),i=gg(i,n,r,g,h[9],5,568446438),g=gg(g,i,n,r,h[14],9,-1019803690),r=gg(r,g,i,n,h[3],14,-187363961),n=gg(n,r,g,i,h[8],20,1163531501),i=gg(i,n,r,g,h[13],5,-1444681467),g=gg(g,i,n,r,h[2],9,-51403784),r=gg(r,g,i,n,h[7],14,1735328473),i=hh(i,n=gg(n,r,g,i,h[12],20,-1926607734),r,g,h[5],4,-378558),g=hh(g,i,n,r,h[8],11,-2022574463),r=hh(r,g,i,n,h[11],16,1839030562),n=hh(n,r,g,i,h[14],23,-35309556),i=hh(i,n,r,g,h[1],4,-1530992060),g=hh(g,i,n,r,h[4],11,1272893353),r=hh(r,g,i,n,h[7],16,-155497632),n=hh(n,r,g,i,h[10],23,-1094730640),i=hh(i,n,r,g,h[13],4,681279174),g=hh(g,i,n,r,h[0],11,-358537222),r=hh(r,g,i,n,h[3],16,-722521979),n=hh(n,r,g,i,h[6],23,76029189),i=hh(i,n,r,g,h[9],4,-640364487),g=hh(g,i,n,r,h[12],11,-421815835),r=hh(r,g,i,n,h[15],16,530742520),i=ii(i,n=hh(n,r,g,i,h[2],23,-995338651),r,g,h[0],6,-198630844),g=ii(g,i,n,r,h[7],10,1126891415),r=ii(r,g,i,n,h[14],15,-1416354905),n=ii(n,r,g,i,h[5],21,-57434055),i=ii(i,n,r,g,h[12],6,1700485571),g=ii(g,i,n,r,h[3],10,-1894986606),r=ii(r,g,i,n,h[10],15,-1051523),n=ii(n,r,g,i,h[1],21,-2054922799),i=ii(i,n,r,g,h[8],6,1873313359),g=ii(g,i,n,r,h[15],10,-30611744),r=ii(r,g,i,n,h[6],15,-1560198380),n=ii(n,r,g,i,h[13],21,1309151649),i=ii(i,n,r,g,h[4],6,-145523070),g=ii(g,i,n,r,h[11],10,-1120210379),r=ii(r,g,i,n,h[2],15,718787259),n=ii(n,r,g,i,h[9],21,-343485551),f[0]=add32(i,f[0]),f[1]=add32(n,f[1]),f[2]=add32(r,f[2]),f[3]=add32(g,f[3])}function cmn(f,h,i,n,r,g){return h=add32(add32(h,f),add32(n,g)),add32(h<<r|h>>>32-r,i)}function ff(f,h,i,n,r,g,t){return cmn(h&i|~h&n,f,h,r,g,t)}function gg(f,h,i,n,r,g,t){return cmn(h&n|i&~n,f,h,r,g,t)}function hh(f,h,i,n,r,g,t){return cmn(h^i^n,f,h,r,g,t)}function ii(f,h,i,n,r,g,t){return cmn(i^(h|~n),f,h,r,g,t)}function md51(f){txt="";var h,i=f.length,n=[1732584193,-271733879,-1732584194,271733878];for(h=64;h<=f.length;h+=64)md5cycle(n,md5blk(f.substring(h-64,h)));f=f.substring(h-64);var r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(h=0;h<f.length;h++)r[h>>2]|=f.charCodeAt(h)<<(h%4<<3);if(r[h>>2]|=128<<(h%4<<3),h>55)for(md5cycle(n,r),h=0;h<16;h++)r[h]=0;return r[14]=8*i,md5cycle(n,r),n}function md5blk(f){var h,i=[];for(h=0;h<64;h+=4)i[h>>2]=f.charCodeAt(h)+(f.charCodeAt(h+1)<<8)+(f.charCodeAt(h+2)<<16)+(f.charCodeAt(h+3)<<24);return i}var hex_chr="0123456789abcdef".split("");function rhex(f){for(var h="",i=0;i<4;i++)h+=hex_chr[f>>8*i+4&15]+hex_chr[f>>8*i&15];return h}function hex(f){for(var h=0;h<f.length;h++)f[h]=rhex(f[h]);return f.join("")}function md5(f){return hex(md51(f))}function add32(f,h){return f+h&4294967295}
</script>
<script type="module">
const ENV = window.location.port || window.location.host.indexOf('githubpreview.dev') > 0 ? 'DEV' : 'PROD'
let isJuncture = window.location.hostname.indexOf('juncture-digital.org') === 0 || ENV === 'DEV'
const junctureVersion = 'main'
let junctureVersionHash
let qargs = window.location.href.indexOf('?') > 0 ? parseQueryString(window.location.href.split('?')[1]) : {}
const referrerUrl = document.referrer
if (referrerUrl) {
const referrer = parseUrl(referrerUrl)
if (referrer.host === 'github.com' && referrer.pathname.indexOf('/jstor-labs/juncture/wiki') < 0) {
const referrerPath = referrer.pathname.slice(1).split('/')
const ghAcct = referrerPath[0]
const ghRepo = referrerPath[1]
const ghBranch = referrerPath.length > 3 ? referrerPath[3] : 'main'
const pathStart = 4
const pathEnd = referrerPath[referrerPath.length-1] === 'README.md' || referrerPath[referrerPath.length-1] === 'index.md' ? referrerPath.length-1 : referrerPath.length
const ghPath = referrerPath.slice(pathStart, pathEnd).join('/').replace(/\.md$/, '')
const redirect = `${window.location.origin}/${ghAcct}/${ghRepo}/${ghPath}${ghBranch === 'master' || ghBranch === 'main' ? '' : '?ref=' + ghBranch}`
window.location = redirect
}
}
Vue.directive('highlightjs', {
deep: true,
bind: function(el, binding) {
let targets = el.querySelectorAll('code')
targets.forEach((target) => {
if (binding.value) {
target.textContent = binding.value
}
hljs.highlightBlock(target)
})
},
componentUpdated: function(el, binding) {
let targets = el.querySelectorAll('code')
targets.forEach((target) => {
if (binding.value) {
target.textContent = binding.value
hljs.highlightBlock(target)
}
})
}
})
let md = window.markdownit({
html: true,
breaks: false,
linkify: false,
typographer: false,
highlight: function (str, lang) {
if (lang && hljs.getLanguage(lang)) {
try {
return hljs.highlight(lang, str).value;
} catch (__) {}
}
return ''; // use external default escaping
}
})
.use(window.markdownitFootnote)
.use(markdownItAttrs)
async function getContentSource() {
let contentSource
if (window.location.host.indexOf('juncture-digital.org') >= 0) {
contentSource = {
acct: 'jstor-labs', repo: 'juncture-digital', ref: 'main', hash: null, basePath: '', isGhpSite: false,
baseUrl: window.location.origin,
assetsBaseUrl: `${window.location.origin}`
}
let pathElems = window.location.pathname.split('/').filter(elem => elem !== '')
if (pathElems.length >= 2) {
let ghRepoInfo = await githubRepoInfo(pathElems[0], pathElems[1])
if (ghRepoInfo) {
contentSource = {...contentSource, ...ghRepoInfo,
...{basePath: `/${ghRepoInfo.acct}/${ghRepoInfo.repo}`, assetsBaseUrl: `https://raw.githubusercontent.com/${ghRepoInfo.acct}/${ghRepoInfo.repo}/${ghRepoInfo.ref}`}}
}
}
} else if (ENV === 'DEV') {
// For local dev
let repo = 'juncture'
contentSource = {
baseUrl: window.location.origin,
basePath: '',
assetsBaseUrl: `${window.location.origin}`
}
let pathElems = window.location.pathname.split('/').filter(elem => elem !== '')
if (pathElems.length >= 2) {
let ghRepoInfo = await githubRepoInfo(pathElems[0], pathElems[1])
if (ghRepoInfo) {
contentSource = {
...contentSource,
...ghRepoInfo,
...{
basePath: `/${ghRepoInfo.acct}/${ghRepoInfo.repo}`,
assetsBaseUrl: `https://raw.githubusercontent.com/${ghRepoInfo.acct}/${ghRepoInfo.repo}/${ghRepoInfo.ref}`
}
}
}
}
} else {
// GHP deploy mode
if (window.location.hostname.indexOf('github.io') > 0) {
let [acct, repo] = window.location.href.replace(/\.github\.io/,'').split('/').slice(2, 4)
contentSource = {
acct, repo, ref: qargs.ref || 'main', basePath: `/${repo}`, isGhpSite: true, baseUrl: window.location.origin
}
let ghRepoInfo = await githubRepoInfo(acct, repo)
if (ghRepoInfo) {
contentSource = {...contentSource, ...ghRepoInfo}
}
// Deployed in a non juncture-digital.org custom domain
} else {
contentSource = {acct: null, repo: null, ref: null, baseUrl: window.location.origin, basePath: '', isGhpSite: false}
}
}
return contentSource
}
// GLobal variables used to initialize Vue
let siteConfig, contentSource, componentsList, ghUnscopedToken, oauthAccessToken, gcApiKey, gcAuthDomain, gaPropertyID, fontawesome
let oauthCredsFound = false
let authenticatedUser = null
const componentsRoot = 'components'
const componentPrefix = 've-'
const availableViewers = []
const knownGhAccts = {'jstor-labs': 'main', 'kent-map': 'main'}
async function getGhUnscopedToken() {
let resp = await fetch('https://api.juncture-digital.org/gh-token')
if (resp.ok) return await resp.text()
}
ghUnscopedToken = await getGhUnscopedToken()
async function headRef(acct, repo, ref, token) {
token = token || oauthAccessToken || ghUnscopedToken
let heads, tags, found, sha
let resp = await fetch(`https://api.github.com/repos/${acct}/${repo}/git/refs/heads`, {
headers: {Authorization: `Token ${token}`, Accept: 'application/vnd.github.v3+json'} })
if (resp.ok) {
heads = await resp.json()
found = heads.find(head => head.ref === `refs/heads/${ref}`)
sha = found ? found.object.sha : null
}
if (!sha) {
resp = await fetch(`https://api.github.com/repos/${acct}/${repo}/tags`, {
headers: {Authorization: `Token ${token}`, Accept: 'application/vnd.github.v3+json'} })
if (resp.ok) {
tags = await resp.json()
found = tags.find(tag => tag.name === ref)
sha = found ? found.commit.sha : null
}
}
return sha
}
async function getFile(acct, repo, ref, path, token) {
token = token || oauthAccessToken || ghUnscopedToken
let content
let resp = await fetch(`https://api.github.com/repos/${acct}/${repo}/contents${path}?ref=${ref}`, {headers: {Authorization:`Token ${token}`}})
if (resp.ok) {
resp = await resp.json()
content = decodeURIComponent(escape(atob(resp.content)))
}
return Promise.resolve(content)
}
async function gcOauth() {
if (gcApiKey && gcAuthDomain) {
firebase.initializeApp({apiKey: gcApiKey, authDomain: gcAuthDomain})
let result = await firebase.auth().getRedirectResult()
if (result.credential) window.localStorage.setItem('ghAuth', JSON.stringify(result))
}
try {
let ghAuth = JSON.parse(window.localStorage.getItem('ghAuth'))
if (ghAuth) {
let currentTime = new Date().getTime()
let expirationTime = ghAuth.user.stsTokenManager.expirationTime
let expiresInSecs = (expirationTime-currentTime)/1000
if (expiresInSecs >= 300) {
authenticatedUser = ghAuth.user
authenticatedUser.acct = ghAuth.additionalUserInfo.username
authenticatedUser.isAdmin = siteConfig.siteAdmins && siteConfig.siteAdmins.indexOf(authenticatedUser.acct) >= 0
oauthAccessToken = ghAuth.credential.oauthAccessToken
}
}
} catch(err){console.log(err)}
}
getContentSource()
.then(sourceInfo => {
contentSource = sourceInfo
return getSiteConfig()
})
.then(config => {
siteConfig = config
if (ENV === 'PROD') {
contentSource = {...contentSource, ...{
acct: config.acct || contentSource.acct,
repo: config.repo || contentSource.repo,
ref: qargs.ref || config.ref || contentSource.ref || 'main'
}}
}
if (gaPropertyID) ga('create', gaPropertyID, 'auto')
if (siteConfig.description) setMetaDescription(siteConfig.description)
let attrsWithUrls = ['banner', 'favicon', 'logo']
if (ENV === 'DEV' && (contentSource.acct === 'jstor-labs' && contentSource.repo === 'juncture-digital') ) {
attrsWithUrls.forEach(attr => { if (config[attr]) config[attr] = convertURL(config[attr]) })
} else if (contentSource.repo) {
headRef(contentSource.acct, contentSource.repo, contentSource.ref).then(headHash => {
if (headHash) {
contentSource.hash = headHash.slice(0,7)
contentSource.assetsBaseUrl = `https://raw.githubusercontent.com/${contentSource.acct}/${contentSource.repo}/${contentSource.hash}`
attrsWithUrls.forEach(attr => { if (config[attr]) config[attr] = convertURL(config[attr]) })
}
})
}
return config
})
.then(config => gcOauth())
.then(resp => headRef('jstor-labs', 'juncture', junctureVersion, ghUnscopedToken))
.then(hash => {
junctureVersionHash = hash ? hash.slice(0,7) : null
// console.log(`ENV=${ENV} junctureVersion=${junctureVersion} junctureVersionHash=${junctureVersionHash} referrer=${document.referrer}`)
return getComponentsList()
})
.then(clist => {
componentsList = clist
componentsList.forEach(componentUrl => {
let httpComponent = httpVueLoader(componentUrl)
let componentName = `${componentPrefix}${camelToKebab(componentUrl.split('/').pop().split('.')[0])}`
if (availableViewers.indexOf(componentName) <0) {
availableViewers.push(componentName)
Vue.component(componentName, httpComponent)
}
})
if (siteConfig.favicon ) document.querySelector('head').appendChild(makeLink(siteConfig.favicon, 'icon'))
if (siteConfig.title) document.title = siteConfig.title
if (fontawesome) document.querySelector('body').appendChild(makeScriptTag(fontawesome, 'anonymous'))
if (ENV === 'DEV') {
dir('/css').then(files => {
return Promise.all([
...[ files['main.css']
? fetch(files['main.css']).then(resp => resp.text())
: getFile('jstor-labs', 'juncture', 'main', '/css/main.css')
],
...Object.keys(files).filter(file => file !== 'main.css').map(file => fetch(files[file]).then(resp => resp.text()))
])
})
.then(styles => {
styles.forEach(css => {
let style = document.createElement('style')
style.innerHTML = css
document.querySelector('head').appendChild(style)
})
})
} else {
getFile('jstor-labs', 'juncture', 'main', '/css/main.css').then(css => {
let style = document.createElement('style')
style.innerHTML = css
document.querySelector('head').appendChild(style)
})
}
if (contentSource.repo) {
dir('/css', contentSource).then(files => {
let cssUrls = Object.values(files)
return cssUrls.length > 0
? Promise.all([cssUrls.map(url => fetch(url).then(resp => resp.text()))])
: []
})
.then(styles => {
styles.forEach(css => {
let style = document.createElement('style')
style.innerHTML = css
document.querySelector('head').appendChild(style)
})
})
}
if (siteConfig.enableOneTrust && siteConfig.oneTrustSiteKey) {
let el = document.createElement('script')
el.src = 'https://cdn.cookielaw.org/scripttemplates/otSDKStub.js'
el.setAttribute('data-domain-script', siteConfig.oneTrustSiteKey)
document.querySelector('body').appendChild(el)
}
new Vue({
el: '#app',
data: () => ({
html: null,
entities: {},
params: [],
anchor: null,
items: [],
active: null,
qargs,
layouts: [],
siteConfig,
contentSource,
componentsList,
isJuncture,
junctureVersion,
path: '/',
mdPath: '',
mdDir: '/',
markdown: null,
markdownViewer: null,
viewerHeight: 0,
availableViewers,
viewersEnabled: [],
selectedViewer: null,
viewerData: {},
scrollTop: 0,
forceHorizontalLayout: window.matchMedia('only screen and (max-width: 1000px)').matches,
viewerIsOpen: false,
hoverEntity: undefined,
hoverItem: undefined,
selectedItem: undefined,
actions: {},
authenticatedUser,
oauthCredsFound,
externalWindow: null,
newRepo: null,
newPage: null,
formProcessingMessage: '',
formProcessingStatus: 'ready',
releases: [],
selectedRelease: null,
reposForAcct: [],
selectedRepo: null,
doActionCallback: {},
essayConfig: null
}),
computed: {
headerComponent() { return this.essayConfig && this.essayConfig.header ? `ve-${this.essayConfig.header.toLowerCase()}` : null},
mainComponent() { return this.essayConfig && this.essayConfig.main ? `ve-${this.essayConfig.main.toLowerCase()}` : null},
footerComponent() { return this.essayConfig && this.essayConfig.footer ? `ve-${this.essayConfig.footer.toLowerCase()}` : null},
isAdminUser() { return ENV === 'DEV' || authenticatedUser !== null && (authenticatedUser.isAdmin || contentSource.acct === authenticatedUser.acct) },
ghToken() { return oauthAccessToken || ghUnscopedToken },
viewerStyle() { return {
height: this.viewerIsOpen
? this.isVerticalLayout
? '100%'
: `calc(50vh - ${this.$refs.header.clientHeight/2}px)`
: 0
}
},
isVerticalLayout() { return !this.forceHorizontalLayout && this.layouts.indexOf('vertical') >= 0 },
loginsEnabled() { return this.oauthCredsFound && (!this.essayConfig || !this.essayConfig['logins-disabled']) }
},
mounted() {
let path
if (window.location.href.indexOf('#') > 0) {
path = window.location.href.split('#')[0].split('/').slice(3).join('')
let anchor = window.location.href.split('#').pop()
if (path) this.anchor = anchor
else path = anchor
}
window.onpopstate = (e) => this.loadEssay(e.state.file, true)
const resizeObserver = new ResizeObserver(entries => {
this.forceHorizontalLayout = window.matchMedia('only screen and (max-width: 1000px)').matches
})
resizeObserver.observe(this.$refs.app)
this.loadEssay(path)
// Initialize Markdown source viewer
this.markdownViewer = tippy(this.$refs.header, {
trigger: 'manual',
theme: 'light-border',
allowHTML: true,
interactive: true,
arrow: false,
placement: 'bottom-start',
onShow: async (instance) => { instance.setContent(this.$refs.markdownViewer.innerHTML) },
onHide: (instance) => {}
})
},
methods: {
authenticate() {
let provider = new firebase.auth.GithubAuthProvider()
provider.addScope('repo')
firebase.auth().signInWithRedirect(provider)
},
logout() {
this.authenticatedUser = null; window.localStorage.removeItem('ghAuth')
this.loadEssay()
},
editMarkdown() {
this.openWindow(`https://github.com/${this.contentSource.acct}/${this.contentSource.repo}/edit/${this.contentSource.ref}${this.mdPath}`)
},
openWindow(url, options) {
if (this.externalWindow) { this.externalWindow.close() }
if (options === undefined) options = 'toolbar=yes,location=yes,left=0,top=0,width=1000,height=1200,scrollbars=yes,status=yes'
this.externalWindow = window.open(url, '_blank', options)
},
// Updates viewer data from events emitted when viewer components are loaded
updateComponentData(data) { this.viewerData = {...this.viewerData, ...data }},
// Sets active element based on essay window scroll position
onScroll: _.throttle(function (e) {
e.preventDefault()
e.stopPropagation()
this.scrollTop = e.target.scrollTop
}, 5),
// Handles menu actions from header
async doAction(action, options) {
if (action === 'sendmail') {
this.doActionCallback = {status: 'processing', message: 'Processing request'}
let resp = await sendmail(options)
this.doActionCallback = {status: 'done', message: 'Email sent'}
} else if (action === 'view-markdown') {
this.markdownViewer.show()
} else if (action === 'user-guide') {
window.open('https://github.com/JSTOR-Labs/juncture/wiki', '_blank')
} else if (action === 'edit-page') {
this.editMarkdown()
} else if (action === 'add-page') {
this.reposForAcct = await this.listRepositories()
this.selectedRepo = this.reposForAcct.length > 0 ? this.reposForAcct[0].name : null
this.showForm('add-page-form')
} else if (action === 'create-site') {
this.showForm('create-site-form')
} else if (action === 'software-update') {
let releases = await getGHReleases()
this.selectedRelease = releases[0]
this.releases = releases
this.showForm('update-site-form')
} else if (action === 'goto-github') {
window.open(`https://github.com/${contentSource.acct}/${contentSource.repo}/tree/${contentSource.ref}`, '_blank')
} else if (action === 'viewSiteOnJuncture') {
window.location.href = `https://juncture-digital.org/${contentSource.acct}/${contentSource.repo}`
} else if (action === 'authenticate') {
this.authenticate()
} else if (action === 'logout') {
this.logout()
} else if (action === 'load-page') {
this.loadEssay(options)
}
},
showForm(formId) {
this.$refs.app.classList.add('dimmed')
let form = document.getElementById(formId)
form.style.display = 'unset'
form.classList.add('visible-form')
},
hideForm() {
this.$refs.app.classList.remove('dimmed')
let form = document.querySelector('.visible-form')
form.style.display = 'none'
form.classList.remove('visible-form')
this.formProcessingMessage = ''
this.formProcessingStatus = 'ready'
},
async doSiteCreate() {
this.formProcessingStatus = 'processing'
this.formProcessingMessage = 'Creating site...'
await this.createSite(this.authenticatedUser.acct, this.newRepo, junctureVersion)
let siteUrl = `https://${this.authenticatedUser.acct}.github.io/${this.newRepo}`
// this.formProcessingMessage = `New Juncture site created at <a href="${siteUrl}">${siteUrl}</a>`
this.formProcessingMessage = `New Juncture site created.`
this.formProcessingStatus = 'done'
},
loadNewSite() {
this.hideForm()
window.open(`https://juncture-digital.org/${this.authenticatedUser.acct}/${this.newRepo}`, '_blank')
},
gotoAddedPage() {
this.hideForm()
this.loadEssay(this.newPage)
},
async doSiteUpdate() {
this.formProcessingStatus = 'processing'
this.formProcessingMessage = `Updating site to version ${this.selectedRelease.name}...`
await this.updateSite(this.selectedRelease)
let siteUrl = `https://${this.contentSource.acct}.github.io/${this.contentSource.repo}`
this.formProcessingMessage = `Site <a href="${siteUrl}">${siteUrl}</a> updated to version ${this.selectedRelease.name}`
this.formProcessingStatus = 'done'
},
async doPageAdd() {
let targetRepo = this.reposForAcct.find(repo => repo.name === this.selectedRepo)
if (targetRepo) {
if (this.newPage[0] !== '/') this.newPage = `/${this.newPage}`
if (this.newPage[this.newPage.length-1] === '/') this.newPage = this.newPage.slice(0,-1)
this.formProcessingStatus = 'processing'
this.formProcessingMessage = `Adding essay ${this.newPage} to ${targetRepo.name}...`
await this.addPage(this.authenticatedUser.acct, targetRepo.name, targetRepo.default_branch, this.newPage)
this.contentSource.acct = this.authenticatedUser.acct
this.contentSource.repo = targetRepo.name
this.contentSource.ref = targetRepo.default_branch
this.contentSource.basePath = `/${this.authenticatedUser.acct}/${targetRepo.name}`
let refHash = await headRef(this.contentSource.acct, this.contentSource.repo, this.contentSource.ref)
contentSource.assetsBaseUrl = `https://raw.githubusercontent.com/${this.contentSource.acct}/${this.contentSource.repo}/${refHash}`
this.formProcessingMessage = `New page added`
this.formProcessingStatus = 'done'
}
},
gotoSite(url) {
this.hideForm()
window.open(url, '_blank')
},
async getMarkdown(path) {
if (ENV === 'DEV' && !contentSource.repo) {
let url = `${contentSource.baseUrl}${contentSource.basePath}${path}`
let resp = await fetch(url)
if (resp.ok) return await resp.text()
} else {
let url = `https://api.github.com/repos/${contentSource.acct}/${contentSource.repo}/contents${path}?ref=${contentSource.ref}`
let resp = await fetch(url, this.ghToken ? {cache: 'no-cache', headers: {Authorization:`Token ${this.ghToken}`}} : {})
if (resp.ok) {
resp = await resp.json()
return decodeURIComponent(escape(atob(resp.content)))
}
}
return null
},
// Loads essay Markdown file
async loadEssay(path, replace, anchor) {
this.viewersEnabled = []
this.essayConfig = null
path = path || window.location.pathname.slice(contentSource.basePath.length) || '/'
if (path.slice(-1) !== '/') path += '/'
this.path = path
let _pathElems = path.split('/').filter(pe => pe)
let _mdDir = `/${_pathElems.slice(0,-1).join('/')}`
let _mdFile = `${_pathElems.pop()}.md`
let pathsToTry = (await dir(_mdDir, contentSource.repo ? contentSource : null))[_mdFile]
? [`${path.slice(0,-1)}.md`, `${path}README.md`, ]
: [`${path}README.md`, `${path.slice(0,-1)}.md`]
// console.log(`loadEssay: basePath=${contentSource.basePath} path=${path} anchor=${this.anchor}`)
let markdown
for (let i = 0; i < pathsToTry.length; i++) {
markdown = await this.getMarkdown(pathsToTry[i])
if (markdown) {
let pathElems = pathsToTry[i].split('/').filter(elem => elem)
let mdFile = pathElems.slice(-1)
this.mdDir = `/${pathElems.slice(0,-1).join('/')}`
this.mdPath = pathsToTry[i]
break
}
}
let browserPath = `${contentSource.basePath}${path}${this.anchor ? '#'+this.anchor : ''}`
if (qargs.ref) browserPath += `?ref=${qargs.ref}`
if (replace) {
history.replaceState({file: path || ''}, '', browserPath)
} else {
history.pushState({file: path || ''}, '', browserPath)
}
if (markdown) {
([this.markdown, this.html, this.params, this.entities] = await this.parseMarkdown(markdown))
let essayConfig = this.params.find(param => param['ve-config']) || {}
if (essayConfig.banner) essayConfig.banner = convertURL(essayConfig.banner)
essayConfig.header = essayConfig.header || 'header'
essayConfig.main = essayConfig.main || essayConfig.component || 'visual-essay'
essayConfig.footer = essayConfig.footer || 'footer'
this.essayConfig = essayConfig
}
if (gaPropertyID) ga('send', 'pageview', `${contentSource.basePath}${path}`)
},
// Convert essay Markdown into HTML. Markdown headings are used to infer content heirarchy
async parseMarkdown(markdown) {
let tmp = new DOMParser().parseFromString(md.render(markdown), 'text/html').children[0].children[1]
this.convertResourceUrls(tmp)
let essay = document.createElement('div')
let currentSection = essay
currentSection.setAttribute('data-id', '1')
let segments = []
let segment
Array.from(tmp.querySelectorAll('param'))
.filter(param => Object.values(param.attributes).find(attr => attr.nodeName !== 'id' && attr.nodeName !== 'class') === undefined)
.forEach(param => {
if (param.id || param.className) {
let prior = param.previousElementSibling
if (param.id && prior) prior.id = param.id
if (param.className) {
if (prior) prior.className = param.className
else essay.className = param.className
}
param.parentElement.removeChild(param)
}
})
Array.from(tmp.children).forEach(el => {
if (el.tagName[0] === 'H' && isNumeric(el.tagName.slice(1))) {
let sectionLevel = parseInt(el.tagName.slice(1))
if (segments) {
segments.forEach(segment => currentSection.innerHTML += segment.outerHTML)
segments = []
segment = null
}
currentSection = new DOMParser().parseFromString('<section></section>', 'text/html').children[0].children[1].children[0]
let elClasses = Array.from(el.classList)
el.removeAttribute('class')
if (el.id) {
currentSection.id = el.id
el.removeAttribute('id')
}
if (!el.innerHTML) el.style.display = 'none'
currentSection.innerHTML += el.outerHTML
let headings = [...essay.querySelectorAll(`H${sectionLevel-1}`)]
let parent = sectionLevel === 1 || headings.length === 0 ? essay : headings.pop().parentElement
let parentDataID = parent.dataset.id || ''
let sectionSeq = parent.querySelectorAll(`H${sectionLevel}`).length + 1
let currentDataID = parentDataID ? `${parentDataID}.${sectionSeq}` : sectionSeq
currentSection.setAttribute('data-id', currentDataID)
if (elClasses.indexOf('cards') >= 0) {
let wrapper = new DOMParser().parseFromString(`<section class="${elClasses.join(' ')}"></section>`, 'text/html').children[0].children[1].children[0]
currentSection.appendChild(wrapper)
} else {
currentSection.classList.add(...elClasses)
let wrapper = parent.querySelector(':scope > .cards')
if (wrapper) {
currentSection.classList.add('card')
parent = wrapper
}
}
parent.appendChild(currentSection)
} else if (el.tagName === 'P' || el.tagName === 'UL' || el.tagName === 'OL') {
if (el.innerHTML.indexOf('ve-button.png') >= 0) {
el = null
} else if (el.innerHTML.indexOf('class="nav"') >= 0) {
currentSection.innerHTML += el.innerHTML
} else {
let segID = `${currentSection.dataset.id}.${segments.length + 1}`
segment = new DOMParser().parseFromString('<div></div>', 'text/html').children[0].children[1].children[0]
segment.setAttribute('data-id', segID)
segment.setAttribute('id', segID)
segment.classList.add('segment')
segment.innerHTML = el.outerHTML
segments.push(segment)
}
} else if (el.tagName === 'SECTION' && el.className === 'footnotes') {
currentSection.innerHTML += el.outerHTML
} else {
if (segment) {
segment.innerHTML += el.outerHTML
} else {
currentSection.innerHTML += el.outerHTML
}
}
})
if (segments) {
segments.forEach(segment => currentSection.innerHTML += segment.outerHTML)
segments = []
}
let assignedId = 0
let params = Array.from(essay.querySelectorAll('param'))
.map(paramEl => {
let prior = paramEl.previousElementSibling
while (prior && prior.tagName !== 'P' && prior.tagName[0] !== 'H') {
prior = prior.previousElementSibling
}
return { ...{ path: getDomPath(prior || tmp).filter(elem => elem !== 'html' && elem !== 'body').join('>') }, ...attrsToObject(paramEl) }
})
.map(paramObj => {
let viewerTag = Object.keys(paramObj).find(attr => !attr.value && this.availableViewers.indexOf(attr) >= 0)
if (viewerTag) paramObj.viewer = viewerTag
else if (!Object.keys(paramObj).find(attr => attr.indexOf('ve-') === 0)) paramObj['ve-entity'] = ''
return paramObj
})
.map(paramObj => {
if (!paramObj.id) paramObj.id = paramObj.eid || `P${++assignedId}`
return paramObj
})
let entities = await this.getEntityData(this.findEntities(tmp, params))
return [markdown, essay.innerHTML, params, entities]
},
// Finds all entity references in param tags
findEntities(root, params) {
let entities = Object.fromEntries(
params.filter(param => param.eid || param['ve-entity'] !== undefined)
.map(entity => { return {...entity, ...{
id: entity.eid || entity.id,
aliases: new Set(entity.aliases ? entity.aliases.split('|') : []),
foundIn: new Set()
}} })
.map(entity => [entity.id, entity]))
Array.from(root.querySelectorAll('span'))
.filter(el => el.attributes.eid)
.map(el => attrsToObject(el))
.map(entity => { return {...entity, ...{id: entity.eid || entity.id} } })
.forEach(entity => { if (!entities[entity.eid]) entities[entity.eid] = entity })
params.filter(param => param.center && isEntityID(param.center))
.map(param => { return {...param, ...{id: param.center, eid: param.center} } })
.forEach(entity => { if (!entities[entity.eid]) entities[entity.eid] = entity })
return entities
},
// Gets labels, aliases, images and geo coords for referenced Wikdata entities
async getEntityData(entities) {
let values = Object.values(entities).filter(entity => entity.eid).map(entity => `(<http://www.wikidata.org/entity/${entity.eid}>)`).join(' ')
let query = `SELECT ?item ?label ?aliases ?description ?images ?coords ?whosOnFirst WHERE {
VALUES (?item) { ${values} }
?item rdfs:label ?label . FILTER(LANG(?label) = 'en')
OPTIONAL { ?item schema:description ?description . FILTER(LANG(?description) = 'en') }
OPTIONAL { ?item skos:altLabel ?aliases . FILTER(LANG(?aliases) = 'en') }
OPTIONAL { ?item wdt:P18 ?images . }
OPTIONAL { ?item wdt:P625 ?coords . }
OPTIONAL { ?item wdt:P6766 ?whosOnFirst . }
}`
let resp = await fetch('https://query.wikidata.org/sparql', {
method: 'POST', body: `query=${encodeURIComponent(query)}`,
headers: { Accept: 'application/sparql-results+json', 'Content-Type': 'application/x-www-form-urlencoded' }
})
resp = await resp.json()
// let enrichedEntities = {}
resp.results.bindings.forEach(rec => {
let eid = rec.item.value.split('/').pop()
if (!entities[eid].images) entities[eid] = {
...entities[eid],
...{
eid,
label: rec.label.value,
aliases: new Set(entities[eid].aliases ? Array.from(entities[eid].aliases) : []),
description: rec.description && rec.description.value,
geojson: rec.whosOnFirst && rec.whosOnFirst.value && this.whosOnFirstUrl(rec.whosOnFirst.value),
images: [],
thumbnails: [],
coords: rec.coords && rec.coords.value.replace(/Point\(/,'').replace(/\)/,'').split(' ').reverse().map(coord => parseFloat(coord)),
foundIn: new Set(),
}
}
if (rec.aliases && !entities[eid].aliases.has(rec.aliases.value)) entities[eid].aliases.add(rec.aliases.value)
if (rec.images && entities[eid].images.indexOf(rec.images.value) < 0) {
entities[eid].images.push(rec.images.value)
entities[eid].thumbnails.push(this.commonsImageUrl(rec.images.value, 200))
}
})
query = `SELECT ?item ?mwPage WHERE {
VALUES (?item) { ${values} }
?mwPage schema:about ?item .
?mwPage schema:isPartOf <https://en.wikipedia.org/> . }`
resp = await fetch('https://query.wikidata.org/sparql', {
method: 'POST', body: `query=${encodeURIComponent(query)}`,
headers: { Accept: 'application/sparql-results+json', 'Content-Type': 'application/x-www-form-urlencoded' }
})
resp = await resp.json()
resp.results.bindings.forEach(rec => entities[rec.item.value.split('/').pop()]['mwPage'] = rec.mwPage.value)
return entities
},
convertResourceUrls(root) {
let pathIsDir = this.path.slice(0,-1) === this.mdDir
root.querySelectorAll('img').forEach(img => {
if (img.src.indexOf(window.location.origin) === 0) img.setAttribute('src', convertURL(img.src, this.path, pathIsDir))
})
root.querySelectorAll('param').forEach(param => {
['url', 'banner', 'article', 'logo'].forEach(attr => {
if (param.attributes[attr]) {
param.setAttribute(attr, convertURL(param.attributes[attr].value, this.path, pathIsDir))
}
})
})
return root
},
// Creates a GeoJSON file URL from a Who's on First ID
whosOnFirstUrl(wof) {
let wofParts = []
for (let i = 0; i < wof.length; i += 3) {
wofParts.push(wof.slice(i,i+3))
}
return `https://data.whosonfirst.org/${wofParts.join('/')}/${wof}.geojson`
},
commonsImageUrl(url, width) {
// Converts Wikimedia commons File URL to an image link
// If a width is provided a thumbnail is returned
let mwImg = url.indexOf('Special:FilePath') > 0 ? url.split('/Special:FilePath/').pop() : url.split('/File:').pop()
mwImg = decodeURIComponent(mwImg).replace(/ /g,'_')
const ImgMD5 = md5(mwImg)