-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexport-report.js
More file actions
1749 lines (1544 loc) · 56.4 KB
/
export-report.js
File metadata and controls
1749 lines (1544 loc) · 56.4 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
import {
getAppSettings,
getMediaBlob,
getThumbnailBlob,
listFolders,
listItems,
updateMediaMetadata,
updateAppSettings
} from "./src/storage/storage.js";
import { installRuntimeGuard } from "./src/shared/runtime-guard.js";
const filterSummary = document.getElementById("filterSummary");
const stats = document.getElementById("stats");
const itemsContainer = document.getElementById("itemsContainer");
const status = document.getElementById("status");
const refreshBtn = document.getElementById("refreshBtn");
const includeSourceUrlInReport = document.getElementById("includeSourceUrlInReport");
const includeBrowserInfoInReport = document.getElementById("includeBrowserInfoInReport");
const copySummaryBtn = document.getElementById("copySummaryBtn");
const copyHtmlBtn = document.getElementById("copyHtmlBtn");
const copyImageBtn = document.getElementById("copyImageBtn");
const downloadMarkdownBtn = document.getElementById("downloadMarkdownBtn");
const downloadTextBtn = document.getElementById("downloadTextBtn");
const downloadHtmlBtn = document.getElementById("downloadHtmlBtn");
const downloadHtmlSummaryBtn = document.getElementById("downloadHtmlSummaryBtn");
const downloadPdfBtn = document.getElementById("downloadPdfBtn");
const downloadPngBtn = document.getElementById("downloadPngBtn");
const downloadJpgBtn = document.getElementById("downloadJpgBtn");
const downloadWebpBtn = document.getElementById("downloadWebpBtn");
const downloadJsonBtn = document.getElementById("downloadJsonBtn");
const downloadZipBtn = document.getElementById("downloadZipBtn");
const printBtn = document.getElementById("printBtn");
const jiraUrl = document.getElementById("jiraUrl");
const githubIssueUrl = document.getElementById("githubIssueUrl");
const trelloCardUrl = document.getElementById("trelloCardUrl");
const shareSubject = document.getElementById("shareSubject");
const shareNotes = document.getElementById("shareNotes");
const openJiraBtn = document.getElementById("openJiraBtn");
const openGithubBtn = document.getElementById("openGithubBtn");
const openTrelloBtn = document.getElementById("openTrelloBtn");
const openMailBtn = document.getElementById("openMailBtn");
const state = {
filters: parseFilters(),
folders: [],
items: [],
filteredItems: [],
appSettings: null,
excludedItemIds: new Set()
};
const encoder = new TextEncoder();
const crcTable = buildCrcTable();
setup().catch((error) => {
console.error(error);
setStatus("Failed to load Send View.", true);
});
async function setup() {
await loadSettingsIntoForm();
bindEvents();
await refresh();
}
function bindEvents() {
refreshBtn?.addEventListener("click", refresh);
copySummaryBtn?.addEventListener("click", copySummary);
copyHtmlBtn?.addEventListener("click", copyHtmlSnippet);
copyImageBtn?.addEventListener("click", copyPrimaryImageFromSelection);
downloadMarkdownBtn?.addEventListener("click", downloadMarkdown);
downloadTextBtn?.addEventListener("click", downloadTextSummary);
downloadHtmlBtn?.addEventListener("click", downloadHtmlReport);
downloadHtmlSummaryBtn?.addEventListener("click", downloadHtmlSummary);
downloadPdfBtn?.addEventListener("click", downloadPdfReport);
downloadPngBtn?.addEventListener("click", () => downloadPrimaryImageAs("png"));
downloadJpgBtn?.addEventListener("click", () => downloadPrimaryImageAs("jpg"));
downloadWebpBtn?.addEventListener("click", () => downloadPrimaryImageAs("webp"));
downloadJsonBtn?.addEventListener("click", downloadJsonMetadata);
downloadZipBtn?.addEventListener("click", downloadZipBundle);
printBtn?.addEventListener("click", printSelection);
[jiraUrl, githubIssueUrl, trelloCardUrl, shareSubject, shareNotes].forEach((field) => {
field?.addEventListener("change", saveShareSettings);
});
[includeSourceUrlInReport, includeBrowserInfoInReport].forEach((field) => {
field?.addEventListener("change", async () => {
await saveShareSettings();
renderItems();
});
});
openJiraBtn?.addEventListener("click", openJiraDraft);
openGithubBtn?.addEventListener("click", openGithubDraft);
openTrelloBtn?.addEventListener("click", openTrelloDraft);
openMailBtn?.addEventListener("click", openMailDraft);
}
async function loadSettingsIntoForm() {
const appSettings = await getAppSettings();
state.appSettings = appSettings;
const settings = appSettings.shareSettings || {};
jiraUrl.value = sanitizeText(settings.jiraUrl || "");
githubIssueUrl.value = sanitizeText(settings.githubIssueUrl || "");
trelloCardUrl.value = sanitizeText(settings.trelloCardUrl || "");
shareSubject.value = sanitizeText(settings.shareSubject || "Olho Send View Report");
shareNotes.value = sanitizeText(settings.shareNotes || "");
includeSourceUrlInReport.checked = settings.includeSourceUrlInReport !== false;
includeBrowserInfoInReport.checked = Boolean(settings.includeBrowserInfoInReport);
}
async function saveShareSettings() {
const latest = await getAppSettings();
const existing = latest.shareSettings || {};
const next = {
...existing,
jiraUrl: sanitizeText(jiraUrl.value),
githubIssueUrl: sanitizeText(githubIssueUrl.value),
trelloCardUrl: sanitizeText(trelloCardUrl.value),
shareSubject: sanitizeText(shareSubject.value || "Olho Send View Report"),
shareNotes: sanitizeText(shareNotes.value),
includeSourceUrlInReport: includeSourceUrlInReport.checked,
includeBrowserInfoInReport: includeBrowserInfoInReport.checked
};
const saved = await updateAppSettings({ shareSettings: next });
state.appSettings = saved;
}
function parseFilters() {
const params = new URLSearchParams(window.location.search);
return {
folderId: params.get("folderId") || "",
query: (params.get("query") || "").trim().toLowerCase(),
tag: (params.get("tag") || "").trim(),
sort: params.get("sort") || "newest"
};
}
function sanitizeText(value) {
return String(value || "")
.replace(/[\u0000-\u001f\u007f]/g, " ")
.trim();
}
function escapeHtml(value) {
return String(value || "")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/\"/g, """)
.replace(/'/g, "'");
}
function formatBytes(bytes) {
const size = Number(bytes || 0);
if (size < 1024) return `${size} B`;
if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;
if (size < 1024 * 1024 * 1024) return `${(size / (1024 * 1024)).toFixed(1)} MB`;
return `${(size / (1024 * 1024 * 1024)).toFixed(2)} GB`;
}
function formatDate(value) {
return new Date(value).toLocaleString();
}
function extensionFromItem(item) {
const mime = String(item.metadata?.mimeType || "").toLowerCase();
if (mime.includes("png")) return "png";
if (mime.includes("jpeg") || mime.includes("jpg")) return "jpg";
if (mime.includes("webp")) return "webp";
if (mime.includes("pdf")) return "pdf";
if (mime.includes("webm")) return "webm";
if (mime.includes("mp4")) return "mp4";
if (mime.includes("gif")) return "gif";
return item.type === "video" ? "webm" : "png";
}
function itemTitle(item) {
return sanitizeText(item.metadata?.title || `Untitled ${item.type}`) || `Untitled ${item.type}`;
}
function itemTags(item) {
return Array.isArray(item.metadata?.tags) ? item.metadata.tags.map((tag) => sanitizeText(tag)).filter(Boolean) : [];
}
function safeFilename(value) {
return sanitizeText(value)
.replace(/[^a-z0-9-_ ]+/gi, "")
.replace(/\s+/g, "-")
.replace(/-+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 60) || "item";
}
function folderNameById(folderId) {
const folder = state.folders.find((entry) => entry.id === folderId);
return folder?.name || "In Sight";
}
function filterItems(items) {
let filtered = [...items].filter((item) => !state.excludedItemIds.has(item.id));
if (state.filters.folderId) {
filtered = filtered.filter((item) => item.folderId === state.filters.folderId);
}
if (state.filters.query) {
filtered = filtered.filter((item) => itemTitle(item).toLowerCase().includes(state.filters.query));
}
if (state.filters.tag) {
filtered = filtered.filter((item) => itemTags(item).includes(state.filters.tag));
}
filtered.sort((a, b) => {
if (state.filters.sort === "oldest") {
return new Date(a.createdAt) - new Date(b.createdAt);
}
if (state.filters.sort === "title") {
return itemTitle(a).localeCompare(itemTitle(b));
}
return new Date(b.createdAt) - new Date(a.createdAt);
});
return filtered;
}
function setStatus(message, isError = false) {
status.textContent = message;
status.style.borderColor = isError ? "rgba(248, 113, 113, 0.8)" : "rgba(108, 184, 255, 0.6)";
status.style.color = isError ? "#fecaca" : "#dbeafe";
}
installRuntimeGuard({
onError(message) {
setStatus(`Unexpected error: ${message}`, true);
}
});
function renderStats() {
const totalBytes = state.filteredItems.reduce((sum, item) => sum + Number(item.metadata?.sizeBytes || 0), 0);
const imageCount = state.filteredItems.filter((item) => item.type === "image").length;
const videoCount = state.filteredItems.filter((item) => item.type === "video").length;
const tiles = [
{ label: "Items", value: String(state.filteredItems.length) },
{ label: "Screenshots", value: String(imageCount) },
{ label: "Recordings", value: String(videoCount) },
{ label: "Total Size", value: formatBytes(totalBytes) }
];
stats.innerHTML = "";
tiles.forEach((tile) => {
const box = document.createElement("div");
box.className = "stat";
box.innerHTML = `<div class="label">${escapeHtml(tile.label)}</div><div class="value">${escapeHtml(tile.value)}</div>`;
stats.append(box);
});
}
function renderFilterSummary() {
const parts = [];
if (state.filters.folderId) {
parts.push(`Folder: ${folderNameById(state.filters.folderId)}`);
}
if (state.filters.query) {
parts.push(`Query: ${state.filters.query}`);
}
if (state.filters.tag) {
parts.push(`Tag: ${state.filters.tag}`);
}
parts.push(`Sort: ${state.filters.sort}`);
filterSummary.textContent = parts.join(" | ");
}
function sanitizeUrlLike(value) {
const text = sanitizeText(value);
if (!text) return "";
if (/^(chrome|about|edge|devtools):\/\//i.test(text)) return "";
return text;
}
function getBrowserInfo() {
if (typeof navigator === "undefined") return "";
const ua = sanitizeText(navigator.userAgent || "");
const platform = sanitizeText(navigator.platform || "");
return [ua, platform].filter(Boolean).join(" | ");
}
function inferAnnotationSummary(metadata = {}) {
if (sanitizeText(metadata.annotationSummary)) {
return sanitizeText(metadata.annotationSummary);
}
const project = metadata.olhoProject;
if (!project || !Array.isArray(project.actions) || !project.actions.length) {
return "";
}
const counts = new Map();
project.actions.forEach((action) => {
const type = sanitizeText(action?.type || "annotation");
if (!type) return;
counts.set(type, (counts.get(type) || 0) + 1);
});
if (!counts.size) return "";
return [...counts.entries()]
.map(([type, count]) => `${type}: ${count}`)
.join(", ");
}
function reportEntryFromItem(item) {
const metadata = item.metadata && typeof item.metadata === "object" ? item.metadata : {};
const includeSourceUrl = includeSourceUrlInReport.checked;
const includeBrowserInfo = includeBrowserInfoInReport.checked;
const sourcePageTitle = sanitizeText(
metadata.sourcePageTitle ||
metadata.pageTitle ||
metadata.capturePageTitle ||
""
);
const sourceUrl = sanitizeUrlLike(
metadata.sourceUrl ||
metadata.pageUrl ||
metadata.capturePageUrl ||
""
);
const captureType = sanitizeText(metadata.sourceType || item.type || "capture");
const title = itemTitle(item);
const extension = extensionFromItem(item);
const filename = `${safeFilename(title)}.${extension}`;
const noteText = sanitizeText(metadata.notes || metadata.note || "");
const annotations = inferAnnotationSummary(metadata);
const tags = itemTags(item);
return {
id: item.id,
title,
captureDate: new Date(item.createdAt).toISOString(),
captureType,
sourcePageTitle: sourcePageTitle || "",
sourceUrlRaw: sourceUrl,
sourceUrl: includeSourceUrl ? sourceUrl : "",
sourceUrlStored: Boolean(sourceUrl),
filename,
notes: noteText,
tags,
browserInfo: includeBrowserInfo ? getBrowserInfo() : "",
annotationSummary: annotations,
kind: item.type,
folderName: folderNameById(item.folderId),
mimeType: sanitizeText(metadata.mimeType || ""),
sizeBytes: Number(metadata.sizeBytes || 0),
durationMs: Number(metadata.durationMs || 0),
privacyNote:
"Generated locally by Olho. No upload, no hosted links, and no remote processing."
};
}
function buildReportEntries() {
return state.filteredItems.map(reportEntryFromItem);
}
function summaryBodyText(entries) {
const notes = sanitizeText(shareNotes.value || "");
const lines = [];
lines.push("Olho Send View Report");
lines.push(`Generated: ${new Date().toISOString()}`);
lines.push(`Items: ${entries.length}`);
lines.push(`Screenshots: ${entries.filter((entry) => entry.kind === "image").length}`);
lines.push(`Recordings: ${entries.filter((entry) => entry.kind === "video").length}`);
lines.push("");
lines.push("Attach files manually.");
if (notes) {
lines.push(`Notes: ${notes}`);
}
lines.push("");
entries.forEach((entry, index) => {
lines.push(`${index + 1}. ${entry.title}`);
lines.push(` Capture date: ${entry.captureDate}`);
lines.push(` Capture type: ${entry.captureType}`);
lines.push(` Source page title: ${entry.sourcePageTitle || "(not available)"}`);
if (includeSourceUrlInReport.checked) {
if (entry.sourceUrl) {
lines.push(` Source URL: ${entry.sourceUrl}`);
} else if (entry.sourceUrlStored) {
lines.push(" Source URL: (stored but filtered)");
} else {
lines.push(" Source URL: (not stored)");
}
} else {
lines.push(" Source URL: (excluded from report)");
}
lines.push(` Filename: ${entry.filename}`);
lines.push(` Tags: ${entry.tags.length ? entry.tags.join(", ") : "(none)"}`);
lines.push(` Notes: ${entry.notes || "(none)"}`);
lines.push(` Annotation summary: ${entry.annotationSummary || "(none)"}`);
if (includeBrowserInfoInReport.checked) {
lines.push(` Browser info: ${entry.browserInfo || "(not available)"}`);
}
lines.push(` Privacy note: ${entry.privacyNote}`);
lines.push("");
});
return lines.join("\n");
}
function markdownSummary(entries) {
const notes = sanitizeText(shareNotes.value || "");
const lines = [];
lines.push("# Olho Send View Report");
lines.push(`Generated: ${new Date().toISOString()}`);
lines.push("");
lines.push(`- Items: ${entries.length}`);
lines.push(`- Screenshots: ${entries.filter((entry) => entry.kind === "image").length}`);
lines.push(`- Recordings: ${entries.filter((entry) => entry.kind === "video").length}`);
lines.push("- Attach files manually.");
if (notes) {
lines.push(`- Notes: ${notes}`);
}
lines.push("");
lines.push("## Entries");
lines.push("");
entries.forEach((entry, index) => {
lines.push(`### ${index + 1}. ${entry.title}`);
lines.push(`- Capture date: ${entry.captureDate}`);
lines.push(`- Capture type: ${entry.captureType}`);
lines.push(`- Source page title: ${entry.sourcePageTitle || "(not available)"}`);
lines.push(`- Source URL: ${entry.sourceUrl || "(not stored or excluded)"}`);
lines.push(`- Filename: ${entry.filename}`);
lines.push(`- Notes: ${entry.notes || "(none)"}`);
lines.push(`- Tags: ${entry.tags.length ? entry.tags.join(", ") : "(none)"}`);
lines.push(`- Browser info: ${entry.browserInfo || "(excluded)"}`);
lines.push(`- Annotation summary: ${entry.annotationSummary || "(none)"}`);
lines.push(`- Privacy note: ${entry.privacyNote}`);
lines.push("");
});
return lines.join("\n");
}
function htmlSummaryFragment(entries) {
const rows = entries
.map((entry) => {
return `<tr>
<td>${escapeHtml(entry.title)}</td>
<td>${escapeHtml(entry.captureDate)}</td>
<td>${escapeHtml(entry.captureType)}</td>
<td>${escapeHtml(entry.sourcePageTitle || "-")}</td>
<td>${escapeHtml(entry.sourceUrl || "-")}</td>
<td>${escapeHtml(entry.filename)}</td>
<td>${escapeHtml(entry.notes || "-")}</td>
<td>${escapeHtml(entry.tags.join(", ") || "-")}</td>
<td>${escapeHtml(entry.browserInfo || "-")}</td>
<td>${escapeHtml(entry.annotationSummary || "-")}</td>
</tr>`;
})
.join("");
return `<section>
<h2>Olho Send View Report</h2>
<p>Generated: ${escapeHtml(new Date().toISOString())}</p>
<p>Attach files manually. Generated locally by Olho.</p>
<table border="1" cellpadding="6" cellspacing="0">
<thead>
<tr>
<th>Title</th>
<th>Capture Date</th>
<th>Capture Type</th>
<th>Source Page Title</th>
<th>Source URL</th>
<th>Filename</th>
<th>Notes</th>
<th>Tags</th>
<th>Browser Info</th>
<th>Annotation Summary</th>
</tr>
</thead>
<tbody>${rows}</tbody>
</table>
</section>`;
}
function fullReportDocument(entries) {
const notes = sanitizeText(shareNotes.value || "");
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Olho Send View Report</title>
<style>
body { font-family: "Segoe UI", Arial, sans-serif; margin: 24px; color: #111827; }
h1, h2 { margin-bottom: 8px; }
p { margin: 4px 0; }
table { border-collapse: collapse; width: 100%; margin-top: 12px; }
th, td { border: 1px solid #d1d5db; text-align: left; padding: 8px; vertical-align: top; }
th { background: #eef2ff; }
code { background: #f3f4f6; padding: 2px 4px; border-radius: 4px; }
</style>
</head>
<body>
<h1>Olho Send View Report</h1>
<p><strong>Generated:</strong> ${escapeHtml(new Date().toISOString())}</p>
<p><strong>Items:</strong> ${entries.length}</p>
<p><strong>Filters:</strong> ${escapeHtml(filterSummary.textContent || "none")}</p>
<p><strong>Local privacy note:</strong> Generated locally by Olho. No upload, no hosted links, and no remote processing.</p>
<p><strong>Manual sharing:</strong> Attach files manually.</p>
${notes ? `<h2>Notes</h2><p>${escapeHtml(notes)}</p>` : ""}
${htmlSummaryFragment(entries)}
</body>
</html>`;
}
function reportJson(entries) {
return {
title: "Olho Send View Report",
generatedAt: new Date().toISOString(),
filterSummary: filterSummary.textContent || "",
notes: sanitizeText(shareNotes.value || ""),
includeSourceUrlInReport: includeSourceUrlInReport.checked,
includeBrowserInfoInReport: includeBrowserInfoInReport.checked,
privacy:
"Generated locally by Olho. No upload, no hosted links, and no remote processing.",
attachFilesManually: true,
count: entries.length,
items: entries
};
}
function shareBody(entries) {
const text = summaryBodyText(entries);
return `${text}\n\nAttach files manually.`;
}
function downloadBlob(blob, filename) {
const url = URL.createObjectURL(blob);
return chrome.downloads
.download({
url,
filename,
saveAs: true
})
.finally(() => {
setTimeout(() => URL.revokeObjectURL(url), 10_000);
});
}
function cleanBaseUrl(url) {
return sanitizeText(url).replace(/\/+$/, "");
}
function ensureHttpUrl(url) {
if (!url) return "";
if (/^https?:\/\//i.test(url)) return url;
return `https://${url}`;
}
function buildIssueSubject() {
return sanitizeText(shareSubject.value || "Olho Send View Report");
}
function createCopyFilename(item) {
return `Olho/${safeFilename(itemTitle(item))}-${Date.now()}.${extensionFromItem(item)}`;
}
async function openEditorAndCopy(item, options = { copyAfterOpen: true }) {
if (!item?.id) {
setStatus("This item cannot be opened in editor copy mode.", true);
return;
}
const query = options.copyAfterOpen ? "©=1" : "";
const url = chrome.runtime.getURL(`editor.html?itemId=${encodeURIComponent(item.id)}${query}`);
await chrome.tabs.create({ url });
setStatus(options.copyAfterOpen ? "Editor opened for copy action." : "Editor opened.");
}
function normalizeUserUrlInput(value) {
const raw = sanitizeText(value);
if (!raw) return "";
if (/^(chrome|about|edge|devtools):\/\//i.test(raw)) {
return "";
}
if (/^https?:\/\//i.test(raw)) {
return raw;
}
return `https://${raw}`;
}
async function promptAndSetSourceUrl(item) {
const current = sanitizeUrlLike(item?.metadata?.sourceUrl || item?.metadata?.pageUrl || "");
const nextInput = window.prompt(
"Set source URL for this capture. Leave blank to clear it.",
current
);
if (nextInput === null) return;
const next = normalizeUserUrlInput(nextInput);
try {
await updateMediaMetadata(item.id, {
metadata: {
sourceUrl: next
}
});
setStatus(next ? "Source URL saved for this item." : "Source URL cleared for this item.");
await refresh();
} catch (error) {
console.error(error);
setStatus("Could not update source URL.", true);
}
}
async function downloadItemFile(item) {
const blob = await getMediaBlob(item.id);
if (!(blob instanceof Blob)) {
setStatus("Source file is unavailable for this item.", true);
return;
}
await downloadBlob(blob, createCopyFilename(item));
setStatus("File download started.");
}
function primaryImageItem() {
return (
state.filteredItems.find((item) => item.type === "image") ||
state.items.find((item) => item.type === "image") ||
null
);
}
async function convertImageBlobFormat(blob, format) {
if (!(blob instanceof Blob)) {
throw new Error("Image source is unavailable.");
}
if (format === "png") {
if (blob.type === "image/png") return blob;
}
const bitmap = await createImageBitmap(blob);
const canvas = makeCanvas(bitmap.width, bitmap.height);
const context = canvas.getContext("2d");
if (!context) {
bitmap.close?.();
throw new Error("Canvas is unavailable for image conversion.");
}
context.drawImage(bitmap, 0, 0);
bitmap.close?.();
if (format === "png") {
return canvasToBlob(canvas, "image/png");
}
if (format === "jpg") {
return canvasToBlob(canvas, "image/jpeg", 0.92);
}
if (format === "webp") {
return canvasToBlob(canvas, "image/webp", 0.9);
}
throw new Error(`Unsupported image export format: ${format}`);
}
async function downloadPrimaryImageAs(format) {
const item = primaryImageItem();
if (!item) {
setStatus("No screenshot is available for this export.", true);
return;
}
const source = await getMediaBlob(item.id);
if (!(source instanceof Blob)) {
setStatus("Screenshot source is unavailable.", true);
return;
}
try {
const blob = await convertImageBlobFormat(source, format);
const ext = format === "jpg" ? "jpg" : format;
await downloadBlob(blob, `Olho/${safeFilename(itemTitle(item))}-${Date.now()}.${ext}`);
setStatus(`${format.toUpperCase()} download started.`);
} catch (error) {
console.error(error);
setStatus(`${format.toUpperCase()} export failed.`, true);
}
}
async function copyPrimaryImageFromSelection() {
const item = primaryImageItem();
if (!item) {
setStatus("No screenshot is available to copy.", true);
return;
}
await copyItemFile(item);
}
function buildSingleImagePdfBlob(jpegBytes, width, height) {
const chunks = [];
const offsets = [0];
let offset = 0;
const push = (bytes) => {
chunks.push(bytes);
offset += bytes.length;
};
const pushText = (text) => push(encoder.encode(text));
pushText("%PDF-1.4\n");
offsets[1] = offset;
pushText("1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
offsets[2] = offset;
pushText("2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
offsets[3] = offset;
pushText(
`3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${width} ${height}] /Resources << /XObject << /Im0 4 0 R >> >> /Contents 5 0 R >>\nendobj\n`
);
offsets[4] = offset;
pushText(
`4 0 obj\n<< /Type /XObject /Subtype /Image /Width ${width} /Height ${height} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length ${jpegBytes.length} >>\nstream\n`
);
push(jpegBytes);
pushText("\nendstream\nendobj\n");
const content = encoder.encode(`q\n${width} 0 0 ${height} 0 0 cm\n/Im0 Do\nQ\n`);
offsets[5] = offset;
pushText(`5 0 obj\n<< /Length ${content.length} >>\nstream\n`);
push(content);
pushText("\nendstream\nendobj\n");
const xrefStart = offset;
pushText("xref\n0 6\n");
pushText("0000000000 65535 f \n");
for (let i = 1; i <= 5; i += 1) {
pushText(`${String(offsets[i]).padStart(10, "0")} 00000 n \n`);
}
pushText(`trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n${xrefStart}\n%%EOF`);
return new Blob([joinUint8(chunks)], { type: "application/pdf" });
}
async function tryLegacyImageClipboardCopy(blob) {
if (!(blob instanceof Blob)) return false;
if (!blob.type.startsWith("image/")) return false;
if (typeof document === "undefined" || typeof document.execCommand !== "function") return false;
const url = URL.createObjectURL(blob);
const container = document.createElement("div");
container.contentEditable = "true";
container.style.position = "fixed";
container.style.left = "-9999px";
container.style.top = "0";
container.style.opacity = "0";
container.setAttribute("aria-hidden", "true");
const image = document.createElement("img");
image.src = url;
image.alt = "";
container.append(image);
document.body.append(container);
try {
await new Promise((resolve, reject) => {
image.onload = () => resolve();
image.onerror = () => reject(new Error("Failed to load image for legacy clipboard copy."));
});
const selection = window.getSelection();
if (!selection) return false;
const range = document.createRange();
range.selectNodeContents(container);
selection.removeAllRanges();
selection.addRange(range);
const copied = document.execCommand("copy");
selection.removeAllRanges();
return Boolean(copied);
} catch (error) {
console.error(error);
return false;
} finally {
URL.revokeObjectURL(url);
container.remove();
}
}
async function copyItemFile(item) {
const blob = await getMediaBlob(item.id);
if (!(blob instanceof Blob)) {
setStatus("Source file is unavailable for this item.", true);
return;
}
try {
if (navigator.clipboard?.write && typeof ClipboardItem !== "undefined") {
const mimeType = blob.type || (item.type === "video" ? "video/webm" : "image/png");
const payload = {
[mimeType]: blob
};
if (!mimeType.startsWith("image/")) {
payload["application/octet-stream"] = blob;
}
await navigator.clipboard.write([new ClipboardItem(payload)]);
setStatus(`${item.type === "video" ? "Video" : "Image"} file copied to clipboard.`);
return;
}
const legacyCopied = await tryLegacyImageClipboardCopy(blob);
if (legacyCopied) {
setStatus("Image copied using legacy clipboard fallback.");
return;
}
} catch (error) {
console.error(error);
const legacyCopied = await tryLegacyImageClipboardCopy(blob);
if (legacyCopied) {
setStatus("Image copied using legacy clipboard fallback.");
return;
}
}
await downloadBlob(blob, createCopyFilename(item));
setStatus(
item.type === "video"
? "Clipboard video copy is not available in this environment. File downloaded for manual attachment."
: "Clipboard image copy is unavailable. File downloaded for manual attachment. Use Open Editor and Copy for another local copy attempt."
);
}
function renderItems() {
itemsContainer.innerHTML = "";
if (!state.filteredItems.length) {
const empty = document.createElement("p");
empty.className = "muted";
empty.textContent = "No items matched the current filters.";
itemsContainer.append(empty);
return;
}
const entriesById = new Map(buildReportEntries().map((entry) => [entry.id, entry]));
state.filteredItems.forEach((item) => {
const entry = entriesById.get(item.id);
const row = document.createElement("article");
row.className = "item-row";
row.setAttribute("role", "listitem");
const left = document.createElement("div");
left.className = "item-main";
const title = document.createElement("strong");
title.className = "item-title";
title.textContent = entry.title;
const meta = document.createElement("p");
meta.className = "item-meta";
meta.textContent = [
entry.captureType,
formatDate(entry.captureDate),
formatBytes(entry.sizeBytes || 0),
entry.durationMs ? `${Math.round(entry.durationMs / 1000)}s` : ""
]
.filter(Boolean)
.join(" | ");
const facts = document.createElement("div");
facts.className = "item-facts";
const factRows = [
["Source title", entry.sourcePageTitle || "(not available)"],
["Source URL", entry.sourceUrl || "(not stored or excluded)"],
["Filename", entry.filename],
["Tags", entry.tags.join(", ") || "(none)"],
["Annotation summary", entry.annotationSummary || "(none)"]
];
factRows.forEach(([label, value]) => {
const fact = document.createElement("p");
fact.className = "item-fact";
fact.innerHTML = `<span class="fact-label">${escapeHtml(label)}:</span> ${escapeHtml(value)}`;
facts.append(fact);
});
left.append(title, meta, facts);
const actions = document.createElement("div");
actions.className = "item-actions";
const primaryActions = document.createElement("div");
primaryActions.className = "item-primary-actions";
const secondaryActions = document.createElement("div");
secondaryActions.className = "item-secondary-actions";
const downloadBtn = document.createElement("button");
downloadBtn.type = "button";
downloadBtn.className = "ghost";
downloadBtn.textContent = "Download File";
downloadBtn.setAttribute("aria-label", `Download file for ${entry.title}`);
downloadBtn.addEventListener("click", () => {
downloadItemFile(item).catch((error) => {
console.error(error);
setStatus("File download failed.", true);
});
});
const copyBtn = document.createElement("button");
copyBtn.type = "button";
copyBtn.className = "ghost";
copyBtn.textContent = "Copy File";
copyBtn.setAttribute("aria-label", `Copy file for ${entry.title}`);
copyBtn.addEventListener("click", () => {
copyItemFile(item).catch((error) => {
console.error(error);
setStatus("File copy failed.", true);
});
});
primaryActions.append(downloadBtn);
if (item.type === "image") {
const openEditorBtn = document.createElement("button");
openEditorBtn.type = "button";
openEditorBtn.className = "ghost";
openEditorBtn.textContent = "Open Editor";
openEditorBtn.setAttribute("aria-label", `Open editor for ${entry.title}`);
openEditorBtn.addEventListener("click", () => {
openEditorAndCopy(item, { copyAfterOpen: false }).catch((error) => {
console.error(error);
setStatus("Could not open editor.", true);
});
});
primaryActions.append(openEditorBtn);
}
const sourceBtn = document.createElement("button");
sourceBtn.type = "button";
sourceBtn.className = "ghost";
sourceBtn.textContent = "Set Source URL";
sourceBtn.setAttribute("aria-label", `Set source URL for ${entry.title}`);
sourceBtn.addEventListener("click", () => {
promptAndSetSourceUrl(item).catch((error) => {
console.error(error);
setStatus("Could not update source URL.", true);
});
});
const removeBtn = document.createElement("button");
removeBtn.type = "button";
removeBtn.className = "ghost";
removeBtn.textContent = "Remove";
removeBtn.setAttribute("aria-label", `Remove ${entry.title} from this export set`);
removeBtn.addEventListener("click", () => {
state.excludedItemIds.add(item.id);
state.filteredItems = filterItems(state.items);
renderFilterSummary();
renderStats();
renderItems();
setStatus("Item removed from current export set.");
});
const more = document.createElement("details");
more.className = "item-more-actions";
const summary = document.createElement("summary");
summary.textContent = "More actions";
secondaryActions.append(copyBtn, sourceBtn, removeBtn);
more.append(summary, secondaryActions);
actions.append(primaryActions, more);
row.append(left, actions);
itemsContainer.append(row);
});
}
async function copySummary() {
try {
const entries = buildReportEntries();
await navigator.clipboard.writeText(markdownSummary(entries));
setStatus("Send summary copied.");
} catch (error) {
console.error(error);
setStatus("Failed to copy summary.", true);
}
}
async function copyHtmlSnippet() {
try {
const entries = buildReportEntries();
const html = htmlSummaryFragment(entries);
const text = markdownSummary(entries);
if (window.ClipboardItem && navigator.clipboard?.write) {