This repository has been archived by the owner on May 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
app.R
80 lines (71 loc) · 2.02 KB
/
app.R
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
library(shiny)
library(XML)
library(magrittr)
library(purrr)
library(stringr)
ui <- fluidPage(
titlePanel("HTML to R Converter"),
fluidRow(
column(5, textAreaInput("html", "HTML", rows=20, value = ' <table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>')
),
column(2, checkboxInput("prefix", "Prefix"), actionButton("convert", "Convert")),
column(5, tags$pre(textOutput("rCode")))
),
fluidRow(tags$a(href = "https://github.com/alandipert/html2r", "Github"))
)
makeAttrs <- function(node) {
attrs <- xmlAttrs(node)
names(attrs) %>%
Map(function (name) {
val <- attrs[[name]]
paste0(name, ' = ', if (val == "") "NA" else paste0('"', val, '"'))
}, .)
}
Keep <- function(fun, xs) Map(fun, xs) %>% Filter(Negate(is.null), .)
renderNode <- function(node, indent = 0, prefix = FALSE) {
if (xmlName(node) == "text") {
txt <- xmlValue(node)
if (nchar(trimws(txt)) > 0) {
paste0('"', trimws(txt), '"')
}
} else {
tagName <- if (prefix) paste0("tags$", xmlName(node)) else xmlName(node)
newIndent <- indent + length(tagName) + 1
xmlChildren(node) %>%
Keep(partial(renderNode, indent = newIndent, prefix = prefix), .) %>%
append(makeAttrs(node), .) %>%
paste(collapse = str_pad(",\n", width = newIndent, side = c("right"))) %>%
trimws(which = c("left")) %>%
paste0(tagName, "(", ., ")")
}
}
html2R <- function(htmlStr, prefix = FALSE) {
htmlStr %>%
htmlParse %>%
getNodeSet("/html/body/*") %>%
`[[`(1) %>%
renderNode(prefix = prefix)
}
server <- function(input, output, session) {
rcode <- eventReactive(input$convert, {
html2R(input$html, prefix = input$prefix)
}, ignoreInit = TRUE)
output$rCode <- renderText(rcode())
}
shinyApp(ui, server)