create-tooldock-extension 0.0.0-stage → 1.0.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
@@ -1,3 +1,24 @@
1
- # Temporary Holding Version
1
+ # create-tooldock-extension
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 建立 ToolDock 擴充專案。
4
+
5
+ ```bash
6
+ npm create tooldock-extension@latest my-tool
7
+ ```
8
+
9
+ 執行後會以互動方式詢問 id、顯示名稱和範本。不想互動時可以直接帶參數:
10
+
11
+ ```bash
12
+ npm create tooldock-extension@latest my-tool -- --id my-tool --name "我的工具" --template service -y
13
+ ```
14
+
15
+ | 範本 | 內容 |
16
+ |---|---|
17
+ | `view` | 分頁畫面加後端:示範 `invoke`、`emit` 推送、`storage`、對話框、指令、設定與生命週期 |
18
+ | `service` | 背景服務:隨平台啟動、定時工作、狀態列、暫停與恢復、休眠與喚醒 |
19
+
20
+ 產生的專案包含 `tooldock-cli`、`tooldock-types`、JSDoc 型別檢查、VS Code 偵錯設定(F5)、`.tbxignore` 和 README。
21
+
22
+ 參數:
23
+ - `--no-install`:不自動執行 `npm install`
24
+ - `-y`:全部使用預設值
package/index.js ADDED
@@ -0,0 +1,197 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /**
4
+ * npm create tooldock-extension@latest [資料夾] [選項]
5
+ *
6
+ * --id <id> 擴充 id(預設取資料夾名稱)
7
+ * --name <顯示名稱>
8
+ * --template view|service
9
+ * --yes, -y 全部使用預設值,不詢問
10
+ * --no-install 不自動執行 npm install
11
+ * --cwd <資料夾> 相對路徑的基準目錄(預設為目前目錄)
12
+ */
13
+ const fs = require('fs');
14
+ const path = require('path');
15
+ const readline = require('readline');
16
+ const { spawnSync } = require('child_process');
17
+
18
+ const tty = process.stdout.isTTY;
19
+ const c = (n) => (s) => (tty ? `\x1b[${n}m${s}\x1b[0m` : String(s));
20
+ const bold = c(1);
21
+ const dim = c(2);
22
+ const green = c(32);
23
+ const red = c(31);
24
+ const cyan = c(36);
25
+
26
+ const TEMPLATES = {
27
+ view: '畫面 + 後端:有自己的分頁畫面,前端呼叫後端處理資料(大多數工具)',
28
+ service: '背景服務:隨平台啟動、定時執行、狀態列顯示(例如監控、同步)',
29
+ };
30
+ const ID_RE = /^[a-z0-9][a-z0-9.-]{0,62}$/;
31
+
32
+ function parseArgs(argv) {
33
+ const o = { _: [] };
34
+ for (let i = 0; i < argv.length; i++) {
35
+ const a = argv[i];
36
+ if (a === '-y' || a === '--yes') o.yes = true;
37
+ else if (a === '--no-install') o.noInstall = true;
38
+ else if (a.startsWith('--')) {
39
+ const [k, v] = a.slice(2).split('=');
40
+ o[k] = v !== undefined ? v : argv[++i];
41
+ } else o._.push(a);
42
+ }
43
+ return o;
44
+ }
45
+
46
+ function ask(rl, q, def) {
47
+ return new Promise((resolve) => rl.question(`${cyan('?')} ${q}${def ? dim(` (${def})`) : ''} `, (a) => resolve(a.trim() || def || '')));
48
+ }
49
+
50
+ /** 從本機原始碼執行(非 npm 安裝)時,相依改用 file: 指向同 repo 的套件,方便在發佈前測試 */
51
+ function localPackages() {
52
+ if (__dirname.split(path.sep).includes('node_modules')) return null;
53
+ const root = path.join(__dirname, '..');
54
+ const cli = path.join(root, 'cli');
55
+ const types = path.join(root, 'types');
56
+ if (fs.existsSync(path.join(cli, 'package.json')) && fs.existsSync(path.join(types, 'package.json'))) return { cli, types };
57
+ return null;
58
+ }
59
+
60
+ function render(text, vars) {
61
+ return text.replace(/\{\{(\w+)\}\}/g, (m, k) => (k in vars ? vars[k] : m));
62
+ }
63
+
64
+ function copyTemplate(src, dest, vars) {
65
+ for (const ent of fs.readdirSync(src, { withFileTypes: true })) {
66
+ // npm 發佈時會移除 .gitignore 等點檔,範本內以 _ 開頭命名
67
+ const name = ent.name.replace(/^_(gitignore|vscode|tbxignore)$/, '.$1');
68
+ const from = path.join(src, ent.name);
69
+ const to = path.join(dest, name);
70
+ if (ent.isDirectory()) {
71
+ fs.mkdirSync(to, { recursive: true });
72
+ copyTemplate(from, to, vars);
73
+ } else {
74
+ fs.writeFileSync(to, render(fs.readFileSync(from, 'utf8'), vars));
75
+ }
76
+ }
77
+ }
78
+
79
+ function manifest(vars, template) {
80
+ const contributes = template === 'view'
81
+ ? {
82
+ views: [{ id: `${vars.camel}.main`, title: vars.name, icon: '🧩', entry: 'ui/index.html' }],
83
+ commands: [{ id: `${vars.camel}.hello`, title: `${vars.name}:打招呼` }],
84
+ configuration: {
85
+ [`${vars.camel}.greeting`]: { type: 'string', default: '哈囉', title: '問候語', description: '後端回覆時使用的問候語' },
86
+ },
87
+ lifecycle: { 'app:before-quit': 'onBeforeQuit' },
88
+ }
89
+ : {
90
+ commands: [
91
+ { id: `${vars.camel}.runNow`, title: `${vars.name}:立即執行` },
92
+ { id: `${vars.camel}.toggle`, title: `${vars.name}:暫停 / 恢復` },
93
+ ],
94
+ configuration: {
95
+ [`${vars.camel}.intervalSeconds`]: { type: 'number', default: 60, title: '執行間隔(秒)', description: '背景工作的執行間隔,最小 5 秒' },
96
+ },
97
+ lifecycle: { 'app:before-quit': 'onBeforeQuit', 'system:suspend': 'onSuspend', 'system:resume': 'onResume' },
98
+ };
99
+ return {
100
+ id: vars.id,
101
+ displayName: vars.name,
102
+ description: vars.description,
103
+ icon: template === 'view' ? '🧩' : '⚙️',
104
+ engine: '^1.0.0',
105
+ activationEvents: template === 'service' ? ['onStartup'] : [],
106
+ contributes,
107
+ };
108
+ }
109
+
110
+ async function main() {
111
+ const args = parseArgs(process.argv.slice(2));
112
+ console.log(`\n${bold('建立 ToolDock 擴充')}\n`);
113
+
114
+ const interactive = tty && !args.yes;
115
+ const rl = interactive ? readline.createInterface({ input: process.stdin, output: process.stdout }) : null;
116
+
117
+ let dir = args._[0] || (interactive ? await ask(rl, '專案資料夾名稱', 'my-tooldock-extension') : 'my-tooldock-extension');
118
+ const target = path.resolve(args.cwd || '.', dir);
119
+ if (fs.existsSync(target) && fs.readdirSync(target).length) {
120
+ rl && rl.close();
121
+ throw new Error(`資料夾已存在且不是空的:${target}`);
122
+ }
123
+ const defId = path.basename(target).toLowerCase().replace(/[^a-z0-9.-]+/g, '-').replace(/^-+|-+$/g, '');
124
+ let id = args.id || (interactive ? await ask(rl, '擴充 id(小寫英數、- 與 .)', defId) : defId);
125
+ while (!ID_RE.test(id)) {
126
+ if (!interactive) throw new Error(`id "${id}" 不合法`);
127
+ console.log(red(' id 只能使用小寫英數、點與連字號,且以英數開頭'));
128
+ id = await ask(rl, '擴充 id', defId);
129
+ }
130
+ const name = args.name || (interactive ? await ask(rl, '顯示名稱', id) : id);
131
+ const description = args.description || (interactive ? await ask(rl, '一句話描述', `${name}`) : name);
132
+ let template = args.template;
133
+ if (!template && interactive) {
134
+ console.log(`${cyan('?')} 範本:`);
135
+ Object.entries(TEMPLATES).forEach(([k, v], i) => console.log(` ${i + 1}) ${bold(k)} ${dim(v)}`));
136
+ const pick = await ask(rl, '選擇 1 或 2', '1');
137
+ template = Object.keys(TEMPLATES)[Number(pick) - 1] || pick;
138
+ }
139
+ template = template || 'view';
140
+ if (!TEMPLATES[template]) throw new Error(`沒有範本 "${template}"(可用:${Object.keys(TEMPLATES).join(', ')})`);
141
+ rl && rl.close();
142
+
143
+ const camel = id.replace(/[-.]+(\w)/g, (_, ch) => ch.toUpperCase());
144
+ const vars = { id, name, description, camel, template };
145
+ const local = localPackages();
146
+
147
+ fs.mkdirSync(target, { recursive: true });
148
+ copyTemplate(path.join(__dirname, 'templates', '_shared'), target, vars);
149
+ copyTemplate(path.join(__dirname, 'templates', template), target, vars);
150
+
151
+ const pkg = {
152
+ name: id,
153
+ version: '0.1.0',
154
+ description,
155
+ main: 'backend/index.js',
156
+ private: true,
157
+ scripts: {
158
+ dev: 'tooldock-ext dev',
159
+ debug: 'tooldock-ext dev --inspect',
160
+ validate: 'tooldock-ext validate',
161
+ pack: 'tooldock-ext pack',
162
+ 'install-local': 'tooldock-ext install',
163
+ },
164
+ tooldock: manifest(vars, template),
165
+ dependencies: {},
166
+ devDependencies: {
167
+ 'tooldock-cli': local ? `file:${local.cli}` : '^1.0.0',
168
+ 'tooldock-types': local ? `file:${local.types}` : '^1.0.0',
169
+ '@types/node': '^22.0.0',
170
+ },
171
+ };
172
+ fs.writeFileSync(path.join(target, 'package.json'), `${JSON.stringify(pkg, null, 2)}\n`);
173
+
174
+ console.log(`\n${green('✔')} 已建立 ${bold(id)}(${template} 範本)於 ${target}`);
175
+ if (local) console.log(dim(' 本機模式:tooldock-cli 與 tooldock-types 以 file: 連結到本機原始碼'));
176
+
177
+ if (!args.noInstall) {
178
+ console.log(dim('\n執行 npm install…'));
179
+ const r = spawnSync(process.platform === 'win32' ? 'npm.cmd' : 'npm', ['install', '--no-audit', '--no-fund'], { cwd: target, stdio: 'inherit', shell: process.platform === 'win32' });
180
+ if (r.status !== 0) console.log(red('npm install 失敗,請稍後手動執行'));
181
+ }
182
+
183
+ const rel = path.relative(process.cwd(), target) || '.';
184
+ console.log(`
185
+ ${bold('下一步')}
186
+ cd ${rel}${args.noInstall ? '\n npm install' : ''}
187
+ npm run dev ${dim('以開發模式啟動 ToolDock,存檔即重載')}
188
+ npm run debug ${dim('同上,並開啟後端偵錯埠 9229(VS Code 按 F5 附加)')}
189
+ npm run validate ${dim('檢查 manifest')}
190
+ npm run pack ${dim('打包成 dist/*.tbx')}
191
+ `);
192
+ }
193
+
194
+ main().catch((err) => {
195
+ console.error(red(`\n✘ ${err.message}`));
196
+ process.exit(1);
197
+ });
package/package.json CHANGED
@@ -1,6 +1,14 @@
1
1
  {
2
2
  "name": "create-tooldock-extension",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "建立 ToolDock 擴充專案:npm create tooldock-extension@latest",
5
+ "bin": {
6
+ "create-tooldock-extension": "index.js"
7
+ },
8
+ "files": ["index.js", "templates"],
9
+ "engines": {
10
+ "node": ">=18"
11
+ },
12
+ "keywords": ["tooldock", "extension", "scaffold", "create"],
13
+ "license": "MIT"
14
+ }
@@ -0,0 +1,56 @@
1
+ # {{name}}
2
+
3
+ {{description}}
4
+
5
+ 這是 ToolDock 擴充,用 `create-tooldock-extension` 的 `{{template}}` 範本建立。
6
+
7
+ ## 開發
8
+
9
+ 需要先安裝 ToolDock 和 Node.js 18 以上。
10
+
11
+ | 指令 | 說明 |
12
+ |---|---|
13
+ | `npm run dev` | 以開發模式啟動 ToolDock 並載入這個擴充。存檔後會自動重新載入後端和畫面 |
14
+ | `npm run debug` | 同上,並開啟後端偵錯埠 `127.0.0.1:9229` |
15
+ | `npm run validate` | 檢查 manifest、檔案和相依套件 |
16
+ | `npm run pack` | 打包成 `dist/{{id}}-<版本>.tbx`,只含正式相依 |
17
+ | `npm run install-local` | 打包並安裝到本機的 ToolDock |
18
+
19
+ 開發模式使用獨立的資料目錄(`ToolDock-ExtDev`),可以和平常使用的 ToolDock 同時開啟,互不干擾。如果想從乾淨的狀態開始,執行 `npm run dev -- --fresh`。
20
+
21
+ 找不到 ToolDock 時,可以用 `--app` 參數或 `TOOLDOCK_PATH` 環境變數指定位置:
22
+
23
+ ```bash
24
+ TOOLDOCK_PATH=/Applications/ToolDock.app npm run dev
25
+ ```
26
+
27
+ ## 偵錯
28
+
29
+ **後端**
30
+
31
+ - **VS Code**:按 F5 選「ToolDock:啟動並偵錯擴充」,就能在 `backend/` 設中斷點。擴充重新載入後,除錯器會自動重新連線。
32
+ - **其他工具**:執行 `npm run debug`,再到 Chrome 開啟 `chrome://inspect` 附加。
33
+ - **偵錯啟動流程**:要偵錯 `activate()` 本身時,執行 `npm run dev -- --inspect-brk`,擴充會停在第一行等待除錯器。
34
+
35
+ **畫面**:在 ToolDock 的分頁上按右鍵,選「檢查此畫面」,開發者工具會直接定位到這個擴充的畫面。
36
+
37
+ **日誌**:`ctx.log.*` 和 `console.log` 會顯示在 ToolDock 的輸出面板(`⇧⌘U`),也會顯示在執行 `npm run dev` 的終端機。
38
+
39
+ ## 專案結構
40
+
41
+ ```
42
+ package.json manifest(tooldock 欄位:畫面、指令、設定、生命週期)
43
+ backend/index.js 後端:activate(ctx) / deactivate()
44
+ ui/ 畫面(如果有)
45
+ .tbxignore 打包時要排除的檔案
46
+ ```
47
+
48
+ ## 加入函式庫
49
+
50
+ ```bash
51
+ npm install <套件>
52
+ ```
53
+
54
+ 用 `npm install` 安裝的套件會列在 `dependencies`,打包時一起帶走,ToolDock 平台不需要更新。`devDependencies` 不會被打包。
55
+
56
+ API 型別定義在 `node_modules/tooldock-types/index.d.ts`。編輯器裡的自動完成和型別檢查已經透過 `jsconfig.json` 設定好了。
@@ -0,0 +1,4 @@
1
+ node_modules/
2
+ dist/
3
+ *.tbx
4
+ .DS_Store
@@ -0,0 +1,7 @@
1
+ # 打包成 .tbx 時要排除的檔案(gitignore 語法的簡化版)
2
+ # 預設已排除:.git、.vscode、dist/、*.tbx、*.map、devDependencies
3
+ # 例如:
4
+ # test/
5
+ # *.psd
6
+ README.md
7
+ jsconfig.json
@@ -0,0 +1,28 @@
1
+ {
2
+ "version": "0.2.0",
3
+ "configurations": [
4
+ {
5
+ "name": "ToolDock:啟動並偵錯擴充",
6
+ "type": "node",
7
+ "request": "attach",
8
+ "preLaunchTask": "tooldock: debug",
9
+ "address": "127.0.0.1",
10
+ "port": 9229,
11
+ "restart": true,
12
+ "timeout": 30000,
13
+ "continueOnAttach": true,
14
+ "skipFiles": ["<node_internals>/**"]
15
+ },
16
+ {
17
+ "name": "ToolDock:附加到執行中的擴充後端",
18
+ "type": "node",
19
+ "request": "attach",
20
+ "address": "127.0.0.1",
21
+ "port": 9229,
22
+ "restart": true,
23
+ "timeout": 30000,
24
+ "continueOnAttach": true,
25
+ "skipFiles": ["<node_internals>/**"]
26
+ }
27
+ ]
28
+ }
@@ -0,0 +1,20 @@
1
+ {
2
+ "version": "2.0.0",
3
+ "tasks": [
4
+ {
5
+ "label": "tooldock: debug",
6
+ "type": "npm",
7
+ "script": "debug",
8
+ "isBackground": true,
9
+ "problemMatcher": {
10
+ "owner": "tooldock",
11
+ "pattern": { "regexp": "^__tooldock_never_match__$" },
12
+ "background": {
13
+ "activeBegins": true,
14
+ "beginsPattern": "ToolDock 擴充開發模式",
15
+ "endsPattern": "後端偵錯埠 127\\.0\\.0\\.1:\\d+"
16
+ }
17
+ }
18
+ }
19
+ ]
20
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "compilerOptions": {
3
+ "module": "commonjs",
4
+ "target": "es2022",
5
+ "lib": ["es2022", "dom"],
6
+ "checkJs": true,
7
+ "skipLibCheck": true,
8
+ "noEmit": true,
9
+ "types": ["node", "tooldock-types/ui"]
10
+ },
11
+ "exclude": ["node_modules", "dist"]
12
+ }
@@ -0,0 +1,104 @@
1
+ // @ts-check
2
+ 'use strict';
3
+ /**
4
+ * {{name}}:背景服務
5
+ *
6
+ * 隨平台啟動(activationEvents: onStartup),定時執行工作並在狀態列顯示結果。
7
+ * 範例工作是讀取系統記憶體與負載;請替換成你的邏輯(呼叫 API、同步檔案、檢查資料庫…)。
8
+ * 完整 API:node_modules/tooldock-types/index.d.ts
9
+ */
10
+ const os = require('os');
11
+
12
+ /** @type {NodeJS.Timeout | null} */
13
+ let timer = null;
14
+ let paused = false;
15
+ let suspended = false;
16
+ /** activate 內建立的操作,供下方生命週期函式使用 @type {{ schedule(): void, runJob(reason: string): Promise<unknown> } | null} */
17
+ let service = null;
18
+
19
+ /** @typedef {{ at: number, freeMemPct: number, load: number, durationMs: number }} RunResult */
20
+
21
+ /** @param {import('tooldock-types').ExtensionContext} ctx */
22
+ exports.activate = (ctx) => {
23
+ paused = ctx.storage.get('paused', false);
24
+
25
+ /** @param {string} reason @returns {Promise<RunResult>} */
26
+ const runJob = async (reason) => {
27
+ const t0 = Date.now();
28
+ // ── 把這裡換成你的背景工作 ──
29
+ const freeMemPct = Math.round((os.freemem() / os.totalmem()) * 100);
30
+ const load = Math.round(os.loadavg()[0] * 100) / 100;
31
+ // ─────────────────────────
32
+ /** @type {RunResult} */
33
+ const result = { at: Date.now(), freeMemPct, load, durationMs: Date.now() - t0 };
34
+ ctx.storage.set('last', result);
35
+ ctx.log.info(`執行完成(${reason}):可用記憶體 ${freeMemPct}%,負載 ${load}`);
36
+ updateStatus(result);
37
+ return result;
38
+ };
39
+
40
+ /** @param {RunResult | null} result */
41
+ const updateStatus = (result) => {
42
+ ctx.window.setStatus({
43
+ text: paused ? '⚙️ {{name}}:已暫停' : `⚙️ 記憶體 ${result ? result.freeMemPct : '—'}%`,
44
+ tooltip: '{{name}}(點擊暫停 / 恢復)',
45
+ command: '{{camel}}.toggle',
46
+ });
47
+ };
48
+
49
+ const schedule = () => {
50
+ if (timer) clearInterval(timer);
51
+ timer = null;
52
+ if (paused || suspended) return;
53
+ const sec = Math.max(5, Number(ctx.settings.get('{{camel}}.intervalSeconds', 60)));
54
+ timer = setInterval(() => { runJob('schedule').catch((e) => ctx.log.error(e)); }, sec * 1000);
55
+ };
56
+
57
+ ctx.subscriptions.push(
58
+ ctx.commands.register('{{camel}}.runNow', () => runJob('manual')),
59
+ ctx.commands.register('{{camel}}.toggle', async () => {
60
+ paused = !paused;
61
+ ctx.storage.set('paused', paused);
62
+ schedule();
63
+ updateStatus(ctx.storage.get('last', null));
64
+ await ctx.window.toast(paused ? '{{name}} 已暫停' : '{{name}} 已恢復', 'info');
65
+ }),
66
+ ctx.settings.onDidChange((key) => { if (key === '{{camel}}.intervalSeconds') schedule(); }),
67
+ // 動態註冊生命週期(另一種方式是 package.json 的 contributes.lifecycle)
68
+ ctx.lifecycle.on('app:idle', () => ctx.log.info('平台進入閒置階段')),
69
+ { dispose: () => { if (timer) clearInterval(timer); } },
70
+ );
71
+
72
+ service = { schedule, runJob };
73
+ // activate 應該盡快完成;第一次執行放到背景,不等待結果
74
+ schedule();
75
+ runJob('startup').catch((e) => ctx.log.error(e));
76
+ };
77
+
78
+ /* ── 以下對應 package.json 的 contributes.lifecycle ── */
79
+
80
+ /** @param {import('tooldock-types').ExtensionContext} ctx */
81
+ exports.onSuspend = (ctx) => {
82
+ suspended = true;
83
+ if (timer) clearInterval(timer);
84
+ timer = null;
85
+ ctx.log.info('系統休眠:暫停背景工作');
86
+ };
87
+
88
+ /** @param {import('tooldock-types').ExtensionContext} ctx */
89
+ exports.onResume = (ctx) => {
90
+ suspended = false;
91
+ ctx.log.info('系統喚醒:立即執行一次');
92
+ if (!service) return;
93
+ service.schedule();
94
+ return service.runJob('resume');
95
+ };
96
+
97
+ /** @param {import('tooldock-types').ExtensionContext} ctx */
98
+ exports.onBeforeQuit = (ctx) => {
99
+ ctx.log.info('平台即將結束');
100
+ };
101
+
102
+ exports.deactivate = () => {
103
+ if (timer) clearInterval(timer);
104
+ };
@@ -0,0 +1,68 @@
1
+ // @ts-check
2
+ 'use strict';
3
+ /**
4
+ * {{name}}:後端
5
+ *
6
+ * 在獨立的 Node.js 程序中執行:可以使用 fs、child_process、fetch,
7
+ * 也可以 require 任何 npm 套件(在本資料夾 `npm install <套件>` 即可,平台不需更新)。
8
+ * 完整 API:node_modules/tooldock-types/index.d.ts
9
+ */
10
+ const fs = require('fs');
11
+
12
+ /** @typedef {{ id: string, text: string, createdAt: number }} Note */
13
+
14
+ /** @param {import('tooldock-types').ExtensionContext} ctx */
15
+ exports.activate = (ctx) => {
16
+ ctx.log.info('{{name}} 已啟用');
17
+
18
+ /** @returns {Note[]} */
19
+ const load = () => ctx.storage.get('notes', []);
20
+
21
+ /** @param {Note[]} notes */
22
+ const save = (notes) => {
23
+ ctx.storage.set('notes', notes);
24
+ ctx.ui.emit('notesChanged', notes); // 推送給所有開啟中的畫面
25
+ return notes;
26
+ };
27
+
28
+ // ── 畫面呼叫的方法:tooldock.invoke('<方法>', ...參數) ──
29
+ ctx.ui.handle('greet', (name) => {
30
+ const greeting = ctx.settings.get('{{camel}}.greeting', '哈囉');
31
+ return `${greeting},${name || '朋友'}!(來自 PID ${process.pid} 的後端)`;
32
+ });
33
+
34
+ ctx.ui.handle('listNotes', () => load());
35
+
36
+ ctx.ui.handle('addNote', (text) => {
37
+ const t = String(text || '').trim();
38
+ if (!t) throw new Error('內容不可為空'); // 錯誤會傳回畫面端的 Promise reject
39
+ return save([{ id: Date.now().toString(36), text: t, createdAt: Date.now() }, ...load()]);
40
+ });
41
+
42
+ ctx.ui.handle('removeNote', (id) => save(load().filter((n) => n.id !== id)));
43
+
44
+ ctx.ui.handle('exportNotes', async () => {
45
+ const r = await ctx.window.showSaveDialog({ defaultPath: 'notes.txt' });
46
+ if (r.canceled || !r.filePath) return null;
47
+ fs.writeFileSync(r.filePath, load().map((n) => `- ${n.text}`).join('\n'), 'utf8');
48
+ return r.filePath;
49
+ });
50
+
51
+ // ── 指令:命令面板、lifecycle.json 的 hook、其他擴充都能呼叫 ──
52
+ ctx.subscriptions.push(
53
+ ctx.commands.register('{{camel}}.hello', async () => {
54
+ await ctx.window.toast('來自 {{name}} 的問候', 'success');
55
+ }),
56
+ ctx.settings.onDidChange((key) => ctx.ui.emit('settingsChanged', { key })),
57
+ );
58
+ };
59
+
60
+ /**
61
+ * 對應 package.json 的 contributes.lifecycle["app:before-quit"]
62
+ * @param {import('tooldock-types').ExtensionContext} ctx
63
+ */
64
+ exports.onBeforeQuit = (ctx) => {
65
+ ctx.log.info('平台即將結束,筆記數量:', ctx.storage.get('notes', []).length);
66
+ };
67
+
68
+ exports.deactivate = () => {};
@@ -0,0 +1,52 @@
1
+ // @ts-check
2
+ /** {{name}}:畫面(可改用任何前端框架,打包後的檔案放在 ui/ 即可) */
3
+ const td = window.tooldock;
4
+
5
+ /** @template {HTMLElement} T @param {string} sel @returns {T} */
6
+ const $ = (sel) => /** @type {T} */ (document.querySelector(sel));
7
+
8
+ /** @typedef {{ id: string, text: string, createdAt: number }} Note */
9
+
10
+ /** @param {Note[]} notes */
11
+ function renderNotes(notes) {
12
+ const list = $('#notes');
13
+ list.innerHTML = notes.length
14
+ ? notes.map((n) => `<li>
15
+ <span>${td.escape(n.text)}</span>
16
+ <time>${new Date(n.createdAt).toLocaleString('zh-TW', { hour12: false })}</time>
17
+ <button class="danger" data-id="${n.id}">刪除</button>
18
+ </li>`).join('')
19
+ : '<li class="faint">還沒有筆記</li>';
20
+ }
21
+
22
+ $('#greet').addEventListener('click', async () => {
23
+ /** @type {HTMLInputElement} */
24
+ const input = $('#name');
25
+ $('#greeting').textContent = await td.invoke('greet', input.value);
26
+ });
27
+
28
+ $('#add').addEventListener('click', async () => {
29
+ /** @type {HTMLInputElement} */
30
+ const input = $('#note');
31
+ try {
32
+ await td.invoke('addNote', input.value); // 畫面會由 notesChanged 事件更新
33
+ input.value = '';
34
+ } catch (err) {
35
+ td.toast(err instanceof Error ? err.message : String(err), 'warn');
36
+ }
37
+ });
38
+
39
+ $('#notes').addEventListener('click', (e) => {
40
+ const btn = /** @type {HTMLElement} */ (e.target).closest('button[data-id]');
41
+ if (btn instanceof HTMLElement) td.invoke('removeNote', btn.dataset.id);
42
+ });
43
+
44
+ $('#export').addEventListener('click', async () => {
45
+ const file = await td.invoke('exportNotes');
46
+ if (file) td.toast(`已匯出到 ${file}`, 'success');
47
+ });
48
+
49
+ // 後端 ctx.ui.emit('notesChanged', notes) 推送的事件
50
+ td.on('notesChanged', renderNotes);
51
+
52
+ td.invoke('listNotes').then(renderNotes);
@@ -0,0 +1,45 @@
1
+ <!doctype html>
2
+ <html lang="zh-Hant">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <title>{{name}}</title>
6
+ <!-- 平台共用主題(自動跟隨深色 / 淺色),提供 button、.card、.badge、table.grid 等樣式 -->
7
+ <link rel="stylesheet" href="tooldock://sdk/ui-base.css">
8
+ <style>
9
+ body { padding: 24px 28px; max-width: 760px; }
10
+ .card { margin-bottom: 16px; }
11
+ #notes { list-style: none; margin: 12px 0 0; padding: 0; }
12
+ #notes li { display: flex; align-items: center; gap: 10px; padding: 6px 0; border-bottom: 1px solid var(--border); }
13
+ #notes li span { flex: 1; }
14
+ #notes li time { font-size: 11px; color: var(--fg-faint); }
15
+ #notes li button { min-height: 22px; padding: 0 8px; }
16
+ </style>
17
+ </head>
18
+ <body>
19
+ <h1>🧩 {{name}}</h1>
20
+ <p class="muted">{{description}}</p>
21
+
22
+ <div class="card stack">
23
+ <h3>呼叫後端</h3>
24
+ <div class="row">
25
+ <input id="name" placeholder="輸入名字">
26
+ <button id="greet">打招呼</button>
27
+ </div>
28
+ <div id="greeting" class="muted"></div>
29
+ </div>
30
+
31
+ <div class="card">
32
+ <h3>筆記(儲存在 ctx.storage,後端推送更新)</h3>
33
+ <div class="row">
34
+ <input id="note" placeholder="新增一則筆記" style="flex:1">
35
+ <button id="add">新增</button>
36
+ <button id="export" class="secondary">匯出…</button>
37
+ </div>
38
+ <ul id="notes"></ul>
39
+ </div>
40
+
41
+ <!-- 提供 window.tooldock -->
42
+ <script src="tooldock://sdk/ui-sdk.js"></script>
43
+ <script src="app.js"></script>
44
+ </body>
45
+ </html>