@thirty-coder/electron-base-kit 0.1.0 → 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,12 +84,32 @@ 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
 
66
91
  `updater` 打开后要填 `update`,`license` 打开后要填 `publicKey`。
67
92
 
93
+ ## 配置存储
94
+
95
+ `app.config.json` 是只读的项目配置。用户数据(窗口尺寸、上次打开的目录)用 `settings`:
96
+
97
+ ```ts
98
+ import { settings } from '@thirty-coder/electron-base-kit'
99
+
100
+ settings.get('window.bounds', { width: 1200, height: 800 })
101
+ settings.set('window.bounds', { width: 1440, height: 900, x: 100, y: 80 })
102
+ settings.has('window.bounds')
103
+ settings.remove('window.bounds')
104
+ settings.all()
105
+ settings.onChange('window.bounds', (bounds) => { /* ... */ })
106
+ settings.filePath
107
+ ```
108
+
109
+ 键是点分字符串,平铺存在 `<userData>/settings.json`。读走内存,写防抖 100ms,退出前同步落盘。文件损坏会改名成 `settings.bad.json` 留档,按空数据启动。
110
+
111
+ `bootstrap` 之后才能用,提前访问会抛错。
112
+
68
113
  ## 升级
69
114
 
70
115
  ```bash
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 {
@@ -42,12 +48,46 @@ interface AppConfig {
42
48
  window?: WindowConfig;
43
49
  }
44
50
 
51
+ type Listener = (value: unknown) => void;
52
+ interface SettingsApi {
53
+ get<T>(key: string, fallback: T): T;
54
+ set(key: string, value: unknown): void;
55
+ has(key: string): boolean;
56
+ remove(key: string): void;
57
+ all(): Record<string, unknown>;
58
+ onChange(key: string, listener: Listener): () => void;
59
+ flush(): Promise<void>;
60
+ readonly filePath: string;
61
+ }
62
+ declare const settings: SettingsApi;
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
+
45
85
  /**
46
86
  * 初始化框架。
47
87
  *
48
- * 骨架阶段只保存配置,各能力后续逐个接入。
88
+ * 常开能力初始化失败直接抛;可选能力失败只记错误,继续启动。
49
89
  */
50
90
  declare function bootstrap(config: AppConfig): void;
51
91
 
52
- export { bootstrap };
53
- export type { AppConfig, FeatureFlags, LicenseConfig, UpdateConfig, UpdateProvider, WindowConfig };
92
+ export { bootstrap, createWindow, settings };
93
+ export type { AppConfig, CreateWindowOptions, FeatureFlags, LicenseConfig, SettingsApi, UpdateConfig, UpdateProvider, WindowConfig };
package/dist/index.js CHANGED
@@ -20,15 +20,356 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
- bootstrap: () => bootstrap
23
+ bootstrap: () => bootstrap,
24
+ createWindow: () => createWindow,
25
+ settings: () => settings
24
26
  });
25
27
  module.exports = __toCommonJS(index_exports);
26
28
 
29
+ // src/settings.ts
30
+ var import_electron = require("electron");
31
+ var import_node_fs = require("fs");
32
+ var import_node_path = require("path");
33
+ var WRITE_DELAY = 100;
34
+ var store = null;
35
+ var filePath = "";
36
+ var dirty = false;
37
+ var timer = null;
38
+ var listeners = /* @__PURE__ */ new Map();
39
+ function assertInit() {
40
+ if (store === null) {
41
+ throw new Error("settings \u672A\u521D\u59CB\u5316\uFF1A\u8BF7\u5148\u5728 app.whenReady() \u4E2D\u8C03\u7528 bootstrap(config)");
42
+ }
43
+ return store;
44
+ }
45
+ function load() {
46
+ if (!(0, import_node_fs.existsSync)(filePath)) return {};
47
+ let raw;
48
+ try {
49
+ raw = (0, import_node_fs.readFileSync)(filePath, "utf8");
50
+ } catch (err) {
51
+ console.error("[electron-base-kit] \u8BFB\u53D6 settings \u5931\u8D25\uFF1A", err);
52
+ return {};
53
+ }
54
+ try {
55
+ const parsed = JSON.parse(raw);
56
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
57
+ throw new Error("\u6839\u8282\u70B9\u4E0D\u662F\u5BF9\u8C61");
58
+ }
59
+ return parsed;
60
+ } catch (err) {
61
+ console.error("[electron-base-kit] settings \u5185\u5BB9\u65E0\u6548\uFF0C\u5DF2\u6539\u540D\u7559\u6863\uFF1A", err);
62
+ try {
63
+ (0, import_node_fs.renameSync)(filePath, (0, import_node_path.join)((0, import_node_path.dirname)(filePath), "settings.bad.json"));
64
+ } catch (renameErr) {
65
+ console.error("[electron-base-kit] \u7559\u6863\u5931\u8D25\uFF1A", renameErr);
66
+ }
67
+ return {};
68
+ }
69
+ }
70
+ function writeNow() {
71
+ if (!dirty || store === null) return;
72
+ try {
73
+ const tmp = `${filePath}.tmp`;
74
+ (0, import_node_fs.writeFileSync)(tmp, `${JSON.stringify(store, null, 2)}
75
+ `);
76
+ (0, import_node_fs.renameSync)(tmp, filePath);
77
+ dirty = false;
78
+ } catch (err) {
79
+ console.error("[electron-base-kit] \u5199\u5165 settings \u5931\u8D25\uFF1A", err);
80
+ }
81
+ }
82
+ function schedule() {
83
+ dirty = true;
84
+ if (timer) return;
85
+ timer = setTimeout(() => {
86
+ timer = null;
87
+ writeNow();
88
+ }, WRITE_DELAY);
89
+ timer.unref?.();
90
+ }
91
+ function emit(key, value) {
92
+ const set = listeners.get(key);
93
+ if (!set) return;
94
+ for (const fn of [...set]) {
95
+ try {
96
+ fn(value);
97
+ } catch (err) {
98
+ console.error(`[electron-base-kit] settings.onChange(${key}) \u56DE\u8C03\u629B\u9519\uFF1A`, err);
99
+ }
100
+ }
101
+ }
102
+ function initSettings() {
103
+ if (store !== null) return;
104
+ filePath = (0, import_node_path.join)(import_electron.app.getPath("userData"), "settings.json");
105
+ (0, import_node_fs.mkdirSync)((0, import_node_path.dirname)(filePath), { recursive: true });
106
+ store = load();
107
+ import_electron.app.on("before-quit", () => {
108
+ if (timer) {
109
+ clearTimeout(timer);
110
+ timer = null;
111
+ }
112
+ writeNow();
113
+ });
114
+ }
115
+ var settings = {
116
+ get(key, fallback) {
117
+ const data = assertInit();
118
+ return key in data && data[key] !== void 0 ? data[key] : fallback;
119
+ },
120
+ set(key, value) {
121
+ const data = assertInit();
122
+ let serialized;
123
+ try {
124
+ serialized = JSON.stringify(value);
125
+ } catch {
126
+ throw new TypeError(`settings.set('${key}') \u7684\u503C\u65E0\u6CD5\u5E8F\u5217\u5316\u4E3A JSON`);
127
+ }
128
+ if (serialized === void 0) {
129
+ throw new TypeError(`settings.set('${key}') \u7684\u503C\u65E0\u6CD5\u5E8F\u5217\u5316\u4E3A JSON`);
130
+ }
131
+ const previous = key in data ? JSON.stringify(data[key]) : void 0;
132
+ if (previous === serialized) return;
133
+ data[key] = value;
134
+ schedule();
135
+ emit(key, value);
136
+ },
137
+ has(key) {
138
+ const data = assertInit();
139
+ return key in data && data[key] !== void 0;
140
+ },
141
+ remove(key) {
142
+ const data = assertInit();
143
+ if (!(key in data)) return;
144
+ delete data[key];
145
+ schedule();
146
+ emit(key, void 0);
147
+ },
148
+ all() {
149
+ return { ...assertInit() };
150
+ },
151
+ onChange(key, listener) {
152
+ assertInit();
153
+ let set = listeners.get(key);
154
+ if (!set) {
155
+ set = /* @__PURE__ */ new Set();
156
+ listeners.set(key, set);
157
+ }
158
+ set.add(listener);
159
+ return () => {
160
+ const current = listeners.get(key);
161
+ if (!current) return;
162
+ current.delete(listener);
163
+ if (current.size === 0) listeners.delete(key);
164
+ };
165
+ },
166
+ async flush() {
167
+ assertInit();
168
+ if (timer) {
169
+ clearTimeout(timer);
170
+ timer = null;
171
+ }
172
+ writeNow();
173
+ },
174
+ get filePath() {
175
+ assertInit();
176
+ return filePath;
177
+ }
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
+
27
335
  // src/bootstrap.ts
336
+ function assertConfig(config) {
337
+ if (!config || typeof config !== "object") {
338
+ throw new TypeError("bootstrap: \u7F3A\u5C11 config");
339
+ }
340
+ if (!config.appId) {
341
+ throw new Error("bootstrap: config.appId \u4E0D\u80FD\u4E3A\u7A7A");
342
+ }
343
+ if (!config.productName) {
344
+ throw new Error("bootstrap: config.productName \u4E0D\u80FD\u4E3A\u7A7A");
345
+ }
346
+ }
28
347
  function bootstrap(config) {
29
- void config;
348
+ assertConfig(config);
349
+ initSettings();
350
+ setWindowDefaults(config.window);
351
+ if (config.features?.updater) {
352
+ }
353
+ if (config.features?.license) {
354
+ }
355
+ if (config.features?.tray) {
356
+ }
357
+ if (config.features?.notify) {
358
+ }
359
+ if (config.features?.shortcut) {
360
+ }
361
+ if (config.features?.dialog) {
362
+ }
363
+ if (config.features?.clipboard) {
364
+ }
365
+ if (config.features?.autolaunch) {
366
+ }
367
+ if (config.features?.deeplink) {
368
+ }
30
369
  }
31
370
  // Annotate the CommonJS export names for ESM import in node:
32
371
  0 && (module.exports = {
33
- bootstrap
372
+ bootstrap,
373
+ createWindow,
374
+ settings
34
375
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thirty-coder/electron-base-kit",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Electron 桌面应用基础能力",
5
5
  "license": "MIT",
6
6
  "repository": {