@thirty-coder/electron-base-kit 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -32,13 +32,38 @@ Electron 桌面应用的基础能力,业务项目以 npm 依赖引入。
32
32
  业务项目在 `electron/main.ts` 里调用:
33
33
 
34
34
  ```ts
35
- import { bootstrap } from '@thirty-coder/electron-base-kit'
35
+ import { bootstrap, createWindow } from '@thirty-coder/electron-base-kit'
36
+ import { join } from 'node:path'
36
37
  import config from '../app.config.json'
37
38
 
38
- bootstrap(config)
39
+ app.whenReady().then(() => {
40
+ bootstrap(config)
41
+
42
+ createWindow({
43
+ preload: join(__dirname, '../preload/preload.js'),
44
+ renderer: join(__dirname, '../renderer/index.html'),
45
+ })
46
+ })
47
+ ```
48
+
49
+ 框架不读配置文件,config 由项目传入。`preload`、`renderer` 必须是业务传的绝对路径,因为本包装在 `node_modules` 里拿不到业务的目录结构。
50
+
51
+ ## 窗口
52
+
53
+ `createWindow` 接管了这些事:
54
+
55
+ - 记忆位置和尺寸,下次启动回到原处
56
+ - 窗口跑到屏幕外(拔掉副屏、改分辨率)时拉回可见区域
57
+ - `show: false` + `ready-to-show`,启动不白屏
58
+ - `contextIsolation`、`sandbox`、`nodeIntegration: false` 默认按安全基线配好
59
+
60
+ 多窗口每个传一个 `id`,记忆数据按 `id` 分开存:
61
+
62
+ ```ts
63
+ createWindow({ id: 'settings', preload, renderer, width: 640, height: 480, remember: false })
39
64
  ```
40
65
 
41
- 框架不读配置文件,config 由项目传入。
66
+ 不传 `id` 就是 `main`。窗口尺寸和开关默认读 `app.config.json` 的 `window`,只有需要和主窗口不同的窗口才在参数里覆盖。
42
67
 
43
68
  ## 配置
44
69
 
@@ -59,7 +84,7 @@ bootstrap(config)
59
84
  "url": "https://dl.example.com/myapp"
60
85
  },
61
86
  "license": { "publicKey": "" },
62
- "window": { "width": 1200, "height": 800, "minWidth": 900, "minHeight": 600 }
87
+ "window": { "width": 1200, "height": 800, "minWidth": 900, "minHeight": 600, "remember": true, "ensureVisible": true }
63
88
  }
