Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide better error message when adding unnamed attrib values #229

Merged
merged 11 commits into from
Apr 21, 2021
23 changes: 18 additions & 5 deletions R/tags.R
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,14 @@ tagFunction <- function(func) {
#' @export
tagAppendAttributes <- function(tag, ...) {
throw_if_tag_function(tag)
tag$attribs <- c(tag$attribs, dropNullsOrEmpty(dots_list(...)))
newAttribs <- dropNullsOrEmpty(dots_list(...))
if (any(names2(newAttribs) == "")) {
stop(
"At least one of the new attribute values did not have a name.\n",
"Did you forget to include an attribute name?"
)
}
tag$attribs <- c(tag$attribs, newAttribs)
tag
}

Expand Down Expand Up @@ -406,9 +413,7 @@ throw_if_tag_function <- function(tag) {
tag <- function(`_tag_name`, varArgs, .noWS=NULL) {
validateNoWS(.noWS)
# Get arg names; if not a named list, use vector of empty strings
varArgsNames <- names(varArgs)
if (is.null(varArgsNames))
varArgsNames <- character(length=length(varArgs))
varArgsNames <- names2(varArgs)

# Named arguments become attribs, dropping NULL and length-0 values
named_idx <- nzchar(varArgsNames)
Expand Down Expand Up @@ -489,9 +494,17 @@ tagWrite <- function(tag, textWriter, indent=0, eol = "\n") {
textWriter$write(concat8("<", tag$name))

attribs <- flattenTagAttribs(tag$attribs)
attribNames <- names2(attribs)
if (any(!nzchar(attribNames))) {
# Can not display attrib without a key
stop(
"A tag's attribute value did not have a name.\n",
"Did you forget to name all of your attribute values?"
)
}

# write attributes
for (attrib in names(attribs)) {
for (attrib in attribNames) {
attribValue <- attribs[[attrib]]
if (!is.na(attribValue)) {
if (is.logical(attribValue))
Expand Down
19 changes: 19 additions & 0 deletions tests/testthat/test-tags.r
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,25 @@ test_that("Adding attributes to tags", {
)
})

test_that("Adding unnamed attributes creates a warning", {
expect_error(
tagAppendAttributes(
tags$div(),
"value"
),
"include an attribute name"
)

x <- div()
x$attribs[[1]] <- "value"
expect_error(
print(x),
"name all of your attribute values"
)
})



test_that("Testing for attributes on tags", {
t1 <- tags$div("foo", class = "c1", class = "c2", id = "foo")

Expand Down