-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenderer.js
More file actions
686 lines (599 loc) · 20.1 KB
/
Copy pathrenderer.js
File metadata and controls
686 lines (599 loc) · 20.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
// --- State ---
let config = { registry: [], workspaces: [] };
let activeWorkspaceId = null;
let activeView = 'welcome'; // 'welcome' | 'workspace' | 'registry'
let syncing = false;
let logVisible = false;
// --- DOM refs ---
const $ = (sel) => document.querySelector(sel);
const $$ = (sel) => document.querySelectorAll(sel);
// --- Init ---
async function init() {
const gitOk = await window.api.checkGit();
if (!gitOk) {
$('#git-error').style.display = 'flex';
return;
}
config = await window.api.getConfig();
renderSidebar();
showView('welcome');
bindEvents();
initLogPanel();
}
// --- Save helper ---
async function save() {
await window.api.saveConfig(config);
}
// --- Sidebar ---
function renderSidebar() {
const list = $('#workspace-list');
list.innerHTML = '';
config.workspaces.forEach((ws) => {
const li = document.createElement('li');
li.textContent = ws.name;
li.dataset.id = ws.id;
if (ws.id === activeWorkspaceId) li.classList.add('active');
li.addEventListener('click', () => selectWorkspace(ws.id));
list.appendChild(li);
});
}
// --- View switching ---
function showView(name) {
activeView = name;
$$('.view').forEach((v) => (v.style.display = 'none'));
$(`#view-${name}`).style.display = '';
}
// --- Select workspace ---
async function selectWorkspace(id) {
activeWorkspaceId = id;
renderSidebar();
showView('workspace');
await renderWorkspace();
}
// --- Render workspace ---
async function renderWorkspace() {
const ws = config.workspaces.find((w) => w.id === activeWorkspaceId);
if (!ws) return;
$('#ws-title').textContent = ws.name;
$('#sync-summary').style.display = 'none';
const tbody = $('#repo-tbody');
tbody.innerHTML = '';
for (const repo of ws.repos) {
const reg = config.registry.find((r) => r.id === repo.registryId);
const tr = document.createElement('tr');
tr.dataset.registryId = repo.registryId;
// Repo name
const tdName = document.createElement('td');
tdName.textContent = repo.registryId;
tdName.title = reg ? reg.localPath : 'Not in registry';
tr.appendChild(tdName);
// Target branch
const tdTarget = document.createElement('td');
tdTarget.textContent = repo.branch || '(current)';
tr.appendChild(tdTarget);
// Current branch
const tdCurrent = document.createElement('td');
tdCurrent.textContent = '...';
tdCurrent.className = 'cell-current-branch';
tr.appendChild(tdCurrent);
// Status
const tdStatus = document.createElement('td');
tdStatus.innerHTML = '<span class="status-dot"></span><span class="status-label"></span>';
tr.appendChild(tdStatus);
// Sync status
const tdSync = document.createElement('td');
tdSync.className = 'sync-text';
tr.appendChild(tdSync);
tbody.appendChild(tr);
// Fetch status async
if (reg) {
fetchRepoStatus(tr, reg.localPath);
} else {
tdCurrent.textContent = '-';
tdStatus.querySelector('.status-dot').classList.add('status-error');
tdStatus.querySelector('.status-label').textContent = 'Not in registry';
}
}
}
async function fetchRepoStatus(tr, localPath) {
const tdCurrent = tr.querySelector('.cell-current-branch');
const dot = tr.querySelector('.status-dot');
const label = tr.querySelector('.status-label');
try {
const status = await window.api.repoStatus(localPath);
if (status.error) {
tdCurrent.textContent = '-';
dot.classList.add('status-error');
label.textContent = status.error;
} else {
tdCurrent.textContent = status.currentBranch;
if (status.dirty) {
dot.classList.add('status-dirty');
label.textContent = 'dirty';
} else {
dot.classList.add('status-clean');
label.textContent = 'clean';
}
}
} catch (e) {
tdCurrent.textContent = '-';
dot.classList.add('status-error');
label.textContent = 'Error';
}
}
// --- Sync all ---
async function syncAll() {
if (syncing) return;
const ws = config.workspaces.find((w) => w.id === activeWorkspaceId);
if (!ws) return;
// Gather statuses first
const repoInfos = [];
for (const repo of ws.repos) {
const reg = config.registry.find((r) => r.id === repo.registryId);
if (!reg) {
repoInfos.push({ repo, reg: null, status: null });
continue;
}
const status = await window.api.repoStatus(reg.localPath);
repoInfos.push({ repo, reg, status });
}
// Check for dirty repos
const dirtyRepos = repoInfos.filter(
(ri) => ri.status && !ri.status.error && ri.status.dirty
);
if (dirtyRepos.length > 0) {
const proceed = await showDirtyWarning(dirtyRepos);
if (!proceed) return;
}
// Sync clean repos
syncing = true;
$('#btn-sync').disabled = true;
let synced = 0;
let skipped = 0;
let failed = 0;
const rows = $('#repo-tbody').querySelectorAll('tr');
for (let i = 0; i < repoInfos.length; i++) {
const ri = repoInfos[i];
const row = rows[i];
const syncCell = row.querySelector('.sync-text');
const dot = row.querySelector('.status-dot');
if (!ri.reg) {
syncCell.textContent = 'Skipped (not in registry)';
syncCell.className = 'sync-text sync-err';
skipped++;
continue;
}
if (ri.status && ri.status.dirty) {
syncCell.textContent = 'Skipped (dirty)';
syncCell.className = 'sync-text sync-err';
skipped++;
continue;
}
if (ri.status && ri.status.error) {
syncCell.textContent = 'Skipped (error)';
syncCell.className = 'sync-text sync-err';
skipped++;
continue;
}
// Sync this repo
dot.className = 'status-dot status-syncing';
syncCell.textContent = 'Syncing...';
syncCell.className = 'sync-text';
const result = await window.api.syncRepo(ri.reg.localPath, ri.repo.branch || null);
if (result.success) {
syncCell.textContent = 'Done';
syncCell.className = 'sync-text sync-ok';
dot.className = 'status-dot status-clean';
// Update current branch display
const tdCurrent = row.querySelector('.cell-current-branch');
if (ri.repo.branch) tdCurrent.textContent = ri.repo.branch;
const label = row.querySelector('.status-label');
label.textContent = 'clean';
synced++;
} else {
syncCell.textContent = result.error;
syncCell.className = 'sync-text sync-err';
dot.className = 'status-dot status-error';
failed++;
}
}
// Summary
const summary = $('#sync-summary');
summary.style.display = '';
if (failed === 0 && skipped === 0) {
summary.className = 'sync-summary success';
summary.textContent = `Sync complete. ${synced} repo(s) updated.`;
} else {
summary.className = 'sync-summary partial';
const parts = [`${synced} synced`];
if (skipped > 0) parts.push(`${skipped} skipped`);
if (failed > 0) parts.push(`${failed} failed`);
summary.textContent = `Sync finished: ${parts.join(', ')}.`;
}
syncing = false;
$('#btn-sync').disabled = false;
}
// --- Dirty warning modal ---
function showDirtyWarning(dirtyRepos) {
return new Promise((resolve) => {
const list = $('#dirty-repo-list');
list.innerHTML = '';
dirtyRepos.forEach((ri) => {
const li = document.createElement('li');
li.textContent = ri.repo.registryId;
list.appendChild(li);
});
$('#modal-dirty').style.display = 'flex';
const onAbort = () => { cleanup(); resolve(false); };
const onContinue = () => { cleanup(); resolve(true); };
const cleanup = () => {
$('#modal-dirty').style.display = 'none';
$('#dirty-abort').removeEventListener('click', onAbort);
$('#dirty-continue').removeEventListener('click', onContinue);
};
$('#dirty-abort').addEventListener('click', onAbort);
$('#dirty-continue').addEventListener('click', onContinue);
});
}
// --- Workspace CRUD ---
function openWorkspaceModal(editId) {
const isEdit = !!editId;
const ws = isEdit ? config.workspaces.find((w) => w.id === editId) : null;
$('#modal-ws-title').textContent = isEdit ? 'Edit Workspace' : 'New Workspace';
$('#modal-ws-name').value = ws ? ws.name : '';
// Build repo checklist from registry
const container = $('#modal-ws-repos');
container.innerHTML = '';
// Select All header row
const selectAllDiv = document.createElement('div');
selectAllDiv.className = 'modal-repo-item modal-repo-header';
const selectAllCb = document.createElement('input');
selectAllCb.type = 'checkbox';
const selectAllLabel = document.createElement('span');
selectAllLabel.className = 'repo-name';
selectAllLabel.textContent = 'Select All';
selectAllLabel.style.fontWeight = '600';
const spacer = document.createElement('span');
spacer.style.width = '160px';
spacer.style.display = 'inline-block';
selectAllDiv.appendChild(selectAllCb);
selectAllDiv.appendChild(selectAllLabel);
selectAllDiv.appendChild(spacer);
container.appendChild(selectAllDiv);
config.registry.forEach((reg) => {
const wsRepo = ws ? ws.repos.find((r) => r.registryId === reg.id) : null;
const div = document.createElement('div');
div.className = 'modal-repo-item';
const cb = document.createElement('input');
cb.type = 'checkbox';
cb.checked = !!wsRepo;
cb.dataset.regId = reg.id;
const name = document.createElement('span');
name.className = 'repo-name';
name.textContent = reg.id;
const branchInput = document.createElement('input');
branchInput.type = 'text';
branchInput.placeholder = '(always active branch)';
branchInput.value = wsRepo ? wsRepo.branch || '' : '';
branchInput.dataset.regId = reg.id;
// If no explicit branch set, pre-fill with current branch from registry
if (!branchInput.value) {
branchInput.classList.add('branch-loading');
branchInput.placeholder = 'loading...';
window.api.repoStatus(reg.localPath).then((status) => {
if (status && !status.error && !branchInput.value) {
branchInput.value = status.currentBranch;
}
branchInput.placeholder = '(always active branch)';
branchInput.classList.remove('branch-loading');
}).catch(() => {
branchInput.placeholder = '(always active branch)';
branchInput.classList.remove('branch-loading');
});
}
div.appendChild(cb);
div.appendChild(name);
div.appendChild(branchInput);
container.appendChild(div);
});
// Select All wiring
const repoCheckboxes = () => container.querySelectorAll('.modal-repo-item:not(.modal-repo-header) input[type="checkbox"]');
function updateSelectAllState() {
const cbs = repoCheckboxes();
const total = cbs.length;
const checked = [...cbs].filter((c) => c.checked).length;
selectAllCb.checked = checked === total && total > 0;
selectAllCb.indeterminate = checked > 0 && checked < total;
}
selectAllCb.addEventListener('change', () => {
repoCheckboxes().forEach((cb) => { cb.checked = selectAllCb.checked; });
});
repoCheckboxes().forEach((cb) => {
cb.addEventListener('change', updateSelectAllState);
});
updateSelectAllState();
$('#modal-workspace').style.display = 'flex';
// Save handler
const onSave = () => {
const name = $('#modal-ws-name').value.trim();
if (!name) return;
const repos = [];
container.querySelectorAll('.modal-repo-item:not(.modal-repo-header)').forEach((item) => {
const cb = item.querySelector('input[type="checkbox"]');
if (!cb.checked) return;
const branchInput = item.querySelector('input[type="text"]');
repos.push({
registryId: cb.dataset.regId,
branch: branchInput.value.trim() || null,
});
});
if (isEdit) {
ws.name = name;
ws.repos = repos;
} else {
config.workspaces.push({
id: 'ws-' + Date.now(),
name,
repos,
});
}
save();
renderSidebar();
if (isEdit) renderWorkspace();
cleanup();
};
const onCancel = () => cleanup();
const cleanup = () => {
$('#modal-workspace').style.display = 'none';
$('#modal-ws-save').removeEventListener('click', onSave);
$('#modal-ws-cancel').removeEventListener('click', onCancel);
};
$('#modal-ws-save').addEventListener('click', onSave);
$('#modal-ws-cancel').addEventListener('click', onCancel);
}
function deleteWorkspace() {
if (!activeWorkspaceId) return;
const ws = config.workspaces.find((w) => w.id === activeWorkspaceId);
if (!confirm(`Delete workspace "${ws.name}"?`)) return;
config.workspaces = config.workspaces.filter((w) => w.id !== activeWorkspaceId);
activeWorkspaceId = null;
save();
renderSidebar();
showView('welcome');
}
// --- Export ---
async function exportWorkspace() {
const ws = config.workspaces.find((w) => w.id === activeWorkspaceId);
if (!ws) return;
const data = {
name: ws.name,
exportedAt: new Date().toISOString(),
repos: ws.repos.map((r) => ({ id: r.registryId, branch: r.branch })),
};
await window.api.exportWorkspace(data);
}
// --- Import ---
async function importWorkspace() {
const data = await window.api.importWorkspace();
if (!data) return;
if (data.error) {
showImportResult('Import Error', data.error, []);
return;
}
// Validate structure
if (!data.name || !Array.isArray(data.repos)) {
showImportResult('Import Error', 'Invalid workspace file format.', []);
return;
}
// Check all repos exist in registry
const missing = [];
data.repos.forEach((r) => {
if (!config.registry.find((reg) => reg.id === r.id)) {
missing.push(r.id);
}
});
if (missing.length > 0) {
showImportResult(
'Import Failed',
'The following repositories are not in your registry. Add them first, then try again:',
missing
);
return;
}
// Create workspace
config.workspaces.push({
id: 'ws-' + Date.now(),
name: data.name,
repos: data.repos.map((r) => ({ registryId: r.id, branch: r.branch })),
});
await save();
renderSidebar();
showImportResult('Import Successful', `Workspace "${data.name}" has been imported.`, []);
}
function showImportResult(title, message, missingList) {
$('#import-title').textContent = title;
$('#import-message').textContent = message;
const ul = $('#import-missing-list');
ul.innerHTML = '';
missingList.forEach((id) => {
const li = document.createElement('li');
li.textContent = id;
ul.appendChild(li);
});
$('#modal-import').style.display = 'flex';
const onOk = () => {
$('#modal-import').style.display = 'none';
$('#import-ok').removeEventListener('click', onOk);
};
$('#import-ok').addEventListener('click', onOk);
}
// --- Registry view ---
async function showRegistry() {
showView('registry');
renderRegistry();
}
function renderRegistry() {
const tbody = $('#registry-tbody');
tbody.innerHTML = '';
const empty = $('#registry-empty');
if (config.registry.length === 0) {
empty.style.display = '';
$('#registry-table').style.display = 'none';
return;
}
empty.style.display = 'none';
$('#registry-table').style.display = '';
config.registry.forEach((reg) => {
const tr = document.createElement('tr');
const tdId = document.createElement('td');
tdId.textContent = reg.id;
tr.appendChild(tdId);
const tdPath = document.createElement('td');
tdPath.textContent = reg.localPath;
tdPath.style.fontSize = '12px';
tdPath.style.color = 'var(--text-dim)';
tr.appendChild(tdPath);
const tdValid = document.createElement('td');
tdValid.innerHTML = '<span class="status-dot"></span>';
tr.appendChild(tdValid);
const tdAction = document.createElement('td');
const removeBtn = document.createElement('button');
removeBtn.className = 'btn-remove';
removeBtn.textContent = '\u00d7';
removeBtn.title = 'Remove from registry';
removeBtn.addEventListener('click', () => removeFromRegistry(reg.id));
tdAction.appendChild(removeBtn);
tr.appendChild(tdAction);
tbody.appendChild(tr);
// Check validity async
window.api.repoStatus(reg.localPath).then((status) => {
const dot = tdValid.querySelector('.status-dot');
if (status.error) {
dot.classList.add('status-error');
dot.title = status.error;
} else {
dot.classList.add('status-clean');
dot.title = 'Valid';
}
});
});
}
async function addRepoToRegistry() {
const result = await window.api.pickRepoFolder();
if (!result) return;
if (result.error) {
alert(result.error);
return;
}
if (config.registry.find((r) => r.id === result.id)) {
alert(`"${result.id}" is already in the registry.`);
return;
}
config.registry.push({ id: result.id, localPath: result.localPath });
await save();
renderRegistry();
}
async function scanFolderToRegistry() {
const found = await window.api.scanFolder();
if (!found || found.length === 0) return;
let added = 0;
found.forEach((item) => {
if (!config.registry.find((r) => r.id === item.id)) {
config.registry.push({ id: item.id, localPath: item.localPath });
added++;
}
});
await save();
renderRegistry();
if (added > 0) {
alert(`Added ${added} new repositor${added === 1 ? 'y' : 'ies'} to the registry.`);
} else {
alert('No new repositories found (all already registered).');
}
}
function removeFromRegistry(regId) {
// Check if used in any workspace
const usedIn = config.workspaces.filter((ws) =>
ws.repos.some((r) => r.registryId === regId)
);
if (usedIn.length > 0) {
const names = usedIn.map((w) => w.name).join(', ');
if (!confirm(`"${regId}" is used in: ${names}.\nRemove it anyway? It will be removed from those workspaces too.`)) {
return;
}
// Remove from workspaces
config.workspaces.forEach((ws) => {
ws.repos = ws.repos.filter((r) => r.registryId !== regId);
});
} else {
if (!confirm(`Remove "${regId}" from registry?`)) return;
}
config.registry = config.registry.filter((r) => r.id !== regId);
save();
renderRegistry();
renderSidebar();
}
// --- Log terminal ---
const MAX_LOG_ENTRIES = 500;
function initLogPanel() {
window.api.onGitLog((entry) => {
appendLogEntry(entry);
});
}
function appendLogEntry(entry) {
const logContent = $('#log-content');
if (!logContent) return;
const div = document.createElement('div');
div.className = 'log-entry';
const ts = document.createElement('span');
ts.className = 'log-entry-ts';
ts.textContent = new Date(entry.timestamp).toLocaleTimeString();
div.appendChild(ts);
if (entry.type === 'cmd') {
const span = document.createElement('span');
span.className = 'log-entry-cmd';
span.textContent = entry.command;
div.appendChild(span);
} else if (entry.type === 'output') {
const span = document.createElement('span');
span.className = 'log-entry-output';
span.textContent = entry.text;
div.appendChild(span);
} else if (entry.type === 'error') {
const span = document.createElement('span');
span.className = 'log-entry-error';
span.textContent = entry.text;
div.appendChild(span);
}
logContent.appendChild(div);
// Trim old entries
while (logContent.children.length > MAX_LOG_ENTRIES) {
logContent.removeChild(logContent.firstChild);
}
// Auto-scroll
logContent.scrollTop = logContent.scrollHeight;
}
function toggleLogPanel() {
logVisible = !logVisible;
$('#log-panel').style.display = logVisible ? 'flex' : 'none';
}
function clearLog() {
$('#log-content').innerHTML = '';
}
// --- Bind events ---
function bindEvents() {
$('#btn-new-workspace').addEventListener('click', () => openWorkspaceModal(null));
$('#btn-registry').addEventListener('click', showRegistry);
$('#btn-import').addEventListener('click', importWorkspace);
$('#btn-sync').addEventListener('click', syncAll);
$('#btn-edit-ws').addEventListener('click', () => openWorkspaceModal(activeWorkspaceId));
$('#btn-export-ws').addEventListener('click', exportWorkspace);
$('#btn-delete-ws').addEventListener('click', deleteWorkspace);
$('#btn-add-repo').addEventListener('click', addRepoToRegistry);
$('#btn-scan-folder').addEventListener('click', scanFolderToRegistry);
$('#btn-toggle-log-panel').addEventListener('click', toggleLogPanel);
$('#btn-clear-log').addEventListener('click', clearLog);
$('#btn-collapse-log').addEventListener('click', () => toggleLogPanel());
}
// --- Start ---
init();