-
-
Notifications
You must be signed in to change notification settings - Fork 644
Expand file tree
/
Copy pathPDFPrintService.test.ts
More file actions
562 lines (489 loc) · 20.7 KB
/
Copy pathPDFPrintService.test.ts
File metadata and controls
562 lines (489 loc) · 20.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
import { afterEach, describe, expect, it, vi } from 'vitest';
import { renderElementToImageBlob } from '../ImageRenderService';
import { PDFPrintService } from '../PDFPrintService';
vi.mock('../ImageRenderService', () => ({
renderElementToImageBlob: vi.fn(async () => new Blob(['png'], { type: 'image/png' })),
}));
describe('PDFPrintService', () => {
afterEach(() => {
try {
window.dispatchEvent(new Event('afterprint'));
} catch {
/* ignore */
}
vi.useRealTimers();
vi.clearAllMocks();
document.body.innerHTML = '';
document.title = 'Gemini';
try {
window.history.pushState({}, '', '/');
} catch {
/* ignore */
}
});
it('triggers print and cleans up container on afterprint', async () => {
vi.useFakeTimers();
window.print = vi.fn();
const exportPromise = PDFPrintService.export([{ user: 'u', assistant: 'a', starred: false }], {
url: 'https://gemini.google.com/app/x',
exportedAt: new Date().toISOString(),
count: 1,
title: 'My Chat',
});
await vi.advanceTimersByTimeAsync(100);
await exportPromise;
expect(window.print).toHaveBeenCalledOnce();
expect(document.getElementById('gv-pdf-print-container')).toBeTruthy();
window.dispatchEvent(new Event('afterprint'));
expect(document.getElementById('gv-pdf-print-container')).toBeNull();
});
it('renders custom speaker labels as escaped text', async () => {
window.print = vi.fn();
await PDFPrintService.export(
[{ user: 'u', assistant: 'a', starred: false }],
{
url: 'https://gemini.google.com/app/x',
exportedAt: new Date().toISOString(),
count: 1,
title: 'Safe labels',
},
{
speakerLabels: {
user: '<img src=x onerror=alert(1)>',
assistant: 'Nova & Co.',
},
},
);
const labels = Array.from(document.querySelectorAll('.gv-print-turn-label'));
expect(labels.map((label) => label.textContent)).toEqual([
'👤 <img src=x onerror=alert(1)>',
'🤖 Nova & Co.',
]);
expect(document.querySelector('.gv-print-turn-label img')).toBeNull();
});
it('injects print rules scoped by pdf printing class with white page reset', async () => {
window.print = vi.fn();
await PDFPrintService.export([{ user: 'u', assistant: 'a', starred: false }], {
url: 'https://gemini.google.com/app/x',
exportedAt: new Date().toISOString(),
count: 1,
title: 'Scoped Print Styles',
});
const style = document.getElementById('gv-pdf-print-styles');
const styleText = style?.textContent || '';
expect(styleText).toContain('body.gv-pdf-printing > *:not(#gv-pdf-print-container)');
expect(styleText).toContain('html,');
expect(styleText).toContain('body {');
expect(styleText).toContain('background: #fff !important;');
});
it('uses a compact ChatGPT-like conversation layout when requested', async () => {
document.title = 'Stale page title';
window.print = vi.fn();
await PDFPrintService.export(
[{ user: 'A short question', assistant: 'A useful answer', starred: false }],
{
url: 'https://chatgpt.com/c/abc',
exportedAt: new Date().toISOString(),
count: 1,
title: 'Export test',
},
{ appearance: 'chatgpt' },
);
const documentRoot = document.querySelector('.gv-print-document--chatgpt');
const sourceLink = document.querySelector('.gv-print-meta a');
const styleText = document.getElementById('gv-pdf-print-styles')?.textContent ?? '';
expect(documentRoot).toBeTruthy();
expect(sourceLink?.textContent).toBe('ChatGPT conversation');
expect(document.title).toBe('Export test - ChatGPT');
expect(styleText).toContain('.gv-print-document--chatgpt');
expect(styleText).toContain('.gv-print-turn-user .gv-print-turn-text');
expect(styleText).toContain('border-radius: 18px 18px 4px 18px;');
expect(styleText).toContain('.gv-print-turn-text pre');
expect(styleText).toContain('border: 1px solid #d1d5db;');
expect(styleText).toContain('color: #1f1f1f;');
expect(styleText).toContain('display: table-header-group !important;');
expect(styleText).toContain('.gv-print-cover-title::before');
});
it('does not use the generic ChatGPT page title as a conversation title', async () => {
document.title = 'ChatGPT';
window.print = vi.fn();
await PDFPrintService.export(
[{ user: 'Question', assistant: 'Answer', starred: false }],
{
url: 'https://chatgpt.com/',
exportedAt: new Date().toISOString(),
count: 1,
title: '',
},
{ appearance: 'chatgpt' },
);
expect(document.title).toBe('ChatGPT Conversation');
});
it('falls back to captured text when rich user HTML extraction is empty', async () => {
window.print = vi.fn();
const userElement = document.createElement('div');
await PDFPrintService.export(
[
{
user: 'Fallback user message',
assistant: 'Answer',
starred: false,
userElement,
},
],
{
url: 'https://chatgpt.com/c/abc',
exportedAt: new Date().toISOString(),
count: 1,
title: 'Fallback content',
},
{ appearance: 'chatgpt' },
);
expect(document.querySelector('.gv-print-turn-user .gv-print-turn-text')?.textContent).toBe(
'Fallback user message',
);
});
it('injects descendant display override to survive immersive-mode print rules', async () => {
window.print = vi.fn();
await PDFPrintService.export([{ user: 'u', assistant: 'a', starred: false }], {
url: 'https://gemini.google.com/app/x',
exportedAt: new Date().toISOString(),
count: 1,
title: 'Immersive Print Override',
});
const style = document.getElementById('gv-pdf-print-styles');
const styleText = style?.textContent || '';
expect(styleText).toMatch(
/body\.gv-pdf-printing #gv-pdf-print-container \*\s*\{\s*display:\s*revert !important;/,
);
});
it('restores KaTeX layout primitives after immersive-mode display override', async () => {
window.print = vi.fn();
await PDFPrintService.export([{ user: 'u', assistant: 'a', starred: false }], {
url: 'https://gemini.google.com/app/x',
exportedAt: new Date().toISOString(),
count: 1,
title: 'KaTeX Print Layout',
});
const style = document.getElementById('gv-pdf-print-styles');
const styleText = style?.textContent || '';
expect(styleText).toContain('.katex .vlist-t');
expect(styleText).toContain('display: inline-table !important;');
expect(styleText).toContain('.katex .vlist-r');
expect(styleText).toContain('display: table-row !important;');
expect(styleText).toContain('.katex .vlist,');
expect(styleText).toContain('.katex .vlist-s');
expect(styleText).toContain('display: table-cell !important;');
expect(styleText).toContain('.katex .base');
expect(styleText).toContain('white-space: nowrap !important;');
expect(styleText).toContain('width: min-content !important;');
expect(styleText).toContain('.katex .vlist > span');
expect(styleText).toContain('height: 0 !important;');
expect(styleText).toContain('.katex .mfrac .frac-line');
expect(styleText).toContain('.katex .sqrt > .root');
expect(styleText).toContain('.katex svg');
expect(styleText).toContain('fill: currentColor !important;');
expect(styleText).toContain('position: absolute !important;');
expect(styleText).toContain('.katex img.katex-svg');
expect(styleText).toContain('max-width: none !important;');
expect(styleText).toContain('object-fit: fill !important;');
expect(styleText).toContain('.katex .hide-tail');
expect(styleText).toContain('.gv-print-turn-text .katex');
expect(styleText).toContain('line-height: 1.2 !important;');
});
it('keeps cover page centered under immersive-mode display override', async () => {
window.print = vi.fn();
await PDFPrintService.export([{ user: 'u', assistant: 'a', starred: false }], {
url: 'https://gemini.google.com/app/x',
exportedAt: new Date().toISOString(),
count: 1,
title: 'Centered Cover',
});
const style = document.getElementById('gv-pdf-print-styles');
const styleText = style?.textContent || '';
expect(styleText).toMatch(
/body\.gv-pdf-printing #gv-pdf-print-container \.gv-print-cover-page\s*\{[\s\S]*display:\s*flex !important;/,
);
});
it('reuses conversation print markup for document PDF content', async () => {
document.title = 'Original Title';
window.print = vi.fn();
await PDFPrintService.exportDocument({
title: 'Deep Research Report',
url: 'https://gemini.google.com/app/x',
exportedAt: new Date().toISOString(),
markdown: '# Markdown heading',
html: '<div class="markdown-main-panel"><h2>HTML heading</h2><p>HTML body</p></div>',
});
const turn = document.querySelector('.gv-print-turn');
const reportContainer = document.querySelector('.gv-print-report-content');
const coverTitle = document.querySelector('.gv-print-cover-title');
const turnText = document.querySelector('.gv-print-turn-text');
expect(turn).toBeTruthy();
expect(reportContainer).toBeNull();
expect(coverTitle?.textContent).toContain('Deep Research Report');
expect(turnText?.textContent).toContain('HTML heading');
expect(turnText?.textContent).not.toContain('Markdown heading');
});
it('uses classed div containers instead of semantic print tags', async () => {
window.print = vi.fn();
await PDFPrintService.export([{ user: 'u', assistant: 'a', starred: false }], {
url: 'https://gemini.google.com/app/x',
exportedAt: new Date().toISOString(),
count: 1,
title: 'No Semantic Tags',
});
const container = document.getElementById('gv-pdf-print-container');
expect(container).toBeTruthy();
expect(container?.querySelector('header, main, article, footer')).toBeNull();
});
it('renders uploaded file placeholders in conversation PDFs', async () => {
window.print = vi.fn();
const userElement = document.createElement('div');
userElement.innerHTML = `
<user-query-file-preview>
<div data-test-id="uploaded-file">
<button class="new-file-preview-file" aria-label="proposal.pdf">PDF</button>
</div>
</user-query-file-preview>
`;
await PDFPrintService.export(
[{ user: '', assistant: 'Reviewed', starred: false, userElement }],
{
url: 'https://gemini.google.com/app/x',
exportedAt: new Date().toISOString(),
count: 1,
title: 'Attachment',
},
);
const attachment = document.querySelector('.gv-export-attachment');
const styleText = document.getElementById('gv-pdf-print-styles')?.textContent ?? '';
expect(attachment?.textContent).toContain('proposal.pdf');
expect(styleText).toContain('.gv-print-turn-text .gv-export-attachment');
});
it('renders Mermaid SVG with print-safe scoped styles', async () => {
window.print = vi.fn();
const assistantElement = document.createElement('div');
assistantElement.innerHTML = `
<message-content>
<div class="markdown">
<div class="gv-mermaid-wrapper" data-gv-mermaid-theme="dark">
<code-block style="display: none;">
<div class="code-block-decoration">mermaid</div>
<pre><code role="text">flowchart TD\nA --> B</code></pre>
</code-block>
<div class="gv-mermaid-toggle"><button>Diagram</button></div>
<div class="gv-mermaid-diagram">
<svg data-render-theme="dark" viewBox="0 0 640 1190"><g><text>A</text><text>B</text></g></svg>
</div>
<template class="gv-mermaid-light-export">
<svg data-export-theme="light" viewBox="0 0 640 1190">
<foreignObject width="160" height="24">
<div xmlns="http://www.w3.org/1999/xhtml" style="display: table-cell">
<span class="nodeLabel"><p>核心能力构建</p></span>
</div>
</foreignObject>
</svg>
</template>
</div>
</div>
</message-content>
`;
await PDFPrintService.export(
[{ user: 'Diagram', assistant: '', starred: false, assistantElement }],
{
url: 'https://gemini.google.com/app/x',
exportedAt: new Date().toISOString(),
count: 1,
title: 'Mermaid Export',
},
);
const turnText = document.querySelector('.gv-print-turn-assistant .gv-print-turn-text');
const styleText = document.getElementById('gv-pdf-print-styles')?.textContent ?? '';
const mermaidImage = turnText?.querySelector<HTMLImageElement>(
'.gv-export-mermaid img.gv-export-mermaid-image',
);
const dataUrl = mermaidImage?.getAttribute('src') || '';
expect(mermaidImage).toBeTruthy();
expect(dataUrl).toMatch(/^data:image\/png;base64,/);
expect(turnText?.querySelector('.gv-export-mermaid svg')).toBeNull();
expect(turnText?.querySelector('pre, code-block, .gv-mermaid-toggle')).toBeNull();
expect(styleText).toContain('.gv-print-turn-text .gv-export-mermaid');
expect(styleText).toContain('.gv-print-turn-text .gv-export-mermaid > img {');
expect(styleText).toContain('display: block !important;');
expect(styleText).toContain('break-inside: avoid;');
expect(styleText).toContain('page-break-inside: avoid;');
expect(styleText).toContain('max-width: 100%;');
expect(styleText).toContain('height: auto;');
expect(styleText).toContain('max-height: 160mm;');
expect(styleText).toContain('object-fit: contain;');
expect(vi.mocked(renderElementToImageBlob)).toHaveBeenCalledWith(
expect.any(HTMLElement),
expect.objectContaining({ pixelRatio: 2 }),
);
expect(turnText?.textContent).not.toContain('核心能力构建');
expect(
turnText?.querySelector('.gv-export-mermaid')?.getAttribute('data-gv-mermaid-theme'),
).toBe('light');
expect(styleText).not.toContain('.gv-export-mermaid[data-gv-mermaid-theme="dark"]');
expect(styleText).not.toContain('background: #1f2020;');
expect(styleText).toContain('print-color-adjust: exact;');
expect(styleText).toContain('-webkit-print-color-adjust: exact;');
});
it('falls back to an isolated Mermaid SVG image when rasterization fails', async () => {
window.print = vi.fn();
vi.mocked(renderElementToImageBlob).mockRejectedValueOnce(
new Error('Mermaid rasterization failed'),
);
const assistantElement = document.createElement('div');
assistantElement.innerHTML = `
<message-content>
<div class="markdown">
<div class="gv-mermaid-wrapper" data-gv-mermaid-theme="light">
<code-block style="display: none;">
<div class="code-block-decoration">mermaid</div>
<pre><code role="text">flowchart TD\nA --> B</code></pre>
</code-block>
<div class="gv-mermaid-diagram">
<svg aria-label="Workflow diagram" viewBox="0 0 640 480">
<g><text>A</text><text>B</text></g>
</svg>
</div>
</div>
</div>
</message-content>
`;
await PDFPrintService.export(
[{ user: 'Diagram', assistant: '', starred: false, assistantElement }],
{
url: 'https://gemini.google.com/app/x',
exportedAt: new Date().toISOString(),
count: 1,
title: 'Mermaid Fallback Export',
},
);
const wrapper = document.querySelector<HTMLElement>(
'.gv-print-turn-assistant .gv-export-mermaid',
);
const image = wrapper?.querySelector<HTMLImageElement>('img.gv-export-mermaid-image');
expect(image?.src).toMatch(/^data:image\/svg\+xml;charset=utf-8,/);
expect(image?.alt).toBe('Workflow diagram');
expect(wrapper?.querySelector('svg')).toBeNull();
expect(wrapper?.getAttribute('data-gv-mermaid-theme')).toBe('light');
});
it('normalizes metadata title suffix when page title is generic', async () => {
document.title = 'Gemini';
window.print = vi.fn();
await PDFPrintService.export([{ user: 'u', assistant: 'a', starred: false }], {
url: 'https://gemini.google.com/app/x',
exportedAt: new Date().toISOString(),
count: 1,
title: '房贷还款方式对比分析 - Gemini',
});
const coverTitle = document.querySelector('.gv-print-cover-title');
expect(coverTitle?.textContent).toBe('房贷还款方式对比分析');
});
it('extracts title from native sidebar by conversation id and restores page title after print', async () => {
vi.useFakeTimers();
document.title = 'Google Gemini';
window.print = vi.fn();
window.history.pushState({}, '', '/app/abc12345');
const nativeConversation = document.createElement('div');
nativeConversation.setAttribute('data-test-id', 'conversation');
nativeConversation.setAttribute('jslog', 'x c_abc12345 y');
const link = document.createElement('a');
link.setAttribute('href', '/app/abc12345');
const text = document.createElement('span');
text.className = 'conversation-title-text';
text.textContent = '房贷还款方式对比分析';
link.appendChild(text);
nativeConversation.appendChild(link);
document.body.appendChild(nativeConversation);
const exportPromise = PDFPrintService.export([{ user: 'u', assistant: 'a', starred: false }], {
url: 'https://gemini.google.com/app/abc12345',
exportedAt: new Date().toISOString(),
count: 1,
title: 'Untitled Conversation',
});
await vi.advanceTimersByTimeAsync(100);
await exportPromise;
const coverTitle = document.querySelector('.gv-print-cover-title');
expect(coverTitle?.textContent).toBe('房贷还款方式对比分析');
expect(document.title).toBe('房贷还款方式对比分析 - Gemini');
window.dispatchEvent(new Event('afterprint'));
expect(document.title).toBe('Google Gemini');
});
it('keeps omitEmptySections behavior for selected exports', async () => {
document.title = 'Original Title';
window.print = vi.fn();
await PDFPrintService.export(
[
{
user: '',
assistant: 'Assistant only message',
starred: false,
omitEmptySections: true,
},
],
{
url: 'https://gemini.google.com/app/x',
exportedAt: new Date().toISOString(),
count: 1,
title: 'Selection Export',
},
);
const userSection = document.querySelector('.gv-print-turn-user');
const assistantSection = document.querySelector('.gv-print-turn-assistant');
expect(userSection).toBeNull();
expect(assistantSection?.textContent).toContain('Assistant only message');
});
it('still calls window.print when bridge element exists but has no listener', async () => {
window.print = vi.fn();
const bridge = document.createElement('div');
bridge.id = 'gv-print-bridge';
document.body.appendChild(bridge);
await PDFPrintService.export([{ user: 'u', assistant: 'a', starred: false }], {
url: 'https://gemini.google.com/app/x',
exportedAt: new Date().toISOString(),
count: 1,
title: 'Bridge Fallback',
});
expect(window.print).toHaveBeenCalledOnce();
});
it('escapes quotes in header link href attribute', async () => {
window.print = vi.fn();
await PDFPrintService.export([{ user: 'u', assistant: 'a', starred: false }], {
url: 'https://gemini.google.com/app/x" onclick="alert(1)',
exportedAt: new Date().toISOString(),
count: 1,
title: 'Attribute Escape',
});
const link = document.querySelector('.gv-print-meta a');
expect(link).toBeTruthy();
expect(link?.getAttribute('onclick')).toBeNull();
expect(link?.getAttribute('href')).toContain('" onclick="');
});
it('handles special CSS characters in conversation id selectors', () => {
const conversationId = 'ab"]\\cd';
const nativeConversation = document.createElement('div');
nativeConversation.setAttribute('data-test-id', 'conversation');
nativeConversation.setAttribute('jslog', `x c_${conversationId} y`);
const link = document.createElement('a');
link.setAttribute('href', `/app/${conversationId}`);
const text = document.createElement('span');
text.className = 'conversation-title-text';
text.textContent = 'Escaped Selector Title';
link.appendChild(text);
nativeConversation.appendChild(link);
document.body.appendChild(nativeConversation);
let title: string | null = null;
expect(() => {
title = (
PDFPrintService as unknown as {
extractTitleFromNativeSidebarByConversationId: (id: unknown) => string | null;
}
).extractTitleFromNativeSidebarByConversationId(conversationId);
}).not.toThrow();
expect(title).toBe('Escaped Selector Title');
});
});