Repository navigation
Expand file tree
/
Copy pathvisual-editor.js
More file actions
581 lines (506 loc) · 23.8 KB
/
Copy pathvisual-editor.js
File metadata and controls
581 lines (506 loc) · 23.8 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
// editor.js
// unique namespace on window
window.__myEditor = window.__myEditor || {};
window.__myEditor.editMode = false;
window.__myEditor.selectedEl = null; // Hover element
window.__myEditor.permanentlySelectedEl = null; // Clicked/selected element
window.__myEditor.overlay = null; // Hover overlay (red)
window.__myEditor.selectedOverlay = null; // Selected element overlay (purple)
window.__myEditor.mousemoveHandler = null;
window.__myEditor.clickHandler = null;
window.__myEditor.globalClickInterceptor = null; // Intercepts all clicks to prevent navigation
window.__myEditor.formSubmitInterceptor = null; // Prevents form submissions
window.__myEditor.scrollHandler = null;
window.__myEditor.resizeHandler = null;
window.__myEditor.currentTheme = 'system'; // Current theme preference
window.__myEditor.systemThemeListener = null; // Listener for system theme changes
window.__myEditor.currentThemeVars = null; // Current theme variables (all modes)
window.__myEditor.currentThemeMode = null; // Current theme mode (light/dark)
window.__myEditor.currentThemeId = null; // Current theme ID
window.__myEditor.appliedThemeVarNames = []; // List of CSS variable names we've applied
window.__myEditor.startEditMode = function() {
if (window.__myEditor.editMode) return;
window.__myEditor.editMode = true;
// Hover overlay (red) - for previewing elements on hover
const overlay = document.createElement('div');
overlay.style.position = 'absolute';
overlay.style.pointerEvents = 'none';
overlay.style.border = '2px solid #ff0000';
overlay.style.background = 'rgba(255,0,0,0.1)';
overlay.style.display = 'none';
overlay.style.zIndex = 9999;
document.body.appendChild(overlay);
// Selected element overlay (purple) - for permanently selected element
const selectedOverlay = document.createElement('div');
selectedOverlay.style.position = 'absolute';
selectedOverlay.style.pointerEvents = 'none';
selectedOverlay.style.border = '2px solid #8b5cf6';
selectedOverlay.style.background = 'rgba(139,92,246,0.1)';
selectedOverlay.style.display = 'none';
selectedOverlay.style.zIndex = 10000; // Higher than hover overlay
document.body.appendChild(selectedOverlay);
window.__myEditor.overlay = overlay;
window.__myEditor.selectedOverlay = selectedOverlay;
// Make updateOverlay accessible globally (for hover preview - red)
window.__myEditor.updateOverlay = function(el, overlayEl) {
if (!el || !overlayEl) return;
const rect = el.getBoundingClientRect();
overlayEl.style.top = `${rect.top + window.scrollY}px`;
overlayEl.style.left = `${rect.left + window.scrollX}px`;
overlayEl.style.width = `${rect.width}px`;
overlayEl.style.height = `${rect.height}px`;
overlayEl.style.display = 'block';
};
// Update selected element overlay (purple)
window.__myEditor.updateSelectedOverlay = function() {
if (window.__myEditor.permanentlySelectedEl && selectedOverlay) {
window.__myEditor.updateOverlay(window.__myEditor.permanentlySelectedEl, selectedOverlay);
} else if (selectedOverlay) {
selectedOverlay.style.display = 'none';
}
};
// Update hover overlay (red)
window.__myEditor.updateHoverOverlay = function() {
// Only show hover overlay if hovering over a different element than the selected one
if (window.__myEditor.selectedEl &&
window.__myEditor.selectedEl !== window.__myEditor.permanentlySelectedEl &&
overlay) {
window.__myEditor.updateOverlay(window.__myEditor.selectedEl, overlay);
} else if (overlay) {
overlay.style.display = 'none';
}
};
// Store handlers so they can be removed later
window.__myEditor.mousemoveHandler = (e) => {
if (!window.__myEditor.editMode) return;
const el = e.target.closest('[data-id]');
// Always update hover preview (red) when moving over elements
if (el && el !== window.__myEditor.selectedEl) {
window.__myEditor.selectedEl = el;
// Show hover preview if it's not the permanently selected element
if (el !== window.__myEditor.permanentlySelectedEl) {
window.__myEditor.updateHoverOverlay();
} else {
// Hide hover overlay if hovering over selected element
if (overlay) overlay.style.display = 'none';
}
} else if (!el) {
window.__myEditor.selectedEl = null;
// Hide hover overlay when not over any element
if (overlay) overlay.style.display = 'none';
}
};
// Global click interceptor - blocks all clicks except selection on [data-id] elements
window.__myEditor.globalClickInterceptor = (e) => {
if (!window.__myEditor.editMode) return;
// Always prevent default to stop navigation, form submission, etc.
e.preventDefault();
// Check if clicking on or inside a [data-id] element
const dataIdEl = e.target.closest('[data-id]');
if (dataIdEl) {
// Inside [data-id] - stop immediate propagation to block other handlers
// but manually trigger selection
e.stopImmediatePropagation();
// Manually trigger selection since we stopped propagation
window.__myEditor.permanentlySelectedEl = dataIdEl;
window.__myEditor.selectedEl = dataIdEl;
window.__myEditor.updateSelectedOverlay();
if (window.__myEditor.overlay) window.__myEditor.overlay.style.display = 'none';
// Get original style and computed colors from the element
const originalStyle = dataIdEl.getAttribute('style') || dataIdEl.style.cssText || "";
let extractedTextColor = "";
let extractedBgColor = "";
try {
const computedStyle = window.getComputedStyle(dataIdEl);
if (computedStyle) {
const color = computedStyle.color;
const bgColor = computedStyle.backgroundColor;
if (color && color !== 'rgba(0, 0, 0, 0)' && color !== 'rgb(0, 0, 0)') {
extractedTextColor = window.__myEditor.rgbToHex(color);
}
if (bgColor && bgColor !== 'rgba(0, 0, 0, 0)' && bgColor !== 'transparent' && bgColor !== 'rgba(0, 0, 0, 0)') {
extractedBgColor = window.__myEditor.rgbToHex(bgColor);
}
}
} catch (e) {
if (originalStyle) {
const colorMatch = originalStyle.match(/color:\s*([^;]+)/);
const bgMatch = originalStyle.match(/background-color:\s*([^;]+)/);
if (colorMatch) extractedTextColor = colorMatch[1].trim();
if (bgMatch) extractedBgColor = bgMatch[1].trim();
}
}
// Check if element has nested elements (not just text nodes)
// Check for any element nodes (nodeType === 1) as children
const hasNestedElements = Array.from(dataIdEl.childNodes).some(node => node.nodeType === 1);
// Check if there are text nodes (nodeType === 3) - allows editing text in buttons with icons
const hasTextNodes = Array.from(dataIdEl.childNodes).some(node => node.nodeType === 3 && node.textContent.trim());
// Build message
const message = {
type: 'element-selected',
file: dataIdEl.getAttribute('data-file'),
line: dataIdEl.getAttribute('data-line'),
id: dataIdEl.getAttribute('data-id'),
class: dataIdEl.getAttribute('class'),
tag: dataIdEl.tagName,
hasNestedElements: hasNestedElements,
originalStyle: originalStyle,
originalTextColor: extractedTextColor,
originalBgColor: extractedBgColor
};
// Include innerHTML/textContent if:
// 1. No nested elements (simple text-only content) - send both
// 2. Has nested elements BUT also has text nodes (e.g., button with icon + text) - send textContent only
if (!hasNestedElements) {
// Simple element - send both innerHTML and textContent
message.innerHTML = dataIdEl.innerHTML;
message.textContent = dataIdEl.textContent;
} else if (hasTextNodes) {
// Mixed content (elements + text) - send textContent so user can edit the text part
message.textContent = dataIdEl.textContent;
}
// If only nested elements with no text nodes, don't send anything (editing disabled)
window.parent.postMessage(message, '*');
return false;
}
// Not inside [data-id] - block everything completely
e.stopPropagation();
e.stopImmediatePropagation();
return false;
};
// Prevent form submissions
window.__myEditor.formSubmitInterceptor = (e) => {
if (!window.__myEditor.editMode) return;
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
return false;
};
// Helper to convert rgb/rgba to hex
window.__myEditor.rgbToHex = function(rgb) {
if (!rgb || rgb === 'transparent') return "";
if (rgb.startsWith('#')) return rgb;
const match = rgb.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*[\d.]+)?\)/);
if (match) {
const r = parseInt(match[1]).toString(16).padStart(2, '0');
const g = parseInt(match[2]).toString(16).padStart(2, '0');
const b = parseInt(match[3]).toString(16).padStart(2, '0');
return `#${r}${g}${b}`;
}
return "";
};
window.__myEditor.clickHandler = (e) => {
if (!window.__myEditor.editMode) return;
const el = e.target.closest('[data-id]');
if (el) {
// Set as permanently selected element
window.__myEditor.permanentlySelectedEl = el;
window.__myEditor.selectedEl = el;
// Update selected overlay (purple) for the clicked element
window.__myEditor.updateSelectedOverlay();
// Hide hover overlay since we're now on the selected element
if (overlay) overlay.style.display = 'none';
// Get original style and computed colors from the element
const originalStyle = el.getAttribute('style') || el.style.cssText || "";
let extractedTextColor = "";
let extractedBgColor = "";
try {
const computedStyle = window.getComputedStyle(el);
if (computedStyle) {
const color = computedStyle.color;
const bgColor = computedStyle.backgroundColor;
// Convert rgb to hex if needed
if (color && color !== 'rgba(0, 0, 0, 0)' && color !== 'rgb(0, 0, 0)') {
extractedTextColor = window.__myEditor.rgbToHex(color);
}
if (bgColor && bgColor !== 'rgba(0, 0, 0, 0)' && bgColor !== 'transparent' && bgColor !== 'rgba(0, 0, 0, 0)') {
extractedBgColor = window.__myEditor.rgbToHex(bgColor);
}
}
} catch (e) {
// If we can't get computed style, try to parse inline style
if (originalStyle) {
const colorMatch = originalStyle.match(/color:\s*([^;]+)/);
const bgMatch = originalStyle.match(/background-color:\s*([^;]+)/);
if (colorMatch) extractedTextColor = colorMatch[1].trim();
if (bgMatch) extractedBgColor = bgMatch[1].trim();
}
}
// Check if element has nested elements (not just text nodes)
// Check for any element nodes (nodeType === 1) as children
const hasNestedElements = Array.from(el.childNodes).some(node => node.nodeType === 1);
// Check if there are text nodes (nodeType === 3) - allows editing text in buttons with icons
const hasTextNodes = Array.from(el.childNodes).some(node => node.nodeType === 3 && node.textContent.trim());
// Build message
const message = {
type: 'element-selected',
file: el.getAttribute('data-file'),
line: el.getAttribute('data-line'),
id: el.getAttribute('data-id'),
class: el.getAttribute('class'),
tag: el.tagName,
hasNestedElements: hasNestedElements,
originalStyle: originalStyle,
originalTextColor: extractedTextColor,
originalBgColor: extractedBgColor
};
// Include innerHTML/textContent if:
// 1. No nested elements (simple text-only content) - send both
// 2. Has nested elements BUT also has text nodes (e.g., button with icon + text) - send textContent only
if (!hasNestedElements) {
// Simple element - send both innerHTML and textContent
message.innerHTML = el.innerHTML;
message.textContent = el.textContent;
} else if (hasTextNodes) {
// Mixed content (elements + text) - send textContent so user can edit the text part
message.textContent = el.textContent;
}
// If only nested elements with no text nodes, don't send anything (editing disabled)
window.parent.postMessage(message, '*');
e.preventDefault();
e.stopPropagation();
}
};
// Update overlay position on scroll/resize to keep it aligned with selected element
window.__myEditor.scrollHandler = () => {
// Update selected overlay (purple)
window.__myEditor.updateSelectedOverlay();
// Update hover overlay (red)
window.__myEditor.updateHoverOverlay();
};
window.__myEditor.resizeHandler = () => {
// Update selected overlay (purple)
window.__myEditor.updateSelectedOverlay();
// Update hover overlay (red)
window.__myEditor.updateHoverOverlay();
};
document.body.addEventListener('mousemove', window.__myEditor.mousemoveHandler);
// Add global click interceptor in capture phase (before other handlers)
// This blocks all clicks and handles selection for [data-id] elements
window.addEventListener('click', window.__myEditor.globalClickInterceptor, true);
// Prevent form submissions
window.addEventListener('submit', window.__myEditor.formSubmitInterceptor, true);
window.addEventListener('scroll', window.__myEditor.scrollHandler, true);
window.addEventListener('resize', window.__myEditor.resizeHandler);
};
window.__myEditor.stopEditMode = function() {
if (!window.__myEditor.editMode) return;
window.__myEditor.editMode = false;
// Remove event listeners
if (window.__myEditor.mousemoveHandler) {
document.body.removeEventListener('mousemove', window.__myEditor.mousemoveHandler);
window.__myEditor.mousemoveHandler = null;
}
if (window.__myEditor.globalClickInterceptor) {
window.removeEventListener('click', window.__myEditor.globalClickInterceptor, true);
window.__myEditor.globalClickInterceptor = null;
}
if (window.__myEditor.formSubmitInterceptor) {
window.removeEventListener('submit', window.__myEditor.formSubmitInterceptor, true);
window.__myEditor.formSubmitInterceptor = null;
}
if (window.__myEditor.clickHandler) {
document.body.removeEventListener('click', window.__myEditor.clickHandler);
window.__myEditor.clickHandler = null;
}
if (window.__myEditor.scrollHandler) {
window.removeEventListener('scroll', window.__myEditor.scrollHandler, true);
window.__myEditor.scrollHandler = null;
}
if (window.__myEditor.resizeHandler) {
window.removeEventListener('resize', window.__myEditor.resizeHandler);
window.__myEditor.resizeHandler = null;
}
// Remove overlays
if (window.__myEditor.overlay && window.__myEditor.overlay.parentNode) {
window.__myEditor.overlay.parentNode.removeChild(window.__myEditor.overlay);
window.__myEditor.overlay = null;
}
if (window.__myEditor.selectedOverlay && window.__myEditor.selectedOverlay.parentNode) {
window.__myEditor.selectedOverlay.parentNode.removeChild(window.__myEditor.selectedOverlay);
window.__myEditor.selectedOverlay = null;
}
// Reset selected elements
window.__myEditor.selectedEl = null;
window.__myEditor.permanentlySelectedEl = null;
};
window.addEventListener('message', (event) => {
const data = event.data;
if (data.type === 'start-edit-mode') {
window.__myEditor.startEditMode();
} else if (data.type === 'stop-edit-mode') {
window.__myEditor.stopEditMode();
} else if (data.type === 'apply-theme-vars') {
// Apply theme CSS variables directly to HTML tag
const htmlEl = document.documentElement;
const vars = data.vars || {};
const mode = data.mode || 'light';
// Clear previously applied variables first
if (window.__myEditor.appliedThemeVarNames) {
window.__myEditor.appliedThemeVarNames.forEach(varName => {
htmlEl.style.removeProperty(varName);
});
}
// Reset the list
window.__myEditor.appliedThemeVarNames = [];
// Apply all theme variables as CSS custom properties
Object.keys(vars).forEach(key => {
// Convert kebab-case to CSS custom property format (--variable-name)
// Handle keys like "text-color-1" -> "--text-color-1"
// and "primary" -> "--primary"
const cssVarName = '--' + key.replace(/([A-Z])/g, '-$1').toLowerCase();
htmlEl.style.setProperty(cssVarName, vars[key]);
window.__myEditor.appliedThemeVarNames.push(cssVarName);
});
// Store current theme info for mode switching
window.__myEditor.currentThemeVars = data.allModes || {};
window.__myEditor.currentThemeMode = mode;
window.__myEditor.currentThemeId = data.themeId;
} else if (data.type === 'clear-theme-vars') {
// Clear all theme CSS variables from HTML tag
const htmlEl = document.documentElement;
// Remove only the variables we've applied
if (window.__myEditor.appliedThemeVarNames) {
window.__myEditor.appliedThemeVarNames.forEach(varName => {
htmlEl.style.removeProperty(varName);
});
window.__myEditor.appliedThemeVarNames = [];
}
// Clear stored theme info
window.__myEditor.currentThemeVars = null;
window.__myEditor.currentThemeMode = null;
window.__myEditor.currentThemeId = null;
} else if (data.type === 'set-theme') {
// Handle theme change
const theme = data.theme; // "system", "light", or "dark"
window.__myEditor.currentTheme = theme;
// Remove existing listener if it exists
if (window.__myEditor.systemThemeListener) {
window.matchMedia('(prefers-color-scheme: dark)').removeEventListener('change', window.__myEditor.systemThemeListener);
window.__myEditor.systemThemeListener = null;
}
// Apply theme
const applyTheme = (prefersDark) => {
// Remove existing data-theme attribute
document.documentElement.removeAttribute('data-theme');
let themeMode;
if (theme === 'system') {
// Use system preference
themeMode = prefersDark ? 'dark' : 'light';
document.documentElement.setAttribute('data-theme', themeMode);
document.documentElement.style.colorScheme = themeMode;
// Listen for system preference changes
window.__myEditor.systemThemeListener = (e) => {
if (window.__myEditor.currentTheme === 'system') {
const newMode = e.matches ? 'dark' : 'light';
document.documentElement.setAttribute('data-theme', newMode);
document.documentElement.style.colorScheme = newMode;
// If theme vars are applied, update them for new mode
if (window.__myEditor.currentThemeVars && window.__myEditor.currentThemeVars[newMode]) {
const vars = window.__myEditor.currentThemeVars[newMode];
const htmlEl = document.documentElement;
Object.keys(vars).forEach(key => {
const cssVarName = '--' + key.replace(/([A-Z])/g, '-$1').toLowerCase();
htmlEl.style.setProperty(cssVarName, vars[key]);
});
window.__myEditor.currentThemeMode = newMode;
}
}
};
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', window.__myEditor.systemThemeListener);
} else if (theme === 'light') {
themeMode = 'light';
document.documentElement.setAttribute('data-theme', 'light');
document.documentElement.style.colorScheme = 'light';
} else if (theme === 'dark') {
themeMode = 'dark';
document.documentElement.setAttribute('data-theme', 'dark');
document.documentElement.style.colorScheme = 'dark';
}
// If theme vars are applied, update them for new mode
if (window.__myEditor.currentThemeVars && themeMode && window.__myEditor.currentThemeVars[themeMode]) {
const vars = window.__myEditor.currentThemeVars[themeMode];
const htmlEl = document.documentElement;
Object.keys(vars).forEach(key => {
const cssVarName = '--' + key.replace(/([A-Z])/g, '-$1').toLowerCase();
htmlEl.style.setProperty(cssVarName, vars[key]);
});
window.__myEditor.currentThemeMode = themeMode;
}
};
// Get current system preference
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
applyTheme(prefersDark);
} else if (data.type === 'update-element') {
const el = document.querySelector(`[data-id="${data.id}"]`);
if (el) {
// Apply inline styles - never touch the class attribute
if (data.props.style !== undefined) {
if (data.props.style && data.props.style.trim()) {
// Parse the style string and apply each property
const styleString = data.props.style.trim();
const styleParts = styleString.split(';').filter(part => part.trim());
// Track which properties we're setting
const propertiesToSet = new Set();
styleParts.forEach(part => {
const colonIndex = part.indexOf(':');
if (colonIndex > 0) {
const property = part.substring(0, colonIndex).trim();
const value = part.substring(colonIndex + 1).trim();
if (property && value) {
// Convert kebab-case to camelCase for style property
const camelProperty = property.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
el.style[camelProperty] = value;
propertiesToSet.add(camelProperty);
}
}
});
// If style string is provided but empty, clear all style properties we manage
// (We only clear color and backgroundColor to avoid breaking other styles)
if (styleString === '' || styleParts.length === 0) {
if (el.style.color) el.style.color = '';
if (el.style.backgroundColor) el.style.backgroundColor = '';
}
} else {
// Empty style string - clear color and background-color only
if (el.style.color) el.style.color = '';
if (el.style.backgroundColor) el.style.backgroundColor = '';
}
}
// Update class attribute if provided
if (data.props.class !== undefined) {
if (data.props.class && data.props.class.trim()) {
el.setAttribute('class', data.props.class.trim());
} else {
// Empty class string - remove the class attribute
el.removeAttribute('class');
}
}
// Update innerHTML or textContent if provided
// textContent is used for elements with nested divs to preserve structure
// innerHTML is used for simple elements without nested structure
if (data.props.textContent !== undefined) {
// For elements with nested divs, update textContent to preserve structure
// Only update if the value is different from current
if (el.textContent !== data.props.textContent) {
el.textContent = data.props.textContent;
}
} else if (data.props.innerHTML !== undefined) {
// For simple elements, update innerHTML
// Only update if the value is different from current to avoid unnecessary DOM manipulation
if (el.innerHTML !== data.props.innerHTML) {
el.innerHTML = data.props.innerHTML;
}
}
// If neither innerHTML nor textContent is provided, we don't touch the content - preserving existing content
// Update overlay position if this is the selected element
if (el === window.__myEditor.permanentlySelectedEl) {
setTimeout(() => {
if (window.__myEditor.updateSelectedOverlay) {
window.__myEditor.updateSelectedOverlay();
}
}, 0);
}
}
}
});