-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhtml_renderer.py
More file actions
587 lines (484 loc) · 19.6 KB
/
html_renderer.py
File metadata and controls
587 lines (484 loc) · 19.6 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
# Renders Claude conversations as styled HTML pages with syntax highlighting,
# collapsible sections for thinking and tool blocks, and embedded attachments.
# Also generates the index page for browsing all exported conversations.
import html
import json
from datetime import datetime
from zoneinfo import ZoneInfo
import markdown
from pygments import highlight as pygments_highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_by_name, get_lexer_for_mimetype, TextLexer
from pygments.util import ClassNotFound
from chat_message import ChatMessage
from conversation import Conversation
_FORMATTER = HtmlFormatter(style="default", cssclass="codehilite")
PYGMENTS_CSS = _FORMATTER.get_style_defs(".codehilite")
PAGE_CSS = """
body {
max-width: 48em; margin: 2em auto;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, sans-serif;
line-height: 1.6; color: #1a1a1a; background: #fdfdfd; padding: 0 1em;
}
h1 { font-size: 1.6em; border-bottom: 1px solid #ddd; padding-bottom: 0.3em; }
h2 { font-size: 1.3em; margin-top: 1.5em; }
.message { margin: 1.5em 0; padding: 1em; border-radius: 6px; }
.message-human { background: #f0f4f8; border-left: 3px solid #4a90d9; }
.message-assistant { background: #f8f8f0; border-left: 3px solid #6ab04c; }
.sender { font-weight: bold; margin-bottom: 0.5em; color: #555; text-transform: capitalize; }
.timestamp { font-size: 0.8em; color: #888; margin-left: 1em; }
details { margin: 0.8em 0; border: 1px solid #ddd; border-radius: 4px; }
details > summary {
cursor: pointer; font-weight: bold; color: #555; padding: 0.5em 0.8em;
list-style: none;
}
details > summary::-webkit-details-marker { display: none; }
details > summary::before { content: "\\25b6 "; font-size: 0.7em; }
details[open] > summary::before { content: "\\25bc "; }
details > summary:hover { background: #f5f5f5; }
details > .details-body { padding: 0.5em 0.8em; }
.thinking-block { background: #fff8e1; border-color: #ffd54f; }
.tool-block { background: #f3e5f5; border-color: #ce93d8; }
.tool-result-block { background: #e8f5e9; border-color: #81c784; }
.tool-error-block { background: #ffebee; border-color: #ef5350; }
.attachment-block { background: #e3f2fd; border-color: #64b5f6; }
.file-ref {
display: inline-flex; align-items: center; gap: 0.3em;
padding: 0.2em 0.6em; background: #f5f5f5; border: 1px solid #ddd;
border-radius: 3px; font-size: 0.9em; margin: 0.2em 0;
}
.info-icon {
display: inline-block; width: 1.1em; height: 1.1em; border-radius: 50%;
background: #aaa; color: white; text-align: center; font-size: 0.65em;
line-height: 1.7em; cursor: help; font-style: italic; font-weight: bold;
font-family: Georgia, serif;
}
.citations { font-size: 0.85em; margin-top: 0.8em; padding-top: 0.5em; border-top: 1px solid #eee; }
.citations a { color: #0366d6; word-break: break-all; }
pre { background: #f5f5f5; border: 1px solid #ddd; border-radius: 4px; padding: 1em; overflow-x: auto; }
code {
font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
font-size: 0.9em;
}
p code { background: #f5f5f5; padding: 0.2em 0.4em; border-radius: 3px; }
blockquote { border-left: 3px solid #ddd; margin-left: 0; padding-left: 1em; color: #666; }
table { border-collapse: collapse; width: 100%; margin: 1em 0; }
th, td { border: 1px solid #ddd; padding: 0.4em 0.8em; text-align: left; }
th { background: #f5f5f5; }
a { color: #0366d6; text-decoration: none; }
a:hover { text-decoration: underline; }
hr { border: none; border-top: 1px solid #ddd; margin: 1.5em 0; }
img { max-width: 100%; }
"""
INDEX_CSS = """
body {
max-width: 60em; margin: 2em auto;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, sans-serif;
line-height: 1.6; color: #1a1a1a; background: #fdfdfd; padding: 0 1em;
}
h1 {
font-size: 1.6em; position: sticky; top: 0; background: #fdfdfd;
border-bottom: 1px solid #ddd; padding: 0.3em 0; z-index: 10;
}
h2 { font-size: 1.3em; margin-top: 1.5em; }
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ddd; padding: 0.4em 0.8em; text-align: left; }
th { background: #f5f5f5; }
td:first-child { width: 7em; white-space: nowrap; }
a { color: #0366d6; text-decoration: none; }
a:hover { text-decoration: underline; }
.source { font-size: 0.8em; color: #888; }
.month-section { border: none; margin: 2em 0 0 0; padding: 0; }
.month-section > summary { cursor: pointer; list-style: none; }
.month-section > summary::-webkit-details-marker { display: none; }
.month-section > summary > h2 { display: inline; }
.month-section > summary::before { content: "\\25bc "; font-size: 0.7em; }
.month-section:not([open]) > summary::before { content: "\\25b6 "; }
.attachment-icon { display: inline-block; width: 1em; height: 1em; margin-left: 0.4em; vertical-align: middle; }
"""
PAPERCLIP_SVG = (
'<svg class="attachment-icon" viewBox="0 0 24 24" fill="none" stroke="#888" '
'stroke-width="2" stroke-linecap="round" stroke-linejoin="round">'
'<path d="M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 '
'015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"/></svg>'
)
_MD = markdown.Markdown(
extensions=["fenced_code", "codehilite", "tables"],
extension_configs={
"codehilite": {"css_class": "codehilite", "guess_lang": True},
},
)
def _md_to_html(text: str) -> str:
"""Convert markdown text to HTML using the shared Markdown instance.
Args:
text: Raw markdown string.
Returns:
Rendered HTML string.
"""
_MD.reset()
return _MD.convert(text)
def _get_lexer(file_type: str):
"""Resolve a Pygments lexer from a file extension or MIME type.
Tries name-based lookup first (e.g. 'py', 'go'), then MIME type
lookup for values like 'application/x-sh' or 'text/x-python'.
Falls back to plain text.
Args:
file_type: File extension without dot, or a MIME type string.
Returns:
A Pygments lexer instance.
"""
try:
return get_lexer_by_name(file_type)
except ClassNotFound:
pass
if "/" in file_type:
try:
return get_lexer_for_mimetype(file_type)
except ClassNotFound:
pass
return TextLexer()
def _syntax_highlight(content: str, file_type: str) -> str:
"""Syntax-highlight content using Pygments based on file extension or MIME type.
Args:
content: Raw source code or text content.
file_type: File extension without dot (e.g. 'py', 'go', 'sh')
or MIME type (e.g. 'application/x-sh').
Returns:
HTML string with syntax highlighting, or escaped plain text on failure.
"""
return pygments_highlight(content, _get_lexer(file_type), _FORMATTER)
def _format_timestamp(iso_str: str, tz: ZoneInfo | None = None) -> str:
"""Format an ISO 8601 timestamp for display.
Args:
iso_str: ISO 8601 timestamp string.
tz: Target timezone. If None, uses UTC.
Returns:
Formatted datetime string like '2025-03-10 14:30'.
"""
if not iso_str:
return ""
dt = datetime.fromisoformat(iso_str)
if tz:
dt = dt.astimezone(tz)
return dt.strftime("%Y-%m-%d %H:%M")
def _format_file_size(size_bytes: int) -> str:
"""Format a file size in bytes to a human-readable string.
Args:
size_bytes: File size in bytes.
Returns:
Formatted string like '10.3 KB' or '1.2 MB'.
"""
if size_bytes < 1024:
return f"{size_bytes} B"
if size_bytes < 1024 * 1024:
return f"{size_bytes / 1024:.1f} KB"
return f"{size_bytes / (1024 * 1024):.1f} MB"
class HtmlRenderer:
"""Renders conversations and index pages as styled HTML.
Attributes:
tz: Timezone for displaying timestamps.
"""
def __init__(self, tz: ZoneInfo | None = None):
"""Initialize the renderer.
Args:
tz: Timezone for timestamp display. Defaults to US/Eastern.
"""
self.tz = tz or ZoneInfo("US/Eastern")
def render_conversation(self, conv: Conversation) -> str:
"""Render a complete conversation as a standalone HTML page.
Args:
conv: The conversation to render.
Returns:
Complete HTML document as a string.
"""
title = html.escape(conv.name)
created = _format_timestamp(conv.created_at, self.tz)
messages_html = []
for msg in conv.chat_messages:
messages_html.append(self._render_message(msg))
body = "\n<hr>\n".join(messages_html)
return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{title}</title>
<style>
{PAGE_CSS}
{PYGMENTS_CSS}
</style>
</head>
<body>
<h1>{title}</h1>
<p class="timestamp">Created: {created}</p>
{body}
</body>
</html>
"""
def _render_message(self, msg: ChatMessage) -> str:
"""Render a single chat message with all its content blocks.
Args:
msg: The message to render.
Returns:
HTML string for the message div.
"""
sender = html.escape(msg.sender)
css_class = f"message-{msg.sender}" if msg.sender in ("human", "assistant") else ""
timestamp = _format_timestamp(msg.created_at, self.tz)
parts = []
# Attachments (human messages)
for att in msg.attachments:
parts.append(self._render_attachment(att))
# File references (human messages)
for f in msg.files:
parts.append(self._render_file_ref(f))
# Content blocks
for block in msg.content:
block_html = self._render_content_block(block)
if block_html:
parts.append(block_html)
content = "\n".join(parts)
return f"""<div class="message {css_class}">
<div class="sender">{sender}<span class="timestamp">{timestamp}</span></div>
{content}
</div>"""
def _render_content_block(self, block: dict) -> str:
"""Dispatch a content block to the appropriate renderer.
Args:
block: Content block dict with a 'type' field.
Returns:
HTML string for the block, or empty string if unhandled.
"""
block_type = block.get("type", "")
if block_type == "text":
return self._render_text_block(block)
if block_type == "thinking":
return self._render_thinking_block(block)
if block_type == "tool_use":
return self._render_tool_use_block(block)
if block_type == "tool_result":
return self._render_tool_result_block(block)
return ""
def _render_text_block(self, block: dict) -> str:
"""Render a text content block as HTML with markdown conversion.
Args:
block: Text content block dict.
Returns:
HTML string with rendered markdown and optional citations.
"""
text = block.get("text", "")
if not text:
return ""
rendered = _md_to_html(text)
citations = block.get("citations", [])
if citations:
rendered += self._render_citations(citations)
return rendered
def _render_citations(self, citations: list[dict]) -> str:
"""Render citation links as a sources section.
Args:
citations: List of citation dicts with details.url fields.
Returns:
HTML string for the citations section.
"""
seen_urls: set[str] = set()
links = []
for cite in citations:
url = cite.get("details", {}).get("url", "")
if url and url not in seen_urls:
seen_urls.add(url)
escaped = html.escape(url)
# Show domain as link text
domain = url.split("//")[-1].split("/")[0]
links.append(f'<a href="{escaped}" rel="noopener">{html.escape(domain)}</a>')
if not links:
return ""
items = " | ".join(links)
return f'<div class="citations">Sources: {items}</div>'
def _render_thinking_block(self, block: dict) -> str:
"""Render a thinking block as a collapsible section.
Args:
block: Thinking content block dict.
Returns:
HTML string with collapsed details element.
"""
thinking = block.get("thinking", "")
if not thinking:
return ""
escaped = html.escape(thinking)
return f"""<details class="thinking-block">
<summary>Thinking</summary>
<div class="details-body"><pre>{escaped}</pre></div>
</details>"""
def _render_tool_use_block(self, block: dict) -> str:
"""Render a tool_use block as a collapsible section.
Shows the tool name in the summary. For artifacts, displays the
title and renders the content. For other tools, shows the input
as formatted JSON.
Args:
block: Tool use content block dict.
Returns:
HTML string with collapsed details element.
"""
name = block.get("name", "unknown")
tool_input = block.get("input", {})
# Special handling for artifacts
if name == "artifacts" and isinstance(tool_input, dict):
title = tool_input.get("title", "")
art_type = tool_input.get("type", "")
command = tool_input.get("command", "create")
content = tool_input.get("content", "")
summary = f"Artifact: {html.escape(title)}" if title else "Artifact"
if art_type:
summary += f" ({html.escape(art_type)})"
summary += f" [{html.escape(command)}]"
if content:
if "markdown" in art_type or "html" in art_type:
body = _md_to_html(content)
else:
body = f"<pre>{html.escape(content)}</pre>"
else:
body = "<em>No content</em>"
return f"""<details class="tool-block">
<summary>{summary}</summary>
<div class="details-body">{body}</div>
</details>"""
# Generic tool use
summary = f"Tool: {html.escape(name)}"
if tool_input:
formatted = json.dumps(tool_input, indent=2, ensure_ascii=False)
body = f"<pre>{html.escape(formatted)}</pre>"
else:
body = "<em>No input</em>"
return f"""<details class="tool-block">
<summary>{summary}</summary>
<div class="details-body">{body}</div>
</details>"""
def _render_tool_result_block(self, block: dict) -> str:
"""Render a tool_result block as a collapsible section.
Args:
block: Tool result content block dict.
Returns:
HTML string with collapsed details element.
"""
name = block.get("name", "unknown")
is_error = block.get("is_error", False)
content_blocks = block.get("content", [])
css_class = "tool-error-block" if is_error else "tool-result-block"
error_label = " (Error)" if is_error else ""
summary = f"Result: {html.escape(name)}{error_label}"
parts = []
for item in content_blocks:
if isinstance(item, dict):
text = item.get("text", "")
if text:
parts.append(f"<pre>{html.escape(text)}</pre>")
elif isinstance(item, str):
parts.append(f"<pre>{html.escape(item)}</pre>")
body = "\n".join(parts) if parts else "<em>No output</em>"
return f"""<details class="{css_class}">
<summary>{summary}</summary>
<div class="details-body">{body}</div>
</details>"""
def _render_attachment(self, attachment: dict) -> str:
"""Render an attachment as a collapsible section with extracted content.
Args:
attachment: Attachment dict with file_name, file_size, file_type,
and optional extracted_content.
Returns:
HTML string with collapsed details element showing file content.
"""
file_name = attachment.get("file_name", "unknown")
file_size = attachment.get("file_size", 0)
file_type = attachment.get("file_type", "")
content = attachment.get("extracted_content", "")
size_str = _format_file_size(file_size)
type_str = f" .{html.escape(file_type)}" if file_type else ""
summary = f"Attachment: {html.escape(file_name)} ({size_str}{type_str})"
if content:
body = _syntax_highlight(content, file_type) if file_type else f"<pre>{html.escape(content)}</pre>"
else:
body = "<em>No extracted content available</em>"
return f"""<details class="attachment-block">
<summary>{summary}</summary>
<div class="details-body">{body}</div>
</details>"""
def _render_file_ref(self, file_ref: dict) -> str:
"""Render a file reference as a filename with an info icon tooltip.
Args:
file_ref: File reference dict with file_name field.
Returns:
HTML string showing the filename with an info icon.
"""
file_name = file_ref.get("file_name") or "unknown"
return (
f'<span class="file-ref">'
f'{html.escape(file_name)}'
f'<span class="info-icon" title="No file contents available">i</span>'
f'</span>'
)
def render_index(
self,
entries: list[dict],
source_file: str = "",
) -> str:
"""Render the index.html page listing all conversations by month.
Args:
entries: List of dicts with 'date', 'title', 'path', and 'created_dt'
keys for each exported conversation.
source_file: Optional source filename to display in the header.
Returns:
Complete HTML document for the index page.
"""
# Group by YYYY/MM
months: dict[str, list[dict]] = {}
for entry in entries:
key = entry["created_dt"].strftime("%Y/%m")
months.setdefault(key, []).append(entry)
# Sort months reverse chronologically
sorted_months = sorted(months.keys(), reverse=True)
source_html = ""
if source_file:
source_html = f'<br><span class="source">Source: {html.escape(source_file)}</span>'
sections = []
for month_key in sorted_months:
month_entries = months[month_key]
# Sort entries within month reverse chronologically
month_entries.sort(key=lambda e: e["created_dt"], reverse=True)
dt = month_entries[0]["created_dt"]
month_name = dt.strftime("%B %Y")
count = len(month_entries)
rows = []
for entry in month_entries:
date_str = entry["date"]
title_escaped = html.escape(entry["title"])
path_escaped = html.escape(entry["path"])
clip = PAPERCLIP_SVG if entry.get("has_attachments") else ""
rows.append(
f"<tr><td>{date_str}</td>"
f'<td><a href="{path_escaped}">{title_escaped}</a>{clip}</td></tr>'
)
rows_html = "\n".join(rows)
sections.append(
f'<details class="month-section" open>\n'
f"<summary><h2>{month_name} ({count})</h2></summary>\n"
f"<table>\n<tr><th>Date</th><th>Title</th></tr>\n"
f"{rows_html}\n</table>\n</details>"
)
body = "\n".join(sections)
return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>declaude Export Index</title>
<style>
{INDEX_CSS}
</style>
</head>
<body>
<h1>declaude Export Index{source_html}</h1>
{body}
</body>
</html>
"""