From dc6aeaac4c0162e8b9046d496b900ef291cb66cc Mon Sep 17 00:00:00 2001 From: Hadley Wickham Date: Thu, 18 Apr 2024 17:13:25 -0500 Subject: [PATCH] Tweak source srcrefs Fixes #2402 --- NEWS.md | 2 ++ R/tweak-tags.R | 16 ++++++++++++---- tests/testthat/test-tweak-tags.R | 13 ++++++++++++- 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/NEWS.md b/NEWS.md index 3e3f620af..65a628509 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,7 @@ # pkgdown (development version) +* `` tags now have their `srcref` attributes tweaked in the same way that the `src` attributes of `` tags are (#2402). + # pkgdown 2.0.9 * Fixes for regressions in 2.0.8: diff --git a/R/tweak-tags.R b/R/tweak-tags.R index 7c9b8cb60..b61698ecd 100644 --- a/R/tweak-tags.R +++ b/R/tweak-tags.R @@ -83,11 +83,19 @@ tweak_link_external <- function(html, pkg = list()) { # Fix relative image links tweak_img_src <- function(html) { + fix_path <- function(x) { + x <- gsub("(^|/)vignettes/", "\\1articles/", x, perl = TRUE) + x <- gsub("(^|/)man/figures/", "\\1reference/figures/", x, perl = TRUE) + x + } + imgs <- xml2::xml_find_all(html, ".//img[not(starts-with(@src, 'http'))]") - urls <- xml2::xml_attr(imgs, "src") - new_urls <- gsub("(^|/)vignettes/", "\\1articles/", urls, perl = TRUE) - new_urls <- gsub("(^|/)man/figures/", "\\1reference/figures/", new_urls, perl = TRUE) - purrr::map2(imgs, new_urls, ~ xml2::xml_set_attr(.x, "src", .y)) + urls <- fix_path(xml2::xml_attr(imgs, "src")) + purrr::map2(imgs, urls, ~ xml2::xml_set_attr(.x, "src", .y)) + + imgs <- xml2::xml_find_all(html, ".//source[not(starts-with(@srcset, 'http'))]") + urls <- fix_path(xml2::xml_attr(imgs, "srcset")) + purrr::map2(imgs, urls, ~ xml2::xml_set_attr(.x, "srcset", .y)) invisible() } diff --git a/tests/testthat/test-tweak-tags.R b/tests/testthat/test-tweak-tags.R index 5a08e9891..7101c960f 100644 --- a/tests/testthat/test-tweak-tags.R +++ b/tests/testthat/test-tweak-tags.R @@ -198,6 +198,18 @@ test_that("tweak_link_r6() correctly modifies link to inherited R6 classes", { ) }) + +test_that("tweak_img_src() updates img and source tags", { + html <- xml2::read_html(' + + + ') + + tweak_img_src(html) + expect_equal(xpath_attr(html, ".//img", "src"), "reference/figures/bar.png") + expect_equal(xpath_attr(html, ".//source", "srcset"), "reference/figures/foo.png") +}) + test_that("tweak_img_src() doesn't modify absolute links", { html <- xml2::read_html(' @@ -212,7 +224,6 @@ test_that("tweak_img_src() doesn't modify absolute links", { ) }) - # stripped divs etc ------------------------------------------------------- test_that("selectively remove hide- divs", {