agy-git-graph 0.0.0-stage → 1.1.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.
@@ -0,0 +1,997 @@
1
+ <!doctype html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Git Graph</title>
7
+ <style>
8
+ :root {
9
+ color-scheme: dark;
10
+ --bg: var(--color-background-primary, #0f0f11);
11
+ --surface: var(--color-background-secondary, #141416);
12
+ --surface-2: var(--color-background-tertiary, #1b1b1e);
13
+ --hover-bg: #29292e;
14
+ --even-row: #121214;
15
+ --active-row: #222331;
16
+ --border: var(--color-border-primary, rgba(255,255,255,0.08));
17
+ --drawer-border: #35353d;
18
+ --text: var(--color-text-primary, #ededef);
19
+ --text-secondary: var(--color-text-secondary, #a1a1aa);
20
+ --muted: #71717a;
21
+ --ui-font-default: var(--font-sans, -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei UI", sans-serif);
22
+ --ui-font: var(--ui-font-default);
23
+ --ui-font-weight: 400;
24
+ --mono: "Cascadia Code", Consolas, monospace;
25
+ --accent: #a5b4fc;
26
+ --branch-bg: #1c1d2c;
27
+ --branch-mark: #818cf8;
28
+ --primary-bg: #4f46b6;
29
+ --primary-hover: #6057d2;
30
+ --primary-border: #6b61df;
31
+ --primary-text: #ffffff;
32
+ --green: #86efac;
33
+ --green-bg: #162820;
34
+ --red: #fda4af;
35
+ --red-bg: #311b23;
36
+ --red-border: #723545;
37
+ --amber: #fcd34d;
38
+ --amber-bg: #282117;
39
+ --info-fg: #7dd3fc;
40
+ --info-bg: #132534;
41
+ --hunk-fg: #a5b4fc;
42
+ --hunk-bg: #1c2036;
43
+ --ref-head-fg: #a7f3d0;
44
+ --ref-head-bg: #15352d;
45
+ --ref-local-fg: #bae6fd;
46
+ --ref-local-bg: #153045;
47
+ --ref-remote-fg: #cbd5e1;
48
+ --ref-remote-border: #374151;
49
+ --ref-tag-bg: #392b15;
50
+ }
51
+ :root[data-theme="light"] {
52
+ color-scheme: light;
53
+ --bg: var(--color-background-primary, #faf8f5);
54
+ --surface: var(--color-background-secondary, #f3efe8);
55
+ --surface-2: var(--color-background-tertiary, #eae4da);
56
+ --hover-bg: #e1d9cc;
57
+ --even-row: #f5f1ea;
58
+ --active-row: #e6e9f8;
59
+ --border: var(--color-border-primary, rgba(24,24,27,0.12));
60
+ --drawer-border: rgba(24,24,27,0.2);
61
+ --text: var(--color-text-primary, #1f1f23);
62
+ --text-secondary: var(--color-text-secondary, #57534e);
63
+ --muted: #78716c;
64
+ --accent: #4338ca;
65
+ --branch-bg: #e5e7fb;
66
+ --branch-mark: #4f46e5;
67
+ --primary-bg: #4338ca;
68
+ --primary-hover: #3730a3;
69
+ --primary-border: #3730a3;
70
+ --primary-text: #ffffff;
71
+ --green: #15803d;
72
+ --green-bg: #dcfce7;
73
+ --red: #be123c;
74
+ --red-bg: #ffe4e6;
75
+ --red-border: #fda4af;
76
+ --amber: #b45309;
77
+ --amber-bg: #fef3c7;
78
+ --info-fg: #0369a1;
79
+ --info-bg: #e0f2fe;
80
+ --hunk-fg: #4338ca;
81
+ --hunk-bg: #e0e7ff;
82
+ --ref-head-fg: #047857;
83
+ --ref-head-bg: #d1fae5;
84
+ --ref-local-fg: #0369a1;
85
+ --ref-local-bg: #e0f2fe;
86
+ --ref-remote-fg: #475569;
87
+ --ref-remote-border: #cbd5e1;
88
+ --ref-tag-bg: #fef3c7;
89
+ }
90
+ /*__POWERTOOLS_FONT_CSS__*/
91
+ * { box-sizing: border-box; }
92
+ [hidden] { display: none !important; }
93
+ html, body { height: 100%; margin: 0; }
94
+ body {
95
+ display: flex; flex-direction: column; overflow: hidden; background: var(--bg);
96
+ color: var(--text); font: var(--ui-font-weight) 12px/1.5 var(--ui-font);
97
+ }
98
+ button, input, select, textarea { font: inherit; color: inherit; }
99
+ button, select, input, textarea {
100
+ min-width: 0; border: 1px solid var(--border); border-radius: 6px; background: var(--surface-2);
101
+ }
102
+ button { cursor: pointer; padding: 3px 8px; }
103
+ button:hover:not(:disabled) { background: var(--hover-bg); }
104
+ button:disabled { opacity: .45; cursor: default; }
105
+ button:focus-visible, input:focus-visible, select:focus-visible,
106
+ textarea:focus-visible, summary:focus-visible, [role="separator"]:focus-visible {
107
+ outline: 1px solid var(--accent); outline-offset: -1px;
108
+ }
109
+ input, select { height: 28px; padding: 3px 7px; }
110
+ .icon { width: 28px; height: 28px; padding: 0; font: 17px/1 var(--ui-font); flex: none; }
111
+ .quiet { background: transparent; border-color: transparent; color: var(--text-secondary); }
112
+ .truncate { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
113
+ .muted { color: var(--text-secondary); }
114
+ .mono { font-family: var(--mono); }
115
+ .toolbar {
116
+ display: flex; align-items: center; gap: 6px; padding: 9px 10px;
117
+ background: var(--surface); border-bottom: 1px solid var(--border);
118
+ }
119
+ #repos { flex: 1 1 105px; width: 0; }
120
+ .branch {
121
+ max-width: 44%; padding: 3px 7px; display: flex; gap: 5px; align-items: center;
122
+ color: var(--accent); background: var(--branch-bg); border-radius: 5px;
123
+ }
124
+ .branch-mark { color: var(--branch-mark); flex: none; }
125
+ #branchCounts { color: var(--text-secondary); flex: none; white-space: nowrap; }
126
+ .repo-form {
127
+ display: flex; align-items: center; gap: 5px; padding: 7px 10px;
128
+ background: var(--surface); border-bottom: 1px solid var(--border);
129
+ }
130
+ .repo-form input { flex: 1; }
131
+ .notice { padding: 5px 10px; color: var(--text-secondary); overflow-wrap: anywhere; max-height: 6em; overflow: auto; }
132
+ .notice[data-error="true"] { color: var(--red); background: var(--red-bg); }
133
+ main { flex: 1; min-height: 0; display: flex; flex-direction: column; }
134
+ .section-bar, .history-bar {
135
+ display: flex; align-items: center; gap: 6px; flex: none;
136
+ padding: 6px 10px; background: var(--surface);
137
+ }
138
+ .section-bar { border-bottom: 1px solid var(--border); }
139
+ .section-bar button { display: flex; align-items: center; gap: 6px; border: 0; padding: 1px 3px; }
140
+ h1, h2, h3, p { margin: 0; }
141
+ h1, h2 { font-size: 13px; font-weight: 650; }
142
+ .caret { display: inline-block; width: 10px; color: var(--muted); font-size: 10px; }
143
+ [aria-expanded="true"] > .caret { transform: rotate(90deg); }
144
+ .count { color: var(--text-secondary); font: 10px var(--mono); }
145
+ #changes { flex: 0 1 auto; display: flex; flex-direction: column; min-height: 0; }
146
+ #changesBody {
147
+ max-height: min(var(--changes-size, 250px), 60dvh); min-height: 0;
148
+ overflow: auto; scrollbar-width: thin;
149
+ }
150
+ .commit-form { padding: 9px 10px; display: flex; flex-direction: column; gap: 6px; }
151
+ .commit-form textarea {
152
+ width: 100%; resize: vertical; min-height: 46px; max-height: 120px;
153
+ padding: 6px 8px; background: var(--bg);
154
+ }
155
+ .commit-form textarea::placeholder, input::placeholder { color: var(--text-secondary); }
156
+ .primary {
157
+ background: var(--primary-bg); border-color: var(--primary-border); color: var(--primary-text);
158
+ font-weight: 650; align-self: stretch; min-height: 27px;
159
+ }
160
+ .primary:hover:not(:disabled) { background: var(--primary-hover); }
161
+ .change-header {
162
+ display: flex; align-items: center; justify-content: space-between;
163
+ gap: 4px; padding: 3px 10px; border-top: 1px solid var(--border);
164
+ }
165
+ .change-header button { background: transparent; }
166
+ .change-toggle { display: flex; align-items: center; gap: 5px; padding: 1px 2px; font-weight: 600; }
167
+ .action-all { padding: 1px 4px; font-size: 11px; }
168
+ .change-row { display: flex; align-items: center; min-height: 28px; padding: 0 8px 0 10px; }
169
+ .change-row:hover, .change-row:focus-within { background: var(--surface-2); }
170
+ .file-main {
171
+ flex: 1; display: flex; align-items: center; gap: 6px; text-align: left;
172
+ padding: 2px 3px; border: 0; background: transparent;
173
+ }
174
+ .file-main:hover:not(:disabled) { background: transparent; }
175
+ .file-dir { color: var(--text-secondary); font-size: 11px; }
176
+ .file-name { flex: 0 1 auto; }
177
+ .file-status {
178
+ display: grid; place-items: center; flex: 0 0 16px; height: 16px; border-radius: 4px;
179
+ color: var(--amber); background: var(--amber-bg); font: 10px var(--mono);
180
+ }
181
+ .file-status[data-status="A"], .file-status[data-status="?"] { color: var(--green); background: var(--green-bg); }
182
+ .file-status[data-status="D"], .file-status[data-status="U"] { color: var(--red); background: var(--red-bg); }
183
+ .file-status[data-status="R"], .file-status[data-status="C"] { color: var(--info-fg); background: var(--info-bg); }
184
+ .row-actions { display: flex; align-items: center; flex: none; opacity: 0; }
185
+ .change-row:hover .row-actions, .change-row:focus-within .row-actions,
186
+ .row-actions:has(.confirm) { opacity: 1; }
187
+ @media (hover: none) { .row-actions { opacity: 1; } }
188
+ .row-actions button { height: 23px; min-width: 22px; padding: 0 4px; }
189
+ .row-actions .confirm { color: var(--red); border-color: var(--red-border); background: var(--red-bg); }
190
+ #splitter {
191
+ flex: 0 0 7px; background: var(--surface); border-block: 1px solid var(--border);
192
+ cursor: row-resize; touch-action: none; display: grid; place-items: center;
193
+ }
194
+ #splitter::before { content: ""; height: 2px; width: 26px; background: var(--muted); opacity: .45; border-radius: 2px; }
195
+ #splitter:hover::before, #splitter:focus-visible::before { background: var(--accent); opacity: 1; }
196
+ #history { flex: 1; min-height: 0; display: flex; flex-direction: column; }
197
+ .history-bar { border-bottom: 1px solid var(--border); }
198
+ .history-bar h1 { white-space: nowrap; margin-right: 3px; }
199
+ #branchFilter { flex: 1 1 138px; width: 0; }
200
+ #search { flex: 0 1 128px; width: 0; min-width: 52px; }
201
+ #historyScroll { flex: 1; min-height: 0; overflow: auto; scrollbar-width: thin; }
202
+ #commitList { min-width: var(--history-min, 0px); }
203
+ .commit-row {
204
+ width: 100%; height: 26px; padding: 0 8px 0 2px; border: 0; border-radius: 0;
205
+ display: grid; grid-template-columns: var(--lane-width) minmax(0, 1fr) auto;
206
+ align-items: center; gap: 6px; text-align: left; background: var(--bg);
207
+ }
208
+ .commit-row:nth-child(even) { background: var(--even-row); }
209
+ .commit-row:hover:not(:disabled), .commit-row[aria-current="true"] { background: var(--active-row); }
210
+ .commit-row svg { display: block; overflow: hidden; }
211
+ .commit-center { display: flex; align-items: center; gap: 4px; overflow: hidden; min-width: 0; }
212
+ .subject { flex: 1 1 50px; }
213
+ .refs { flex: 0 2 auto; display: flex; gap: 3px; max-width: 64%; min-width: 0; overflow: hidden; }
214
+ .ref {
215
+ max-width: 118px; min-width: 18px; padding: 0 4px; border: 1px solid transparent;
216
+ border-radius: 4px; font-size: 10px; line-height: 15px;
217
+ }
218
+ .ref.head { color: var(--ref-head-fg); background: var(--ref-head-bg); }
219
+ .ref.local { color: var(--ref-local-fg); background: var(--ref-local-bg); }
220
+ .ref.remote { color: var(--ref-remote-fg); border-color: var(--ref-remote-border); }
221
+ .ref.tag { color: var(--amber); background: var(--ref-tag-bg); }
222
+ .commit-meta { display: flex; align-items: center; gap: 6px; color: var(--text-secondary); font-size: 10px; }
223
+ .commit-author { max-width: 64px; }
224
+ @media (max-width: 440px) { .commit-author { display: none; } }
225
+ @media (max-width: 325px) { .commit-time { display: none; } .toolbar, .history-bar { gap: 4px; } }
226
+ @media (min-width: 960px) {
227
+ main { flex-direction: row; }
228
+ #changes { flex: 0 0 360px; width: 360px; border-right: 1px solid var(--border); }
229
+ #changesBody { max-height: none; flex: 1; }
230
+ #splitter { display: none; }
231
+ #history { flex: 1; min-width: 0; }
232
+ #repos { max-width: 320px; }
233
+ #branchFilter { max-width: 240px; }
234
+ #search { max-width: 240px; }
235
+ .commit-author { max-width: 120px; }
236
+ }
237
+ .empty { padding: 8px 12px; color: var(--text-secondary); }
238
+ #more { display: block; margin: 8px auto; }
239
+ dialog {
240
+ inset: auto 0 0; margin: 0; width: 100%; max-width: none; max-height: min(78dvh, 100%);
241
+ padding: 0; border: 1px solid var(--drawer-border); border-radius: 12px 12px 0 0;
242
+ background: var(--surface); color: var(--text);
243
+ }
244
+ dialog[open] { display: flex; flex-direction: column; }
245
+ dialog::backdrop { background: #0008; }
246
+ dialog header {
247
+ display: flex; align-items: center; gap: 6px; padding: 7px 9px;
248
+ background: var(--surface-2); border-bottom: 1px solid var(--border);
249
+ }
250
+ #drawerTitle { flex: 1; }
251
+ #drawerToggle, #drawerClose { flex: none; }
252
+ #drawerBody { min-height: 0; overflow: auto; scrollbar-width: thin; }
253
+ .drawer-summary { padding: 10px; display: grid; gap: 4px; }
254
+ .drawer-summary p, .commit-body { overflow-wrap: anywhere; }
255
+ .hash-line { display: flex; align-items: center; gap: 5px; }
256
+ .hash-line code { flex: 0 1 auto; overflow-wrap: anywhere; word-break: break-all; }
257
+ .commit-body { margin: 3px 0 0; white-space: pre-wrap; font: inherit; }
258
+ .commit-files { border-block: 1px solid var(--border); }
259
+ .commit-files button {
260
+ display: flex; width: 100%; align-items: center; gap: 6px;
261
+ border: 0; border-radius: 0; padding: 4px 10px; background: transparent; text-align: left;
262
+ }
263
+ .commit-files button[aria-current="true"] { background: var(--active-row); }
264
+ .commit-files .file-path { flex: 1; }
265
+ .stat { font: 10px var(--mono); white-space: nowrap; }
266
+ .stat.add { color: var(--green); }
267
+ .stat.del { color: var(--red); }
268
+ .diff { margin: 0; overflow-x: auto; font: 11px/1.6 var(--mono); tab-size: 4; }
269
+ .diff span { display: block; min-width: 100%; width: max-content; padding: 0 9px; }
270
+ .diff .addition { color: var(--green); background: var(--green-bg); }
271
+ .diff .deletion { color: var(--red); background: var(--red-bg); }
272
+ .diff .hunk { color: var(--hunk-fg); background: var(--hunk-bg); }
273
+ .diff .header { color: var(--text-secondary); background: var(--surface-2); }
274
+ </style>
275
+ </head>
276
+ <body>
277
+ <header class="toolbar">
278
+ <select id="repos" aria-label="Git 仓库"><option value="">选择仓库</option></select>
279
+ <button id="addToggle" class="icon quiet" type="button" title="添加仓库" aria-label="添加仓库"
280
+ aria-expanded="false" aria-controls="repoForm">+</button>
281
+ <span id="branchBadge" class="branch" hidden>
282
+ <span class="branch-mark" aria-hidden="true">⑂</span>
283
+ <span id="branchName" class="truncate"></span>
284
+ <span id="branchCounts"></span>
285
+ </span>
286
+ <button id="refresh" class="icon quiet" type="button" title="刷新" aria-label="刷新">↻</button>
287
+ </header>
288
+ <form id="repoForm" class="repo-form" hidden>
289
+ <input id="repoPath" aria-label="仓库路径" placeholder="粘贴 Git 仓库路径" autocomplete="off">
290
+ <button type="submit">添加</button>
291
+ <button id="removeRepo" type="button" class="quiet" hidden>移除记录</button>
292
+ </form>
293
+ <p id="notice" class="notice" role="status" hidden></p>
294
+ <main>
295
+ <section id="changes" aria-label="更改">
296
+ <div class="section-bar">
297
+ <h2><button id="changesToggle" type="button" aria-expanded="true" aria-controls="changesBody">
298
+ <span class="caret" aria-hidden="true">▸</span>更改 <span id="changeCount" class="count"></span>
299
+ </button></h2>
300
+ </div>
301
+ <div id="changesBody">
302
+ <form id="commitForm" class="commit-form">
303
+ <textarea id="message" rows="2" aria-label="提交信息" placeholder="输入提交信息 (Ctrl+Enter 提交)"></textarea>
304
+ <button id="commitButton" class="primary" type="submit" disabled>全部提交 (0)</button>
305
+ </form>
306
+ <div class="change-header">
307
+ <button class="change-toggle quiet" type="button" aria-expanded="true" aria-controls="staged">
308
+ <span class="caret" aria-hidden="true">▸</span>已暂存更改 <span id="stagedCount" class="count"></span>
309
+ </button>
310
+ <button id="unstageAll" class="action-all quiet" type="button" disabled>全部取消暂存</button>
311
+ </div>
312
+ <div id="staged"></div>
313
+ <div class="change-header">
314
+ <button class="change-toggle quiet" type="button" aria-expanded="true" aria-controls="unstaged">
315
+ <span class="caret" aria-hidden="true">▸</span>更改 <span id="unstagedCount" class="count"></span>
316
+ </button>
317
+ <button id="stageAll" class="action-all quiet" type="button" disabled>全部暂存</button>
318
+ </div>
319
+ <div id="unstaged"></div>
320
+ </div>
321
+ </section>
322
+ <div id="splitter" role="separator" aria-label="调整更改区域高度" aria-orientation="horizontal"
323
+ aria-controls="changesBody" tabindex="0"></div>
324
+ <section id="history" aria-label="提交图">
325
+ <div class="history-bar">
326
+ <h1>提交图</h1>
327
+ <select id="branchFilter" aria-label="分支筛选">
328
+ <option value="all">所有分支</option><option value="current">当前分支</option>
329
+ </select>
330
+ <input type="search" id="search" aria-label="搜索提交信息" placeholder="搜索提交" autocomplete="off">
331
+ </div>
332
+ <div id="historyScroll">
333
+ <div id="commitList"></div>
334
+ <p id="historyEmpty" class="empty">选择或添加 Git 仓库。</p>
335
+ <button id="more" type="button" hidden>加载更多</button>
336
+ </div>
337
+ </section>
338
+ </main>
339
+ <dialog id="drawer" aria-labelledby="drawerTitle">
340
+ <header>
341
+ <h2 id="drawerTitle" class="truncate">Diff</h2>
342
+ <button id="drawerToggle" type="button" hidden></button>
343
+ <button id="drawerClose" class="icon quiet" type="button" aria-label="关闭 Diff">×</button>
344
+ </header>
345
+ <div id="drawerBody"></div>
346
+ </dialog>
347
+ <!--__MCP_APP_BRIDGE__-->
348
+ <script>
349
+ 'use strict';
350
+
351
+ const $ = (id) => document.getElementById(id);
352
+ const lanes = ['#38bdf8', '#4ade80', '#f472b6', '#fbbf24', '#a78bfa', '#fb7185', '#2dd4bf', '#fb923c'];
353
+ const pageSize = 80;
354
+ const timeFormat = new Intl.DateTimeFormat('zh-CN', { dateStyle: 'medium', timeStyle: 'short' });
355
+ const relativeFormat = new Intl.RelativeTimeFormat('zh-CN', { numeric: 'auto' });
356
+ const emptyStatus = { staged: [], unstaged: [] };
357
+ const mcpBridge = globalThis.__AGY_MCP_EXT_APPS__ || null;
358
+ let mcpApp = null;
359
+ let mcpConnectPromise = null;
360
+ let bootedFromToolResult = false;
361
+ let selected = '';
362
+ let repos = [];
363
+ let repoState = null;
364
+ let stateRequest = 0;
365
+ let workspaceRequest = 0;
366
+ let displayedLimit = pageSize;
367
+ let pendingDiscard = '';
368
+ let searchTimer;
369
+ let mutating = false;
370
+ let loading = false;
371
+ let drawerView = null;
372
+ let drawerRequest = 0;
373
+ let fileRequest = 0;
374
+
375
+ function escapeHtml(value) {
376
+ return String(value ?? '').replace(/[&<>"']/g, (char) => ({
377
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
378
+ })[char]);
379
+ }
380
+
381
+ function notice(message = '', isError = false) {
382
+ $('notice').textContent = message;
383
+ $('notice').hidden = !message;
384
+ $('notice').dataset.error = isError;
385
+ }
386
+
387
+ function applyHostCtx(ctx) {
388
+ if (!ctx || !mcpBridge) return;
389
+ if (ctx.theme) {
390
+ document.documentElement.dataset.theme = ctx.theme;
391
+ mcpBridge.applyDocumentTheme?.(ctx.theme);
392
+ }
393
+ if (ctx.styles?.variables) {
394
+ mcpBridge.applyHostStyleVariables?.(ctx.styles.variables);
395
+ }
396
+ }
397
+
398
+ function parseToolResultPayload(result) {
399
+ if (result?.structuredContent && typeof result.structuredContent === 'object') {
400
+ return result.structuredContent;
401
+ }
402
+ const text = result?.content?.[0]?.text;
403
+ if (typeof text === 'string' && text.trim()) {
404
+ try {
405
+ return JSON.parse(text);
406
+ } catch {
407
+ return { ok: !result.isError, message: text };
408
+ }
409
+ }
410
+ return {};
411
+ }
412
+
413
+ async function api(route, data = {}) {
414
+ if (mcpApp) {
415
+ if (mcpConnectPromise) await mcpConnectPromise;
416
+ const result = await mcpApp.callServerTool({
417
+ name: 'git_graph_rpc',
418
+ arguments: { route, payload: data },
419
+ });
420
+ const payload = parseToolResultPayload(result);
421
+ if (result?.isError || payload?.ok === false) {
422
+ throw new Error(payload?.error || payload?.message || 'MCP RPC 调用失败');
423
+ }
424
+ return payload;
425
+ }
426
+ const response = await fetch('/api/' + route, {
427
+ method: 'POST',
428
+ headers: { 'Content-Type': 'application/json' },
429
+ body: JSON.stringify(data),
430
+ });
431
+ const result = await response.json();
432
+ if (!response.ok || result.ok === false) {
433
+ throw new Error(result.error || result.message || ('HTTP ' + response.status));
434
+ }
435
+ return result;
436
+ }
437
+
438
+ function repoApi(route, data, path = selected) {
439
+ return api('repo/' + route, { repoPath: path, ...data });
440
+ }
441
+
442
+ function switchRepo(path) {
443
+ if (path === selected) return;
444
+ stateRequest++;
445
+ loading = false;
446
+ selected = path;
447
+ repoState = null;
448
+ displayedLimit = pageSize;
449
+ pendingDiscard = '';
450
+ $('branchFilter').value = 'all';
451
+ $('search').value = '';
452
+ $('message').value = '';
453
+ $('historyScroll').scrollTop = 0;
454
+ if ($('drawer').open) $('drawer').close();
455
+ renderState();
456
+ }
457
+
458
+ function renderRepoOptions() {
459
+ $('repos').innerHTML = repos.length ? repos.map((repo) => {
460
+ const info = escapeHtml(repo.path);
461
+ return '<option value="' + info + '" title="' + info + '">' + escapeHtml(repo.name) + '</option>';
462
+ }).join('') : '<option value="">选择仓库</option>';
463
+ $('repos').value = selected;
464
+ $('repos').title = selected;
465
+ $('removeRepo').hidden = !repos.find((repo) => repo.path === selected)?.isCustom;
466
+ }
467
+
468
+ async function refreshRepos(preferred = '') {
469
+ const request = ++workspaceRequest;
470
+ notice('正在查找 Git 仓库…');
471
+ try {
472
+ const result = await api('workspaces');
473
+ if (request !== workspaceRequest) return;
474
+ repos = result.repos;
475
+ const next = [preferred, selected].find((path) => repos.some((repo) => repo.path === path));
476
+ switchRepo(next || repos[0]?.path || '');
477
+ renderRepoOptions();
478
+ await refreshState();
479
+ } catch (error) {
480
+ if (request === workspaceRequest) notice(error.message, true);
481
+ }
482
+ }
483
+
484
+ async function refreshState({ limit = displayedLimit, resetScroll = false, retry = true } = {}) {
485
+ const request = ++stateRequest;
486
+ if (!selected) {
487
+ loading = false;
488
+ notice();
489
+ renderState();
490
+ return;
491
+ }
492
+ const branch = $('branchFilter').value;
493
+ const scope = branch === 'all' || branch === 'current' ? branch : 'branch';
494
+ loading = true;
495
+ updateControls();
496
+ notice(repoState ? '' : '正在读取 Git 仓库…');
497
+ try {
498
+ const result = await repoApi('state', { scope, branch, search: $('search').value, limit });
499
+ if (request !== stateRequest) return;
500
+ repoState = result;
501
+ displayedLimit = limit;
502
+ pendingDiscard = '';
503
+ if (resetScroll) $('historyScroll').scrollTop = 0;
504
+ notice();
505
+ renderState();
506
+ } catch (error) {
507
+ if (request !== stateRequest) return;
508
+ if (scope === 'branch' && retry && error.message.includes('找不到该分支')) {
509
+ $('branchFilter').value = 'all';
510
+ await refreshState({ limit: pageSize, resetScroll: true, retry: false });
511
+ } else {
512
+ notice(error.message, true);
513
+ }
514
+ } finally {
515
+ if (request === stateRequest) {
516
+ loading = false;
517
+ updateControls();
518
+ }
519
+ }
520
+ }
521
+
522
+ function renderState() {
523
+ const repo = repoState?.repo;
524
+ $('branchBadge').hidden = !repo;
525
+ $('branchName').textContent = repo?.detached ? '分离 HEAD ' + repo.branch : (repo?.branch || '');
526
+ $('branchCounts').textContent = [repo?.ahead ? '↑' + repo.ahead : '', repo?.behind ? '↓' + repo.behind : '']
527
+ .filter(Boolean).join(' ');
528
+ $('branchBadge').title = repo?.branch ? [repo.branch, repo.upstream].filter(Boolean).join(' · ') : '';
529
+ renderChanges();
530
+ renderBranchFilter();
531
+ renderHistory();
532
+ updateControls();
533
+ }
534
+
535
+ function renderBranchFilter() {
536
+ const filter = $('branchFilter');
537
+ const value = filter.value;
538
+ const { local = [], remote = [] } = repoState?.branches || {};
539
+ const group = (label, prefix, names) => {
540
+ if (!names.length) return '';
541
+ return '<optgroup label="' + label + '">' + names.map((name) => {
542
+ return '<option value="' + prefix + escapeHtml(name) + '">' + escapeHtml(name) + '</option>';
543
+ }).join('') + '</optgroup>';
544
+ };
545
+ filter.innerHTML = '<option value="all">所有分支</option><option value="current">当前分支</option>' +
546
+ group('本地分支', 'refs/heads/', local) + group('远端分支', 'refs/remotes/', remote);
547
+ filter.value = [...filter.options].some((option) => option.value === value) ? value : 'all';
548
+ }
549
+
550
+ function renderChanges() {
551
+ const { staged, unstaged } = repoState?.status || emptyStatus;
552
+ $('stagedCount').textContent = staged.length;
553
+ $('unstagedCount').textContent = unstaged.length;
554
+ $('changeCount').textContent = staged.length + unstaged.length || '';
555
+ $('staged').innerHTML = changeRows(staged, true);
556
+ $('unstaged').innerHTML = changeRows(unstaged, false);
557
+ }
558
+
559
+ function changeRows(items, staged) {
560
+ return items.map((item, index) => {
561
+ const confirming = !staged && item.path === pendingDiscard;
562
+ const pathTitle = escapeHtml(item.origPath ? item.origPath + ' → ' + item.path : item.path);
563
+ const status = escapeHtml(item.status);
564
+ const discard = item.conflict || staged ? '' : '<button type="button" class="quiet' +
565
+ (confirming ? ' confirm' : '') + '" data-action="discard" title="' +
566
+ (confirming ? '确认放弃更改' : '放弃更改') + '" aria-label="放弃更改">' +
567
+ (confirming ? '确认放弃' : '↺') + '</button>';
568
+ return '<div class="change-row" data-index="' + index + '">' +
569
+ '<button type="button" class="file-main" data-action="working-diff" title="' + pathTitle + '">' +
570
+ '<span class="file-status" data-status="' + status + '">' + status + '</span>' +
571
+ '<span class="file-name truncate">' + escapeHtml(item.fileName) + '</span>' +
572
+ '<span class="file-dir truncate">' + escapeHtml(item.dir) + '</span></button>' +
573
+ '<div class="row-actions">' + discard +
574
+ '<button type="button" class="quiet" data-action="' + (staged ? 'unstage' : 'stage') +
575
+ '" aria-label="' + (staged ? '取消暂存' : '暂存') + '" title="' + (staged ? '取消暂存' : '暂存') + '">' +
576
+ (staged ? '−' : '+') + '</button></div></div>';
577
+ }).join('');
578
+ }
579
+
580
+ function updateControls() {
581
+ const { staged, unstaged } = repoState?.status || emptyStatus;
582
+ const count = staged.length || unstaged.length;
583
+ $('commitButton').textContent = (staged.length ? '提交已暂存' : '全部提交') + ' (' + count + ')';
584
+ $('commitButton').disabled = mutating || !count || !$('message').value.trim();
585
+ $('stageAll').disabled = mutating || !unstaged.length;
586
+ $('unstageAll').disabled = mutating || !staged.length;
587
+ $('more').disabled = loading || mutating;
588
+ $('branchFilter').disabled = !selected;
589
+ $('search').disabled = !selected;
590
+ $('drawerToggle').disabled = mutating;
591
+ for (const button of document.querySelectorAll('.row-actions button')) button.disabled = mutating;
592
+ }
593
+
594
+ function dateText(timestamp) {
595
+ return timeFormat.format(new Date(timestamp * 1000));
596
+ }
597
+
598
+ function relativeTime(timestamp) {
599
+ const seconds = Math.round(timestamp - Date.now() / 1000);
600
+ for (const [unit, size] of [['year', 31536000], ['month', 2592000], ['day', 86400], ['hour', 3600], ['minute', 60]]) {
601
+ if (Math.abs(seconds) >= size) return relativeFormat.format(Math.trunc(seconds / size), unit);
602
+ }
603
+ return Math.abs(seconds) < 5 ? '刚刚' : relativeFormat.format(seconds, 'second');
604
+ }
605
+
606
+ function graphSvg(commit, width) {
607
+ const row = commit.graphRow;
608
+ const x = (lane) => 7 + lane * 14;
609
+ const path = (d, color) => '<path d="' + d + '" stroke="' + lanes[color] +
610
+ '" stroke-width="1.4" fill="none"/>';
611
+ const line = (lane, top, bottom, color) => path('M' + x(lane) + ' ' + top + ' V' + bottom, color);
612
+ const curve = (edge, start, end) => {
613
+ const a = x(edge.fromLane);
614
+ const b = x(edge.toLane);
615
+ const middle = (start + end) / 2;
616
+ return path('M' + a + ' ' + start + ' C' + a + ' ' + middle + ' ' + b + ' ' + middle +
617
+ ' ' + b + ' ' + end, edge.colorIndex);
618
+ };
619
+ const straightIn = row.inLanes.includes(row.lane) ? line(row.lane, 0, 13, row.colorIndex) : '';
620
+ const straightOut = row.outLanes.includes(row.lane) && !row.branchOutEdges.some((edge) => edge.toLane === row.lane)
621
+ ? line(row.lane, 13, 26, row.colorIndex) : '';
622
+ const color = lanes[row.colorIndex];
623
+ const circle = (radius, fill, stroke, opacity = 1) => '<circle cx="' + x(row.lane) +
624
+ '" cy="13" r="' + radius + '" fill="' + fill + '" stroke="' + stroke +
625
+ '" stroke-width="1.3" opacity="' + opacity + '"/>';
626
+ return '<svg aria-hidden="true" width="' + width + '" height="26" viewBox="0 0 ' + width + ' 26">' +
627
+ row.passThroughLanes.map((rail) => line(rail.lane, 0, 26, rail.colorIndex)).join('') +
628
+ straightIn + straightOut + row.mergeInEdges.map((edge) => curve(edge, 0, 13)).join('') +
629
+ row.branchOutEdges.map((edge) => curve(edge, 13, 26)).join('') +
630
+ (commit.isHead ? circle(5.8, 'none', color, .65) : '') +
631
+ circle(commit.isMerge ? 3.8 : 3, commit.isMerge ? 'var(--surface)' : color, color) + '</svg>';
632
+ }
633
+
634
+ function renderHistory() {
635
+ const commits = repoState?.commits || [];
636
+ const width = Math.max(1, repoState?.maxLanes || 0) * 14;
637
+ $('commitList').style.setProperty('--lane-width', width + 'px');
638
+ $('commitList').style.setProperty('--history-min', commits.length ? (width + 120) + 'px' : '0px');
639
+ $('commitList').innerHTML = commits.map((commit, index) => {
640
+ const title = escapeHtml([commit.subject, commit.hash, dateText(commit.timestamp)].join('\n'));
641
+ const refs = commit.parsedRefs.map((ref) => {
642
+ return '<span class="ref truncate ' + escapeHtml(ref.type) + '" title="' + escapeHtml(ref.name) +
643
+ '">' + escapeHtml(ref.name) + '</span>';
644
+ }).join('');
645
+ return '<button type="button" class="commit-row" data-index="' + index + '" title="' + title +
646
+ '" aria-current="' + (drawerView?.hash === commit.hash) + '">' + graphSvg(commit, width) +
647
+ '<span class="commit-center">' + (refs ? '<span class="refs">' + refs + '</span>' : '') +
648
+ '<span class="subject truncate">' + escapeHtml(commit.subject) + '</span></span>' +
649
+ '<span class="commit-meta"><span class="commit-time">' + escapeHtml(relativeTime(commit.timestamp)) +
650
+ '</span><span class="commit-author truncate">' + escapeHtml(commit.author) + '</span></span></button>';
651
+ }).join('');
652
+ $('historyEmpty').hidden = commits.length > 0;
653
+ $('historyEmpty').textContent = !selected ? '选择或添加 Git 仓库。' :
654
+ !repoState ? '正在读取提交记录…' : $('search').value.trim() ? '未找到匹配的提交。' : '暂无提交。';
655
+ $('more').hidden = !repoState?.hasMore;
656
+ }
657
+
658
+ async function mutate(action, data, after = () => {}) {
659
+ if (!selected || mutating) return;
660
+ const path = selected;
661
+ mutating = true;
662
+ pendingDiscard = '';
663
+ updateControls();
664
+ notice();
665
+ try {
666
+ await repoApi(action, data, path);
667
+ if (selected === path) {
668
+ after();
669
+ await refreshState();
670
+ }
671
+ } catch (error) {
672
+ if (selected === path) {
673
+ await refreshState();
674
+ if (selected !== path) return;
675
+ if ($('drawer').open) {
676
+ const target = $('drawerError');
677
+ if (target) target.textContent = error.message;
678
+ } else {
679
+ notice(error.message, true);
680
+ }
681
+ }
682
+ } finally {
683
+ mutating = false;
684
+ updateControls();
685
+ }
686
+ }
687
+
688
+ function diffMarkup(result) {
689
+ if (result.binary) return '<p class="empty">二进制文件</p>';
690
+ if (!result.diff) return '<p class="empty">没有可显示的文本差异。</p>';
691
+ const lines = result.diff.replace(/\n$/, '').split('\n');
692
+ const groups = [];
693
+ for (const line of lines) {
694
+ let type = '';
695
+ if (/^(diff --git |index |--- |\+\+\+ )/.test(line)) type = 'header';
696
+ else if (line.startsWith('@@')) type = 'hunk';
697
+ else if (line.startsWith('+')) type = 'addition';
698
+ else if (line.startsWith('-')) type = 'deletion';
699
+ const previous = groups.at(-1);
700
+ if (previous?.type === type) previous.lines.push(line || ' ');
701
+ else groups.push({ type, lines: [line || ' '] });
702
+ }
703
+ const formatted = groups.map(({ type, lines }) =>
704
+ '<span class="' + type + '">' + escapeHtml(lines.join('\n')) + '</span>').join('');
705
+ return '<pre class="diff">' + formatted + '</pre>' +
706
+ (result.truncated ? '<p class="empty">差异已截断至 200 KB。</p>' : '');
707
+ }
708
+
709
+ function drawerStart(view, title) {
710
+ const request = ++drawerRequest;
711
+ fileRequest++;
712
+ drawerView = view;
713
+ $('drawerTitle').textContent = title;
714
+ $('drawerTitle').title = title;
715
+ $('drawerToggle').hidden = view.kind !== 'working';
716
+ $('drawerToggle').textContent = view.staged ? '取消暂存' : '暂存';
717
+ $('drawerBody').innerHTML = '<p id="drawerError" role="alert"></p><div id="drawerContent"><p class="empty">正在加载…</p></div>';
718
+ $('drawerBody').scrollTop = 0;
719
+ if (!$('drawer').open) $('drawer').showModal();
720
+ updateControls();
721
+ return request;
722
+ }
723
+
724
+ function drawerError(error) {
725
+ $('drawerContent').innerHTML = '<p class="empty" role="alert">' + escapeHtml(error.message) + '</p>';
726
+ }
727
+
728
+ async function openWorking(item, staged) {
729
+ const request = drawerStart({ kind: 'working', item, staged }, (staged ? '已暂存 · ' : '') + item.path);
730
+ try {
731
+ const result = await repoApi('working-diff', { filePath: item.path, staged });
732
+ if (request === drawerRequest && $('drawer').open) $('drawerContent').innerHTML = diffMarkup(result);
733
+ } catch (error) {
734
+ if (request === drawerRequest && $('drawer').open) drawerError(error);
735
+ }
736
+ }
737
+
738
+ async function openCommit(commit) {
739
+ const request = drawerStart({ kind: 'commit', hash: commit.hash }, commit.subject || commit.shortHash);
740
+ try {
741
+ const detail = await repoApi('commit-detail', { hash: commit.hash });
742
+ if (request !== drawerRequest || !$('drawer').open) return;
743
+ drawerView.detail = detail;
744
+ const files = detail.files.map((file, index) => {
745
+ const path = file.origPath ? file.origPath + ' → ' + file.path : file.path;
746
+ return '<button type="button" data-file="' + index + '" title="' + escapeHtml(path) + '">' +
747
+ '<span class="file-status" data-status="' + escapeHtml(file.status) + '">' + escapeHtml(file.status) +
748
+ '</span><span class="file-path truncate">' + escapeHtml(path) + '</span>' +
749
+ (file.binary ? '<span class="muted">二进制</span>' :
750
+ '<span class="stat add">+' + escapeHtml(file.added ?? 0) + '</span>' +
751
+ '<span class="stat del">−' + escapeHtml(file.deleted ?? 0) + '</span>') + '</button>';
752
+ }).join('');
753
+ $('drawerContent').innerHTML = '<div class="drawer-summary">' +
754
+ '<div class="hash-line"><code>' + escapeHtml(detail.hash) + '</code>' +
755
+ '<button type="button" data-copy class="quiet">复制</button></div>' +
756
+ '<p class="muted">' + escapeHtml(detail.author + ' · ' + dateText(detail.timestamp)) + '</p>' +
757
+ (detail.body ? '<pre class="commit-body">' + escapeHtml(detail.body) + '</pre>' : '') + '</div>' +
758
+ (files ? '<div class="commit-files">' + files + '</div>' : '<p class="empty">此提交没有文件差异。</p>') +
759
+ '<div id="commitFileDiff"></div>';
760
+ } catch (error) {
761
+ if (request === drawerRequest && $('drawer').open) drawerError(error);
762
+ }
763
+ }
764
+
765
+ async function openCommitFile(button) {
766
+ const request = ++fileRequest;
767
+ const { detail } = drawerView;
768
+ const file = detail.files[Number(button.dataset.file)];
769
+ const output = $('commitFileDiff');
770
+ for (const item of document.querySelectorAll('[data-file]')) {
771
+ item.setAttribute('aria-current', String(item === button));
772
+ }
773
+ output.innerHTML = '<p class="empty">正在加载差异…</p>';
774
+ try {
775
+ const result = await repoApi('commit-file-diff', {
776
+ hash: detail.hash, filePath: file.path, origPath: file.origPath,
777
+ });
778
+ if (request === fileRequest && $('drawer').open) output.innerHTML = diffMarkup(result);
779
+ } catch (error) {
780
+ if (request === fileRequest && $('drawer').open) output.innerHTML =
781
+ '<p class="empty" role="alert">' + escapeHtml(error.message) + '</p>';
782
+ }
783
+ }
784
+
785
+ async function copyHash(button) {
786
+ const hash = drawerView.detail.hash;
787
+ try {
788
+ await navigator.clipboard.writeText(hash);
789
+ button.textContent = '已复制';
790
+ } catch {
791
+ const code = button.previousElementSibling;
792
+ const selection = window.getSelection();
793
+ const range = document.createRange();
794
+ range.selectNodeContents(code);
795
+ selection.removeAllRanges();
796
+ selection.addRange(range);
797
+ button.textContent = document.execCommand('copy') ? '已复制' : '请手动复制';
798
+ }
799
+ }
800
+
801
+ function toggleRepoForm(open) {
802
+ $('repoForm').hidden = !open;
803
+ $('addToggle').setAttribute('aria-expanded', String(open));
804
+ if (open) $('repoPath').focus();
805
+ }
806
+
807
+ function setExpanded(button, expanded) {
808
+ const section = $(button.getAttribute('aria-controls'));
809
+ section.hidden = !expanded;
810
+ button.setAttribute('aria-expanded', String(expanded));
811
+ if (button.id === 'changesToggle') $('splitter').hidden = !expanded;
812
+ }
813
+
814
+ function resizeChanges(height) {
815
+ const clamped = Math.max(48, Math.min(Math.round(window.innerHeight * .60), height));
816
+ $('changesBody').style.setProperty('--changes-size', clamped + 'px');
817
+ }
818
+
819
+ $('splitter').addEventListener('pointerdown', (event) => {
820
+ if (event.button !== 0) return;
821
+ const splitter = event.currentTarget;
822
+ const start = event.clientY;
823
+ const height = $('changesBody').clientHeight;
824
+ splitter.setPointerCapture(event.pointerId);
825
+ splitter.onpointermove = (move) => resizeChanges(height + move.clientY - start);
826
+ splitter.onlostpointercapture = () => { splitter.onpointermove = null; };
827
+ });
828
+ $('splitter').addEventListener('keydown', (event) => {
829
+ if (!['ArrowDown', 'ArrowUp'].includes(event.key)) return;
830
+ event.preventDefault();
831
+ resizeChanges($('changesBody').clientHeight + (event.key === 'ArrowDown' ? 20 : -20));
832
+ });
833
+
834
+ $('changesToggle').onclick = (event) => {
835
+ const button = event.currentTarget;
836
+ setExpanded(button, button.getAttribute('aria-expanded') !== 'true');
837
+ };
838
+ for (const button of document.querySelectorAll('.change-toggle')) {
839
+ button.onclick = () => setExpanded(button, button.getAttribute('aria-expanded') !== 'true');
840
+ }
841
+
842
+ $('repos').onchange = (event) => {
843
+ switchRepo(event.target.value);
844
+ renderRepoOptions();
845
+ refreshState();
846
+ };
847
+ $('addToggle').onclick = () => toggleRepoForm($('repoForm').hidden);
848
+ $('refresh').onclick = () => refreshRepos();
849
+ $('repoForm').onsubmit = async (event) => {
850
+ event.preventDefault();
851
+ const dirPath = $('repoPath').value.trim();
852
+ if (!dirPath) return;
853
+ try {
854
+ const { repo } = await api('workspaces/add', { dirPath });
855
+ $('repoPath').value = '';
856
+ toggleRepoForm(false);
857
+ await refreshRepos(repo.path);
858
+ } catch (error) {
859
+ notice(error.message, true);
860
+ }
861
+ };
862
+ $('removeRepo').onclick = async () => {
863
+ try {
864
+ await api('workspaces/remove', { repoPath: selected });
865
+ toggleRepoForm(false);
866
+ await refreshRepos();
867
+ } catch (error) {
868
+ notice(error.message, true);
869
+ }
870
+ };
871
+
872
+ function updateFilter() {
873
+ clearTimeout(searchTimer);
874
+ refreshState({ limit: pageSize, resetScroll: true });
875
+ }
876
+ $('branchFilter').onchange = updateFilter;
877
+ $('search').oninput = () => {
878
+ clearTimeout(searchTimer);
879
+ searchTimer = setTimeout(updateFilter, 240);
880
+ };
881
+ $('more').onclick = () => refreshState({ limit: displayedLimit + pageSize });
882
+ $('stageAll').onclick = () => mutate('stage', { all: true });
883
+ $('unstageAll').onclick = () => mutate('unstage', { all: true });
884
+ $('message').oninput = updateControls;
885
+ $('message').onkeydown = (event) => {
886
+ if (event.key === 'Enter' && (event.ctrlKey || event.metaKey) && !event.isComposing) {
887
+ event.preventDefault();
888
+ $('commitForm').requestSubmit();
889
+ }
890
+ };
891
+ $('commitForm').onsubmit = (event) => {
892
+ event.preventDefault();
893
+ if ($('commitButton').disabled) return;
894
+ const message = $('message').value;
895
+ const stageAllIfEmpty = !repoState.status.staged.length;
896
+ mutate('commit', { message, stageAllIfEmpty }, () => {
897
+ if ($('message').value === message) $('message').value = '';
898
+ });
899
+ };
900
+
901
+ function stageChange(action, item, after) {
902
+ const paths = action === 'stage' && item.status === 'R' && item.origPath
903
+ ? [item.origPath, item.path] : [item.path];
904
+ return mutate(action, { paths }, after);
905
+ }
906
+
907
+ for (const section of ['staged', 'unstaged']) {
908
+ $(section).onclick = (event) => {
909
+ const button = event.target.closest('[data-action]');
910
+ if (!button) return;
911
+ const item = repoState?.status[section][Number(button.closest('.change-row').dataset.index)];
912
+ if (!item) return;
913
+ const { action } = button.dataset;
914
+ if (action === 'working-diff') {
915
+ openWorking(item, section === 'staged');
916
+ } else if (action === 'discard') {
917
+ if (pendingDiscard === item.path) {
918
+ mutate('discard', { filePath: item.path, untracked: item.untracked });
919
+ } else {
920
+ pendingDiscard = item.path;
921
+ renderChanges();
922
+ updateControls();
923
+ $(section).querySelector('.confirm')?.focus();
924
+ }
925
+ } else {
926
+ stageChange(action, item);
927
+ }
928
+ };
929
+ }
930
+ $('commitList').onclick = (event) => {
931
+ const row = event.target.closest('.commit-row');
932
+ if (row) openCommit(repoState.commits[Number(row.dataset.index)]);
933
+ };
934
+ $('drawerBody').onclick = (event) => {
935
+ const button = event.target.closest('[data-file], [data-copy]');
936
+ if (!button) return;
937
+ if (button.hasAttribute('data-copy')) copyHash(button);
938
+ else openCommitFile(button);
939
+ };
940
+ $('drawerClose').onclick = () => $('drawer').close();
941
+ $('drawer').onclose = () => {
942
+ if ($('drawer').open) return;
943
+ drawerRequest++;
944
+ fileRequest++;
945
+ drawerView = null;
946
+ };
947
+ $('drawerToggle').onclick = async () => {
948
+ const view = drawerView;
949
+ if (view?.kind !== 'working') return;
950
+ let changed = false;
951
+ await stageChange(view.staged ? 'unstage' : 'stage', view.item, () => { changed = true; });
952
+ if (!changed || view !== drawerView || !$('drawer').open) return;
953
+ const next = (view.staged ? repoState?.status.unstaged : repoState?.status.staged)
954
+ ?.find((item) => item.path === view.item.path);
955
+ if (next) await openWorking(next, !view.staged);
956
+ else $('drawer').close();
957
+ };
958
+ document.addEventListener('keydown', (event) => {
959
+ if (event.key !== 'Escape' || $('drawer').open) return;
960
+ if (pendingDiscard) {
961
+ pendingDiscard = '';
962
+ renderChanges();
963
+ updateControls();
964
+ } else if (!$('repoForm').hidden) {
965
+ toggleRepoForm(false);
966
+ $('addToggle').focus();
967
+ }
968
+ });
969
+
970
+ renderState();
971
+ if (mcpBridge) {
972
+ mcpApp = new mcpBridge.App({ name: 'Git Graph', version: '1.1.0' }, {});
973
+ mcpApp.onhostcontextchanged = applyHostCtx;
974
+ mcpApp.ontoolresult = (result) => {
975
+ const data = parseToolResultPayload(result);
976
+ if (Array.isArray(data?.repos)) {
977
+ bootedFromToolResult = true;
978
+ repos = data.repos;
979
+ const preferred = data.initialRepoPath || '';
980
+ const next = [preferred, selected].find((path) => repos.some((repo) => repo.path === path));
981
+ switchRepo(next || repos[0]?.path || '');
982
+ renderRepoOptions();
983
+ void refreshState();
984
+ }
985
+ };
986
+ mcpConnectPromise = mcpApp.connect().then(() => {
987
+ applyHostCtx(mcpApp.getHostContext());
988
+ if (!bootedFromToolResult) return refreshRepos();
989
+ }).catch((error) => {
990
+ notice(error?.message || '连接 Antigravity MCP App 失败', true);
991
+ });
992
+ } else {
993
+ refreshRepos();
994
+ }
995
+ </script>
996
+ </body>
997
+ </html>