-
Notifications
You must be signed in to change notification settings - Fork 406
/
index.js
3333 lines (3152 loc) · 100 KB
/
index.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 */
/* eslint no-console: ["error", { allow: ["warn", "error", "debug"] }] */
/* global CodeMirror, Cookies, moment, Spinner, Idle, serverurl,
key, Dropbox, ot, hex2rgb, Visibility */
import TurndownService from 'turndown'
import { saveAs } from 'file-saver'
import randomColor from 'randomcolor'
import store from 'store'
import hljs from 'highlight.js'
import url from 'wurl'
import _ from 'lodash'
import List from 'list.js'
import {
checkLoginStateChanged,
setloginStateChangeEvent
} from './lib/common/login'
import {
debug,
DROPBOX_APP_KEY,
noteid,
noteurl,
urlpath,
version
} from './lib/config'
import {
autoLinkify,
deduplicatedHeaderId,
exportToHTML,
exportToRawHTML,
removeDOMEvents,
finishView,
generateToc,
isValidURL,
md,
parseMeta,
postProcess,
renderFilename,
renderTOC,
renderTags,
renderTitle,
scrollToHash,
smoothHashScroll,
updateLastChange,
updateLastChangeUser,
updateOwner
} from './extra'
import {
clearMap,
setupSyncAreas,
syncScrollToEdit,
syncScrollToView
} from './lib/syncscroll'
import {
writeHistory,
deleteServerHistory,
getHistory,
saveHistory,
removeHistory
} from './history'
import { preventXSS } from './render'
import Editor from './lib/editor'
import getUIElements from './lib/editor/ui-elements'
import modeType from './lib/modeType'
import appState from './lib/appState'
require('../vendor/showup/showup')
require('../css/index.css')
require('../css/extra.css')
require('../css/slide-preview.css')
require('../css/site.css')
require('highlight.js/styles/github-gist.css')
var defaultTextHeight = 20
var viewportMargin = 20
var defaultEditorMode = 'gfm'
var idleTime = 300000 // 5 mins
var updateViewDebounce = 100
var cursorMenuThrottle = 50
var cursorActivityDebounce = 50
var cursorAnimatePeriod = 100
var supportContainers = ['success', 'info', 'warning', 'danger']
var supportCodeModes = ['javascript', 'typescript', 'jsx', 'htmlmixed', 'htmlembedded', 'css', 'xml', 'clike', 'clojure', 'ruby', 'python', 'shell', 'php', 'sql', 'haskell', 'coffeescript', 'yaml', 'pug', 'lua', 'cmake', 'nginx', 'perl', 'sass', 'r', 'dockerfile', 'tiddlywiki', 'mediawiki', 'go', 'gherkin'].concat(hljs.listLanguages())
var supportCharts = ['sequence', 'flow', 'graphviz', 'mermaid', 'abc']
var supportHeaders = [
{
text: '# h1',
search: '#'
},
{
text: '## h2',
search: '##'
},
{
text: '### h3',
search: '###'
},
{
text: '#### h4',
search: '####'
},
{
text: '##### h5',
search: '#####'
},
{
text: '###### h6',
search: '######'
},
{
text: '###### tags: `example`',
search: '###### tags:'
}
]
const supportReferrals = [
{
text: '[reference link]',
search: '[]'
},
{
text: '[reference]: https:// "title"',
search: '[]:'
},
{
text: '[^footnote link]',
search: '[^]'
},
{
text: '[^footnote reference]: https:// "title"',
search: '[^]:'
},
{
text: '^[inline footnote]',
search: '^[]'
},
{
text: '[link text][reference]',
search: '[][]'
},
{
text: '[link text](https:// "title")',
search: '[]()'
},
{
text: '![image alt][reference]',
search: '![][]'
},
{
text: '',
search: '![]()'
},
{
text: '',
search: '![]()'
},
{
text: '[TOC]',
search: '[]'
}
]
const supportExternals = [
{
text: '{%youtube youtubeid %}',
search: 'youtube'
},
{
text: '{%vimeo vimeoid %}',
search: 'vimeo'
},
{
text: '{%gist gistid %}',
search: 'gist'
},
{
text: '{%slideshare slideshareid %}',
search: 'slideshare'
},
{
text: '{%speakerdeck speakerdeckid %}',
search: 'speakerdeck'
},
{
text: '{%pdf pdfurl %}',
search: 'pdf'
}
]
const supportExtraTags = [
{
text: '[name tag]',
search: '[]',
command: function () {
return '[name=' + personalInfo.name + ']'
}
},
{
text: '[time tag]',
search: '[]',
command: function () {
return '[time=' + moment().format('llll') + ']'
}
},
{
text: '[my color tag]',
search: '[]',
command: function () {
return '[color=' + personalInfo.color + ']'
}
},
{
text: '[random color tag]',
search: '[]',
command: function () {
var color = randomColor()
return '[color=' + color + ']'
}
}
]
const statusType = {
connected: {
msg: 'CONNECTED',
label: 'label-warning',
fa: 'fa-wifi'
},
online: {
msg: 'ONLINE',
label: 'label-primary',
fa: 'fa-users'
},
offline: {
msg: 'OFFLINE',
label: 'label-danger',
fa: 'fa-plug'
}
}
// global vars
window.loaded = false
let needRefresh = false
let isDirty = false
let editShown = false
let visibleXS = false
let visibleSM = false
let visibleMD = false
let visibleLG = false
const isTouchDevice = 'ontouchstart' in document.documentElement
let currentStatus = statusType.offline
let lastInfo = {
needRestore: false,
cursor: null,
scroll: null,
edit: {
scroll: {
left: null,
top: null
},
cursor: {
line: null,
ch: null
},
selections: null
},
view: {
scroll: {
left: null,
top: null
}
},
history: null
}
let personalInfo = {}
let onlineUsers = []
const fileTypes = {
'pl': 'perl',
'cgi': 'perl',
'js': 'javascript',
'php': 'php',
'sh': 'bash',
'rb': 'ruby',
'html': 'html',
'py': 'python'
}
// editor settings
const textit = document.getElementById('textit')
if (!textit) {
throw new Error('There was no textit area!')
}
const editorInstance = new Editor()
var editor = editorInstance.init(textit)
// FIXME: global referncing in jquery-textcomplete patch
window.editor = editor
defaultTextHeight = parseInt($('.CodeMirror').css('line-height'))
// initalize ui reference
const ui = getUIElements()
// page actions
var opts = {
lines: 11, // The number of lines to draw
length: 20, // The length of each line
width: 2, // The line thickness
radius: 30, // The radius of the inner circle
corners: 0, // Corner roundness (0..1)
rotate: 0, // The rotation offset
direction: 1, // 1: clockwise, -1: counterclockwise
color: '#000', // #rgb or #rrggbb or array of colors
speed: 1.1, // Rounds per second
trail: 60, // Afterglow percentage
shadow: false, // Whether to render a shadow
hwaccel: true, // Whether to use hardware acceleration
className: 'spinner', // The CSS class to assign to the spinner
zIndex: 2e9, // The z-index (defaults to 2000000000)
top: '50%', // Top position relative to parent
left: '50%' // Left position relative to parent
}
/* eslint-disable no-unused-vars */
var spinner = new Spinner(opts).spin(ui.spinner[0])
/* eslint-enable no-unused-vars */
// idle
var idle = new Idle({
onAway: function () {
idle.isAway = true
emitUserStatus()
updateOnlineStatus()
},
onAwayBack: function () {
idle.isAway = false
emitUserStatus()
updateOnlineStatus()
setHaveUnreadChanges(false)
updateTitleReminder()
},
awayTimeout: idleTime
})
ui.area.codemirror.on('touchstart', function () {
idle.onActive()
})
var haveUnreadChanges = false
function setHaveUnreadChanges (bool) {
if (!window.loaded) return
if (bool && (idle.isAway || Visibility.hidden())) {
haveUnreadChanges = true
} else if (!bool && !idle.isAway && !Visibility.hidden()) {
haveUnreadChanges = false
}
}
function updateTitleReminder () {
if (!window.loaded) return
if (haveUnreadChanges) {
document.title = '• ' + renderTitle(ui.area.markdown)
} else {
document.title = renderTitle(ui.area.markdown)
}
}
function setRefreshModal (status) {
$('#refreshModal').modal('show')
$('#refreshModal').find('.modal-body > div').hide()
$('#refreshModal').find('.' + status).show()
}
function setNeedRefresh () {
needRefresh = true
editor.setOption('readOnly', true)
socket.disconnect()
showStatus(statusType.offline)
}
setloginStateChangeEvent(function () {
setRefreshModal('user-state-changed')
setNeedRefresh()
})
// visibility
var wasFocus = false
Visibility.change(function (e, state) {
var hidden = Visibility.hidden()
if (hidden) {
if (editorHasFocus()) {
wasFocus = true
editor.getInputField().blur()
}
} else {
if (wasFocus) {
if (!visibleXS) {
editor.focus()
editor.refresh()
}
wasFocus = false
}
setHaveUnreadChanges(false)
}
updateTitleReminder()
})
// when page ready
$(document).ready(function () {
idle.checkAway()
checkResponsive()
// if in smaller screen, we don't need advanced scrollbar
var scrollbarStyle
if (visibleXS) {
scrollbarStyle = 'native'
} else {
scrollbarStyle = 'overlay'
}
if (scrollbarStyle !== editor.getOption('scrollbarStyle')) {
editor.setOption('scrollbarStyle', scrollbarStyle)
clearMap()
}
checkEditorStyle()
/* cache dom references */
var $body = $('body')
/* we need this only on touch devices */
if (isTouchDevice) {
/* bind events */
$(document)
.on('focus', 'textarea, input', function () {
$body.addClass('fixfixed')
})
.on('blur', 'textarea, input', function () {
$body.removeClass('fixfixed')
})
}
// Re-enable nightmode
if (store.get('nightMode') || Cookies.get('nightMode')) {
$body.addClass('night')
ui.toolbar.night.addClass('active')
}
// showup
$().showUp('.navbar', {
upClass: 'navbar-hide',
downClass: 'navbar-show'
})
// tooltip
$('[data-toggle="tooltip"]').tooltip()
// shortcuts
// allow on all tags
key.filter = function (e) { return true }
key('ctrl+alt+e', function (e) {
changeMode(modeType.edit)
})
key('ctrl+alt+v', function (e) {
changeMode(modeType.view)
})
key('ctrl+alt+b', function (e) {
changeMode(modeType.both)
})
// toggle-dropdown
$(document).on('click', '.toggle-dropdown .dropdown-menu', function (e) {
e.stopPropagation()
})
})
// when page resize
$(window).resize(function () {
checkLayout()
checkEditorStyle()
checkTocStyle()
checkCursorMenu()
windowResize()
})
// when page unload
$(window).on('unload', function () {
// updateHistoryInner();
})
$(window).on('error', function () {
// setNeedRefresh();
})
setupSyncAreas(ui.area.codemirrorScroll, ui.area.view, ui.area.markdown, editor)
function autoSyncscroll () {
if (editorHasFocus()) {
syncScrollToView()
} else {
syncScrollToEdit()
}
}
var windowResizeDebounce = 200
var windowResize = _.debounce(windowResizeInner, windowResizeDebounce)
function windowResizeInner (callback) {
checkLayout()
checkResponsive()
checkEditorStyle()
checkTocStyle()
checkCursorMenu()
// refresh editor
if (window.loaded) {
if (editor.getOption('scrollbarStyle') === 'native') {
setTimeout(function () {
clearMap()
autoSyncscroll()
updateScrollspy()
if (callback && typeof callback === 'function') { callback() }
}, 1)
} else {
// force it load all docs at once to prevent scroll knob blink
editor.setOption('viewportMargin', Infinity)
setTimeout(function () {
clearMap()
autoSyncscroll()
editor.setOption('viewportMargin', viewportMargin)
// add or update user cursors
for (var i = 0; i < onlineUsers.length; i++) {
if (onlineUsers[i].id !== personalInfo.id) { buildCursor(onlineUsers[i]) }
}
updateScrollspy()
if (callback && typeof callback === 'function') { callback() }
}, 1)
}
}
}
function checkLayout () {
var navbarHieght = $('.navbar').outerHeight()
$('body').css('padding-top', navbarHieght + 'px')
}
function editorHasFocus () {
return $(editor.getInputField()).is(':focus')
}
// 768-792px have a gap
function checkResponsive () {
visibleXS = $('.visible-xs').is(':visible')
visibleSM = $('.visible-sm').is(':visible')
visibleMD = $('.visible-md').is(':visible')
visibleLG = $('.visible-lg').is(':visible')
if (visibleXS && appState.currentMode === modeType.both) {
if (editorHasFocus()) { changeMode(modeType.edit) } else { changeMode(modeType.view) }
}
emitUserStatus()
}
var lastEditorWidth = 0
var previousFocusOnEditor = null
function checkEditorStyle () {
var desireHeight = editorInstance.statusBar ? (ui.area.edit.height() - editorInstance.statusBar.outerHeight()) : ui.area.edit.height()
if (editorInstance.toolBar) {
desireHeight = desireHeight - editorInstance.toolBar.outerHeight()
}
// set editor height and min height based on scrollbar style and mode
var scrollbarStyle = editor.getOption('scrollbarStyle')
if (scrollbarStyle === 'overlay' || appState.currentMode === modeType.both) {
ui.area.codemirrorScroll.css('height', desireHeight + 'px')
ui.area.codemirrorScroll.css('min-height', '')
checkEditorScrollbar()
} else if (scrollbarStyle === 'native') {
ui.area.codemirrorScroll.css('height', '')
ui.area.codemirrorScroll.css('min-height', desireHeight + 'px')
}
// workaround editor will have wrong doc height when editor height changed
editor.setSize(null, ui.area.edit.height())
// make editor resizable
if (!ui.area.resize.handle.length) {
ui.area.edit.resizable({
handles: 'e',
maxWidth: $(window).width() * 0.7,
minWidth: $(window).width() * 0.2,
create: function (e, ui) {
$(this).parent().on('resize', function (e) {
e.stopPropagation()
})
},
start: function (e) {
editor.setOption('viewportMargin', Infinity)
},
resize: function (e) {
ui.area.resize.syncToggle.stop(true, true).show()
checkTocStyle()
},
stop: function (e) {
lastEditorWidth = ui.area.edit.width()
// workaround that scroll event bindings
window.preventSyncScrollToView = 2
window.preventSyncScrollToEdit = true
editor.setOption('viewportMargin', viewportMargin)
if (editorHasFocus()) {
windowResizeInner(function () {
ui.area.codemirrorScroll.scroll()
})
} else {
windowResizeInner(function () {
ui.area.view.scroll()
})
}
checkEditorScrollbar()
}
})
ui.area.resize.handle = $('.ui-resizable-handle')
}
if (!ui.area.resize.syncToggle.length) {
ui.area.resize.syncToggle = $('<button class="btn btn-lg btn-default ui-sync-toggle" title="Toggle sync scrolling"><i class="fa fa-link fa-fw"></i></button>')
ui.area.resize.syncToggle.hover(function () {
previousFocusOnEditor = editorHasFocus()
}, function () {
previousFocusOnEditor = null
})
ui.area.resize.syncToggle.click(function () {
appState.syncscroll = !appState.syncscroll
checkSyncToggle()
})
ui.area.resize.handle.append(ui.area.resize.syncToggle)
ui.area.resize.syncToggle.hide()
ui.area.resize.handle.hover(function () {
ui.area.resize.syncToggle.stop(true, true).delay(200).fadeIn(100)
}, function () {
ui.area.resize.syncToggle.stop(true, true).delay(300).fadeOut(300)
})
}
}
function checkSyncToggle () {
if (appState.syncscroll) {
if (previousFocusOnEditor) {
window.preventSyncScrollToView = false
syncScrollToView()
} else {
window.preventSyncScrollToEdit = false
syncScrollToEdit()
}
ui.area.resize.syncToggle.find('i').removeClass('fa-unlink').addClass('fa-link')
} else {
ui.area.resize.syncToggle.find('i').removeClass('fa-link').addClass('fa-unlink')
}
}
var checkEditorScrollbar = _.debounce(function () {
editor.operation(checkEditorScrollbarInner)
}, 50)
function checkEditorScrollbarInner () {
// workaround simple scroll bar knob
// will get wrong position when editor height changed
var scrollInfo = editor.getScrollInfo()
editor.scrollTo(null, scrollInfo.top - 1)
editor.scrollTo(null, scrollInfo.top)
}
function checkTocStyle () {
// toc right
var paddingRight = parseFloat(ui.area.markdown.css('padding-right'))
var right = ($(window).width() - (ui.area.markdown.offset().left + ui.area.markdown.outerWidth() - paddingRight))
ui.toc.toc.css('right', right + 'px')
// affix toc left
var newbool
var rightMargin = (ui.area.markdown.parent().outerWidth() - ui.area.markdown.outerWidth()) / 2
// for ipad or wider device
if (rightMargin >= 133) {
newbool = true
var affixLeftMargin = (ui.toc.affix.outerWidth() - ui.toc.affix.width()) / 2
var left = ui.area.markdown.offset().left + ui.area.markdown.outerWidth() - affixLeftMargin
ui.toc.affix.css('left', left + 'px')
ui.toc.affix.css('width', rightMargin + 'px')
} else {
newbool = false
}
// toc scrollspy
ui.toc.toc.removeClass('scrollspy-body, scrollspy-view')
ui.toc.affix.removeClass('scrollspy-body, scrollspy-view')
if (appState.currentMode === modeType.both) {
ui.toc.toc.addClass('scrollspy-view')
ui.toc.affix.addClass('scrollspy-view')
} else if (appState.currentMode !== modeType.both && !newbool) {
ui.toc.toc.addClass('scrollspy-body')
ui.toc.affix.addClass('scrollspy-body')
} else {
ui.toc.toc.addClass('scrollspy-view')
ui.toc.affix.addClass('scrollspy-body')
}
if (newbool !== enoughForAffixToc) {
enoughForAffixToc = newbool
generateScrollspy()
}
}
function showStatus (type, num) {
currentStatus = type
var shortStatus = ui.toolbar.shortStatus
var status = ui.toolbar.status
var label = $('<span class="label"></span>')
var fa = $('<i class="fa"></i>')
var msg = ''
var shortMsg = ''
shortStatus.html('')
status.html('')
switch (currentStatus) {
case statusType.connected:
label.addClass(statusType.connected.label)
fa.addClass(statusType.connected.fa)
msg = statusType.connected.msg
break
case statusType.online:
label.addClass(statusType.online.label)
fa.addClass(statusType.online.fa)
shortMsg = num
msg = num + ' ' + statusType.online.msg
break
case statusType.offline:
label.addClass(statusType.offline.label)
fa.addClass(statusType.offline.fa)
msg = statusType.offline.msg
break
}
label.append(fa)
var shortLabel = label.clone()
shortLabel.append(' ' + shortMsg)
shortStatus.append(shortLabel)
label.append(' ' + msg)
status.append(label)
}
function toggleMode () {
switch (appState.currentMode) {
case modeType.edit:
changeMode(modeType.view)
break
case modeType.view:
changeMode(modeType.edit)
break
case modeType.both:
changeMode(modeType.view)
break
}
}
var lastMode = null
function changeMode (type) {
// lock navbar to prevent it hide after changeMode
lockNavbar()
saveInfo()
if (type) {
lastMode = appState.currentMode
appState.currentMode = type
}
var responsiveClass = 'col-lg-6 col-md-6 col-sm-6'
var scrollClass = 'ui-scrollable'
ui.area.codemirror.removeClass(scrollClass)
ui.area.edit.removeClass(responsiveClass)
ui.area.view.removeClass(scrollClass)
ui.area.view.removeClass(responsiveClass)
switch (appState.currentMode) {
case modeType.edit:
ui.area.edit.show()
ui.area.view.hide()
if (!editShown) {
editor.refresh()
editShown = true
}
break
case modeType.view:
ui.area.edit.hide()
ui.area.view.show()
break
case modeType.both:
ui.area.codemirror.addClass(scrollClass)
ui.area.edit.addClass(responsiveClass).show()
ui.area.view.addClass(scrollClass)
ui.area.view.show()
break
}
// save mode to url
if (history.replaceState && window.loaded) history.replaceState(null, '', serverurl + '/' + noteid + '?' + appState.currentMode.name)
if (appState.currentMode === modeType.view) {
editor.getInputField().blur()
}
if (appState.currentMode === modeType.edit || appState.currentMode === modeType.both) {
// add and update status bar
if (!editorInstance.statusBar) {
editorInstance.addStatusBar()
editorInstance.updateStatusBar()
}
// add and update tool bar
if (!editorInstance.toolBar) {
editorInstance.addToolBar()
}
// work around foldGutter might not init properly
editor.setOption('foldGutter', false)
editor.setOption('foldGutter', true)
}
if (appState.currentMode !== modeType.edit) {
$(document.body).css('background-color', 'white')
updateView()
} else {
$(document.body).css('background-color', ui.area.codemirror.css('background-color'))
}
// check resizable editor style
if (appState.currentMode === modeType.both) {
if (lastEditorWidth > 0) {
ui.area.edit.css('width', lastEditorWidth + 'px')
} else {
ui.area.edit.css('width', '')
}
ui.area.resize.handle.show()
} else {
ui.area.edit.css('width', '')
ui.area.resize.handle.hide()
}
windowResizeInner()
restoreInfo()
if (lastMode === modeType.view && appState.currentMode === modeType.both) {
window.preventSyncScrollToView = 2
syncScrollToEdit(null, true)
}
if (lastMode === modeType.edit && appState.currentMode === modeType.both) {
window.preventSyncScrollToEdit = 2
syncScrollToView(null, true)
}
if (lastMode === modeType.both && appState.currentMode !== modeType.both) {
window.preventSyncScrollToView = false
window.preventSyncScrollToEdit = false
}
if (lastMode !== modeType.edit && appState.currentMode === modeType.edit) {
editor.refresh()
}
$(document.body).scrollspy('refresh')
ui.area.view.scrollspy('refresh')
ui.toolbar.both.removeClass('active')
ui.toolbar.edit.removeClass('active')
ui.toolbar.view.removeClass('active')
var modeIcon = ui.toolbar.mode.find('i')
modeIcon.removeClass('fa-pencil').removeClass('fa-eye')
if (ui.area.edit.is(':visible') && ui.area.view.is(':visible')) { // both
ui.toolbar.both.addClass('active')
modeIcon.addClass('fa-eye')
} else if (ui.area.edit.is(':visible')) { // edit
ui.toolbar.edit.addClass('active')
modeIcon.addClass('fa-eye')
} else if (ui.area.view.is(':visible')) { // view
ui.toolbar.view.addClass('active')
modeIcon.addClass('fa-pencil')
}
unlockNavbar()
}
function lockNavbar () {
$('.navbar').addClass('locked')
}
var unlockNavbar = _.debounce(function () {
$('.navbar').removeClass('locked')
}, 200)
function showMessageModal (title, header, href, text, success) {
var modal = $('.message-modal')
modal.find('.modal-title').html(title)
modal.find('.modal-body h5').html(header)
if (href) { modal.find('.modal-body a').attr('href', href).text(text) } else { modal.find('.modal-body a').removeAttr('href').text(text) }
modal.find('.modal-footer button').removeClass('btn-default btn-success btn-danger')
if (success) { modal.find('.modal-footer button').addClass('btn-success') } else { modal.find('.modal-footer button').addClass('btn-danger') }
modal.modal('show')
}
// check if dropbox app key is set and load scripts
if (DROPBOX_APP_KEY) {
$('<script>')
.attr('type', 'text/javascript')
.attr('src', 'https://www.dropbox.com/static/api/2/dropins.js')
.attr('id', 'dropboxjs')
.attr('data-app-key', DROPBOX_APP_KEY)
.prop('async', true)
.prop('defer', true)
.appendTo('body')
} else {
ui.toolbar.import.dropbox.hide()
ui.toolbar.export.dropbox.hide()
}
// button actions
// share
ui.toolbar.publish.attr('href', noteurl + '/publish')
// extra
// slide
ui.toolbar.extra.slide.attr('href', noteurl + '/slide')
// download
// markdown
ui.toolbar.download.markdown.click(function (e) {
e.preventDefault()
e.stopPropagation()
var filename = renderFilename(ui.area.markdown) + '.md'
var markdown = editor.getValue()
var blob = new Blob([markdown], {
type: 'text/markdown;charset=utf-8'
})
saveAs(blob, filename, true)
})
// html
ui.toolbar.download.html.click(function (e) {
e.preventDefault()
e.stopPropagation()
exportToHTML(ui.area.markdown)
})
// raw html
ui.toolbar.download.rawhtml.click(function (e) {
e.preventDefault()
e.stopPropagation()
exportToRawHTML(ui.area.markdown)
})
// pdf
ui.toolbar.download.pdf.attr('download', '').attr('href', noteurl + '/pdf')
// export to dropbox
ui.toolbar.export.dropbox.click(function () {
var filename = renderFilename(ui.area.markdown) + '.md'
var options = {
files: [
{
'url': noteurl + '/download',
'filename': filename
}
],
error: function (errorMessage) {
console.error(errorMessage)
}
}
Dropbox.save(options)
})
// export to gist
ui.toolbar.export.gist.attr('href', noteurl + '/gist')
// export to snippet
ui.toolbar.export.snippet.click(function () {
ui.spinner.show()
$.get(serverurl + '/auth/gitlab/callback/' + noteid + '/projects')
.done(function (data) {
$('#snippetExportModalAccessToken').val(data.accesstoken)
$('#snippetExportModalBaseURL').val(data.baseURL)
$('#snippetExportModalVersion').val(data.version)
$('#snippetExportModalLoading').hide()
$('#snippetExportModal').modal('toggle')
$('#snippetExportModalProjects').find('option').remove().end().append('<option value="init" selected="selected" disabled="disabled">Select From Available Projects</option>')
if (data.projects) {
data.projects.sort(function (a, b) {
return (a.path_with_namespace < b.path_with_namespace) ? -1 : ((a.path_with_namespace > b.path_with_namespace) ? 1 : 0)
})
data.projects.forEach(function (project) {
if (!project.snippets_enabled ||
(project.permissions.project_access === null && project.permissions.group_access === null) ||
(project.permissions.project_access !== null && project.permissions.project_access.access_level < 20)) {
return
}
$('<option>').val(project.id).text(project.path_with_namespace).appendTo('#snippetExportModalProjects')
})
$('#snippetExportModalProjects').prop('disabled', false)
}
$('#snippetExportModalLoading').hide()
})
.fail(function (data) {
showMessageModal('<i class="fa fa-gitlab"></i> Import from Snippet', 'Unable to fetch gitlab parameters :(', '', '', false)
})
.always(function () {
ui.spinner.hide()
})
})
// import from dropbox
ui.toolbar.import.dropbox.click(function () {
var options = {