-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
393 lines (393 loc) · 10.9 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
MathJax.Hub.Config({
skipStartupTypeset: true,
showProcessingMessages: false,
tex2jax: {
inlineMath: [['$', '$'], ['\\(', '\\)']],
displayMath: [['$$', '$$'], ['\\[', '\\]']],
processEscapes: true
},
TeX: {
equationNumbers: {
autoNumber: 'AMS'
}
}
})
marked.setOptions({
smartLists: true,
smartypants: true
})
const Preview = {
delay: 0,
preview: null,
buffer: null,
timeout: null,
mjRunning: false,
oldText: null,
Init() {
this.preview = document.getElementById('viewer')
this.buffer = document.getElementById('buffer')
this.textarea = document.getElementById('getm')
this.wordcount = document.getElementById('wordcount')
this.charcount = document.getElementById('charcount')
this.save = document.getElementById('save')
},
SwapBuffers() {
let buffer = this.preview
let preview = this.buffer
this.buffer = buffer
this.preview = preview
buffer.style.display = 'none'
preview.style.display = 'flex'
},
Update() {
if (this.timeout) {
clearTimeout(this.timeout)
}
this.timeout = setTimeout(this.callback, this.delay)
},
CreatePreview() {
Preview.timeout = null
if (this.mjRunning) return
let text = this.textarea.value
if (text === this.oldtext) return
text = this.Escape(text)
this.buffer.innerHTML = this.oldtext = text
this.mjRunning = true
MathJax.Hub.Configured()
MathJax.Hub.Queue(['Typeset', MathJax.Hub, this.buffer], ['PreviewDone', this], ['resetEquationNumbers', MathJax.InputJax.TeX])
let viewer = document.getElementById('viewer').style.display == 'none' ? document.getElementById('buffer') : document.getElementById('viewer')
let regex = /\s+/gi
if (text !== '') {
let wordCount = viewer.innerText.trim().replace(regex, ' ').split(' ').length
let charCount = viewer.innerText.replace(regex, '').length
this.wordcount.innerHTML = `${wordCount} words`
this.charcount.innerHTML = `${charCount} chars`
this.save.disabled = false
} else {
this.wordcount.innerHTML = '0 words'
this.charcount.innerHTML = '0 chars'
this.save.disabled = true
}
mouseUp()
},
PreviewDone() {
this.mjRunning = false
text = this.buffer.innerHTML
text = this.PartialDescape(text)
this.buffer.innerHTML = marked(text)
document.querySelectorAll('code').forEach((block) => {
hljs.highlightBlock(block)
})
this.SwapBuffers()
},
Escape(html, encode) {
return html
.replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
},
PartialDescape(html) {
let lines = html.split('\n')
let out = ''
// is true when we are
// ```
// inside a code block
// ```
let inside_code = false
for (let i = 0; i < lines.length; i++) {
// a hack to properly rendre the blockquotes
if (lines[i].startsWith('>')) {
lines[i] = lines[i].replace(/>/g, '>')
}
// rendrer properly stuff like this
// ```c
// if (a > b)
// ```
if (inside_code) {
// inside the code we descape stuff
lines[i] = lines[i]
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, '\'')
}
if (lines[i].startsWith('```')) {
inside_code = !inside_code
}
out += `${lines[i]}\n`
}
return out
},
// The idea here is to perform fast updates.
// See http://stackoverflow.com/questions/11228558/let-pagedown-and-mathjax-work-together/21563171?noredirect=1#comment46869312_21563171
// But our implementation is a bit buggy: flickering, bad rendering when someone types very fast.
//
// If you want to enable such buggy fast updates, you should
// add something like onkeypress="Preview.UpdateKeyPress(event)" to textarea's attributes.
UpdateKeyPress({
keyCode
}) {
if (keyCode < 16 || keyCode > 47) {
this.preview.innerHTML = `<p>${marked(this.textarea.value)}</p>`
this.buffer.innerHTML = `<p>${marked(this.textarea.value)}</p>`
}
this.Update()
}
}
Preview.callback = MathJax.Callback(['CreatePreview', Preview])
Preview.callback.autoReset = true
Preview.Init()
Preview.Update()
const mouseUp = () => {
let mark = document.getElementById('getm')
let lineno = document.getElementById('lineno')
let colno = document.getElementById('colno')
let textLines = mark.value.substr(0, mark.selectionStart).split('\n')
lineno.innerHTML = `Line ${textLines.length}`
colno.innerHTML = `Col ${textLines[textLines.length - 1].length}`
}
const toggleSwitch = document.querySelector('.theme-switch input[type="checkbox"]')
if (localStorage.getItem('marcdownTheme') == 'dark') {
document.documentElement.setAttribute('data-theme', 'dark')
document.querySelector('meta[name=theme-color]').setAttribute('content', '#282a36')
toggleSwitch.checked = true
localStorage.setItem('marcdownTheme', 'dark')
} else {
document.documentElement.setAttribute('data-theme', 'light')
document.querySelector('meta[name=theme-color]').setAttribute('content', '#DAE5ED')
toggleSwitch.checked = false
localStorage.setItem('marcdownTheme', 'light')
}
const switchTheme = ({
target
}) => {
if (target.checked) {
document.documentElement.setAttribute('data-theme', 'dark')
document.querySelector('meta[name=theme-color]').setAttribute('content', '#282a36')
localStorage.setItem('marcdownTheme', 'dark')
} else {
document.documentElement.setAttribute('data-theme', 'light')
document.querySelector('meta[name=theme-color]').setAttribute('content', '#DAE5ED')
localStorage.setItem('marcdownTheme', 'light')
}
}
toggleSwitch.addEventListener('change', switchTheme, false)
const download = () => {
let text = document.getElementById('getm').value
text = text.replace(/\n/g, '\r\n')
let blob = new Blob([text], {
type: 'text/plain'
})
let anchor = document.createElement('a')
anchor.download = 'markdown.md'
anchor.href = window.URL.createObjectURL(blob)
anchor.target = '_blank'
anchor.style.display = 'none'
document.body.appendChild(anchor)
anchor.click()
document.body.removeChild(anchor)
}
const openFile = ({
target
}) => {
let input = target
let reader = new FileReader()
reader.onload = () => {
document.getElementById('getm').value = reader.result
input.value = ''
Preview.Update()
}
reader.readAsText(input.files[0])
}
const handleFileSelect = (evt) => {
evt.stopPropagation()
evt.preventDefault()
const files = evt.dataTransfer.files
const reader = new FileReader()
reader.onload = ({
target
}) => {
document.getElementById('getm').value = target.result
Preview.Update()
}
reader.readAsText(files[0], 'UTF-8')
}
const handleDragOver = (evt) => {
evt.stopPropagation()
evt.preventDefault()
evt.dataTransfer.dropEffect = 'copy'
}
let dropZone = document.getElementById('getm')
dropZone.addEventListener('dragover', handleDragOver, false)
dropZone.addEventListener('drop', handleFileSelect, false)
document.onkeyup = ({
altKey,
which
}) => {
if (altKey && which == 79) {
document.getElementById('file').click()
} else if (altKey && which == 83) {
document.getElementById('save').click()
}
}
const apply = (e) => {
let myField = document.getElementById('getm')
let myValueBefore
let myValueAfter
switch (e) {
case 'bold':
myValueBefore = '**'
myValueAfter = '**'
break
case 'italic':
myValueBefore = '*'
myValueAfter = '*'
break
case 'strike':
myValueBefore = '~'
myValueAfter = '~'
break
case 'h1':
myValueBefore = '# '
myValueAfter = ''
break
case 'h2':
myValueBefore = '## '
myValueAfter = ''
break
case 'h3':
myValueBefore = '### '
myValueAfter = ''
break
case 'bq':
myValueBefore = '> '
myValueAfter = ''
break
case 'ol':
myValueBefore = '1. '
myValueAfter = ''
break
case 'ul':
myValueBefore = '- '
myValueAfter = ''
break
case 'ic':
myValueBefore = '`'
myValueAfter = '`'
break
case 'bc':
myValueBefore = '```\n'
myValueAfter = '\n```'
break
case 'link':
myValueBefore = '['
myValueAfter = ']()'
break
case 'check':
myValueBefore = '- [x] '
myValueAfter = ''
break
case 'image':
myValueBefore = '![alt text](image.jpg)'
myValueAfter = ''
break
case 'hr':
myValueBefore = '---\n'
myValueAfter = ''
break
case 'table':
myValueBefore = '| Header | Title |\n| ----------- | ----------- |\n| Paragraph | Text |\n'
myValueAfter = ''
break
}
if (document.selection) {
myField.focus()
document.selection.createRange().text = myValueBefore + document.selection.createRange().text + myValueAfter
} else if (myField.selectionStart || myField.selectionStart == '0') {
let startPos = myField.selectionStart
let endPos = myField.selectionEnd
myField.value = myField.value.substring(0, startPos) + myValueBefore + myField.value.substring(startPos, endPos) + myValueAfter + myField.value.substring(endPos, myField.value.length)
myField.selectionStart = startPos + myValueBefore.length
myField.selectionEnd = endPos + myValueBefore.length
myField.focus()
}
Preview.Update()
}
const slide = (e) => {
let viewer = document.getElementById('viewer')
let mark = document.getElementById('getm')
switch (e) {
case 'nill':
viewer.style.width = '100vw'
viewer.style.padding = '16px'
mark.style.width = '0'
mark.style.padding = '0'
break
case 'half':
viewer.style.width = '50vw'
viewer.style.padding = '16px'
mark.style.width = '50vw'
mark.style.padding = '16px'
break
case 'full':
viewer.style.width = '0'
viewer.style.padding = '0'
mark.style.width = '100vw'
mark.style.padding = '16px'
break
}
}
const modal = document.querySelector('.modal')
const trigger = document.querySelector('.trigger')
const closeButton = document.querySelector('.close-button')
const toggleModal = () => modal.classList.toggle('show-modal')
const windowOnClick = ({
target
}) => {
if (target === modal) {
toggleModal()
}
}
trigger.addEventListener('click', toggleModal)
closeButton.addEventListener('click', toggleModal)
window.addEventListener('click', windowOnClick)
let pwaInstalled = localStorage.getItem('pwaInstalled') == 'yes'
if (window.matchMedia('(display-mode: standalone)').matches) {
localStorage.setItem('pwaInstalled', 'yes')
pwaInstalled = true
}
if (window.navigator.standalone === true) {
localStorage.setItem('pwaInstalled', 'yes')
pwaInstalled = true
}
if (pwaInstalled) {
document.getElementById('installPWA').style.display = 'none'
} else {
document.getElementById('installPWA').style.display = 'inline-flex'
}
let deferredPrompt = null
window.addEventListener('beforeinstallprompt', (e) => {
deferredPrompt = e
})
async function installPWA() {
if (deferredPrompt) {
deferredPrompt.prompt()
deferredPrompt.userChoice.then(({
outcome
}) => {
if (outcome === 'accepted') {
console.log('Your PWA has been installed')
} else {
console.log('User chose to not install your PWA')
}
deferredPrompt = null
})
}
}
window.addEventListener('appinstalled', (evt) => {
localStorage.setItem('pwaInstalled', 'yes')
pwaInstalled = true
document.getElementById('installPWA').style.display = 'none'
})