-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
807 lines (698 loc) · 27.7 KB
/
Copy pathcontent.js
File metadata and controls
807 lines (698 loc) · 27.7 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
(function() {
// Generate a cryptographically secure token for cross-world message passing validation
const secureToken = (typeof crypto !== 'undefined' && crypto.randomUUID)
? crypto.randomUUID()
: Math.random().toString(36).substring(2) + Date.now().toString(36);
// Dynamically inject inject.js at document_start to establish fetch hooks in the MAIN world
try {
const script = document.createElement('script');
script.src = chrome.runtime.getURL('inject.js');
script.dataset.token = secureToken;
(document.head || document.documentElement).appendChild(script);
script.remove(); // Remove tag immediately to prevent page scripts from inspecting it
} catch (e) {
console.error('[Exporter] Failed to inject network interceptor:', e);
}
let container = null;
let fab = null;
let menu = null;
let statusDot = null;
let statusText = null;
// Active requests transaction map (prevents promise collisions and SPA race conditions)
const pendingRequests = {};
// Helper utility for asynchronous delays
const delay = ms => new Promise(res => setTimeout(res, ms));
// Security: Handle postMessage replies with strict origin and token validation
window.addEventListener('message', (event) => {
if (event.source !== window || event.origin !== window.location.origin) return;
const message = event.data;
if (message && message.type === 'OAI_EXPORT_RESPONSE') {
// Security Check: Ignore message if token doesn't match
if (message.token !== secureToken) return;
const { requestId, success, data, error } = message;
const request = pendingRequests[requestId];
if (request) {
clearTimeout(request.timeoutId);
delete pendingRequests[requestId];
// SPA Navigation check: Cancel if user navigated away while fetching
if (getActiveConversationId() !== request.conversationId) {
request.reject(new Error('Export cancelled: Navigation detected.'));
return;
}
if (success) {
request.resolve(data);
} else {
request.reject(new Error(error || 'Failed to fetch conversation data.'));
}
}
}
});
// Request the conversation data from inject.js running in MAIN world
function requestConversationData(conversationId, platform) {
const requestId = (typeof crypto !== 'undefined' && crypto.randomUUID)
? crypto.randomUUID()
: Math.random().toString(36).substring(2) + Date.now().toString(36);
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
if (pendingRequests[requestId]) {
delete pendingRequests[requestId];
reject(new Error('Request timed out. Please refresh the page and try again.'));
}
}, 8000);
pendingRequests[requestId] = { resolve, reject, timeoutId, conversationId };
window.postMessage({
type: 'OAI_EXPORT_REQUEST',
conversationId,
platform,
requestId,
token: secureToken
}, window.location.origin);
});
}
// Get active platform
function getPlatform() {
const host = window.location.hostname;
if (host.includes('claude.ai')) return 'claude';
if (host.includes('gemini.google.com')) return 'gemini';
return 'chatgpt';
}
// Get active conversation ID from the URL pathname
function getActiveConversationId() {
const platform = getPlatform();
if (platform === 'claude') {
const match = window.location.pathname.match(/\/chat\/([a-f0-9-]+)/);
return match ? match[1] : null;
}
if (platform === 'gemini') {
const path = window.location.pathname.replace(/\/+$/, '');
const segs = path.split('/').filter(Boolean);
if (segs.length === 0) return null;
let i = 0;
if (segs[0] === 'u' && /^\d+$/.test(segs[1] || '')) {
i = 2;
}
if (segs[i] === 'app' && segs[i + 1]) {
return segs[i + 1];
}
if (segs[i] === 'gem' && segs[i + 1] && segs[i + 2]) {
return segs[i + 2];
}
return null;
}
const match = window.location.pathname.match(/\/c\/([a-f0-9-]+)/);
return match ? match[1] : null;
}
// Sanitize filename for downloading
function sanitizeFilename(name) {
if (!name) return 'chatgpt-export';
return name
.trim()
.replace(/[\\/*?:"<>|]/g, '') // Remove invalid chars
.replace(/\s+/g, '-') // Replace spaces with dashes
.substring(0, 50); // Max 50 chars
}
// Set status indicator in the UI
function setStatus(state, text) {
if (!statusDot || !statusText) return;
statusDot.className = 'oai-exporter-status-dot';
statusText.innerText = text;
if (state === 'loading') {
statusDot.classList.add('loading');
} else if (state === 'error') {
statusDot.classList.add('error');
}
}
// Find the primary scrollable container in ChatGPT DOM (Section 17)
function findScrollContainer() {
const main = document.querySelector('main');
if (main) {
const scrollable = main.querySelector('.react-scroll-to-bottom--css-item-child') ||
main.querySelector('.overflow-y-auto') || main;
return scrollable;
}
return window;
}
// Parse complex content parts into markdown or readable placeholders (Section 8)
function parseContentPart(part) {
if (typeof part === 'string') return part;
if (typeof part === 'object' && part !== null) {
if (part.content_type === 'image') {
return `\n\n*Prompt: ${part.prompt || ''}*`;
}
if (part.name) {
return `[Attachment: ${part.name}]`;
}
if (part.content_type === 'citation') {
return `[Citation: ${part.text || 'Reference'}]`;
}
// General metadata placeholder instead of dumping JSON.stringify
return `[Media Content: ${part.content_type || 'Metadata object'}]`;
}
return '';
}
// Resolve and clean inline citation unicode tags (e.g. \uE200cite\uE202...)
function cleanCitations(text, contentRefs) {
if (!text) return '';
let cleanedText = text;
if (contentRefs && contentRefs.length > 0) {
for (const ref of contentRefs) {
if (ref.matched_text && cleanedText.includes(ref.matched_text)) {
let url = '';
let label = '';
if (ref.items && ref.items.length > 0) {
const firstItem = ref.items[0];
url = firstItem.url || (ref.safe_urls && ref.safe_urls[0]) || '';
label = firstItem.attribution || firstItem.title || 'Reference';
} else if (ref.safe_urls && ref.safe_urls.length > 0) {
url = ref.safe_urls[0];
try {
label = new URL(url).hostname.replace('www.', '');
} catch (e) {
label = 'Reference';
}
}
if (url && label) {
const parts = ref.matched_text.replace(/[\uE200\uE201]/g, '').split('\uE202');
const count = parts.length - 1;
const extra = count > 1 ? `+${count - 1}` : '';
const markdownLink = `[${label}${extra}](${url})`;
cleanedText = cleanedText.split(ref.matched_text).join(markdownLink);
}
}
}
}
// Strip any remaining/unresolved citation tags
cleanedText = cleanedText.replace(/\uE200[^\uE201]*\uE201/g, '');
// Strip leftover citation control characters to be absolutely clean
cleanedText = cleanedText.replace(/[\uE200-\uE202]/g, '');
return cleanedText;
}
// Normalize the raw API JSON data into the standardized internal message model (Section 7)
function normalizeConversation(data) {
const mapping = data.mapping;
const currentNodeId = data.current_node;
const conversationId = getActiveConversationId() || data.conversation_id || '';
const result = {
conversationId: conversationId,
title: data.title || 'ChatGPT Conversation',
url: window.location.href,
exportedAt: new Date().toISOString(),
source: 'network',
messages: [],
raw: data,
integrity: {
status: 'complete',
warnings: []
}
};
if (!mapping || !currentNodeId) {
result.integrity.status = 'incomplete';
result.integrity.warnings.push('Missing mapping or current_node in the payload.');
return result;
}
// Traverse the conversation tree backwards from current leaf node to root
const nodes = [];
let nodeId = currentNodeId;
while (nodeId) {
const node = mapping[nodeId];
if (node) {
nodes.push(node);
}
nodeId = node ? node.parent : null;
}
nodes.reverse(); // Convert to chronological order
if (nodes.length === 0) {
result.integrity.status = 'incomplete';
result.integrity.warnings.push('Traversed active message path is empty.');
return result;
}
let messageIndex = 0;
for (const node of nodes) {
const message = node.message;
if (!message) continue;
const role = message.author ? message.author.role : '';
if (role === 'system') continue;
const isCode = message.recipient === 'python' || (message.content && message.content.content_type === 'code');
// Skip non-Python tool messages (e.g. browser/web search tool queries)
if (role === 'tool' && !isCode) continue;
// Extract text content
let text = '';
if (message.content && message.content.parts) {
text = message.content.parts.map(part => parseContentPart(part)).join('\n');
}
// Handle empty messages running code interpreter
if (!text.trim() && role === 'assistant' && message.metadata && message.metadata.command) {
text = message.metadata.command;
}
// Clean citations in message text (Issue resolution for sentence-end garbage chars)
if (role === 'assistant' && message.metadata) {
text = cleanCitations(text, message.metadata.content_references);
} else if (text.includes('\uE200')) {
text = text.replace(/\uE200[^\uE201]*\uE201/g, '').replace(/[\uE200-\uE202]/g, '');
}
const contentType = isCode ? 'code' : (role === 'tool' ? 'tool' : 'markdown');
const normalizedMsg = {
id: message.id || node.id || `msg-${messageIndex}`,
parentId: node.parent || null,
index: messageIndex++,
role: role || 'unknown',
createdAt: message.create_time ? new Date(message.create_time * 1000).toISOString() : null,
content: [
{
type: contentType,
text: text,
language: isCode ? 'python' : null,
metadata: message.metadata || {}
}
],
raw: message,
hash: ''
};
result.messages.push(normalizedMsg);
}
// Perform Integrity Checks (Section 9)
const messages = result.messages;
if (messages.length === 0) {
result.integrity.status = 'incomplete';
result.integrity.warnings.push('No valid user, assistant, or tool messages resolved.');
} else {
// 2. Check if first message is from User
if (messages[0].role !== 'user') {
result.integrity.status = 'probably-complete';
result.integrity.warnings.push('Sequence anomaly: Conversation does not start with a User message.');
}
// 3. Check if last message leaves user hanging
const lastMsg = messages[messages.length - 1];
if (lastMsg.role === 'user') {
result.integrity.status = 'probably-complete';
result.integrity.warnings.push('Sequence anomaly: Conversation ends with a User message (missing final response).');
}
}
return result;
}
// Clean and convert Claude's XML <antArtifact> tags into standard Markdown elements
function cleanClaudeArtifacts(text) {
if (!text) return '';
let cleaned = text;
// Regex to find all antArtifact blocks and parse their attributes
const artifactRegex = /<antArtifact\s+([^>]*?)>([\s\S]*?)<\/antArtifact>/gi;
cleaned = cleaned.replace(artifactRegex, (match, attrsStr, content) => {
// Parse attributes
const attrs = {};
const attrRegex = /(\w+)="([^"]*)"/g;
let attrMatch;
while ((attrMatch = attrRegex.exec(attrsStr)) !== null) {
attrs[attrMatch[1].toLowerCase()] = attrMatch[2];
}
const type = attrs.type || '';
const title = attrs.title || 'Artifact';
const lang = attrs.language || '';
const code = content.trim();
// 1. SVG Vector graphics - Keep raw SVG tag and strip antArtifact wrapper so it renders in markdown
if (type === 'image/svg+xml' || code.startsWith('<svg')) {
return `\n\n<!-- Artifact: ${title} -->\n${code}\n\n`;
}
// 2. Mermaid diagram - Render as standard Markdown Mermaid code block
if (lang === 'mermaid') {
return `\n\n### Artifact: ${title}\n\n\`\`\`mermaid\n${code}\n\`\`\`\n\n`;
}
// 3. React components - Wrap in jsx code blocks
if (type.includes('react') || type.includes('jsx')) {
return `\n\n### Artifact: ${title} (React Component)\n\n\`\`\`jsx\n${code}\n\`\`\`\n\n`;
}
// 4. HTML pages - Wrap in html code blocks
if (type === 'text/html') {
return `\n\n### Artifact: ${title} (HTML)\n\n\`\`\`html\n${code}\n\`\`\`\n\n`;
}
// 5. Code blocks (e.g. vnd.ant.code)
if (type.includes('code') || lang) {
const codeLang = lang || 'javascript';
return `\n\n### Artifact: ${title}\n\n\`\`\`${codeLang}\n${code}\n\`\`\`\n\n`;
}
// 6. Markdown - Keep as is
if (type === 'text/markdown') {
return `\n\n### Artifact: ${title}\n\n${code}\n\n`;
}
// Fallback - wrap in generic code block if it looks like code/tags, else plain text
if (code.startsWith('<') || code.includes('import ') || code.includes('export ')) {
return `\n\n### Artifact: ${title}\n\n\`\`\`\n${code}\n\`\`\`\n\n`;
}
return `\n\n### Artifact: ${title}\n\n${code}\n\n`;
});
// Clean remaining tags if any
cleaned = cleaned.replace(/<\/?antArtifact[^>]*>/gi, '');
return cleaned;
}
// Normalize Claude's JSON data into the standardized internal model
function normalizeClaudeConversation(payload, conversationId, includeThinking = false) {
const rawData = payload.data || payload;
const result = {
conversationId: conversationId,
title: rawData.name || 'Claude Conversation',
url: window.location.href,
exportedAt: new Date().toISOString(),
source: 'network',
messages: [],
raw: rawData,
integrity: {
status: 'complete',
warnings: []
}
};
const chatMessages = rawData.chat_messages || [];
let messageIndex = 0;
for (const msg of chatMessages) {
const sender = msg.sender;
if (sender !== 'human' && sender !== 'assistant') continue;
const role = sender === 'human' ? 'user' : 'assistant';
let text = '';
let thoughtsText = '';
if (Array.isArray(msg.content)) {
for (const block of msg.content) {
if (block.type === 'text') {
text += (block.text || '') + '\n\n';
} else if (block.type === 'thinking') {
thoughtsText += (block.thinking || '') + '\n\n';
} else if (block.type === 'redacted_thinking') {
thoughtsText += '*[Thinking process redacted]*\n\n';
}
}
} else if (typeof msg.text === 'string') {
text = msg.text;
}
text = text.trim();
text = cleanClaudeArtifacts(text);
thoughtsText = thoughtsText.trim();
if (thoughtsText && includeThinking) {
text = `<details>\n<summary>Thinking Process</summary>\n\n${thoughtsText}\n</details>\n\n${text}`;
}
if (msg.attachments && msg.attachments.length > 0) {
const attachmentTexts = msg.attachments.map(att => {
return `[Attachment: ${att.file_name || att.name || 'file'}]`;
}).join('\n');
if (text) {
text = text + '\n\n' + attachmentTexts;
} else {
text = attachmentTexts;
}
}
const normalizedMsg = {
id: msg.uuid || `claude-msg-${messageIndex}`,
parentId: null,
index: messageIndex++,
role: role,
createdAt: msg.created_at || null,
content: [
{
type: 'markdown',
text: text
}
],
raw: msg
};
result.messages.push(normalizedMsg);
}
return result;
}
// Normalize Gemini's batchexecute blocks into the standardized internal model
function normalizeGeminiConversation(payload, chatId, includeThinking = false) {
const result = {
conversationId: chatId,
title: payload.title || 'Gemini Conversation',
url: window.location.href,
exportedAt: new Date().toISOString(),
source: 'network',
messages: [],
raw: payload,
integrity: {
status: 'complete',
warnings: []
}
};
const blocks = payload.blocks || [];
let messageIndex = 0;
for (const block of blocks) {
const userMsg = {
id: `gemini-user-${messageIndex}`,
parentId: null,
index: messageIndex++,
role: 'user',
createdAt: block.tsPair ? new Date(block.tsPair[0] * 1000).toISOString() : null,
content: [
{
type: 'markdown',
text: block.userText || ''
}
],
raw: block
};
result.messages.push(userMsg);
let assistantText = block.assistantText || '';
if (includeThinking && block.thoughtsText && block.thoughtsText.trim()) {
assistantText = `<details>\n<summary>Thinking Process</summary>\n\n${block.thoughtsText.trim()}\n</details>\n\n${assistantText}`;
}
const assistantMsg = {
id: `gemini-assistant-${messageIndex}`,
parentId: `gemini-user-${messageIndex - 1}`,
index: messageIndex++,
role: 'assistant',
createdAt: block.tsPair ? new Date(block.tsPair[0] * 1000).toISOString() : null,
content: [
{
type: 'markdown',
text: assistantText
}
],
raw: block
};
result.messages.push(assistantMsg);
}
return result;
}
// Format the normalized message model into a clean, presentation-ready Markdown string (Matching standard ChatGPT export style)
function convertNormalizedToMarkdown(model) {
const platform = getPlatform();
let markdown = `# ${model.title}\n\n`;
markdown += `- **Source URL:** [Link](${model.url})\n`;
markdown += `- **Exported At:** ${new Date(model.exportedAt).toLocaleString()}\n`;
markdown += `- **Platform:** ${platform.toUpperCase()}\n`;
markdown += `- **Integrity Status:** ${model.integrity ? model.integrity.status : 'complete'}\n`;
if (model.integrity && model.integrity.warnings && model.integrity.warnings.length > 0) {
markdown += `- **Warnings:**\n`;
model.integrity.warnings.forEach(w => {
markdown += ` - ${w}\n`;
});
}
markdown += `\n---\n\n`;
let lastAuthor = null;
for (const msg of model.messages) {
const role = msg.role;
const contentItem = msg.content[0] || { text: '', type: 'markdown' };
const text = contentItem.text.trim();
// Skip empty messages or system messages
if (!text || role === 'system') continue;
// Handle tool / code interpreter output
if (role === 'tool') {
markdown += `**Code Interpreter / Tool Output:**\n\n\`\`\`\n${text}\n\`\`\`\n\n`;
lastAuthor = 'tool';
continue;
}
let assistantName = 'Assistant';
if (platform === 'claude') {
assistantName = 'Claude';
} else if (platform === 'gemini') {
assistantName = 'Gemini';
} else {
assistantName = 'ChatGPT';
}
const authorLabel = role === 'user' ? '**You:**' : `**${assistantName}:**`;
if (lastAuthor === authorLabel) {
// Merge consecutive messages from the same role to keep markdown clean and readable
if (contentItem.type === 'code') {
markdown += `\`\`\`python\n${text}\n\`\`\`\n\n`;
} else {
markdown += `${text}\n\n`;
}
} else {
// Add a separator between turns (except before the first message)
if (lastAuthor !== null) {
markdown += `* * *\n\n`;
}
markdown += `${authorLabel}\n\n`;
if (contentItem.type === 'code') {
markdown += `\`\`\`python\n${text}\n\`\`\`\n\n`;
} else {
markdown += `${text}\n\n`;
}
lastAuthor = authorLabel;
}
}
return markdown;
}
// Trigger file download in browser
function triggerDownload(content, filename, contentType) {
const blob = new Blob([content], { type: contentType });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
let isExporting = false;
// Core handler for exporting
async function performExport(format, action = 'download') {
if (isExporting) return;
const conversationId = getActiveConversationId();
if (!conversationId) {
setStatus('error', 'No conversation ID');
return;
}
isExporting = true;
setStatus('loading', 'Loading data...');
try {
const platform = getPlatform();
const rawData = await requestConversationData(conversationId, platform);
const includeThinkingCheckbox = document.getElementById('oai-exporter-include-thinking');
const includeThinking = includeThinkingCheckbox ? includeThinkingCheckbox.checked : false;
let model;
if (platform === 'claude') {
model = normalizeClaudeConversation(rawData, conversationId, includeThinking);
} else if (platform === 'gemini') {
model = normalizeGeminiConversation(rawData, conversationId, includeThinking);
} else {
model = normalizeConversation(rawData);
}
if (format === 'markdown') {
const markdown = convertNormalizedToMarkdown(model);
if (action === 'download') {
const filename = `${sanitizeFilename(model.title)}_${new Date().toISOString().slice(0, 10)}.md`;
triggerDownload(markdown, filename, 'text/markdown;charset=utf-8');
setStatus('ready', `Exported MD! (${model.integrity.status || 'complete'})`);
} else if (action === 'copy') {
await navigator.clipboard.writeText(markdown);
setStatus('ready', 'Copied to clipboard!');
}
} else if (format === 'json') {
const filename = `${sanitizeFilename(model.title)}_${new Date().toISOString().slice(0, 10)}.json`;
triggerDownload(JSON.stringify(model, null, 2), filename, 'application/json;charset=utf-8');
setStatus('ready', `Exported JSON! (${model.integrity.status || 'complete'})`);
}
// Reset to ready status after a short delay
setTimeout(() => setStatus('ready', 'Ready'), 2500);
} catch (err) {
console.error('[Exporter] Export failed:', err);
setStatus('error', err.message || 'Export failed');
setTimeout(() => setStatus('ready', 'Ready'), 4000);
} finally {
isExporting = false;
}
}
// Initialize and inject the UI elements into the page
function initUI() {
if (document.getElementById('oai-exporter-container')) return;
if (!document.body) return;
container = document.createElement('div');
container.id = 'oai-exporter-container';
// SVG Icons
const downloadIcon = `<svg viewBox="0 0 24 24"><path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM17 13l-5 5-5-5h3V9h4v4h3z"/></svg>`;
const mdIcon = `<svg viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2.5" fill="none" stroke="currentColor" stroke-width="2"/><text x="12" y="15.5" font-family="system-ui, sans-serif" font-size="10" font-weight="900" text-anchor="middle">MD</text></svg>`;
const jsonIcon = `<svg viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2.5" fill="none" stroke="currentColor" stroke-width="2"/><text x="12" y="15" font-family="system-ui, sans-serif" font-size="9" font-weight="900" text-anchor="middle">{ }</text></svg>`;
const copyIcon = `<svg viewBox="0 0 24 24"><rect x="8" y="8" width="11" height="11" rx="1.5" fill="none" stroke="currentColor" stroke-width="2"/><path d="M16 8V6a1.5 1.5 0 00-1.5-1.5h-7A1.5 1.5 0 006 6v7a1.5 1.5 0 001.5 1.5H8" stroke="currentColor" stroke-width="2" fill="none"/></svg>`;
container.innerHTML = `
<div class="oai-exporter-fab" title="Export conversation">
${downloadIcon}
<div class="oai-exporter-tooltip">Export Chat</div>
</div>
<div class="oai-exporter-menu">
<div class="oai-exporter-header">Export Options</div>
<button class="oai-exporter-item btn-md">
${mdIcon}
Export Markdown (.md)
</button>
<button class="oai-exporter-item btn-json">
${jsonIcon}
Export Raw JSON (.json)
</button>
<button class="oai-exporter-item btn-copy">
${copyIcon}
Copy Markdown
</button>
<div class="oai-exporter-divider"></div>
<div class="oai-exporter-checkbox-container">
<label class="oai-exporter-checkbox-label">
<input type="checkbox" id="oai-exporter-include-thinking" />
<span>Include Thinking Process</span>
</label>
</div>
<div class="oai-exporter-divider"></div>
<div class="oai-exporter-status">
<div class="oai-exporter-status-dot"></div>
<span class="oai-exporter-status-text">Ready</span>
</div>
</div>
`;
document.body.appendChild(container);
fab = container.querySelector('.oai-exporter-fab');
menu = container.querySelector('.oai-exporter-menu');
statusDot = container.querySelector('.oai-exporter-status-dot');
statusText = container.querySelector('.oai-exporter-status-text');
// Click handler for FAB
fab.addEventListener('click', (e) => {
e.stopPropagation();
const isOpen = menu.classList.toggle('show');
fab.classList.toggle('open', isOpen);
});
// Close menu when clicking outside
document.addEventListener('click', (e) => {
if (container && !container.contains(e.target)) {
if (menu) menu.classList.remove('show');
if (fab) fab.classList.remove('open');
}
});
// Action button clicks (API path)
container.querySelector('.btn-md').addEventListener('click', (e) => {
e.stopPropagation();
performExport('markdown', 'download');
});
container.querySelector('.btn-json').addEventListener('click', (e) => {
e.stopPropagation();
performExport('json', 'download');
});
container.querySelector('.btn-copy').addEventListener('click', (e) => {
e.stopPropagation();
performExport('markdown', 'copy');
});
}
// Display or hide the FAB based on page state
function updateUIState() {
const conversationId = getActiveConversationId();
if (conversationId) {
if (!document.getElementById('oai-exporter-container')) {
initUI();
}
if (container) {
container.style.display = 'block';
}
} else {
if (container) {
container.style.display = 'none';
if (menu) menu.classList.remove('show');
if (fab) fab.classList.remove('open');
}
}
}
// Performance-friendly URL polling replacing heavy MutationObserver (Issue 6)
let lastUrl = location.href;
setInterval(() => {
const url = location.href;
if (url !== lastUrl) {
lastUrl = url;
updateUIState();
}
}, 800);
// Initial check on load
updateUIState();
})();