| 1 |
#' Preview Markdown and R Markdown files |
| 2 |
#' |
| 3 |
#' Launch a web page to list and preview files under a directory. |
| 4 |
#' |
| 5 |
#' Markdown files will be converted to HTML and returned to the web browser |
| 6 |
#' directly without writing to HTML files, to keep the directory clean during |
| 7 |
#' the preview. Clicking on a filename will bring up an HTML preview. To see its |
| 8 |
#' raw content, click on the link on its file size instead. |
| 9 |
#' @param dir A directory path. |
| 10 |
#' @param live Whether to enable live preview. If enabled, the browser page will |
| 11 |
#' be automatically updated upon modification of local files used by the page |
| 12 |
#' (e.g., the Markdown file or external CSS/JS/image files). If disabled, you |
| 13 |
#' can manually refresh the page to fully re-render it. |
| 14 |
#' @param ... Other arguments to be passed to [xfun::new_app()]. |
| 15 |
#' @return A URL (invisibly) for the preview. |
| 16 |
#' @export |
| 17 |
roam = function(dir = '.', live = TRUE, ...) in_dir(dir, { |
| 18 |
# a proxy server to return files under inst/resources/ |
| 19 |
s = new_app('.litedown', function(path, ...) { |
| 20 |
file_raw(pkg_file('resources', path)) |
| 21 |
}, open = FALSE) |
| 22 |
# the URL needs to be translated on RStudio Server |
| 23 |
if (Sys.getenv('RSTUDIO_PROGRAM_MODE') == 'server' && loadable('rstudioapi')) |
| 24 |
s = rstudioapi::translateLocalUrl(s, TRUE) |
| 25 |
# load litedown assets via http://127.0.0.1:port/custom/.litedown/assets |
| 26 |
asset_url = function(path) paste0(s, path) |
| 27 |
|
| 28 |
t1 = list() # store modification times of files |
| 29 |
check_time = function(path) { |
| 30 |
t2 = if (dir.exists(path)) { |
| 31 |
file.info(list.files(path, full.names = TRUE))[, 'mtime', drop = FALSE] |
| 32 |
} else file.mtime(path) |
| 33 |
t = t1[[path]]; t1[[path]] <<- t2 |
| 34 |
!is.null(t) && !(is.null(dim(t2)) && is.na(t2)) && !identical(t2, t) |
| 35 |
} |
| 36 |
|
| 37 |
new_app('litedown', function(path, query, post, headers) { |
| 38 |
# set up proper default options for mark() |
| 39 |
opt = options( |
| 40 |
litedown.html.meta = list( |
| 41 |
css = asset_url(c('default.css', if (dir.exists(path)) 'listing.css')) |
| 42 |
), |
| 43 |
litedown.html.options = list(embed_resources = FALSE), |
| 44 |
litedown.roaming = TRUE |
| 45 |
) |
| 46 |
on.exit(options(opt), add = TRUE) |
| 47 |
# capture errors in fuse() because I don't know if it's possible to capture |
| 48 |
# general errors in the handler; without capturing errors, users will see a |
| 49 |
# plain-text error page, which may be hard to understand |
| 50 |
opts = reactor(error = TRUE); on.exit(reactor(opts), add = TRUE) |
| 51 |
query = as.list(query) |
| 52 |
ext = tolower(file_ext(path)) |
| 53 |
# we keep POSTing to the page assets' URLs, and if an asset file has been |
| 54 |
# modified, we return a response telling the browser to update it |
| 55 |
type = if (length(headers)) grep_sub( |
| 56 |
'.*\nlitedown-data: ([^[:space:]]+).*', '\\1', rawToChar(headers) |
| 57 |
) |
| 58 |
if (length(type) != 1) type = '' |
| 59 |
# we may need to check rawToChar(headers) to decide what to do for the |
| 60 |
# request; for now, we simply ignore request headers, and treat the POST |
| 61 |
# body as the type of request |
| 62 |
if (type == 'open') { |
| 63 |
xfun:::open_path( |
| 64 |
query[['path']] %||% path, !dir.exists(path) && is_text_file(file = path), |
| 65 |
as.integer(query[['line']]) %|% -1L |
| 66 |
) |
| 67 |
return(list(payload = 'done')) |
| 68 |
} |
| 69 |
# create a new file with selected features |
| 70 |
if (grepl('^new($|:)', type)) |
| 71 |
return(list(payload = if (type == 'new') feature_form(path) else new_file(path, ext, type))) |
| 72 |
# render Rmd in new R sessions and save to file |
| 73 |
if (type == 'save') { |
| 74 |
return(if (is_lite_ext(ext)) { |
| 75 |
# check if the file is for a book or site |
| 76 |
info = proj_info(path) |
| 77 |
list(payload = paste('Rendered and saved:', switch( |
| 78 |
info$type, |
| 79 |
book = Rscript_call(fuse_book, list(info$root)), |
| 80 |
site = { Rscript_call(fuse_site, list(info$root)); info$root }, |
| 81 |
if (ext == 'md') mark(path) else Rscript_call(fuse, list(path)) |
| 82 |
))) |
| 83 |
} else { |
| 84 |
list(payload = paste0( |
| 85 |
"Unable to render '", path, "' (only ", |
| 86 |
paste0('.', lite_exts, collapse = ', '), " are supported)." |
| 87 |
)) |
| 88 |
}) |
| 89 |
} |
| 90 |
# clean up __files/ |
| 91 |
if (type == 'cleanup') { |
| 92 |
if (dir.exists(fig <- fig_path(path)) && |
| 93 |
!is.null(fig_time <- .env$roam_files[[fig]]) && |
| 94 |
!dir.exists(aux_path(, 'cache.path', path))) { |
| 95 |
fig_time2 = file.mtime(fig) |
| 96 |
# remove fig dir if it has not been modified since its mtime was |
| 97 |
# recorded last time (in file_resp()); if it has, update to new mtime so |
| 98 |
# we can clean it up next time when we receive the request; checking |
| 99 |
# mtime is necessary because the Ajax cleanup request (sent from the |
| 100 |
# 'beforeunload' event) may arrive _after_ file_resp() rebuilds the |
| 101 |
# current page when the page is refreshed, which may be counterintuitive |
| 102 |
# but Ajax is _asynchronous_ anyway (this took me hours to figure out) |
| 103 |
.env$roam_files[[fig]] = if (fig_time2 <= fig_time) { |
| 104 |
unlink(fig, recursive = TRUE); NULL |
| 105 |
} else fig_time2 |
| 106 |
} |
| 107 |
return(list(payload = '')) |
| 108 |
} |
| 109 |
# TODO: should we implement Hugo's --navigateToChanged? |
| 110 |
if (live && type != '') { |
| 111 |
resp = '' |
| 112 |
if (type %in% c('asset', 'page')) { |
| 113 |
if (check_time(path)) resp = '1' |
| 114 |
} else if (grepl('^book:', type) && check_time(f <- sub('^book:', '', type))) { |
| 115 |
store_book(dirname(path), f) |
| 116 |
# the book file path to preview is encoded in `type = book:foo/bar.Rmd` |
| 117 |
resp = fuse_book(c(dirname(path), f), 'html', globalenv()) |
| 118 |
} |
| 119 |
return(list(payload = resp)) |
| 120 |
} |
| 121 |
res = lite_handler(path, query, post, headers) |
| 122 |
# inject js to communicate with the R server via POST for live preview |
| 123 |
p = res$payload |
| 124 |
if (is.null(p) || (res[['content-type']] %||% 'text/html') != 'text/html') |
| 125 |
return(res) |
| 126 |
p = sub( |
| 127 |
'</head>', one_string(c( |
| 128 |
if (live) '<meta name="live-previewer" content="litedown::roam">', |
| 129 |
gen_tags(asset_url('server.css')), '</head>' |
| 130 |
)), p, fixed = TRUE |
| 131 |
) |
| 132 |
p = sub( |
| 133 |
'</body>', one_string(c(gen_tags(asset_url('server.js')), '</body>')), p, |
| 134 |
fixed = TRUE |
| 135 |
) |
| 136 |
res$payload = p |
| 137 |
res |
| 138 |
}, ...) |
| 139 |
}) |
| 140 |
|
| 141 |
# a handler returns list(payload, file, `content-type`, header, `status code`) |
| 142 |
lite_handler = function(path, query, post, headers) { |
| 143 |
if (dir.exists(path)) list(payload = dir_page(path)) else { |
| 144 |
file_page(path, query[['preview']] %||% '0') |
| 145 |
} |
| 146 |
} |
| 147 |
|
| 148 |
dir_page = function(dir = '.') { |
| 149 |
files = list.files(dir, full.names = TRUE) |
| 150 |
# index.* files should appear first |
| 151 |
files = files[order(!sans_ext(basename(files)) == 'index')] |
| 152 |
# show file size and mtime |
| 153 |
info = function(f, b, extra = '') { |
| 154 |
sprintf( |
| 155 |
'_( [%s](<%s>){title="Raw file"} %s%s%s)_', file_size(f), b, file_time(f), |
| 156 |
if (is_text_file(file = f)) btn('.open', b) else '', extra |
| 157 |
) |
| 158 |
} |
| 159 |
# create link to preview a file |
| 160 |
p_link = function(f, t = f, n = 1, a = NULL) { |
| 161 |
btn(t, sprintf('%s?preview=%d', f, n), a) |
| 162 |
} |
| 163 |
i1 = is_lite_ext(file = files) |
| 164 |
# order first by folder, then by .Rmd/.R, and other files go to the end |
| 165 |
res = lapply(files[i1][order(grepl('^[_.]', basename(files[i1])))], function(f) { |
| 166 |
b = basename(f) |
| 167 |
fenced_div(c( |
| 168 |
fenced_div(c( |
| 169 |
p_link(b, a = NULL), info(f, b, btn('.save', b)), |
| 170 |
p_link(b, '.run', 2, 'title="Run in memory"') |
| 171 |
), '.caption .name'), |
| 172 |
fenced_block(readLines(f, n = 10, encoding = 'UTF-8', warn = FALSE)) |
| 173 |
), '.box') |
| 174 |
}) |
| 175 |
files = files[!i1] |
| 176 |
i2 = dir.exists(files) |
| 177 |
res = c(res, '', lapply(files[order(!i2, files)], function(f) { |
| 178 |
b = basename(f) |
| 179 |
if (d <- dir.exists(f)) b = paste0(b, '/') |
| 180 |
sprintf( |
| 181 |
'- [%s](<%s%s>) %s', b, b, if (d) '' else '?preview=1', |
| 182 |
if (d) '' else info(f, b) |
| 183 |
) |
| 184 |
})) |
| 185 |
mark_full(unlist(res), meta = list(title = dir_title(dir))) |
| 186 |
} |
| 187 |
|
| 188 |
# add directory navigation to the top of the page |
| 189 |
file_page = function(x, preview) { |
| 190 |
res = file_resp(x, preview) |
| 191 |
if (is.null(p <- res$payload)) return(res) |
| 192 |
# inject navigation links to the top of the page |
| 193 |
nav = dir_title(x, preview) |
| 194 |
nav = sub('<p>', '<p class="nav-path">', nav, fixed = TRUE) |
| 195 |
res$payload = sub('<body>', paste0('<body>\n', nav), p, fixed = TRUE) |
| 196 |
res |
| 197 |
} |
| 198 |
|
| 199 |
# extensions that litedown can render |
| 200 |
lite_exts = c('md', 'rmd', 'qmd', 'r') |
| 201 |
|
| 202 |
is_lite_ext = function(ext = file_ext(file), file) tolower(ext) %in% lite_exts |
| 203 |
|
| 204 |
# render the path to HTML if possible |
| 205 |
file_resp = function(x, preview) { |
| 206 |
raw = preview == '0' # 0: send raw response; 1: render verbatim; 2: fuse()/mark() |
| 207 |
ext = if (raw) '' else tolower(file_ext(x)) |
| 208 |
if (preview == '2' && is_lite_ext(ext)) { |
| 209 |
# to clean up the __files/ dir if requested (via options()) and the dir |
| 210 |
# didn't exist before |
| 211 |
if (getOption('litedown.roam.cleanup', FALSE)) { |
| 212 |
fig = fig_path(x) |
| 213 |
if (!dir.exists(fig)) on.exit({ |
| 214 |
if (dir.exists(fig)) .env$roam_files[[fig]] = file.mtime(fig) |
| 215 |
}) |
| 216 |
} |
| 217 |
# check if the file is for a book or site |
| 218 |
info = proj_info(x) |
| 219 |
list(payload = switch( |
| 220 |
info$type, |
| 221 |
book = { |
| 222 |
store_book(info$root, x, info$index) |
| 223 |
fuse_book(if (info$index) info$root else x, full_output, globalenv()) |
| 224 |
}, |
| 225 |
site = fuse_site(x), |
| 226 |
if (ext == 'md') mark_full(x) else fuse(x, full_output, envir = globalenv()) |
| 227 |
)) |
| 228 |
} else { |
| 229 |
type = mime_type(x) |
| 230 |
if (!raw && is_text_file(ext, type) && |
| 231 |
!inherits(txt <- try_silent(read_utf8(x, error = TRUE)), 'try-error')) { |
| 232 |
list(payload = mark_full( |
| 233 |
fenced_block(txt, lineno_attr(if (ext == '') 'plain' else ext)) |
| 234 |
)) |
| 235 |
} else { |
| 236 |
file_raw(x, type) |
| 237 |
} |
| 238 |
} |
| 239 |
} |
| 240 |
|
| 241 |
# store book dir for books to resolve number_refs() because the book may be |
| 242 |
# partially rendered (in which case we can't resolve refs to other chapters) |
| 243 |
store_book = function(dir, x, index = FALSE) { |
| 244 |
f = function(...) .mapply( |
| 245 |
function(n, v) .env[[paste0('current_', n)]] = v, |
| 246 |
c('book', 'file', 'index'), list(...) |
| 247 |
) |
| 248 |
f(dir, x, index) |
| 249 |
exit_call(function() f(NULL)) |
| 250 |
} |
| 251 |
|
| 252 |
# detect project type for a directory (_litedown.yml may be in an upper-level dir) |
| 253 |
proj_info = function(x, d = dirname(x)) { |
| 254 |
while (length(yaml <- yml_config(d)) == 0) { |
| 255 |
if (same_path(d, d2 <- file.path(d, '..'))) break |
| 256 |
d = d2 |
| 257 |
} |
| 258 |
# use the field 'type' if provided, otherwise look for 'book' or 'site' |
| 259 |
type = yaml[['type']] %||% head(intersect(c('book', 'site'), names(yaml)), 1) |
| 260 |
root = if (length(type)) d else NA |
| 261 |
if (is.na(root)) type = 'default' |
| 262 |
# a file doesn't belong to a site if it doesn't match the site file pattern |
| 263 |
if (type != 'default' && x != '') { |
| 264 |
p = yaml[[type]][['pattern']] %||% site_pattern |
| 265 |
if (!grepl(p, x)) type = 'default' |
| 266 |
} |
| 267 |
list( |
| 268 |
type = type, root = root, yaml = yaml, |
| 269 |
index = !is.na(root) && is_index(x) && same_path(x, file.path(root, basename(x))) |
| 270 |
) |
| 271 |
} |
| 272 |
|
| 273 |
full_output = structure('html', full = TRUE) |
| 274 |
# generate full HTML output (instead of fragments) |
| 275 |
mark_full = function(...) mark(..., output = full_output) |
| 276 |
|
| 277 |
# guess if a file is a text file |
| 278 |
is_text_file = function(ext = file_ext(file), type = mime_type(file), file) { |
| 279 |
(ext %in% c('js', 'latex', 'qmd', 'tex', 'xml') || grepl('^text/', type)) |
| 280 |
} |
| 281 |
|
| 282 |
is_roaming = function() isTRUE(getOption('litedown.roaming')) |
| 283 |
|
| 284 |
# return a raw file response |
| 285 |
file_raw = function(x, type = mime_type(x)) { |
| 286 |
list(file = normalizePath(x), `content-type` = type) |
| 287 |
} |
| 288 |
|
| 289 |
file_size = function(x) xfun::format_bytes(file.size(x)) |
| 290 |
file_time = function(x) format(file.mtime(x)) |
| 291 |
dir_title = function(f, preview = '1') { |
| 292 |
links = if (f != '.') { |
| 293 |
d = if (file_exists(f)) dirname(f) else f |
| 294 |
d = if (d == '.') character() else unlist(strsplit(d, '/')) |
| 295 |
b = basename(f) |
| 296 |
c( |
| 297 |
sprintf('[%s/](%s)', c('.', d), c(rev(strrep('../', seq_along(d))), './')), |
| 298 |
if (file_exists(f)) b, if (is_lite_ext(file = f)) c( |
| 299 |
btn('.save'), if (preview != '2') |
| 300 |
btn('.run', sprintf('%s?preview=2', b), 'title="Run"') |
| 301 |
), |
| 302 |
if (is_text_file(file = f)) btn('.open') |
| 303 |
) |
| 304 |
} |
| 305 |
txt = one_string(c(sprintf('_%s:_', normalize_path('.')), links), ' ') |
| 306 |
move_attrs(commonmark::markdown_html(txt, smart = TRUE)) |
| 307 |
} |
| 308 |
|
| 309 |
btn = function(t, u = '#', a = character()) { |
| 310 |
if (startsWith(t, '.')) { |
| 311 |
a = c(t, a); t = .icons[t] |
| 312 |
} |
| 313 |
a = if (is.character(a)) one_string(c('.btn-lite', a), ' ') |
| 314 |
a = if (is.null(a)) '' else paste0('{', a, '}') |
| 315 |
sprintf(' [%s](<%s>)%s ', t, u, a) |
| 316 |
} |
| 317 |
|
| 318 |
.icons = c(.open = '✎', .run = '⏵', .save = '↯') |
| 319 |
|
| 320 |
new_file = function(path, ext, type, css = NULL, js = NULL) { |
| 321 |
if (file.exists(path)) return(sprintf("The file '%s' already exists.", path)) |
| 322 |
on.exit(xfun:::open_path(path), add = TRUE) |
| 323 |
if (!is_lite_ext(ext)) return(tolower(file.create(path))) |
| 324 |
features = strsplit(sub('^new:', '', type), ',')[[1]] |
| 325 |
a = assets[features, , drop = FALSE] |
| 326 |
m = list( |
| 327 |
title = 'Comfortably Untitled', |
| 328 |
author = tools::toTitleCase(Sys.getenv('USERNAME', Sys.getenv('USER'))), |
| 329 |
date = format(Sys.Date()) |
| 330 |
) |
| 331 |
if (nrow(a)) m$output$html = list(meta = list( |
| 332 |
css = I(na_omit(a[, 'css'])), js = I(na_omit(a[, 'js'])) |
| 333 |
)) |
| 334 |
txt = c('---', xfun::taml_save(m), '---', '', 'Relax. I need some information first.') |
| 335 |
if (ext == 'r') txt = paste("#'", split_lines(txt)) |
| 336 |
write_utf8(txt, path) |
| 337 |
'view' |
| 338 |
} |