-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
350 lines (275 loc) · 7.76 KB
/
content.js
File metadata and controls
350 lines (275 loc) · 7.76 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
let exportInProgress = false;
let requestCounter = 0;
const pendingRequests = new Map();
window.addEventListener("message", (event) => {
if (event.source !== window) {
return;
}
const data = event.data;
if (!data || data.source !== "arena-export-page" || data.type !== "EXTRACT_REACT_MARKDOWN_RESULT") {
return;
}
const requestId = data.requestId;
const pending = pendingRequests.get(requestId);
if (!pending) {
return;
}
pendingRequests.delete(requestId);
pending.resolve(data.results || {});
});
chrome.runtime.onMessage.addListener((message) => {
if (message?.type === "ARENA_EXPORT_START") {
void runExport();
}
});
function sanitizeFileName(value) {
return (
String(value || "")
.replace(/[<>:"/\\|?*\x00-\x1F]/g, "_")
.trim()
.slice(0, 120) || "arena-dialog"
);
}
function getConversationIdFromUrl() {
const match = location.pathname.match(/\/c\/([^/]+)/i);
if (match) {
return match[1];
}
const parts = location.pathname.split("/").filter(Boolean);
return parts[parts.length - 1] || "arena-dialog";
}
function buildFolderName() {
return sanitizeFileName(getConversationIdFromUrl());
}
function normalizeMarkdown(text) {
return `${String(text ?? "")
.replace(/\r\n/g, "\n")
.trimEnd()}\n`;
}
function showToast(text) {
let toast = document.getElementById("__arena_export_toast__");
if (!toast) {
toast = document.createElement("div");
toast.id = "__arena_export_toast__";
Object.assign(toast.style, {
position: "fixed",
right: "16px",
bottom: "16px",
zIndex: "2147483647",
maxWidth: "420px",
background: "rgba(17, 24, 39, 0.95)",
color: "#ffffff",
padding: "10px 14px",
borderRadius: "10px",
fontSize: "13px",
lineHeight: "1.4",
fontFamily: "system-ui, sans-serif",
boxShadow: "0 10px 30px rgba(0, 0, 0, 0.25)",
transition: "opacity 0.2s ease",
opacity: "0",
pointerEvents: "none",
});
document.documentElement.appendChild(toast);
}
toast.textContent = text;
toast.style.opacity = "1";
window.clearTimeout(showToast._timer);
showToast._timer = window.setTimeout(() => {
toast.style.opacity = "0";
}, 3000);
}
showToast._timer = 0;
function hasCopyIcon(button) {
const paths = Array.from(button.querySelectorAll("svg path")).map((node) => node.getAttribute("d") || "");
const hasFirstPath = paths.some((d) => d.includes("M19.4 20H9.6"));
const hasSecondPath = paths.some((d) => d.includes("M15 9V4.6"));
return hasFirstPath && hasSecondPath;
}
function classifyMessageCopyButton(button) {
if (button.closest("[data-code-block='true']")) {
return null;
}
const classText = button.getAttribute("class") || "";
const isAssistantButton = button.getAttribute("data-slot") === "tooltip-trigger" && classText.includes("size-3") && hasCopyIcon(button);
const isUserButton = classText.includes("group-hover:opacity-100") && classText.includes("size-6") && hasCopyIcon(button);
if (isUserButton) {
return "user";
}
if (isAssistantButton) {
return "assistant";
}
return null;
}
function getMessageCopyButtons() {
const root = document.querySelector("main") || document.body;
const buttons = Array.from(root.querySelectorAll("button"));
return buttons
.map((button) => ({
button,
role: classifyMessageCopyButton(button),
}))
.filter((item) => item.role);
}
function countMessageCopyButtonsInside(root) {
let count = 0;
for (const button of root.querySelectorAll("button")) {
if (classifyMessageCopyButton(button)) {
count += 1;
}
}
return count;
}
function getNodeTextLength(node) {
return String(node?.innerText || node?.textContent || "")
.replace(/\s+/g, " ")
.trim().length;
}
function findMessageContainer(button) {
let node = button.parentElement;
let best = null;
while (node && node !== document.body && node !== document.documentElement) {
const copyCount = countMessageCopyButtonsInside(node);
const textLength = getNodeTextLength(node);
if (copyCount === 1 && textLength > 0) {
best = node;
} else if (copyCount > 1 && best) {
break;
}
node = node.parentElement;
}
return best;
}
function compareNodesInDocumentOrder(a, b) {
if (a === b) {
return 0;
}
const position = a.compareDocumentPosition(b);
if (position & Node.DOCUMENT_POSITION_FOLLOWING) {
return -1;
}
if (position & Node.DOCUMENT_POSITION_PRECEDING) {
return 1;
}
return 0;
}
function getVisualPosition(node) {
const rect = node.getBoundingClientRect();
return {
top: rect.top + window.scrollY,
left: rect.left + window.scrollX,
};
}
function sortEntriesByVisualOrder(entries) {
return entries.slice().sort((a, b) => {
const aPos = getVisualPosition(a.root);
const bPos = getVisualPosition(b.root);
if (Math.abs(aPos.top - bPos.top) > 4) {
return aPos.top - bPos.top;
}
if (Math.abs(aPos.left - bPos.left) > 4) {
return aPos.left - bPos.left;
}
return compareNodesInDocumentOrder(a.root, b.root);
});
}
function requestReactMarkdown(items) {
const requestId = `arena-export-${Date.now()}-${++requestCounter}`;
return new Promise((resolve, reject) => {
const timeoutId = window.setTimeout(() => {
pendingRequests.delete(requestId);
reject(new Error("Page bridge timeout"));
}, 5000);
pendingRequests.set(requestId, {
resolve: (result) => {
window.clearTimeout(timeoutId);
resolve(result);
},
});
window.postMessage(
{
source: "arena-export-content",
type: "EXTRACT_REACT_MARKDOWN",
requestId,
items,
},
"*",
);
});
}
async function runExport() {
if (exportInProgress) {
showToast("Export is already underway");
return;
}
exportInProgress = true;
try {
const buttonItems = getMessageCopyButtons();
if (buttonItems.length === 0) {
throw new Error("Didn't find a copy message button");
}
const entries = [];
const usedRoots = new Set();
for (const item of buttonItems) {
const root = findMessageContainer(item.button);
if (!root || usedRoots.has(root)) {
continue;
}
usedRoots.add(root);
entries.push({
root,
role: item.role,
});
}
const orderedEntries = sortEntriesByVisualOrder(entries);
if (orderedEntries.length === 0) {
throw new Error("Could not find message containers");
}
const requestItems = orderedEntries.map((entry, index) => {
const id = `arena-export-msg-${index + 1}`;
entry.root.setAttribute("data-arena-export-id", id);
return { id };
});
showToast(`Exporting ${orderedEntries.length} messages...`);
const results = await requestReactMarkdown(requestItems);
const files = [];
const debugRows = [];
for (let i = 0; i < orderedEntries.length; i += 1) {
const id = requestItems[i].id;
const result = results[id];
if (!result?.ok || !result.text) {
console.log("[arena-export] Failed container:", orderedEntries[i].root);
console.log("[arena-export] Top candidates:", result?.top || result);
throw new Error(`Didn't find Markdown in React props for message ${i + 1}`);
}
files.push({
name: `${i + 1}.md`,
text: normalizeMarkdown(result.text),
});
debugRows.push({
n: i + 1,
role: orderedEntries[i].role,
score: result.score,
path: result.path,
preview: String(result.text).slice(0, 140).replace(/\n/g, "\\n"),
});
}
console.table(debugRows);
const downloadResult = await chrome.runtime.sendMessage({
type: "ARENA_EXPORT_DOWNLOAD",
folderName: buildFolderName(),
files,
});
if (!downloadResult?.ok) {
throw new Error(downloadResult?.error || "Failed to download files");
}
showToast(`Done: ${files.length} files`);
} catch (error) {
console.error("[arena-export]", error);
showToast(`Error: ${error instanceof Error ? error.message : String(error)}`);
} finally {
for (const node of document.querySelectorAll("[data-arena-export-id]")) {
node.removeAttribute("data-arena-export-id");
}
exportInProgress = false;
}
}