🔨 Refactor(ts): change js -> ts

This commit is contained in:
Molunerfinn
2019-12-19 19:17:21 +08:00
parent 72e6e2aed5
commit 4e67a75be0
91 changed files with 8223 additions and 6755 deletions

View File

@@ -2,12 +2,6 @@ import fs from 'fs-extra'
import path from 'path'
import os from 'os'
import { remote, app } from 'electron'
if (process.env.NODE_ENV !== 'development') {
global.__static = path.join(__dirname, '/static').replace(/\\/g, '\\\\')
}
if (process.env.DEBUG_ENV === 'debug') {
global.__static = path.join(__dirname, '../../../static').replace(/\\/g, '\\\\')
}
const APP = process.type === 'renderer' ? remote.app : app
const STORE_PATH = APP.getPath('userData')
@@ -50,7 +44,7 @@ function resolveClipboardImageGenerator () {
})
}
function diffFilesAndUpdate (filePath1, filePath2) {
function diffFilesAndUpdate (filePath1: string, filePath2: string) {
let file1 = fs.readFileSync(filePath1)
let file2 = fs.readFileSync(filePath2)

View File

@@ -1,23 +1,24 @@
import path from 'path'
import db from '../../datastore'
import db from '#/datastore'
import { App } from 'electron'
// eslint-disable-next-line
const requireFunc = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require
const getPicBeds = (app) => {
const getPicBeds = (app: App) => {
const PicGo = requireFunc('picgo')
const STORE_PATH = app.getPath('userData')
const CONFIG_PATH = path.join(STORE_PATH, '/data.json')
const picgo = new PicGo(CONFIG_PATH)
const picBedTypes = picgo.helper.uploader.getIdList()
const picBedFromDB = db.get('picBed.list') || []
const picBeds = picBedTypes.map(item => {
const visible = picBedFromDB.find(i => i.type === item) // object or undefined
const picBeds = picBedTypes.map((item: string) => {
const visible = picBedFromDB.find((i: PicBedType) => i.type === item) // object or undefined
return {
type: item,
name: picgo.helper.uploader.get(item).name || item,
visible: visible ? visible.visible : true
}
})
}) as PicBedType[]
picgo.cmd.program.removeAllListeners()
return picBeds
}

View File

@@ -2,17 +2,23 @@ import {
dialog,
BrowserWindow,
clipboard,
Notification
Notification,
IpcMain,
WebContents
} from 'electron'
import db from '../../datastore'
import db from '#/datastore'
import Uploader from './uploader'
import pasteTemplate from './pasteTemplate'
import pasteTemplate from '#/utils/pasteTemplate'
import PicGoCore from '~/universal/types/picgo'
const WEBCONTENTS = Symbol('WEBCONTENTS')
const IPCMAIN = Symbol('IPCMAIN')
const PICGO = Symbol('PICGO')
class GuiApi {
constructor (ipcMain, webcontents, picgo) {
private [WEBCONTENTS]: WebContents
private [IPCMAIN]: IpcMain
private [PICGO]: PicGoCore
constructor (ipcMain: IpcMain, webcontents: WebContents, picgo: PicGoCore) {
this[WEBCONTENTS] = webcontents
this[IPCMAIN] = ipcMain
this[PICGO] = picgo
@@ -23,7 +29,7 @@ class GuiApi {
* @param {object} options
* return type is string or ''
*/
showInputBox (options) {
showInputBox (options: IShowInputBoxOption) {
if (options === undefined) {
options = {
title: '',
@@ -32,7 +38,7 @@ class GuiApi {
}
this[WEBCONTENTS].send('showInputBox', options)
return new Promise((resolve, reject) => {
this[IPCMAIN].once('showInputBox', (event, value) => {
this[IPCMAIN].once('showInputBox', (event: Event, value: string) => {
resolve(value)
})
})
@@ -42,12 +48,12 @@ class GuiApi {
* for plugin show file explorer
* @param {object} options
*/
showFileExplorer (options) {
showFileExplorer (options: {}) {
if (options === undefined) {
options = {}
}
return new Promise((resolve, reject) => {
dialog.showOpenDialog(BrowserWindow.fromWebContents(this[WEBCONTENTS]), options, filename => {
dialog.showOpenDialog(BrowserWindow.fromWebContents(this[WEBCONTENTS]), options, (filename: string) => {
resolve(filename)
})
})
@@ -57,16 +63,16 @@ class GuiApi {
* for plugin to upload file
* @param {array} input
*/
async upload (input) {
async upload (input: []) {
const imgs = await new Uploader(input, this[WEBCONTENTS], this[PICGO]).upload()
if (imgs !== false) {
const pasteStyle = db.get('settings.pasteStyle') || 'markdown'
let pasteText = ''
for (let i in imgs) {
for (let i = 0; i < imgs.length; i++) {
pasteText += pasteTemplate(pasteStyle, imgs[i]) + '\r\n'
const notification = new Notification({
title: '上传成功',
body: imgs[i].imgUrl,
body: imgs[i].imgUrl as string,
icon: imgs[i].imgUrl
})
setTimeout(() => {
@@ -110,13 +116,13 @@ class GuiApi {
return new Promise((resolve, reject) => {
dialog.showMessageBox(
BrowserWindow.fromWebContents(this[WEBCONTENTS]),
options,
(result, checkboxChecked) => {
resolve({
result,
checkboxChecked
})
options
).then((res) => {
resolve({
result: res.response,
checkboxChecked: res.checkboxChecked
})
})
})
}
}

View File

@@ -1,5 +1,9 @@
import path from 'path'
import fs from 'fs-extra'
type ClipboardFileObject = {
path: string
}
type Result = ClipboardFileObject[]
const getUploadFiles = (argv = process.argv, cwd = process.cwd()) => {
let files = argv.slice(1)
if (files.length > 0 && files[0] === 'upload') {
@@ -7,7 +11,7 @@ const getUploadFiles = (argv = process.argv, cwd = process.cwd()) => {
return null // for uploading images in clipboard
} else if (files.length > 1) {
files = argv.slice(1)
let result = []
let result: Result = []
if (files.length > 0) {
result = files.map(item => {
if (path.isAbsolute(item)) {
@@ -24,7 +28,7 @@ const getUploadFiles = (argv = process.argv, cwd = process.cwd()) => {
return null
}
}
}).filter(item => item !== null)
}).filter(item => item !== null) as Result
}
return result
}

View File

@@ -1,31 +0,0 @@
import db from '../../datastore'
const formatCustomLink = (customLink, item) => {
let fileName = item.fileName.replace(new RegExp(`\\${item.extname}$`), '')
let url = item.url || item.imgUrl
let formatObj = {
url,
fileName
}
let keys = Object.keys(formatObj)
keys.forEach(item => {
if (customLink.indexOf(`$${item}`) !== -1) {
let reg = new RegExp(`\\$${item}`, 'g')
customLink = customLink.replace(reg, formatObj[item])
}
})
return customLink
}
export default (style, item) => {
let url = item.url || item.imgUrl
const customLink = db.get('settings.customLink') || '$url'
const tpl = {
'markdown': `![](${url})`,
'HTML': `<img src="${url}"/>`,
'URL': url,
'UBB': `[IMG]${url}[/IMG]`,
'Custom': formatCustomLink(customLink, item)
}
return tpl[style]
}

View File

@@ -1,16 +1,27 @@
import path from 'path'
import GuiApi from './guiApi'
import { dialog, shell } from 'electron'
import db from '../../datastore'
import { dialog, shell, IpcMain, IpcMainEvent, App } from 'electron'
import db from '#/datastore'
import PicGoCore from '~/universal/types/picgo'
// eslint-disable-next-line
const requireFunc = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require
const PicGo = requireFunc('picgo')
const PicGo = requireFunc('picgo') as typeof PicGoCore
const PluginHandler = requireFunc('picgo/dist/lib/PluginHandler').default
type PicGoNotice = {
title: string,
body: string[]
}
interface GuiMenuItem {
label: string
handle: (arg0: PicGoCore, arg1: GuiApi) => Promise<void>
}
// get uploader or transformer config
const getConfig = (name, type, ctx) => {
let config = []
const getConfig = (name: string, type: PicGoHelperType, ctx: PicGoCore) => {
let config: any[] = []
if (name === '') {
return config
} else {
@@ -24,7 +35,7 @@ const getConfig = (name, type, ctx) => {
}
}
const handleConfigWithFunction = config => {
const handleConfigWithFunction = (config: any[]) => {
for (let i in config) {
if (typeof config[i].default === 'function') {
config[i].default = config[i].default()
@@ -36,8 +47,8 @@ const handleConfigWithFunction = config => {
return config
}
const handleGetPluginList = (ipcMain, STORE_PATH, CONFIG_PATH) => {
ipcMain.on('getPluginList', event => {
const handleGetPluginList = (ipcMain: IpcMain, STORE_PATH: string, CONFIG_PATH: string) => {
ipcMain.on('getPluginList', (event: IpcMainEvent) => {
const picgo = new PicGo(CONFIG_PATH)
const pluginList = picgo.pluginLoader.getList()
const list = []
@@ -57,7 +68,7 @@ const handleGetPluginList = (ipcMain, STORE_PATH, CONFIG_PATH) => {
gui = true
}
}
const obj = {
const obj: IPicGoPlugin = {
name: pluginList[i].replace(/picgo-plugin-/, ''),
author: pluginPKG.author.name || pluginPKG.author,
description: pluginPKG.description,
@@ -71,11 +82,11 @@ const handleGetPluginList = (ipcMain, STORE_PATH, CONFIG_PATH) => {
},
uploader: {
name: uploaderName,
config: handleConfigWithFunction(getConfig(uploaderName, 'uploader', picgo))
config: handleConfigWithFunction(getConfig(uploaderName, PicGoHelperType.uploader, picgo))
},
transformer: {
name: transformerName,
config: handleConfigWithFunction(getConfig(uploaderName, 'transformer', picgo))
config: handleConfigWithFunction(getConfig(uploaderName, PicGoHelperType.transformer, picgo))
}
},
enabled: picgo.getConfig(`picgoPlugins.${pluginList[i]}`),
@@ -90,11 +101,11 @@ const handleGetPluginList = (ipcMain, STORE_PATH, CONFIG_PATH) => {
})
}
const handlePluginInstall = (ipcMain, CONFIG_PATH) => {
ipcMain.on('installPlugin', async (event, msg) => {
const handlePluginInstall = (ipcMain: IpcMain, CONFIG_PATH: string) => {
ipcMain.on('installPlugin', async (event: IpcMainEvent, msg: string) => {
const picgo = new PicGo(CONFIG_PATH)
const pluginHandler = new PluginHandler(picgo)
picgo.on('installSuccess', notice => {
picgo.on('installSuccess', (notice: PicGoNotice) => {
event.sender.send('installSuccess', notice.body[0].replace(/picgo-plugin-/, ''))
})
picgo.on('failed', () => {
@@ -106,11 +117,11 @@ const handlePluginInstall = (ipcMain, CONFIG_PATH) => {
})
}
const handlePluginUninstall = (ipcMain, CONFIG_PATH) => {
ipcMain.on('uninstallPlugin', async (event, msg) => {
const handlePluginUninstall = (ipcMain: IpcMain, CONFIG_PATH: string) => {
ipcMain.on('uninstallPlugin', async (event: IpcMainEvent, msg: string) => {
const picgo = new PicGo(CONFIG_PATH)
const pluginHandler = new PluginHandler(picgo)
picgo.on('uninstallSuccess', notice => {
picgo.on('uninstallSuccess', (notice: PicGoNotice) => {
event.sender.send('uninstallSuccess', notice.body[0].replace(/picgo-plugin-/, ''))
})
picgo.on('failed', () => {
@@ -121,8 +132,8 @@ const handlePluginUninstall = (ipcMain, CONFIG_PATH) => {
})
}
const handlePluginUpdate = (ipcMain, CONFIG_PATH) => {
ipcMain.on('updatePlugin', async (event, msg) => {
const handlePluginUpdate = (ipcMain: IpcMain, CONFIG_PATH: string) => {
ipcMain.on('updatePlugin', async (event: IpcMainEvent, msg: string) => {
const picgo = new PicGo(CONFIG_PATH)
const pluginHandler = new PluginHandler(picgo)
picgo.on('updateSuccess', notice => {
@@ -141,15 +152,15 @@ const handleNPMError = () => {
title: '发生错误',
message: '请安装Node.js并重启PicGo再继续操作',
buttons: ['Yes']
}, (res) => {
if (res === 0) {
}).then((res) => {
if (res.response === 0) {
shell.openExternal('https://nodejs.org/')
}
})
}
const handleGetPicBedConfig = (ipcMain, CONFIG_PATH) => {
ipcMain.on('getPicBedConfig', (event, type) => {
const handleGetPicBedConfig = (ipcMain: IpcMain, CONFIG_PATH: string) => {
ipcMain.on('getPicBedConfig', (event: IpcMainEvent, type: string) => {
const picgo = new PicGo(CONFIG_PATH)
const name = picgo.helper.uploader.get(type).name || type
if (picgo.helper.uploader.get(type).config) {
@@ -162,13 +173,13 @@ const handleGetPicBedConfig = (ipcMain, CONFIG_PATH) => {
})
}
const handlePluginActions = (ipcMain, CONFIG_PATH) => {
ipcMain.on('pluginActions', (event, name, label) => {
const handlePluginActions = (ipcMain: IpcMain, CONFIG_PATH: string) => {
ipcMain.on('pluginActions', (event: IpcMainEvent, name: string, label: string) => {
const picgo = new PicGo(CONFIG_PATH)
const plugin = picgo.pluginLoader.getPlugin(`picgo-plugin-${name}`)
const guiApi = new GuiApi(ipcMain, event.sender, picgo)
if (plugin.guiMenu && plugin.guiMenu(picgo).length > 0) {
const menu = plugin.guiMenu(picgo)
const menu: GuiMenuItem[] = plugin.guiMenu(picgo)
menu.forEach(item => {
if (item.label === label) {
item.handle(picgo, guiApi)
@@ -178,8 +189,8 @@ const handlePluginActions = (ipcMain, CONFIG_PATH) => {
})
}
const handleRemoveFiles = (ipcMain, CONFIG_PATH) => {
ipcMain.on('removeFiles', (event, files) => {
const handleRemoveFiles = (ipcMain: IpcMain, CONFIG_PATH: string) => {
ipcMain.on('removeFiles', (event: IpcMainEvent, files: ImgInfo[]) => {
const picgo = new PicGo(CONFIG_PATH)
const guiApi = new GuiApi(ipcMain, event.sender, picgo)
setTimeout(() => {
@@ -188,18 +199,18 @@ const handleRemoveFiles = (ipcMain, CONFIG_PATH) => {
})
}
const handlePluginShortKeyRegister = (plugin) => {
if (plugin.shortKeys && plugin.shortKeys.length > 0) {
let shortKeyConfig = db.get('settings.shortKey')
plugin.shortKeys.forEach(item => {
if (!shortKeyConfig[item.name]) {
shortKeyConfig[item.name] = item
}
})
}
}
// const handlePluginShortKeyRegister = (plugin) => {
// if (plugin.shortKeys && plugin.shortKeys.length > 0) {
// let shortKeyConfig = db.get('settings.shortKey')
// plugin.shortKeys.forEach(item => {
// if (!shortKeyConfig[item.name]) {
// shortKeyConfig[item.name] = item
// }
// })
// }
// }
export default (app, ipcMain) => {
export default (app: App, ipcMain: IpcMain) => {
const STORE_PATH = app.getPath('userData')
const CONFIG_PATH = path.join(STORE_PATH, '/data.json')
handleGetPluginList(ipcMain, STORE_PATH, CONFIG_PATH)
@@ -209,5 +220,5 @@ export default (app, ipcMain) => {
handleGetPicBedConfig(ipcMain, CONFIG_PATH)
handlePluginActions(ipcMain, CONFIG_PATH)
handleRemoveFiles(ipcMain, CONFIG_PATH)
handlePluginShortKeyRegister({})
// handlePluginShortKeyRegister({})
}

View File

@@ -1,4 +1,7 @@
import bus from './eventBus'
import {
GlobalShortcut
} from 'electron'
let isInModifiedMode = false // 修改快捷键模式
bus.on('toggleShortKeyModifiedMode', flag => {
isInModifiedMode = flag
@@ -7,7 +10,7 @@ bus.on('toggleShortKeyModifiedMode', flag => {
*
* @param {string} name
*/
const shortKeyHandler = (name) => {
const shortKeyHandler = (name: string) => {
if (isInModifiedMode) {
return
}
@@ -20,11 +23,8 @@ const shortKeyHandler = (name) => {
/**
*
* @param {globalShortcut} globalShortcut
* @param {keyObject} item
* @param {string} oldKey
*/
const shortKeyUpdater = (globalShortcut, item, oldKey) => {
const shortKeyUpdater = (globalShortcut: GlobalShortcut, item: ShortKeyConfig, oldKey: string) => {
// 如果提供了旧key则解绑
if (oldKey) {
globalShortcut.unregister(oldKey)
@@ -39,7 +39,7 @@ const shortKeyUpdater = (globalShortcut, item, oldKey) => {
}
// 初始化阶段的注册
const initShortKeyRegister = (globalShortcut, shortKeys) => {
const initShortKeyRegister = (globalShortcut: GlobalShortcut, shortKeys: ShortKeyConfig[]) => {
let errorList = []
for (let i in shortKeys) {
try {

View File

@@ -1,10 +1,15 @@
import { dialog, shell } from 'electron'
import db from '../../datastore'
import db from '#/datastore'
import axios from 'axios'
import pkg from '../../../package.json'
import pkg from 'root/package.json'
const version = pkg.version
const release = 'https://api.github.com/repos/Molunerfinn/PicGo/releases/latest'
let release = 'https://api.github.com/repos/Molunerfinn/PicGo/releases/latest'
const downloadUrl = 'https://github.com/Molunerfinn/PicGo/releases/latest'
const isDevelopment = process.env.NODE_ENV !== 'production'
if (isDevelopment) {
release = `${release}?access_token=${process.env.GITHUB_TOKEN}`
}
const checkVersion = async () => {
let showTip = db.get('settings.showUpdateTip')
@@ -13,7 +18,12 @@ const checkVersion = async () => {
showTip = true
}
if (showTip) {
const res = await axios.get(release)
let res: any
try {
res = await axios.get(release)
} catch (err) {
console.log(err)
}
if (res.status === 200) {
const latest = res.data.name
const result = compareVersion2Update(version, latest)
@@ -25,11 +35,11 @@ const checkVersion = async () => {
message: `发现新版本${latest},更新了很多功能,是否去下载最新的版本?`,
checkboxLabel: '以后不再提醒',
checkboxChecked: false
}, (res, checkboxChecked) => {
if (res === 0) { // if selected yes
}).then(res => {
if (res.response === 0) { // if selected yes
shell.openExternal(downloadUrl)
}
db.set('settings.showUpdateTip', !checkboxChecked)
db.set('settings.showUpdateTip', !res.checkboxChecked)
})
}
} else {
@@ -41,7 +51,7 @@ const checkVersion = async () => {
}
// if true -> update else return false
const compareVersion2Update = (current, latest) => {
const compareVersion2Update = (current: string, latest: string) => {
const currentVersion = current.split('.').map(item => parseInt(item))
const latestVersion = latest.split('.').map(item => parseInt(item))

View File

@@ -2,20 +2,39 @@ import {
app,
Notification,
BrowserWindow,
ipcMain
ipcMain,
WebContents
} from 'electron'
import path from 'path'
import dayjs from 'dayjs'
import PicGoCore from '~/universal/types/picgo'
// eslint-disable-next-line
const requireFunc = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require
const PicGo = requireFunc('picgo')
const PicGo = requireFunc('picgo') as typeof PicGoCore
const STORE_PATH = app.getPath('userData')
const CONFIG_PATH = path.join(STORE_PATH, '/data.json')
const renameURL = process.env.NODE_ENV === 'development' ? `http://localhost:9080/#rename-page` : `file://${__dirname}/index.html#rename-page`
const createRenameWindow = (win) => {
let options = {
// type BrowserWindowOptions = {
// height: number,
// width: number,
// show: boolean,
// fullscreenable: boolean,
// resizable: boolean,
// vibrancy: string | any,
// webPreferences: {
// nodeIntegration: boolean,
// nodeIntegrationInWorker: boolean,
// backgroundThrottling: boolean
// },
// backgroundColor?: string
// autoHideMenuBar?: boolean
// transparent?: boolean
// }
const createRenameWindow = (win: BrowserWindow) => {
let options: BrowserWindowOptions = {
height: 175,
width: 300,
show: true,
@@ -55,7 +74,7 @@ const createRenameWindow = (win) => {
return window
}
const waitForShow = (webcontent) => {
const waitForShow = (webcontent: WebContents) => {
return new Promise((resolve, reject) => {
webcontent.on('dom-ready', () => {
resolve()
@@ -63,9 +82,9 @@ const waitForShow = (webcontent) => {
})
}
const waitForRename = (window, id) => {
const waitForRename = (window: BrowserWindow, id: number): Promise<string|null> => {
return new Promise((resolve, reject) => {
ipcMain.once(`rename${id}`, (evt, newName) => {
ipcMain.once(`rename${id}`, (evt: Event, newName: string) => {
resolve(newName)
window.hide()
})
@@ -77,15 +96,18 @@ const waitForRename = (window, id) => {
}
class Uploader {
constructor (img, webContents, picgo = undefined) {
private picgo: PicGoCore
private webContents: WebContents
private img: undefined | string[]
constructor (img: undefined | string[], webContents: WebContents, picgo: PicGoCore | undefined = undefined) {
this.img = img
this.webContents = webContents
this.picgo = picgo
this.picgo = picgo || new PicGo(CONFIG_PATH)
}
upload () {
upload (): Promise<ImgInfo[]|false> {
const win = BrowserWindow.fromWebContents(this.webContents)
const picgo = this.picgo || new PicGo(CONFIG_PATH)
const picgo = this.picgo
picgo.config.debug = true
// for picgo-core
picgo.config.PICGO_ENV = 'GUI'
@@ -96,8 +118,8 @@ class Uploader {
const rename = picgo.getConfig('settings.rename')
const autoRename = picgo.getConfig('settings.autoRename')
await Promise.all(ctx.output.map(async (item, index) => {
let name
let fileName
let name: undefined | string | null
let fileName: string | undefined
if (autoRename) {
fileName = dayjs().add(index, 'second').format('YYYYMMDDHHmmss') + item.extname
} else {
@@ -137,7 +159,7 @@ class Uploader {
return new Promise((resolve) => {
picgo.on('finished', ctx => {
if (ctx.output.every(item => item.imgUrl)) {
if (ctx.output.every((item: ImgInfo) => item.imgUrl)) {
resolve(ctx.output)
} else {
resolve(false)