Debian Codegraph @

R/site.R

raw
1 #' Fuse R Markdown documents individually under a directory
2 #'
3 #' Run [fuse()] on R Markdown documents individually to generate a website.
4 #'
5 #' If a directory contains a config file `_litedown.yml`, which has a YAML field
6 #' `site`, the directory will be recognized as a site root directory. The YAML
7 #' field `output` will be applied to all R Markdown files (an individual R
8 #' Markdown file can provide its own `output` field in YAML to override the
9 #' global config). For example:
10 #'
11 #' ```yaml
12 #' ---
13 #' site:
14 #' rebuild: "outdated"
15 #' pattern: "[.]R?md$"
16 #' output:
17 #' html:
18 #' meta:
19 #' css: ["@default"]
20 #' include_before: "[Home](/) [About](/about.html)"
21 #' include_after: "© 2024 | [Edit]($input$)"
22 #' ---
23 #' ```
24 #'
25 #' The option `rebuild` determines whether to rebuild `.Rmd` files. Possible
26 #' values are:
27 #'
28 #' - `newfile`: Build an input file if it does not have a `.html` output file.
29 #'
30 #' - `outdated`: Rebuild an input file if the modification time of its `.html`
31 #' output file is older than the input.
32 #' @param input The root directory of the site, or a vector of input file paths.
33 #' @return Output file paths (invisibly).
34 #' @export
35 fuse_site = function(input = '.') {
36 info = NULL; preview = FALSE
37 inputs = if (length(input) == 1 && dir.exists(input)) {
38 info = proj_info('', input)
39 find_input(input, TRUE, info$yaml[['site']][['pattern']])
40 } else {
41 info = proj_info(input[1])
42 preview = is_roaming() && length(input) == 1
43 input
44 }
45 root = info$root
46 output = with_ext(inputs, '.html')
47 cfg = merge_list(list(rebuild = 'outdated'), info$yaml[['site']])
48 b = cfg[['rebuild']]
49 if (b == 'outdated') b = 0
50 i = if (is.numeric(b)) filter_outdated(inputs, output, b) else {
51 if (b == 'newfile') !file_exists(output) else TRUE
52 }
53 opts = yaml_field(info$yaml, 'html', c('meta', 'options'))
54 opts[['meta']] = merge_list(list(
55 css2 = c(site_css, '@site'), js2 = site_js,
56 include_before = nav_menu(info), include_after = format(Sys.Date(), '© %Y')
57 ), opts[['meta']])
58 opts[['options']] = merge_list(
59 list(embed_resources = FALSE, toc = TRUE), opts[['options']]
60 )
61 out = lapply(inputs[i], function(x) {
62 res = if (grepl('[.]md$', x)) {
63 opts = set_site_options(opts, x, root); on.exit(options(opts))
64 mark(x, full_output)
65 } else {
66 Rscript_call(
67 function(x, opts, set, root, flag, output) {
68 set(opts, x, root, list(litedown.roaming = flag))
69 litedown::fuse(x, output, envir = globalenv())
70 },
71 list(x, opts, set_site_options, root, is_roaming(), full_output),
72 fail = paste('Failed to run litedown::fuse() on', x)
73 )
74 }
75 # resolve / to relative paths
76 if (!is.na(info$root)) {
77 up = relative_path(info$root, dirname(x))
78 if (up == '.') up = ''
79 res = match_replace(res, ' (href|src)(=")/', function(z) {
80 gsub('/$', up, z)
81 })
82 }
83 if (preview) res else write_utf8(res, with_ext(x, '.html'))
84 })
85 if (preview) {
86 if (i) out[[1]] else xfun::file_string(output)
87 } else invisible(output)
88 }
89
90 # common css/js for sites/books
91 site_css = c('@default', '@article', '@copy-button', '@heading-anchor', '@pages')
92 site_js = c('@sidenotes', '@appendix', '@toc-highlight', '@copy-button', '@heading-anchor', '@pages')
93
94 # set global options litedown.html.[meta|options] read from _litedown.yml
95 set_site_options = function(opts, input, root, extra = NULL) {
96 m = opts[['meta']]
97 for (i in c('include_before', 'include_after')) {
98 if (!is.character(m[[i]])) next
99 tag = if (i == 'include_before') 'nav' else 'footer'
100 x = mark(I(one_string(m[[i]], test = c(dirname(input), root))))
101 x = sprintf('<%s>%s</%s>', tag, x, tag)
102 m[[i]] = sub_vars(x, list(input = I(input)))
103 }
104 opts[['meta']] = m
105 options(c(set_names(opts, paste0('litedown.html.', names(opts))), extra))
106 }
107
108 filter_outdated = function(x, x2, n) {
109 m1 = file.mtime(x); m2 = file.mtime(x2); is.na(m2) | m1 - m2 > n
110 }
111
112 # build a nav menu from filenames under root directory
113 nav_menu = function(info) {
114 if (is.na(info$root)) return('[Home](/index.html)')
115 files = find_input(info$root, FALSE, info$yaml[['site']][['pattern']])
116 b = basename(files)
117 x = gsub('[-_]', ' ', sans_ext(ifelse(is_index(b), 'home', b)))
118 sprintf(
119 '[%s](/%s)', tools::toTitleCase(x),
120 if (is_roaming()) paste0(b, '?preview=2') else with_ext(b, '.html')
121 )
122 }
123
124 #' Fuse multiple R Markdown documents to a single output file
125 #'
126 #' This is a helper function to [fuse()] `.Rmd` files and convert all their
127 #' Markdown output to a single output file, which is similar to
128 #' `bookdown::render_book()`, but one major differences is that all HTML output
129 #' is written to one file, instead of one HTML file per chapter.
130 #'
131 #' If the output format needs to be customized, the settings should be written
132 #' in the config file `_litedown.yml`, e.g.,
133 #'
134 #' ```yaml
135 #' ---
136 #' output:
137 #' html:
138 #' options:
139 #' toc:
140 #' depth: 4
141 #' latex:
142 #' meta:
143 #' documentclass: "book"
144 #' ```
145 #'
146 #' In addition, you can configure the book via the `book` field, e.g.,
147 #'
148 #' ```yaml
149 #' ---
150 #' book:
151 #' new_session: true
152 #' subdir: false
153 #' pattern: "[.]R?md$"
154 #' chapter_before: "Information before a chapter."
155 #' chapter_after: "This chapter was generated from `$input$`."
156 #' ---
157 #' ```
158 #'
159 #' The option `new_session` specifies whether to render each input file in the
160 #' current R session or a separate new R session; `chapter_before` and
161 #' `chapter_after` specify text to be added to the beginning and end of each
162 #' file, respectively, which accepts some variables (e.g., `$input$` is the
163 #' current input file path).
164 #' @inheritParams fuse
165 #' @param input A directory or a vector of file paths. By default, all
166 #' `.Rmd`/`.md` files under the current working directory are used as the
167 #' input, except for filenames that start with `.` or `_` (e.g., `_foo.Rmd`),
168 #' or `.md` files with the same base names as `.Rmd` files (e.g., `bar.md`
169 #' will not be used if `bar.Rmd` exists). For a directory `input`, the file
170 #' search will be recursive if `input` ends with a slash (i.e.,
171 #' sub-directories will also be searched). If a file named `index.Rmd` or
172 #' `index.md` exists, it will always be treated as the first input file. Input
173 #' files can also be specified in the config file `_litedown.yml` (in the
174 #' `input` field under `book`).
175 #' @return An output file path or the output content, depending on the `output`
176 #' argument.
177 #' @export
178 fuse_book = function(input = '.', output = NULL, envir = parent.frame()) {
179 # when input is c(dir, file1, file2, ...), we find book files under dir, but
180 # only preview file1, file2, ...
181 if (dir.exists(input[1])) {
182 preview = input[-1]; input = input[1]
183 } else preview = NULL
184
185 yaml = NULL
186 # search for book files or read from config if input is a dir
187 if (length(input) == 1 && dir.exists(input)) {
188 yaml = yml_config(input)
189 cfg = yaml[['book']]
190 input = file.path(input, cfg[['input']]) %|%
191 find_input(input, cfg[['subdir']] %||% grepl('/$', input), cfg[['pattern']])
192 } else {
193 # if input files are provided directly, read config from the dir of first file
194 cfg = if (length(input)) {
195 yaml = yml_config(dirname(input[1]))
196 yaml[['book']]
197 }
198 }
199 if (length(input) == 0) stop('No input was provided or found.')
200 input = sub('^[.]/+', '', input) # clean up the leading ./ in paths
201
202 full = is_output_full(output)
203 format = detect_format(output, yaml)
204 output = auto_output(input[1], output, format)
205 cfg = merge_list(list(
206 new_session = FALSE, chapter_before = '', chapter_after = "Source: `$input$`"
207 ), cfg)
208
209 # provide a simpler way to configure timing in YAML; only env vars are
210 # inherited in new R sessions, so we attach the timing path to R_LITEDOWN_TIME
211 if (is.character(p <- cfg$time)) {
212 # treat relative path as a path relative to the first input's cache dir
213 if (is_rel_path(p))
214 p = file.path(paste0(sans_ext(normalize_path(input[1])), '__cache'), p)
215 vars = set_envvar(c(R_LITEDOWN_TIME = p))
216 on.exit(set_envvar(vars), add = TRUE)
217 if (file_exists(p)) {
218 # filter out data from input files that do not belong to the book
219 d = readRDS(p)
220 if (!all(i <- d$source %in% input)) {
221 d = d[i, ]; saveRDS(d, p)
222 }
223 } else dir_create(dirname(p))
224 }
225
226 res = lapply(preview %|% input, function(x) {
227 out = if (grepl('[.]md$', x)) read_utf8(x) else {
228 fmt = paste0('markdown:', format) # generate intermediate markdown output
229 if (cfg$new_session) {
230 Rscript_call(fuse, list(x, fmt))
231 } else {
232 fuse(x, fmt, NULL, envir)
233 }
234 }
235 # remove YAML in the preview mode or for non-index chapters since we only need the body
236 if (length(preview) || isFALSE(.env$current_index) || x != input[1])
237 out = sans_yaml(out)
238
239 if (format != 'html') return(out)
240 # add input filenames to the end for HTML output and wrap each file in a div
241 info = function(cls) c(
242 sprintf('::: {.chapter-%s .side .side-right}', cls),
243 sub_vars(cfg[[sprintf('chapter_%s', cls)]], list(input = I(x))), ':::'
244 )
245 # for the first input, the fenced Divs should be inserted after YAML
246 h = if (length(preview) == 0 && x == input[1]) {
247 out = split_lines(out)
248 if (length(i <- xfun:::locate_yaml(out)) >= 2) {
249 i = seq_len(i[2]); h = out[i]; out = out[-i]
250 h
251 }
252 }
253 c(
254 h, sprintf('::: {.chapter .body data-source="%s"}', x),
255 info('before'), '', out, '', info('after'), ':::'
256 )
257 })
258 tweak_options(format, yaml, list(
259 body_class = '', css2 = c(site_css, '@book'), js2 = site_js
260 ), toc = length(preview) == 0)
261 fuse_output(input[1], output, unlist(res), full)
262 }
263
264 # read the config file _litedown.yml
265 yml_config = function(d) {
266 if (file_exists(cfg <- file.path(d, '_litedown.yml'))) {
267 yaml = xfun::taml_file(cfg)
268 if (!is.null(yaml2 <- normalize_yaml(yaml))) yaml = yaml2
269 yaml
270 }
271 }
272
273 site_pattern = '[.][Rq]?md$'
274
275 # find input files under a directory
276 find_input = function(d, deep = grepl('/$', d), pattern = NULL) {
277 if (!is.character(pattern)) pattern = site_pattern
278 x = list.files(d, pattern, full.names = TRUE, recursive = deep)
279 # exclude .* and _* files
280 x = x[!grepl('^[_.]', basename(x))]
281 # exclude readme
282 x = x[tolower(basename(sans_ext(x))) != 'readme']
283 # for .md files, don't include them if they have .Rmd/.qmd files
284 b = sans_ext(x); i = file_ext(x) == 'md'
285 x = x[!i | !(b %in% sub('[.][Rq]md$', '', x))]
286 x = reorder_input(x)
287 x = sub('^[.]/+', '', x)
288 x
289 }
290
291 # move index.[Rq]md to the first
292 reorder_input = function(x) {
293 i = is_index(x)
294 index = x[i][which.min(nchar(x[i]))] # take the shortest path
295 c(index, setdiff(x, index))
296 }
297
298 is_index = function(x) sans_ext(basename(x)) == 'index'
299
300 # temporarily set global metadata and options (inheriting from index.Rmd)
301 tweak_options = function(format, yaml, meta = NULL, toc = TRUE, options = NULL) {
302 nms = paste0('litedown.', format, c('.meta', '.options'))
303 defaults = list(
304 merge_list(
305 .Options[[nms[1]]], meta, yaml_field(yaml, format, 'meta')
306 ),
307 merge_list(
308 .Options[[nms[2]]], options,
309 list(toc = toc, number_sections = TRUE, embed_resources = FALSE),
310 yaml_field(yaml, format, 'options')
311 )
312 )
313 names(defaults) = nms
314 opts = options(defaults)
315 exit_call(function() options(opts))
316 }