-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathextra.js
1492 lines (1367 loc) · 46.2 KB
/
extra.js
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
/* eslint-env browser, jquery */
/* global moment, serverurl, plantumlServer, L */
import Prism from 'prismjs'
import hljs from 'highlight.js'
import PDFObject from 'pdfobject'
import { saveAs } from 'file-saver'
import escapeHTML from 'lodash/escape'
import unescapeHTML from 'lodash/unescape'
import isURL from 'validator/lib/isURL'
import { transform } from 'markmap-lib/dist/transform'
import { Markmap } from 'markmap-lib/dist/view'
import { stripTags } from '../../utils/string'
import getUIElements from './lib/editor/ui-elements'
import { emojifyImageDir } from './lib/editor/constants'
import {
parseFenceCodeParams,
serializeParamToAttribute,
deserializeParamAttributeFromElement
} from './lib/markdown/utils'
import { renderFretBoard } from './lib/renderer/fretboard/fretboard'
import './lib/renderer/lightbox'
import { renderCSVPreview } from './lib/renderer/csvpreview'
import { escapeAttrValue } from './render'
import { sanitizeUrl } from './utils'
import markdownit from 'markdown-it'
import markdownitContainer from 'markdown-it-container'
/* Defined regex markdown it plugins */
import Plugin from 'markdown-it-regexp'
require('prismjs/themes/prism.css')
require('prismjs/components/prism-wiki')
require('prismjs/components/prism-haskell')
require('prismjs/components/prism-go')
require('prismjs/components/prism-typescript')
require('prismjs/components/prism-jsx')
require('prismjs/components/prism-makefile')
require('prismjs/components/prism-gherkin')
require('./lib/common/login')
require('../vendor/md-toc')
let viz = new window.Viz()
const plantumlEncoder = require('plantuml-encoder')
const ui = getUIElements()
// auto update last change
window.createtime = null
window.lastchangetime = null
window.lastchangeui = {
status: $('.ui-status-lastchange'),
time: $('.ui-lastchange'),
user: $('.ui-lastchangeuser'),
nouser: $('.ui-no-lastchangeuser')
}
const ownerui = $('.ui-owner')
export function updateLastChange () {
if (!window.lastchangeui) return
if (window.createtime) {
if (window.createtime && !window.lastchangetime) {
window.lastchangeui.status.text('created')
} else {
window.lastchangeui.status.text('changed')
}
const time = window.lastchangetime || window.createtime
window.lastchangeui.time.html(moment(time).fromNow())
window.lastchangeui.time.attr('title', moment(time).format('llll'))
}
}
setInterval(updateLastChange, 60000)
window.lastchangeuser = null
window.lastchangeuserprofile = null
export function updateLastChangeUser () {
if (window.lastchangeui) {
if (window.lastchangeuser && window.lastchangeuserprofile) {
const icon = window.lastchangeui.user.children('i')
icon.attr('title', window.lastchangeuserprofile.name).tooltip('fixTitle')
if (window.lastchangeuserprofile.photo) { icon.attr('style', `background-image:url(${window.lastchangeuserprofile.photo})`) }
window.lastchangeui.user.show()
window.lastchangeui.nouser.hide()
} else {
window.lastchangeui.user.hide()
window.lastchangeui.nouser.show()
}
}
}
window.owner = null
window.ownerprofile = null
export function updateOwner () {
if (ownerui) {
if (window.owner && window.ownerprofile && window.owner !== window.lastchangeuser) {
const icon = ownerui.children('i')
icon.attr('title', window.ownerprofile.name).tooltip('fixTitle')
const styleString = `background-image:url(${window.ownerprofile.photo})`
if (window.ownerprofile.photo && icon.attr('style') !== styleString) { icon.attr('style', styleString) }
ownerui.show()
} else {
ownerui.hide()
}
}
}
// get title
function getTitle (view) {
let title = ''
if (md && md.meta && md.meta.title && (typeof md.meta.title === 'string' || typeof md.meta.title === 'number')) {
title = md.meta.title
} else {
const h1s = view.find('h1')
if (h1s.length > 0) {
title = h1s.first().text()
} else {
title = null
}
}
return title
}
// render title
export function renderTitle (view) {
let title = getTitle(view)
if (title) {
title += ' - CodiMD'
} else {
title = 'CodiMD - Collaborative markdown notes'
}
return title
}
// render filename
export function renderFilename (view) {
let filename = getTitle(view)
if (!filename) {
filename = 'Untitled'
}
return filename
}
// render tags
export function renderTags (view) {
const tags = []
const rawtags = []
if (md && md.meta && md.meta.tags && (typeof md.meta.tags === 'string' || typeof md.meta.tags === 'number')) {
const metaTags = (`${md.meta.tags}`).split(',')
for (let i = 0; i < metaTags.length; i++) {
const text = metaTags[i].trim()
if (text) rawtags.push(text)
}
} else {
view.find('h6').each((key, value) => {
if (/^tags/gmi.test($(value).text())) {
const codes = $(value).find('code')
for (let i = 0; i < codes.length; i++) {
const text = codes[i].innerHTML.trim()
if (text) rawtags.push(text)
}
}
})
}
for (let i = 0; i < rawtags.length; i++) {
let found = false
for (let j = 0; j < tags.length; j++) {
if (tags[j] === rawtags[i]) {
found = true
break
}
}
if (!found) { tags.push(rawtags[i]) }
}
return tags
}
function slugifyWithUTF8 (text) {
// remove HTML tags and trim spaces
let newText = stripTags(text.toString().trim())
// replace space between words with dashes
newText = newText.replace(/\s+/g, '-')
// slugify string to make it valid as an attribute
newText = newText.replace(/([!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g, '')
return newText
}
// parse meta
export function parseMeta (md, edit, view, toc, tocAffix) {
let lang = null
let dir = null
let breaks = window.defaultUseHardbreak
if (md && md.meta) {
const meta = md.meta
lang = meta.lang
dir = meta.dir
breaks = meta.breaks
}
if (!lang || typeof lang !== 'string') {
lang = 'en'
}
// text language
view.attr('lang', lang)
toc.attr('lang', lang)
tocAffix.attr('lang', lang)
if (edit) { edit.attr('lang', lang) }
// text direction
if (dir && typeof dir === 'string') {
view.attr('dir', dir)
toc.attr('dir', dir)
tocAffix.attr('dir', dir)
} else {
view.removeAttr('dir')
toc.removeAttr('dir')
tocAffix.removeAttr('dir')
}
// breaks
if (typeof breaks === 'boolean') {
md.options.breaks = breaks
} else {
md.options.breaks = window.defaultUseHardbreak
}
}
window.viewAjaxCallback = null
// regex for extra tags
const spaceregex = /\s*/
const notinhtmltagregex = /(?![^<]*>|[^<>]*<\/)/
let coloregex = /\[color=([#|(|)|\s|,|\w]*?)\]/
coloregex = new RegExp(coloregex.source + notinhtmltagregex.source, 'g')
let nameregex = /\[name=(.*?)\]/
let timeregex = /\[time=([:|,|+|-|(|)|\s|\w]*?)\]/
const nameandtimeregex = new RegExp(nameregex.source + spaceregex.source + timeregex.source + notinhtmltagregex.source, 'g')
nameregex = new RegExp(nameregex.source + notinhtmltagregex.source, 'g')
timeregex = new RegExp(timeregex.source + notinhtmltagregex.source, 'g')
function replaceExtraTags (html) {
html = html.replace(coloregex, '<span class="color" data-color="$1"></span>')
html = html.replace(nameandtimeregex, '<small><i class="fa fa-user"></i> $1 <i class="fa fa-clock-o"></i> $2</small>')
html = html.replace(nameregex, '<small><i class="fa fa-user"></i> $1</small>')
html = html.replace(timeregex, '<small><i class="fa fa-clock-o"></i> $1</small>')
return html
}
if (typeof window.mermaid !== 'undefined' && window.mermaid) {
window.mermaid.startOnLoad = false
window.mermaid.parseError = function (err, hash) {
console.warn(err)
}
}
function jsonp (url, callback) {
const callbackName = 'jsonp_callback_' + Math.round(1000000000 * Math.random())
window[callbackName] = function (data) {
delete window[callbackName]
document.body.removeChild(script)
callback(data)
}
const script = document.createElement('script')
script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName
document.body.appendChild(script)
script.onerror = function (e) {
console.error(e)
script.remove()
}
}
// dynamic event or object binding here
export function finishView (view) {
// todo list
const lis = view.find('li.raw').removeClass('raw').sortByDepth().toArray()
for (let li of lis) {
let html = $(li).clone()[0].innerHTML
const p = $(li).children('p')
if (p.length === 1) {
html = p.html()
li = p[0]
}
html = replaceExtraTags(html)
li.innerHTML = html
let disabled = 'disabled'
if (typeof editor !== 'undefined' && window.havePermission()) { disabled = '' }
if (/^\s*\[[x ]]\s*/.test(html)) {
li.innerHTML = html.replace(/^\s*\[ ]\s*/, `<input type="checkbox" class="task-list-item-checkbox "${disabled}><label></label>`)
.replace(/^\s*\[x]\s*/, `<input type="checkbox" class="task-list-item-checkbox" checked ${disabled}><label></label>`)
if (li.tagName.toLowerCase() !== 'li') {
li.parentElement.setAttribute('class', 'task-list-item')
} else {
li.setAttribute('class', 'task-list-item')
}
}
if (typeof editor !== 'undefined' && window.havePermission()) { $(li).find('input').change(toggleTodoEvent) }
// color tag in list will convert it to tag icon with color
const tagColor = $(li).closest('ul').find('.color')
tagColor.each((key, value) => {
$(value).addClass('fa fa-tag').css('color', $(value).attr('data-color'))
})
}
// youtube
view.find('div.youtube.raw').removeClass('raw')
.click(function () {
imgPlayiframe(this, '//www.youtube.com/embed/')
})
// vimeo
view.find('div.vimeo.raw').removeClass('raw')
.click(function () {
imgPlayiframe(this, '//player.vimeo.com/video/')
})
.each((key, value) => {
const videoId = $(value).attr('data-videoid')
let urlForJsonp = ''
try {
const url = new URL(`https://vimeo.com/api/v2/video/${videoId}.json`)
if (!url.pathname.startsWith('/api/v2/video/')) {
throw new Error(`Invalid vimeo video id: ${videoId}`)
}
urlForJsonp = `//${url.origin}${url.pathname}`
} catch (err) {
console.error(err)
return
}
jsonp(urlForJsonp, function (data) {
const thumbnailSrc = data[0].thumbnail_large
const image = `<img src="${thumbnailSrc}" />`
$(value).prepend(image)
if (window.viewAjaxCallback) window.viewAjaxCallback()
})
})
// gist
view.find('code[data-gist-id]').each((key, value) => {
if ($(value).children().length === 0) {
// strip HTML tags to avoid stored XSS
const gistid = value.getAttribute('data-gist-id')
value.setAttribute('data-gist-id', stripTags(gistid))
const gistfile = value.getAttribute('data-gist-file')
if (gistfile) value.setAttribute('data-gist-file', stripTags(gistfile))
const gistline = value.getAttribute('data-gist-line')
if (gistline) value.setAttribute('data-gist-line', stripTags(gistline))
const gisthighlightline = value.getAttribute('data-gist-highlight-line')
if (gisthighlightline) value.setAttribute('data-gist-highlight-line', stripTags(gisthighlightline))
const gistshowloading = value.getAttribute('data-gist-show-loading')
if (gistshowloading) value.setAttribute('data-gist-show-loading', stripTags(gistshowloading))
$(value).gist(window.viewAjaxCallback)
}
})
// sequence diagram
const sequences = view.find('div.sequence-diagram.raw').removeClass('raw')
sequences.each((key, value) => {
try {
var $value = $(value)
const $ele = $(value).parent().parent()
const sequence = $value
sequence.sequenceDiagram({
theme: 'simple'
})
$ele.addClass('sequence-diagram')
$value.children().unwrap().unwrap()
const svg = $ele.find('> svg')
svg[0].setAttribute('viewBox', `0 0 ${svg.attr('width')} ${svg.attr('height')}`)
svg[0].setAttribute('preserveAspectRatio', 'xMidYMid meet')
} catch (err) {
$value.unwrap()
$value.parent().append(`<div class="alert alert-warning">${escapeHTML(err)}</div>`)
console.warn(err)
}
})
// flowchart
const flow = view.find('div.flow-chart.raw').removeClass('raw')
flow.each((key, value) => {
try {
var $value = $(value)
const $ele = $(value).parent().parent()
const chart = window.flowchart.parse($value.text())
$value.html('')
chart.drawSVG(value, {
'line-width': 2,
fill: 'none',
'font-size': '16px',
'font-family': "'Andale Mono', monospace"
})
$ele.addClass('flow-chart')
$value.children().unwrap().unwrap()
} catch (err) {
$value.unwrap()
$value.parent().append(`<div class="alert alert-warning">${escapeHTML(err)}</div>`)
console.warn(err)
}
})
// graphviz
var graphvizs = view.find('div.graphviz.raw').removeClass('raw')
graphvizs.each(function (key, value) {
try {
var $value = $(value)
const options = deserializeParamAttributeFromElement(value)
var $ele = $(value).parent().parent()
$value.unwrap()
viz.renderString($value.text(), options)
.then(graphviz => {
if (!graphviz) throw Error('viz.js output empty graph')
$value.html(graphviz)
$ele.addClass('graphviz')
$value.children().unwrap()
})
.catch(err => {
viz = new window.Viz()
$value.parent().append(`<div class="alert alert-warning">${escapeHTML(err)}</div>`)
console.warn(err)
})
} catch (err) {
viz = new window.Viz()
$value.parent().append(`<div class="alert alert-warning">${escapeHTML(err)}</div>`)
console.warn(err)
}
})
// mermaid
const mermaids = view.find('div.mermaid.raw').removeClass('raw')
mermaids.each((key, value) => {
try {
var $value = $(value)
const $ele = $(value).closest('pre')
const text = $value.text()
// validate the syntax first
if (window.mermaid.parse(text)) {
$ele.addClass('mermaid')
$ele.text(text)
// render the diagram
window.mermaid.init(undefined, $ele)
}
} catch (err) {
$value.unwrap()
$value.parent().append(`<div class="alert alert-warning">${escapeHTML(err.str)}</div>`)
console.warn(err)
}
})
// abc.js
const abcs = view.find('div.abc.raw').removeClass('raw')
abcs.each((key, value) => {
try {
var $value = $(value)
var $ele = $(value).parent().parent()
window.ABCJS.renderAbc(value, $value.text())
$ele.addClass('abc')
$value.children().unwrap().unwrap()
const svg = $ele.find('> svg')
svg[0].setAttribute('viewBox', `0 0 ${svg.attr('width')} ${svg.attr('height')}`)
svg[0].setAttribute('preserveAspectRatio', 'xMidYMid meet')
} catch (err) {
$value.unwrap()
$value.parent().append(`<div class="alert alert-warning">${escapeHTML(err)}</div>`)
console.warn(err)
}
})
// vega-lite
const vegas = view.find('div.vega.raw').removeClass('raw')
vegas.each((key, value) => {
try {
var $value = $(value)
var $ele = $(value).parent().parent()
const specText = $value.text()
$value.unwrap()
window.vegaEmbed($ele[0], JSON.parse(specText), { renderer: 'svg' })
.then(result => {
$ele.addClass('vega')
})
.catch(err => {
$ele.append(`<div class="alert alert-warning">${escapeHTML(err)}</div>`)
console.warn(err)
})
.finally(() => {
if (window.viewAjaxCallback) window.viewAjaxCallback()
})
} catch (err) {
$ele.append(`<div class="alert alert-warning">${escapeHTML(err)}</div>`)
console.warn(err)
}
})
// geo map
view.find('div.geo.raw').removeClass('raw').each(async function (key, value) {
const $elem = $(value).parent().parent()
const $value = $(value)
const content = $value.text()
$value.unwrap()
try {
let position, zoom
if (content.match(/^[-\d.,\s]+$/)) {
const [lng, lat, zoo] = content.split(',').map(parseFloat)
zoom = zoo
position = [lat, lng]
} else {
// parse value as address
const data = await fetch(`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(content)}&format=json`).then(r => r.json())
if (!data || !data.length) {
throw new Error('Location not found')
}
const { lat, lon } = data[0]
position = [lat, lon]
}
$elem.html('<div class="geo-map"></div>')
const map = L.map($elem.find('.geo-map')[0]).setView(position, zoom || 16)
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '<a href="https://www.openstreetmap.org/">OSM</a>',
maxZoom: 18
}).addTo(map)
L.marker(position, {
icon: L.icon({
iconUrl: `${serverurl}/build/leaflet/images/marker-icon.png`,
shadowUrl: `${serverurl}/build/leaflet/images/marker-shadow.png`
})
}).addTo(map)
$elem.addClass('geo')
} catch (err) {
$elem.append(`<div class="alert alert-warning">${escapeHTML(err)}</div>`)
console.warn(err)
}
})
// fretboard
const fretboard = view.find('div.fretboard_instance.raw').removeClass('raw')
fretboard.each((key, value) => {
const params = deserializeParamAttributeFromElement(value)
const $value = $(value)
try {
const $ele = $(value).parent().parent()
$ele.html(renderFretBoard($value.text(), params))
$ele.addClass('fretboard')
} catch (err) {
$value.unwrap()
$value.parent().append(`<div class="alert alert-warning">${escapeHTML(err)}</div>`)
console.warn(err)
}
})
// markmap
view.find('div.markmap.raw').removeClass('raw').each(async (key, value) => {
const $elem = $(value).parent().parent()
const $value = $(value)
const content = $value.text()
$value.unwrap()
try {
const { root: data } = transform(content)
$elem.html('<div class="markmap-container"><svg></svg></div>')
Markmap.create($elem.find('svg')[0], {
duration: 0
}, data)
} catch (err) {
$elem.html(`<div class="alert alert-warning">${escapeHTML(err)}</div>`)
console.warn(err)
}
})
// image href new window(emoji not included)
const images = view.find('img.raw[src]').removeClass('raw')
images.each((key, value) => {
// if it's already wrapped by link, then ignore
const $value = $(value)
$value[0].onload = e => {
if (window.viewAjaxCallback) window.viewAjaxCallback()
}
})
// blockquote
const blockquote = view.find('blockquote.raw').removeClass('raw')
const blockquoteP = blockquote.find('p')
blockquoteP.each((key, value) => {
let html = $(value).html()
html = replaceExtraTags(html)
$(value).html(html)
})
// color tag in blockquote will change its left border color
const blockquoteColor = blockquote.find('.color')
blockquoteColor.each((key, value) => {
$(value).closest('blockquote').css('border-left-color', $(value).attr('data-color'))
})
// slideshare
view.find('div.slideshare.raw').removeClass('raw')
.each((key, value) => {
$.ajax({
type: 'GET',
url: `//www.slideshare.net/api/oembed/2?url=http://www.slideshare.net/${$(value).attr('data-slideshareid')}&format=json`,
jsonp: 'callback',
dataType: 'jsonp',
success (data) {
const $html = $(data.html)
const iframe = $html.closest('iframe')
const caption = $html.closest('div')
const inner = $('<div class="inner"></div>').append(iframe)
const height = iframe.attr('height')
const width = iframe.attr('width')
const ratio = (height / width) * 100
inner.css('padding-bottom', `${ratio}%`)
$(value).html(inner).append(caption)
if (window.viewAjaxCallback) window.viewAjaxCallback()
}
})
})
// speakerdeck
view.find('div.speakerdeck.raw').removeClass('raw')
.each((key, value) => {
const url = `https://speakerdeck.com/${$(value).attr('data-speakerdeckid')}`
const inner = $('<a>Speakerdeck</a>')
inner.attr('href', url)
inner.attr('rel', 'noopener noreferrer')
inner.attr('target', '_blank')
$(value).append(inner)
})
// pdf
view.find('div.pdf.raw').removeClass('raw')
.each(function (key, value) {
const url = $(value).attr('data-pdfurl')
const cleanUrl = sanitizeUrl(url)
const inner = $('<div></div>')
$(this).append(inner)
setTimeout(() => {
PDFObject.embed(cleanUrl, inner, {
height: '400px'
})
}, 1)
})
// syntax highlighting
view.find('code.raw').removeClass('raw')
.each((key, value) => {
const langDiv = $(value)
if (langDiv.length > 0) {
const reallang = langDiv[0].className.replace(/hljs|wrap/g, '').trim()
const codeDiv = langDiv.find('.code')
let code = ''
if (codeDiv.length > 0) code = codeDiv.html()
else code = langDiv.html()
var result
if (!reallang) {
result = {
value: code
}
} else if (reallang === 'haskell' || reallang === 'go' || reallang === 'typescript' || reallang === 'jsx' || reallang === 'gherkin') {
code = unescapeHTML(code)
result = {
value: Prism.highlight(code, Prism.languages[reallang])
}
} else if (reallang === 'tiddlywiki' || reallang === 'mediawiki') {
code = unescapeHTML(code)
result = {
value: Prism.highlight(code, Prism.languages.wiki)
}
} else if (reallang === 'cmake') {
code = unescapeHTML(code)
result = {
value: Prism.highlight(code, Prism.languages.makefile)
}
} else {
code = unescapeHTML(code)
const languages = hljs.listLanguages()
if (!languages.includes(reallang)) {
result = hljs.highlightAuto(code)
} else {
result = hljs.highlight(reallang, code)
}
}
if (codeDiv.length > 0) codeDiv.html(result.value)
else langDiv.html(result.value)
}
})
// mathjax
const mathjaxdivs = view.find('span.mathjax.raw').removeClass('raw').toArray()
try {
if (mathjaxdivs.length > 1) {
window.MathJax.Hub.Queue(['Typeset', window.MathJax.Hub, mathjaxdivs])
window.MathJax.Hub.Queue(window.viewAjaxCallback)
} else if (mathjaxdivs.length > 0) {
window.MathJax.Hub.Queue(['Typeset', window.MathJax.Hub, mathjaxdivs[0]])
window.MathJax.Hub.Queue(window.viewAjaxCallback)
}
} catch (err) {
console.warn(err)
}
// register details toggle for scrollmap recalulation
view.find('details.raw').removeClass('raw').each(function (key, val) {
$(val).on('toggle', window.viewAjaxCallback)
})
// render title
document.title = renderTitle(view)
}
// only static transform should be here
export function postProcess (code) {
const result = $(`<div>${code}</div>`)
// process style tags
result.find('style').each((key, value) => {
let html = $(value).html()
// unescape > symbel inside the style tags
html = html.replace(/>/g, '>')
// remove css @import to prevent XSS
html = html.replace(/@import url\(([^)]*)\);?/gi, '')
$(value).html(html)
})
// link should open in new window or tab
// also add noopener to prevent clickjacking
// See details: https://mathiasbynens.github.io/rel-noopener/
result.find('a:not([href^="#"]):not([target])').attr('target', '_blank').attr('rel', 'noopener')
// update continue line numbers
const linenumberdivs = result.find('.gutter.linenumber').toArray()
for (let i = 0; i < linenumberdivs.length; i++) {
if ($(linenumberdivs[i]).hasClass('continue')) {
const startnumber = linenumberdivs[i - 1] ? parseInt($(linenumberdivs[i - 1]).find('> span').last().attr('data-linenumber')) : 0
$(linenumberdivs[i]).find('> span').each((key, value) => {
$(value).attr('data-linenumber', startnumber + key + 1)
})
}
}
// show yaml meta paring error
if (md.metaError) {
var warning = result.find('div#meta-error')
if (warning && warning.length > 0) {
warning.text(md.metaError)
} else {
warning = $(`<div id="meta-error" class="alert alert-warning">${escapeHTML(md.metaError)}</div>`)
result.prepend(warning)
}
}
return result
}
window.postProcess = postProcess
var domevents = Object.getOwnPropertyNames(document).concat(Object.getOwnPropertyNames(Object.getPrototypeOf(Object.getPrototypeOf(document)))).concat(Object.getOwnPropertyNames(Object.getPrototypeOf(window))).filter(function (i) {
return !i.indexOf('on') && (document[i] === null || typeof document[i] === 'function')
}).filter(function (elem, pos, self) {
return self.indexOf(elem) === pos
})
export function removeDOMEvents (view) {
for (var i = 0, l = domevents.length; i < l; i++) {
view.find('[' + domevents[i] + ']').removeAttr(domevents[i])
}
}
window.removeDOMEvents = removeDOMEvents
function generateCleanHTML (view) {
const src = view.clone()
const eles = src.find('*')
// remove syncscroll parts
eles.removeClass('part')
src.find('*[class=""]').removeAttr('class')
eles.removeAttr('data-startline data-endline')
src.find("a[href^='#'][smoothhashscroll]").removeAttr('smoothhashscroll')
// remove gist content
src.find('code[data-gist-id]').children().remove()
// disable todo list
src.find('input.task-list-item-checkbox').attr('disabled', '')
// replace emoji image path
src.find('img.emoji').each((key, value) => {
let name = $(value).attr('alt')
name = name.substr(1)
name = name.slice(0, name.length - 1)
$(value).attr('src', `https://cdn.jsdelivr.net/npm/@hackmd/[email protected]/dist/images/basic/${name}.png`)
})
// replace video to iframe
src.find('div[data-videoid]').each((key, value) => {
const id = $(value).attr('data-videoid')
const style = $(value).attr('style')
let url = null
if ($(value).hasClass('youtube')) {
url = 'https://www.youtube.com/embed/'
} else if ($(value).hasClass('vimeo')) {
url = 'https://player.vimeo.com/video/'
}
if (url) {
const iframe = $('<iframe frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>')
iframe.attr('src', url + id)
iframe.attr('style', style)
$(value).html(iframe)
}
})
return src
}
export function exportToRawHTML (view) {
const filename = `${renderFilename(ui.area.markdown)}.html`
const src = generateCleanHTML(view)
$(src).find('a.anchor').remove()
const html = src[0].outerHTML
const blob = new Blob([html], {
type: 'text/html;charset=utf-8'
})
saveAs(blob, filename, true)
}
// extract markdown body to html and compile to template
export function exportToHTML (view) {
const title = renderTitle(ui.area.markdown)
const filename = `${renderFilename(ui.area.markdown)}.html`
const src = generateCleanHTML(view)
// generate toc
const toc = $('#ui-toc').clone()
toc.find('*').removeClass('active').find("a[href^='#'][smoothhashscroll]").removeAttr('smoothhashscroll')
const tocAffix = $('#ui-toc-affix').clone()
tocAffix.find('*').removeClass('active').find("a[href^='#'][smoothhashscroll]").removeAttr('smoothhashscroll')
// generate html via template
$.get(`${serverurl}/build/html.min.css`, css => {
$.get(`${serverurl}/views/html.hbs`, data => {
const template = window.Handlebars.compile(data)
const context = {
url: serverurl,
title,
css,
html: src[0].outerHTML,
'ui-toc': toc.html(),
'ui-toc-affix': tocAffix.html(),
lang: (md && md.meta && md.meta.lang) ? `lang="${escapeAttrValue(md.meta.lang)}"` : null,
dir: (md && md.meta && md.meta.dir) ? `dir="${escapeAttrValue(md.meta.dir)}"` : null
}
const html = template(context)
// console.log(html);
const blob = new Blob([html], {
type: 'text/html;charset=utf-8'
})
saveAs(blob, filename, true)
})
})
}
// jQuery sortByDepth
$.fn.sortByDepth = function () {
const ar = this.map(function () {
return {
length: $(this).parents().length,
elt: this
}
}).get()
const result = []
let i = ar.length
ar.sort((a, b) => a.length - b.length)
while (i--) {
result.push(ar[i].elt)
}
return $(result)
}
function toggleTodoEvent (e) {
const startline = $(this).closest('li').attr('data-startline') - 1
const line = window.editor.getLine(startline)
const matches = line.match(/^[>\s-]*[-+*]\s\[([x ])\]/)
if (matches && matches.length >= 2) {
let checked = null
if (matches[1] === 'x') { checked = true } else if (matches[1] === ' ') { checked = false }
const replacements = matches[0].match(/(^[>\s-]*[-+*]\s\[)([x ])(\])/)
window.editor.replaceRange(checked ? ' ' : 'x', {
line: startline,
ch: replacements[1].length
}, {
line: startline,
ch: replacements[1].length + 1
}, '+input')
}
}
// remove hash
function removeHash () {
history.pushState('', document.title, window.location.pathname + window.location.search)
}
let tocExpand = false
function checkExpandToggle () {
const toc = $('.ui-toc-dropdown .toc')
const expand = $('.expand-toggle.expand-all')
const collapse = $('.expand-toggle.collapse-all')
if (!tocExpand) {
toc.removeClass('expand')
expand.show()
collapse.hide()
} else {
toc.addClass('expand')
expand.hide()
collapse.show()
}
}
// toc
export function generateToc (id) {
const target = $(`#${id}`)
target.html('')
/* eslint-disable no-unused-vars */
var tocOptions = md.meta.toc || {}
var maxLevel = (typeof tocOptions.maxLevel === 'number' && tocOptions.maxLevel > 0) ? tocOptions.maxLevel : window.defaultTocDepth
var toc = new window.Toc('doc', {
level: maxLevel,
top: -1,
class: 'toc',
ulClass: 'nav',
targetId: id,
process: getHeaderContent
})
/* eslint-enable no-unused-vars */
if (target.text() === 'undefined') { target.html('') }
checkExpandToggle()
const tocMenu = $('body').children('.toc-menu')
target.append(tocMenu.clone().show())
const toggle = $('.expand-toggle', target)
const backtotop = $('.back-to-top', target)
const gotobottom = $('.go-to-bottom', target)
toggle.click(e => {
e.preventDefault()
e.stopPropagation()
tocExpand = !tocExpand
checkExpandToggle()
})
backtotop.click(e => {
e.preventDefault()
e.stopPropagation()
if (window.scrollToTop) { window.scrollToTop() }
removeHash()
})
gotobottom.click(e => {
e.preventDefault()
e.stopPropagation()
if (window.scrollToBottom) { window.scrollToBottom() }
removeHash()
})
}
// smooth all hash trigger scrolling
export function smoothHashScroll () {
const hashElements = $("a[href^='#']:not([smoothhashscroll])").toArray()
for (const element of hashElements) {
const $element = $(element)
const hash = element.hash
if (hash) {
$element.on('click', function (e) {
// store hash
const hash = decodeURIComponent(this.hash)
// escape special characters in jquery selector
const $hash = $(hash.replace(/(:|\.|\[|\]|,)/g, '\\$1'))
// return if no element been selected
if ($hash.length <= 0) return
// prevent default anchor click behavior
e.preventDefault()
// animate
$('body, html').stop(true, true).animate({
scrollTop: $hash.offset().top
}, 100, 'linear', () => {
// when done, add hash to url
// (default click behaviour)
window.location.hash = hash
})
})
$element.attr('smoothhashscroll', '')
}
}
}
function imgPlayiframe (element, src) {
if (!$(element).attr('data-videoid')) return
const iframe = $("<iframe frameborder='0' webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>")
$(iframe).attr('src', `${src + $(element).attr('data-videoid')}?autoplay=1`)
$(element).find('img').css('visibility', 'hidden')
$(element).append(iframe)
}
const anchorForId = id => {
const anchor = document.createElement('a')
anchor.className = 'anchor hidden-xs'
anchor.href = `#${id}`
anchor.innerHTML = '<i class="fa fa-link"></i>'
anchor.title = id
return anchor
}
const createHeaderId = (headerContent, headerIds = null) => {
// to escape characters not allow in css and humanize
const slug = slugifyWithUTF8(headerContent)
let id