Skip to content

Commit

Permalink
fix: not converting array of strings values
Browse files Browse the repository at this point in the history
Fix not converting array of strings values. This was likely caused by naming the variable for attribute `value` and the one for the attribute value `key`. Change the variable names to be more accurate.

Add a better JSDoc type annotation for `this.args` to make more obvious when errors in normalizing attribute values occur.
  • Loading branch information
kleinfreund committed Jun 26, 2024
1 parent 6156e2c commit 9281185
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
22 changes: 15 additions & 7 deletions drupal-attribute.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
/**
* @param {Array} args
* @param {Array<[string, string[] | string | boolean]>} args
*/
function DrupalAttribute(args) {
/**
* @type {Array<[string, string[] | string | boolean]>}
*/
this.args = args;

this.args.forEach((arg) => {
Expand Down Expand Up @@ -90,14 +93,19 @@ DrupalAttribute.prototype.toString = function () {
let result = "";
let components = [];

this.args.forEach(([value, key]) => {
if (Array.isArray(value)) {
value = value.join(" ");
this.args.forEach(([attribute, value]) => {
// Ignore the special `$drupal` attribute.
if (attribute === "$drupal") {
return;
}

if (value !== "$drupal") {
components.push([value, '"' + key + '"'].join("="));
}
// Normalize array-of-strings and boolean values to strings.
const normalizedValue = Array.isArray(value)
? value.join(" ")
: typeof value === "boolean" ? String(value) : value;

// Set `attribute` instead of `attribute=""` when the value is the empty string.
components.push(attribute + (normalizedValue === "" ? "" : '="' + normalizedValue + '"'));
});

let rendered = components.join(" ");
Expand Down
8 changes: 7 additions & 1 deletion drupal-attribute.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,13 @@ describe("DrupalAttribute", () => {
"boolean-true": true,
"boolean-false": false,
},
' data-selector="" aria-controls="test" id="test" single-space=" " boolean-true="true" boolean-false="false"'
' data-selector aria-controls="test" id="test" single-space=" " boolean-true="true" boolean-false="false"'
],
[
{
class: ["one", "two", "three"],
},
` class="one two three"`,
],
])("toString", (attributes, htmlAttributeString) => {
const drupalAttribute = new DrupalAttribute(Object.entries(attributes))
Expand Down

0 comments on commit 9281185

Please sign in to comment.