Browse Source

style: 优化代码格式

main
npmrun 5 months ago
parent
commit
7023810b2a
  1. 12
      config/index.ts
  2. 12
      electron-builder.yml
  3. 28
      electron.vite.config.ts
  4. 46
      src/main/index.ts
  5. 16
      src/main/modules/App.ts
  6. 10
      src/main/modules/db/custom.ts
  7. 28
      src/main/modules/db/index.ts
  8. 4
      src/main/modules/index.ts
  9. 6
      src/main/modules/module.ts
  10. 45
      src/main/modules/setting/index.ts
  11. 2
      src/preload/index.d.ts
  12. 8
      src/preload/index.ts
  13. 10
      src/renderer/src/App.vue
  14. 8
      src/renderer/src/assets/base.css
  15. 6
      src/renderer/src/assets/main.css
  16. 2
      src/renderer/src/components/Versions.vue
  17. 4
      src/renderer/src/env.d.ts
  18. 12
      src/renderer/src/main.ts
  19. 4
      src/renderer/src/shims.d.ts
  20. 10
      uno.config.ts

12
config/index.ts

@ -1,12 +1,12 @@
interface IConfig {
app_title: string,
app_title: string
default_config: {
language: "zh" | "en" // i18n
"common.theme": "light" | "dark" | "auto" // 主题
"desktop:wallpaper": string
"update.repo"?: string // 更新地址
"update.owner"?: string // 更新通道
"update.allowDowngrade": boolean,
"update.allowDowngrade": boolean
"update.allowPrerelease": boolean
"editor.bg": string // 更新通道
"editor.logoType": "logo" | "bg" // 更新通道
@ -20,8 +20,8 @@ interface IConfig {
export default {
app_title: "ada",
default_config: {
"storagePath": "$storagePath$",
"language": "zh",
storagePath: "$storagePath$",
language: "zh",
"common.theme": "auto",
"desktop:wallpaper": "",
"editor.bg": "",
@ -30,6 +30,6 @@ export default {
"update.repo": "wood-desktop",
"update.owner": "npmrun",
"update.allowDowngrade": false,
"update.allowPrerelease": false
}
"update.allowPrerelease": false,
},
} as IConfig

12
electron-builder.yml

@ -3,12 +3,12 @@ productName: my-app
directories:
buildResources: build
files:
- '!**/.vscode/*'
- '!src/*'
- '!electron.vite.config.{js,ts,mjs,cjs}'
- '!{.eslintignore,.eslintrc.cjs,.prettierignore,.prettierrc.yaml,dev-app-update.yml,CHANGELOG.md,README.md}'
- '!{.env,.env.*,.npmrc,pnpm-lock.yaml}'
- '!{tsconfig.json,tsconfig.node.json,tsconfig.web.json}'
- "!**/.vscode/*"
- "!src/*"
- "!electron.vite.config.{js,ts,mjs,cjs}"
- "!{.eslintignore,.eslintrc.cjs,.prettierignore,.prettierrc.yaml,dev-app-update.yml,CHANGELOG.md,README.md}"
- "!{.env,.env.*,.npmrc,pnpm-lock.yaml}"
- "!{tsconfig.json,tsconfig.node.json,tsconfig.web.json}"
asarUnpack:
- resources/**
win:

28
electron.vite.config.ts

@ -1,28 +1,28 @@
import { resolve } from 'path'
import { defineConfig, externalizeDepsPlugin } from 'electron-vite'
import vue from '@vitejs/plugin-vue'
import UnoCSS from 'unocss/vite'
import { resolve } from "path"
import { defineConfig, externalizeDepsPlugin } from "electron-vite"
import vue from "@vitejs/plugin-vue"
import UnoCSS from "unocss/vite"
export default defineConfig({
main: {
resolve: {
alias: {
config: resolve('config'),
vc: resolve('src/main'),
res: resolve('resources')
}
config: resolve("config"),
vc: resolve("src/main"),
res: resolve("resources"),
},
plugins: [externalizeDepsPlugin()]
},
plugins: [externalizeDepsPlugin()],
},
preload: {
plugins: [externalizeDepsPlugin()]
plugins: [externalizeDepsPlugin()],
},
renderer: {
resolve: {
alias: {
'@renderer': resolve('src/renderer/src')
}
"@renderer": resolve("src/renderer/src"),
},
},
plugins: [UnoCSS(), vue()],
},
plugins: [UnoCSS(), vue()]
}
})

46
src/main/index.ts

@ -1,10 +1,10 @@
import "reflect-metadata";
import { app, shell, BrowserWindow, ipcMain } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from 'res/icon.png?asset'
import { container } from 'vc/modules'
import { App } from 'vc/modules/App'
import "reflect-metadata"
import { app, shell, BrowserWindow, ipcMain } from "electron"
import { join } from "path"
import { electronApp, optimizer, is } from "@electron-toolkit/utils"
import icon from "res/icon.png?asset"
import { container } from "vc/modules"
import { App } from "vc/modules/App"
container.get(App).init()
@ -15,28 +15,28 @@ function createWindow(): void {
height: 670,
show: false,
autoHideMenuBar: true,
...(process.platform === 'linux' ? { icon } : {}),
...(process.platform === "linux" ? { icon } : {}),
webPreferences: {
preload: join(__dirname, '../preload/index.mjs'),
sandbox: false
}
preload: join(__dirname, "../preload/index.mjs"),
sandbox: false,
},
})
mainWindow.on('ready-to-show', () => {
mainWindow.on("ready-to-show", () => {
mainWindow.show()
})
mainWindow.webContents.setWindowOpenHandler((details) => {
mainWindow.webContents.setWindowOpenHandler(details => {
shell.openExternal(details.url)
return { action: 'deny' }
return { action: "deny" }
})
// HMR for renderer base on electron-vite cli.
// Load the remote URL for development or the local html file for production.
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
if (is.dev && process.env["ELECTRON_RENDERER_URL"]) {
mainWindow.loadURL(process.env["ELECTRON_RENDERER_URL"])
} else {
mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
mainWindow.loadFile(join(__dirname, "../renderer/index.html"))
}
}
@ -45,21 +45,21 @@ function createWindow(): void {
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
// Set app user model id for windows
electronApp.setAppUserModelId('com.electron')
electronApp.setAppUserModelId("com.electron")
// Default open or close DevTools by F12 in development
// and ignore CommandOrControl + R in production.
// see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
app.on('browser-window-created', (_, window) => {
app.on("browser-window-created", (_, window) => {
optimizer.watchWindowShortcuts(window)
})
// IPC test
ipcMain.on('ping', () => console.log(icon))
ipcMain.on("ping", () => console.log(icon))
createWindow()
app.on('activate', function () {
app.on("activate", function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
@ -69,8 +69,8 @@ app.whenReady().then(() => {
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit()
}
})

16
src/main/modules/App.ts

@ -2,30 +2,24 @@ import { injectable, inject } from "inversify"
import Setting from "./setting"
import DB from "./db"
@injectable()
class App {
private _setting: Setting
private _db: DB
constructor(
@inject(Setting) setting: Setting,
@inject(DB) db: DB,
) {
console.log(`App inited`);
constructor(@inject(Setting) setting: Setting, @inject(DB) db: DB) {
console.log(`App inited`)
this._setting = setting
this._db = db
}
async init() {
console.log(this._setting.config());
console.log(this._setting.config())
this._db.saveData("aaa", { a: 123123 })
console.log(await this._db.getData("aaa"));
console.log(await this._db.getData("aaa"))
}
}
export default App
export {
App
}
export { App }

10
src/main/modules/db/custom.ts

@ -1,18 +1,18 @@
import { JSONFile } from "lowdb/node"
import { Low } from 'lowdb'
import fs from 'fs-extra'
import { Low } from "lowdb"
import fs from "fs-extra"
export class CustomAdapter<T> extends JSONFile<T> {
constructor(filepath: string) {
super(filepath)
this.filepath = filepath
}
filepath: string = ''
filepath: string = ""
async read() {
if (!fs.existsSync(this.filepath)) {
return null
}
let data = fs.readJSONSync(this.filepath, { throws: false })
const data = fs.readJSONSync(this.filepath, { throws: false })
if (!data) {
return null
}
@ -29,5 +29,5 @@ export class CustomLow<T> extends Low<T> {
super(adapter, defaultData)
this.filepath = adapter.filepath
}
filepath: string = ''
filepath: string = ""
}

28
src/main/modules/db/index.ts

@ -1,7 +1,7 @@
import { inject, injectable } from "inversify";
import Setting from "../setting";
import { CustomAdapter, CustomLow } from "./custom";
import path from "node:path";
import { inject, injectable } from "inversify"
import Setting from "../setting"
import { CustomAdapter, CustomLow } from "./custom"
import path from "node:path"
@injectable()
class DB {
@ -9,26 +9,26 @@ class DB {
Modules: Record<string, CustomLow<any>> = {}
constructor(@inject(Setting) setting: Setting) {
console.log(`DB inited`);
console.log(`DB inited`)
this._setting = setting
}
create(filepath) {
let adapter = new CustomAdapter<any>(filepath)
const db = new CustomLow<{}>(adapter, {})
const adapter = new CustomAdapter<any>(filepath)
const db = new CustomLow<object>(adapter, {})
db.filepath = filepath
return db
}
getDB(dbName: string) {
if (this.Modules[dbName] === undefined) {
let filepath = path.resolve(this._setting.values("storagePath"), './db/' + dbName + '.json')
const filepath = path.resolve(this._setting.values("storagePath"), "./db/" + dbName + ".json")
this.Modules[dbName] = this.create(filepath)
return this.Modules[dbName]
} else {
let cur = this.Modules[dbName]
let filepath = path.resolve(this._setting.values("storagePath"), './db/' + dbName + '.json')
const cur = this.Modules[dbName]
const filepath = path.resolve(this._setting.values("storagePath"), "./db/" + dbName + ".json")
if (cur.filepath != filepath) {
this.Modules[dbName] = this.create(filepath)
}
@ -44,7 +44,7 @@ class DB {
db = this.getDB(dbName)
rData = data
} else {
db = this.getDB('db')
db = this.getDB("db")
rData = dbName
}
if (db) {
@ -60,7 +60,7 @@ class DB {
if (dbName) {
db = this.getDB(dbName)
} else {
db = this.getDB('db')
db = this.getDB("db")
}
if (db) {
await db.read()
@ -71,6 +71,4 @@ class DB {
}
export default DB
export {
DB
}
export { DB }

4
src/main/modules/index.ts

@ -6,6 +6,4 @@ const container = new Container()
container.load(module)
export default container
export {
container
}
export { container }

6
src/main/modules/module.ts

@ -3,13 +3,11 @@ import { Setting } from "./setting"
import { DB } from "./db"
import App from "./App"
const module = new ContainerModule((bind) => {
const module = new ContainerModule(bind => {
bind(Setting).toConstantValue(new Setting())
bind(DB).toSelf().inSingletonScope()
bind(App).toSelf().inSingletonScope()
})
export default module
export {
module
}
export { module }

45
src/main/modules/setting/index.ts

@ -11,13 +11,13 @@ type IOnFunc = (n: IConfig, c: IConfig, keys?: (keyof IConfig)[]) => void
type IT = (keyof IConfig)[] | keyof IConfig | "_"
let storagePath = path.join(app.getPath("documents"), Config.app_title)
let storagePathDev = path.join(app.getPath("documents"), Config.app_title + "-dev")
const storagePathDev = path.join(app.getPath("documents"), Config.app_title + "-dev")
if (process.env.NODE_ENV === "development") {
storagePath = storagePathDev
}
let _tempConfig = cloneDeep(Config.default_config as IConfig)
const _tempConfig = cloneDeep(Config.default_config as IConfig)
Object.keys(_tempConfig).forEach(key => {
if (typeof _tempConfig[key] === "string" && _tempConfig[key].includes("$storagePath$")) {
_tempConfig[key] = _tempConfig[key].replace(/\$storagePath\$/g, storagePath)
@ -29,7 +29,7 @@ Object.keys(_tempConfig).forEach(key => {
function isPath(str) {
// 使用正则表达式检查字符串是否以斜杠或盘符开头
return /^(?:\/|[a-zA-Z]:\\)/.test(str);
return /^(?:\/|[a-zA-Z]:\\)/.test(str)
}
function init(config: IConfig) {
@ -46,7 +46,7 @@ function init(config: IConfig) {
// 判断是否是空文件夹
function isEmptyDir(fPath: string) {
var pa = fs.readdirSync(fPath)
const pa = fs.readdirSync(fPath)
if (pa.length === 0) {
return true
} else {
@ -57,7 +57,7 @@ function isEmptyDir(fPath: string) {
@injectable()
class Setting {
constructor() {
console.log(`Setting inited`);
console.log(`Setting inited`)
this.#init()
}
@ -90,7 +90,10 @@ class Setting {
}
}
#pathFile: string = process.env.NODE_ENV === "development" ? path.resolve(app.getPath("userData"), "./config_path-dev") : path.resolve(app.getPath("userData"), "./config_path")
#pathFile: string =
process.env.NODE_ENV === "development"
? path.resolve(app.getPath("userData"), "./config_path-dev")
: path.resolve(app.getPath("userData"), "./config_path")
#config: IConfig = cloneDeep(_tempConfig)
#configPath(storagePath?: string): string {
return path.join(storagePath || this.#config.storagePath, "./config.json")
@ -159,10 +162,10 @@ class Setting {
this.set(key, cloneDeep(_tempConfig[key]))
}
set(key: keyof IConfig | Partial<IConfig>, value?: any) {
let oldMainConfig = Object.assign({}, this.#config)
const oldMainConfig = Object.assign({}, this.#config)
let isChange = false
let changeKeys: (keyof IConfig)[] = []
let canChangeStorage = (targetPath: string) => {
const changeKeys: (keyof IConfig)[] = []
const canChangeStorage = (targetPath: string) => {
if (fs.existsSync(oldMainConfig.storagePath) && fs.existsSync(targetPath) && !isEmptyDir(targetPath)) {
if (fs.existsSync(path.join(targetPath, "./config.json"))) {
return true
@ -178,11 +181,7 @@ class Setting {
throw "无法改变存储地址"
return
}
try {
this.#change(value)
} catch (error) {
throw error
}
changeKeys.push("storagePath")
this.#config["storagePath"] = value
} else {
@ -192,21 +191,17 @@ class Setting {
isChange = true
}
} else {
if (key['storagePath'] !== undefined && key['storagePath'] !== this.#config['storagePath']) {
if (!canChangeStorage(key['storagePath'])) {
if (key["storagePath"] !== undefined && key["storagePath"] !== this.#config["storagePath"]) {
if (!canChangeStorage(key["storagePath"])) {
throw "无法改变存储地址"
return
}
try {
this.#change(key['storagePath'])
} catch (error) {
throw error
}
this.#config['storagePath'] = key['storagePath']
changeKeys.push('storagePath')
this.#change(key["storagePath"])
this.#config["storagePath"] = key["storagePath"]
changeKeys.push("storagePath")
isChange = true
}
for (const _ in key as any) {
for (const _ in key) {
if (Object.prototype.hasOwnProperty.call(key, _)) {
const v = key[_]
if (v != undefined && _ !== "storagePath" && v !== this.#config[_]) {
@ -228,6 +223,4 @@ class Setting {
}
export default Setting
export {
Setting
}
export { Setting }

2
src/preload/index.d.ts

@ -1,4 +1,4 @@
import { ElectronAPI } from '@electron-toolkit/preload'
import { ElectronAPI } from "@electron-toolkit/preload"
declare global {
interface Window {

8
src/preload/index.ts

@ -1,5 +1,5 @@
import { contextBridge } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'
import { contextBridge } from "electron"
import { electronAPI } from "@electron-toolkit/preload"
// Custom APIs for renderer
const api = {}
@ -9,8 +9,8 @@ const api = {}
// just add to the DOM global.
if (process.contextIsolated) {
try {
contextBridge.exposeInMainWorld('electron', electronAPI)
contextBridge.exposeInMainWorld('api', api)
contextBridge.exposeInMainWorld("electron", electronAPI)
contextBridge.exposeInMainWorld("api", api)
} catch (error) {
console.error(error)
}

10
src/renderer/src/App.vue

@ -1,7 +1,7 @@
<script setup lang="ts">
import Versions from './components/Versions.vue'
import Versions from "./components/Versions.vue"
const ipcHandle = () => window.electron.ipcRenderer.send('ping')
const ipcHandle = () => window.electron.ipcRenderer.send("ping")
</script>
<template>
@ -13,7 +13,11 @@ const ipcHandle = () => window.electron.ipcRenderer.send('ping')
and
<span class="ts">TypeScript</span>
</div>
<p class="tip">Please try pressing <code>F12</code> to open the devTool</p>
<p class="tip">
Please try pressing
<code>F12</code>
to open the devTool
</p>
<div class="actions">
<div class="action">
<a href="https://electron-vite.org/" target="_blank" rel="noreferrer">Documentation</a>

8
src/renderer/src/assets/base.css

@ -52,14 +52,14 @@ body {
Inter,
-apple-system,
BlinkMacSystemFont,
'Segoe UI',
"Segoe UI",
Roboto,
Oxygen,
Ubuntu,
Cantarell,
'Fira Sans',
'Droid Sans',
'Helvetica Neue',
"Fira Sans",
"Droid Sans",
"Helvetica Neue",
sans-serif;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;

6
src/renderer/src/assets/main.css

@ -1,11 +1,11 @@
@import './base.css';
@import "./base.css";
body {
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
background-image: url('./wavy-lines.svg');
background-image: url("./wavy-lines.svg");
background-size: cover;
user-select: none;
}
@ -129,7 +129,7 @@ code {
bottom: 30px;
margin: 0 auto;
padding: 15px 0;
font-family: 'Menlo', 'Lucida Console', monospace;
font-family: "Menlo", "Lucida Console", monospace;
display: inline-flex;
overflow: hidden;
align-items: center;

2
src/renderer/src/components/Versions.vue

@ -1,5 +1,5 @@
<script setup lang="ts">
import { reactive } from 'vue'
import { reactive } from "vue"
const versions = reactive({ ...window.electron.process.versions })
</script>

4
src/renderer/src/env.d.ts

@ -1,7 +1,7 @@
/// <reference types="vite/client" />
declare module '*.vue' {
import type { DefineComponent } from 'vue'
declare module "*.vue" {
import type { DefineComponent } from "vue"
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types
const component: DefineComponent<{}, {}, any>
export default component

12
src/renderer/src/main.ts

@ -1,8 +1,8 @@
import 'virtual:uno.css'
import '@unocss/reset/normalize.css'
import './assets/main.css'
import "virtual:uno.css"
import "@unocss/reset/normalize.css"
import "./assets/main.css"
import { createApp } from 'vue'
import App from './App.vue'
import { createApp } from "vue"
import App from "./App.vue"
createApp(App).mount('#app')
createApp(App).mount("#app")

4
src/renderer/src/shims.d.ts

@ -1,5 +1,5 @@
import type { AttributifyAttributes } from '@unocss/preset-attributify'
import type { AttributifyAttributes } from "@unocss/preset-attributify"
declare module '@vue/runtime-dom' {
declare module "@vue/runtime-dom" {
interface HTMLAttributes extends AttributifyAttributes {}
}

10
uno.config.ts

@ -1,10 +1,6 @@
import { defineConfig, presetAttributify, presetUno } from 'unocss'
import presetRemToPx from '@unocss/preset-rem-to-px'
import { defineConfig, presetAttributify, presetUno } from "unocss"
import presetRemToPx from "@unocss/preset-rem-to-px"
export default defineConfig({
presets: [
presetAttributify(),
presetUno(),
presetRemToPx(),
],
presets: [presetAttributify(), presetUno(), presetRemToPx()],
})
Loading…
Cancel
Save