Skip to content

Commit ad87131

Browse files
committed
✨ Feature(custom): streamline code for better readability and performance
1 parent 476966f commit ad87131

File tree

10 files changed

+103
-232
lines changed

10 files changed

+103
-232
lines changed

src/utils/index.ts

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ export interface IMessageToShow {
44
}
55

66
export const isUrlEncode = (url: string): boolean => {
7-
url = url || ''
7+
if (!url) return false
88
try {
99
return url !== decodeURI(url)
1010
} catch {
@@ -32,13 +32,11 @@ export function extractUrl(str: string): string[] {
3232
/\[img\](.*?)\[\/img\]/g
3333
]
3434

35-
const urls = []
35+
const urls = new Set<string>()
3636
for (const pattern of patterns) {
37-
while (true) {
38-
const match = pattern.exec(str)
39-
if (!match) break
40-
urls.push(match[1])
37+
for (const match of str.matchAll(pattern)) {
38+
if (match[1]) urls.add(match[1])
4139
}
4240
}
43-
return Array.from(new Set(urls))
41+
return Array.from(urls)
4442
}

src/utils/meta.ts

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
11
import nls = require('../../package.nls.json')
22

3-
export const getNLSText = (field: keyof typeof nls) => {
4-
return nls[field]
5-
}
3+
export const getNLSText = (field: keyof typeof nls) => nls[field]

src/vscode/Editor.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@ export class Editor {
77

88
static async writeToEditor(text: string) {
99
const editor = this.editor
10-
return await editor?.edit(textEditor => {
11-
textEditor.replace(editor.selection, text)
10+
return await editor?.edit(editBuilder => {
11+
editBuilder.replace(editor.selection, text)
1212
})
1313
}
1414
}

src/vscode/clipboard/getClipboardImage.ts

Lines changed: 16 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -14,31 +14,19 @@ type Platform = 'darwin' | 'win32' | 'win10' | 'linux'
1414
function getCurrentPlatform(): Platform {
1515
const platform = process.platform
1616
if (platform === 'win32') {
17-
const currentOS = os.release().split('.')[0]
18-
if (currentOS === '10') {
19-
return 'win10'
20-
} else {
21-
return 'win32'
22-
}
23-
} else if (platform === 'darwin') {
24-
return 'darwin'
25-
} else {
26-
return 'linux'
17+
return os.release().split('.')[0] === '10' ? 'win10' : 'win32'
2718
}
19+
return platform === 'darwin' ? 'darwin' : 'linux'
2820
}
2921

30-
const platform2ScriptContent: {
31-
[key in Platform]: string
32-
} = {
22+
const platform2ScriptContent: { [key in Platform]: string } = {
3323
darwin: macClipboardScript,
3424
win32: windowsClipboardScript,
3525
win10: windows10ClipboardScript,
3626
linux: linuxClipboardScript
3727
}
3828

39-
const platform2ScriptFilename: {
40-
[key in Platform]: string
41-
} = {
29+
const platform2ScriptFilename: { [key in Platform]: string } = {
4230
darwin: 'mac.applescript',
4331
win32: 'windows.ps1',
4432
win10: 'windows10.ps1',
@@ -47,32 +35,27 @@ const platform2ScriptFilename: {
4735

4836
interface IClipboardImage {
4937
imgPath: string
50-
/**
51-
* if the path is generate by picgo -> false
52-
* if the path is a real file path in system -> true
53-
*/
5438
shouldKeepAfterUploading: boolean
5539
}
5640

5741
function appDataPath() {
58-
const appDataPath = getAppDataPath('vs-piclist')
59-
fs.ensureDirSync(appDataPath)
60-
return appDataPath
42+
const dir = getAppDataPath('vs-piclist')
43+
fs.ensureDirSync(dir)
44+
return dir
6145
}
6246

6347
function ImageSaveDir() {
64-
const imageSavePath = path.join(appDataPath(), 'piclist-clipboard-image')
65-
fs.emptyDirSync(imageSavePath)
66-
return imageSavePath
48+
const dir = path.join(appDataPath(), 'piclist-clipboard-image')
49+
fs.emptyDirSync(dir)
50+
return dir
6751
}
6852

6953
const getClipboardImage = async (): Promise<IClipboardImage> => {
7054
const imageSaveDir = ImageSaveDir()
7155
const imagePath = path.join(imageSaveDir, `${dayjs().format('YYYYMMDDHHmmss')}.png`)
72-
return await new Promise<IClipboardImage>((resolve: any, reject: any): void => {
56+
return await new Promise<IClipboardImage>((resolve, reject) => {
7357
const platform = getCurrentPlatform()
7458
const scriptPath = path.join(appDataPath(), platform2ScriptFilename[platform])
75-
// If the script does not exist yet, we need to write the content to the script file
7659
if (!fs.existsSync(scriptPath)) {
7760
fs.writeFileSync(scriptPath, platform2ScriptContent[platform], 'utf8')
7861
}
@@ -87,10 +70,6 @@ const getClipboardImage = async (): Promise<IClipboardImage> => {
8770
'-sta',
8871
'-executionpolicy',
8972
'unrestricted',
90-
// fix windows 10 native cmd crash bug when "picgo upload"
91-
// https://github.com/PicGo/PicGo-Core/issues/32
92-
// '-windowstyle','hidden',
93-
// '-noexit',
9473
'-file',
9574
scriptPath,
9675
imagePath
@@ -100,34 +79,18 @@ const getClipboardImage = async (): Promise<IClipboardImage> => {
10079
}
10180

10281
execution.stdout.on('data', (data: Buffer) => {
103-
if (platform === 'linux') {
104-
if (data.toString().trim() === 'no xclip or wl-clipboard') {
105-
return reject(new Error('Please install xclip(for x11) or wl-clipboard(for wayland) before run picgo'))
106-
}
82+
if (platform === 'linux' && data.toString().trim() === 'no xclip or wl-clipboard') {
83+
return reject(new Error('Please install xclip(for x11) or wl-clipboard(for wayland) before run picgo'))
10784
}
10885
const imgPath = data.toString().trim()
109-
110-
// if the filePath is the real file in system
111-
// we should keep it instead of removing
11286
let shouldKeepAfterUploading = false
113-
114-
// in macOS if your copy the file in system, it's basename will not equal to our default basename
115-
if (path.basename(imgPath) !== path.basename(imagePath)) {
116-
// if the path is not generate by picgo
117-
// but the path exists, we should keep it
118-
if (fs.existsSync(imgPath)) {
119-
shouldKeepAfterUploading = true
120-
}
87+
if (path.basename(imgPath) !== path.basename(imagePath) && fs.existsSync(imgPath)) {
88+
shouldKeepAfterUploading = true
12189
}
122-
// if the imgPath is invalid
12390
if (imgPath !== 'no image' && !fs.existsSync(imgPath)) {
12491
return reject(new Error(`Can't find ${imgPath}`))
12592
}
126-
127-
resolve({
128-
imgPath,
129-
shouldKeepAfterUploading
130-
})
93+
resolve({ imgPath, shouldKeepAfterUploading })
13194
})
13295
})
13396
}

src/vscode/commands.ts

Lines changed: 40 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,7 @@ export class Commands {
2020
) {
2121
const output = await Uploader.picgoAPI.upload(input, getFileNameFromRes)
2222
if (!output) return
23-
if (shouldKeepAfterUploading === false && input) {
24-
fs.removeSync(input[0])
25-
}
23+
if (!shouldKeepAfterUploading && input) fs.removeSync(input[0])
2624
if (writeToEditor) {
2725
vscode.env.clipboard.writeText(output)
2826
await Editor.writeToEditor(output)
@@ -41,22 +39,17 @@ export class Commands {
4139

4240
async uploadImageFromExplorer() {
4341
const result = await vscode.window.showOpenDialog({
44-
filters: {
45-
Images: ['png', 'jpg', 'jpeg', 'webp', 'gif', 'bmp', 'tiff', 'ico', 'svg']
46-
},
42+
filters: { Images: ['png', 'jpg', 'jpeg', 'webp', 'gif', 'bmp', 'tiff', 'ico', 'svg'] },
4743
canSelectMany: true
4844
})
49-
50-
if (result != null) {
51-
const input = result.map(item => item.fsPath)
52-
this.uploadCommand(input.map(item => path.resolve(item)))
45+
if (result) {
46+
const input = result.map(item => path.resolve(item.fsPath))
47+
this.uploadCommand(input)
5348
}
5449
}
5550

5651
async uploadImageFromInputBox() {
57-
let result = await vscode.window.showInputBox({
58-
placeHolder: 'Please input an local image path or URL'
59-
})
52+
let result = await vscode.window.showInputBox({ placeHolder: 'Please input an local image path or URL' })
6053
const imageReg = /\.(png|jpg|jpeg|webp|gif|bmp|tiff|ico|svg)$/
6154
if (isURL(result)) {
6255
return await this.uploadCommand([result!])
@@ -86,25 +79,18 @@ export class Commands {
8679
}
8780

8881
async DeleteImage(items: IStringKeyObject[]): Promise<boolean> {
89-
if (items.length === 0) return true
82+
if (!items.length) return true
9083
try {
9184
const res = await axios.post(
9285
Uploader.picgoAPI.getDeleteAPIUrl(),
93-
{
94-
list: items
95-
},
96-
{
97-
headers: {
98-
'Content-Type': 'application/json'
99-
}
100-
}
86+
{ list: items },
87+
{ headers: { 'Content-Type': 'application/json' } }
10188
)
10289
if (res.status === 200 && res.data.success) {
10390
DataStore.removeUploadedFileDBItem(items)
10491
return true
105-
} else {
106-
return false
10792
}
93+
return false
10894
} catch (error) {
10995
console.error(error)
11096
return false
@@ -113,62 +99,45 @@ export class Commands {
11399

114100
async uploadAllImgInFile(selected = false) {
115101
const editor = vscode.window.activeTextEditor
116-
if (editor) {
117-
const document = editor.document
118-
let text = document.getText()
119-
if (selected) {
120-
if (editor.selection.isEmpty) {
121-
return
122-
}
123-
text = document.getText(editor.selection)
124-
}
125-
const textLength = text.length
126-
const regex = /(!\[.*?\]\((.*?)\))|(<img[^>]*src="(.*?)"[^>]*>)|(https?:\/\/[^\s]+)|(\[img\](.*?)\[\/img\])/g
127-
let match
128-
const uploadedImages: { [key: string]: string } = {}
129-
const matches = []
130-
while ((match = regex.exec(text)) !== null) {
131-
matches.push(match)
132-
}
133-
for (const match of matches) {
134-
const imgSyntax = match[0]
135-
const url = match[2] || match[4] || match[5] || match[7]
136-
if (url) {
137-
let res: string | undefined
138-
if (uploadedImages[url]) {
139-
res = uploadedImages[url]
102+
if (!editor) return
103+
const document = editor.document
104+
let text = selected && !editor.selection.isEmpty ? document.getText(editor.selection) : document.getText()
105+
const textLength = text.length
106+
const regex = /(!\[.*?\]\((.*?)\))|(<img[^>]*src="(.*?)"[^>]*>)|(https?:\/\/[^\s]+)|(\[img\](.*?)\[\/img\])/g
107+
let match
108+
const uploadedImages: { [key: string]: string } = {}
109+
const matches = []
110+
while ((match = regex.exec(text)) !== null) matches.push(match)
111+
for (const match of matches) {
112+
const imgSyntax = match[0]
113+
const url = match[2] || match[4] || match[5] || match[7]
114+
if (url) {
115+
let res: string | undefined = uploadedImages[url]
116+
if (!res) {
117+
if (isURL(url)) {
118+
res = await this.uploadCommand([url], true, false, true)
140119
} else {
141-
if (isURL(url)) {
142-
res = await this.uploadCommand([url], true, false, true)
143-
} else {
144-
const localPath = path.isAbsolute(url) ? url : path.join(document.uri.fsPath, '../', url)
145-
if (fs.existsSync(localPath)) {
146-
res = await this.uploadCommand([localPath], true, false, true)
147-
}
148-
}
149-
if (res) {
150-
uploadedImages[url] = res
120+
const localPath = path.isAbsolute(url) ? url : path.join(document.uri.fsPath, '../', url)
121+
if (fs.existsSync(localPath)) {
122+
res = await this.uploadCommand([localPath], true, false, true)
151123
}
152124
}
153-
if (res) {
154-
text = text.replace(imgSyntax, res)
155-
}
125+
if (res) uploadedImages[url] = res
156126
}
127+
if (res) text = text.replace(imgSyntax, res)
157128
}
158-
const range =
159-
selected && !editor.selection.isEmpty
160-
? editor.selection
161-
: new vscode.Range(document.positionAt(0), document.positionAt(textLength))
162-
editor.edit(editBuilder => {
163-
editBuilder.replace(range, text)
164-
})
165129
}
130+
const range =
131+
selected && !editor.selection.isEmpty
132+
? editor.selection
133+
: new vscode.Range(document.positionAt(0), document.positionAt(textLength))
134+
editor.edit(editBuilder => {
135+
editBuilder.replace(range, text)
136+
})
166137
}
167138

168139
async uploadSelectedImg() {
169140
const editor = vscode.window.activeTextEditor
170-
if (editor) {
171-
await this.uploadAllImgInFile(true)
172-
}
141+
if (editor) await this.uploadAllImgInFile(true)
173142
}
174143
}

src/vscode/db.ts

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,12 @@ export interface IStringKeyObject {
88

99
export class DataStore {
1010
static dataStore: DataStore = new DataStore()
11-
1211
private constructor() {}
1312

1413
get appDataPath() {
15-
const appDataPath = getAppDataPath('vs-piclist')
16-
fs.ensureDirSync(appDataPath)
17-
return appDataPath
14+
const dir = getAppDataPath('vs-piclist')
15+
fs.ensureDirSync(dir)
16+
return dir
1817
}
1918

2019
get conUploadedFileDBPath() {
@@ -43,23 +42,16 @@ export class DataStore {
4342

4443
static searchUploadedFileDB(urls: string[]): IStringKeyObject[] {
4544
const data = DataStore.readUploadedFileDB()
46-
const res = [] as IStringKeyObject[]
47-
for (const url of urls) {
48-
const item = data.find(item => item.imgUrl === url || decodeURI(item.imgUrl) === url)
49-
if (item) {
50-
res.push(item)
51-
}
52-
}
53-
return res
45+
return urls
46+
.map(url => data.find(item => item.imgUrl === url || decodeURI(item.imgUrl) === url))
47+
.filter(Boolean) as IStringKeyObject[]
5448
}
5549

5650
static removeUploadedFileDBItem(items: IStringKeyObject[]) {
5751
const data = DataStore.readUploadedFileDB()
5852
for (const item of items) {
5953
const index = data.findIndex((i: IStringKeyObject) => i.id === item.id)
60-
if (index !== -1) {
61-
data.splice(index, 1)
62-
}
54+
if (index !== -1) data.splice(index, 1)
6355
}
6456
fs.writeJSONSync(DataStore.dataStore.conUploadedFileDBPath, data)
6557
}

0 commit comments

Comments
 (0)