64
89
  ```
65
90
 
package/dist/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { BrowserWindow } from 'electron';
2
+
1
3
  /** 能力开关。未声明的能力视为关闭。 */
2
4
  interface FeatureFlags {
3
5
  updater?: boolean;
@@ -29,6 +31,10 @@ interface WindowConfig {
29
31
  height?: number;
30
32
  minWidth?: number;
31
33
  minHeight?: number;
34
+ /** 记忆位置和尺寸,默认 true */
35
+ remember?: boolean;
36
+ /** 窗口跑到屏幕外时拉回来,默认 true */
37
+ ensureVisible?: boolean;
32
38
  }
33
39
  /** 由业务项目传入,框架不读文件。 */
34
40
  interface AppConfig {
@@ -55,6 +61,27 @@ interface SettingsApi {
55
61
  }
56
62
  declare const settings: SettingsApi;
57
63
 
64
+ interface CreateWindowOptions {
65
+ /** preload 脚本绝对路径 */
66
+ preload: string;
67
+ /** 生产环境入口绝对路径 */
68
+ renderer: string;
69
+ /** 窗口标识,默认 main。决定记忆数据存在哪个键下 */
70
+ id?: string;
71
+ width?: number;
72
+ height?: number;
73
+ minWidth?: number;
74
+ minHeight?: number;
75
+ remember?: boolean;
76
+ ensureVisible?: boolean;
77
+ }
78
+ /**
79
+ * 创建窗口。位置和尺寸从 settings 里按 id 读写。
80
+ *
81
+ * 必须在 bootstrap 之后调用。
82
+ */
83
+ declare function createWindow(options: CreateWindowOptions): BrowserWindow;
84
+
58
85
  /**
59
86
  * 初始化框架。
60
87
  *
@@ -62,5 +89,5 @@ declare const settings: SettingsApi;
62
89
  */
63
90
  declare function bootstrap(config: AppConfig): void;
64
91
 
65
- export { bootstrap, settings };
66
- export type { AppConfig, FeatureFlags, LicenseConfig, SettingsApi, UpdateConfig, UpdateProvider, WindowConfig };
92
+ export { bootstrap, createWindow, settings };
93
+ export type { AppConfig, CreateWindowOptions, FeatureFlags, LicenseConfig, SettingsApi, UpdateConfig, UpdateProvider, WindowConfig };
package/dist/index.js CHANGED
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  bootstrap: () => bootstrap,
24
+ createWindow: () => createWindow,
24
25
  settings: () => settings
25
26
  });
26
27
  module.exports = __toCommonJS(index_exports);
@@ -176,6 +177,161 @@ var settings = {
176
177
  }
177
178
  };
178
179
 
180
+ // src/window.ts
181
+ var import_electron2 = require("electron");
182
+ var FALLBACK = { width: 1200, height: 800, minWidth: 900, minHeight: 600 };
183
+ var VISIBLE_RATIO = 0.3;
184
+ var SAVE_DELAY = 300;
185
+ var defaults = {};
186
+ function setWindowDefaults(config) {
187
+ defaults = config ?? {};
188
+ }
189
+ function clamp(value, min, max) {
190
+ return Math.min(Math.max(value, min), max);
191
+ }
192
+ function intersectArea(a, b) {
193
+ const width = Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x);
194
+ const height = Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y);
195
+ return width > 0 && height > 0 ? width * height : 0;
196
+ }
197
+ function isBounds(value) {
198
+ if (value === null || typeof value !== "object") return false;
199
+ const bounds = value;
200
+ for (const key of ["x", "y", "width", "height"]) {
201
+ if (!Number.isFinite(bounds[key])) return false;
202
+ }
203
+ return bounds.width > 0 && bounds.height > 0;
204
+ }
205
+ function bestWorkArea(rect) {
206
+ let best = import_electron2.screen.getPrimaryDisplay().workArea;
207
+ let bestArea = 0;
208
+ for (const display of import_electron2.screen.getAllDisplays()) {
209
+ const area = intersectArea(rect, display.workArea);
210
+ if (area > bestArea) {
211
+ bestArea = area;
212
+ best = display.workArea;
213
+ }
214
+ }
215
+ return best;
216
+ }
217
+ function centerOnPrimary(size) {
218
+ const primary = import_electron2.screen.getPrimaryDisplay().workArea;
219
+ const width = Math.min(size.width, primary.width);
220
+ const height = Math.min(size.height, primary.height);
221
+ return {
222
+ x: primary.x + Math.round((primary.width - width) / 2),
223
+ y: primary.y + Math.round((primary.height - height) / 2),
224
+ width,
225
+ height
226
+ };
227
+ }
228
+ function resolveBounds(saved, size, ensureVisible) {
229
+ if (!saved) {
230
+ return { bounds: { width: size.width, height: size.height }, center: true };
231
+ }
232
+ if (!ensureVisible) {
233
+ return { bounds: saved, center: false };
234
+ }
235
+ const area = bestWorkArea(saved);
236
+ const ratio = intersectArea(saved, area) / (saved.width * saved.height);
237
+ if (ratio < VISIBLE_RATIO) {
238
+ return { bounds: centerOnPrimary(saved), center: false };
239
+ }
240
+ const width = Math.min(saved.width, area.width);
241
+ const height = Math.min(saved.height, area.height);
242
+ return {
243
+ bounds: {
244
+ x: clamp(saved.x, area.x, area.x + area.width - width),
245
+ y: clamp(saved.y, area.y, area.y + area.height - height),
246
+ width,
247
+ height
248
+ },
249
+ center: false
250
+ };
251
+ }
252
+ function attachPersistence(win, key) {
253
+ let timer2 = null;
254
+ const save = () => {
255
+ if (win.isDestroyed()) return;
256
+ if (win.isMaximized() || win.isMinimized() || win.isFullScreen()) return;
257
+ settings.set(`${key}.bounds`, win.getBounds());
258
+ };
259
+ const schedule2 = () => {
260
+ if (timer2) clearTimeout(timer2);
261
+ timer2 = setTimeout(() => {
262
+ timer2 = null;
263
+ save();
264
+ }, SAVE_DELAY);
265
+ timer2.unref?.();
266
+ };
267
+ win.on("move", schedule2);
268
+ win.on("resize", schedule2);
269
+ win.on("maximize", () => settings.set(`${key}.maximized`, true));
270
+ win.on("unmaximize", () => settings.set(`${key}.maximized`, false));
271
+ win.on("close", () => {
272
+ if (timer2) {
273
+ clearTimeout(timer2);
274
+ timer2 = null;
275
+ }
276
+ save();
277
+ });
278
+ }
279
+ function attachDisplayGuard(win) {
280
+ const handle = () => {
281
+ if (win.isDestroyed()) return;
282
+ if (win.isMaximized() || win.isMinimized() || win.isFullScreen()) return;
283
+ const current = win.getBounds();
284
+ const area = bestWorkArea(current);
285
+ if (intersectArea(current, area) / (current.width * current.height) >= VISIBLE_RATIO) return;
286
+ win.setBounds(centerOnPrimary(current));
287
+ };
288
+ import_electron2.screen.on("display-removed", handle);
289
+ import_electron2.screen.on("display-metrics-changed", handle);
290
+ win.once("closed", () => {
291
+ import_electron2.screen.removeListener("display-removed", handle);
292
+ import_electron2.screen.removeListener("display-metrics-changed", handle);
293
+ });
294
+ }
295
+ function createWindow(options) {
296
+ const id = options.id ?? "main";
297
+ const remember = options.remember ?? defaults.remember ?? true;
298
+ const ensureVisible = options.ensureVisible ?? defaults.ensureVisible ?? true;
299
+ const size = {
300
+ width: options.width ?? defaults.width ?? FALLBACK.width,
301
+ height: options.height ?? defaults.height ?? FALLBACK.height
302
+ };
303
+ const minWidth = options.minWidth ?? defaults.minWidth ?? FALLBACK.minWidth;
304
+ const minHeight = options.minHeight ?? defaults.minHeight ?? FALLBACK.minHeight;
305
+ const key = `window.${id}`;
306
+ const saved = remember ? settings.get(`${key}.bounds`, void 0) : void 0;
307
+ const maximized = remember ? settings.get(`${key}.maximized`, false) : false;
308
+ const { bounds, center } = resolveBounds(isBounds(saved) ? saved : void 0, size, ensureVisible);
309
+ const win = new import_electron2.BrowserWindow({
310
+ ...bounds,
311
+ minWidth,
312
+ minHeight,
313
+ center,
314
+ show: false,
315
+ backgroundColor: "#ffffff",
316
+ webPreferences: {
317
+ preload: options.preload,
318
+ contextIsolation: true,
319
+ nodeIntegration: false,
320
+ sandbox: true
321
+ }
322
+ });
323
+ if (maximized) win.maximize();
324
+ win.once("ready-to-show", () => win.show());
325
+ if (process.env.ELECTRON_RENDERER_URL) {
326
+ win.loadURL(process.env.ELECTRON_RENDERER_URL);
327
+ } else {
328
+ win.loadFile(options.renderer);
329
+ }
330
+ if (remember) attachPersistence(win, key);
331
+ if (ensureVisible) attachDisplayGuard(win);
332
+ return win;
333
+ }
334
+
179
335
  // src/bootstrap.ts
180
336
  function assertConfig(config) {
181
337
  if (!config || typeof config !== "object") {
@@ -191,6 +347,7 @@ function assertConfig(config) {
191
347
  function bootstrap(config) {
192
348
  assertConfig(config);
193
349
  initSettings();
350
+ setWindowDefaults(config.window);
194
351
  if (config.features?.updater) {
195
352
  }
196
353
  if (config.features?.license) {
@@ -213,5 +370,6 @@ function bootstrap(config) {
213
370
  // Annotate the CommonJS export names for ESM import in node:
214
371
  0 && (module.exports = {
215
372
  bootstrap,
373
+ createWindow,
216
374
  settings
217
375
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thirty-coder/electron-base-kit",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Electron 桌面应用基础能力",
5
5
  "license": "MIT",
6
6
  "repository": {