-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimageSelection.js
More file actions
434 lines (374 loc) · 14.1 KB
/
imageSelection.js
File metadata and controls
434 lines (374 loc) · 14.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
// imageSelection.js — theme-slot picker in the popup.
//
// Storage schema (shared with manage-images.js):
// - `uploadedImages`: [{ filename, dataUrl, source?, originalUrl? }]
// `source` is "upload" (default) or "url" for URL-imported images.
// - `disabledImages`: [src] — logical-deletion flag for predefined
// remote-URL images listed in images.json.
// - Theme slots (welcome, sidenav, chatview, navside) store either a
// remote URL or a data: URL — both are usable directly as <img> src
// and as CSS background-image.
//
// All images (bundled assets have been removed) are remote URLs or data:
// URLs, so no path translation is needed anywhere.
const PLACEHOLDER_SRC =
"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 9'%3E%3Crect fill='%23242530' width='16' height='9'/%3E%3C/svg%3E";
const THEME_SLOTS = ["welcome", "sidenav", "chatview", "navside"];
let predefinedSrcs = []; // from images.json (flat list of URLs)
let uploadedImages = []; // [{ filename, dataUrl, source?, originalUrl? }]
let disabledImages = new Set(); // src strings flagged as hidden
let currentType = null;
let selectedSrc = null;
let renderToken = 0; // guard against overlapping batched renders
const urlToDataUrlCache = new Map(); // remote URL → data URL, for the lifetime of the popup
// DOM
const modal = document.getElementById("image-modal");
const modalGallery = document.getElementById("modal-gallery");
const modalTitle = document.getElementById("modal-title");
const modalUploadBtn = document.getElementById("modal-upload");
if (modalUploadBtn) modalUploadBtn.textContent = "Manage Images";
// ── Helpers ─────────────────────────────────────────────────────────────────
function isUsableSrc(src) {
return typeof src === "string" && /^(https?:|data:)/.test(src);
}
function previewFor(src) {
return isUsableSrc(src) ? src : PLACEHOLDER_SRC;
}
function isUserImage(src) {
return uploadedImages.some((i) => i.dataUrl === src);
}
function isPredefinedImage(src) {
return predefinedSrcs.includes(src);
}
function setPreview(slot, src) {
const el = document.getElementById(`${slot}-preview`);
if (el) el.src = previewFor(src);
}
function openManagePage() {
const url = chrome.runtime.getURL("manage-images.html");
if (chrome.tabs && chrome.tabs.create) {
chrome.tabs.create({ url });
} else {
window.open(url, "_blank");
}
}
// Fetches a remote image and converts it to a data URL using the same pipeline
// as local uploads. Needed because WhatsApp Web's CSP blocks external image
// origins in `background-image: url(...)`, so the theme slot must always hold
// a data URL by the time the content script reads it.
function fetchAsDataUrl(url) {
if (urlToDataUrlCache.has(url)) return Promise.resolve(urlToDataUrlCache.get(url));
return fetch(url, { mode: "cors" })
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.blob();
})
.then((blob) => {
if (!blob.type || !blob.type.startsWith("image/")) {
throw new Error("The URL did not return an image.");
}
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () => reject(reader.error || new Error("Read failed."));
reader.readAsDataURL(blob);
});
})
.then((dataUrl) => {
urlToDataUrlCache.set(url, dataUrl);
return dataUrl;
});
}
// Unified conversion funnel: every save goes through here so the theme slot
// ends up with a `data:` URL regardless of whether the source was an upload,
// a URL-imported image (already a data URL), or a predefined remote URL.
async function ensureDataUrl(src) {
if (typeof src !== "string" || !src) return null;
if (src.startsWith("data:")) return src;
if (/^https?:/.test(src)) return await fetchAsDataUrl(src);
return null;
}
// ── Bootstrap ───────────────────────────────────────────────────────────────
document.addEventListener("DOMContentLoaded", () => {
chrome.storage.local.get(
[...THEME_SLOTS, "uploadedImages", "disabledImages"],
(result) => {
THEME_SLOTS.forEach((slot) => setPreview(slot, result[slot]));
uploadedImages = Array.isArray(result.uploadedImages)
? result.uploadedImages
: [];
disabledImages = new Set(
Array.isArray(result.disabledImages) ? result.disabledImages : [],
);
fetch(chrome.runtime.getURL("images.json"))
.then((res) => res.json())
.then((data) => {
predefinedSrcs = extractPredefinedSrcs(data);
renderGallery();
})
.catch((err) => console.error("Failed to load images.json:", err));
// Self-heal slots left over from pre-CSP-fix installs: they contain a
// raw HTTPS URL that WhatsApp Web's CSP blocks. Convert to data URLs
// in the background so the selection actually renders next time.
migrateLegacySlots(result);
},
);
if (modalUploadBtn) {
modalUploadBtn.addEventListener("click", (e) => {
e.preventDefault();
openManagePage();
closeModal();
});
}
});
async function migrateLegacySlots(initialValues) {
const migrations = {};
for (const slot of THEME_SLOTS) {
const v = initialValues[slot];
if (typeof v === "string" && /^https?:/.test(v)) {
try {
migrations[slot] = await fetchAsDataUrl(v);
} catch (err) {
console.warn(`Legacy ${slot} slot could not be converted:`, err);
}
}
}
if (Object.keys(migrations).length > 0) {
chrome.storage.local.set(migrations);
}
}
function extractPredefinedSrcs(data) {
const out = [];
if (!data) return out;
for (const key of Object.keys(data)) {
// `uploaded` was a legacy side-channel — ignore if it ever appears.
if (key === "uploaded") continue;
const files = data[key]?.files;
if (!Array.isArray(files)) continue;
for (const src of files) if (isUsableSrc(src)) out.push(src);
}
return out;
}
// ── Live sync with the management page ─────────────────────────────────────
chrome.storage.onChanged.addListener((changes, area) => {
if (area !== "local") return;
let libraryChanged = false;
if (changes.uploadedImages) {
uploadedImages = Array.isArray(changes.uploadedImages.newValue)
? changes.uploadedImages.newValue
: [];
libraryChanged = true;
}
if (changes.disabledImages) {
disabledImages = new Set(
Array.isArray(changes.disabledImages.newValue)
? changes.disabledImages.newValue
: [],
);
libraryChanged = true;
}
for (const slot of THEME_SLOTS) {
if (changes[slot]) setPreview(slot, changes[slot].newValue);
}
if (libraryChanged && modal.style.display === "flex") renderGallery();
});
// ── Library view (predefined + user, minus disabled) ────────────────────────
function visibleSrcs() {
const seen = new Set();
const out = [];
for (const src of predefinedSrcs) {
if (disabledImages.has(src) || seen.has(src)) continue;
seen.add(src);
out.push(src);
}
for (const img of uploadedImages) {
const src = img.dataUrl;
if (!isUsableSrc(src) || disabledImages.has(src) || seen.has(src)) continue;
seen.add(src);
out.push(src);
}
return out;
}
// ── Gallery rendering ───────────────────────────────────────────────────────
function renderGallery() {
const token = ++renderToken;
modalGallery.innerHTML = "";
const images = visibleSrcs();
if (images.length === 0) {
const empty = document.createElement("div");
empty.className = "gallery-empty-hint";
empty.style.cssText =
"padding:20px;color:#a0a0a0;font-size:13px;text-align:center;width:100%";
empty.textContent =
"No images available. Use “Manage Images” to add some.";
modalGallery.appendChild(empty);
return;
}
const BATCH_SIZE = 12;
let index = 0;
const renderBatch = () => {
if (token !== renderToken) return; // superseded by another render
const fragment = document.createDocumentFragment();
const end = Math.min(index + BATCH_SIZE, images.length);
for (let i = index; i < end; i++) {
fragment.appendChild(createOption(images[i]));
}
modalGallery.appendChild(fragment);
index = end;
if (index < images.length) {
(window.requestIdleCallback || window.requestAnimationFrame)(renderBatch, {
timeout: 100,
});
} else if (selectedSrc) {
selectImageInGallery(selectedSrc);
}
};
renderBatch();
}
function createOption(src) {
const option = document.createElement("div");
option.className = "image-option";
option.dataset.src = src;
const img = document.createElement("img");
img.alt = "";
img.loading = "lazy";
img.decoding = "async";
img.src = src;
option.appendChild(img);
// Per-image delete button:
// - predefined → logical disable (adds to disabledImages)
// - upload / url → hard delete from uploadedImages
const delBtn = document.createElement("button");
delBtn.className = "delete-btn";
delBtn.textContent = "✕";
delBtn.title = isPredefinedImage(src)
? "Hide this image"
: "Delete this image";
delBtn.addEventListener("click", (e) => {
e.stopPropagation();
deleteImage(src);
});
option.appendChild(delBtn);
option.addEventListener("click", () => {
modalGallery
.querySelectorAll(".image-option.selected")
.forEach((el) => el.classList.remove("selected"));
option.classList.add("selected");
selectedSrc = src;
if (currentType) setPreview(currentType, src);
});
return option;
}
function selectImageInGallery(src) {
modalGallery
.querySelectorAll(".image-option.selected")
.forEach((el) => el.classList.remove("selected"));
const option = modalGallery.querySelector(
`.image-option[data-src="${cssEscape(src)}"]`,
);
if (option) {
option.classList.add("selected");
selectedSrc = src;
}
}
// CSS.escape isn't needed for https URLs but data: URLs contain characters
// (`:`, `,`, `/`, `+`, `=`) that the selector engine handles fine inside an
// attribute selector — except when the value also contains `"`. The data URL
// we produce never does, but escape defensively.
function cssEscape(value) {
return window.CSS && CSS.escape ? CSS.escape(value) : value.replace(/"/g, '\\"');
}
// ── Deletion ────────────────────────────────────────────────────────────────
function deleteImage(src) {
if (isUserImage(src)) {
uploadedImages = uploadedImages.filter((i) => i.dataUrl !== src);
chrome.storage.local.set({ uploadedImages }, () => clearSlotsUsing(src));
// A user image might also have been individually disabled — clean up.
if (disabledImages.delete(src)) {
chrome.storage.local.set({ disabledImages: [...disabledImages] });
}
} else if (isPredefinedImage(src)) {
disabledImages.add(src);
chrome.storage.local.set(
{ disabledImages: [...disabledImages] },
() => clearSlotsUsing(src),
);
} else {
return;
}
if (selectedSrc === src) selectedSrc = null;
renderGallery();
}
function clearSlotsUsing(src) {
chrome.storage.local.get(THEME_SLOTS, (result) => {
const toRemove = THEME_SLOTS.filter((slot) => result[slot] === src);
if (toRemove.length === 0) return;
chrome.storage.local.remove(toRemove, () => {
toRemove.forEach((slot) => setPreview(slot, null));
});
});
}
// ── Modal logic ─────────────────────────────────────────────────────────────
function openModal(type) {
currentType = type;
// Nutze innerHTML für die Formatierung (fett & kursiv)
modalTitle.innerHTML = `Image selection for <b><i>${type}</i></b>`;
modal.style.display = "flex";
modalGallery.scrollTo({ top: 0 });
chrome.storage.local.get([type], (result) => {
if (result[type]) selectImageInGallery(result[type]);
});
}
function closeModal() {
modal.style.display = "none";
currentType = null;
selectedSrc = null;
}
const modalSaveBtn = document.getElementById("modal-save");
modalSaveBtn.addEventListener("click", async () => {
if (!currentType || !selectedSrc) {
closeModal();
return;
}
const slot = currentType;
const src = selectedSrc;
const originalLabel = modalSaveBtn.textContent;
modalSaveBtn.disabled = true;
modalSaveBtn.textContent = "Saving…";
try {
const dataUrl = await ensureDataUrl(src);
if (!dataUrl) {
alert(
"Couldn't prepare that image. It may have blocked cross-origin access — try uploading it from your device via Manage Images.",
);
return;
}
await new Promise((resolve) =>
chrome.storage.local.set({ [slot]: dataUrl }, resolve),
);
setPreview(slot, dataUrl);
closeModal();
} catch (err) {
console.error("Failed to save image:", err);
alert(
"Couldn't save that image: " +
(err && err.message ? err.message : "fetch failed.") +
"\nTip: download the image and add it via Manage Images instead.",
);
} finally {
modalSaveBtn.disabled = false;
modalSaveBtn.textContent = originalLabel;
}
});
document.getElementById("modal-none").addEventListener("click", () => {
if (currentType) {
chrome.storage.local.remove(currentType);
setPreview(currentType, null);
}
closeModal();
});
document.getElementById("modal-cancel").addEventListener("click", closeModal);
document.addEventListener("click", (e) => {
const option = e.target.closest(".image-option[data-type]");
if (option) openModal(option.dataset.type);
});