-
-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathmain.js
More file actions
377 lines (338 loc) · 10.4 KB
/
main.js
File metadata and controls
377 lines (338 loc) · 10.4 KB
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
/* eslint-disable @typescript-eslint/no-var-requires */
document.addEventListener('DOMContentLoaded', function () {
let workingNote
let ignoreTextChange = false
let initialLoad = true
let lastValue, lastUUID, clientData
let renderNote = false
let showingUnsafeContentAlert = false
const componentRelay = new ComponentRelay({
targetWindow: window,
onReady: () => {
document.body.classList.add(componentRelay.platform)
document.body.classList.add(componentRelay.environment)
initializeEditor()
},
handleRequestForContentHeight: () => {
const baseHeight = 30
const toolbarHeight = document.querySelector('.editor-toolbar')?.offsetHeight
const scrollHeight = document.getElementsByClassName('CodeMirror-code')[0]?.scrollHeight
return baseHeight + toolbarHeight + scrollHeight
},
})
componentRelay.streamContextItem(async (note) => {
if (showingUnsafeContentAlert) {
return
}
if (note.uuid !== lastUUID) {
// Note changed, reset last values
lastValue = null
initialLoad = true
lastUUID = note.uuid
clientData = note.clientData
}
workingNote = note
// Only update UI on non-metadata updates.
if (note.isMetadataUpdate || !window.easymde) {
return
}
document
.getElementsByClassName('CodeMirror-code')[0]
.setAttribute('spellcheck', JSON.stringify(note.content.spellcheck))
const isUnsafeContent = checkIfUnsafeContent(note.content.text)
if (isUnsafeContent) {
const trustUnsafeContent = clientData['trustUnsafeContent'] ?? false
if (!trustUnsafeContent) {
const result = await showUnsafeContentAlert()
if (result) {
setTrustUnsafeContent(workingNote)
}
renderNote = result
} else {
renderNote = true
}
} else {
renderNote = true
}
/**
* If the user decides not to continue rendering the note,
* clear the editor and disable it.
*/
if (!renderNote) {
window.easymde.value('')
if (!window.easymde.isPreviewActive()) {
window.easymde.togglePreview()
}
return
}
if (note.content.text !== lastValue) {
ignoreTextChange = true
window.easymde.value(note.content.text)
toggleHighlightByLength(note.content.text)
ignoreTextChange = false
}
if (initialLoad) {
initialLoad = false
window.easymde.codemirror.getDoc().clearHistory()
const mode = clientData && clientData.mode
// Set initial editor mode
if (mode === 'preview') {
if (!window.easymde.isPreviewActive()) {
window.easymde.togglePreview()
}
} else if (mode === 'split') {
if (!window.easymde.isSideBySideActive()) {
window.easymde.toggleSideBySide()
}
// falback config
} else if (window.easymde.isPreviewActive()) {
window.easymde.togglePreview()
}
}
})
function initializeEditor() {
window.easymde = new EasyMDE({
element: document.getElementById('editor'),
autoDownloadFontAwesome: false,
spellChecker: false,
nativeSpellcheck: true,
inputStyle: getInputStyleForEnvironment(),
status: false,
shortcuts: {
toggleSideBySide: 'Cmd-Alt-P',
},
renderingConfig: {
codeSyntaxHighlighting: true,
},
toolbar: [
{
className: 'fa fa-eye',
default: true,
name: 'preview',
noDisable: true,
title: 'Toggle Preview',
action: function () {
window.easymde.togglePreview()
saveMetadata()
},
},
{
className: 'fa fa-columns',
default: true,
name: 'side-by-side',
noDisable: true,
noMobile: true,
title: 'Toggle Side by Side',
action: function () {
window.easymde.toggleSideBySide()
saveMetadata()
},
},
'|',
'heading',
'bold',
'italic',
'strikethrough',
'|',
'quote',
'code',
'|',
'unordered-list',
'ordered-list',
'|',
'clean-block',
'|',
'link',
'image',
'|',
'table',
],
})
/**
* Can be set to Infinity to make sure the whole document is always rendered,
* and thus the browser's text search works on it. This will have bad effects
* on performance of big documents.Really bad performance on Safari. Unusable.
*/
window.easymde.codemirror.setOption('viewportMargin', 100)
window.easymde.codemirror.on('change', function () {
const strip = (html) => {
const tmp = document.implementation.createHTMLDocument('New').body
tmp.innerHTML = html
return tmp.textContent || tmp.innerText || ''
}
const truncateString = (string, limit = 90) => {
if (string.length <= limit) {
return string
} else {
return string.substring(0, limit) + '...'
}
}
if (!ignoreTextChange && renderNote) {
if (workingNote) {
// Be sure to capture this object as a variable, as this.note may be reassigned in `streamContextItem`, so by the time
// you modify it in the presave block, it may not be the same object anymore, so the presave values will not be applied to
// the right object, and it will save incorrectly.
const note = workingNote
componentRelay.saveItemWithPresave(note, () => {
lastValue = window.easymde.value()
toggleHighlightByLength(lastValue)
let html = window.easymde.options.previewRender(window.easymde.value())
let strippedHtml = truncateString(strip(html))
note.content.preview_plain = strippedHtml
note.content.preview_html = null
note.content.text = lastValue
})
}
}
})
/**
* Scrolls the cursor into view, so the soft keyboard on mobile devices
* doesn't overlap the cursor. A short delay is added to prevent scrolling
* before the keyboard is shown.
*/
const scrollCursorIntoView = (editor) => {
setTimeout(() => editor.scrollIntoView(), 200)
}
window.easymde.codemirror.on('cursorActivity', function (editor) {
if (componentRelay.environment !== 'mobile') {
return
}
scrollCursorIntoView(editor)
})
// Some sort of issue on Mobile RN where this causes an exception (".className is not defined")
try {
window.easymde.toggleFullScreen()
} catch (e) {
console.error('Error:', e)
}
}
function saveMetadata() {
if (!renderNote) {
return
}
const getEditorMode = () => {
const editor = window.easymde
if (editor) {
if (editor.isPreviewActive()) {
return 'preview'
}
if (editor.isSideBySideActive()) {
return 'split'
}
}
return 'edit'
}
const note = workingNote
componentRelay.saveItemWithPresave(note, () => {
note.clientData = {
...note.clientData,
mode: getEditorMode(),
}
})
}
function setTrustUnsafeContent(note) {
componentRelay.saveItemWithPresave(note, () => {
note.clientData = {
...note.clientData,
trustUnsafeContent: true,
}
})
}
/**
* Checks if a markdown text is safe to render.
*/
function checkIfUnsafeContent(markdownText) {
const marked = require('marked')
const DOMPurify = require('dompurify')
/**
* Using marked to get the resulting HTML string from the markdown text.
*/
const renderedHtml = marked(markdownText, {
headerIds: false,
smartypants: true,
})
const sanitizedHtml = DOMPurify.sanitize(renderedHtml, {
/**
* We don't need script or style tags.
*/
FORBID_TAGS: ['script', 'style'],
/**
* XSS payloads can be injected via these attributes.
*/
FORBID_ATTR: [
'onerror',
'onload',
'onunload',
'onclick',
'ondblclick',
'onmousedown',
'onmouseup',
'onmouseover',
'onmousemove',
'onmouseout',
'onfocus',
'onblur',
'onkeypress',
'onkeydown',
'onkeyup',
'onsubmit',
'onreset',
'onselect',
'onchange',
],
})
/**
* Create documents from both the sanitized string and the rendered string.
* This will allow us to compare them, and if they are not equal
* (i.e: do not contain the same properties, attributes, inner text, etc)
* it means something was stripped.
*/
const renderedDom = new DOMParser().parseFromString(renderedHtml, 'text/html')
const sanitizedDom = new DOMParser().parseFromString(sanitizedHtml, 'text/html')
return !renderedDom.isEqualNode(sanitizedDom)
}
function showUnsafeContentAlert() {
if (showingUnsafeContentAlert) {
return
}
showingUnsafeContentAlert = true
const text =
'We’ve detected that this note contains a script or code snippet which may be unsafe to execute. ' +
'Scripts executed in the editor have the ability to impersonate as the editor to Standard Notes. ' +
'Press Continue to mark this script as safe and proceed, or Cancel to avoid rendering this note.'
return new Promise((resolve) => {
const Stylekit = require('sn-stylekit')
const alert = new Stylekit.SKAlert({
title: null,
text,
buttons: [
{
text: 'Cancel',
style: 'neutral',
action: function () {
showingUnsafeContentAlert = false
resolve(false)
},
},
{
text: 'Continue',
style: 'danger',
action: function () {
showingUnsafeContentAlert = false
resolve(true)
},
},
],
})
alert.present()
})
}
function getInputStyleForEnvironment() {
const environment = componentRelay.environment ?? 'web'
return environment === 'mobile' ? 'textarea' : 'contenteditable'
}
function toggleHighlightByLength(text) {
const maxHighlightLength = 5000
window.easymde.options.renderingConfig.codeSyntaxHighlighting = (window.easymde && text.length < maxHighlightLength)
}
})