Debian Codegraph @

R/view_html.R

raw
1 html_grid <- function(x,title="",max_width=80,...){
2 x <- as.matrix(x)
3 n <- nchar(x)
4 x[n>max_width] <- paste0(substr(x[n>max_width],start=1,stop=max_width),"...")
5 tbody <- paste0("<td>",x,"</td>")
6 dim(tbody) <- dim(x)
7 tbody <- apply(tbody,1,paste0,collapse="")
8 tbody <- paste0("<tr>",tbody,"</tr>")
9 tbody <- c("<tbody>",tbody,"</tbody>")
10 thead <- paste0("<th>",colnames(x),"</th>")
11 thead <- paste0(thead,collapse="")
12 thead <- paste0("<tr>",thead,"</tr>")
13 thead <- c("<thead>",thead,"</thead>")
14 table <- c(thead,tbody)
15 table <- c("<table>",table,"</table>")
16 style <- c("table { border: 0.5px solid #555; border-collapse:collapse; position: relative; }",
17 "thead { background-color: #ddd; border: 0.5px solid #555; }",
18 "td { border: 0.5px solid #555; text-align: right; padding: 3px; white-space: nowrap; }",
19 "th { border: 0.5px solid #555; text-align: center; padding: 3px;
20 background-color: #ddd; position: sticky; top: 0;}",
21 "body { margin: 0; }")
22 style <- paste(style,collapse="\n")
23 style <- c("<style>",style,"</style>")
24 title <- paste0("<title>",title,"</title>")
25 head <- c("<head>",title,style,"</head>")
26 body <- c("<body>",table,"</body>")
27 html <- c("<html>",head,body,"</html>")
28 structure(html,class="raw_html")
29 }
30
31
32
33 view_html <- function(x,title=deparse(substitute(x)),output,...){
34
35 ht <- html_grid(x,title,...)
36
37 if(interactive()){
38 # Test whether running under RStudio
39 isRStudio <- Sys.getenv("RSTUDIO") == "1"
40 if(isRStudio)
41 deflt.output <- "file-show"
42 else
43 deflt.output <- "browser"
44 }
45 else
46 deflt.output <- "stdout"
47
48 if(missing(output))
49 output <- getOption("html_viewer",deflt.output)
50
51 if(mode(output)=="character")
52 output <- match.arg(output,c("stdout","browser","file-show"))
53 else if(!is.function(output))
54 stop("'output' should be either a character string of a function")
55
56 if(is.function(output)){
57
58 tf <- file.path(tempdir(),title)
59 tf <- paste0(tf,".html")
60 cat(ht,file=tf)
61
62 output(tf)
63 }
64 else if(nzchar(Sys.getenv("JPY_PARENT_PID"))){
65 ## Inside Jupyter
66 return(html_div(ht))
67 }
68 else if(output=="stdout") cat(ht)
69 else {
70
71 tf <- file.path(tempdir(),title)
72 tf <- paste0(tf,".html")
73 cat(ht,file=tf)
74
75 if(output=="file-show")
76 file.show(tf,title=deparse(substitute(x)))
77 else
78 browseURL(tf)
79 }
80
81 }
82