forked from DigiHum1/dofe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
1697 lines (1566 loc) · 80.8 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>
<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://unpkg.com/tippy.js@6/dist/tippy.css" rel="stylesheet"/>
<link href="https://unpkg.com/tippy.js@6/themes/light-border.css" rel="stylesheet"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
<title>Juncture</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://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]/dist/vue.js"></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://unpkg.com/@popperjs/core@2"></script>
<script src="https://unpkg.com/tippy.js@6"></script>
<script src="https://gitcdn.link/repo/jstor-labs/juncture/main/js/md5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/highlight.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.4.3/firebase.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) {
let q = {}
l.search.slice(1).split('&').forEach(function(v) {
let a = v.split('=')
q[a[0]] = a.slice(1).join('=').replace(/~and~/g, '&')
})
if (q.p !== undefined) {
window.history.replaceState(null, null, l.pathname.slice(0, -1) + (q.p || '') + (q.q ? ('?' + q.q) : '') + l.hash)
}
}
}(window.location))
</script>
<script>
console.log(window.location)
const ENV = window.location.hostname === 'localhost' || window.location.hostname.indexOf('gitpod') > 0 ? 'DEV' : 'PROD'
let isJuncture = window.location.hostname.indexOf('juncture-digital.org') === 0 || ENV === 'DEV'
const junctureVersion = 'main'
let junctureVersionHash
const referrerUrl = document.referrer
if (referrerUrl) {
const referrer = parseUrl(referrerUrl)
if (referrer.host === 'github.com') {
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.port === '8088' || window.location.host.indexOf('8088') === 0 || 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}`}}
}
}
} else if (window.location.port === '8080' || window.location.host.indexOf('8080') === 0) {
// For local dev in GHP mode
// let repo = window.location.pathname.split('/').filter(elem => elem !== '')[0] || 'juncture'
let repo = 'juncture'
contentSource = {
acct: 'jstor-labs',
repo: 'juncture',
branch: 'main',
ref: 'main',
hash: null,
isGhpSite: true,
baseUrl: window.location.origin,
basePath: '',
assetsBaseUrl: `${window.location.origin}`
}
} else {
// GHP deploy mode
if (window.location.hostname.indexOf('github.io') > 0) {
[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}
}
// juncture-digital.org
/*
else if (isJuncture) {
contentSource = {
acct: 'jstor-labs', repo: 'juncture-digital', ref: 'main', basePath: '', isGhpSite: false,
baseUrl: window.location.origin, assetsBaseUrl: `https://raw.githubusercontent.com/jstor-labs/juncture/main`
}
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}
// contentSource.basePath = `/${contentSource.acct}/${contentSource.repo}`
}
}
} else if (window.location.hostname === 'dev.juncture-digital.org') {
contentSource = {
acct: 'jstor-labs', repo: 'juncture-dev', ref: 'main', basePath: '', isGhpSite: false,
baseUrl: window.location.origin, assetsBaseUrl: `https://raw.githubusercontent.com/jstor-labs/juncture-dev/main`
}
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}
contentSource.basePath = `/${contentSource.acct}/${contentSource.repo}`
}
}
*/
// 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
}
let qargs = window.location.href.indexOf('?') > 0 ? parseQueryString(window.location.href.split('?')[1]) : {}
// GLobal variables used to initialize Vue
let siteConfig, contentSource, componentsList, ghUnscopedToken, oauthAccessToken, gcApiKey, gcAuthDomain, gaPropertyID, fontawesome
let loginsEnabled = false
let authenticatedUser = null
const componentsRoot = 'components'
const componentPrefix = 've-'
const availableViewers = []
const knownGhAccts = {'jstor-labs': 'main', 'kent-map': 'main'}
async function headRef(acct, repo, ref, token) {
token = token || oauthAccessToken || ghUnscopedToken
let heads, tags, found, sha
// console.log(`headRef: acct=${acct} repo=${repo} ref=${ref} token=${token} oauthAccessToken=${oauthAccessToken} ghUnscopedToken=${ghUnscopedToken}`)
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
// console.log(`getFile: token=${token} oauthAccessToken=${oauthAccessToken} ghUnscopedToken=${ghUnscopedToken}`)
// console.log(`getFile: acct=${acct} repo=${repo} ref=${ref} path=${path} token=${token}`)
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
console.log(`oauthAccessToken: expiresInSecs=${expiresInSecs} isValid=${expiresInSecs >= 300}`)
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
}}
//}
if (gaPropertyID) ga('create', gaPropertyID, 'auto')
if (siteConfig.description) {
let el = document.createElement('meta')
el.name = 'description'
el.content = siteConfig.description
document.querySelector('head').appendChild(el)
}
let attrsWithUrls = ['banner', 'favicon', 'logo']
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.slice(0,7)
console.log(`isJuncture=${isJuncture} 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'))
Promise.all([
getFile('jstor-labs', 'juncture', junctureVersionHash, '/css/main.css'),
fetch(`${window.location.origin}${contentSource.basePath}/css/main.css`).then(resp => resp.ok ? resp.text() : null)
]).then(responses => {
let style = document.createElement('style')
style.innerHTML = responses[0] || responses[1]
document.querySelector('head').appendChild(style)
})
let customCssPromise = ENV === 'DEV'
? fetch(`${contentSource.assetsBaseUrl}/css/custom.css`).then(resp => resp.ok ? resp.text() : null)
: getFile(contentSource.acct, contentSource.repo, contentSource.ref, '/css/custom.css')
customCssPromise.then(css => {
if (css) {
let style = document.createElement('style')
style.innerHTML = css
document.querySelector('head').appendChild(style)
}
})
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,
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,
loginsEnabled,
externalWindow: null,
newRepo: null,
newPage: null,
formProcessingMessage: '',
formProcessingStatus: 'ready',
releases: [],
selectedRelease: null,
reposForAcct: [],
selectedRepo: null,
doActionCallback: {},
essayConfig: null
}),
computed: {
// essayConfig() { return this.params.find(attr => attr['ve-config'] !== undefined) },
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 },
viewersEnabled() {
let viewers = this.items.filter(item => this.availableViewers.indexOf(item.viewer) >= 0).map(item => item.viewer)
return viewers.filter((viewer, index) => viewers.indexOf(viewer) === index)
}
},
mounted() {
this.anchor = window.location.href.indexOf('#') >= 0 ? window.location.href.split('#').pop() : null
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()
// 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) {
// console.log('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.location.href = `https://juncture-digital.org/${this.authenticatedUser.acct}/${this.newRepo}`
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 (window.location.hostname === 'localhost' || window.location.hostname.indexOf('8080') === 0 ) {
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) {
// Array.from(this.$refs.app.classList).forEach(cls => this.$refs.app.classList.remove(cls))
this.essayConfig = null
path = path || window.location.pathname.slice(contentSource.basePath.length) || '/'
if (path.slice(-1) !== '/') path += '/'
this.path = path
console.log(`loadEssay: basePath=${contentSource.basePath} path=${path} anchor=${this.anchor}`)
// let pathsToTry = [`${path}index.md`, `${path}README.md`, `${path.slice(0,-1)}.md`]
let pathsToTry = [`${path}index.md`, `${path}README.md`, `${path.slice(0,-1)}.md`]
if (this.authenticatedUser !== null) pathsToTry = [...[`${path}admin.md`], ...pathsToTry]
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)
/*
let segLink = document.createElement('span')
segment.appendChild(segLink)
segLink.outerHTML = `<span class="seg-link" data-anchor="${this.contentSource.baseUrl}${this.contentSource.basePath}${this.path}#${segID}" title="${segID}"><i class="fas fa-link"></span>`
*/
}
} 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,`${contentSource.basePath}${this.path}`, pathIsDir))
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)
const extension = mwImg.slice(mwImg.length-4)
let imgUrl = `https://upload.wikimedia.org/wikipedia/commons/${width ? 'thumb/' : ''}`
imgUrl += `${ImgMD5.slice(0,1)}/${ImgMD5.slice(0,2)}/${mwImg}`
if (width) imgUrl += `/${width}px-${mwImg}`
if (extension === '.svg') imgUrl += '.png'
if (extension === '.tif') imgUrl += '.jpg'
return imgUrl
},