-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheditor.js
More file actions
1635 lines (1398 loc) · 55.3 KB
/
editor.js
File metadata and controls
1635 lines (1398 loc) · 55.3 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
class ThemeEditor {
constructor() {
this.editor = document.getElementById('editor');
this.editorHighlight = document.getElementById('editor-highlight');
this.lineNumbers = document.getElementById('line-numbers');
this.statusIndicator = document.getElementById('status-indicator');
this.editorContainer = document.getElementById('editor-container');
// Form input elements
this.themeNameInput = document.getElementById('theme-name-input');
this.websiteUrlInput = document.getElementById('website-url-input');
// Action buttons
this.exportBtn = document.getElementById('export-btn');
this.deleteBtn = document.getElementById('delete-btn');
this.isValid = true;
this.validationTimeout = null;
this.isHighlighting = false;
this.autoSaveTimeout = null;
// Theme data
this.currentThemeId = null;
this.theme = null;
this.originalCSS = '';
// Auto-suggestion properties
this.suggestionBox = null;
this.suggestions = [];
this.currentSuggestionIndex = 0;
this.isShowingSuggestions = false;
this.suggestionTimeout = null;
this.init();
}
init() {
this.setupEventListeners();
this.createSuggestionBox();
this.loadThemeFromURL();
this.updateLineNumbers();
this.updateSyntaxHighlighting();
}
createSuggestionBox() {
this.suggestionBox = document.createElement('div');
this.suggestionBox.className = 'suggestion-box';
this.suggestionBox.style.cssText = `
position: absolute;
background: #2d2d30;
border: 1px solid #3e3e42;
border-radius: 6px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
max-height: 200px;
overflow-y: auto;
z-index: 1000;
display: none;
font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
font-size: 13px;
`;
document.body.appendChild(this.suggestionBox);
}
setupEventListeners() {
// Action buttons
this.exportBtn.addEventListener('click', () => {
this.exportTheme();
});
this.deleteBtn.addEventListener('click', () => {
this.deleteTheme();
});
// Form inputs - auto-save on change
this.themeNameInput.addEventListener('input', () => {
this.debounceAutoSave();
});
this.websiteUrlInput.addEventListener('input', () => {
this.debounceAutoSave();
});
// Keyboard shortcuts
this.editor.addEventListener('keydown', (e) => {
// Handle suggestion navigation
if (this.isShowingSuggestions) {
if (e.key === 'ArrowDown') {
e.preventDefault();
this.navigateSuggestions(1);
return;
}
if (e.key === 'ArrowUp') {
e.preventDefault();
this.navigateSuggestions(-1);
return;
}
if (e.key === 'Enter' || e.key === 'Tab') {
e.preventDefault();
this.selectSuggestion();
return;
}
if (e.key === 'Escape') {
e.preventDefault();
this.hideSuggestions();
return;
}
}
// Handle tab key for indentation
if (e.key === 'Tab') {
e.preventDefault();
this.handleTabKey(e.shiftKey);
}
// Handle enter key for proper indentation
if (e.key === 'Enter') {
e.preventDefault();
this.handleEnterKey();
}
// Handle Ctrl+S for save
if (e.key === 's' && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
this.saveTheme();
}
// Handle Ctrl+/ for comment/uncomment
if (e.key === '/' && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
this.handleCommentToggle();
}
});
// Auto-save on content change (debounced) - only if valid
let saveTimeout;
let highlightTimeout;
this.editor.addEventListener('input', () => {
clearTimeout(saveTimeout);
clearTimeout(highlightTimeout);
this.showStatus('Typing...', 'typing');
// Update line numbers immediately
this.updateLineNumbers();
// Debounce syntax highlighting to prevent rapid updates
highlightTimeout = setTimeout(() => {
this.syncHighlightingLayer();
this.updateSyntaxHighlighting();
}, 50);
// Simple validation without interrupting user
this.simpleValidate();
// Handle auto-suggestions
this.handleAutoSuggestions();
saveTimeout = setTimeout(() => {
// Only auto-save if CSS is valid
if (this.isValid) {
this.autoSave();
}
}, 300); // Reduced from 500ms to 300ms for faster auto-save
});
// Handle scroll synchronization
this.editor.addEventListener('scroll', () => {
this.editorHighlight.scrollTop = this.editor.scrollTop;
this.editorHighlight.scrollLeft = this.editor.scrollLeft;
});
// Ensure highlighting layer stays in sync with textarea dimensions
const resizeObserver = new ResizeObserver(() => {
this.syncHighlightingLayer();
});
resizeObserver.observe(this.editor);
// Hide suggestions when clicking outside
document.addEventListener('click', (e) => {
if (this.isShowingSuggestions && !this.suggestionBox.contains(e.target) && e.target !== this.editor) {
this.hideSuggestions();
}
});
}
handleAutoSuggestions() {
if (this.suggestionTimeout) {
clearTimeout(this.suggestionTimeout);
}
this.suggestionTimeout = setTimeout(() => {
const cursorPos = this.editor.selectionStart;
const value = this.editor.value;
const beforeCursor = value.substring(0, cursorPos);
// Check if we're typing a CSS property (after a selector, before a colon)
const propertyMatch = this.getPropertySuggestions(beforeCursor);
if (propertyMatch) {
this.showPropertySuggestions(propertyMatch.suggestions, propertyMatch.prefix, propertyMatch.isVariable);
return;
}
// Check if we're typing a CSS value (after a colon)
const valueMatch = this.getValueSuggestions(beforeCursor);
if (valueMatch) {
this.showValueSuggestions(valueMatch.suggestions, valueMatch.prefix, valueMatch.property);
return;
}
// Hide suggestions if no match
this.hideSuggestions();
}, 100);
}
getPropertySuggestions(beforeCursor) {
// Look for the start of a property (after a closing brace or newline)
const lines = beforeCursor.split('\n');
const currentLine = lines[lines.length - 1];
// Check if we're defining a CSS variable (--variable-name)
const variableMatch = currentLine.match(/^(\s*)(--[a-zA-Z0-9-]*)$/);
if (variableMatch) {
const prefix = variableMatch[2];
const suggestions = this.getCSSVariableNames(prefix);
if (suggestions.length > 0) {
return { suggestions, prefix, isVariable: true };
}
}
// Check if we're in a property context (after a selector, before a colon)
// Only show suggestions if we're inside a CSS rule block (after an opening brace)
const propertyMatch = currentLine.match(/^(\s*)([a-zA-Z-]*)$/);
if (propertyMatch) {
// Check if we're inside a CSS rule block by counting braces
if (this.isInsideCSSRuleBlock(beforeCursor)) {
const prefix = propertyMatch[2];
const suggestions = this.getCSSProperties(prefix);
if (suggestions.length > 0) {
return { suggestions, prefix };
}
}
}
return null;
}
getCSSVariableNames(prefix = '') {
// Common CSS variable naming patterns
const commonVariableNames = [
'--bg-primary', '--bg-secondary', '--bg-tertiary',
'--text-primary', '--text-secondary', '--text-muted',
'--color-primary', '--color-secondary', '--color-accent',
'--border-color', '--border-radius', '--border-width',
'--font-family', '--font-size', '--font-weight',
'--spacing-xs', '--spacing-sm', '--spacing-md', '--spacing-lg', '--spacing-xl',
'--shadow-sm', '--shadow-md', '--shadow-lg',
'--transition-duration', '--transition-timing',
'--z-index-dropdown', '--z-index-modal', '--z-index-tooltip',
'--header-height', '--sidebar-width', '--footer-height',
'--container-max-width', '--grid-gap', '--border-radius-sm', '--border-radius-md', '--border-radius-lg'
];
if (!prefix) return commonVariableNames.slice(0, 15);
return commonVariableNames
.filter(name => name.toLowerCase().includes(prefix.toLowerCase()))
.sort((a, b) => {
const aStarts = a.toLowerCase().startsWith(prefix.toLowerCase());
const bStarts = b.toLowerCase().startsWith(prefix.toLowerCase());
if (aStarts && !bStarts) return -1;
if (!aStarts && bStarts) return 1;
return a.localeCompare(b);
})
.slice(0, 15);
}
getValueSuggestions(beforeCursor) {
// Look for a colon followed by potential value
const lines = beforeCursor.split('\n');
const currentLine = lines[lines.length - 1];
// Check if we're after a colon (property: value)
const valueMatch = currentLine.match(/^(\s*[a-zA-Z-]+:\s*)([a-zA-Z0-9#\-\(\)]*)$/);
if (valueMatch) {
// Check if we're inside a CSS rule block by counting braces
if (this.isInsideCSSRuleBlock(beforeCursor)) {
const property = valueMatch[1].replace(/:\s*$/, '').trim();
const prefix = valueMatch[2];
const suggestions = this.getCSSValues(property, prefix);
if (suggestions.length > 0) {
return { suggestions, prefix, property };
}
}
}
return null;
}
isInsideCSSRuleBlock(text) {
// Count opening and closing braces to determine if we're inside a rule block
let braceCount = 0;
let inComment = false;
let inString = false;
let stringChar = '';
for (let i = 0; i < text.length; i++) {
const char = text[i];
const nextChar = text[i + 1];
// Handle comments
if (char === '/' && nextChar === '*') {
inComment = true;
i++; // Skip next character
continue;
}
if (char === '*' && nextChar === '/' && inComment) {
inComment = false;
i++; // Skip next character
continue;
}
if (inComment) continue;
// Handle single-line comments
if (char === '/' && nextChar === '/') {
// Skip to end of line
const lineEnd = text.indexOf('\n', i);
if (lineEnd === -1) break;
i = lineEnd;
continue;
}
// Handle strings
if ((char === '"' || char === "'") && !inString) {
inString = true;
stringChar = char;
continue;
}
if (char === stringChar && inString) {
inString = false;
stringChar = '';
continue;
}
if (inString) continue;
// Count braces
if (char === '{') {
braceCount++;
} else if (char === '}') {
braceCount--;
}
}
// We're inside a rule block if we have more opening braces than closing braces
return braceCount > 0;
}
getCSSProperties(prefix = '') {
const allProperties = [
'background', 'background-color', 'background-image', 'background-repeat', 'background-position', 'background-size',
'border', 'border-width', 'border-style', 'border-color', 'border-radius', 'border-top', 'border-right', 'border-bottom', 'border-left',
'color', 'font', 'font-family', 'font-size', 'font-weight', 'font-style', 'font-variant', 'line-height',
'margin', 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
'padding', 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
'width', 'height', 'min-width', 'min-height', 'max-width', 'max-height',
'display', 'position', 'top', 'right', 'bottom', 'left', 'z-index',
'float', 'clear', 'overflow', 'overflow-x', 'overflow-y',
'text-align', 'text-decoration', 'text-transform', 'text-indent', 'text-shadow',
'box-shadow', 'opacity', 'visibility', 'cursor', 'outline',
'transition', 'animation', 'transform', 'filter',
'flex', 'flex-direction', 'flex-wrap', 'flex-basis', 'flex-grow', 'flex-shrink',
'grid', 'grid-template', 'grid-template-columns', 'grid-template-rows', 'grid-gap',
'justify-content', 'align-items', 'align-content', 'justify-self', 'align-self',
'object-fit', 'object-position', 'vertical-align', 'white-space', 'word-wrap',
'list-style', 'list-style-type', 'list-style-position', 'list-style-image',
'table-layout', 'border-collapse', 'border-spacing', 'empty-cells',
'content', 'quotes', 'counter-reset', 'counter-increment',
'page-break-before', 'page-break-after', 'page-break-inside',
'orphans', 'widows', 'tab-size', 'hyphens', 'direction',
'unicode-bidi', 'writing-mode', 'text-orientation', 'text-combine-upright'
];
if (!prefix) return allProperties.slice(0, 20); // Show first 20 if no prefix
return allProperties
.filter(prop => prop.toLowerCase().includes(prefix.toLowerCase()))
.sort((a, b) => {
const aStarts = a.toLowerCase().startsWith(prefix.toLowerCase());
const bStarts = b.toLowerCase().startsWith(prefix.toLowerCase());
if (aStarts && !bStarts) return -1;
if (!aStarts && bStarts) return 1;
return a.localeCompare(b);
})
.slice(0, 15); // Limit to 15 suggestions
}
getCSSValues(property, prefix = '') {
const propertyValues = {
'display': ['block', 'inline', 'inline-block', 'flex', 'grid', 'table', 'none', 'contents'],
'position': ['static', 'relative', 'absolute', 'fixed', 'sticky'],
'color': ['transparent', 'currentColor', 'inherit', 'initial', 'unset'],
'background-color': ['transparent', 'currentColor', 'inherit', 'initial', 'unset'],
'border-style': ['solid', 'dashed', 'dotted', 'double', 'groove', 'ridge', 'inset', 'outset', 'none', 'hidden'],
'text-align': ['left', 'right', 'center', 'justify', 'start', 'end'],
'font-weight': ['normal', 'bold', 'bolder', 'lighter', '100', '200', '300', '400', '500', '600', '700', '800', '900'],
'font-style': ['normal', 'italic', 'oblique'],
'text-decoration': ['none', 'underline', 'overline', 'line-through', 'blink'],
'text-transform': ['none', 'capitalize', 'uppercase', 'lowercase', 'full-width'],
'overflow': ['visible', 'hidden', 'scroll', 'auto', 'clip'],
'visibility': ['visible', 'hidden', 'collapse'],
'cursor': ['auto', 'default', 'pointer', 'text', 'move', 'not-allowed', 'help', 'wait', 'crosshair'],
'float': ['left', 'right', 'none'],
'clear': ['left', 'right', 'both', 'none'],
'white-space': ['normal', 'nowrap', 'pre', 'pre-wrap', 'pre-line', 'break-spaces'],
'word-wrap': ['normal', 'break-word', 'break-all', 'keep-all'],
'vertical-align': ['baseline', 'sub', 'super', 'top', 'text-top', 'middle', 'bottom', 'text-bottom'],
'list-style-type': ['disc', 'circle', 'square', 'decimal', 'decimal-leading-zero', 'lower-roman', 'upper-roman', 'lower-alpha', 'upper-alpha', 'none'],
'list-style-position': ['inside', 'outside'],
'border-collapse': ['separate', 'collapse'],
'table-layout': ['auto', 'fixed'],
'empty-cells': ['show', 'hide'],
'direction': ['ltr', 'rtl'],
'unicode-bidi': ['normal', 'embed', 'isolate', 'bidi-override', 'isolate-override', 'plaintext']
};
// Common values for any property
const commonValues = ['inherit', 'initial', 'unset', 'auto', 'none', 'transparent', 'currentColor'];
let values = propertyValues[property] || commonValues;
// Add existing CSS variables if user is typing 'var' or variable names
if (prefix.toLowerCase().includes('var') || prefix.startsWith('--')) {
const existingVariables = this.getExistingCSSVariables();
values = [...existingVariables, ...values];
}
if (prefix) {
values = values.filter(value =>
value.toLowerCase().includes(prefix.toLowerCase())
).sort((a, b) => {
const aStarts = a.toLowerCase().startsWith(prefix.toLowerCase());
const bStarts = b.toLowerCase().startsWith(prefix.toLowerCase());
if (aStarts && !bStarts) return -1;
if (!aStarts && bStarts) return 1;
return a.localeCompare(b);
});
}
return values.slice(0, 15); // Limit to 15 suggestions
}
getExistingCSSVariables() {
const css = this.editor.value;
const variables = [];
// Extract CSS custom properties (variables)
const variableRegex = /--[a-zA-Z0-9-]+/g;
const matches = css.match(variableRegex);
if (matches) {
// Remove duplicates and sort
const uniqueVariables = [...new Set(matches)].sort();
// Format as var(--variable-name) for suggestions
uniqueVariables.forEach(variable => {
variables.push(`var(${variable})`);
});
}
return variables;
}
showPropertySuggestions(suggestions, prefix, isVariable = false) {
this.suggestions = suggestions;
this.currentSuggestionIndex = 0;
this.isShowingSuggestions = true;
this.suggestionBox.innerHTML = '';
suggestions.forEach((suggestion, index) => {
const item = document.createElement('div');
item.className = 'suggestion-item';
item.style.cssText = `
padding: 8px 12px;
cursor: pointer;
color: #f0f0f0;
border-bottom: 1px solid #3e3e42;
transition: background 0.2s ease;
display: flex;
align-items: center;
gap: 8px;
`;
if (index === 0) {
item.style.backgroundColor = '#007acc';
item.style.color = '#ffffff';
}
// Check if this is a variable suggestion
const isVariableSuggestion = suggestion.startsWith('--');
if (isVariableSuggestion) {
// Add variable icon/indicator
const icon = document.createElement('span');
icon.textContent = '🎨';
icon.style.fontSize = '12px';
icon.style.opacity = '0.7';
item.appendChild(icon);
}
const textSpan = document.createElement('span');
textSpan.textContent = suggestion;
if (isVariableSuggestion) {
textSpan.style.color = '#4fc1ff'; // Variable color
}
item.appendChild(textSpan);
item.addEventListener('mouseenter', () => {
this.currentSuggestionIndex = index;
this.updateSuggestionSelection();
});
item.addEventListener('click', () => {
this.selectSuggestion();
});
this.suggestionBox.appendChild(item);
});
this.positionSuggestionBox();
this.suggestionBox.style.display = 'block';
}
showValueSuggestions(suggestions, prefix, property) {
this.suggestions = suggestions;
this.currentSuggestionIndex = 0;
this.isShowingSuggestions = true;
this.suggestionBox.innerHTML = '';
suggestions.forEach((suggestion, index) => {
const item = document.createElement('div');
item.className = 'suggestion-item';
item.style.cssText = `
padding: 8px 12px;
cursor: pointer;
color: #f0f0f0;
border-bottom: 1px solid #3e3e42;
transition: background 0.2s ease;
display: flex;
align-items: center;
gap: 8px;
`;
if (index === 0) {
item.style.backgroundColor = '#007acc';
item.style.color = '#ffffff';
}
// Check if this is a variable suggestion
const isVariable = suggestion.startsWith('var(--');
if (isVariable) {
// Add variable icon/indicator
const icon = document.createElement('span');
icon.textContent = '🔗';
icon.style.fontSize = '12px';
icon.style.opacity = '0.7';
item.appendChild(icon);
}
const textSpan = document.createElement('span');
textSpan.textContent = suggestion;
if (isVariable) {
textSpan.style.color = '#4fc1ff'; // Variable color
}
item.appendChild(textSpan);
item.addEventListener('mouseenter', () => {
this.currentSuggestionIndex = index;
this.updateSuggestionSelection();
});
item.addEventListener('click', () => {
this.selectSuggestion();
});
this.suggestionBox.appendChild(item);
});
this.positionSuggestionBox();
this.suggestionBox.style.display = 'block';
}
positionSuggestionBox() {
const rect = this.editor.getBoundingClientRect();
const cursorPos = this.editor.selectionStart;
const value = this.editor.value;
const beforeCursor = value.substring(0, cursorPos);
const lines = beforeCursor.split('\n');
const currentLineIndex = lines.length - 1;
const currentLineText = lines[currentLineIndex];
// Calculate line height (approximately 19.5px based on CSS)
const lineHeight = 19.5;
// Calculate horizontal position based on current line text
const tempDiv = document.createElement('div');
tempDiv.style.cssText = `
position: absolute;
visibility: hidden;
white-space: pre;
font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
font-size: 13px;
padding: 12px;
`;
tempDiv.textContent = currentLineText;
document.body.appendChild(tempDiv);
const lineWidth = tempDiv.offsetWidth;
document.body.removeChild(tempDiv);
// Position the suggestion box
const top = rect.top + (currentLineIndex + 1) * lineHeight + 12;
let left = rect.left + lineWidth + 12;
// Ensure the suggestion box doesn't go off-screen
const suggestionWidth = 200; // Minimum width
if (left + suggestionWidth > window.innerWidth) {
left = window.innerWidth - suggestionWidth - 10;
}
this.suggestionBox.style.top = `${top}px`;
this.suggestionBox.style.left = `${left}px`;
}
navigateSuggestions(direction) {
if (!this.isShowingSuggestions || this.suggestions.length === 0) return;
this.currentSuggestionIndex = (this.currentSuggestionIndex + direction + this.suggestions.length) % this.suggestions.length;
this.updateSuggestionSelection();
}
updateSuggestionSelection() {
const items = this.suggestionBox.querySelectorAll('.suggestion-item');
items.forEach((item, index) => {
if (index === this.currentSuggestionIndex) {
item.style.backgroundColor = '#007acc';
item.style.color = '#ffffff';
} else {
item.style.backgroundColor = 'transparent';
item.style.color = '#f0f0f0';
}
});
}
selectSuggestion() {
if (!this.isShowingSuggestions || this.suggestions.length === 0) return;
const selectedSuggestion = this.suggestions[this.currentSuggestionIndex];
const cursorPos = this.editor.selectionStart;
const value = this.editor.value;
const beforeCursor = value.substring(0, cursorPos);
const afterCursor = value.substring(cursorPos);
// Find the word being typed and replace it
const lines = beforeCursor.split('\n');
const currentLine = lines[lines.length - 1];
// Check if we're in a property context
const propertyMatch = currentLine.match(/^(\s*)([a-zA-Z-]*)$/);
if (propertyMatch) {
const prefix = propertyMatch[2];
const newLine = currentLine.substring(0, currentLine.length - prefix.length) + selectedSuggestion;
const newValue = lines.slice(0, -1).join('\n') + (lines.length > 1 ? '\n' : '') + newLine + afterCursor;
this.editor.value = newValue;
this.editor.setSelectionRange(cursorPos - prefix.length + selectedSuggestion.length, cursorPos - prefix.length + selectedSuggestion.length);
} else {
// Check if we're in a value context
const valueMatch = currentLine.match(/^(\s*[a-zA-Z-]+:\s*)([a-zA-Z0-9#\-\(\)]*)$/);
if (valueMatch) {
const prefix = valueMatch[2];
const newLine = currentLine.substring(0, currentLine.length - prefix.length) + selectedSuggestion;
const newValue = lines.slice(0, -1).join('\n') + (lines.length > 1 ? '\n' : '') + newLine + afterCursor;
this.editor.value = newValue;
this.editor.setSelectionRange(cursorPos - prefix.length + selectedSuggestion.length, cursorPos - prefix.length + selectedSuggestion.length);
}
}
this.hideSuggestions();
this.updateLineNumbers();
this.updateSyntaxHighlighting();
}
hideSuggestions() {
this.isShowingSuggestions = false;
this.suggestionBox.style.display = 'none';
}
// Cleanup method to remove suggestion box when editor is destroyed
destroy() {
if (this.suggestionBox && this.suggestionBox.parentNode) {
this.suggestionBox.parentNode.removeChild(this.suggestionBox);
}
}
loadThemeFromURL() {
const urlParams = new URLSearchParams(window.location.search);
const themeId = urlParams.get('theme');
if (!themeId) {
this.showError('No theme ID provided');
return;
}
this.currentThemeId = themeId;
this.loadTheme();
}
async loadTheme() {
try {
const data = await this.getStorageData(['themes', 'isEnabled']);
if (!data.themes || !data.themes[this.currentThemeId]) {
this.showError('Theme not found');
return;
}
this.theme = data.themes[this.currentThemeId];
this.originalCSS = this.theme.css;
// Update UI
this.themeNameInput.value = this.theme.name || '';
this.websiteUrlInput.value = this.theme.websiteUrl || '';
// Load CSS into editor
this.editor.value = this.theme.css;
this.updateLineNumbers();
this.updateSyntaxHighlighting();
this.simpleValidate();
} catch (error) {
console.error('Error loading theme:', error);
this.showError('Failed to load theme');
}
}
hasUnsavedChanges() {
return this.editor.value !== this.originalCSS ||
this.themeNameInput.value !== (this.theme.name || '') ||
this.websiteUrlInput.value !== (this.theme.websiteUrl || '');
}
async previewTheme() {
try {
const processedCSS = this.processCSS(this.editor.value);
// Apply CSS to the current tab for preview
this.sendMessageToContentScript({
action: 'applyCSS',
css: processedCSS
}, (response) => {
if (response && response.success) {
this.showStatus('Preview applied', 'saved');
setTimeout(() => this.hideStatus(), 2000);
}
});
} catch (error) {
console.error('Error previewing theme:', error);
this.showStatus('Error applying preview', 'error');
setTimeout(() => this.hideStatus(), 2000);
}
}
async saveTheme() {
try {
this.showStatus('Saving...', 'saving');
// Get current themes
const data = await this.getStorageData('themes');
const themes = data.themes || {};
if (!themes[this.currentThemeId]) {
this.showError('Theme not found');
return;
}
// Update theme with precise timestamp
const now = new Date();
themes[this.currentThemeId].name = this.themeNameInput.value;
themes[this.currentThemeId].websiteUrl = this.websiteUrlInput.value;
themes[this.currentThemeId].css = this.editor.value;
themes[this.currentThemeId].updatedAt = now.toISOString();
// Save to storage
await this.setStorageData({ themes: themes });
// Update original values reference
this.originalCSS = this.editor.value;
this.theme.name = this.themeNameInput.value;
this.theme.websiteUrl = this.websiteUrlInput.value;
this.theme.updatedAt = now.toISOString();
// Apply changes if theme is enabled
const enabledData = await this.getStorageData('isEnabled');
if (enabledData.isEnabled) {
const processedCSS = this.processCSS(this.editor.value);
this.sendMessageToContentScript({
action: 'applyCSS',
css: processedCSS
});
}
this.showStatus('Saved', 'saved');
setTimeout(() => this.hideStatus(), 2000);
} catch (error) {
console.error('Error saving theme:', error);
this.showStatus('Error saving theme', 'error');
setTimeout(() => this.hideStatus(), 2000);
}
}
async deleteTheme() {
if (!confirm(`Are you sure you want to delete "${this.theme.name}"? This action cannot be undone.`)) {
return;
}
try {
this.showStatus('Deleting...', 'saving');
// Get current themes
const data = await this.getStorageData(['themes', 'currentThemeId']);
const themes = data.themes || {};
if (!themes[this.currentThemeId]) {
this.showError('Theme not found');
return;
}
// Don't allow deleting the last theme
if (Object.keys(themes).length <= 1) {
this.showError('Cannot delete the last theme. Please create another theme first.');
return;
}
// Delete the theme
delete themes[this.currentThemeId];
// If we deleted the current theme, switch to another one
if (data.currentThemeId === this.currentThemeId) {
const remainingThemes = Object.keys(themes);
const newCurrentThemeId = remainingThemes[0];
await this.setStorageData({
themes: themes,
currentThemeId: newCurrentThemeId
});
// Apply the new current theme
const newTheme = themes[newCurrentThemeId];
const processedCSS = this.processCSS(newTheme.css);
this.sendMessageToContentScript({
action: 'applyCSS',
css: processedCSS
});
} else {
await this.setStorageData({ themes: themes });
}
this.showStatus('Theme deleted', 'saved');
setTimeout(() => {
this.hideStatus();
window.close();
}, 2000);
} catch (error) {
console.error('Error deleting theme:', error);
this.showStatus('Error deleting theme', 'error');
setTimeout(() => this.hideStatus(), 2000);
}
}
async autoSave() {
try {
// Don't save if CSS is invalid
if (!this.isValid) {
return;
}
this.showStatus('Auto-saving...', 'saving');
// Get current themes
const data = await this.getStorageData('themes');
const themes = data.themes || {};
if (!themes[this.currentThemeId]) {
return;
}
// Update theme with precise timestamp
const now = new Date();
themes[this.currentThemeId].name = this.themeNameInput.value;
themes[this.currentThemeId].websiteUrl = this.websiteUrlInput.value;
themes[this.currentThemeId].css = this.editor.value;
themes[this.currentThemeId].updatedAt = now.toISOString();
// Save to storage
await this.setStorageData({ themes: themes });
// Update original values reference
this.originalCSS = this.editor.value;
this.theme.name = this.themeNameInput.value;
this.theme.websiteUrl = this.websiteUrlInput.value;
this.theme.updatedAt = now.toISOString();
this.showStatus('Auto-saved', 'saved');
setTimeout(() => {
this.hideStatus();
}, 1000);
} catch (error) {
console.error('Error auto-saving:', error);
this.showStatus('Auto-save error', 'error');
setTimeout(() => {
this.hideStatus();
}, 2000);
}
}
showError(message) {
this.showStatus(message, 'error');
setTimeout(() => this.hideStatus(), 3000);
}
// Helper methods (simplified versions)
handleTabKey(shiftKey) {
const start = this.editor.selectionStart;
const end = this.editor.selectionEnd;
const value = this.editor.value;
if (shiftKey) {
const beforeCursor = value.substring(0, start);
const afterCursor = value.substring(end);
const lineStart = beforeCursor.lastIndexOf('\n') + 1;
const lineEnd = afterCursor.indexOf('\n');
const line = value.substring(lineStart, end + (lineEnd === -1 ? value.length : lineEnd));
if (line.startsWith(' ')) {
const newValue = value.substring(0, lineStart) + line.substring(2) + value.substring(end + (lineEnd === -1 ? value.length : lineEnd));
this.editor.value = newValue;
this.editor.setSelectionRange(start - 2, end - 2);
}
} else {
const newValue = value.substring(0, start) + ' ' + value.substring(end);
this.editor.value = newValue;
this.editor.setSelectionRange(start + 2, start + 2);
}
this.updateLineNumbers();
this.updateSyntaxHighlighting();
}
handleEnterKey() {
const cursorPos = this.editor.selectionStart;
const value = this.editor.value;
const beforeCursor = value.substring(0, cursorPos);
const afterCursor = value.substring(cursorPos);
const lineStart = beforeCursor.lastIndexOf('\n') + 1;
const currentLine = value.substring(lineStart, cursorPos);
const match = currentLine.match(/^(\s*)/);
const currentIndent = match ? match[1] : '';
let newIndent = currentIndent;
if (currentLine.trim().endsWith('{')) {
newIndent += ' ';
} else if (afterCursor.trim().startsWith('}')) {
newIndent = newIndent.substring(0, Math.max(0, newIndent.length - 2));
}
const newValue = beforeCursor + '\n' + newIndent + afterCursor;
this.editor.value = newValue;
this.editor.setSelectionRange(cursorPos + 1 + newIndent.length, cursorPos + 1 + newIndent.length);
this.updateLineNumbers();
this.updateSyntaxHighlighting();
}
handleCommentToggle() {
const start = this.editor.selectionStart;
const end = this.editor.selectionEnd;
const value = this.editor.value;
// If there's a selection, handle multiple lines
if (start !== end) {
this.toggleMultiLineComment(start, end, value);
} else {
// Handle single line comment
this.toggleSingleLineComment(start, value);
}
}