-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfileOperations.js
More file actions
1259 lines (1121 loc) · 56.6 KB
/
Copy pathfileOperations.js
File metadata and controls
1259 lines (1121 loc) · 56.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
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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { RECENT_FILES_KEY, MAX_RECENT_FILES } from './config.js';
import { appState, domRefs } from './state.js';
import {
setLoading, setDirty, showMessage, clearMessages,
updateWorkspaceTitle, renderCurrentFlow, clearWorkspace,
updateViewToggle, setupPaneResizer
} from './uiUtils.js';
import { handleClearResults, updateRunnerUI, handleStopFlow } from './runnerInterface.js';
import {
flowModelToJson, jsonToFlowModel, validateFlow, createTemplateFlow,
escapeHTML, findStepById
} from './flowCore.js';
import { assignNewIdsRecursive } from './modelUtils.js';
import { showConfirmDialog, showInputDialog } from './dialogs.js';
import {
createEmptyWorkspace, parseWorkspace, serializeWorkspace,
addFolder, renameFolder, removeFolder, listChildFolders,
moveFlowToFolder, listFlowsInFolder, removeFlow,
} from './workspaceManager.js';
import { showValidationErrors } from './uiUtils.js';
import { initializeAppComponents } from './app.js'; // <-- ADDED IMPORT
import { logger } from './logger.js'; // <-- ADDED IMPORT
// WAVE2 file-features: rebase the undo/redo "clean" baseline on save.
import { markFlowHistorySaved } from './flowHistory.js';
// Background-run launching from the flow list (Select mode + right-click).
import { createListSelection, formatRunLabel } from './listSelection.js';
import { openContextMenu } from './contextMenu.js';
import { launchBackgroundRuns } from './launchFlows.js';
import { openLaunchConfig } from './launchConfigPopover.js';
// --- Flow-list multi-selection (Select mode) --------------------------------
const flowSelection = createListSelection();
let flowSelectMode = false;
export function isFlowSelectMode() { return flowSelectMode; }
export function getFlowSelectionPaths() { return flowSelection.list(); }
export function flowSelectionSize() { return flowSelection.size(); }
function flowListEl() { return domRefs.flowList || document.getElementById('flow-list'); }
function orderedVisibleRowEls() {
const list = flowListEl();
return list ? [...list.querySelectorAll('.recent-file-item')] : [];
}
function orderedVisiblePaths() {
return orderedVisibleRowEls().map((el) => el.dataset.filePath).filter(Boolean);
}
function knownFlowPaths() {
const filed = (workspaceModel.flows || []).map((f) => f.path);
return new Set([...getRecentFiles(), ...filed]);
}
export function setFlowSelectMode(on) {
flowSelectMode = !!on;
if (!flowSelectMode) flowSelection.clear();
rerenderFlowManager();
}
export function toggleFlowSelectMode() { setFlowSelectMode(!flowSelectMode); }
export function clearFlowSelection() { flowSelection.clear(); rerenderFlowManager(); }
/** Reflect selection count + mode onto the drawer chrome (toggle, action bar). */
function updateFlowSelectionChrome() {
const list = flowListEl();
const n = flowSelection.size();
if (list) {
list.classList.toggle('select-mode', flowSelectMode);
list.classList.toggle('has-selection', n > 0);
}
const toggle = document.getElementById('flow-select-toggle');
if (toggle) {
toggle.setAttribute('aria-pressed', String(flowSelectMode));
toggle.classList.toggle('active', flowSelectMode);
}
const bar = document.getElementById('flowlist-actionbar');
if (bar) {
bar.classList.toggle('visible', flowSelectMode && n > 0);
const count = bar.querySelector('#flowlist-selcount');
if (count) { count.textContent = String(n); count.setAttribute('aria-label', `${n} selected`); }
// The number badge carries the count; the button label stays short so
// it never truncates in the narrow drawer.
const runBtn = bar.querySelector('#flowlist-run-btn');
if (runBtn) runBtn.disabled = n === 0;
}
}
function launchFlowSelection(anchorEl) {
const paths = flowSelection.list();
if (!paths.length) return;
openLaunchConfig({
anchorEl: anchorEl || document.getElementById('flowlist-run-btn') || flowListEl(),
count: paths.length,
onLaunch: (cfg) => { launchBackgroundRuns(paths, cfg); setFlowSelectMode(false); },
});
}
function openRowContextMenu(event, filePath) {
event.preventDefault();
// Never act on an invisible selection (Finder/VS Code): if the right-clicked
// row is not selected, select just it (and enter select mode) first.
if (!flowSelection.has(filePath)) {
flowSelection.set([filePath]);
flowSelectMode = true;
rerenderFlowManager();
}
const paths = flowSelection.list();
const n = paths.length;
const row = event.currentTarget;
const items = [
{ id: 'run', label: formatRunLabel(n), icon: 'i-repeat',
action: () => launchFlowSelection(row) },
];
if (n === 1) {
items.push({ id: 'open', label: 'Open in editor', icon: 'i-file',
action: () => { const li = orderedVisibleRowEls().find((el) => el.dataset.filePath === filePath); setFlowSelectMode(false); if (li) handleFlowListActions({ target: li }); } });
}
items.push({ separator: true });
items.push({ id: 'clear', label: 'Clear selection', action: () => setFlowSelectMode(false) });
openContextMenu({ x: event.clientX, y: event.clientY, items, anchorEl: row });
}
// Simple path shim for display purposes
const path = {
basename: (p) => p.split(/[\\/]/).pop() || p
};
// --- Recent Files Helpers ---
//
// Recent files are now PERSISTED across sessions via electron-store in the main
// process (see main.js `store:*` IPC + preload `getRecentFiles`/`addRecentFile`/
// etc.). To keep every existing SYNCHRONOUS caller working, localStorage remains
// the fast in-renderer mirror and synchronous source of truth; every mutation is
// ALSO pushed to electron-store (fire-and-forget) so the list survives a restart
// and a cleared localStorage. `hydrateRecentFiles()` reconciles the durable store
// back into localStorage on startup.
/** Persist the current localStorage recent-files list to electron-store (async, best-effort). */
function syncRecentFilesToStore(list) {
try {
if (window.electronAPI && typeof window.electronAPI.setRecentFiles === 'function') {
// Fire-and-forget; the durable store is a mirror of the local list.
Promise.resolve(window.electronAPI.setRecentFiles(list)).catch(err => {
logger.warn("Failed to persist recent files to electron-store:", err);
});
}
} catch (error) {
logger.warn("Error syncing recent files to electron-store:", error);
}
}
/**
* Reconcile the durable electron-store recent-files list into the renderer.
* Called once at startup (from loadFlowList). If the durable store has entries
* they become the source of truth (they survive a cleared localStorage); if it's
* empty but localStorage has entries (first run after upgrade), we seed the store
* from localStorage instead. Always re-renders the list when done.
*/
export async function hydrateRecentFiles() {
await hydrateWorkspace();
if (!window.electronAPI || typeof window.electronAPI.getRecentFiles !== 'function') {
// No durable store available (e.g. tests/browser) — render whatever localStorage has.
renderFlowList(getRecentFiles());
return;
}
try {
const result = await window.electronAPI.getRecentFiles();
const durable = (result && result.success && Array.isArray(result.recentFiles))
? result.recentFiles
: [];
const local = getRecentFiles();
if (durable.length > 0) {
// Durable store wins; mirror it into localStorage.
localStorage.setItem(RECENT_FILES_KEY, JSON.stringify(durable));
renderFlowList(durable);
} else if (local.length > 0) {
// First run with persistence: seed the durable store from localStorage.
syncRecentFilesToStore(local);
renderFlowList(local);
} else {
renderFlowList([]);
}
} catch (error) {
logger.error("Error hydrating recent files from electron-store:", error);
renderFlowList(getRecentFiles());
}
}
// --- NEW HELPER FUNCTION ---
/**
* Adds a file path to the recent files list (localStorage mirror + durable
* electron-store).
* @param {string} filePath
* @param {boolean} [moveToTop=true] - If true the file is moved to the top of the list.
*/
export function addRecentFile(filePath, moveToTop = true) {
if (!filePath) return;
try {
let recentFiles = getRecentFiles();
const existingIndex = recentFiles.indexOf(filePath);
if (existingIndex !== -1) {
if (moveToTop) {
recentFiles.splice(existingIndex, 1);
recentFiles.unshift(filePath);
}
} else {
if (moveToTop) {
recentFiles.unshift(filePath);
} else {
recentFiles.push(filePath);
}
}
if (recentFiles.length > MAX_RECENT_FILES) {
recentFiles = recentFiles.slice(0, MAX_RECENT_FILES);
}
localStorage.setItem(RECENT_FILES_KEY, JSON.stringify(recentFiles));
syncRecentFilesToStore(recentFiles);
renderFlowList(recentFiles);
} catch (error) {
logger.error("Error updating recent files in localStorage:", error);
}
}
/**
* Read a flow file into a model WITHOUT touching the open editor — used by the
* Runs page to launch background runs of flows that are not currently open.
* @param {string} filePath
* @returns {Promise<object>} flow model
*/
export async function readFlowModelFromPath(filePath) {
if (!window.electronAPI || typeof window.electronAPI.readFile !== 'function') {
throw new Error('Reading flow files from disk requires the desktop app.');
}
const result = await window.electronAPI.readFile(filePath);
if (!result || !result.success) {
throw new Error(result?.error || 'Could not read the file.');
}
return jsonToFlowModel(JSON.parse(result.data));
}
// --- NEW HELPER FUNCTION ---
// --- SUGGESTED MODIFICATION for NEW VERSION's getRecentFiles ---
export function getRecentFiles() {
try {
const stored = localStorage.getItem(RECENT_FILES_KEY);
logger.debug("Raw stored recent files:", stored);
if (!stored) {
logger.debug("No stored recent files found");
return [];
}
let parsed;
try {
parsed = JSON.parse(stored);
} catch (parseError) {
logger.error("Error parsing recent files from localStorage:", parseError, "Stored data:", stored);
// Corrupted JSON, consider removing or trying to salvage, but for now, just return empty.
// localStorage.removeItem(RECENT_FILES_KEY); // Avoid automatic removal for now
return [];
}
logger.info("Parsed recent files:", parsed);
if (!Array.isArray(parsed)) {
logger.warn("Stored recent files is not an array, resetting to empty. Original data:", parsed);
localStorage.setItem(RECENT_FILES_KEY, '[]'); // Reset if not an array
return [];
}
const validFiles = parsed.filter(path => typeof path === 'string' && path.trim().length > 0);
if (validFiles.length !== parsed.length) {
logger.warn("Filtered out invalid entries from recent files. Saving cleaned list.");
localStorage.setItem(RECENT_FILES_KEY, JSON.stringify(validFiles));
}
return validFiles;
} catch (error) { // This outer catch is for unexpected errors beyond parsing
logger.error("Unexpected error reading recent files from localStorage:", error);
// Do NOT remove the key here, as it might be a temporary issue.
return [];
}
}
function getAfterElement(container, y) {
const items = [...container.querySelectorAll('.recent-file-item:not(.dragging)')];
let closest = { offset: Number.NEGATIVE_INFINITY, element: null };
items.forEach(item => {
const box = item.getBoundingClientRect();
const offset = y - box.top - box.height / 2;
if (offset < 0 && offset > closest.offset) {
closest = { offset, element: item };
}
});
return closest.element;
}
// --- Sidebar Logic (Recent Files) ---
// --- MODIFIED FUNCTION ---
export function loadFlowList() {
// Load and render the recent files list from localStorage
if (!domRefs.flowList) {
logger.error("Cannot load flow list: DOM element not found");
return;
}
logger.debug("Loading recent files list...");
try {
domRefs.flowList.innerHTML = '<li class="loading-flows">Loading recent files...</li>';
// Render the local mirror immediately, then reconcile with the durable
// electron-store (which may add entries that survived a restart).
renderFlowList(getRecentFiles());
hydrateRecentFiles();
} catch (error) {
logger.debug("Error loading recent files:", error);
domRefs.flowList.innerHTML = '<li class="error-flows">Error loading recent files.</li>';
}
}
// --- MODIFIED FUNCTION ---
// --- Flow manager: sidecar workspace (folders / organization) --------------
// Data layer in workspaceManager.js; persisted via workspace IPC in Electron,
// localStorage in the browser (degraded mode) so the manager works everywhere.
const WORKSPACE_LS_KEY = 'flowrunnerWorkspace';
const FOLDER_COLLAPSE_KEY = 'flowrunnerFolderCollapsed';
let workspaceModel = createEmptyWorkspace();
export async function hydrateWorkspace() {
try {
if (window.electronAPI && typeof window.electronAPI.loadWorkspace === 'function') {
const res = await window.electronAPI.loadWorkspace();
if (res && res.success && res.workspace) {
workspaceModel = parseWorkspace(res.workspace);
return;
}
} else if (typeof localStorage !== 'undefined') {
const raw = localStorage.getItem(WORKSPACE_LS_KEY);
if (raw) {
workspaceModel = parseWorkspace(JSON.parse(raw));
return;
}
}
} catch (error) {
logger.warn('Could not hydrate workspace (using empty):', error);
}
workspaceModel = createEmptyWorkspace();
}
function persistWorkspace() {
try {
const data = serializeWorkspace(workspaceModel);
if (window.electronAPI && typeof window.electronAPI.saveWorkspace === 'function') {
Promise.resolve(window.electronAPI.saveWorkspace(data)).catch((err) => {
logger.warn('Failed to persist workspace:', err);
});
} else if (typeof localStorage !== 'undefined') {
localStorage.setItem(WORKSPACE_LS_KEY, JSON.stringify(data));
}
} catch (error) {
logger.warn('Error persisting workspace:', error);
}
}
function loadCollapsedFolders() {
try {
const raw = localStorage.getItem(FOLDER_COLLAPSE_KEY);
const arr = raw ? JSON.parse(raw) : [];
return new Set(Array.isArray(arr) ? arr : []);
} catch { return new Set(); }
}
function saveCollapsedFolders(set) {
try { localStorage.setItem(FOLDER_COLLAPSE_KEY, JSON.stringify([...set])); } catch { /* ignore */ }
}
function rerenderFlowManager() {
renderFlowList(getRecentFiles());
}
/** Create a folder (root or subfolder) via the in-app input dialog. */
async function promptNewFolder(parentId = null) {
const name = await showInputDialog({
title: parentId ? 'New subfolder' : 'New folder',
message: 'Folders organize your flows; the flow files themselves stay where they are.',
placeholder: 'Folder name',
confirmText: 'Create',
mono: false,
multiline: false,
});
if (!name || !name.trim()) return;
addFolder(workspaceModel, { name: name.trim(), parentId });
persistWorkspace();
rerenderFlowManager();
}
/** One-time wiring for the drawer's flow-manager chrome (New Folder + Select). */
export function initializeFlowManager() {
document.getElementById('new-folder-btn')?.addEventListener('click', () => promptNewFolder(null));
// Select-mode toggle (reveals checkboxes for multi-select bulk launch).
document.getElementById('flow-select-toggle')?.addEventListener('click', () => toggleFlowSelectMode());
// Contextual action bar buttons.
document.getElementById('flowlist-run-btn')?.addEventListener('click', (e) => launchFlowSelection(e.currentTarget));
document.getElementById('flowlist-clear-btn')?.addEventListener('click', () => setFlowSelectMode(false));
}
export function renderFlowList(recentFiles) {
if (!domRefs.flowList) return;
const list = domRefs.flowList;
list.innerHTML = '';
const recent = Array.isArray(recentFiles) ? recentFiles : [];
const getFileName = (filePath) => path.basename(filePath);
const collapsed = loadCollapsedFolders();
const filedPaths = new Set(workspaceModel.flows.filter(f => f.folderId).map(f => f.path));
// ---- flow rows (same structure/classes as before: selection, open-on-click,
// remove button and reorder-drag all keep working) ----
const makeFlowRow = (filePath, { inFolder = false } = {}) => {
const li = document.createElement('li');
li.className = 'flow-list-item recent-file-item';
if (inFolder) li.classList.add('in-folder');
li.dataset.filePath = filePath;
li.title = filePath;
if (filePath === appState.currentFilePath) li.classList.add('selected');
const isChecked = flowSelection.has(filePath);
if (isChecked) li.classList.add('selected-multi');
li.innerHTML = `
<div class="flow-item-content">
<span class="flow-select-box" aria-hidden="true">${isChecked ? '<svg class="icon icon-sm" aria-hidden="true"><use href="#i-check"/></svg>' : ''}</span>
<svg class="icon flow-item-icon" aria-hidden="true"><use href="#i-file"/></svg>
<span class="flow-item-name">${escapeHTML(getFileName(filePath))}</span>
<button class="btn-remove-recent-file"
data-action="remove-recent"
title="Remove from recent list"
aria-label="Remove ${escapeHTML(getFileName(filePath))} from recent list">
<svg class="icon icon-sm" aria-hidden="true"><use href="#i-x"/></svg>
</button>
</div>
`;
li.addEventListener('click', (e) => {
if (e.target.closest('.btn-remove-recent-file')) return;
const hitBox = e.target.closest('.flow-select-box');
// Select mode (or a modifier, or the checkbox) toggles selection
// instead of opening; a plain click at rest still opens the flow.
if (flowSelectMode || hitBox || e.metaKey || e.ctrlKey || e.shiftKey) {
e.preventDefault();
if (!flowSelectMode) flowSelectMode = true;
if (e.shiftKey) flowSelection.range(filePath, orderedVisiblePaths());
else flowSelection.toggle(filePath);
rerenderFlowManager();
return;
}
handleFlowListActions({ target: li });
});
li.addEventListener('contextmenu', (e) => openRowContextMenu(e, filePath));
// Drag: reorder within Recent (existing behavior) + drop onto a folder.
li.draggable = true;
li.addEventListener('dragstart', (e) => {
// Selecting must never start a drag (drag-to-folder is load-bearing).
if (flowSelectMode || e.metaKey || e.ctrlKey || e.shiftKey) { e.preventDefault(); return; }
li.classList.add('dragging');
try { e.dataTransfer.setData('text/flow-path', filePath); } catch { /* jsdom */ }
if (e.dataTransfer) e.dataTransfer.effectAllowed = 'move';
});
li.addEventListener('dragend', () => {
li.classList.remove('dragging');
// Persist the visual order of the TOP-LEVEL (unfiled) rows only;
// folder membership is workspace state, not recency order.
const order = [...list.querySelectorAll(':scope > .recent-file-item')].map(el => el.dataset.filePath);
const filed = getRecentFiles().filter(p => !order.includes(p));
const full = [...order, ...filed];
localStorage.setItem(RECENT_FILES_KEY, JSON.stringify(full));
syncRecentFilesToStore(full);
renderFlowList(full);
});
return li;
};
// ---- folder rows ----
const renderFolder = (folder, depth, parentUl) => {
const li = document.createElement('li');
li.className = 'folder-item';
li.style.setProperty('--depth', depth);
const isCollapsed = collapsed.has(folder.id);
const flowsIn = listFlowsInFolder(workspaceModel, folder.id);
const childFolders = listChildFolders(workspaceModel, folder.id);
const row = document.createElement('div');
row.className = 'folder-row';
row.dataset.folderId = folder.id;
row.style.setProperty('--depth', depth);
row.innerHTML = `
<svg class="icon icon-sm folder-chevron${isCollapsed ? ' collapsed' : ''}" aria-hidden="true"><use href="#i-chevron-down"/></svg>
<svg class="icon icon-sm" aria-hidden="true"><use href="#i-folder"/></svg>
<span class="folder-name">${escapeHTML(folder.name)}</span>
<span class="folder-actions">
<button data-folder-action="new-sub" title="New subfolder"><svg class="icon icon-sm" aria-hidden="true"><use href="#i-folder-plus"/></svg></button>
<button data-folder-action="rename" title="Rename folder"><svg class="icon icon-sm" aria-hidden="true"><use href="#i-pencil"/></svg></button>
<button data-folder-action="delete" title="Delete folder (flows are kept)"><svg class="icon icon-sm" aria-hidden="true"><use href="#i-trash"/></svg></button>
</span>
<span class="folder-count">${flowsIn.length}</span>
`;
row.addEventListener('click', async (e) => {
const actionBtn = e.target.closest('[data-folder-action]');
if (actionBtn) {
e.stopPropagation();
const action = actionBtn.dataset.folderAction;
if (action === 'new-sub') {
await promptNewFolder(folder.id);
} else if (action === 'rename') {
const name = await showInputDialog({
title: 'Rename folder', placeholder: 'Folder name',
initialValue: folder.name, confirmText: 'Rename',
mono: false, multiline: false,
});
if (name && name.trim()) {
renameFolder(workspaceModel, folder.id, name.trim());
persistWorkspace();
rerenderFlowManager();
}
} else if (action === 'delete') {
const ok = await showConfirmDialog(
`Delete folder "${folder.name}"? Flows inside are kept and return to Recent; subfolders move up a level.`,
{ title: 'Delete folder', confirmText: 'Delete', danger: true },
);
if (ok) {
removeFolder(workspaceModel, folder.id);
persistWorkspace();
rerenderFlowManager();
}
}
return;
}
// Row click toggles collapse.
const set = loadCollapsedFolders();
if (set.has(folder.id)) set.delete(folder.id); else set.add(folder.id);
saveCollapsedFolders(set);
rerenderFlowManager();
});
// Drop a flow onto the folder to file it.
row.addEventListener('dragover', (e) => { e.preventDefault(); row.classList.add('drop-target'); });
row.addEventListener('dragleave', () => row.classList.remove('drop-target'));
row.addEventListener('drop', (e) => {
e.preventDefault();
e.stopPropagation();
row.classList.remove('drop-target');
let flowPath = '';
try { flowPath = e.dataTransfer.getData('text/flow-path'); } catch { /* ignore */ }
if (!flowPath) flowPath = list.querySelector('.recent-file-item.dragging')?.dataset.filePath || '';
if (!flowPath) return;
moveFlowToFolder(workspaceModel, flowPath, folder.id);
persistWorkspace();
rerenderFlowManager();
});
li.appendChild(row);
const childUl = document.createElement('ul');
childUl.className = 'folder-children';
if (isCollapsed) childUl.style.display = 'none';
childFolders.forEach((cf) => renderFolder(cf, depth + 1, childUl));
flowsIn.forEach((entry) => childUl.appendChild(makeFlowRow(entry.path, { inFolder: true })));
if (!childUl.children.length) {
const empty = document.createElement('li');
empty.className = 'folder-empty';
empty.style.setProperty('--depth', depth);
empty.textContent = 'Empty — drag a flow here';
childUl.appendChild(empty);
}
li.appendChild(childUl);
parentUl.appendChild(li);
};
const rootFolders = listChildFolders(workspaceModel, null);
rootFolders.forEach((f) => renderFolder(f, 0, list));
const unfiled = recent.filter((p) => !filedPaths.has(p));
if (rootFolders.length === 0 && unfiled.length === 0) {
list.innerHTML = '<li class="no-flows">No recent files.</li>';
return;
}
if (rootFolders.length > 0) {
const head = document.createElement('li');
head.className = 'flow-list-section';
head.textContent = 'Recent';
// Dropping on the Recent header un-files a flow.
head.addEventListener('dragover', (e) => { e.preventDefault(); head.classList.add('drop-root-target'); });
head.addEventListener('dragleave', () => head.classList.remove('drop-root-target'));
head.addEventListener('drop', (e) => {
e.preventDefault();
head.classList.remove('drop-root-target');
let flowPath = '';
try { flowPath = e.dataTransfer.getData('text/flow-path'); } catch { /* ignore */ }
if (!flowPath) return;
moveFlowToFolder(workspaceModel, flowPath, null);
persistWorkspace();
rerenderFlowManager();
});
list.appendChild(head);
}
unfiled.forEach((filePath) => list.appendChild(makeFlowRow(filePath)));
// Reorder-drag positioning for the unfiled rows (existing behavior).
list.ondragover = (e) => {
e.preventDefault();
const dragging = list.querySelector(':scope > .recent-file-item.dragging');
if (!dragging) return;
const afterEl = getAfterElement(list, e.clientY);
if (afterEl == null) {
list.appendChild(dragging);
} else if (afterEl.parentElement === list) {
list.insertBefore(dragging, afterEl);
}
};
// Drop any selected paths whose file no longer exists (folder-collapse keeps
// filed flows selected; a real removal drops them), then reflect the chrome.
flowSelection.retain([...knownFlowPaths()]);
updateFlowSelectionChrome();
}
// --- MODIFIED FUNCTION ---
export async function handleFlowListActions(event) {
// First check if we clicked a remove button
const removeButton = event.target.closest('.btn-remove-recent-file');
if (removeButton) {
event.stopPropagation(); // Prevent opening the flow
const listItem = removeButton.closest('.recent-file-item');
if (listItem) {
const filePathToRemove = listItem.dataset.filePath;
if (filePathToRemove) {
logger.debug("Remove from recents:", filePathToRemove);
let currentRecent = getRecentFiles();
currentRecent = currentRecent.filter(p => p !== filePathToRemove);
localStorage.setItem(RECENT_FILES_KEY, JSON.stringify(currentRecent));
// Filed flows live in the workspace, not the recent list — drop
// them there too or the row re-renders inside its folder with a
// dead X (and folders keep referencing files deleted from disk).
removeFlow(workspaceModel, filePathToRemove);
persistWorkspace();
if (window.electronAPI && typeof window.electronAPI.removeRecentFile === 'function') {
Promise.resolve(window.electronAPI.removeRecentFile(filePathToRemove)).catch(err => {
logger.warn("Failed to remove recent file from electron-store:", err);
});
}
renderFlowList(currentRecent);
// If we're removing the currently open flow, clear the current path but don't clear workspace
if (filePathToRemove === appState.currentFilePath) {
appState.currentFilePath = null;
updateWorkspaceTitle(); // Update title to reflect no current file
}
return;
}
}
}
// Handle flow selection (if we didn't click a remove button)
const targetListItem = event.target.closest('.recent-file-item');
if (targetListItem) {
const filePath = targetListItem.dataset.filePath;
if (filePath && filePath !== appState.currentFilePath) {
if (!await confirmStopContinuousRun(`Selecting a new flow`)) {
return;
}
logger.debug(`Recent file selected: ${filePath}`);
handleSelectFlow(filePath);
}
}
}
// --- [Modified Code] in app.js ---
export async function confirmDiscardChanges() {
if (appState.isDirty || appState.stepEditorIsDirty) {
const discard = await showConfirmDialog(
"You have unsaved changes. Discard them and continue?",
{ title: 'Unsaved changes', confirmText: 'Discard changes', cancelText: 'Keep editing', danger: true }
);
if (!discard) {
return false; // User canceled
}
}
// User confirmed discard OR no changes existed
logger.info("Discarding or confirming no unsaved changes.");
appState.isDirty = false;
appState.stepEditorIsDirty = false;
// updateWorkspaceTitle(); // updateWorkspaceTitle is called by setDirty
setDirty(); // Pass false was removed, setDirty will re-evaluate based on new appState flags
return true;
}
// --- MODIFIED FUNCTION ---
export async function handleSelectFlow(filePath) {
// Loads a flow from the given file path
if (appState.isLoading || !filePath) return;
logger.debug(`Attempting to load flow from: ${filePath}`);
if (!await confirmStopContinuousRun(`Loading flow "${path.basename(filePath)}"`)) {
return;
}
if (!(await confirmDiscardChanges())) {
return; // User cancelled discarding changes
}
// Proceed with loading
appState.selectedStepId = null; // Reset step selection
// Do not reorder recent list when selecting from the sidebar
loadAndRenderFlow(filePath, false);
// Update selection highlight in the recent files list (done within loadAndRenderFlow via addRecentFile)
// renderFlowList(getRecentFiles()); // This is redundant if loadAndRenderFlow calls addRecentFile
}
// --- NEW EVENT LISTENER ---
export async function handleOpenFile() {
// Triggered by the "Open Flow" button
if (appState.isLoading) return;
if (!await confirmStopContinuousRun(`Opening a new file`)) {
return;
}
if (!(await confirmDiscardChanges())) {
return; // User cancelled discarding changes
}
logger.info("Requesting open file dialog...");
setLoading(true, 'global');
clearMessages();
try {
if (!window.electronAPI) throw new Error("Electron API not available.");
const result = await window.electronAPI.showOpenFile();
if (result && result.success && !result.cancelled && result.filePath) {
logger.info("File selected:", result.filePath);
// Load and render the selected file
await loadAndRenderFlow(result.filePath);
// Selection highlight updated within loadAndRenderFlow -> addRecentFile
} else if (result && result.success && result.cancelled) {
logger.info("Open file dialog cancelled.");
} else if (result && !result.success && result.error) {
let userMsg = result.error;
if (result.code === 'ENOENT') userMsg = 'File not found. Please check the path.';
else if (result.code === 'EACCES') userMsg = 'Permission denied. You do not have access to this file.';
else if (result.code === 'EISDIR') userMsg = 'Cannot open: Path is a directory.';
else if (result.code === 'EPERM') userMsg = 'Operation not permitted. Check your permissions.';
else if (result.code === 'EMFILE') userMsg = 'Too many files open. Please close some files and try again.';
showMessage(`Error opening file: ${userMsg}`, 'error');
clearWorkspace(true);
initializeAppComponents(); // <-- MODIFIED: Call initializeAppComponents
return;
} else {
logger.warn("Unexpected response from showOpenFile:", result);
throw new Error('Received unexpected response when trying to open file.');
}
} catch (error) {
logger.error('Error opening file:', error);
showMessage(`Error opening file: ${error.message}`, 'error');
// Don't clear workspace on cancel, only on error
if (error.message !== 'Open file dialog cancelled.') {
clearWorkspace(true); // Clear workspace on actual error
initializeAppComponents(); // <-- MODIFIED: Call initializeAppComponents
}
} finally {
setLoading(false, 'global');
}
}
// --- MODIFIED FUNCTION ---
export async function handleCreateNewFlow() {
if (appState.isLoading) return;
if (!await confirmStopContinuousRun(`Creating a new flow`)) {
return;
}
if (!(await confirmDiscardChanges())) {
return; // User cancelled discarding changes
}
logger.info("Creating new flow...");
clearWorkspace(false); // Clear workspace but keep titles etc. temporarily
initializeAppComponents(); // <-- MODIFIED: Call initializeAppComponents
appState.currentFilePath = null; // No file path for new flow
appState.selectedStepId = null;
appState.currentFlowModel = createTemplateFlow();
appState.stepEditorIsDirty = false; // Editor starts clean
appState.isDirty = true; // New flow is dirty until saved
renderCurrentFlow(); // Render the empty flow
renderFlowList(getRecentFiles()); // Update recent list selection (none selected)
updateWorkspaceTitle(); // Reflects new flow name and dirty state
showMessage("New flow created. Edit and save.", "info");
// Ensure controls are visible for the new flow
if(domRefs.toggleInfoBtn) domRefs.toggleInfoBtn.style.display = '';
if(domRefs.toggleVariablesBtn) domRefs.toggleVariablesBtn.style.display = '';
if(domRefs.toggleViewBtn) domRefs.toggleViewBtn.style.display = '';
// Set dirty state which enables/disables save buttons
setDirty(true); // Explicitly call setDirty to update buttons based on new state
// Reset runner
handleClearResults(); // <-- CORRECT: Clears results when creating a new flow
updateRunnerUI();
}
// --- MODIFIED FUNCTION ---
export async function handleCloneFlow() {
// Clones the *current* flow in memory, marks as dirty, clears file path
if (appState.isLoading || !appState.currentFlowModel) {
showMessage("No flow loaded to clone.", "warning");
return;
}
// No need to confirm discard for cloning, as we're cloning the current state.
// If the current state IS dirty, the clone will also be dirty, which is correct.
logger.info("Cloning current flow in memory...");
setLoading(true, 'global');
clearMessages();
try {
// Deep clone the current model in memory using serialization
const clonedModel = jsonToFlowModel(flowModelToJson(appState.currentFlowModel)); // Ensures clean copy
// Ensure unique IDs in the cloned model!
clonedModel.steps = assignNewIdsRecursive(clonedModel.steps);
clonedModel.name = `Copy of ${clonedModel.name || 'Untitled Flow'}`;
clonedModel.id = null; // Cloned flow doesn't have a persistent ID until saved
// Update app state for the clone
appState.currentFlowModel = clonedModel;
appState.currentFilePath = null; // Clone needs to be saved to a new file
appState.selectedStepId = null; // Reset selection
appState.stepEditorIsDirty = false; // Editor starts clean for the clone
appState.isDirty = true; // Clone is immediately dirty
initializeAppComponents(); // <-- MODIFIED: Call initializeAppComponents
renderCurrentFlow(); // Render the cloned flow
renderFlowList(getRecentFiles()); // Update recent list highlighting (no path = no highlight)
updateWorkspaceTitle(); // Reflect clone name and dirty state
showMessage(`Cloned flow "${appState.currentFlowModel.name}". Review and save as new file.`, "info");
// Ensure controls are visible
if(domRefs.toggleInfoBtn) domRefs.toggleInfoBtn.style.display = '';
if(domRefs.toggleVariablesBtn) domRefs.toggleVariablesBtn.style.display = '';
if(domRefs.toggleViewBtn) domRefs.toggleViewBtn.style.display = '';
// Set dirty state which enables/disables save buttons
setDirty(true); // Explicitly call setDirty to update buttons based on new state
handleClearResults(); // <-- CORRECT: Reset runner for the clone
updateRunnerUI(); // Update runner based on cloned state
} catch (error) {
logger.error('Error cloning flow:', error);
showMessage(`Error preparing clone: ${error.message}`, 'error');
} finally {
setLoading(false, 'global');
}
}
// --- MODIFIED FUNCTION ---
// Functionality removed as file deletion is handled by the OS.
export function handleDeleteFlow( /* flowId */ ) {
// This function is no longer needed for local file management.
// Deletion is handled by the user through the operating system's file explorer.
// Associated UI buttons should be removed from the flow list item rendering.
logger.warn("handleDeleteFlow function called, but file deletion should be handled via OS.");
showMessage("To delete a flow, please remove the corresponding '.flow.json' file using your file explorer.", "info");
}
// --- MODIFIED FUNCTION ---
export async function loadAndRenderFlow(filePath, moveToTop = true) {
// Core function to load data from a file path and update the UI
if (!filePath) {
logger.warn("loadAndRenderFlow called with no filePath.");
return false;
}
setLoading(true, 'global');
clearWorkspace(false); // Clear views but keep titles etc.
clearMessages();
let success = false;
try {
if (!window.electronAPI) throw new Error("Electron API not available.");
logger.info(`Reading file via IPC: ${filePath}`);
const result = await window.electronAPI.readFile(filePath);
if (result && result.success) {
logger.info(`File read success: ${filePath}`);
const flowDataJson = result.data;
try {
// Attempt to parse the JSON content
const flowData = JSON.parse(flowDataJson);
appState.currentFlowModel = jsonToFlowModel(flowData); // Convert to internal model
appState.currentFilePath = filePath; // Store the path of the loaded file
appState.stepEditorIsDirty = false; // Reset editor dirty state on load
appState.isDirty = false; // Not dirty initially
initializeAppComponents(); // <-- MODIFIED: Call initializeAppComponents
renderCurrentFlow(); // Render the currently active view
updateWorkspaceTitle(); // Reflects new flow name and path
addRecentFile(filePath, moveToTop); // Add successfully loaded file to recents
// Show controls now that flow is loaded
if(domRefs.toggleInfoBtn) domRefs.toggleInfoBtn.style.display = '';
if(domRefs.toggleVariablesBtn) domRefs.toggleVariablesBtn.style.display = '';
if(domRefs.toggleViewBtn) domRefs.toggleViewBtn.style.display = '';
// Set dirty state which enables/disables save buttons
setDirty(false); // Ensure buttons reflect clean state
handleClearResults(); // <-- CORRECT: Clears results when a new flow is loaded
updateRunnerUI(); // Update runner buttons based on loaded flow
success = true;
} catch (parseError) {
logger.error(`Error parsing JSON from file ${filePath}:`, parseError);
throw new Error(`File is not valid JSON: ${parseError.message}`);
}
} else if (result && !result.success && result.error) {
let userMsg = result.error;
if (result.code === 'ENOENT') userMsg = 'File not found. Please check the path.';
else if (result.code === 'EACCES') userMsg = 'Permission denied. You do not have access to this file.';
else if (result.code === 'EISDIR') userMsg = 'Cannot open: Path is a directory.';
else if (result.code === 'EPERM') userMsg = 'Operation not permitted. Check your permissions.';
else if (result.code === 'EMFILE') userMsg = 'Too many files open. Please close some files and try again.';
showMessage(`Error opening file: ${userMsg}`, 'error');
clearWorkspace(true);
initializeAppComponents(); // <-- MODIFIED: Call initializeAppComponents
return false;
} else {
logger.warn("Unexpected response from readFile IPC:", result);
throw new Error('Unexpected response when trying to read file.');
}
} catch (error) {
logger.error(`Error loading flow from ${filePath}:`, error);
showMessage(`Error loading flow: ${error.message}`, 'error');
clearWorkspace(true); // Clear fully on error
initializeAppComponents(); // <-- MODIFIED: Call initializeAppComponents
appState.currentFilePath = null; // Clear path on error
updateWorkspaceTitle(); // Reset title
success = false;
} finally {
setLoading(false, 'global');
}
return success;
}
// --- Saving Flow (Local Files) ---
// --- [Modified Code] in app.js ---
export async function saveCurrentFlow(forceSaveAs = false) {
if (!appState.currentFlowModel || appState.isLoading) {
showMessage("No flow loaded or currently busy.", "warning");
return false;
}
if (!window.electronAPI) {
showMessage("Error: Cannot save file. Electron API not available.", "error");
return false;
}
let editorCommitted = true; // Assume true unless proven otherwise
// --- CRITICAL: Commit step editor changes if dirty ---
if (appState.stepEditorIsDirty && appState.builderComponent && appState.currentView === 'list-editor') {
logger.info("Step editor is dirty. Attempting programmatic commit before flow save...");
// We need to access the editor's save button, ideally via the builder component instance
// Or by querying the DOM (less ideal but might be necessary)
try {
const editorMount = domRefs.flowBuilderMount?.querySelector('.step-editor-panel .step-editor'); // More specific search
const saveBtn = editorMount?.querySelector('.step-editor-actions .btn-save-step');
if (saveBtn && !saveBtn.disabled) {
saveBtn.click(); // Trigger the editor's save action
// --- VERIFICATION: Check if the editor is still dirty after the click ---
// The click should synchronously trigger handleBuilderStepEdit, which sets stepEditorIsDirty = false.
// If it's still true, the save likely failed validation or encountered an error.
if (appState.stepEditorIsDirty) {
// The editor's internal save logic might have failed (e.g., validation).
// The editor itself should show the specific error.
throw new Error("Unsaved changes in the step editor could not be committed. Please check the editor for errors.");