forked from marktext/marktext
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
435 lines (385 loc) · 10.6 KB
/
index.js
File metadata and controls
435 lines (385 loc) · 10.6 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
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
import runSanitize from './dompurify'
import { URL_REG, DATA_URL_REG, IMAGE_EXT_REG } from '../config'
const ID_PREFIX = 'ag-'
let id = 0
const TIMEOUT = 1500
const HTML_TAG_REPLACEMENTS = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
}
export const getUniqueId = () => `${ID_PREFIX}${id++}`
export const getLongUniqueId = () => `${getUniqueId()}-${(+new Date()).toString(32)}`
export const isMetaKey = ({ key }) => key === 'Shift' || key === 'Control' || key === 'Alt' || key === 'Meta'
export const noop = () => {}
export const identity = i => i
export const isOdd = number => Math.abs(number) % 2 === 1
export const isEven = number => Math.abs(number) % 2 === 0
export const isLengthEven = (str = '') => str.length % 2 === 0
export const snakeToCamel = name => name.replace(/_([a-z])/g, (p0, p1) => p1.toUpperCase())
export const camelToSnake = name => name.replace(/([A-Z])/g, (_, p) => `-${p.toLowerCase()}`)
/**
* Are two arrays have intersection
*/
export const conflict = (arr1, arr2) => {
return !(arr1[1] < arr2[0] || arr2[1] < arr1[0])
}
export const union = ({ start: tStart, end: tEnd }, { start: lStart, end: lEnd, active }) => {
if (!(tEnd <= lStart || lEnd <= tStart)) {
if (lStart < tStart) {
return {
start: tStart,
end: tEnd < lEnd ? tEnd : lEnd,
active
}
} else {
return {
start: lStart,
end: tEnd < lEnd ? tEnd : lEnd,
active
}
}
}
return null
}
// https://github.com/jashkenas/underscore
export const throttle = (func, wait = 50) => {
let context
let args
let result
let timeout = null
let previous = 0
const later = () => {
previous = Date.now()
timeout = null
result = func.apply(context, args)
if (!timeout) {
context = args = null
}
}
return function () {
const now = Date.now()
const remaining = wait - (now - previous)
context = this
args = arguments
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout)
timeout = null
}
previous = now
result = func.apply(context, args)
if (!timeout) {
context = args = null
}
} else if (!timeout) {
timeout = setTimeout(later, remaining)
}
return result
}
}
// simple implementation...
export const debounce = (func, wait = 50) => {
let timer = null
return function (...args) {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
func(...args)
}, wait)
}
}
export const deepCopyArray = array => {
const result = []
const len = array.length
let i
for (i = 0; i < len; i++) {
if (typeof array[i] === 'object' && array[i] !== null) {
if (Array.isArray(array[i])) {
result.push(deepCopyArray(array[i]))
} else {
result.push(deepCopy(array[i]))
}
} else {
result.push(array[i])
}
}
return result
}
// TODO: @jocs rewrite deepCopy
export const deepCopy = object => {
const obj = {}
Object.keys(object).forEach(key => {
if (typeof object[key] === 'object' && object[key] !== null) {
if (Array.isArray(object[key])) {
obj[key] = deepCopyArray(object[key])
} else {
obj[key] = deepCopy(object[key])
}
} else {
obj[key] = object[key]
}
})
return obj
}
export const loadImage = async (url, detectContentType = false) => {
if (detectContentType) {
const isImage = await checkImageContentType(url)
if (!isImage) throw new Error('not an image')
}
return new Promise((resolve, reject) => {
const image = new Image()
image.onload = () => {
resolve({
url,
width: image.width,
height: image.height
})
}
image.onerror = err => {
reject(err)
}
image.src = url
})
}
export const isOnline = () => {
return navigator.onLine === true
}
export const getPageTitle = url => {
// No need to request the title when it's not url.
if (!url.startsWith('http')) {
return ''
}
// No need to request the title when off line.
if (!isOnline()) {
return ''
}
const req = new XMLHttpRequest()
let settle
const promise = new Promise((resolve, reject) => {
settle = resolve
})
const handler = () => {
if (req.readyState === XMLHttpRequest.DONE) {
if (req.status === 200) {
const contentType = req.getResponseHeader('Content-Type')
if (/text\/html/.test(contentType)) {
const { response } = req
if (typeof response === 'string') {
const match = response.match(/<title>(.*)<\/title>/)
return match && match[1] ? settle(match[1]) : settle('')
}
return settle('')
}
return settle('')
} else {
return settle('')
}
}
}
const handleError = (e) => {
settle('')
}
req.open('GET', url)
req.onreadystatechange = handler
req.onerror = handleError
req.send()
// Resolve empty string when `TIMEOUT` passed.
const timer = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('')
}, TIMEOUT)
})
return Promise.race([promise, timer])
}
export const checkImageContentType = url => {
const req = new XMLHttpRequest()
let settle
const promise = new Promise((resolve, reject) => {
settle = resolve
})
const handler = () => {
if (req.readyState === XMLHttpRequest.DONE) {
if (req.status === 200) {
const contentType = req.getResponseHeader('Content-Type')
if (/^image\/(?:jpeg|png|gif|svg\+xml|webp)$/.test(contentType)) {
settle(true)
} else {
settle(false)
}
} else if (req.status === 405) { // status 405 means method not allowed, and just return true.(Solve issue#1297)
settle(true)
} else {
settle(false)
}
}
}
const handleError = () => {
settle(false)
}
req.open('HEAD', url)
req.onreadystatechange = handler
req.onerror = handleError
req.send()
return promise
}
/**
* Return image information and correct the relative image path if needed.
*
* @param {string} src Image url
* @param {string} baseUrl Base path; used on desktop to fix the relative image path.
*/
export const getImageInfo = (src, baseUrl = window.DIRNAME) => {
const imageExtension = IMAGE_EXT_REG.test(src)
const isUrl = URL_REG.test(src) || (imageExtension && /^file:\/\/.+/.test(src))
// Treat an URL with valid extension as image.
if (imageExtension) {
// NOTE: Check both "C:\" and "C:/" because we're using "file:///C:/".
const isAbsoluteLocal = /^(?:\/|\\\\|[a-zA-Z]:\\|[a-zA-Z]:\/).+/.test(src)
if (isUrl || (!isAbsoluteLocal && !baseUrl)) {
if (!isUrl && !baseUrl) {
console.warn('"baseUrl" is not defined!')
}
return {
isUnknownType: false,
src
}
} else {
// Correct relative path on desktop. If we resolve a absolute path "path.resolve" doesn't do anything.
// NOTE: We don't need to convert Windows styled path to UNIX style because Chromium handels this internal.
return {
isUnknownType: false,
src: 'file://' + require('path').resolve(baseUrl, src)
}
}
} else if (isUrl && !imageExtension) {
// Assume it's a valid image and make a http request later
return {
isUnknownType: true,
src
}
}
// Data url
if (DATA_URL_REG.test(src)) {
return {
isUnknownType: false,
src
}
}
// Url type is unknown
return {
isUnknownType: false,
src: ''
}
}
export const escapeHTML = str =>
str.replace(
/[&<>'"]/g,
tag =>
({
'&': '&',
'<': '<',
'>': '>',
"'": ''',
'"': '"'
}[tag] || tag)
)
export const unescapeHTML = str =>
str.replace(
/(?:&|<|>|"|')/g,
tag =>
({
'&': '&',
'<': '<',
'>': '>',
''': "'",
'"': '"'
}[tag] || tag)
)
export const escapeInBlockHtml = html => {
return html
.replace(/(<(style|script|title)[^<>]*>)([\s\S]*?)(<\/\2>)/g, (m, p1, p2, p3, p4) => {
return `${escapeHTML(p1)}${p3}${escapeHTML(p4)}`
})
}
export const escapeHtmlTags = html => {
return html.replace(/[&<>"']/g, x => { return HTML_TAG_REPLACEMENTS[x] })
}
export const wordCount = markdown => {
const paragraph = markdown.split(/\n{2,}/).filter(line => line).length
let word = 0
let character = 0
let all = 0
const removedChinese = markdown.replace(/[\u4e00-\u9fa5]/g, '')
const tokens = removedChinese.split(/[\s\n]+/).filter(t => t)
const chineseWordLength = markdown.length - removedChinese.length
word += chineseWordLength + tokens.length
character += tokens.reduce((acc, t) => acc + t.length, 0) + chineseWordLength
all += markdown.length
return { word, paragraph, character, all }
}
/**
* [genUpper2LowerKeyHash generate constants map hash, the value is lowercase of the key,
* also translate `_` to `-`]
*/
export const genUpper2LowerKeyHash = keys => {
return keys.reduce((acc, key) => {
const value = key.toLowerCase().replace(/_/g, '-')
return Object.assign(acc, { [key]: value })
}, {})
}
/**
* generate constants map, the value is the key.
*/
export const generateKeyHash = keys => {
return keys.reduce((acc, key) => {
return Object.assign(acc, { [key]: key })
}, {})
}
// mixins
export const mixins = (constructor, ...object) => {
return Object.assign(constructor.prototype, ...object)
}
export const sanitize = (html, purifyOptions, disableHtml) => {
if (disableHtml) {
return runSanitize(escapeHtmlTags(html), purifyOptions)
} else {
return runSanitize(escapeInBlockHtml(html), purifyOptions)
}
}
export const getParagraphReference = (ele, id) => {
const { x, y, left, top, bottom, height } = ele.getBoundingClientRect()
return {
getBoundingClientRect () {
return { x, y, left, top, bottom, height, width: 0, right: left }
},
clientWidth: 0,
clientHeight: height,
id
}
}
export const verticalPositionInRect = (event, rect) => {
const { clientY } = event
const { top, height } = rect
return (clientY - top) > (height / 2) ? 'down' : 'up'
}
export const collectFootnotes = (blocks) => {
const map = new Map()
for (const block of blocks) {
if (block.type === 'figure' && block.functionType === 'footnote') {
const identifier = block.children[0].text
map.set(identifier, block)
}
}
return map
}
export const getDefer = () => {
const defer = {}
const promise = new Promise((resolve, reject) => {
defer.resolve = resolve
defer.reject = reject
})
defer.promise = promise
return defer
}