-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsquareCraft copy 2.js
525 lines (437 loc) · 18.7 KB
/
squareCraft copy 2.js
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
(async function squareCraft() {
const widgetScript = document.getElementById("squarecraft-script");
if (!widgetScript) {
console.error("❌ Widget script not found! Ensure the script tag exists with id 'squarecraft-script'.");
return;
}
const token = widgetScript.dataset?.token;
const squareCraft_u_id = widgetScript.dataset?.uId;
const squareCraft_w_id = widgetScript.dataset?.wId;
const userId = localStorage.getItem("squareCraft_u_id");
const widgetId = localStorage.getItem("squareCraft_w_id");
if (token) {
console.log("🔑 Token received:", token);
localStorage.setItem("squareCraft_auth_token", token);
document.cookie = `squareCraft_auth_token=${token}; path=.squarespace.com;`;
}
if (squareCraft_u_id) {
console.log("👤 User ID received:", squareCraft_u_id);
localStorage.setItem("squareCraft_u_id", squareCraft_u_id);
document.cookie = `squareCraft_u_id=${squareCraft_u_id}; path=.squarespace.com;`;
}
if (squareCraft_w_id) {
console.log("🛠️ Widget ID received:", squareCraft_w_id);
localStorage.setItem("squareCraft_w_id", squareCraft_w_id);
document.cookie = `squareCraft_w_id=${squareCraft_w_id}; path=.squarespace.com;`;
}
if (token) localStorage.setItem("squareCraft_auth_token", token);
if (userId) localStorage.setItem("squareCraft_u_id", userId);
if (widgetId) localStorage.setItem("squareCraft_w_id", widgetId);
let selectedElement = null;
let appliedStyles = new Set(); // Track applied styles to prevent duplicate injection
function getPageId() {
let pageElement = document.querySelector("article[data-page-sections]");
return pageElement ? pageElement.getAttribute("data-page-sections") : null;
}
let pageId = getPageId();
if (!pageId) console.warn("⚠️ No page ID found. Plugin may not work correctly.");
/**
* 🎨 Apply Styles to an Element & Ensure Persistence
*/
// function applyStylesToElement(elementId, css) {
// if (!elementId || !css || appliedStyles.has(elementId)) return;
// let styleTag = document.getElementById(`style-${elementId}`);
// if (!styleTag) {
// styleTag = document.createElement("style");
// styleTag.id = `style-${elementId}`;
// document.head.appendChild(styleTag);
// }
// let cssText = `#${elementId} { `;
// Object.keys(css).forEach(prop => {
// cssText += `${prop}: ${css[prop]} !important; `;
// });
// cssText += "}";
// styleTag.innerHTML = cssText;
// appliedStyles.add(elementId);
// console.log(`✅ Styles Persisted for ${elementId}`);
// }
/**
* 🎨 Apply Styles to an Element & Ensure Persistence
*/
function applyStylesToElement(elementId, css) {
if (!elementId || !css || appliedStyles.has(elementId)) return;
let styleTag = document.getElementById(`style-${elementId}`);
if (!styleTag) {
styleTag = document.createElement("style");
styleTag.id = `style-${elementId}`;
document.head.appendChild(styleTag);
}
let cssText = `#${elementId}, #${elementId} * { `; // Apply to element & all children
Object.keys(css).forEach(prop => {
cssText += `${prop}: ${css[prop]} !important; `;
});
cssText += "}";
styleTag.innerHTML = cssText;
appliedStyles.add(elementId);
console.log(`✅ Styles Persisted for ${elementId}`);
}
/**
* 📡 Fetch & Apply Stored Modifications After Page Load
*/
async function fetchModifications(retries = 3) {
if (!pageId) return;
try {
console.log(`📄 Fetching saved modifications for Page ID: ${pageId}`);
const response = await fetch(
`https://webefo-backend.vercel.app/api/v1/get-modifications?userId=${userId}`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token || localStorage.getItem("squareCraft_auth_token")}`,
},
}
);
if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
const data = await response.json();
if (!data.modifications || data.modifications.length === 0) {
console.warn("⚠️ No styles found for this page.");
return;
}
console.log("📥 Applying stored modifications...", data);
data.modifications.forEach(({ pageId: storedPageId, elements }) => {
if (storedPageId === pageId) {
elements.forEach(({ elementId, css }) => {
applyStylesToElement(elementId, css);
});
}
});
} catch (error) {
console.error("❌ Error fetching modifications:", error);
if (retries > 0) {
console.log(`🔄 Retrying fetch... (${retries} left)`);
setTimeout(() => fetchModifications(retries - 1), 2000);
}
}
}
/**
* 💾 Save Modifications for Selected Element
*/
async function saveModifications(elementId, css) {
if (!pageId || !elementId || !css) {
console.warn("⚠️ Missing required data to save modifications.");
return;
}
applyStylesToElement(elementId, css);
console.log("📡 Saving modifications for:", { pageId, elementId, css });
const modificationData = {
userId,
token,
widgetId,
modifications: [{ pageId, elements: [{ elementId, css }] }],
};
try {
const response = await fetch("https://webefo-backend.vercel.app/api/v1/modifications", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token || localStorage.getItem("squareCraft_auth_token")}`,
"userId": userId,
"pageId": pageId,
"widget-id": widgetId,
},
body: JSON.stringify(modificationData),
});
console.log("✅ Changes Saved Successfully!", await response.json());
} catch (error) {
console.error("❌ Error saving modifications:", error);
}
}
// async function fontfamilies() {
// const response = await fetch("https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyBPpLHcfY1Z1SfUIe78z6UvPe-wF31iwRk");
// const data = await response.json();
// const fontDropdown = document.getElementById("squareCraft-font-family");
// fontDropdown.style.position = "relative";
// fontDropdown.style.width = "100%";
// fontDropdown.style.border = "1px solid #585858";
// fontDropdown.style.borderRadius = "6px";
// fontDropdown.style.background = "#2c2c2c";
// fontDropdown.style.color = "white";
// fontDropdown.style.display = "flex";
// fontDropdown.style.alignItems = "center";
// fontDropdown.style.justifyContent = "space-between";
// fontDropdown.style.padding = "10px";
// fontDropdown.style.cursor = "pointer";
// // Create text container for the selected font
// let selectedFont = "Select a Font";
// const selectedFontText = document.createElement("p");
// selectedFontText.textContent = selectedFont;
// selectedFontText.style.flexGrow = "1";
// selectedFontText.style.fontSize = "14px";
// // Dropdown arrow icon
// const dropdownArrow = document.createElement("img");
// dropdownArrow.src = "https://fatin-webefo.github.io/squareCraft-Plugin/public/arrow.svg";
// dropdownArrow.style.width = "12px";
// dropdownArrow.style.height = "12px";
// dropdownArrow.style.transform = "rotate(180deg)";
// fontDropdown.appendChild(selectedFontText);
// fontDropdown.appendChild(dropdownArrow);
// // Create dropdown list (hidden initially)
// const fontList = document.createElement("div");
// fontList.style.position = "absolute";
// fontList.style.top = "100%";
// fontList.style.left = "0";
// fontList.style.width = "100%";
// fontList.style.background = "#2c2c2c";
// fontList.style.border = "1px solid #585858";
// fontList.style.borderRadius = "6px";
// fontList.style.overflowY = "auto";
// fontList.style.maxHeight = "200px";
// fontList.style.display = "none";
// fontList.style.zIndex = "1000";
// // Add fonts to the dropdown
// data.items.forEach(font => {
// const option = document.createElement("div");
// option.textContent = font.family;
// option.style.padding = "8px";
// option.style.cursor = "pointer";
// option.style.fontFamily = font.family;
// option.style.transition = "background 0.3s";
// option.style.color = "white";
// option.style.fontSize = "14px";
// // Hover effect
// option.addEventListener("mouseover", () => {
// option.style.background = "#444";
// });
// option.addEventListener("mouseout", () => {
// option.style.background = "transparent";
// });
// // Click event to select font
// option.addEventListener("click", async () => {
// selectedFont = font.family;
// selectedFontText.textContent = selectedFont;
// selectedFontText.style.fontFamily = selectedFont;
// fontList.style.display = "none";
// // Apply font-family to the selected element
// if (selectedElement) {
// selectedElement.style.fontFamily = selectedFont;
// // Save the modification immediately
// let css = { "font-family": selectedFont };
// await saveModifications(selectedElement.id, css);
// }
// });
// fontList.appendChild(option);
// });
// fontDropdown.appendChild(fontList);
// // Toggle dropdown on click
// fontDropdown.addEventListener("click", (event) => {
// event.stopPropagation();
// fontList.style.display = fontList.style.display === "block" ? "none" : "block";
// });
// // Close dropdown when clicking outside
// document.addEventListener("click", () => {
// fontList.style.display = "none";
// });
// }
async function fontfamilies() {
const response = await fetch("https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyBPpLHcfY1Z1SfUIe78z6UvPe-wF31iwRk");
const data = await response.json();
const fontDropdown = document.getElementById("squareCraft-font-family");
const fontWeightDropdown = document.getElementById("squareCraftFontWeight");
fontDropdown.style.position = "relative";
fontDropdown.style.width = "100%";
fontDropdown.style.border = "1px solid #585858";
fontDropdown.style.borderRadius = "6px";
fontDropdown.style.background = "#2c2c2c";
fontDropdown.style.color = "white";
fontDropdown.style.display = "flex";
fontDropdown.style.alignItems = "center";
fontDropdown.style.justifyContent = "space-between";
fontDropdown.style.padding = "10px";
fontDropdown.style.cursor = "pointer";
let selectedFont = "Select a Font";
const selectedFontText = document.createElement("p");
selectedFontText.textContent = selectedFont;
selectedFontText.style.flexGrow = "1";
selectedFontText.style.fontSize = "14px";
// Dropdown arrow icon
const dropdownArrow = document.createElement("img");
dropdownArrow.src = "https://fatin-webefo.github.io/squareCraft-Plugin/public/arrow.svg";
dropdownArrow.style.width = "12px";
dropdownArrow.style.height = "12px";
dropdownArrow.style.transform = "rotate(180deg)";
fontDropdown.appendChild(selectedFontText);
fontDropdown.appendChild(dropdownArrow);
// Create dropdown list
const fontList = document.createElement("div");
fontList.style.position = "absolute";
fontList.style.top = "100%";
fontList.style.left = "0";
fontList.style.width = "100%";
fontList.style.background = "#2c2c2c";
fontList.style.border = "1px solid #585858";
fontList.style.borderRadius = "6px";
fontList.style.overflowY = "auto";
fontList.style.maxHeight = "200px";
fontList.style.display = "none";
fontList.style.zIndex = "1000";
// Populate font-family dropdown
data.items.forEach(font => {
const option = document.createElement("div");
option.textContent = font.family;
option.style.padding = "8px";
option.style.cursor = "pointer";
option.style.fontFamily = font.family;
option.style.transition = "background 0.3s";
option.style.color = "white";
option.style.fontSize = "14px";
// Hover effect
option.addEventListener("mouseover", () => {
option.style.background = "#444";
});
option.addEventListener("mouseout", () => {
option.style.background = "transparent";
});
// Click event to select font
// option.addEventListener("click", async () => {
// selectedFont = font.family;
// selectedFontText.textContent = selectedFont;
// selectedFontText.style.fontFamily = selectedFont;
// fontList.style.display = "none";
// // Apply font-family to selected element
// if (selectedElement) {
// selectedElement.style.fontFamily = selectedFont;
// let css = { "font-family": selectedFont };
// await saveModifications(selectedElement.id, css);
// }
// // Update font-weight dropdown based on selected font
// updateFontWeightDropdown(font.variants);
// });
option.addEventListener("click", async () => {
selectedFont = font.family;
selectedFontText.textContent = selectedFont;
selectedFontText.style.fontFamily = selectedFont;
fontList.style.display = "none";
// Apply font-family to the selected element and all its child elements
if (selectedElement) {
let css = { "font-family": selectedFont };
await saveModifications(selectedElement.id, css);
applyStylesToElement(selectedElement.id, css);
}
});
fontList.appendChild(option);
});
fontDropdown.appendChild(fontList);
// Toggle dropdown on click
fontDropdown.addEventListener("click", (event) => {
event.stopPropagation();
fontList.style.display = fontList.style.display === "block" ? "none" : "block";
});
// Close dropdown when clicking outside
document.addEventListener("click", () => {
fontList.style.display = "none";
});
// Function to update font-weight dropdown dynamically
function updateFontWeightDropdown(variants) {
fontWeightDropdown.innerHTML = ""; // Clear existing options
variants.forEach(variant => {
let weight = variant === "regular" ? "400" : variant; // Convert "regular" to 400
let option = document.createElement("option");
option.value = weight;
option.textContent = `Weight ${weight}`;
fontWeightDropdown.appendChild(option);
});
}
}
// Call the function
fontfamilies();
/**
* 🎛️ Create Floating Widget for Editing Styles
*/
function createWidget() {
const widgetContainer = document.createElement("div");
widgetContainer.id = "squarecraft-widget-container";
widgetContainer.style.position = "fixed";
widgetContainer.style.top = "100px";
widgetContainer.style.left = "100px";
widgetContainer.style.zIndex = "9999";
widgetContainer.innerHTML = `
<div style="width: 300px; background: #2c2c2c; padding: 20px; border-radius: 18px; color: white;">
<h3>🎨 SquareCraft Widget</h3>
<label>Font Size:</label>
<input type="number" id="squareCraftFontSize" value="16" min="10" max="50" style="width: 100%;">
<label>Background Color:</label>
<input type="color" id="squareCraftBgColor" value="#ffffff" style="width: 100%;">
<label>Border Radius:</label>
<input type="range" id="squareCraftBorderRadius" min="0" max="50" value="0">
<p>Border Radius: <span id="borderRadiusValue">0px</span></p>
<div id="squareCraft-font-family" class="squareCraft-flex squareCraft-col-span-8 squareCraft-cursor-pointer squareCraft-justify-between squareCraft-border squareCraft-border-solid squareCraft-border-585858 squareCraft-rounded-6px squareCraft-items-center squareCraft-h-full">
<div class="squareCraft-bg-494949 squareCraft-w-full squareCraft-px-2 squareCraft-py-1px ">
<p class="squareCraft-text-sm squareCraft-font-light"></p>
</div <div class="squareCraft-bg-3f3f3f squareCraft-px-2" style="height: 27px; padding: 0 8px;">
<img class="squareCraft-h-full squareCraft-rotate-180" width="12px"
src="https://fatin-webefo.github.io/squareCraft-Plugin/public/arrow.svg" alt="">
</div>
</div>
<label>Font Weight:</label>
<select id="squareCraftFontWeight" style="width: 100%; padding: 6px; background: #2c2c2c; color: white; border: 1px solid #585858; border-radius: 6px;">
<option value="100">Thin (100)</option>
<option value="200">Extra Light (200)</option>
<option value="300">Light (300)</option>
<option value="400" selected>Regular (400)</option>
<option value="500">Medium (500)</option>
<option value="600">Semi Bold (600)</option>
<option value="700">Bold (700)</option>
<option value="800">Extra Bold (800)</option>
<option value="900">Black (900)</option>
</select>
<button id="squareCraftPublish" style="width: 100%; padding: 10px; background: #EF7C2F; color: white;">
Publish Changes
</button>
</div>
`;
document.body.appendChild(widgetContainer);
}
/**
* 🎯 Handle Element Selection & Style Updates
*/
function attachEventListeners() {
document.body.addEventListener("click", (event) => {
let block = event.target.closest('[id^="block-"]');
if (!block) return;
if (selectedElement) selectedElement.style.outline = "";
selectedElement = block;
selectedElement.style.outline = "2px dashed #EF7C2F";
console.log(`✅ Selected Element: ${selectedElement.id}`);
});
document.getElementById("squareCraftPublish").addEventListener("click", async () => {
if (!selectedElement) {
console.warn("⚠️ No element selected.");
return;
}
let css = {
"font-size": document.getElementById("squareCraftFontSize").value + "px",
"background-color": document.getElementById("squareCraftBgColor").value,
"border-radius": document.getElementById("squareCraftBorderRadius").value + "px",
"font-family": document.getElementById("squareCraft-font-family").querySelector("p").textContent,
"font-weight": document.getElementById("squareCraftFontWeight").value // Use selected font weight
};
await saveModifications(selectedElement.id, css);
});
}
/**
* 🔄 Handle AJAX Navigation
*/
const observer = new MutationObserver(() => {
console.log("🔄 Page updated via AJAX. Re-fetching styles...");
pageId = getPageId();
appliedStyles.clear();
fetchModifications();
});
observer.observe(document.body, { childList: true, subtree: true });
document.addEventListener("DOMContentLoaded", () => {
createWidget();
attachEventListeners();
fetchModifications();
});
})();