-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworkspace-manager.js
More file actions
314 lines (272 loc) · 10.6 KB
/
Copy pathworkspace-manager.js
File metadata and controls
314 lines (272 loc) · 10.6 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
// workspace-manager.js
const WorkspaceManager = {
workspaces: [],
activeId: null,
_switching: false,
// --- Persistence ---
_storageKey: 'codeContext_workspaces_v2',
_activeKey: 'codeContext_activeId_v2',
save() {
const serializable = this.workspaces.map(ws => ({
...ws,
selectedPaths: [...(ws.selectedPaths instanceof Set ? ws.selectedPaths : [])],
expandedDirs: [...(ws.expandedDirs instanceof Set ? ws.expandedDirs : [])],
fileCache: ws.fileCache || {}
}));
try {
localStorage.setItem(this._storageKey, JSON.stringify(serializable));
localStorage.setItem(this._activeKey, this.activeId);
} catch (e) {
// localStorage quota exceeded — save without file caches
try {
const slim = serializable.map(ws => ({ ...ws, fileCache: {} }));
localStorage.setItem(this._storageKey, JSON.stringify(slim));
localStorage.setItem(this._activeKey, this.activeId);
} catch {}
}
},
load() {
try {
const raw = localStorage.getItem(this._storageKey);
const savedId = localStorage.getItem(this._activeKey);
if (raw) {
const parsed = JSON.parse(raw);
// Deduplicate by id — keeps first occurrence
const seen = new Set();
this.workspaces = parsed.filter(ws => {
if (!ws.id || seen.has(ws.id)) return false;
seen.add(ws.id);
return true;
});
// Restore non-serializable runtime state
this.workspaces.forEach(ws => {
if (!ws.fileCache) ws.fileCache = {};
if (!ws.selectedPaths) ws.selectedPaths = new Set();
else ws.selectedPaths = new Set(ws.selectedPaths);
if (!ws.expandedDirs) ws.expandedDirs = new Set();
else ws.expandedDirs = new Set(ws.expandedDirs);
});
if (savedId && this.workspaces.find(ws => ws.id === savedId)) {
this.activeId = savedId;
} else if (this.workspaces.length > 0) {
this.activeId = this.workspaces[0].id;
}
return this.workspaces.length > 0;
}
} catch (e) {}
return false;
},
// --- Workspace lifecycle ---
_newId() {
return 'ws_' + Date.now() + '_' + Math.random().toString(36).slice(2, 7);
},
_blankWorkspace(label) {
return {
id: this._newId(),
label: label || 'New Tab',
repoUrl: 'https://github.com/jblarson/neurofold',
branch: null,
branches: [],
defaultBranch: null,
commitMessage: '',
owner: null,
repo: null,
treeData: null, // raw GitHub tree JSON
fileCache: {}, // path -> content
selectedPaths: new Set(), // checked file paths
expandedDirs: new Set(), // expanded dir paths
instructions: '',
output: '',
neurofoldToggle: false,
multiMode: false,
advancedPaths: false,
multiConfig: {
frontendPath: 'frontend',
componentsPath: 'frontend/src/components',
graphSubdirNames: ['graph', 'graph2d', 'graph_semantic', 'graph_geometric'],
holdingResponse: 'We are building a decentralized collective intelligence'
}
};
},
create(label) {
const ws = this._blankWorkspace(label);
this.workspaces.push(ws);
this.save();
return ws;
},
getActive() {
return this.workspaces.find(ws => ws.id === this.activeId) || null;
},
get(id) {
return this.workspaces.find(ws => ws.id === id) || null;
},
remove(id) {
const idx = this.workspaces.findIndex(ws => ws.id === id);
if (idx === -1) return;
this.workspaces.splice(idx, 1);
if (this.activeId === id) {
const next = this.workspaces[Math.max(0, idx - 1)];
this.activeId = next ? next.id : null;
}
this.save();
},
updateLabel(id, label) {
const ws = this.get(id);
if (ws) { ws.label = label; this.save(); }
},
// --- State snapshot / restore ---
snapshotActive() {
const ws = this.getActive();
if (!ws || this._switching) return;
// DOM -> state
const ui = UI.elements;
ws.repoUrl = ui.repoUrlInput.value;
ws.neurofoldToggle = document.getElementById('neurofoldSrcToggle')?.checked || false;
ws.instructions = ui.userInstructions.value;
ws.output = ui.outputMessage.value;
ws.multiMode = ui.multiModeToggle?.checked || false;
ws.advancedPaths = document.getElementById('advancedPathsToggle')?.checked || false;
// Multi config fields
const fp = document.getElementById('frontendPath');
const cp = document.getElementById('componentsPath');
const gs = document.getElementById('graphSubdirsInput');
const hr = document.getElementById('holdingResponse');
if (fp) ws.multiConfig.frontendPath = fp.value;
if (cp) ws.multiConfig.componentsPath = cp.value;
if (gs) ws.multiConfig.graphSubdirNames = gs.value.split(',').map(s => s.trim()).filter(Boolean);
if (hr) ws.multiConfig.holdingResponse = hr.value;
// Snapshot branch selector
const branchEl = ui.branchSelect;
if (branchEl && !branchEl.disabled) {
ws.branch = branchEl.value;
ws.branches = Array.from(branchEl.options).map(o => o.value);
}
// Snapshot commit message
ws.commitMessage = ui.commitInfo?.textContent || '';
// Snapshot checked paths and expanded dirs from DOM
ws.selectedPaths = new Set();
ui.fileListContainer.querySelectorAll('input[type="checkbox"]:checked').forEach(cb => {
if (cb.dataset.nodeType === 'file') ws.selectedPaths.add(cb.value);
});
ws.expandedDirs = new Set();
ui.fileListContainer.querySelectorAll('.dir-toggle.open').forEach(toggle => {
const li = toggle.closest('.file-tree-node');
if (li) ws.expandedDirs.add(li.dataset.nodePath);
});
// fileCache is already kept on ws by reference via GitHubAPI.fileCache
// (we sync it below in switchTo)
ws.fileCache = { ...GitHubAPI.fileCache };
ws.owner = GitHubAPI.currentRepo?.owner || null;
ws.repo = GitHubAPI.currentRepo?.repo || null;
this.save();
},
restoreInto(ws) {
this._switching = true;
const ui = UI.elements;
// Restore URL + neurofold toggle
ui.repoUrlInput.value = ws.repoUrl || '';
const nfToggle = document.getElementById('neurofoldSrcToggle');
if (nfToggle) nfToggle.checked = ws.neurofoldToggle || false;
// Restore instructions / output
ui.userInstructions.value = ws.instructions || '';
ui.outputMessage.value = ws.output || '';
// Restore multi-mode UI
if (ui.multiModeToggle) {
ui.multiModeToggle.checked = ws.multiMode || false;
if (ui.multiModeConfig) {
ui.multiModeConfig.style.display = ws.multiMode ? 'block' : 'none';
}
}
const advToggle = document.getElementById('advancedPathsToggle');
const advConfig = document.getElementById('advancedPathsConfig');
if (advToggle) advToggle.checked = ws.advancedPaths || false;
if (advConfig) advConfig.style.display = ws.advancedPaths ? 'block' : 'none';
// Restore multi config fields
const fp = document.getElementById('frontendPath');
const cp = document.getElementById('componentsPath');
const gs = document.getElementById('graphSubdirsInput');
const hr = document.getElementById('holdingResponse');
if (fp) fp.value = ws.multiConfig?.frontendPath || 'frontend';
if (cp) cp.value = ws.multiConfig?.componentsPath || 'frontend/src/components';
if (gs) gs.value = (ws.multiConfig?.graphSubdirNames || []).join(', ');
if (hr) hr.value = ws.multiConfig?.holdingResponse || '';
// Restore GitHub API state
GitHubAPI.fileCache = ws.fileCache || {};
if (ws.owner && ws.repo && ws.branch) {
GitHubAPI.currentRepo = { owner: ws.owner, repo: ws.repo, branch: ws.branch };
} else {
GitHubAPI.currentRepo = null;
}
// Restore branch selector
if (ws.branches && ws.branches.length > 0) {
ui.branchSelect.innerHTML = ws.branches
.map(b => `<option value="${b}"${b === ws.branch ? ' selected' : ''}>${b}</option>`)
.join('');
ui.branchSelect.disabled = false;
} else {
ui.branchSelect.innerHTML = '<option>Pending...</option>';
ui.branchSelect.disabled = true;
}
// Restore commit info
if (ui.commitInfo) ui.commitInfo.textContent = ws.commitMessage || '';
// Restore file tree
if (ws.treeData && ws.treeData.tree && ws.treeData.tree.length) {
ui.fileListContainer.innerHTML = '';
const tree = UI.buildTree(ws.treeData.tree);
UI.renderTree(tree, ui.fileListContainer);
// Re-apply checked state
ui.fileListContainer.querySelectorAll('input[type="checkbox"]').forEach(cb => {
if (cb.dataset.nodeType === 'file' && ws.selectedPaths.has(cb.value)) {
cb.checked = true;
}
});
// Re-apply expanded dirs
ui.fileListContainer.querySelectorAll('.file-tree-node').forEach(li => {
const path = li.dataset.nodePath;
if (ws.expandedDirs.has(path)) {
const sub = li.querySelector(':scope > ul');
const toggle = li.querySelector(':scope > .node-content .dir-toggle');
if (sub) sub.style.display = 'block';
if (toggle) toggle.classList.add('open');
}
});
// Recompute indeterminate states on dir checkboxes
ui.fileListContainer.querySelectorAll('[data-node-type="dir"]').forEach(dirCb => {
const dirLi = dirCb.closest('.file-tree-node');
const children = dirLi.querySelectorAll('input[type="checkbox"][data-node-type="file"]');
const total = children.length;
const checked = [...children].filter(x => x.checked).length;
if (checked === 0) { dirCb.checked = false; dirCb.indeterminate = false; }
else if (checked === total) { dirCb.checked = true; dirCb.indeterminate = false; }
else { dirCb.checked = false; dirCb.indeterminate = true; }
});
ui.selectAllBtn.disabled = false;
ui.deselectAllBtn.disabled = false;
} else {
ui.fileListContainer.innerHTML = `<div style="height:100%;display:flex;align-items:center;justify-content:center;color:var(--text-dim);">Enter URL and fetch to load file tree.</div>`;
ui.selectAllBtn.disabled = true;
ui.deselectAllBtn.disabled = true;
}
// Clear any stale status
UI.clearStatus();
UI.clearAuthError();
this._switching = false;
},
switchTo(id) {
if (id === this.activeId) return;
this.snapshotActive();
this.activeId = id;
const ws = this.get(id);
if (ws) this.restoreInto(ws);
this.save();
TabBar.render();
},
// Called when treeData is freshly loaded for the active workspace
setTreeData(treeData) {
const ws = this.getActive();
if (ws) {
ws.treeData = treeData;
this.save();
}
}
};