-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathoutline2html.py
More file actions
324 lines (282 loc) · 7.82 KB
/
Copy pathoutline2html.py
File metadata and controls
324 lines (282 loc) · 7.82 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
#!/usr/bin/env python3
"""Convert nested outline (.bike / OPML-like XML) into animated HTML disclosures."""
# usage: python3 outline2html_v2.py "input.bike" output.html --title "Page Title" --theme soft
import argparse
import html
import re
import sys
import xml.etree.ElementTree as ET
from pathlib import Path
URL_RE = re.compile(r'(https?://[^\s<>"]+)')
EMAIL_RE = re.compile(r'([\w.+-]+@[\w-]+(?:\.[\w-]+)*\.[a-zA-Z]{2,})')
def linkify(text):
"""Turn bare URLs and email addresses in plain text into clickable links."""
if not text:
return text
text = URL_RE.sub(
lambda m: (
f'<a href="{m.group(1)}" data-tip="{m.group(1)}" '
f'target="_blank" rel="noopener noreferrer">{m.group(1)}</a>'
),
text,
)
text = EMAIL_RE.sub(
lambda m: f'<a href="mailto:{m.group(1)}" data-tip="{m.group(1)}">{m.group(1)}</a>',
text,
)
return text
THEMES = {
"plain": {
"bg": "#ffffff",
"text": "#222222",
"leaf": "#333333",
"hover": "#f0f0f0",
"radius": "4px",
"border": "transparent",
},
"soft": {
"bg": "#faf7f2",
"text": "#3a3530",
"leaf": "#6b6259",
"hover": "#efe8dd",
"radius": "10px",
"border": "#e5ddd0",
},
"dark": {
"bg": "#1e1e1e",
"text": "#e8e8e8",
"leaf": "#a8a8a8",
"hover": "#2a2a2a",
"radius": "8px",
"border": "#333333",
},
}
CSS = """
__THEME_VARS__
body {
font-family: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
margin: 0 auto;
padding: 3rem 2.5rem;
max-width: 900px;
font-size: 1.4rem;
line-height: 1.6;
background-color: var(--bg);
color: var(--text);
}
details {
margin-left: 1.6rem;
margin-top: 0.4rem;
}
summary {
cursor: pointer;
padding: 6px 8px;
border-radius: var(--radius);
list-style: none;
display: flex;
align-items: center;
gap: 0.6rem;
font-weight: 600;
transition: background-color 150ms ease;
}
summary::-webkit-details-marker {
display: none;
}
summary::before {
content: "\\25B6";
display: inline-block;
flex-shrink: 0;
font-size: 0.75em;
transition: transform 250ms ease-out;
}
details[open] > summary::before {
transform: rotate(90deg);
}
summary:hover {
background-color: var(--hover);
}
details > .content {
overflow: hidden;
border-left: 2px solid var(--border);
margin-left: 0.5rem;
padding-left: 0.6rem;
}
.leaf {
margin-left: 1.6rem;
padding: 6px 8px;
margin-top: 0.3rem;
max-width: 65ch;
color: var(--leaf);
}
h1 {
font-size: 2.75rem;
margin-bottom: 1rem;
}
a[href] {
position: relative;
color: inherit;
text-decoration-color: var(--border);
}
a[href]:not([data-tip])::after {
content: attr(href);
}
a[href]::after {
content: attr(data-tip);
position: absolute;
left: 100%;
top: 50%;
margin-left: 0.5em;
background: var(--text);
color: var(--bg);
padding: 0.3em 0.6em;
border-radius: 6px;
font-size: 0.65em;
font-weight: 400;
white-space: nowrap;
opacity: 0;
transform: translateY(-50%) translateX(-4px);
pointer-events: none;
transition: opacity 150ms ease, transform 150ms ease;
z-index: 10;
}
a[href]:hover::after {
opacity: 1;
transform: translateY(-50%) translateX(0);
}
"""
JS = """
class Accordion {
constructor(el) {
this.el = el;
this.summary = el.querySelector(':scope > summary');
this.content = el.querySelector(':scope > .content');
this.animation = null;
this.isClosing = false;
this.isExpanding = false;
if (this.summary && this.content) {
this.summary.addEventListener('click', (e) => this.onClick(e));
}
}
onClick(e) {
e.preventDefault();
this.el.style.overflow = 'hidden';
if (this.isClosing || !this.el.open) {
this.open();
} else if (this.isExpanding || this.el.open) {
this.shrink();
}
}
shrink() {
this.isClosing = true;
const startHeight = `${this.el.offsetHeight}px`;
const endHeight = `${this.summary.offsetHeight}px`;
if (this.animation) this.animation.cancel();
this.animation = this.el.animate(
{ height: [startHeight, endHeight] },
{ duration: 250, easing: 'ease-out' }
);
this.animation.onfinish = () => this.onAnimationFinish(false);
this.animation.oncancel = () => { this.isClosing = false; };
}
open() {
this.el.style.height = `${this.el.offsetHeight}px`;
this.el.open = true;
window.requestAnimationFrame(() => this.expand());
}
expand() {
this.isExpanding = true;
const startHeight = `${this.el.offsetHeight}px`;
const endHeight = `${this.summary.offsetHeight + this.content.offsetHeight}px`;
if (this.animation) this.animation.cancel();
this.animation = this.el.animate(
{ height: [startHeight, endHeight] },
{ duration: 250, easing: 'ease-out' }
);
this.animation.onfinish = () => this.onAnimationFinish(true);
this.animation.oncancel = () => { this.isExpanding = false; };
}
onAnimationFinish(open) {
this.el.open = open;
this.animation = null;
this.isClosing = false;
this.isExpanding = false;
this.el.style.height = this.el.style.overflow = '';
}
}
document.querySelectorAll('details').forEach((el) => new Accordion(el));
"""
def inner_xml(el):
"""Serialize inner content (text + child tags), auto-linking bare URLs/emails."""
parts = [linkify(html.escape(el.text or ""))]
for child in el:
parts.append(ET.tostring(child, encoding="unicode"))
parts.append(linkify(html.escape(child.tail or "")))
return "".join(parts).strip()
def parse_li(li):
p = li.find("p")
text = inner_xml(p) if p is not None else ""
children = []
ul = li.find("ul")
if ul is not None:
for child_li in ul.findall("li"):
children.append(parse_li(child_li))
return {"text": text, "children": children}
def render_node(node, is_top, indent=0):
pad = " " * indent
if node["children"]:
summary_text = f'<strong>{node["text"]}</strong>' if is_top else node["text"]
inner = "".join(
render_node(c, False, indent + 2) for c in node["children"]
)
return (
f'{pad}<details>\n'
f'{pad} <summary>{summary_text}</summary>\n'
f'{pad} <div class="content">\n'
f'{inner}'
f'{pad} </div>\n'
f'{pad}</details>\n'
)
else:
return f'{pad}<div class="leaf">{node["text"]}</div>\n'
def convert(input_path, title, theme="soft"):
tree = ET.parse(input_path)
root_ul = tree.getroot().find("body").find("ul")
top_items = [parse_li(li) for li in root_ul.findall("li")]
body = "".join(render_node(item, True) for item in top_items)
colors = THEMES[theme]
root_vars = ":root {\n" + "".join(
f" --{name}: {value};\n" for name, value in colors.items()
) + "}"
css = CSS.replace("__THEME_VARS__", root_vars)
return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{title}</title>
<style>{css}</style>
</head>
<body>
<h1>{title}</h1>
{body}
<script>{JS}</script>
</body>
</html>
"""
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("input", help="Path to outline file (.bike / XML)")
parser.add_argument("output", help="Path to write output HTML")
parser.add_argument("--title", help="Page title (default: input filename)")
parser.add_argument(
"--theme",
choices=sorted(THEMES.keys()),
default="soft",
help="Color theme (default: soft)",
)
args = parser.parse_args()
input_path = Path(args.input)
title = args.title or input_path.stem
html = convert(input_path, title, args.theme)
Path(args.output).write_text(html, encoding="utf-8")
print(f"Wrote {args.output}")
if __name__ == "__main__":
main()