Hao Zhu | 501fb45 | 2017-07-05 14:37:13 -0400 | [diff] [blame] | 1 | #' Put a HTML table into a scrollable box |
| 2 | #' |
| 3 | #' @description This function will put a HTML kable object in a fixed-height, |
| 4 | #' fixed-width or both box and make it scrollable. |
| 5 | #' |
| 6 | #' @param kable_input A HTML kable object |
| 7 | #' @param height A character string indicating the height of the box, e.g. "50px" |
| 8 | #' @param width A character string indicating the width of the box, e.g. "100px" |
Hao Zhu | 4b0c51e | 2017-08-01 15:21:07 -0400 | [diff] [blame] | 9 | #' @param box_css CSS text for the box |
| 10 | #' @param extra_css Extra CSS styles |
Hao Zhu | 501fb45 | 2017-07-05 14:37:13 -0400 | [diff] [blame] | 11 | #' |
| 12 | #' @export |
Irene | 319a546 | 2018-04-17 15:37:39 -0700 | [diff] [blame] | 13 | #' |
| 14 | #' @examples |
| 15 | #' \dontrun{ |
| 16 | #' # Specify table size by pixels |
| 17 | #' kable(cbind(mtcars, mtcars), "html") %>% |
| 18 | #' kable_styling() %>% |
| 19 | #' scroll_box(width = "500px", height = "200px") |
| 20 | #' |
| 21 | #' # Specify by percent |
| 22 | #' kable(cbind(mtcars, mtcars), "html") %>% |
| 23 | #' kable_styling() %>% |
| 24 | #' scroll_box(width = "100%", height = "200px") |
| 25 | #' } |
| 26 | |
Hao Zhu | 4b0c51e | 2017-08-01 15:21:07 -0400 | [diff] [blame] | 27 | scroll_box <- function(kable_input, height = NULL, width = NULL, |
| 28 | box_css = "border: 1px solid #ddd; padding: 5px; ", |
| 29 | extra_css = NULL) { |
Hao Zhu | 501fb45 | 2017-07-05 14:37:13 -0400 | [diff] [blame] | 30 | kable_attrs <- attributes(kable_input) |
| 31 | out <- as.character(kable_input) |
Hao Zhu | 4b0c51e | 2017-08-01 15:21:07 -0400 | [diff] [blame] | 32 | box_styles <- c(box_css, extra_css) |
Hao Zhu | 501fb45 | 2017-07-05 14:37:13 -0400 | [diff] [blame] | 33 | if (!is.null(height)) { |
| 34 | box_styles <- c(box_styles, |
| 35 | paste0("overflow-y: scroll; height:", height, "; ")) |
| 36 | } |
| 37 | if (!is.null(width)) { |
| 38 | box_styles <- c(box_styles, |
| 39 | paste0("overflow-x: scroll; width:", width, "; ")) |
| 40 | } |
| 41 | out <- paste0('<div style="', paste(box_styles, collapse = ""), '">', |
| 42 | out, '</div>') |
| 43 | out <- structure(out, format = "html", |
| 44 | class = "knitr_kable") |
| 45 | attributes(out) <- kable_attrs |
Hao Zhu | f210083 | 2018-01-11 16:20:29 -0500 | [diff] [blame] | 46 | if (!"kableExtra" %in% class(out)) class(out) <- c("kableExtra", class(out)) |
Hao Zhu | 501fb45 | 2017-07-05 14:37:13 -0400 | [diff] [blame] | 47 | return(out) |
| 48 | } |