-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathflowStepComponents.js
More file actions
1642 lines (1484 loc) · 86.9 KB
/
Copy pathflowStepComponents.js
File metadata and controls
1642 lines (1484 loc) · 86.9 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
// flowStepComponents.js
/**
* flowStepComponents.js
* Renders individual flow steps for the list view and their corresponding editor forms.
* Uses core logic from flowCore.js.
*/
import {
// Core logic functions needed for rendering/editing steps
extractVariableReferences,
findDefinedVariables, // Used within editors
getHttpMethods,
createNewStep, // Used by Add Step buttons within steps
cloneStep, // Used by clone button on step header
formatJson, // Used by Request editor format button
validateRequestBodyJson, // Used by Request editor format button
parseConditionString, // Used by Condition editor/renderer
generateConditionString, // Used by Condition editor
generateConditionPreview, // Used by Condition editor/renderer
doesOperatorNeedValue, // Used by Condition editor
preProcessBody, // Used by inspector raw ##VAR## marker preview (READ-ONLY)
escapeHTML, // General utility
escapeRegExp // General utility
} from './flowCore.js'; // <--- Ensure this path is correct
import { logger } from './logger.js';
import { TRANSFORM_OP_DEFS, TRANSFORM_OP_NAMES, createTransformOp, normalizeTransformOp } from './transformOps.js';
import { substituteVariables } from './executionHelpers.js';
/**
* Render a flow step element for the steps list view.
* @param {Object} step - Step data object.
* @param {Object} options - Rendering options.
* @param {Object} [options.variables={}] - Available variables for highlighting.
* @param {Function} options.onSelect - Callback when step header is clicked onSelect(stepId).
* @param {Function} options.onUpdate - Callback for step modifications (add, move, clone) onUpdate(action).
* @param {Function} options.onDelete - Callback when delete button is clicked onDelete(stepId). // This maps to onUpdate({type: 'delete', ...}) in the builder
* @param {string | null} options.selectedStepId - The ID of the currently selected step for highlighting.
* @param {boolean} [options.isNested=false] - Flag indicating if the step is rendered inside a branch/loop.
* @param {string | null} [options.parentId=null] - ID of the parent step (for nested adds/deletes).
* @param {string | null} [options.branch=null] - Branch name ('then' or 'else') if nested in a condition.
* @return {HTMLElement} The rendered step element.
*/
export function renderStep(step, options) {
// ... (existing setup) ...
const {
variables = {},
onSelect,
onUpdate, // Used for add/move/clone initiated from list view item
onDelete, // Used for the delete button on the step header
selectedStepId,
isNested = false,
parentId = null, // Capture parentId passed TO this render call
branch = null // Capture branch passed TO this render call
} = options || {};
const stepEl = document.createElement('div');
stepEl.className = `flow-step flow-step-${step.type}`;
stepEl.dataset.stepId = step.id;
if (selectedStepId === step.id) {
stepEl.classList.add('selected');
}
// --- Create Header ---
const header = document.createElement('div');
header.className = 'flow-step-header';
header.innerHTML = `
<span class="flow-step-drag-handle" title="Drag to reorder step" tabindex="0"><svg class="icon icon-sm icon--fill" aria-hidden="true"><use href="#i-grip"/></svg></span>
<span class="flow-step-icon">${getStepTypeIcon(step.type)}</span>
<div class="flow-step-title" title="${escapeHTML(step.name || 'Unnamed Step')}">${escapeHTML(step.name || 'Unnamed Step')}</div>
<div class="flow-step-actions">
<button class="btn-clone" title="Clone this step"><svg class="icon icon-sm" aria-hidden="true"><use href="#i-copy"/></svg></button>
<button class="btn-delete btn-delete-node" title="Delete this step"><svg class="icon icon-sm" aria-hidden="true"><use href="#i-trash"/></svg></button>
</div>
`;
// Header click selects the step (ignore clicks on actions/handle)
header.addEventListener('click', (e) => {
if (!e.target.closest('.flow-step-actions, .flow-step-drag-handle')) {
if (onSelect) onSelect(step.id);
}
});
// Clone button listener
const cloneBtn = header.querySelector('.btn-clone');
if (cloneBtn && onUpdate) {
cloneBtn.addEventListener('click', (e) => {
e.stopPropagation();
const clonedStepData = cloneStep(step); // Use core function
// Ensure clone passes correct context for insertion logic if needed
onUpdate({
type: 'clone',
originalStep: step,
newStep: clonedStepData,
parentId: parentId, // Pass context for insertion logic
branch: branch // Pass context for insertion logic
});
});
}
// Delete button listener
const deleteBtn = header.querySelector('.btn-delete-node, .btn-delete');
if (deleteBtn && onDelete) {
deleteBtn.addEventListener('click', (e) => {
e.stopPropagation();
// The onDelete callback (mapped from onUpdate in builder) triggers the action in app.js
onDelete(step.id); // Correct, onDelete callback handles context
});
}
stepEl.appendChild(header);
// --- Create Content Preview ---
const content = document.createElement('div');
content.className = 'flow-step-content';
// --- CRITICAL: Correctly set parentId and branch for nested calls ---
const nestedOptions = {
...options,
isNested: true,
parentId: step.id, // Current step IS the parent for nested calls
// branch: // branch context will be set specifically inside condition/loop renderers below
};
switch (step.type) {
case 'request':
renderRequestStepContent(content, step, options.variables); // Request doesn't need nested options directly
break;
case 'condition':
// Pass nestedOptions down to condition renderer
renderConditionStepContent(content, step, options.variables, nestedOptions);
break;
case 'loop':
// Pass nestedOptions down to loop renderer
renderLoopStepContent(content, step, options.variables, nestedOptions);
break;
case 'transform':
renderTransformStepContent(content, step, options.variables);
break;
default:
content.innerHTML = `Unknown step type: ${escapeHTML(step.type)}`;
}
stepEl.appendChild(content);
setupDragAndDrop(stepEl, options); // Apply D&D to the step element
return stepEl;
}
// --- Step Content Preview Renderers ---
function renderRequestStepContent(container, step, variables) {
const varNames = Object.keys(variables);
container.innerHTML = `
<div class="request-info">
<span class="request-method ${step.method || 'GET'}">${step.method || 'GET'}</span>
<span class="request-url" title="${escapeHTML(step.url || '')}">${highlightVariables(step.url, varNames)}</span>
</div>
<div class="request-details">
${step.extract && Object.keys(step.extract).length > 0 ? `<div class="request-extractions"><span>Extracts:</span> ${Object.keys(step.extract).map(varName => `<span class="extraction-badge">${escapeHTML(varName)}</span>`).join('')}</div>` : ''}
${step.headers && Object.keys(step.headers).length > 0 ? `<div class="request-headers-badge">${Object.keys(step.headers).length} Header(s)</div>` : ''}
${step.body && String(step.body).trim() ? `<div class="request-body-badge">Has Body</div>` : ''}
</div>
`;
}
function renderConditionStepContent(container, step, variables, options) {
const { onUpdate, parentId, onSelect } = options; // parentId here IS the ID of the condition step itself, get onSelect too
let conditionDisplay = 'No condition set';
if (step.conditionData?.variable && step.conditionData.operator) {
conditionDisplay = escapeHTML(generateConditionPreview(step.conditionData));
} else if (step.condition) {
const parsed = parseConditionString(step.condition);
// Previews carry raw user text (values may contain < / >) — escape
// before innerHTML, same as the visualizer does for this preview.
conditionDisplay = parsed.preview ? escapeHTML(parsed.preview) : escapeHTML(step.condition);
}
container.innerHTML = `
<div class="condition-expression"> <span class="condition-if">If:</span> <code class="condition-code">${conditionDisplay}</code> </div>
<div class="condition-branches">
<div class="branch then-branch"> <div class="branch-header">Then</div> <div class="branch-steps" data-branch-container="then"></div> <button class="btn-add-step" data-branch="then" title="Add step to 'Then'">+ Add Step</button> </div>
<div class="branch else-branch"> <div class="branch-header">Else</div> <div class="branch-steps" data-branch-container="else"></div> <button class="btn-add-step" data-branch="else" title="Add step to 'Else'">+ Add Step</button> </div>
</div>`;
const thenContainer = container.querySelector('[data-branch-container="then"]');
if (step.thenSteps?.length) {
step.thenSteps.forEach(child => thenContainer.appendChild(
renderStep(child, { ...options, branch: 'then' }) // Pass 'then' branch context
));
} else { thenContainer.innerHTML = '<div class="empty-branch">(empty)</div>'; }
const elseContainer = container.querySelector('[data-branch-container="else"]');
if (step.elseSteps?.length) {
step.elseSteps.forEach(child => elseContainer.appendChild(
renderStep(child, { ...options, branch: 'else' }) // Pass 'else' branch context
));
} else { elseContainer.innerHTML = '<div class="empty-branch">(empty)</div>'; }
// Add Step Buttons within branches
container.querySelectorAll('.btn-add-step').forEach(button => {
button.addEventListener('click', (e) => {
e.stopPropagation();
const targetBranch = button.dataset.branch; // 'then' or 'else'
if (onUpdate && parentId) { // parentId is the condition step ID
if (typeof window.showAppStepTypeDialog === 'function') {
window.showAppStepTypeDialog(type => {
if (type) {
const newStep = createNewStep(type);
// --- Use correct parentId and targetBranch ---
onUpdate({ type: 'add', step: newStep, parentId: parentId, branch: targetBranch });
}
});
} else { logger.error("App's step type dialog function not found."); }
} else { logger.error("Cannot add nested step: Missing onUpdate or parentId (condition ID)."); }
});
});
}
function renderLoopStepContent(container, step, variables, options) {
const { onUpdate, parentId, onSelect } = options; // parentId here IS the ID of the loop step itself, get onSelect too
const varNames = Object.keys(variables);
container.innerHTML = `
<div class="loop-config"> <div class="loop-source-row"> <span class="loop-label">For each in:</span> <code class="loop-source">${highlightVariables(`{{${step.source}}}`, varNames)}</code> </div> <div class="loop-variable-row"> <span class="loop-label">As:</span> <code class="loop-variable">${escapeHTML(step.loopVariable || 'item')}</code> </div> </div>
<div class="loop-body"> <div class="loop-header">Loop Body</div> <div class="loop-steps" data-loop-container="body"></div> <button class="btn-add-loop-step" title="Add step inside loop">+ Add Step</button> </div>`;
const loopContainer = container.querySelector('[data-loop-container="body"]');
if (step.loopSteps?.length) {
const loopVariables = { ...variables }; // Pass down current variables
if (step.loopVariable) { // Add loop variable to scope for children
loopVariables[step.loopVariable] = { origin: step.name || 'Loop Step', type: 'loop', stepId: step.id };
}
step.loopSteps.forEach(child => loopContainer.appendChild(
renderStep(child, { ...options, variables: loopVariables /*, branch: null */ }) // No branch for loop children
));
} else { loopContainer.innerHTML = '<div class="empty-branch">(empty)</div>'; }
// Add Step Button within loop body
container.querySelector('.btn-add-loop-step').addEventListener('click', (e) => {
e.stopPropagation();
if (onUpdate && parentId) { // parentId is the loop step ID
if (typeof window.showAppStepTypeDialog === 'function') {
window.showAppStepTypeDialog(type => {
if (type) {
const newStep = createNewStep(type);
// --- Use correct parentId, branch is null for loop ---
onUpdate({ type: 'add', step: newStep, parentId: parentId, branch: null });
}
});
} else { logger.error("App's step type dialog function not found."); }
} else { logger.error("Cannot add loop step: Missing onUpdate or parentId (loop ID)."); }
});
}
function renderTransformStepContent(container, step, variables) {
const ops = Array.isArray(step.ops) ? step.ops : [];
const outputs = ops.map(op => op && typeof op.set === 'string' ? op.set.trim() : '').filter(Boolean);
const outputLabels = outputs.slice(0, 4).map(name => `<span class="extraction-badge">${escapeHTML(name)}</span>`).join('');
const moreCount = outputs.length > 4 ? outputs.length - 4 : 0;
container.innerHTML = `
<div class="request-info">
<span class="request-method TRANSFORM">Transform</span>
<span class="request-url">Ops: ${ops.length}</span>
</div>
<div class="request-details">
${outputs.length > 0 ? `<div class="request-extractions"><span>Outputs:</span> ${outputLabels}${moreCount ? `<span class="extraction-badge">+${moreCount}</span>` : ''}</div>` : ''}
</div>
`;
}
// --- Drag and Drop Setup ---
function setupDragAndDrop(stepEl, options) {
const dragHandle = stepEl.querySelector('.flow-step-drag-handle');
if (!dragHandle || !options.onUpdate) { // Check for onUpdate callback existence
// If no callback, disable D&D
if (dragHandle) dragHandle.draggable = false;
return;
}
dragHandle.draggable = true;
dragHandle.addEventListener('dragstart', (e) => {
// Only allow drag from handle itself
if (!e.target.classList.contains('flow-step-drag-handle')) { e.preventDefault(); return; }
const stepId = stepEl.dataset.stepId;
if (!stepId) return;
e.dataTransfer.setData('text/plain', stepId);
e.dataTransfer.effectAllowed = 'move';
// Delay adding class slightly for better drag image capture
setTimeout(() => stepEl.classList.add('dragging'), 0);
document.body.classList.add('flow-step-dragging'); // Global indicator class
e.stopPropagation();
});
dragHandle.addEventListener('dragend', () => {
// Clean up styles on the dragged element and body
stepEl.classList.remove('dragging');
document.body.classList.remove('flow-step-dragging');
// Ensure any leftover drop indicators are removed globally
document.querySelectorAll('.flow-step.drop-before, .flow-step.drop-after').forEach(el => {
el.classList.remove('drop-before', 'drop-after');
});
});
// Listeners on the step element itself as a potential drop target
stepEl.addEventListener('dragover', (e) => {
e.preventDefault(); // Necessary to allow dropping
const draggingEl = document.querySelector('.flow-step.dragging');
// Prevent dropping on self or inside the content area (only allow dropping relative to the *step element itself*)
// Also prevent dropping a parent step onto one of its descendants
if (!draggingEl || draggingEl === stepEl || stepEl.contains(draggingEl) || e.target.closest('.flow-step-content')) {
e.dataTransfer.dropEffect = 'none';
stepEl.classList.remove('drop-before', 'drop-after'); // Clear indicators if invalid
return;
}
e.dataTransfer.dropEffect = 'move';
// Determine position based on vertical midpoint
const rect = stepEl.getBoundingClientRect();
const isBefore = e.clientY < (rect.top + rect.height / 2);
// Apply indicator classes (only one should be active)
// Check if already set correctly to avoid excessive toggling
if (isBefore && !stepEl.classList.contains('drop-before')) {
stepEl.classList.add('drop-before');
stepEl.classList.remove('drop-after');
} else if (!isBefore && !stepEl.classList.contains('drop-after')) {
stepEl.classList.add('drop-after');
stepEl.classList.remove('drop-before');
}
});
stepEl.addEventListener('dragleave', (e) => {
// Remove indicators only if leaving the element entirely
// relatedTarget is the element the cursor is entering
if (!stepEl.contains(e.relatedTarget)) {
stepEl.classList.remove('drop-before', 'drop-after');
}
});
stepEl.addEventListener('drop', (e) => {
e.preventDefault();
e.stopPropagation(); // Prevent bubbling to parent elements
const sourceStepId = e.dataTransfer.getData('text/plain');
const targetStepId = stepEl.dataset.stepId;
const draggingEl = document.querySelector('.flow-step.dragging'); // Get the element being dragged
// --- Final Validation on Drop ---
// Check source/target IDs and ensure not dropping on self or parent onto descendant
if (!sourceStepId || !targetStepId || sourceStepId === targetStepId || (draggingEl && stepEl.contains(draggingEl)) ) {
stepEl.classList.remove('drop-before', 'drop-after');
if (draggingEl) draggingEl.classList.remove('dragging');
return;
}
// Prevent dropping inside content (redundant check, but safe)
if (e.target.closest('.flow-step-content')) {
stepEl.classList.remove('drop-before', 'drop-after');
if (draggingEl) draggingEl.classList.remove('dragging');
return;
}
// Determine position from class (more reliable than mouse coords at drop time)
const position = stepEl.classList.contains('drop-before') ? 'before' : 'after';
// Clean up indicators immediately
stepEl.classList.remove('drop-before', 'drop-after');
if (draggingEl) draggingEl.classList.remove('dragging'); // Also remove dragging class from source
logger.info(`Drop detected: Move ${sourceStepId} ${position} ${targetStepId}`);
// Trigger the move action via the onUpdate callback provided in options
try {
options.onUpdate({ type: 'move', sourceStepId, targetStepId, position });
} catch (updateError) {
logger.error("Error triggering move update from drop:", updateError);
// Optionally show message, though app.js handler should manage errors
}
});
}
// --- Step Editor Creation ---
/**
* Creates the main editor form structure for a selected step.
* Handles Save/Cancel and dirty state tracking.
* @param {Object} step - The step data object being edited.
* @param {Object} options - Editor options.
* @param {Object} [options.variables={}] - Available variables map.
* @param {Function} options.onChange - Callback triggered on Save: onChange(updatedStepData).
* @param {Object} [options.flowHeaders={}] - Global headers to include in request tooling.
* @param {Object} [options.flowVars={}] - Static flow variables.
* @param {Object | Function | null} [options.runtimeContext=null] - Runtime context (or getter) from last execution.
* @param {Function} [options.onDirtyChange] - Callback for dirty state changes: onDirtyChange(isDirty).
* @return {HTMLElement} The editor form element.
*/
export function createStepEditor(step, options) {
// --- CRITICAL: Check if step data is valid ---
if (!step || !step.id || !step.type) {
logger.error("Cannot create step editor: Invalid step data provided.", step);
const errorEl = document.createElement('div');
errorEl.className = 'step-editor error-message';
errorEl.textContent = "Error: Could not load editor for this step. Step data is missing or invalid.";
return errorEl;
}
const { variables = {}, onChange, onDirtyChange, flowHeaders = {}, flowVars = {}, runtimeContext = null } = options || {};
let localStep; // Local copy for editing
let originalStep; // Store for cancellation
try {
localStep = JSON.parse(JSON.stringify(step));
originalStep = JSON.parse(JSON.stringify(step)); // Keep clean copy for revert
} catch (e) {
logger.error("Failed to clone step for editing:", e);
const errorEl = document.createElement('div'); errorEl.textContent="Error initializing editor state."; return errorEl;
}
let isDirty = false;
// --- Dirty State Management ---
function setDirtyState(dirty) {
if (isDirty === dirty) return; // No change
isDirty = dirty;
if (saveBtn) saveBtn.disabled = !isDirty; // Update save button state (check if saveBtn exists)
if (typeof onDirtyChange === 'function') {
try { onDirtyChange(isDirty); } // Notify parent component
catch (callbackError) { logger.error("Error in onDirtyChange callback:", callbackError); }
}
}
// --- Create Editor Structure (remains same) ---
const editorEl = document.createElement('div');
editorEl.className = 'step-editor inspector inspector-mode-basic';
editorEl.innerHTML = `
<div class="step-editor-content">
<div class="editor-header">
<h3>Edit: ${getStepTypeLabel(localStep.type)} Step</h3>
<div class="inspector-disclosure" role="tablist" aria-label="Field disclosure level">
<button type="button" class="inspector-disclosure-btn active" data-disclosure="basic" role="tab" aria-selected="true" title="Show common fields only">Basic</button>
<button type="button" class="inspector-disclosure-btn" data-disclosure="power" role="tab" aria-selected="false" title="Reveal advanced fields">Power</button>
</div>
</div>
<div class="form-group"> <label for="step-editor-name-${localStep.id}">Step Name</label> <input type="text" id="step-editor-name-${localStep.id}" value="${escapeHTML(localStep.name || '')}" placeholder="Enter a descriptive name"> </div>
<div class="inspector-summary" data-ref="inspectorSummary" aria-live="polite"></div>
<div class="step-save-message" style="display: none; color: var(--run-success); margin: 0.5rem 0; font-weight: 600;"> Step changes saved! </div>
<div class="editor-type-content"> <!-- Type-specific fields go here --> </div>
</div>
<div class="step-editor-actions"> <button class="btn btn-primary btn-save-step" title="Save changes to this step" disabled>Save Step</button> <button class="btn btn-secondary btn-cancel-step" title="Discard changes and revert">Cancel</button> </div>
`;
// --- Get References (remains same) ---
const nameInput = editorEl.querySelector(`#step-editor-name-${localStep.id}`);
const typeContentContainer = editorEl.querySelector('.editor-type-content');
const saveMessageEl = editorEl.querySelector('.step-save-message');
const saveBtn = editorEl.querySelector('.btn-save-step');
const cancelBtn = editorEl.querySelector('.btn-cancel-step');
const summaryEl = editorEl.querySelector('[data-ref="inspectorSummary"]');
const disclosureEl = editorEl.querySelector('.inspector-disclosure');
// --- Basic/Power progressive disclosure (view-only; NEVER marks dirty) ---
function setDisclosure(mode) {
const power = mode === 'power';
editorEl.classList.toggle('inspector-mode-power', power);
editorEl.classList.toggle('inspector-mode-basic', !power);
disclosureEl.querySelectorAll('.inspector-disclosure-btn').forEach(btn => {
const active = btn.dataset.disclosure === mode;
btn.classList.toggle('active', active);
btn.setAttribute('aria-selected', active ? 'true' : 'false');
});
}
disclosureEl.querySelectorAll('.inspector-disclosure-btn').forEach(btn => {
btn.addEventListener('click', () => setDisclosure(btn.dataset.disclosure));
});
// --- Basic-mode at-a-glance summary (common fields distilled) ---
function refreshInspectorSummary() {
if (summaryEl) summaryEl.innerHTML = buildInspectorSummary(localStep);
}
refreshInspectorSummary();
// --- Populate Type-Specific Editor ---
// Pass setDirtyState down
const editorOptions = { variables, localStep, setDirtyState, flowHeaders, flowVars, runtimeContext };
try { // Wrap sub-editor creation
switch (localStep.type) {
case 'request': createRequestEditor(typeContentContainer, editorOptions); break;
case 'condition': createConditionEditor(typeContentContainer, editorOptions); break;
case 'loop': createLoopEditor(typeContentContainer, editorOptions); break;
case 'transform': createTransformEditor(typeContentContainer, editorOptions); break;
default: typeContentContainer.textContent = `Editor not available for type: ${localStep.type}`;
}
} catch (subEditorError) {
logger.error(`Error creating editor for type ${localStep.type}:`, subEditorError);
typeContentContainer.innerHTML = `<p style="color: red;">Error loading ${localStep.type} editor fields.</p>`;
// Disable save button if sub-editor failed
if (saveBtn) saveBtn.disabled = true;
setDirtyState(false); // Not technically dirty if fields failed to load
}
// --- Event Listeners ---
nameInput.addEventListener('input', () => {
localStep.name = nameInput.value;
setDirtyState(true); // Mark dirty on name change
});
// Save Button
saveBtn.addEventListener('click', () => {
if (!isDirty) return; // Do nothing if not dirty
// Perform pre-save logic and validation (moved from createStepEditor main body)
if (localStep.type === 'condition') {
if (localStep.conditionData?.variable && localStep.conditionData?.operator) {
localStep.condition = generateConditionString(localStep.conditionData);
} else {
// Validation: Condition requires variable and operator
document.dispatchEvent(new CustomEvent('flowrunner:toast', { detail: { message: "Condition: select both a variable and an operator.", type: 'error', title: 'Cannot save step' } }));
const varSelect = editorEl.querySelector(`#cond-var-${localStep.id}`);
if (varSelect?.value === '') varSelect.focus();
else editorEl.querySelector(`#cond-op-${localStep.id}`)?.focus();
return; // Prevent saving invalid state
}
}
if (localStep.type === 'loop') {
const loopVar = localStep.loopVariable?.trim();
if (!loopVar || !/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(loopVar)) {
document.dispatchEvent(new CustomEvent('flowrunner:toast', { detail: { message: "Loop: 'Item Variable Name' must be a valid JavaScript variable name.", type: 'error', title: 'Cannot save step' } }));
const varInput = editorEl.querySelector(`#loop-variable-${localStep.id}`);
if (varInput) { varInput.focus(); varInput.style.borderColor = 'red'; }
return; // Prevent saving invalid state
}
let sourceVar = localStep.source?.trim();
// Accept either {{var}} or raw var, but always store as raw var
if (sourceVar && sourceVar.startsWith('{{') && sourceVar.endsWith('}}')) {
sourceVar = sourceVar.slice(2, -2).trim();
}
localStep.source = sourceVar;
if (!sourceVar) {
document.dispatchEvent(new CustomEvent('flowrunner:toast', { detail: { message: "Loop: 'Source' must be a variable reference like {{arrayVariable}}.", type: 'error', title: 'Cannot save step' } }));
const sourceInput = editorEl.querySelector(`#loop-source-${localStep.id}`);
if (sourceInput) sourceInput.focus();
return;
}
}
// Add more validation for Request step if needed (e.g., URL format)
// If validation passes, call parent's onChange with the updated local step data
if (onChange) {
try { onChange(localStep); } // Pass the modified localStep
catch (callbackError) { logger.error("Error in editor save onChange callback:", callbackError); }
}
if (saveMessageEl) { // Check element exists
saveMessageEl.style.display = 'block';
setTimeout(() => { if (saveMessageEl) saveMessageEl.style.display = 'none'; }, 2500);
}
refreshInspectorSummary(); // Reflect saved values in the Basic-mode summary
setDirtyState(false); // Reset dirty state after successful save
});
// Cancel Button
cancelBtn.addEventListener('click', async () => {
if (isDirty) {
// Lazy import avoids a static cycle (dialogs.js imports from this module).
const { showConfirmDialog } = await import('./dialogs.js');
const discard = await showConfirmDialog("Discard unsaved changes to this step?",
{ title: 'Unsaved changes', confirmText: 'Discard', cancelText: 'Keep editing', danger: true });
if (!discard) return; // User canceled the discard action
}
// If discarding or wasn't dirty, reset state and UI
isDirty = false; // Reset local dirty flag first
// --- CRITICAL: Reset localStep object to original state ---
try { localStep = JSON.parse(JSON.stringify(originalStep)); }
catch(e) { logger.error("Failed to revert localStep on cancel:", e); /* Handle error */ return; }
// Reset the UI by re-rendering the editor with original data
nameInput.value = localStep.name || ''; // Reset name input
refreshInspectorSummary(); // Reflect reverted values in the Basic-mode summary
typeContentContainer.innerHTML = ''; // Clear current specific fields
// Re-create sub-editor with original data and pass the *same* setDirtyState function
const revertOptions = { variables, localStep, setDirtyState };
try {
switch (localStep.type) {
case 'request': createRequestEditor(typeContentContainer, revertOptions); break;
case 'condition': createConditionEditor(typeContentContainer, revertOptions); break;
case 'loop': createLoopEditor(typeContentContainer, revertOptions); break;
case 'transform': createTransformEditor(typeContentContainer, revertOptions); break;
default: typeContentContainer.textContent = `Editor not available for type: ${localStep.type}`;
}
} catch (revertError) {
logger.error(`Error reverting editor for type ${localStep.type}:`, revertError);
typeContentContainer.innerHTML = `<p style="color: red;">Error reverting editor fields.</p>`;
}
// Ensure save button is disabled and notify parent that state is clean
if (saveBtn) saveBtn.disabled = true;
if (typeof onDirtyChange === 'function') {
try { onDirtyChange(false); }
catch (callbackError) { logger.error("Error in onDirtyChange callback during cancel:", callbackError); }
}
// Note: We do NOT call onChange(originalStep) here anymore. The editor simply resets itself.
// The parent (app.js) already knows the original state and doesn't need explicit notification of cancellation *unless*
// the cancellation implies a change in the overall flow's dirty state (which setDirtyState(false) handles via onDirtyChange).
});
return editorEl;
}
// --- Type-Specific Editor Creation Functions ---
function shellQuote(value) {
const text = String(value ?? '');
if (text.length === 0) return "''";
return `'${text.replace(/'/g, "'\"'\"'")}'`;
}
function copyTextToClipboard(text) {
if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
return navigator.clipboard.writeText(text);
}
return new Promise((resolve, reject) => {
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.setAttribute('readonly', 'true');
textarea.style.position = 'absolute';
textarea.style.left = '-9999px';
document.body.appendChild(textarea);
textarea.select();
const success = document.execCommand('copy');
document.body.removeChild(textarea);
if (success) resolve();
else reject(new Error('Copy command failed'));
});
}
function replaceUnresolvedPlaceholders(text) {
if (typeof text !== 'string') return text;
return text.replace(/\{\{([^}]+)\}\}/g, (_, varRef) => varRef.trim());
}
function resolveCurlText(value, context, runnerState) {
if (value === undefined || value === null) return '';
if (typeof value !== 'string') {
try {
return JSON.stringify(value);
} catch (error) {
return String(value);
}
}
const substituted = substituteVariables(value, context, { runnerState });
return replaceUnresolvedPlaceholders(substituted);
}
function buildCurlCommand(step, flowHeaders = {}, flowVars = {}, runtimeContext = null) {
const method = (step.method || 'GET').toUpperCase();
const runnerState = { randomIP: null, randomCache: {} };
const context = { ...(flowVars || {}) };
const runtimeValue = typeof runtimeContext === 'function' ? runtimeContext() : runtimeContext;
if (runtimeValue && typeof runtimeValue === 'object') {
Object.assign(context, runtimeValue);
}
const url = resolveCurlText(step.url || '', context, runnerState);
const headers = { ...(flowHeaders || {}), ...(step.headers || {}) };
const parts = ['curl'];
parts.push('-X', method);
parts.push(shellQuote(url));
Object.entries(headers).forEach(([key, value]) => {
if (value === undefined || value === null || String(value).trim() === '') return;
const resolvedValue = resolveCurlText(value, context, runnerState);
parts.push('-H', shellQuote(`${key}: ${resolvedValue}`));
});
const hasContentType = Object.keys(headers).some(key => key.toLowerCase() === 'content-type');
const bodyValue = step.body;
if (bodyValue !== undefined && bodyValue !== null && String(bodyValue).trim() !== '') {
let bodyString = resolveCurlText(bodyValue, context, runnerState);
if (!hasContentType) {
parts.push('-H', shellQuote('Content-Type: application/json'));
}
parts.push('--data-raw', shellQuote(bodyString));
}
return parts.join(' ');
}
// --- [Modified Code] --- in createRequestEditor
function createRequestEditor(container, options) {
const { localStep, variables, setDirtyState, flowHeaders, flowVars, runtimeContext } = options; // Get setDirtyState callback
const availableVarNames = Object.keys(variables);
// --- MODIFICATION START: Add onFailure HTML ---
container.innerHTML = `
<div class="form-group">
<label for="request-url-${localStep.id}">Request</label>
<div class="request-bar" data-method="${escapeHTML(localStep.method || 'GET')}">
<select id="request-method-${localStep.id}" class="request-bar-method" aria-label="HTTP method">${getHttpMethods().map(m => `<option value="${m}" ${localStep.method === m ? 'selected' : ''}>${m}</option>`).join('')}</select>
<input type="text" id="request-url-${localStep.id}" class="request-bar-url" value="${escapeHTML(localStep.url || '')}" placeholder="https://api.example.com/users/{{userId}}" spellcheck="false">
<button class="btn-insert-var request-bar-seg" data-target-input="request-url-${localStep.id}" title="Insert a variable">{{…}}</button>
<button class="btn-copy-curl request-bar-seg" type="button" title="Copy request as cURL"><svg class="icon icon-sm" aria-hidden="true"><use href="#i-terminal"/></svg><span>cURL</span></button>
</div>
</div>
<div class="form-tabs power-only">
<div class="tab-buttons">
<button class="tab-button active" data-tab="headers">Headers (${Object.keys(localStep.headers || {}).length})</button>
<button class="tab-button" data-tab="body">Body</button>
<button class="tab-button" data-tab="extract">Extract (${Object.keys(localStep.extract || {}).length})</button>
<button class="tab-button" data-tab="assertions">Assertions (${Array.isArray(localStep.assertions) ? localStep.assertions.length : 0})</button> <!-- === WAVE3 assertions === -->
<button class="tab-button" data-tab="options">Options</button> <!-- Optional: New tab for options like onFailure -->
</div>
<div class="tab-content active" id="tab-headers-${localStep.id}">
<div class="headers-editor"><div class="headers-list"></div><button class="btn-add-header" style="margin-top:10px;">+ Add Header</button><p class="form-hint">Header values support variables (e.g., <code>{{varName}}</code>) and special variables like <code>{{RANDOM_IP}}</code>, <code>{{RANDOM_INT(1,1000)}}</code>, or <code>{{RANDOM_STRING(16)}}</code>.</p></div>
</div>
<div class="tab-content" id="tab-body-${localStep.id}">
<div class="form-group"><label for="request-body-${localStep.id}">Request Body (JSON)</label><textarea id="request-body-${localStep.id}" rows="10" placeholder='e.g.,\n{\n "key": "value",\n "id": {{var}}\n}'>${escapeHTML(localStep.body || '')}</textarea><div class="form-hint">Use "{{var}}" for strings, {{var}} for numbers/booleans.</div><div class="body-actions"><button type="button" class="btn btn-sm btn-secondary btn-format-json">Format JSON</button><button type="button" class="btn btn-sm btn-secondary btn-insert-var" data-target-input="request-body-${localStep.id}">{{…}} Insert variable</button></div><div class="json-validation-error" style="color:var(--run-error);margin-top:5px;font-size:0.9em;display:none;"></div></div>
<div class="form-group raw-body-markers-group" data-ref="rawBodyGroup" style="display:none;">
<label for="request-body-markers-${localStep.id}">Stored body (##VAR## markers, read-only)</label>
<textarea id="request-body-markers-${localStep.id}" class="raw-body-markers" rows="8" readonly aria-readonly="true" tabindex="-1" spellcheck="false"></textarea>
<div class="form-hint">Read-only preview of exactly what is persisted after <code>{{var}}</code> placeholders are converted to <code>##VAR##</code> markers. Edit the body above, never this view.</div>
</div>
</div>
<div class="tab-content" id="tab-extract-${localStep.id}">
<div class="extract-editor"><div class="extracts-list"></div><button class="btn-add-extract" style="margin-top:10px;">+ Add Extraction</button><p class="form-hint">Extract values via dot notation (<code>body.data.token</code>), array index (<code>body.items[0].id</code>), or keywords (<code>.status</code>, <code>headers.Content-Type</code>, <code>body</code>).</p></div>
</div>
<!-- === WAVE3 assertions === -->
<div class="tab-content" id="tab-assertions-${localStep.id}">
<div class="assertions-editor"><div class="assertions-list"></div><button class="btn-add-assertion" style="margin-top:10px;">+ Add Assertion</button><p class="form-hint">Assertions check a step's result after it runs. Target <code>status</code>, <code>duration</code> (ms), <code>headers.Name</code>, or <code>body.path</code> (e.g. <code>body.data.id</code>). A failed <em>critical</em> assertion stops the flow; others are non-blocking.</p></div>
</div>
<!-- === END WAVE3 assertions === -->
<div class="tab-content" id="tab-options-${localStep.id}">
<div class="form-group">
<label for="request-onfailure-${localStep.id}">On Failure (Network Error or Non-2xx Status)</label>
<select id="request-onfailure-${localStep.id}">
<option value="stop" ${!localStep.onFailure || localStep.onFailure === 'stop' ? 'selected' : ''}>Stop Flow Execution</option>
<option value="continue" ${localStep.onFailure === 'continue' ? 'selected' : ''}>Continue Flow Execution</option>
</select>
<p class="form-hint">Choose behavior when a request fails (network error or status >= 300). 'Stop' halts the entire flow. 'Continue' logs the result and proceeds.</p>
</div>
<div class="form-group">
<label for="request-retry-count-${localStep.id}">Retries</label>
<div class="retries-row">
<label class="retries-field">Extra attempts
<input type="number" id="request-retry-count-${localStep.id}" min="0" max="10" step="1"
value="${Number.isFinite(localStep.retries?.count) ? localStep.retries.count : 0}">
</label>
<label class="retries-field">Delay between attempts
<input type="number" id="request-retry-delay-${localStep.id}" min="0" step="100"
value="${Number.isFinite(localStep.retries?.delayMs) ? localStep.retries.delayMs : 1000}">
<span class="retries-unit">ms</span>
</label>
</div>
<p class="form-hint">Retry a failed request (network error or non-2xx) this many extra times before applying On Failure. 0 = single attempt, exactly today's behavior.</p>
</div>
</div>
</div>`;
// --- MODIFICATION END ---
const methodSelect = container.querySelector(`#request-method-${localStep.id}`);
const urlInput = container.querySelector(`#request-url-${localStep.id}`);
const bodyTextarea = container.querySelector(`#request-body-${localStep.id}`);
const formatBtn = container.querySelector('.btn-format-json');
const copyCurlBtn = container.querySelector('.btn-copy-curl');
const bodyError = container.querySelector('.json-validation-error');
const headersTabBtn = container.querySelector('[data-tab="headers"]');
const extractTabBtn = container.querySelector('[data-tab="extract"]');
const rawBodyGroup = container.querySelector('[data-ref="rawBodyGroup"]');
const rawBodyView = container.querySelector('.raw-body-markers');
// --- READ-ONLY raw ##VAR## marker preview ---
// Renders exactly what preProcessBody() would persist. This view is display-only:
// a hand-typed {{var}} here MUST NEVER reach the saved body JSON, so we route the
// *body textarea* value through preProcessBody unchanged and never read this field back.
function refreshRawBodyMarkers() {
if (!rawBodyView || !rawBodyGroup) return;
const source = String(localStep.body || '');
if (!source.trim()) {
rawBodyGroup.style.display = 'none';
rawBodyView.value = '';
return;
}
rawBodyGroup.style.display = '';
try {
rawBodyView.value = preProcessBody(source);
} catch (error) {
logger.error('Failed to render raw body markers preview:', error);
rawBodyView.value = '';
rawBodyGroup.style.display = 'none';
}
}
refreshRawBodyMarkers();
// --- MODIFICATION START: Get onFailure select ---
const onFailureSelect = container.querySelector(`#request-onfailure-${localStep.id}`);
// --- MODIFICATION END ---
// --- Existing listeners + NEW onFailure listener ---
methodSelect.addEventListener('change', () => {
localStep.method = methodSelect.value;
methodSelect.closest('.request-bar')?.setAttribute('data-method', methodSelect.value);
setDirtyState(true);
});
// Retries ({ count, delayMs } — engine contract in flowRunner; model round-trip in flowCore).
const retryCountInput = container.querySelector(`#request-retry-count-${localStep.id}`);
const retryDelayInput = container.querySelector(`#request-retry-delay-${localStep.id}`);
const syncRetries = () => {
const count = Math.max(0, Math.floor(Number(retryCountInput.value) || 0));
const delayMs = Math.max(0, Number(retryDelayInput.value) || 0);
if (count > 0) localStep.retries = { count, delayMs };
else delete localStep.retries;
setDirtyState(true);
};
retryCountInput?.addEventListener('change', syncRetries);
retryDelayInput?.addEventListener('change', syncRetries);
urlInput.addEventListener('input', () => { localStep.url = urlInput.value; setDirtyState(true); });
bodyTextarea.addEventListener('input', () => { localStep.body = bodyTextarea.value; bodyError.style.display = 'none'; refreshRawBodyMarkers(); setDirtyState(true); });
// --- MODIFICATION START: Add listener for onFailure ---
onFailureSelect.addEventListener('change', () => {
localStep.onFailure = onFailureSelect.value;
setDirtyState(true); // Mark dirty when failure behavior changes
});
if (copyCurlBtn) {
copyCurlBtn.addEventListener('click', () => {
const curlCommand = buildCurlCommand(localStep, flowHeaders, flowVars, runtimeContext);
copyTextToClipboard(curlCommand)
.then(() => {
const originalText = copyCurlBtn.textContent;
copyCurlBtn.textContent = 'Copied';
setTimeout(() => { copyCurlBtn.textContent = originalText; }, 1200);
})
.catch((error) => {
logger.error('Failed to copy cURL command:', error);
});
});
}
// --- MODIFICATION END ---
// ... (rest of formatBtn listener, setupHeadersEditor, setupExtractEditor, tab switching, etc. remain the same) ...
// Setup sub-editors - they call onChange which MUST call setDirtyState(true)
setupHeadersEditor(container.querySelector('.headers-editor'), localStep.headers || {}, availableVarNames, (hdrs) => {
localStep.headers = hdrs;
headersTabBtn.textContent = `Headers (${Object.keys(hdrs).length})`;
setDirtyState(true); // Ensure sub-editor changes mark dirty
});
setupExtractEditor(container.querySelector('.extract-editor'), localStep.extract || {}, (exts) => {
localStep.extract = exts;
extractTabBtn.textContent = `Extract (${Object.keys(exts).length})`;
setDirtyState(true); // Ensure sub-editor changes mark dirty
});
// === WAVE3 assertions ===
const assertionsTabBtn = container.querySelector('[data-tab="assertions"]');
setupAssertionsEditor(container.querySelector('.assertions-editor'), localStep.assertions || [], (asserts) => {
// Keep the model additive: drop the key entirely when empty so a step
// never carries an empty `assertions: []` (byte-stable, CLI-safe).
if (asserts.length > 0) {
localStep.assertions = asserts;
} else {
delete localStep.assertions;
}
if (assertionsTabBtn) assertionsTabBtn.textContent = `Assertions (${asserts.length})`;
setDirtyState(true);
});
// === END WAVE3 assertions ===
// Tab switching logic
container.querySelectorAll('.tab-button').forEach(btn => {
btn.addEventListener('click', () => {
container.querySelectorAll('.tab-button, .tab-content').forEach(el => el.classList.remove('active'));
btn.classList.add('active');
container.querySelector(`#tab-${btn.dataset.tab}-${localStep.id}`).classList.add('active');
});
});
// Add tooltips to tab buttons in editors
container.querySelectorAll('.tab-button').forEach(btn => {
if (btn.dataset.tab === 'headers') btn.title = 'Edit request headers';
else if (btn.dataset.tab === 'body') btn.title = 'Edit request body';
else if (btn.dataset.tab === 'extract') btn.title = 'Extract variables from response';
else if (btn.dataset.tab === 'assertions') btn.title = 'Assert on the response (status, headers, body, duration)';
else if (btn.dataset.tab === 'options') btn.title = 'Request options and error handling';
});
// Setup variable insert buttons (delegated to app.js listener)
container.querySelectorAll('.btn-insert-var').forEach(btn => {
const targetInput = container.querySelector(`#${btn.dataset.targetInput}`);
if (targetInput) setupVariableInsertButton(btn, targetInput, availableVarNames);
});
}
function createConditionEditor(container, options) {
const { localStep, variables, setDirtyState } = options; // Get setDirtyState
const availableVarNames = Object.keys(variables);
// (Ensure conditionData structure - same as before)
if (!localStep.conditionData?.variable || !localStep.conditionData.operator) {
const parsed = parseConditionString(localStep.condition || '');
if (parsed.variable && parsed.operator) localStep.conditionData = parsed;
}
localStep.conditionData = { variable: '', operator: '', value: '', preview: '', ...(localStep.conditionData || {}) };
if (localStep.conditionData.variable && localStep.conditionData.operator) {
localStep.conditionData.preview = generateConditionPreview(localStep.conditionData);
} else {
localStep.conditionData.preview = 'Select variable and operator';
}
// --- PATCH: Add Path input after Variable select ---
const pathValue = localStep.conditionData.variable.split('.').slice(1).join('.') || '';
container.innerHTML = `
<div class="form-group"><label>Condition Logic</label><div class="condition-builder">
<div class="condition-row">
<div class="condition-item"><label for="cond-var-${localStep.id}">Variable</label><select id="cond-var-${localStep.id}"><option value="">-- Select --</option>${availableVarNames.sort().map(v => `<option value="${escapeHTML(v)}" ${localStep.conditionData.variable.split('.')[0] === v ? 'selected' : ''}>${escapeHTML(v)}</option>`).join('')}</select></div>
<div class="condition-item"><label for="cond-path-${localStep.id}">Path</label><input type="text" id="cond-path-${localStep.id}" value="${escapeHTML(pathValue)}" placeholder="e.g. title"></div>
<div class="condition-item"><label for="cond-op-${localStep.id}">Operator</label><select id="cond-op-${localStep.id}"> <option value="">-- Select --</option> <optgroup label="Comparison"><option value="equals">equals</option><option value="not_equals">not equals</option><option value="greater_than">> (number)</option><option value="less_than">< (number)</option><option value="greater_equals">>= (number)</option><option value="less_equals"><= (number)</option></optgroup> <optgroup label="Text"><option value="contains">contains</option><option value="starts_with">starts with</option><option value="ends_with">ends with</option><option value="matches_regex">matches regex</option></optgroup> <optgroup label="Existence"><option value="exists">exists</option><option value="not_exists">does not exist</option></optgroup> <optgroup label="Type"><option value="is_number">is number</option><option value="is_text">is text</option><option value="is_boolean">is boolean</option><option value="is_array">is array</option></optgroup> <optgroup label="Boolean"><option value="is_true">is true</option><option value="is_false">is false</option></optgroup> </select></div>
<div class="condition-item" id="cond-val-cont-${localStep.id}"><label for="cond-val-${localStep.id}">Value</label><div class="input-with-vars"><input type="text" id="cond-val-${localStep.id}" value="${escapeHTML(localStep.conditionData.value)}" placeholder="Enter value"><button class="btn-insert-var" data-target-input="cond-val-${localStep.id}">{{…}}</button></div></div>
</div>
<div class="condition-preview"><label>Preview:</label><pre id="cond-preview-${localStep.id}">${escapeHTML(localStep.conditionData.preview)}</pre></div>
</div></div>
<div class="branches-info"><div class="branch-info then-info"><h4>Then</h4><p>${(localStep.thenSteps?.length || 0)} step(s)</p></div><div class="branch-info else-info"><h4>Else</h4><p>${(localStep.elseSteps?.length || 0)} step(s)</p></div></div>`;
// --- End innerHTML ---
const varSelect = container.querySelector(`#cond-var-${localStep.id}`);
const pathInput = container.querySelector(`#cond-path-${localStep.id}`);
const opSelect = container.querySelector(`#cond-op-${localStep.id}`);
const valInput = container.querySelector(`#cond-val-${localStep.id}`);
const valContainer = container.querySelector(`#cond-val-cont-${localStep.id}`);
const previewEl = container.querySelector(`#cond-preview-${localStep.id}`);
if (localStep.conditionData.operator) opSelect.value = localStep.conditionData.operator;
function updateState() {
const needsValue = doesOperatorNeedValue(opSelect.value);
valContainer.style.display = needsValue ? '' : 'none';
const base = varSelect.value;
const sub = pathInput.value.trim();
const full = sub ? `${base}.${sub}` : base;
localStep.conditionData = {
variable: full,
operator: opSelect.value,
value : needsValue ? valInput.value : ''
};
localStep.conditionData.preview = generateConditionPreview(localStep.conditionData);
previewEl.textContent = escapeHTML(localStep.conditionData.preview);
// Don't call setDirtyState here directly, let the event listeners do it
}
// --- MODIFICATION START: Add immediate dirty listeners ---
varSelect.addEventListener('change', () => { updateState(); setDirtyState(true); });
pathInput.addEventListener('input', () => { updateState(); setDirtyState(true); });
opSelect.addEventListener('change', () => { updateState(); setDirtyState(true); });
valInput.addEventListener('input', () => { updateState(); setDirtyState(true); }); // Use 'input' for value field
// --- MODIFICATION END ---
updateState(); // Initial setup (doesn't mark dirty)
// Setup insert button (delegated)
setupVariableInsertButton(container.querySelector(`#cond-val-cont-${localStep.id} .btn-insert-var`), valInput, availableVarNames);
}
function createLoopEditor(container, options) {
const { localStep, variables, setDirtyState } = options; // Get setDirtyState
const availableVarNames = Object.keys(variables);
// --- Existing innerHTML setup ---
container.innerHTML = `
<div class="form-group"> <label for="loop-source-${localStep.id}">Source (Array Variable)</label> <div class="input-with-vars"> <input type="text" id="loop-source-${localStep.id}" value="${escapeHTML(localStep.source || '')}" placeholder="e.g., {{apiResponse.items}}"> <button class="btn-insert-var" data-target-input="loop-source-${localStep.id}">{{…}}</button> </div> <p class="form-hint">Variable like <code>{{varName}}</code> resolving to an array.</p> </div>
<div class="form-group"> <label for="loop-variable-${localStep.id}">Item Variable Name</label> <input type="text" id="loop-variable-${localStep.id}" value="${escapeHTML(localStep.loopVariable || 'item')}" placeholder="e.g., item"> <p class="form-hint">Name for each item (e.g., {{item}}).</p> <div class="loop-var-validation-error" style="color:red;margin-top:5px;font-size:0.9em;display:none;"></div> </div>
<div class="loop-steps-info"><h4>Loop Body</h4><p>${(localStep.loopSteps?.length || 0)} step(s)</p></div>`;
// --- End innerHTML ---
const sourceInput = container.querySelector(`#loop-source-${localStep.id}`);
const varInput = container.querySelector(`#loop-variable-${localStep.id}`);
const varError = container.querySelector('.loop-var-validation-error');
// --- MODIFICATION START: Validation helper & listeners ---
function validateVarInput(name) {
if (!name) {
varError.textContent = 'Item variable name is required.';
varError.style.display = 'block';
varInput.style.borderColor = 'red';
} else if (!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)) {
varError.textContent = 'Invalid name. Use only letters, numbers, _ or $. Cannot start with a number. Example: item1';
varError.style.display = 'block';
varInput.style.borderColor = 'red';
} else {
varError.style.display = 'none';
varInput.style.borderColor = '';
}
}
varInput.addEventListener('input', () => {
const name = varInput.value.trim();
localStep.loopVariable = name;
validateVarInput(name);