Repository navigation
Expand file tree
/
Copy pathscripts_manager.js
More file actions
841 lines (773 loc) · 28.6 KB
/
Copy pathscripts_manager.js
File metadata and controls
841 lines (773 loc) · 28.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
// =========================================================================================
// WARNING: PARITY INVARIANT WITH NATIVE PYTHON IMPLEMENTATION
// If you modify script actions, dropdown logic, templates, or origin handling in this file,
// you MUST also update the corresponding Python / XDL native implementations:
// - Python Controller & Listeners: plugin/scripting/python_runner_ui.py
// - Document Scripts & Data: plugin/scripting/document_scripts.py
// - Localized Strings Catalog: plugin/scripting/editor_ui_strings.py
// - Native Dialog Layout: extension/Dialogs/PythonScriptDialog.xdl
// - Native New Script Dialog: extension/Dialogs/NewScriptDialog.xdl
// =========================================================================================
(function() {
"use strict";
var scriptSections = [];
var scriptIndex = {};
var currentSelectedName = "";
var currentOrigin = "user";
var selectedScriptName = "";
var deletedScriptName = null;
var currentMode = "";
var syncDropdownOnly = false;
var documentAvailable = false;
var documentReadonly = false;
var documentStale = false;
var initialRequested = false;
// Code sent by the last save_script. The host answers with scripts_list,
// not "saved", so the shell's own "saved" handler never cleared dirty.
var pendingSavedCode = null;
// Pending action held while the host asks Save / Don't save / Cancel,
// then while a Yes save is in flight: { type: "switch", name: string } or { type: "new" }.
var pendingUnsavedAction = null;
var runPendingAfterSave = false;
// New in flight; key is the list key being created, and from/text are the script and text shown when Create was clicked.
var pendingNew = null;
function uiApi() {
return window.waEditorUi || null;
}
function t(key, fallback) {
var api = uiApi();
if (api && api.t) {
return api.t(key, fallback);
}
return fallback;
}
function fmt(key) {
var api = uiApi();
var args = arguments;
if (api && api.fmt) {
return api.fmt.apply(api, args);
}
var template = t(key, "");
return template.replace(/\{(\d+)\}/g, function (_, index) {
var argIndex = parseInt(index, 10) + 1;
return args[argIndex] !== undefined ? args[argIndex] : "";
});
}
function setStatus(text, kind) {
var api = uiApi();
if (api && api.setStatus) {
api.setStatus(text, kind);
return;
}
var el = document.getElementById("status");
if (el) {
el.value = "Status: " + text;
el.classList.remove("status-ok", "status-error");
if (kind === "ok") el.classList.add("status-ok");
if (kind === "error") el.classList.add("status-error");
}
}
function setEditorValueClean(code) {
if (!window.editor) return;
var api = uiApi();
if (api && api.setSuppressDirty) {
api.setSuppressDirty(true);
}
window.editor.setValue(code);
if (api && api.setSuppressDirty) {
api.setSuppressDirty(false);
}
if (api && api.markDirty) {
api.markDirty(false);
}
}
// WARNING: If you change this starter template, also update starter_code in:
// plugin/scripting/python_runner_ui.py (_on_new)
var NEW_SCRIPT_TEMPLATE = '# A simple script\nresult = "Hello from Python!"\n';
function applyScriptManagerChrome() {
var btnNew = document.getElementById("btn-new-script");
if (btnNew) {
btnNew.textContent = t("new_label", "New");
btnNew.title = t("new_script_title", "New Python Script");
}
var scriptLabel = document.querySelector('label[for="script-select"]');
if (scriptLabel) {
scriptLabel.textContent = t("script_label", "Script:");
}
var saveAsBtn = document.getElementById("btn-save-as");
if (saveAsBtn) {
saveAsBtn.textContent = t("save_as_label", "Save As...");
}
var deleteBtn = getDeleteBtn();
if (deleteBtn) {
deleteBtn.textContent = t("delete_label", "Delete");
}
var modalTitle = document.getElementById("new-script-modal-title");
if (modalTitle) {
modalTitle.textContent = t("new_script_title", "New Python Script");
}
var nameLabel = document.getElementById("new-script-name-label");
if (nameLabel) {
nameLabel.textContent = t("script_name_label", "Script name:");
}
attachCheckboxLabel();
var btnCreate = document.getElementById("btn-new-script-create");
if (btnCreate) {
btnCreate.textContent = t("create_label", "Create");
}
var btnCancelModal = document.getElementById("btn-new-script-cancel");
if (btnCancelModal) {
btnCancelModal.textContent = t("cancel_label", "Cancel");
}
}
function attachCheckboxLabel() {
var attachLabel = document.getElementById("new-script-attach-label");
var attachCheck = document.getElementById("new-script-attach-check");
var text;
if (!documentAvailable) {
text = t("attach_unavailable_no_document", "Attach to this document (no document is open)");
} else if (documentStale) {
text = t("attach_unavailable_stale", "Attach to this document (this document changed)");
} else if (documentReadonly) {
text = t("attach_unavailable_readonly", "Attach to this document (this document is read-only)");
} else {
text = t("attach_to_document_label", "Attach to this document");
}
if (attachLabel) {
attachLabel.textContent = text;
}
if (attachCheck) {
attachCheck.title = text;
}
}
function getSelectEl() {
return document.getElementById("script-select");
}
function getDeleteBtn() {
return document.getElementById("btn-delete-script");
}
function getManagerContainer() {
return document.getElementById("script-manager-container");
}
function rebuildScriptIndex(sections) {
scriptIndex = {};
scriptSections = sections || [];
for (var s = 0; s < scriptSections.length; s++) {
var section = scriptSections[s];
var scripts = section.scripts || {};
var names = Object.keys(scripts);
for (var i = 0; i < names.length; i++) {
var name = names[i];
scriptIndex[name] = { code: scripts[name], origin: section.id || "user" };
}
}
}
function legacyScriptsToSections(scripts) {
return [{ id: "user", title: t("my_scripts_fallback", "My Scripts"), scripts: scripts || {} }];
}
function applyScriptsList(msg) {
if (msg.load_follows) {
pendingSavedCode = null;
pendingUnsavedAction = null;
runPendingAfterSave = false;
pendingNew = null;
return;
}
var shown = currentSelectedName;
var savedCode = pendingSavedCode;
pendingSavedCode = null;
var deferredAction = null;
if (runPendingAfterSave) {
deferredAction = pendingUnsavedAction;
runPendingAfterSave = false;
pendingUnsavedAction = null;
}
if (savedCode !== null && !msg.status_error_text && window.editor) {
// Clear only when the buffer still matches what was saved; an edit
// typed while the save was in flight stays dirty.
var api = uiApi();
if (api && api.markDirty && window.editor.getValue() === savedCode) {
api.markDirty(false);
}
}
if (msg.sections && msg.sections.length) {
rebuildScriptIndex(msg.sections);
} else if (msg.scripts) {
rebuildScriptIndex(legacyScriptsToSections(msg.scripts));
}
if (typeof msg.selected_script_name === "string") {
selectedScriptName = msg.selected_script_name;
}
documentAvailable = !!msg.document_available;
documentReadonly = !!msg.document_readonly;
documentStale = !!msg.document_stale;
// A read-only fallback stores the raw My Scripts name, but the [Doc] row
// is still listed. Follow that My Scripts row or the next Save retries
// the document and drops the edit.
if (savedCode !== null && !msg.status_error_text && selectedScriptName
&& scriptIndex[selectedScriptName] && currentSelectedName
&& currentSelectedName !== selectedScriptName
&& scriptIndex[currentSelectedName]
&& scriptIndex[currentSelectedName].origin === "document"
&& scriptIndex[selectedScriptName].origin === "user"
&& storageNameForSaveAs(currentSelectedName) === selectedScriptName) {
currentSelectedName = selectedScriptName;
}
syncDropdownOnly = true;
updateToolbarState();
var select = getSelectEl();
var hadDeletedScript = !!deletedScriptName;
deletedScriptName = null;
updateDropdown();
if (hadDeletedScript) {
var newName = select ? select.value : currentSelectedName;
if (newName && scriptIndex[newName] !== undefined) {
setEditorValueClean(scriptIndex[newName].code);
setDataBindingVisible(currentOrigin === "analysis");
} else {
setEditorValueClean("");
setDataBindingVisible(false);
}
if (window.pywebview && window.pywebview.api && window.pywebview.api.select_script) {
window.pywebview.api.select_script(newName || "");
}
}
// Show the new script only once the host lists it, so the text always belongs to currentSelectedName.
// An edit or a script switch made while New was in flight stays.
// Skip while an unsaved prompt is open so a late New list cannot replace the buffer before the user answers.
if (msg.status_error_text) {
pendingNew = null;
} else if (pendingNew && select && scriptIndex[pendingNew.key] && scriptIndex[pendingNew.key].code === NEW_SCRIPT_TEMPLATE) {
var created = pendingNew;
pendingNew = null;
if (pendingUnsavedAction === null && deferredAction === null && shown === created.from && window.editor && window.editor.getValue() === created.text) {
select.value = created.key;
switchToSelected();
}
}
if (msg.status_ok_text) {
setStatus(msg.status_ok_text, "ok");
}
if (msg.status_error_text) {
setStatus(msg.status_error_text, "error");
}
// Yes in the unsaved prompt: run the deferred action only after the save succeeded.
if (deferredAction !== null && savedCode !== null && !msg.status_error_text) {
runUnsavedAction(deferredAction);
}
}
function runUnsavedAction(action) {
if (action.type === "switch") {
var select = getSelectEl();
if (select) {
select.value = action.name;
switchToSelected();
}
} else if (action.type === "new") {
openScriptModal("new");
}
}
function askIfDirty(action) {
var api = uiApi();
if (!api || !api.isDirty || !api.isDirty()) {
return false;
}
// The host answers with unsaved_choice (Save / Don't save / Cancel).
if (pendingUnsavedAction === null && window.pywebview && window.pywebview.api && window.pywebview.api.ask_unsaved) {
pendingUnsavedAction = action;
window.pywebview.api.ask_unsaved(currentSelectedName || t("this_script", "this script"));
}
return true;
}
function onUnsavedChoice(msg) {
var action = pendingUnsavedAction;
if (action === null) {
return;
}
if (msg.choice === "discard") {
pendingUnsavedAction = null;
runUnsavedAction(action);
} else if (msg.choice === "save") {
if (saveActiveScript(currentSelectedName)) {
runPendingAfterSave = true;
} else {
pendingUnsavedAction = null;
setStatus(t("no_script_selected_to_save", "No script is selected to save. Use Save As or choose Don't save."), "error");
}
} else {
pendingUnsavedAction = null;
}
}
function setDataBindingVisible(visible) {
var label = document.getElementById("data-binding-label");
var input = document.getElementById("data-binding-input");
if (label) {
label.classList.toggle("toolbar-hidden", !visible);
}
if (input) {
input.classList.toggle("toolbar-hidden", !visible);
}
}
function isBuiltInHelperOrigin(origin) {
return origin !== "user" && origin !== "document" && origin !== "";
}
function updateToolbarState() {
if (documentStale) {
setStatus(
t(
"document_stale",
"Document changed — close and reopen Run Python Script to edit document scripts."
),
"error"
);
}
}
function handleScriptsManagerMessages(msg) {
if (!msg) return;
if (msg.type === "load") {
pendingNew = null;
pendingUnsavedAction = null;
runPendingAfterSave = false;
if (window.waEditorUi && window.waEditorUi.applyUiFromLoad) {
window.waEditorUi.applyUiFromLoad(msg);
}
applyScriptManagerChrome();
currentMode = msg.mode || "calc_cell";
var isRunScript = currentMode === "run_script";
var container = getManagerContainer();
if (container) {
container.classList.toggle("toolbar-hidden", !isRunScript);
}
var btnNew = document.getElementById("btn-new-script");
if (btnNew) {
btnNew.classList.toggle("toolbar-hidden", !isRunScript);
}
if (isRunScript) {
if (typeof msg.selected_script_name === "string") {
selectedScriptName = msg.selected_script_name;
currentSelectedName = selectedScriptName;
currentOrigin = originFromName(selectedScriptName);
}
if (window.pywebview && window.pywebview.api && window.pywebview.api.request_scripts) {
window.pywebview.api.request_scripts();
initialRequested = true;
}
} else {
selectedScriptName = "";
currentSelectedName = "";
var select = getSelectEl();
if (select) {
select.innerHTML = "";
select.value = "";
}
closeScriptModal();
}
} else if (msg.type === "scripts_list") {
applyScriptsList(msg);
} else if (msg.type === "unsaved_choice") {
onUnsavedChoice(msg);
} else if (msg.type === "error") {
// A save that times out answers with error, not scripts_list.
if (runPendingAfterSave) {
pendingUnsavedAction = null;
runPendingAfterSave = false;
}
}
}
window.handleScriptsManagerMessage = function(msg) {
if (Array.isArray(msg)) {
for (var i = 0; i < msg.length; i++) {
handleScriptsManagerMessages(msg[i]);
}
} else {
handleScriptsManagerMessages(msg);
}
};
function updateDropdown() {
var select = getSelectEl();
if (!select) return;
var lastVal = currentSelectedName || select.value || "";
if (!lastVal && selectedScriptName) {
lastVal = selectedScriptName;
}
select.innerHTML = "";
for (var s = 0; s < scriptSections.length; s++) {
var section = scriptSections[s];
var scripts = section.scripts || {};
var names = Object.keys(scripts).sort();
if (!names.length) {
continue;
}
var group = document.createElement("optgroup");
group.label = section.title || section.id || t("scripts_fallback", "Scripts");
for (var i = 0; i < names.length; i++) {
var name = names[i];
var opt = document.createElement("option");
opt.value = name;
opt.textContent = name;
opt.dataset.origin = section.id || "user";
group.appendChild(opt);
}
select.appendChild(group);
}
var restored = false;
if (lastVal && scriptIndex[lastVal]) {
select.value = lastVal;
currentOrigin = scriptIndex[lastVal].origin;
restored = true;
}
if (!restored) {
if (selectedScriptName && scriptIndex[selectedScriptName]) {
select.value = selectedScriptName;
currentOrigin = scriptIndex[selectedScriptName].origin;
} else {
var firstOption = select.querySelector("option");
if (firstOption && firstOption.value && scriptIndex[firstOption.value]) {
select.value = firstOption.value;
currentOrigin = scriptIndex[firstOption.value].origin;
} else {
select.value = "";
currentOrigin = "user";
}
}
}
currentSelectedName = select.value;
updateDeleteButtonVisibility();
updateToolbarState();
if (syncDropdownOnly) {
syncDropdownOnly = false;
}
}
function updateDeleteButtonVisibility() {
var deleteBtn = getDeleteBtn();
if (deleteBtn) {
deleteBtn.classList.toggle("toolbar-hidden", false);
}
} // WARNING: If you change dropdown selection logic, also update _ScriptSelectListener in:
// plugin/scripting/python_runner_ui.py
function onDropdownChange() {
var select = getSelectEl();
if (!select) return;
var name = select.value;
if (name === currentSelectedName) {
return;
}
if (askIfDirty({ type: "switch", name: name })) {
select.value = currentSelectedName;
return;
}
switchToSelected();
}
function switchToSelected() {
var select = getSelectEl();
var name = select.value;
currentSelectedName = name;
var selectedOpt = select.options[select.selectedIndex];
if (name && scriptIndex[name]) {
currentOrigin = scriptIndex[name].origin;
} else if (selectedOpt && selectedOpt.dataset && selectedOpt.dataset.origin) {
currentOrigin = selectedOpt.dataset.origin;
} else {
currentOrigin = "user";
}
updateToolbarState();
if (name && scriptIndex[name] !== undefined) {
if (window.editor) {
setEditorValueClean(scriptIndex[name].code);
setStatus(fmt("loaded_script", name), "ok");
}
setDataBindingVisible(currentOrigin === "analysis");
} else {
setDataBindingVisible(false);
}
if (window.pywebview && window.pywebview.api && window.pywebview.api.select_script) {
window.pywebview.api.select_script(name || "");
}
}
// Save As prefills the storage name. The dropdown value for a document or
// helper script is the display key ("[Doc] Regional", "[Vision] Blur").
// Sending that key with origin "user" makes save_user_script reject it as
// a reserved prefix. The native dialog prefills resolve_script_picker_entry's
// real name. User-script keys have no prefix and stay unchanged.
function storageNameForSaveAs(displayName) {
var entry = scriptIndex[displayName];
var origin = entry ? (entry.origin || "") : "";
if (origin === "user" || origin === "") {
return displayName;
}
var marker = "] ";
var at = displayName.indexOf(marker);
if (at > 0 && displayName.charAt(0) === "[") {
return displayName.substring(at + marker.length);
}
return displayName;
}
// Bugfix: scripts_list keys This Document with the [Doc] display name
// (document_script_display_name / DOC_SCRIPT_DISPLAY_PREFIX). New / Save As
// still passes the raw name the user typed. That lookup missed the row, so
// confirm() never ran and save_document_script replaced the existing script.
// A name that is already a display key is left unchanged, so a typed "[Doc] Regional" still matches the row. Save As prefills the storage name via storageNameForSaveAs.
// My Scripts keys stay the raw name.
function documentScriptListKey(name) {
var prefix = "[Doc] ";
return name.indexOf(prefix) === 0 ? name : prefix + name;
}
function originFromName(displayName) {
if (scriptIndex[displayName]) {
return scriptIndex[displayName].origin;
}
return displayName.indexOf("[Doc] ") === 0 ? "document" : "user";
}
function scriptExistsInSection(sectionId, name) {
var lookup = sectionId === "document" ? documentScriptListKey(name) : name;
for (var s = 0; s < scriptSections.length; s++) {
if (scriptSections[s].id === sectionId) {
var scripts = scriptSections[s].scripts || {};
return scripts[lookup] !== undefined;
}
}
return false;
}
var currentModalAction = "new";
function getNewScriptModal() {
return document.getElementById("new-script-modal");
}
function openScriptModal(action) {
currentModalAction = action || "new";
var modal = getNewScriptModal();
if (!modal) return;
var nameInput = document.getElementById("new-script-name-input");
var attachCheck = document.getElementById("new-script-attach-check");
var modalTitle = document.getElementById("new-script-modal-title");
var btnCreate = document.getElementById("btn-new-script-create");
var canWriteDocument = documentAvailable && !documentReadonly && !documentStale;
if (modalTitle) {
modalTitle.textContent = currentModalAction === "save_as"
? t("save_as_title", "Save Script As")
: t("new_script_title", "New Python Script");
}
if (btnCreate) {
btnCreate.textContent = currentModalAction === "save_as"
? t("save_label", "Save")
: t("create_label", "Create");
}
if (nameInput) {
nameInput.value = currentModalAction === "save_as" ? storageNameForSaveAs(currentSelectedName || "") : "";
}
if (attachCheck) {
if (currentModalAction === "save_as") {
attachCheck.checked = (currentOrigin === "document") && canWriteDocument;
} else {
attachCheck.checked = canWriteDocument;
}
attachCheck.disabled = !canWriteDocument;
}
attachCheckboxLabel();
modal.classList.remove("toolbar-hidden");
if (nameInput) {
setTimeout(function() {
nameInput.focus();
if (currentModalAction === "save_as") {
nameInput.select();
}
}, 50);
}
}
function closeScriptModal() {
var modal = getNewScriptModal();
if (modal) {
modal.classList.add("toolbar-hidden");
}
if (window.editor) {
window.editor.focus();
}
}
// WARNING: If you change script creation/save-as modal logic, also update:
// plugin/scripting/python_runner_ui.py (_on_new, _on_save_as)
// and dialog layout in extension/Dialogs/NewScriptDialog.xdl
function onConfirmScriptModal() {
var nameInput = document.getElementById("new-script-name-input");
var name = nameInput ? nameInput.value.trim() : "";
if (!name) {
setStatus(t("script_name_required", "Script name cannot be empty."), "error");
if (nameInput) nameInput.focus();
return;
}
var attachCheck = document.getElementById("new-script-attach-check");
var origin = (attachCheck && attachCheck.checked && documentAvailable && !documentReadonly && !documentStale)
? "document"
: "user";
var overwrite = scriptExistsInSection(origin, name);
if (overwrite) {
var msgKey = origin === "document" ? "attach_overwrite_confirm" : "copy_overwrite_confirm";
if (!confirm(fmt(msgKey, name))) {
return;
}
}
// The list key, not the typed name: a My Scripts entry can have the same typed name.
var key = origin === "document" ? documentScriptListKey(name) : name;
var text = window.editor ? window.editor.getValue() : "";
var code = text;
if (currentModalAction === "new") {
code = NEW_SCRIPT_TEMPLATE;
pendingNew = { key: key, from: currentSelectedName, text: text };
} else {
currentSelectedName = key;
currentOrigin = origin;
pendingSavedCode = code;
}
if (window.pywebview && window.pywebview.api && window.pywebview.api.save_script) {
window.pywebview.api.save_script(name, code, origin);
setStatus(fmt("saving_script", name), "ok");
}
closeScriptModal();
}
// Save *activeScript* through save_script; the scripts_list reply clears dirty.
function saveActiveScript(activeScript) {
if (!activeScript) {
return false;
}
if (window.editor && window.pywebview && window.pywebview.api && window.pywebview.api.save_script) {
var code = window.editor.getValue();
var origin = scriptIndex[activeScript] ? scriptIndex[activeScript].origin : currentOrigin;
pendingSavedCode = code;
var requested = window.waEditorUi && window.waEditorUi.lockForRequestedSave
? window.waEditorUi.lockForRequestedSave()
: false;
window.pywebview.api.save_script(activeScript, code, origin, requested);
setStatus(fmt("saving_script", activeScript), "ok");
return true;
}
return false;
}
// WARNING: If you change Save As logic, also update _on_save_as in:
// plugin/scripting/python_runner_ui.py
function onSaveAs() {
openScriptModal("save_as");
}
// WARNING: If you change Delete logic, also update _on_delete in:
// plugin/scripting/python_runner_ui.py
function onDeleteScript() {
var name = currentSelectedName;
if (!name) {
return;
}
if (confirm(fmt("delete_confirm", name))) {
if (scriptIndex[name] && isBuiltInHelperOrigin(scriptIndex[name].origin)) {
setStatus(t("builtin_cannot_delete", "Built-in helpers cannot be deleted."), "error");
return;
}
if (window.pywebview && window.pywebview.api && window.pywebview.api.delete_script) {
var origin = scriptIndex[name] ? scriptIndex[name].origin : currentOrigin;
deletedScriptName = name;
currentSelectedName = "";
currentOrigin = "user";
window.pywebview.api.delete_script(name, origin);
setStatus(fmt("deleting_script", name), "ok");
}
}
}
function setupInterception() {
if (window.pywebview && window.pywebview.api) {
var originalPoll = window.pywebview.api.poll_messages;
if (originalPoll && !originalPoll.__intercepted) {
window.pywebview.api.poll_messages = function() {
return originalPoll.apply(this, arguments).then(function(messages) {
if (messages && messages.length) {
window.handleScriptsManagerMessage(messages);
}
return messages;
});
};
window.pywebview.api.poll_messages.__intercepted = true;
}
}
}
function ensureInitialRequest() {
if (initialRequested) return;
setupInterception();
if (window.pywebview && window.pywebview.api && window.pywebview.api.request_scripts) {
var btnRun = document.getElementById("btn-run");
var isRunScript = (currentMode === "run_script") || (btnRun && !btnRun.classList.contains("toolbar-hidden"));
if (isRunScript) {
var container = getManagerContainer();
if (container) container.classList.remove("toolbar-hidden");
var btnNew = document.getElementById("btn-new-script");
if (btnNew) btnNew.classList.remove("toolbar-hidden");
window.pywebview.api.request_scripts();
initialRequested = true;
}
}
}
ensureInitialRequest();
var pollInterval = setInterval(function() {
ensureInitialRequest();
if (initialRequested) {
clearInterval(pollInterval);
}
}, 100);
document.addEventListener("DOMContentLoaded", function() {
applyScriptManagerChrome();
var btnNew = document.getElementById("btn-new-script");
if (btnNew) {
btnNew.addEventListener("click", function() {
// Create replaces the buffer with the starter template, so ask before the modal opens.
if (askIfDirty({ type: "new" })) {
return;
}
openScriptModal("new");
});
}
var btnCreate = document.getElementById("btn-new-script-create");
if (btnCreate) {
btnCreate.addEventListener("click", onConfirmScriptModal);
}
var btnCancelModal = document.getElementById("btn-new-script-cancel");
if (btnCancelModal) {
btnCancelModal.addEventListener("click", closeScriptModal);
}
var nameInput = document.getElementById("new-script-name-input");
if (nameInput) {
nameInput.addEventListener("keydown", function(e) {
if (e.key === "Enter") {
e.preventDefault();
onConfirmScriptModal();
} else if (e.key === "Escape") {
e.preventDefault();
closeScriptModal();
}
});
}
var select = getSelectEl();
if (select) {
select.addEventListener("change", onDropdownChange);
}
var btnSaveAs = document.getElementById("btn-save-as");
if (btnSaveAs) {
btnSaveAs.addEventListener("click", onSaveAs);
}
var btnDelete = getDeleteBtn();
if (btnDelete) {
btnDelete.addEventListener("click", onDeleteScript);
}
var btnSave = document.getElementById("btn-save");
if (btnSave) {
btnSave.addEventListener("click", function(event) {
var container = getManagerContainer();
var isRunScriptActive = currentMode === "run_script" && container && !container.classList.contains("toolbar-hidden");
if (!isRunScriptActive) {
return;
}
// After load or Save As, the dropdown still shows the previous script until scripts_list arrives.
// While a delete is in flight currentSelectedName is empty, and the plain Save path would write
// this text over whichever script the host selects next.
var activeScript = currentSelectedName || deletedScriptName;
if (activeScript) {
event.stopImmediatePropagation();
event.preventDefault();
saveActiveScript(activeScript);
}
}, true);
}
});
})();