-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterop.js
More file actions
1742 lines (1514 loc) · 54.5 KB
/
Copy pathinterop.js
File metadata and controls
1742 lines (1514 loc) · 54.5 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
// --- Globals ---
let monacoEditors = {}; // Object to store editor instances
let pyodide;
let monacoLoaded = false;
let monacoLoadPromise = null;
const isMobileDevice = /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigator.userAgent
);
let onConsoleInputRequested = null;
let pendingConsoleInputResolver = null;
let jediAvailable = false;
let pyodideReady = false;
let isVirtualKeyboardEnabled = false; // Track virtual keyboard state
let webllmModulePromise = null;
let webllmEngine = null;
let webllmLoadedModelId = null;
let webllmProgressListener = null;
const preferredWebLlmModelIds = [
"Llama-3.2-1B-Instruct-q4f32_1-MLC",
"Llama-3.2-3B-Instruct-q4f32_1-MLC",
"Qwen2.5-Coder-1.5B-Instruct-q4f32_1-MLC",
"Qwen2.5-1.5B-Instruct-q4f32_1-MLC",
"Phi-3.5-mini-instruct-q4f32_1-MLC",
"gemma-2-2b-it-q4f32_1-MLC",
];
// Set virtual keyboard state from Flutter
window.setVirtualKeyboardEnabled = function(enabled) {
isVirtualKeyboardEnabled = enabled;
console.log('Virtual keyboard mode:', enabled ? 'enabled' : 'disabled');
// Update all existing editors
Object.values(monacoEditors).forEach(editor => {
updateEditorKeyboardMode(editor, enabled);
});
// Also set up a mutation observer to catch dynamically created textareas
if (enabled && !window._keyboardObserver) {
Object.values(monacoEditors).forEach(editor => {
const domNode = editor.getDomNode();
if (domNode && !domNode._hasKeyboardObserver) {
const observer = new MutationObserver((mutations) => {
if (isVirtualKeyboardEnabled) {
updateEditorKeyboardMode(editor, true);
}
});
observer.observe(domNode, { childList: true, subtree: true });
domNode._hasKeyboardObserver = true;
}
});
}
};
// Update a single editor's keyboard mode
function updateEditorKeyboardMode(editor, virtualKeyboardEnabled) {
const editorDomNode = editor.getDomNode();
if (!editorDomNode) return;
const textAreas = editorDomNode.querySelectorAll('textarea');
textAreas.forEach(textArea => {
if (virtualKeyboardEnabled) {
// Virtual keyboard mode: prevent system keyboard
textArea.setAttribute('readonly', 'readonly');
textArea.setAttribute('inputmode', 'none');
textArea.style.caretColor = 'transparent';
// Also prevent focus from triggering keyboard
textArea.addEventListener('focus', (e) => {
if (isVirtualKeyboardEnabled) {
e.preventDefault();
textArea.blur();
}
}, { capture: true });
} else {
// Real keyboard mode: allow system keyboard
textArea.removeAttribute('readonly');
textArea.removeAttribute('inputmode');
textArea.style.caretColor = '';
}
});
}
function requestConsoleInput(promptText = "") {
return new Promise((resolve, reject) => {
if (pendingConsoleInputResolver) {
reject(new Error("Another input() request is already pending."));
return;
}
pendingConsoleInputResolver = resolve;
if (onConsoleInputRequested) {
onConsoleInputRequested(String(promptText ?? ""));
}
});
}
// Helper function to clean common invalid characters from code
function sanitizeCode(code) {
// Replaces non-breaking spaces and other problematic characters
return code.replace(/\u00A0/g, " ").replace(/\u2028/g, "\n").replace(/\u2029/g, "\n");
}
function normalizeErrorText(err) {
if (err == null) {
return "Unknown Python error";
}
if (typeof err === "string") {
return err;
}
if (typeof err.message === "string" && err.message.trim()) {
return err.message;
}
return String(err);
}
function extractUserRelevantPythonError(err) {
const fullMessage = normalizeErrorText(err).replace(/\r\n/g, "\n").trim();
if (!fullMessage) {
return "Unknown Python error";
}
const execFrameIndex = fullMessage.indexOf('File "<exec>"');
if (execFrameIndex >= 0) {
return fullMessage.slice(execFrameIndex).trim();
}
const tracebackIndex = fullMessage.indexOf("Traceback");
if (tracebackIndex >= 0) {
return fullMessage.slice(tracebackIndex).trim();
}
const lines = fullMessage.split("\n");
const filteredLines = lines.filter((line) => {
return !(
line.includes('File "/lib/python') ||
line.includes("_pyodide") ||
line.includes("_base.py")
);
});
return filteredLines.join("\n").trim() || fullMessage;
}
async function ensureWebLlmModule() {
if (!webllmModulePromise) {
webllmModulePromise = import("https://esm.run/@mlc-ai/web-llm");
}
return webllmModulePromise;
}
function safeJsonCallback(callback, payload) {
if (!callback) {
return;
}
try {
callback(JSON.stringify(payload));
} catch (error) {
console.error("Failed to invoke WebLLM callback:", error);
}
}
function buildWebLlmProgressPayload(report) {
const rawProgress = typeof report?.progress === "number" ? report.progress : null;
const normalizedProgress =
rawProgress == null ? null : rawProgress > 1 ? rawProgress / 100 : rawProgress;
return {
text: report?.text || "Loading model...",
progress:
normalizedProgress != null && normalizedProgress >= 0 && normalizedProgress <= 1
? normalizedProgress
: null,
};
}
function simplifyModelRecord(record) {
const requiredFeatures = Array.isArray(record?.required_features)
? record.required_features
: [];
const vramMb =
typeof record?.vram_required_MB === "number" ? record.vram_required_MB : null;
const modelId = String(record?.model_id || "");
const badges = [];
if (record?.low_resource_required) {
badges.push("low resource");
}
if (vramMb != null) {
badges.push(`${Math.round(vramMb)}MB VRAM`);
}
if (requiredFeatures.length > 0) {
badges.push(requiredFeatures.join(", "));
}
return {
id: modelId,
label: modelId,
description: badges.join(" • "),
};
}
async function getRecommendedWebLlmModels() {
const webllm = await ensureWebLlmModule();
const modelList = Array.isArray(webllm?.prebuiltAppConfig?.model_list)
? webllm.prebuiltAppConfig.model_list
: [];
const instructModels = modelList.filter((record) => {
const modelId = String(record?.model_id || "").toLowerCase();
return (
modelId &&
!modelId.includes("embedding") &&
!modelId.includes("vision") &&
!modelId.includes("audio")
);
});
const preferred = preferredWebLlmModelIds
.map((modelId) =>
instructModels.find((record) => String(record?.model_id || "") === modelId),
)
.filter(Boolean);
const fallback = instructModels
.filter(
(record) =>
!preferred.some(
(preferredRecord) => preferredRecord.model_id === record.model_id,
),
)
.slice(0, 6);
return [...preferred, ...fallback].slice(0, 6).map(simplifyModelRecord);
}
async function ensureWebLlmEngine() {
const webllm = await ensureWebLlmModule();
if (!webllmEngine) {
webllmEngine = new webllm.MLCEngine({
initProgressCallback: (report) => {
safeJsonCallback(
webllmProgressListener,
buildWebLlmProgressPayload(report),
);
},
});
}
return webllmEngine;
}
// --- Helper function to format code using Black in Pyodide ---
async function formatPythonCodeWithBlack(code) {
if (!pyodide) {
console.error("Pyodide not loaded, cannot format.");
throw new Error("Pyodide not loaded");
}
const sanitizedCode = sanitizeCode(code);
try {
// Pass the code to the Python environment
pyodide.globals.set("unformatted_code", sanitizedCode);
// Let Pyodide handle exceptions. If this fails, the promise will reject
// and be caught by the JavaScript 'catch' block.
const formattedCode = await pyodide.runPythonAsync(`
import black
# Get the code from the global scope
source_code = unformatted_code
# Configure black's formatting mode
mode = black.FileMode(line_length=88, string_normalization=True)
# Format the string. This will raise an exception on invalid syntax.
black.format_str(source_code, mode=mode)
`);
return formattedCode;
} catch (err) {
// This will now catch Python exceptions directly!
console.error("Error during Pyodide formatting execution:", err);
throw err; // Re-throw to be caught by the Monaco format provider
}
}
// Function to initialize Monaco only once
function loadMonaco() {
if (!monacoLoadPromise) {
monacoLoadPromise = new Promise((resolve) => {
require.config({
paths: { 'vs': 'https://unpkg.com/monaco-editor@0.41.0/min/vs' }
});
require(['vs/editor/editor.main'], () => {
monacoLoaded = true;
resolve();
});
});
}
return monacoLoadPromise;
}
console.log('Monaco Interop JavaScript loaded');
// Pre-define Python suggestions for faster lookup (defined once globally)
const pythonSuggestions = [
// Keywords
{ label: 'def', kind: 14, insertText: 'def ${1:function_name}(${2:parameters}):\n ${3:pass}', insertTextRules: 4 },
{ label: 'class', kind: 14, insertText: 'class ${1:ClassName}:\n def __init__(self${2:, args}):\n ${3:pass}', insertTextRules: 4 },
{ label: 'if', kind: 14, insertText: 'if ${1:condition}:\n ${2:pass}', insertTextRules: 4 },
{ label: 'elif', kind: 14, insertText: 'elif ${1:condition}:\n ${2:pass}', insertTextRules: 4 },
{ label: 'else', kind: 14, insertText: 'else:\n ${1:pass}', insertTextRules: 4 },
{ label: 'for', kind: 14, insertText: 'for ${1:item} in ${2:iterable}:\n ${3:pass}', insertTextRules: 4 },
{ label: 'while', kind: 14, insertText: 'while ${1:condition}:\n ${2:pass}', insertTextRules: 4 },
{ label: 'try', kind: 14, insertText: 'try:\n ${1:pass}\nexcept ${2:Exception} as ${3:e}:\n ${4:pass}', insertTextRules: 4 },
{ label: 'except', kind: 14, insertText: 'except ${1:Exception} as ${2:e}:\n ${3:pass}', insertTextRules: 4 },
{ label: 'finally', kind: 14, insertText: 'finally:\n ${1:pass}', insertTextRules: 4 },
{ label: 'with', kind: 14, insertText: 'with ${1:expression} as ${2:variable}:\n ${3:pass}', insertTextRules: 4 },
{ label: 'import', kind: 14, insertText: 'import ${1:module}', insertTextRules: 4 },
{ label: 'from', kind: 14, insertText: 'from ${1:module} import ${2:name}', insertTextRules: 4 },
{ label: 'return', kind: 14, insertText: 'return ${1:value}', insertTextRules: 4 },
{ label: 'yield', kind: 14, insertText: 'yield ${1:value}', insertTextRules: 4 },
{ label: 'break', kind: 14, insertText: 'break' },
{ label: 'continue', kind: 14, insertText: 'continue' },
{ label: 'pass', kind: 14, insertText: 'pass' },
{ label: 'lambda', kind: 14, insertText: 'lambda ${1:args}: ${2:expression}', insertTextRules: 4 },
{ label: 'async', kind: 14, insertText: 'async def ${1:function_name}(${2:parameters}):\n ${3:pass}', insertTextRules: 4 },
{ label: 'await', kind: 14, insertText: 'await ${1:expression}', insertTextRules: 4 },
{ label: 'global', kind: 14, insertText: 'global ${1:variable}', insertTextRules: 4 },
{ label: 'nonlocal', kind: 14, insertText: 'nonlocal ${1:variable}', insertTextRules: 4 },
{ label: 'raise', kind: 14, insertText: 'raise ${1:Exception}', insertTextRules: 4 },
{ label: 'assert', kind: 14, insertText: 'assert ${1:condition}', insertTextRules: 4 },
{ label: 'del', kind: 14, insertText: 'del ${1:variable}', insertTextRules: 4 },
// Additional 'p' keywords and decorators
{ label: 'property', kind: 10, insertText: '@property\ndef ${1:name}(self):\n return ${2:value}', insertTextRules: 4 },
{ label: 'partial', kind: 3, insertText: 'partial(${1:func}, ${2:args})', insertTextRules: 4 },
{ label: 'pathlib', kind: 9, insertText: 'from pathlib import Path', insertTextRules: 4 },
// Built-in functions
{ label: 'print', kind: 3, insertText: 'print(${1:value})', insertTextRules: 4 },
{ label: 'len', kind: 3, insertText: 'len(${1:obj})', insertTextRules: 4 },
{ label: 'range', kind: 3, insertText: 'range(${1:stop})', insertTextRules: 4 },
{ label: 'enumerate', kind: 3, insertText: 'enumerate(${1:iterable})', insertTextRules: 4 },
{ label: 'zip', kind: 3, insertText: 'zip(${1:iterable1}, ${2:iterable2})', insertTextRules: 4 },
{ label: 'map', kind: 3, insertText: 'map(${1:function}, ${2:iterable})', insertTextRules: 4 },
{ label: 'filter', kind: 3, insertText: 'filter(${1:function}, ${2:iterable})', insertTextRules: 4 },
{ label: 'sorted', kind: 3, insertText: 'sorted(${1:iterable})', insertTextRules: 4 },
{ label: 'sum', kind: 3, insertText: 'sum(${1:iterable})', insertTextRules: 4 },
{ label: 'max', kind: 3, insertText: 'max(${1:iterable})', insertTextRules: 4 },
{ label: 'min', kind: 3, insertText: 'min(${1:iterable})', insertTextRules: 4 },
{ label: 'abs', kind: 3, insertText: 'abs(${1:number})', insertTextRules: 4 },
{ label: 'round', kind: 3, insertText: 'round(${1:number})', insertTextRules: 4 },
{ label: 'input', kind: 3, insertText: 'input(${1:prompt})', insertTextRules: 4 },
{ label: 'open', kind: 3, insertText: 'open(${1:filename}, ${2:mode})', insertTextRules: 4 },
{ label: 'type', kind: 3, insertText: 'type(${1:obj})', insertTextRules: 4 },
{ label: 'isinstance', kind: 3, insertText: 'isinstance(${1:obj}, ${2:type})', insertTextRules: 4 },
{ label: 'hasattr', kind: 3, insertText: 'hasattr(${1:obj}, ${2:attr})', insertTextRules: 4 },
{ label: 'getattr', kind: 3, insertText: 'getattr(${1:obj}, ${2:attr})', insertTextRules: 4 },
{ label: 'setattr', kind: 3, insertText: 'setattr(${1:obj}, ${2:attr}, ${3:value})', insertTextRules: 4 },
{ label: 'pow', kind: 3, insertText: 'pow(${1:base}, ${2:exp})', insertTextRules: 4 },
// Built-in types
{ label: 'str', kind: 7, insertText: 'str(${1:obj})', insertTextRules: 4 },
{ label: 'int', kind: 7, insertText: 'int(${1:obj})', insertTextRules: 4 },
{ label: 'float', kind: 7, insertText: 'float(${1:obj})', insertTextRules: 4 },
{ label: 'bool', kind: 7, insertText: 'bool(${1:obj})', insertTextRules: 4 },
{ label: 'list', kind: 7, insertText: 'list(${1:iterable})', insertTextRules: 4 },
{ label: 'tuple', kind: 7, insertText: 'tuple(${1:iterable})', insertTextRules: 4 },
{ label: 'dict', kind: 7, insertText: 'dict(${1:mapping})', insertTextRules: 4 },
{ label: 'set', kind: 7, insertText: 'set(${1:iterable})', insertTextRules: 4 },
// Constants
{ label: 'True', kind: 21, insertText: 'True' },
{ label: 'False', kind: 21, insertText: 'False' },
{ label: 'None', kind: 21, insertText: 'None' },
// Magic methods
{ label: '__init__', kind: 2, insertText: 'def __init__(self${1:, args}):\n ${2:pass}', insertTextRules: 4 },
{ label: '__str__', kind: 2, insertText: 'def __str__(self):\n return ${1:"string representation"}', insertTextRules: 4 },
{ label: '__repr__', kind: 2, insertText: 'def __repr__(self):\n return ${1:"repr string"}', insertTextRules: 4 },
{ label: '__len__', kind: 2, insertText: 'def __len__(self):\n return ${1:length}', insertTextRules: 4 }
];
function mapCompletionKind(type) {
if (!window.monaco) {
return 9;
}
switch (type) {
case 'function':
return monaco.languages.CompletionItemKind.Function;
case 'class':
return monaco.languages.CompletionItemKind.Class;
case 'module':
return monaco.languages.CompletionItemKind.Module;
case 'instance':
return monaco.languages.CompletionItemKind.Variable;
case 'param':
return monaco.languages.CompletionItemKind.Variable;
case 'path':
return monaco.languages.CompletionItemKind.File;
case 'keyword':
return monaco.languages.CompletionItemKind.Keyword;
case 'statement':
return monaco.languages.CompletionItemKind.Keyword;
case 'property':
return monaco.languages.CompletionItemKind.Property;
default:
return monaco.languages.CompletionItemKind.Text;
}
}
function fallbackSuggestions(partialWord, range) {
return pythonSuggestions
.filter((suggestion) => !partialWord || suggestion.label.toLowerCase().startsWith(partialWord))
.map((suggestion) => ({ ...suggestion, range }));
}
async function ensureJediLoaded() {
if (!pyodide || jediAvailable) {
return jediAvailable;
}
try {
await pyodide.runPythonAsync('import jedi');
jediAvailable = true;
return true;
} catch (error) {
console.error('Jedi import failed:', error);
return false;
}
}
async function fetchJediCompletions(code, lineNumber, column) {
if (!pyodideReady) {
return [];
}
const hasJedi = await ensureJediLoaded();
if (!hasJedi) {
return [];
}
pyodide.globals.set("__completion_source__", String(code ?? ""));
const rawResult = await pyodide.runPythonAsync(`
import json
import jedi
script = jedi.Script(__completion_source__)
completions = script.complete(${lineNumber}, ${column})
json.dumps([
{
"name": completion.name,
"type": completion.type,
"description": (completion.docstring() or "")[:180],
}
for completion in completions[:30]
])
`);
return JSON.parse(rawResult);
}
async function fetchJediDefinitions(code) {
if (!pyodideReady) {
return [];
}
const hasJedi = await ensureJediLoaded();
if (!hasJedi) {
return [];
}
pyodide.globals.set("__analysis_source__", String(code ?? ""));
const rawResult = await pyodide.runPythonAsync(`
import json
import jedi
script = jedi.Script(__analysis_source__)
names = script.get_names(all_scopes=True, definitions=True)
json.dumps([
{
"name": name.name,
"type": name.type,
"line": name.line or 0,
"column": name.column or 0,
"description": (name.docstring() or "")[:120],
}
for name in names[:50]
])
`);
return JSON.parse(rawResult);
}
// Global flag to ensure completion provider is registered only once
let pythonCompletionProviderRegistered = false;
// Register Python completion provider globally (only once)
function registerPythonCompletionProvider() {
if (pythonCompletionProviderRegistered || !window.monaco) {
return;
}
monaco.languages.registerCompletionItemProvider('python', {
provideCompletionItems: async function(model, position) {
const word = model.getWordUntilPosition(position);
const range = {
startLineNumber: position.lineNumber,
endLineNumber: position.lineNumber,
startColumn: word.startColumn,
endColumn: word.endColumn
};
const partialWord = word.word.toLowerCase();
try {
const jediCompletions = await fetchJediCompletions(
model.getValue(),
position.lineNumber,
Math.max(0, position.column - 1)
);
if (jediCompletions.length > 0) {
return {
suggestions: jediCompletions.map((completion) => ({
label: completion.name,
kind: mapCompletionKind(completion.type),
insertText: completion.name,
detail: completion.type,
documentation: completion.description || '',
range
}))
};
}
} catch (error) {
console.error('Jedi completion error:', error);
}
return { suggestions: fallbackSuggestions(partialWord, range) };
}
});
pythonCompletionProviderRegistered = true;
console.log('Python completion provider registered');
}
// --- Monaco Interop ---
window.monacoInterop = {
init: async (containerId, initialCode, theme, fontSize, onContentChanged) => {
console.log('Monaco init called for:', containerId);
try {
// Check if DOM element exists
const container = document.getElementById(containerId);
if (!container) {
throw new Error(`DOM element with ID '${containerId}' not found`);
}
console.log('DOM element found for:', containerId);
// Ensure Monaco is loaded first
if (!monacoLoaded) {
await loadMonaco();
}
const editor = monaco.editor.create(container, {
value: initialCode,
language: 'python',
theme: theme,
fontSize: fontSize,
automaticLayout: true,
formatOnPaste: true,
formatOnType: false,
wordWrap: 'on',
minimap: { enabled: false },
scrollBeyondLastLine: false,
renderLineHighlight: 'line',
selectOnLineNumbers: true,
// Enhanced autocomplete settings for instant response
quickSuggestions: true, // Enable for all contexts
quickSuggestionsDelay: 0, // Instant suggestions
suggestOnTriggerCharacters: true,
acceptSuggestionOnCommitCharacter: false,
acceptSuggestionOnEnter: 'on',
wordBasedSuggestions: false, // Disable default word-based suggestions to prevent duplicates
tabCompletion: 'on',
parameterHints: {
enabled: true,
cycle: true
},
suggest: {
showKeywords: true,
showSnippets: true,
showFunctions: true,
showConstructors: true,
showFields: true,
showVariables: true,
showClasses: true,
showStructs: true,
showInterfaces: true,
showModules: true,
showProperties: true,
showEvents: true,
showOperators: true,
showUnits: true,
showValues: true,
showConstants: true,
showEnums: true,
showEnumMembers: true,
showWords: false, // Disable word suggestions to avoid duplicates
showColors: true,
showFiles: true,
showReferences: true,
showFolders: true,
showTypeParameters: true,
filterGraceful: true,
snippetsPreventQuickSuggestions: false,
insertMode: 'insert',
localityBonus: true,
delay: 0, // No delay for suggestions
maxVisibleSuggestions: 12 // Show more suggestions
},
// Disable system keyboard on mobile
readOnly: false,
contextmenu: false,
// Prevent virtual keyboard on mobile
'semanticHighlighting.enabled': false
});
// Store the editor instance
monacoEditors[containerId] = editor;
// Register the Python completion provider globally (only once)
registerPythonCompletionProvider();
const notifyFlutterEditorFocus = () => {
window.dispatchEvent(new CustomEvent('monaco-editor-focused', {
detail: { editorId: containerId }
}));
};
editor.onDidFocusEditorText(notifyFlutterEditorFocus);
editor.onMouseDown(notifyFlutterEditorFocus);
// Prevent system keyboard and handle touch-to-set-cursor on mobile devices
const editorDomNode = editor.getDomNode();
if (editorDomNode) {
editorDomNode.addEventListener('pointerdown', notifyFlutterEditorFocus, true);
}
if (editorDomNode && isMobileDevice) {
// Touch-to-set-cursor handler: sets cursor position at touch coordinates
const handleTouchToSetCursor = (e) => {
const touch = e.touches[0] || e.changedTouches[0];
if (touch) {
const target = editor.getTargetAtClientPoint(touch.clientX, touch.clientY);
if (target && target.position) {
editor.setPosition(target.position);
// Don't call editor.focus() when virtual keyboard is enabled - it triggers system keyboard
if (!isVirtualKeyboardEnabled) {
editor.focus();
}
}
}
};
// Add touch listeners that respect virtual keyboard setting
editorDomNode.addEventListener('touchstart', (e) => {
if (isVirtualKeyboardEnabled) {
// Virtual keyboard mode: prevent system keyboard
e.preventDefault();
e.stopPropagation();
handleTouchToSetCursor(e);
}
// Real keyboard mode: let default behavior happen (system keyboard shows)
}, { passive: false });
editorDomNode.addEventListener('touchend', (e) => {
if (isVirtualKeyboardEnabled) {
// Virtual keyboard mode: prevent system keyboard
e.preventDefault();
e.stopPropagation();
}
// Real keyboard mode: let default behavior happen
}, { passive: false });
// Set initial keyboard mode
updateEditorKeyboardMode(editor, isVirtualKeyboardEnabled);
}
// Set up content change listener
editor.onDidChangeModelContent((e) => {
onContentChanged(editor.getValue());
// Manually trigger suggestions on content change for better responsiveness
const position = editor.getPosition();
if (position) {
const model = editor.getModel();
const word = model.getWordUntilPosition(position);
// Trigger suggestions if user is typing a word (not deleting or just whitespace)
if (word.word.length > 0 && e.changes.some(change => /\S/.test(change.text))) {
setTimeout(() => {
editor.trigger('keyboard', 'editor.action.triggerSuggest', {});
}, 10);
}
}
});
return editor;
} catch (error) {
console.error('Error creating Monaco editor:', error);
throw error;
}
},
getValue: (containerId) => {
const editor = monacoEditors[containerId];
return editor ? editor.getValue() : '';
},
setValue: (containerId, content) => {
const editor = monacoEditors[containerId];
if (editor) {
editor.setValue(content);
}
},
updateOptions: (containerId, theme, fontSize) => {
const editor = monacoEditors[containerId];
if (editor) {
editor.updateOptions({ theme, fontSize });
}
},
formatDocument: (containerId) => {
const editor = monacoEditors[containerId];
if (editor) {
try {
// For Python, implement proper indentation that fixes bad indentation
const model = editor.getModel();
const value = model.getValue();
// Split into lines and fix indentation
const lines = value.split('\n');
const formattedLines = [];
let currentIndentLevel = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const trimmedLine = line.trim();
// Skip empty lines - preserve them as is
if (trimmedLine === '') {
formattedLines.push('');
continue;
}
// Check if this line should decrease indentation
if (trimmedLine.match(/^(except|elif|else|finally):/)) {
currentIndentLevel = Math.max(0, currentIndentLevel - 1);
}
// Determine if this should be at top level (unindented)
// Top level: function definitions, class definitions, imports, top-level statements that don't follow a colon
let shouldBeTopLevel = false;
if (i === 0) {
// First line is always top level
shouldBeTopLevel = true;
} else {
// Check if this looks like a top-level statement
if (trimmedLine.match(/^(def |class |import |from |if __name__|#|@)/)) {
shouldBeTopLevel = true;
currentIndentLevel = 0;
} else {
// Look back to see if we're following a function/class definition or other top-level code
let foundTopLevelContext = false;
for (let j = i - 1; j >= 0; j--) {
const prevLine = lines[j].trim();
if (prevLine === '') continue; // Skip empty lines
// If previous line was a function/class definition, we should be indented
if (prevLine.match(/^(def |class |if |for |while |try:|with |except|elif|else:)/)) {
foundTopLevelContext = false;
break;
}
// If previous line was clearly top-level, and this line doesn't look like it should be indented
if (prevLine.match(/^(import |from |#|@)/) ||
(!prevLine.endsWith(':') && !prevLine.match(/^(def |class |if |for |while |try:|with )/))) {
// Check if current line looks like it should be top-level
if (trimmedLine.match(/^(print|[a-zA-Z_][a-zA-Z0-9_]*\s*=|[a-zA-Z_][a-zA-Z0-9_]*\()/)) {
foundTopLevelContext = true;
}
break;
}
break;
}
if (foundTopLevelContext) {
shouldBeTopLevel = true;
currentIndentLevel = 0;
}
}
}
// Apply indentation
if (shouldBeTopLevel) {
formattedLines.push(trimmedLine);
currentIndentLevel = 0;
} else {
// Use current indent level
formattedLines.push(' '.repeat(currentIndentLevel) + trimmedLine);
}
// Increase indent for lines ending with ':' (but not comments)
if (trimmedLine.endsWith(':') && !trimmedLine.trimStart().startsWith('#')) {
currentIndentLevel++;
}
}
// Set the formatted code back to the editor
model.setValue(formattedLines.join('\n'));
} catch (error) {
console.log('Python formatting failed, using Monaco default:', error);
// Fallback to Monaco's built-in formatter
try {
editor.getAction('editor.action.formatDocument').run();
} catch (fallbackError) {
console.log('Monaco formatter also failed:', fallbackError);
}
}
}
},
selectAll: (containerId) => {
const editor = monacoEditors[containerId];
if (editor) {
editor.setSelection(editor.getModel().getFullModelRange());
}
},
insertText: (containerId, text) => {
const editor = monacoEditors[containerId];
if (editor) {
const model = editor.getModel();
const selection = editor.getSelection();
if (!model || !selection) {
return;
}
const normalizedText = String(text ?? "").replace(/\r\n/g, "\n");
const startOffset = model.getOffsetAt(selection.getStartPosition());
const endPosition = model.getPositionAt(startOffset + normalizedText.length);
editor.executeEdits('paste-code', [
{
range: selection,
text: normalizedText,
forceMoveMarkers: true,
},
]);
if (endPosition) {
editor.setSelection(
new monaco.Selection(
endPosition.lineNumber,
endPosition.column,
endPosition.lineNumber,
endPosition.column
)
);
}
editor.focus();
}
},
copySelection: (containerId) => {
const editor = monacoEditors[containerId];
if (editor) {
const selection = editor.getSelection();
const text = editor.getModel().getValueInRange(selection);
navigator.clipboard.writeText(text);
}
},
getSelectedText: (containerId) => {
const editor = monacoEditors[containerId];
if (!editor) {
return '';
}
const selection = editor.getSelection();
if (!selection || selection.isEmpty()) {
return '';
}
return editor.getModel().getValueInRange(selection);
},
setAutocomplete: (containerId, enabled) => {
const editor = monacoEditors[containerId];
if (editor) {
editor.updateOptions({
quickSuggestions: enabled ? {
other: true,
comments: false,
strings: false
} : false,
quickSuggestionsDelay: 0, // Instant suggestions
suggestOnTriggerCharacters: enabled,
acceptSuggestionOnCommitCharacter: false,
acceptSuggestionOnEnter: enabled ? 'on' : 'off',
wordBasedSuggestions: enabled,
parameterHints: {
enabled: enabled,
cycle: enabled
},
suggest: {
showKeywords: enabled,
showSnippets: enabled,
showFunctions: enabled,
showConstructors: enabled,
showFields: enabled,
showVariables: enabled,
showClasses: enabled,
showStructs: enabled,
showInterfaces: enabled,
showModules: enabled,
showProperties: enabled,
showEvents: enabled,
showOperators: enabled,
showUnits: enabled,
showValues: enabled,
showConstants: enabled,
showEnums: enabled,
showEnumMembers: enabled,
showWords: enabled,
showColors: enabled,
showFiles: enabled,
showReferences: enabled,
showFolders: enabled,
showTypeParameters: enabled,
filterGraceful: enabled,
snippetsPreventQuickSuggestions: false,
insertMode: 'insert',
localityBonus: enabled,
delay: 0, // No delay for suggestions
maxVisibleSuggestions: 12 // Show more suggestions
}
});
// Trigger suggestions to show immediately when enabling
if (enabled) {
editor.trigger('keyboard', 'editor.action.triggerSuggest', {});
}
}
},
// Manual trigger for autocomplete suggestions
triggerAutocomplete: (containerId) => {
const editor = monacoEditors[containerId];
if (editor) {
editor.trigger('keyboard', 'editor.action.triggerSuggest', {});
}
},
// Scroll to specific line and column, and position cursor there
scrollToLineColumn: (containerId, line, column) => {
const editor = monacoEditors[containerId];
if (editor) {
const position = {
lineNumber: Math.max(1, line),
column: Math.max(1, column)
};
editor.setPosition(position);
editor.revealPositionInCenter(position);
editor.focus();
}
}
};
window.destroyMonacoEditor = function(elementId) {
if(monacoEditors && monacoEditors[elementId]) {