-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.js
More file actions
579 lines (498 loc) · 17.1 KB
/
utils.js
File metadata and controls
579 lines (498 loc) · 17.1 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
// ==UserScript==
// @name Econea Utils
// @namespace https://econea.cz/
// @version 1.4.0
// @description Replaces specified Shopify metafield editors with Suneditor WYSIWYG editor etc.
// @author Stepan
// @match https://*.myshopify.com/admin/*
// @match https://admin.shopify.com/store/*
// @require https://cdn.jsdelivr.net/npm/suneditor@2.47.7/dist/suneditor.min.js
// @require https://cdn.jsdelivr.net/npm/suneditor@2.47.7/src/lang/cs.js
// @resource SuneditorCSS https://cdn.jsdelivr.net/npm/suneditor@2.47.7/dist/css/suneditor.min.css
// @grant GM_getResourceText
// @license MIT
// ==/UserScript==
(function() {
'use strict';
const CONFIG = {
targetMetafields: {
ids: [
'256299762003',
'171702452563',
],
},
// Enable debug logging
debug: true,
editorConfig: {
strictMode: true,
addTagsWhitelist: ".+",
pasteTagsWhitelist: ".+",
tagsBlacklist: "script",
pasteTagsBlacklist: "script",
attributesWhitelist: {
all: ".+",
},
attributesBlacklist: {
// Suneditor automatically wraps inline copy/pasted content in a `span` component with a `style` attribute.
// By blacklisting the `style` attribute on `span` components, it adds a "blank" span which it automatically discards afterwards. Problem solved.
span: "style",
},
minHeight: '300px',
maxHeight: '600px',
height: '300px',
placeholder: '',
buttonList: [
['formatBlock'],
['bold', 'italic', 'underline', 'fontColor'],
['align'],
['link', 'image', 'video', 'table'],
['list', 'outdent', 'indent'],
['removeFormat'],
['fullScreen', 'showBlocks', 'codeView'],
['preview', 'print'],
],
formats: [
'p',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'blockquote',
],
font: null,
fullScreenOffset: "60",
popupDisplay: "local",
historyStackDelayTime: 0,
},
};
let processedElements = new Set();
let observer;
let suneditorInstances = new Map();
let suneditorReady = false;
let initAttempts = 0;
const MAX_INIT_ATTEMPTS = 20;
function log(...args) {
if (CONFIG.debug) {
console.log('[Shopify WYSIWYG]', ...args);
}
}
function logError(...args) {
if (CONFIG.debug) {
console.error('[Shopify WYSIWYG]', ...args);
}
}
function checkSuneditorAvailability() {
return new Promise((resolve) => {
const checkSuneditor = () => {
// Check if Suneditor is available
let editorReady = false;
let editorLangReady = false;
if (typeof window.SUNEDITOR !== 'undefined' && window.SUNEDITOR) {
log('Suneditor detected and ready');
editorReady = true;
}
if (typeof window.SUNEDITOR_LANG !== 'undefined' && window.SUNEDITOR_LANG) {
log('Suneditor lang detected and ready');
editorLangReady = true;
}
if (editorReady && editorLangReady) {
resolve(true);
return;
}
initAttempts++;
if (initAttempts < MAX_INIT_ATTEMPTS) {
log(`Suneditor check attempt ${initAttempts}/${MAX_INIT_ATTEMPTS}...`);
setTimeout(checkSuneditor, 500);
} else {
log('Max attempts reached, Suneditor not available');
resolve(false);
}
};
checkSuneditor();
});
}
function isProductPage() {
const url = window.location.href;
return url.includes('/products/') &&
(url.includes('myshopify.com/admin') || url.includes('admin.shopify.com'));
}
// Enhanced metafield detection using the exact DOM structure
function findMetafieldElements() {
const elements = [];
// Look for the specific structure from your DOM
const metafieldRows = document.querySelectorAll('div._RowWrapper_xxurb_22');
metafieldRows.forEach(row => {
try {
// Find the metafield link to get ID and name
const link = row.querySelector('a[href*="/metafields/"]');
if (!link) return;
const href = link.getAttribute('href');
const metafieldId = href.match(/metafields\/(\d+)/)?.[1];
const metafieldName = link.textContent.trim();
// Find the textarea in this row
const textarea = row.querySelector('textarea.Polaris-TextField__Input[aria-multiline="true"]');
if (!textarea || processedElements.has(textarea)) return;
// Check if this metafield should be targeted
const shouldTarget = shouldTargetMetafield(metafieldId, metafieldName);
if (shouldTarget) {
elements.push({
textarea: textarea,
metafieldId: metafieldId,
metafieldName: metafieldName,
row: row
});
log('Found target metafield:', metafieldName, 'ID:', metafieldId);
}
} catch (error) {
logError('Error processing metafield row:', error);
}
});
return elements;
}
function shouldTargetMetafield(id, name) {
const {
ids,
} = CONFIG.targetMetafields;
// If targeting specific IDs
if (ids.length > 0 && ids.includes(id)) {
return true;
}
return false;
}
function createWYSIWYGEditor(metafieldData) {
try {
const {
textarea,
metafieldId,
metafieldName,
row
} = metafieldData;
log('Creating WYSIWYG for:', metafieldName, 'ID:', metafieldId);
// Find the TextField container
const textFieldContainer = textarea.closest('.Polaris-TextField');
if (!textFieldContainer) {
log('Could not find TextField container');
return null;
}
// Create wrapper with Shadow DOM
const editorWrapper = document.createElement('div');
editorWrapper.className = 'wysiwyg-editor-wrapper';
editorWrapper.style.position = 'relative';
const keyHandler = (e) => {
switch (e.key) {
case "ArrowLeft":
case "ArrowUp":
case "ArrowRight":
case "ArrowDown":
break;
default:
// Prevent Shopify keyboard shortcuts from triggering when interacting with the WYSIWYG editor.
e.stopPropagation();
break;
}
};
editorWrapper.addEventListener("keydown", (e) => {
keyHandler(e);
}, true);
editorWrapper.addEventListener("keyup", (e) => {
keyHandler(e);
}, true);
// Create Shadow DOM for style isolation
const shadowRoot = editorWrapper.attachShadow({ mode: 'open' });
// Add custom styles to Shadow DOM
const customStyles = document.createElement('style');
customStyles.textContent = `
.sun-editor {
border: 1px solid #d1d5db !important;
border-radius: 8px !important;
background: white !important;
}
.se-toolbar {
border-bottom: 1px solid #d1d5db !important;
background: #f9fafb !important;
padding: 8px 12px !important;
}
/* Match Shopify Admin UI font */
.sun-editor-editable {
font-family: -apple-system, BlinkMacSystemFont, San Francisco, Segoe UI, Roboto, Helvetica Neue, sans-serif !important;
line-height: 1.4 !important;
font-size: 0.875rem !important;
}
`;
// place at the top of the shadow root
shadowRoot.insertBefore(customStyles, shadowRoot.firstChild);
const styleEl = document.createElement('style');
styleEl.textContent = GM_getResourceText('SuneditorCSS');
// place at the top of the shadow root
shadowRoot.insertBefore(styleEl, shadowRoot.firstChild);
// Create editor div inside shadow DOM
const editorId = 'wysiwyg-' + metafieldId + '-' + Date.now();
const editorDiv = document.createElement('div');
editorDiv.id = editorId;
shadowRoot.appendChild(editorDiv);
// Replace the TextField but keep the original hidden
textFieldContainer.parentNode.insertBefore(editorWrapper, textFieldContainer);
textFieldContainer.style.display = 'none';
// Store references
editorWrapper.originalElement = textarea;
editorWrapper.originalContainer = textFieldContainer;
processedElements.add(textarea);
// Get initial content
const initialContent = textarea.value || '';
let hasInitialContent = false;
if (initialContent && initialContent.trim()) {
hasInitialContent = true;
}
// Initialize Suneditor
let editor;
try {
// Clone the config and set up callbacks for this instance
const instanceConfig = Object.assign({}, CONFIG.editorConfig);
const syncContent = (triggerReactOnChange) => {
try {
const content = editor.getContents();
// Check if content is just empty paragraph(s) - don't sync these
const isEmpty = !content ||
content.trim() === '<p><br></p>' ||
content.trim() === '<p></p>' ||
content.trim() === '' ||
editor.util.onlyZeroWidthSpace(content);
// Update the original textarea
const oldValue = textarea.value;
const newValue = isEmpty ? '' : content;
// Only trigger events if content actually changed AND it's not just empty formatting
if ((oldValue !== newValue || triggerReactOnChange) && (hasInitialContent || !isEmpty)) {
textarea.value = newValue;
if (triggerReactOnChange) {
// Also try to trigger Shopify React change detection
const reactProps = Object.keys(textarea).find(key => key.startsWith('__react'));
if (reactProps) {
const reactInternalInstance = textarea[reactProps];
if (reactInternalInstance && reactInternalInstance.memoizedProps && reactInternalInstance.memoizedProps.onChange) {
try {
reactInternalInstance.memoizedProps.onChange({
target: textarea,
currentTarget: textarea
});
} catch (e) {
logError('React onChange trigger failed:', e);
}
}
}
}
console.dir({
before: oldValue,
after: newValue,
}, {depth:3});
log('Content synced for:', metafieldName, 'Length:', newValue.length);
}
} catch (error) {
logError('Error syncing content:', error);
}
};
// Initialize Suneditor
instanceConfig.lang = SUNEDITOR_LANG.cs;
editor = SUNEDITOR.create(editorDiv, instanceConfig);
editor.onChange = (contents, core) => {
log("onChange");
syncContent(true);
};
editor.onBlur = (e, core) => {
log("onBlur");
syncContent(true);
};
// Set initial content after initialization
if (hasInitialContent) {
try {
editor.setContents(initialContent);
} catch (e) {
logError('Error setting initial content:', e);
}
}
// Focus editor
requestAnimationFrame(() => {
editor.core.focus();
});
} catch (error) {
logError('Failed to create Suneditor instance:', error);
// Restore original element
textFieldContainer.style.display = '';
editorWrapper.remove();
processedElements.delete(textarea);
return null;
}
suneditorInstances.set(editorId, {
editor: editor,
originalTextarea: textarea,
metafieldName: metafieldName
});
log('WYSIWYG editor created successfully for:', metafieldName);
return editorWrapper;
} catch (error) {
logError('Failed to create WYSIWYG editor:', error);
if (metafieldData.textarea) {
processedElements.delete(metafieldData.textarea);
}
return null;
}
}
async function processMetafields() {
try {
if (!isProductPage()) {
log('Not on product page, skipping...');
return;
}
if (!suneditorReady) {
log('Suneditor not ready yet, checking availability...');
suneditorReady = await checkSuneditorAvailability();
if (!suneditorReady) {
log('Suneditor failed to load properly');
return;
}
}
log('Processing metafields...');
const metafieldElements = findMetafieldElements();
let processedCount = 0;
for (const metafieldData of metafieldElements) {
try {
const result = createWYSIWYGEditor(metafieldData);
if (result) {
processedCount++;
}
} catch (error) {
logError('Failed to create editor for metafield:', error);
}
}
log(`Successfully processed ${processedCount} metafield(s)`);
} catch (error) {
logError('Error in processMetafields:', error);
}
}
let processTimeout;
function debouncedProcess() {
clearTimeout(processTimeout);
processTimeout = setTimeout(processMetafields, 50);
}
// Setup observer for dynamic content
function setupObserver() {
try {
if (observer) {
observer.disconnect();
}
observer = new MutationObserver((mutations) => {
let shouldProcess = false;
for (const mutation of mutations) {
// Only check childList mutations for efficiency
if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
for (const node of mutation.addedNodes) {
if (node.nodeType === Node.ELEMENT_NODE) {
// Check if this node or its descendants contain metafield elements
if (node.matches && (
node.matches('div._RowWrapper_xxurb_22') ||
node.matches('a[href*="/metafields/"]') ||
node.matches('textarea[aria-multiline="true"]')
)) {
shouldProcess = true;
break;
} else if (node.querySelector && (
node.querySelector('div._RowWrapper_xxurb_22') ||
node.querySelector('a[href*="/metafields/"]') ||
node.querySelector('textarea[aria-multiline="true"]')
)) {
shouldProcess = true;
break;
}
}
}
if (shouldProcess) break;
}
}
if (shouldProcess) {
log('DOM changes detected, reprocessing...');
debouncedProcess();
}
});
observer.observe(document.body, {
childList: true,
subtree: true,
// Only observe what we need
attributes: false,
attributeOldValue: false,
characterData: false,
characterDataOldValue: false
});
log('Observer set up successfully');
} catch (error) {
logError('Error setting up observer:', error);
}
}
// Initialize the script
async function initialize() {
try {
if (!isProductPage()) return;
log('Initializing Shopify Metafield WYSIWYG Editor...');
log('Target config:', CONFIG.targetMetafields);
// Wait for Suneditor to be ready
suneditorReady = await checkSuneditorAvailability();
if (suneditorReady) {
log('Suneditor is ready, processing metafields...');
setTimeout(processMetafields, 30);
setTimeout(processMetafields, 350); // Backup processing
setupObserver();
} else {
log('Failed to initialize: Suneditor not available');
}
} catch (error) {
logError('Error in initialize:', error);
}
}
// Handle page navigation
let currentUrl = window.location.href;
function handleUrlChange() {
if (currentUrl !== window.location.href) {
currentUrl = window.location.href;
log('URL changed, reinitializing...');
// Clean up
processedElements.clear();
if (observer) observer.disconnect();
suneditorInstances.forEach((instance, id) => {
try {
instance.editor.destroy();
} catch (e) {
logError(e);
}
});
suneditorInstances.clear();
suneditorReady = false;
initAttempts = 0;
// Reinitialize
setTimeout(initialize, 1000);
}
}
setInterval(handleUrlChange, 1000);
// Start the script
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initialize);
} else {
setTimeout(initialize, 1000);
}
// Cleanup on page unload
window.addEventListener('beforeunload', () => {
try {
if (observer) observer.disconnect();
suneditorInstances.forEach((instance) => {
try {
instance.editor.destroy();
} catch (e) {
logError(e);
}
});
suneditorInstances.clear();
} catch (error) {
logError('Error during cleanup:', error);
}
});
log('Shopify Metafield WYSIWYG Editor script loaded successfully');
})();