src -> packages

This commit is contained in:
草鞋没号
2022-02-08 10:34:14 +08:00
parent c0b257f794
commit 9d702430f0
22 changed files with 25 additions and 19 deletions

70
packages/main/index.ts Normal file
View File

@@ -0,0 +1,70 @@
import os from 'os'
import path from 'path'
import { app, BrowserWindow } from 'electron'
// https://stackoverflow.com/questions/42524606/how-to-get-windows-version-using-node-js
const isWin7 = os.release().startsWith('6.1')
if (isWin7) app.disableHardwareAcceleration()
if (!app.requestSingleInstanceLock()) {
app.quit()
process.exit(0)
}
let win: BrowserWindow | null = null
async function createWindow() {
win = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, '../preload/index.cjs'),
},
})
if (app.isPackaged) {
win.loadFile(path.join(__dirname, '../renderer/index.html'))
} else {
const pkg = await import('../../package.json')
const url = `http://${pkg.env.HOST || '127.0.0.1'}:${pkg.env.PORT}`
win.loadURL(url)
win.webContents.openDevTools()
}
}
app.whenReady().then(createWindow)
app.on('window-all-closed', () => {
win = null
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('second-instance', () => {
if (win) {
// someone tried to run a second instance, we should focus our window.
if (win.isMinimized()) win.restore()
win.focus()
}
})
app.on('activate', () => {
const allWindows = BrowserWindow.getAllWindows()
if (allWindows.length) {
allWindows[0].focus()
} else {
createWindow()
}
})
// @TODO
// auto update
/* if (app.isPackaged) {
app.whenReady()
.then(() => import('electron-updater'))
.then(({ autoUpdater }) => autoUpdater.checkForUpdatesAndNotify())
.catch((e) =>
// maybe you need to record some log files.
console.error('Failed check update:', e)
)
} */

36
packages/preload/index.ts Normal file
View File

@@ -0,0 +1,36 @@
import fs from 'fs'
import { contextBridge, ipcRenderer, IpcRenderer } from 'electron'
import { domReady } from './utils'
import { useLoading } from './loading'
const isDev = process.env.NODE_ENV === 'development'
const { removeLoading, appendLoading } = useLoading()
domReady().then(() => {
appendLoading()
})
// --------- Expose some API to Renderer process. ---------
contextBridge.exposeInMainWorld('fs', fs)
contextBridge.exposeInMainWorld('removeLoading', removeLoading)
contextBridge.exposeInMainWorld('ipcRenderer', withPrototype(ipcRenderer))
// `exposeInMainWorld` can not detect `prototype` attribute and methods, manually patch it.
function withPrototype(obj: Record<string, any>) {
const protos = Object.getPrototypeOf(obj)
for (const [key, value] of Object.entries(protos)) {
if (Object.prototype.hasOwnProperty.call(obj, key)) continue
if (typeof value === 'function') {
// Some native API not work in Renderer-process, like `NodeJS.EventEmitter['on']`. Wrap a function patch it.
obj[key] = function (...args: any) {
return value.call(obj, ...args)
}
} else {
obj[key] = value
}
}
return obj
}

View File

@@ -0,0 +1,56 @@
/**
* https://tobiasahlin.com/spinkit
* https://connoratherton.com/loaders
* https://projects.lukehaas.me/css-loaders
* https://matejkustec.github.io/SpinThatShit
*/
export function useLoading() {
const className = `loaders-css__square-spin`
const styleContent = `
@keyframes square-spin {
25% { transform: perspective(100px) rotateX(180deg) rotateY(0); }
50% { transform: perspective(100px) rotateX(180deg) rotateY(180deg); }
75% { transform: perspective(100px) rotateX(0) rotateY(180deg); }
100% { transform: perspective(100px) rotateX(0) rotateY(0); }
}
.${className} > div {
animation-fill-mode: both;
width: 50px;
height: 50px;
background: #fff;
animation: square-spin 3s 0s cubic-bezier(0.09, 0.57, 0.49, 0.9) infinite;
}
.app-loading-wrap {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: #282c34;
z-index: 9;
}
`
const oStyle = document.createElement('style')
const oDiv = document.createElement('div')
oStyle.id = 'app-loading-style'
oStyle.innerHTML = styleContent
oDiv.className = 'app-loading-wrap'
oDiv.innerHTML = `<div class="${className}"><div></div></div>`
return {
appendLoading() {
document.head.appendChild(oStyle)
document.body.appendChild(oDiv)
},
removeLoading() {
document.head.removeChild(oStyle)
document.body.removeChild(oDiv)
},
}
}

15
packages/preload/utils.ts Normal file
View File

@@ -0,0 +1,15 @@
/** docoment ready */
export function domReady(condition: DocumentReadyState[] = ['complete', 'interactive']) {
return new Promise(resolve => {
if (condition.includes(document.readyState)) {
resolve(true)
} else {
document.addEventListener('readystatechange', () => {
if (condition.includes(document.readyState)) {
resolve(true)
}
})
}
})
}

View File

@@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

View File

@@ -0,0 +1,55 @@
<script setup lang="ts">
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup
import HelloWorld from './components/HelloWorld.vue'
</script>
<template>
<div class="logo-box">
<img style="height:140px;" src="./assets/electron.png" alt="Electron logo">
<span/>
<img style="height:140px;" alt="Vite logo" src="./assets/vite.svg" />
<span/>
<img style="height:140px;" alt="Vue logo" src="./assets/vue.png" />
</div>
<HelloWorld msg="Hello Vue 3 + TypeScript + Vite" />
<div class="static-public">
Place static files into the <code>src/renderer/public</code> folder
<img style="width:90px;" :src="'./images/node.png'" />
</div>
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
.logo-box {
display: flex;
width: 100%;
justify-content: center;
}
.logo-box span {
width: 74px;
}
.static-public {
display: flex;
align-items: center;
justify-content: center;
}
.static-public code {
background-color: #eee;
padding: 2px 4px;
margin: 0 4px;
border-radius: 4px;
color: #304455;
}
</style>

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

View File

@@ -0,0 +1,15 @@
<svg width="410" height="404" viewBox="0 0 410 404" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M399.641 59.5246L215.643 388.545C211.844 395.338 202.084 395.378 198.228 388.618L10.5817 59.5563C6.38087 52.1896 12.6802 43.2665 21.0281 44.7586L205.223 77.6824C206.398 77.8924 207.601 77.8904 208.776 77.6763L389.119 44.8058C397.439 43.2894 403.768 52.1434 399.641 59.5246Z" fill="url(#paint0_linear)"/>
<path d="M292.965 1.5744L156.801 28.2552C154.563 28.6937 152.906 30.5903 152.771 32.8664L144.395 174.33C144.198 177.662 147.258 180.248 150.51 179.498L188.42 170.749C191.967 169.931 195.172 173.055 194.443 176.622L183.18 231.775C182.422 235.487 185.907 238.661 189.532 237.56L212.947 230.446C216.577 229.344 220.065 232.527 219.297 236.242L201.398 322.875C200.278 328.294 207.486 331.249 210.492 326.603L212.5 323.5L323.454 102.072C325.312 98.3645 322.108 94.137 318.036 94.9228L279.014 102.454C275.347 103.161 272.227 99.746 273.262 96.1583L298.731 7.86689C299.767 4.27314 296.636 0.855181 292.965 1.5744Z" fill="url(#paint1_linear)"/>
<defs>
<linearGradient id="paint0_linear" x1="6.00017" y1="32.9999" x2="235" y2="344" gradientUnits="userSpaceOnUse">
<stop stop-color="#41D1FF"/>
<stop offset="1" stop-color="#BD34FE"/>
</linearGradient>
<linearGradient id="paint1_linear" x1="194.651" y1="8.81818" x2="236.076" y2="292.989" gradientUnits="userSpaceOnUse">
<stop stop-color="#FFEA83"/>
<stop offset="0.0833333" stop-color="#FFDD35"/>
<stop offset="1" stop-color="#FFA800"/>
</linearGradient>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

View File

@@ -0,0 +1,52 @@
<script setup lang="ts">
import { ref } from 'vue'
defineProps<{ msg: string }>()
const count = ref(0)
</script>
<template>
<h1>{{ msg }}</h1>
<p>
Recommended IDE setup:
<a href="https://code.visualstudio.com/" target="_blank">VSCode</a>
+
<a href="https://github.com/johnsoncodehk/volar" target="_blank">Volar</a>
</p>
<p>See <code>README.md</code> for more information.</p>
<p>
<a href="https://vitejs.dev/guide/features.html" target="_blank">
Vite Docs
</a>
|
<a href="https://v3.vuejs.org/" target="_blank">Vue 3 Docs</a>
</p>
<button type="button" @click="count++">count is: {{ count }}</button>
<p>
Edit
<code>components/HelloWorld.vue</code> to test hot module replacement.
</p>
</template>
<style scoped>
a {
color: #42b983;
}
label {
margin: 0 0.5em;
font-weight: bold;
}
code {
background-color: #eee;
padding: 2px 4px;
border-radius: 4px;
color: #304455;
}
</style>

8
packages/renderer/src/env.d.ts vendored Normal file
View File

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

11
packages/renderer/src/global.d.ts vendored Normal file
View File

@@ -0,0 +1,11 @@
export { }
declare global {
interface Window {
// Expose some Api through preload script
fs: typeof import('fs')
ipcRenderer: import('electron').IpcRenderer
removeLoading: () => void
}
}

View File

@@ -0,0 +1,9 @@
import { createApp } from 'vue'
import App from './App.vue'
createApp(App)
.mount('#app')
.$nextTick(window.removeLoading)
console.log('fs', window.fs)
console.log('ipcRenderer', window.ipcRenderer)

View File

@@ -0,0 +1,16 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"target": "esnext",
"useDefineForClassFields": true,
"module": "esnext",
"moduleResolution": "node",
"strict": true,
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"lib": ["esnext", "dom"]
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}

View File

@@ -0,0 +1,98 @@
import { join } from 'path'
import { builtinModules } from 'module'
import { defineConfig, Plugin } from 'vite'
import vue from '@vitejs/plugin-vue'
import resolve from 'vite-plugin-resolve'
import pkg from '../../package.json'
// https://vitejs.dev/config/
export default defineConfig({
mode: process.env.NODE_ENV,
root: __dirname,
plugins: [
vue(),
resolveElectron(
/**
* you can custom other module in here
* 🚧 need to make sure custom-resolve-module in `dependencies`, that will ensure that the electron-builder can package them correctly
* @example
* {
* 'electron-store': 'const Store = require("electron-store"); export defalut Store;',
* }
*/
),
],
base: './',
build: {
emptyOutDir: true,
outDir: '../../dist/renderer',
},
server: {
host: pkg.env.HOST,
port: pkg.env.PORT,
},
})
// ------- For use Electron, NodeJs in Renderer-process -------
// https://github.com/caoxiemeihao/electron-vue-vite/issues/52
export function resolveElectron(resolves: Parameters<typeof resolve>[0] = {}): Plugin {
const builtins = builtinModules.filter(t => !t.startsWith('_'))
// https://github.com/caoxiemeihao/vite-plugins/tree/main/packages/resolve#readme
return resolve({
electron: electronExport(),
...builtinModulesExport(builtins),
...resolves,
})
function electronExport() {
return `
/**
* All exports module see https://www.electronjs.org -> API -> Renderer Process Modules
*/
const electron = require("electron");
const {
clipboard,
nativeImage,
shell,
contextBridge,
crashReporter,
ipcRenderer,
webFrame,
desktopCapturer,
deprecate,
} = electron;
export {
electron as default,
clipboard,
nativeImage,
shell,
contextBridge,
crashReporter,
ipcRenderer,
webFrame,
desktopCapturer,
deprecate,
}
`
}
function builtinModulesExport(modules: string[]) {
return modules.map((moduleId) => {
const nodeModule = require(moduleId)
const requireModule = `const M = require("${moduleId}");`
const exportDefault = `export default M;`
const exportMembers = Object.keys(nodeModule).map(attr => `export const ${attr} = M.${attr}`).join(';\n') + ';'
const nodeModuleCode = `
${requireModule}
${exportDefault}
${exportMembers}
`
return { [moduleId]: nodeModuleCode }
}).reduce((memo, item) => Object.assign(memo, item), {})
}
}