This repository has been archived by the owner on Dec 20, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmacros.rs
581 lines (560 loc) · 20.6 KB
/
macros.rs
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
use std::rc::Rc;
use std::cell::RefCell;
use std::path::{PathBuf, Path};
use std::collections::HashMap;
use std::iter::FromIterator;
use std::convert::AsRef;
use serde::{Serialize, Deserialize};
use crate::data::*;
use crate::utils::{
cache_file_dep,
};
///////////////////////////////////////////////////////////////////////////////
// MACROS
///////////////////////////////////////////////////////////////////////////////
pub fn include_tag(ctx: &Context) -> Macro {
let ctx = ctx.clone();
Macro::match_tag("include", Rc::new(move |node: &mut Node| {
let source_dir = ctx.source_dir();
let root_dir = ctx.root_dir.clone();
node.get_attr("src")
.and_then(|src_path_str| {
let src_path = FilePath::resolve_include_path(
&ctx,
&src_path_str,
)?;
if !src_path.exists() {
eprintln!("[WARNING] missing file: {}", src_path);
return None;
}
let base: String = src_path.load_text_file();
let had_doctype = base.contains("<!DOCTYPE html>");
let mut base = Node::parse_str(&base);
// Provision the new document:
{
let mut new_ctx = ctx.clone();
new_ctx.source = ctx
.source_dir()
.unwrap()
.join(&ctx.root_dir, &src_path)
.unwrap();
hooks::document(&new_ctx, &mut base);
}
let mut base = base.to_html_str(0);
if had_doctype {
base = format!("<!DOCTYPE html>\n{}", base);
}
Some(base)
})
.map(|contents| {
let embeded_contents = Node::Fragment(node.get_children()).to_html_str(0);
let contents = contents.replace(
"<content></content>",
&embeded_contents
);
let mut new_node = Node::parse_str(&contents);
*node = new_node;
});
}))
}
pub fn latex_suit(ctx: &Context) -> Macro {
let ctx = ctx.clone();
let block_latex = |node: &Node, value: String| {
let mut attrs = node.get_attributes();
attrs.insert(String::from("latex"), String::from("block"));
Node::new_element(
"div",
attrs,
&[Node::new_text(&format!("$${}$$", value))]
)
};
let inline_latex = |node: &Node, value: String| {
let mut attrs = node.get_attributes();
attrs.insert(String::from("latex"), String::from("inline"));
Node::new_element(
"span",
attrs,
&[Node::new_text(&format!("\\({}\\)", value))]
)
};
Macro::new_void("latex-suit", Rc::new({
let ctx = ctx.clone();
move |node: &mut Node| -> Option<()> {
match node.tag()?.as_ref() {
/// LaTeX Math Block
"tex" if node.has_attr("block") => {
let text_contents = node.get_text_contents()?;
let new_node = block_latex(node, text_contents);
*node = new_node;
Some(())
},
/// LaTeX Inline Math
"tex" if !node.has_attr("block") => {
let text_contents = node.get_text_contents()?;
let new_node = inline_latex(node, text_contents);
*node = new_node;
Some(())
},
/// External File (Block)
"texblock" if node.has_attr("src") => {
node
.get_attr("src")
.and_then(|x| FilePath::resolve_include_path(&ctx, &x))
.and_then(|src_path| {
let value = cache_inline_text(&ctx, &src_path)?;
let new_node = block_latex(node, value);
*node = new_node;
Some(())
})
}
/// LaTeX Math Block
"texblock" if !node.has_attr("src") => {
let text_contents = node.get_text_contents()?;
let new_node = block_latex(node, text_contents);
*node = new_node;
Some(())
}
/// LaTeX Equation (Block)
"equation" => {
let text_contents = node.get_text_contents()?;
let new_node = block_latex(node, format!(
"\\begin{{equation}}\n\\begin{{split}}\n{txt}\n\\end{{split}}\n\\end{{equation}}",
txt=text_contents
));
*node = new_node;
Some(())
},
_ => Some(())
}
}
}))
}
pub fn note_tag(ctx: &Context) -> Macro {
let ctx = ctx.clone();
Macro::new_void("note", Rc::new(move |node: &mut Node| {
if !node.is_tag("note") {return Some(())}
let mut attrs = node.get_attributes();
attrs.insert(String::from("note"), String::new());
*node = Node::new_element(
"div",
attrs,
&node.get_children(),
);
Some(())
}))
}
pub fn items_tag(ctx: &Context) -> Macro {
let ctx = ctx.clone();
Macro::match_tag("items", Rc::new(|node: &mut Node| {
let mut attrs = node.get_attributes();
let mut new_children = Vec::<Node>::new();
for child in node.get_children() {
if child.is_tag("li") {
new_children.push(child);
} else {
new_children.push(
Node::new_element("li", Default::default(), &[child])
);
}
}
*node = Node::new_element(
"ul",
attrs,
&new_children
)
}))
}
pub fn list_tag(ctx: &Context) -> Macro {
let ctx = ctx.clone();
Macro::match_tag("list", Rc::new(|node: &mut Node| {
let mut new_children = Vec::<Node>::new();
let mut attrs = node.get_attributes();
for child in node.get_children() {
if child.is_tag("li") {
new_children.push(child);
} else {
new_children.push(
Node::new_element("li", Default::default(), &[child])
);
}
}
*node = Node::new_element(
"ol",
attrs,
&new_children
)
}))
}
pub fn img_tag(ctx: &Context) -> Macro {
let ctx = ctx.clone();
let processed_attr = "ss.img.processed";
Macro::match_tag("img", Rc::new(move |node: &mut Node| {
node
.get_attr("width")
.map(|width| {
if node.has_attr("ss.proc.width") {
return;
}
if let Some(style) = node.get_attr("style") {
node.set_attr("style", format!(
"{}; min-width: 0; max-width: {}; width: 100%;",
style,
width,
));
} else {
node.set_attr("style", format!(
";min-width: 0; max-width: {}; width: 100%;",
width,
));
}
node.set_attr("ss.proc.width", String::new());
});
// CACHE ASSET
node.get_attr("src")
.and_then(|x| FilePath::resolve_include_path(&ctx, &x))
.and_then(|src_path| {
if !node.has_attr(processed_attr) {
let new_src = crate::data::cache_file(&ctx, &src_path)?;
node.set_attr("src", format!(
"{}",
new_src
));
node.set_attr(processed_attr, String::from(""));
}
Some(())
});
}))
}
pub fn link_tag(ctx: &Context) -> Macro {
let ctx = ctx.clone();
let processed_attr = "ss.link.processed";
Macro::match_tag("link", Rc::new(move |node: &mut Node| {
node.get_attr("href")
.and_then(|x| FilePath::resolve_include_path(&ctx, &x))
.and_then(|src_path| {
if !node.has_attr(processed_attr) {
let new_src = cache_file_dep(&ctx, &src_path)?;
node.set_attr("href", format!(
"{}",
new_src
));
node.set_attr(processed_attr, String::from(""));
}
Some(())
});
}))
}
pub fn desmos_tag(ctx: &Context) -> Macro {
let ctx = ctx.clone();
let process_child = |node: &Node| -> Option<HashMap<String, String>> {
if !node.is_tag("expr") {
return None;
}
let attrs = vec![
("id", "id"),
("label", "label"),
("label-orientations", "labelOrientations"),
("label-size", "labelSize"),
("line-style", "lineStyle"),
("point-style", "pointStyle"),
("drag-mode", "dragMode"),
("color", "color"),
];
let mut command = attrs
.into_iter()
.filter_map(|(html_key, des_key)| {
node.get_attr(html_key)
.map(|value| (des_key.to_owned(), value.to_owned()))
})
.map(|(key, value)| {
if key == "lineStyle" && value.to_lowercase() == "solid" {
return (key, String::from("SOLID"))
}
if key == "lineStyle" && value.to_lowercase() == "dashed" {
return (key, String::from("DASHED"))
}
if key == "lineStyle" && value.to_lowercase() == "dotted" {
return (key, String::from("DOTTED"))
}
(key, value)
})
.collect::<HashMap<_, _>>();
if let Some(value) = node.get_attr("font-size") {
let mut value = value
.replace("-", "_")
.to_owned();
if value.replace("-", "_").to_lowercase() == "very_small" {
value = String::from("VERY_SMALL");
}
if value.replace("-", "_").to_lowercase() == "small" {
value = String::from("SMALL");
}
if value.replace("-", "_").to_lowercase() == "medium" {
value = String::from("MEDIUM");
}
if value.replace("-", "_").to_lowercase() == "large" {
value = String::from("LARGE");
}
if value.replace("-", "_").to_lowercase() == "very_large" {
value = String::from("VERY_LARGE");
}
command.insert(String::from("fontSize"), value);
}
command.insert(String::from("latex"), node.get_text_contents()?);
Some(command)
};
let html_wrapper = |node: &Node, uid: &str, commands: Vec<HashMap<String, String>>| -> Node {
let ref commands = serde_json::to_string(&commands).unwrap();
let mut args = HashMap::<&str, String>::from_iter(vec![
("{{uid}}", String::from(uid)),
("{{width}}", {
node.get_attr("width").unwrap_or(String::from("300px"))
}),
("{{height}}", {
node.get_attr("height").unwrap_or(String::from("300px"))
}),
("{{show_expressions}}", String::from("false")),
("{{lockViewport}}", String::from("true")),
("{{xAxisNumbers}}", String::from("true")),
("{{yAxisNumbers}}", String::from("true")),
("{{showGrid}}", String::from("false")),
("{{math_bounds}}", String::from("null")),
("{{commands}}", String::from(commands)),
]);
let mut html_wrapper = String::from(include_str!("../assets/desmos.txt"));
let mut set_math_bounds = || -> Option<()> {
let mut math_bounds = HashMap::<String, f32>::default();
node.get_attr("left")
.and_then(|x| x.parse::<f32>().ok())
.map(|value: f32| {
math_bounds.insert(String::from("left"), value);
});
node.get_attr("right")
.and_then(|x| x.parse::<f32>().ok())
.map(|value: f32| {
math_bounds.insert(String::from("right"), value);
});
node.get_attr("top")
.and_then(|x| x.parse::<f32>().ok())
.map(|value: f32| {
math_bounds.insert(String::from("top"), value);
});
node.get_attr("bottom")
.and_then(|x| x.parse::<f32>().ok())
.map(|value: f32| {
math_bounds.insert(String::from("bottom"), value);
});
if !math_bounds.is_empty() {
let math_bounds = serde_json::to_string(&math_bounds).ok()?;
args.insert("{{math_bounds}}", math_bounds);
}
Some(())
};
set_math_bounds();
for (key, value) in args {
html_wrapper = html_wrapper.replace(key, &value);
}
Node::parse_str(&html_wrapper)
};
Macro::match_tag("desmos", Rc::new(move |node: &mut Node| {
let uid = format!("uid{}", rand::random::<u64>());
let commands = node
.get_children()
.into_iter()
.filter_map(|node| process_child(&node))
.collect::<Vec<_>>();
let new_node = html_wrapper(node, &uid, commands);
*node = new_node;
}))
}
pub fn element_self_styles(element: &mut Element) {
let mut set_node_id = false;
let node_id = {
if let Some(uid) = element.attrs.get("id") {
uid.clone()
} else {
format!(
"id_{}",
rand::random::<u64>()
)
}
};
for child in element.children.iter_mut() {
if child.is_tag("style") && child.has_attr("self") {
if let Some(contents) = child.get_text_contents() {
let new_contents = contents.replace("self", &format!(
"#{}",
node_id
));
child.replace_children(vec![Node::new_text(&new_contents)]);
set_node_id = true;
}
}
}
if set_node_id {
element.attrs.insert(String::from("id"), node_id);
}
}
pub fn subscript_deps(ctx: &Context) -> Macro {
let ctx = ctx.clone();
Macro::match_tag("head", Rc::new(move |node: &mut Node| {
let deps = Node::parse_str(include_str!("../assets/deps.html"));
node.append_children(deps.into_fragment());
}))
}
pub fn hoist_style_tags(ctx: &Context, html: &mut Node) {
let ctx = ctx.clone();
let style_tags = Rc::new(RefCell::new(Vec::<Node>::new()));
let ret_macro = Macro::match_tag("style", Rc::new({
let style_tags = style_tags.clone();
move |node: &mut Node| {
let style_tags = style_tags.clone();
style_tags.borrow_mut().push(node.clone());
*node = Node::Fragment(Default::default());
}
}));
let hoist_macro = Macro::match_tag("head", Rc::new(move |node: &mut Node| {
let style_tags: Vec<Node> = style_tags.borrow().clone();
node.append_children(style_tags);
}));
html.apply(ret_macro);
html.apply(hoist_macro);
}
pub fn table_of_contents(ctx: &Context, html: &mut Node) {
html.eval(Rc::new(|node: &mut Node| {
if let Some(tag) = node.tag() {
let mut set_id = || {
if node.get_attr("id").is_none() {
node.set_attr("id", format!(
"{}",
rand::random::<u64>()
))
}
};
match &tag[..] {
"h1" => set_id(),
"h2" => set_id(),
"h3" => set_id(),
"h4" => set_id(),
"h5" => set_id(),
"h6" => set_id(),
_ => ()
}
}
}));
fn runner(node: &Node) -> Vec<Node> {
let new_entry = |tag: &str, children: String, uid: &String| {
let mut li_attrs = HashMap::default();
li_attrs.insert(String::from("for"), String::from(tag));
let mut a_attrs = HashMap::default();
a_attrs.insert(String::from("href"), format!(
"#{}",
uid
));
let result = Node::new_element(
"li",
li_attrs,
&[Node::new_element(
"a",
a_attrs,
&[Node::new_text(&children)]
)]
);
vec![result]
};
match node {
Node::Element(element) if &element.tag == "h1" => {
let uid = element.attrs.get("id").unwrap();
let children = node.get_children_as_text().join(" ");
new_entry("h1", children, uid)
}
Node::Element(element) if &element.tag == "h2" => {
let uid = element.attrs.get("id").unwrap();
let children = node.get_children_as_text().join(" ");
new_entry("h2", children, uid)
}
Node::Element(element) if &element.tag == "h3" => {
let uid = element.attrs.get("id").unwrap();
let children = node.get_children_as_text().join(" ");
new_entry("h3", children, uid)
}
Node::Element(element) if &element.tag == "h4" => {
let uid = element.attrs.get("id").unwrap();
let children = node.get_children_as_text().join(" ");
new_entry("h4", children, uid)
}
Node::Element(element) if &element.tag == "h5" => {
let uid = element.attrs.get("id").unwrap();
let children = node.get_children_as_text().join(" ");
new_entry("h5", children, uid)
}
Node::Element(element) if &element.tag == "h6" => {
let uid = element.attrs.get("id").unwrap();
let children = node.get_children_as_text().join(" ");
new_entry("h6", children, uid)
}
Node::Element(element) => {
return element.children.iter().flat_map(|x| runner(x)).collect()
}
Node::Fragment(nodes) => {
nodes
.iter()
.flat_map(|x| runner(x))
.collect()
}
_ => Vec::new()
}
}
let headers = runner(html);
html.eval(Rc::new(move |node: &mut Node| {
if node.is_tag("toc") {
let mut attrs = node.get_attributes();
attrs.insert(String::from("toc"), String::default());
*node = Node::new_element(
"ul",
attrs,
&headers
);
}
}));
}
pub fn gallery_tag(ctx: &Context) -> Macro {
let ctx = ctx.clone();
Macro::match_tag("gallery", Rc::new(|node: &mut Node| {
let mut attrs = node.get_attributes();
attrs.insert(String::from("macro"), String::from("gallery"));
let mut children = node.get_children();
*node = Node::new_element(
"div",
attrs,
&children,
)
}))
}
/// Macro entrypoints.
pub mod hooks {
use super::*;
/// Custom elements use the 'document' hook.
pub fn document(ctx: &Context, html: &mut Node) {
html.apply(include_tag(&ctx));
html.apply(gallery_tag(&ctx));
html.apply(items_tag(&ctx));
html.apply(list_tag(&ctx));
html.apply(latex_suit(&ctx));
html.apply(note_tag(&ctx));
html.apply(img_tag(&ctx));
html.apply(link_tag(&ctx));
html.apply(desmos_tag(&ctx));
}
/// Apply this once to the entire document **before** serializing such to a string.
/// This is where e.g. runtime dependencies are inserted.
pub fn finalize_document(ctx: &Context, html: &mut Node) {
html.apply(subscript_deps(&ctx));
hoist_style_tags(&ctx, html);
table_of_contents(&ctx, html);
}
/// Gets called whenever new elements are created (includes elements from the parser).
pub fn new_element(element: &mut Element) {
element_self_styles(element);
}
}