forked from Tazinho/Advanced-R-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2-21-Translating_R_code.Rmd
executable file
·526 lines (401 loc) · 20 KB
/
2-21-Translating_R_code.Rmd
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
```{r, include=FALSE}
source("common.R")
```
# Translating R code
```{r setup}
library(rlang)
library(purrr)
```
## HTML
1. __[Q]{.Q}__: TODO: Adapt to the new exercise formulation:
The escaping rules for `<script>` tags are different because they contain JavaScript, not HTML. Instead of escaping angle brackets or ampersands, you need to escape `</script>` so that the tag isn't closed too early. For example, `script("'</script>'")`, shouldn't generate this:
```html
<script>'</script>'</script>
```
But
```html
<script>'<\/script>'</script>
```
Adapt the `escape()` to follow these rules when a new argument `script` is set to `TRUE`.
Old exercise text: The escaping rules for `<script>` and `<style>` tags are different: you don't want to escape angle brackets or ampersands, but you do want to escape `</script>` or `</style>`. Adapt the code above to follow these rules.
TODO: Check why escaping of script/style tags would be necessary and change answer accordingly: https://github.com/hadley/adv-r/issues/1190
Required Code from Advanced R:
```{r required code from advr, include=TRUE}
html <- function(x) structure(x, class = "advr_html")
cat_line <- function(...) cat(..., "\n", sep = "")
print.advr_html <- function(x, ...) {
out <- paste0("<HTML> ", x)
cat_line(paste(strwrap(out), collapse = "\n"))
}
dots_partition <- function(...) {
dots <- dots_list(...)
is_named <- names(dots) != ""
list(
named = dots[is_named],
unnamed = dots[!is_named]
)
}
# html_attributes() funtion from the Github Repository of Advanced R
# (adv-r/dsl-html-attributes.r)
html_attributes <- function(list) {
if (length(list) == 0) return("")
attr <- map2_chr(names(list), list, html_attribute)
paste0(" ", unlist(attr), collapse = "")
}
html_attribute <- function(name, value = NULL) {
if (length(value) == 0) return(name) # for attributes with no value
if (length(value) != 1) stop("`value` must be NULL or length 1")
if (is.logical(value)) {
# Convert T and F to true and false
value <- tolower(value)
} else {
value <- escape_attr(value)
}
paste0(name, "='", value, "'")
}
escape_attr <- function(x) {
x <- escape.character(x)
x <- gsub("\'", ''', x)
x <- gsub("\"", '"', x)
x <- gsub("\r", ' ', x)
x <- gsub("\n", ' ', x)
x
}
```
__[A]{.solved}__: Sourcecode wrapped in `<script>` or `<style>` tags is different from the other HTML-tags: the `<script>` tag inserts (mainly) JavaScript into the HTML document. Here the angle brackets and ampersands should not be escaped so the code remains intact. Because JavaScript may contain multiple nested `<script>` tags, we need to escape the inner tags as `<\/script>`.
[check, what is meant with "want to escape `</script>` or `</style>`"]{.todo}
`style` tags encapsulate css-styling guidelines and the escaping follows the same rules as for the JavaScript above.
Our `tag` function factory needs two serve two competing requirements for escaping: For most of the tag functions the content (brackets and ampersands) needs to be escaped. In script and style tags the content should NOT be escaped, but closing `script`- and `style`-tags need to be escaped.
<!-- HW: I'd create a separate function here, rather than using arguments because I think the intent is sufficiently different. -->
To distinguish between these options, we extend `escape.character()` to include an argument (`escape_choice`) to choose the escape-style, that we want.
```{r}
# add argument `escape_choice` to escape-function
escape.character <- function(x,
escape_choice = c("content", "script_or_style")
) {
escape_choice <- match.arg(escape_choice)
if (escape_choice == "content") {
x <- gsub("&", "&", x)
x <- gsub("<", "<", x)
x <- gsub(">", ">", x)
}
if (escape_choice == "script_or_style") {
x <- gsub("</script>", "<\\/script>", x, fixed = TRUE)
x <- gsub("</style>", "<\\/style>", x, fixed = TRUE)
}
html(x)
}
escape.advr_html <- function(x, ...) x
escape <- function(x, ...) UseMethod("escape")
```
When we create the tag functions we can then specify the escape style we want:
<!-- HW: Instead of complicating this code, I'd just create specific tag functions for script and style by hand -->
```{r}
# create tag with specified escape-style
tag <- function(tag,
escape_choice = c("content", "script_or_style")) {
escape_choice <- match.arg(escape_choice)
new_function(
exprs(... = ),
expr({
dots <- dots_partition(...)
attribs <- html_attributes(dots$named)
children <- map_chr(dots$unnamed,
# choose the escaping
~ escape(., escape_choice = !!escape_choice))
html(paste0(
!!paste0("<", tag), attribs, ">",
paste(children, collapse = ""),
!!paste0("</", tag, ">")
))
}),
caller_env()
)
}
```
Let's test our new `tag()` function:
```{r}
p <- tag("p")
b <- tag("b")
identical(p("This &","this <content>",
b("& this will be escaped")) %>%
as.character(),
"<p>This &this <content><b>& this will be escaped</b></p>")
script <- tag("script", escape_choice = "script_or_style")
script("These signs will not be escaped: &, <, >, ", "but these ones will: </script> or </style>")
```
2. __[Q]{.Q}__: The use of `...` for all functions has some big downsides. There's no input validation and there will be little information in the documentation or autocomplete about how they are used in the function. Create a new function that, when given a named list of tags and their attribute names (like below), creates tag functions with named arguments.
```{r, eval = FALSE}
list(
a = c("href"),
img = c("src", "width", "height")
)
```
All tags should get `class` and `id` attributes.
__[A]{.started}__: The use of `...` for all functions seems too general. It is known which attributes each tag function may have, so we can organize them in a named list of tags and attribute names.
We now need to create tag functions where these attributes are prespecified as arguments. This will enable *autocompletion* and *input validation*. (Documentation would require the functions to be bundeled as a package which we won't do here.)
Let's start by programmatically creating one tag function now and worry about the iteration problem later.
```{r}
tag_info <- list(a = c("href", "src"))
```
The function factory needs to be changed: We need to parse the information provided by the list (tag name and arguments) and unquote-splice the provided arguments into the args part of `rlang::new_function()`. This will provide the autocompletion. In this step we also add the global attributes class and id.
The values of the provided named attributes need to be collected, when the function is called. We use a little "environment-hack" to accomplish this.
```{r}
tag <- function(tag_i,
attr,
escape_choice = c("content", "script_or_style")
) {
# check list-input
if (length(tag_info) != 1) {
stop("Please provide information for just one function.")
}
tag <- enquo(tag_i)
# split tag and attribute information
# tag <- names(tag_info)
# attr <- purrr::flatten_chr(tag_info)
# prepare attributes
attr_list <- rep(list(missing_arg()), length(attr))
names(attr_list) <- attr
escape_choice <- match.arg(escape_choice)
new_function(
# unquote splice into fixed arguments
exprs(... = , class = , id = , !!!attr_list),
expr({
attribs <- caller_env(0) %>% # TODO: possibly encapsulate this
as.list() %>%
Filter(function(x) !is.symbol(x), .) %>%
html_attributes()
dots <- validate_dots(...)
children <- map_chr(dots$unnamed,
# choose the escaping
~ escape(., escape_choice = !!escape_choice))
html(paste0(
# TODO: check !!tag, may be clearer!
!!paste0("<", tag), attribs, ">",
paste(children, collapse = ""),
!!paste0("</", tag, ">")
))
}),
caller_env()
)
}
```
<!-- HW: to generate attribs I thnk you'd be better off doing something like this. Note that the defaults need to be NULL so that the user isn't forced to rely on them, and then we can eliminate the use of validate_dots() because we're taking a different approach.
-->
```{r}
tag <- "img"
tag_attrs <- c("src", "width", "height")
attrs <- c("class", "id", tag_attrs)
attr_args <- map(set_names(attrs), ~ NULL)
attr_list <- call2("list", !!!syms(set_names(attrs)))
new_function(
exprs(... = , !!!attr_args),
expr({
ellipsis::check_dots_unnamed() # cheat by using new package
attribs <- !!attr_list
dots <- compact(list(...))
children <- map_chr(dots$unnamed, escape)
html(paste0(
!!paste0("<", tag), attribs, ">",
paste(children, collapse = ""),
!!paste0("</", tag, ">")
))
})
)
```
We also rewrite `validate_dots`. We check for any unexpected named arguments, which will serve as input validation. The list of unnamed arguments will be escaped as before.
```{r}
validate_dots <- function(...) {
dots <- dots_list(...)
# Input validation
if (any(have_name(dots))) { # names(dots) != ""
stop("Unexpected named argument found.")
}
list(unnamed = dots)
}
```
A few comments regarding the implementation details: The `...` had to be placed in front of the other arguments - otherwise positional matching would assign unnamed values to prespecified values and and unnamed content wouldn't be recognized properly. It was also a challenges to properly collect the prespecified arguments. These are prespecified but setting them at runtime is optional, so they had to be collected in a lazy fashion. Our hack via `caller_env()` isn't pretty and could certainly be improved upon - but it works, as we can see here:
```{r, error=TRUE}
# create a single tag function
a <- tag(list(a = "href"))
# all the general and specific arguments exist, so autocompletion will work
formals(a)
# named arguments are attributes, content is escaped properly
a(class = "anchor", id = "a-1",
href = "http://somelink.com", "take a look at this & this")
# not all named arguments need to be used
a(href = "http://somelink.com", "take a look at this")
# unspecified named arguments will throw an error
a(href = "http://somelink.com", "take a look at this", width = "200")
```
To create many tag functions we can iterate over a list with inputs.
```{r}
tag_inputs <- list(
a = c("href"),
img = c("src", "width", "height"),
body = NULL,
h1 = NULL,
b = NULL,
p = NULL
)
# FIX required
# TODO: created functions not fully correct, somehow attribs is written into the tag function instead of the tag-name
# structure of the map/list structure not correct yet
html_tags <- tag_inputs %>%
map(~ tag) # potentially use imap to operate on index as well
```
3. __[Q]{.Q}__: Reason about the following code that calls `with_html()` referening objects from the environment. Will it work or fail? Why? Run the code to verify your predictions.
```{r, eval = FALSE}
greeting <- "Hello!"
with_html(p(greeting))
address <- "123 anywhere street"
with_html(p(address))
```
__[A]{.started}__: (TODO: In the exercise the definition of `p` changed into `p <- function() "p"`. This needs to be added and the exercise/answer might need to get updated. Further `with_html` is defined in the next exercise. Therefore, a change to introduce it already here has to be made...and the chunks then need to be changed to `eval = TRUE`) When we created the various HTML tag functions, `address()` was one of them. This HTML tag may be used to provide contact information on an HTML page. All our tag functions are not present in the global environment, but rather elements of the list `html_tags`.
The DSL code wrapped in `with_html()` is evaluated in its own environment and in the "context" of `html_tags`. The tag functions are available, because we provided a list of them as a data mask. As `r ?as_data_mask` indicates: "Objects in the mask have precedence over objects in the environment."
```{r, error=TRUE, eval = FALSE}
greeting <- "Hello!"
with_html(p(greeting))
address <- "123 anywhere street"
with_html(p(address))
```
The error message then tells us, what the problem is: `p(address)` operates on `address()`, the function not the character, and we haven't implemented an `escape.function()` method.
```{r, eval = FALSE}
# checking our list of tag functions
c("greeting", "address") %in% names(html_tags)
# this works
html_tags$address <- "123 anywhere street"
with_html(p(address))
```
4. __[Q]{.Q}__: Currently the HTML doesn't look terribly pretty, and it's hard to see the
structure. How could you adapt `tag()` to do indenting and formatting? (You may need to do some research into block and inline tags.)
__[A]{.solved}__: First let us define all needed functions from the textbook:
```{r required code from book, include=FALSE}
tag <- function(tag) {
new_function(
exprs(... = ),
expr({
dots <- dots_partition(...)
attribs <- html_attributes(dots$named)
children <- map_chr(dots$unnamed, escape)
html(paste0(
!!paste0("<", tag), attribs, ">",
paste(children, collapse = ""),
!!paste0("</", tag, ">")
))
}),
caller_env()
)
}
void_tag <- function(tag) {
new_function(
exprs(... = ),
expr({
dots <- dots_partition(...)
if (length(dots$unnamed) > 0) {
stop(!!paste0("<",
tag,
"> must not have unnamed arguments"),
call. = FALSE)
}
attribs <- html_attributes(dots$named)
html(paste0(!!paste0("<", tag), attribs, " />"))
}),
caller_env()
)
}
tags <- c("a", "abbr", "address", "article", "aside", "audio", "b",
"bdi", "bdo", "blockquote", "body", "button", "canvas",
"caption","cite", "code", "colgroup", "data", "datalist",
"dd", "del","details", "dfn", "div", "dl", "dt", "em",
"eventsource","fieldset", "figcaption", "figure", "footer",
"form", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header",
"hgroup", "html", "i","iframe", "ins", "kbd", "label", "legend",
"li", "mark", "map","menu", "meter", "nav", "noscript", "object",
"ol", "optgroup", "option", "output", "p", "pre", "progress", "q",
"ruby", "rp","rt", "s", "samp", "script", "section", "select",
"small", "span", "strong", "style", "sub", "summary", "sup",
"table", "tbody", "td", "textarea", "tfoot", "th", "thead",
"time", "title", "tr", "u", "ul", "var", "video")
void_tags <- c("area", "base", "br", "col", "command", "embed", "hr", "img",
"input", "keygen", "link", "meta", "param", "source",
"track", "wbr")
html_tags <- c(tags %>% set_names() %>% map(tag),
void_tags %>% set_names() %>% map(void_tag)
)
with_html <- function(code) {
code <- enquo(code)
eval_tidy(code, html_tags)
}
```
Now, let's look at the example from above:
```{r}
with_html(
body(
h1("A heading", id = "first"),
p("Some text &", b("some bold text.")),
img(src = "myimg.png", width = 100, height = 100)
)
)
```
The formatting comes down to just one long line of code. This output will be more difficult to work with, to inspect what the code does and if it's correct. What kind of formatting would we prefer instead? The [Google HTML Styleguide](https://google.github.io/styleguide/htmlcssguide.html#HTML_Formatting_Rules) suggests *indentation* by 2 spaces and *new lines* for every block, list, or table element. There are other recommendations, but we will keep things simple and will be satisfied with the following output.
```{html, eval=FALSE}
<body>
<h1 id='first'>A heading</h1>
<p>Some text &<b>some bold text.</b></p>
<img src='myimg.png'width='100' height='100' />
</body>
```
First we adjust the `print.advr_html` method. We replace the `strwrap` function, because this will wrap HTML-code into one long line regardless of its input. We use `cat` instead, because it prints linebreaks (`"\n"`) nicely.
```{r}
html <- function(x) structure(x, class = "advr_html")
cat_line <- function(...) cat(..., sep = "")
print.advr_html <- function(x, ...) {
out <- paste("<HTML>", x, sep = "\n") # linebreak added
# cat_line(paste(strwrap(out), collapse = ""))
cat_line(out)
}
```
In our desired output we can see, that the content of the `body`-function requires another formatting than the other tag-functions. We will therefore create a new `format_code`-function, that allows for optional indentation and linbreaks. For this `strwarp` provides two helpful arguments: each element will start with a linebreak (`prefix = "\n"`) and will be indentend propely (`indent = 2`).
```{r}
format_code <- function(children, indent = FALSE){
if (indent) {
paste0(paste(strwrap(children, indent = 2, prefix = "\n"),
collapse = ""), "\n")
} else {
paste(children, collapse = "")
}
}
```
We adjust the body function to include the `format_code()`-helper. (This could also be approached programatically in the tag function factory.)
```{r}
html_tags$body <- function(...){
attribs <- caller_env(0) %>%
as.list() %>%
Filter(function(x) !is.symbol(x), .) %>%
html_attributes()
dots <- validate_dots(...)
children <- map_chr(dots$unnamed, ~escape(., escape_choice = "content"))
html(paste0("<body",
attribs, ">",
# instead of `paste(children, collapse = "")`
format_code(children, indent = TRUE),
"</body>")
)
}
```
The resulting output is much more satisfying.
```{r}
with_html(
body(
h1("A heading", id = "first"),
p("Some text &", b("some bold text.")),
img(src = "myimg.png", width = 100, height = 100)
)
)
```
## LaTeX
1. __[Q]{.Q}__: Add escaping. The special symbols that should be escaped by adding a backslash in front of them are `\`, `$`, and `%`. Just as with HTML, you'll need to make sure you don't end up double-escaping. So you'll need to create a small S3 class and then use that in function operators. That will also allow you to embed arbitrary LaTeX if needed.
__[A]{.solved}__:
2. __[Q]{.Q}__: Complete the DSL to support all the functions that `plotmath` supports.
__[A]{.solved}__: