forked from marktext/marktext
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimagePathAutoComplement.js
More file actions
84 lines (77 loc) · 2.18 KB
/
imagePathAutoComplement.js
File metadata and controls
84 lines (77 loc) · 2.18 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
import fs from 'fs'
import path from 'path'
import { filter } from 'fuzzaldrin'
import log from 'electron-log'
import { isDirectory, isFile } from 'common/filesystem'
import { IMAGE_EXTENSIONS } from 'common/filesystem/paths'
import { BLACK_LIST } from '../config'
// TODO(need::refactor): Refactor this file. Just return an array of directories and files without caching and watching?
// TODO: rebuild cache @jocs
const IMAGE_PATH = new Map()
export const watchers = new Map()
const filesHandler = (files, directory, key) => {
const IMAGE_REG = new RegExp('(' + IMAGE_EXTENSIONS.join('|') + ')$', 'i')
const onlyDirAndImage = files
.map(file => {
const fullPath = path.join(directory, file)
let type = ''
if (isDirectory(fullPath)) {
type = 'directory'
} else if (isFile(fullPath) && IMAGE_REG.test(file)) {
type = 'image'
}
return {
file,
type
}
})
.filter(({
file,
type
}) => {
if (BLACK_LIST.includes(file)) return false
return type === 'directory' || type === 'image'
})
IMAGE_PATH.set(directory, onlyDirAndImage)
if (key !== undefined) {
return filter(onlyDirAndImage, key, {
key: 'file'
})
}
}
const rebuild = (directory) => {
fs.readdir(directory, (err, files) => {
if (err) log.error(err)
else {
filesHandler(files, directory)
}
})
}
const watchDirectory = directory => {
if (watchers.has(directory)) return // Do not duplicate watch the same directory
const watcher = fs.watch(directory, (eventType, filename) => {
if (eventType === 'rename') {
rebuild(directory)
}
})
watchers.set(directory, watcher)
}
export const searchFilesAndDir = (directory, key) => {
let result = []
if (IMAGE_PATH.has(directory)) {
result = filter(IMAGE_PATH.get(directory), key, { key: 'file' })
return Promise.resolve(result)
} else {
return new Promise((resolve, reject) => {
fs.readdir(directory, (err, files) => {
if (err) {
reject(err)
} else {
result = filesHandler(files, directory, key)
watchDirectory(directory)
resolve(result)
}
})
})
}
}