Skip to content

Commit 71ea953

Browse files
committed
be fussy about margin input length
1 parent fd5a5b1 commit 71ea953

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

R/margins.R

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,20 @@
88
margin <- S7::new_class(
99
"margin", parent = S7::new_S3_class(c("simpleUnit", "unit", "unit_v2")),
1010
constructor = function(t = 0, r = 0, b = 0, l = 0, unit = "pt") {
11+
lens <- c(length(t), length(r), length(b), length(l))
12+
if (any(lens != 1)) {
13+
incorrect <- c("t", "r", "b", "l")[lens != 1]
14+
s <- if (length(incorrect) > 1) "s" else ""
15+
cli::cli_warn(c(
16+
"In {.fn margin}, the argument{s} {.and {.arg {incorrect}}} should \\
17+
have length 1, not length {.and {lens[lens != 1]}}.",
18+
i = "Argument{s} get(s) truncated to length 1."
19+
))
20+
t <- t[1]
21+
r <- r[1]
22+
b <- b[1]
23+
l <- l[1]
24+
}
1125
u <- unit(c(t, r, b, l), unit)
1226
S7::new_object(u)
1327
}

tests/testthat/_snaps/theme.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,17 @@
6161
Error in `method(merge_element, list(ggplot2::element, class_any))`:
6262
! Only elements of the same class can be merged.
6363

64+
# margins() warn against wrong input lengths
65+
66+
Code
67+
margin(c(1, 2), 3, 4, c(5, 6, 7))
68+
Condition
69+
Warning:
70+
In `margin()`, the arguments `t` and `l` should have length 1, not length 2 and 3.
71+
i Arguments get(s) truncated to length 1.
72+
Output
73+
[1] 1points 3points 4points 5points
74+
6475
# Theme elements are checked during build
6576

6677
`plot.title.position` must be one of "panel" or "plot", not "test".

tests/testthat/test-theme.R

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -473,6 +473,10 @@ test_that("titleGrob() and margins() work correctly", {
473473
expect_equal(width_cm(g10), width_cm(g1) + 2)
474474
})
475475

476+
test_that("margins() warn against wrong input lengths", {
477+
expect_snapshot(margin(c(1, 2), 3, 4, c(5, 6, 7)))
478+
})
479+
476480
test_that("provided themes explicitly define all elements", {
477481
elements <- names(.element_tree)
478482

0 commit comments

Comments
 (0)