Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions src/__tests__/attributes.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -691,3 +691,43 @@ for (const trailing of ["*", "$", "^", "~", "|"]) {
t.deepEqual(tree.toString(), "[href]");
});
}

for (const [quoteMark, value, expected] of [
['"', "foo", '[href="foo"]'],
['"', "foo bar", '[href="foo bar"]'],
['"', 'say "hi"', '[href="say \\"hi\\""]'],
["'", "it's", "[href='it\\'s']"],
[null, "foo bar", "[href=foo\\ bar]"],
[null, "foo", "[href=foo]"],
]) {
ava(`Attribute constructor applies quoteMark ${quoteMark} to ${value}`, (t) => {
const attr = parser.attribute({ attribute: "href", operator: "=", value, quoteMark });
t.deepEqual(attr.quoteMark, quoteMark);
t.deepEqual(attr.toString(), expected);
const reparsed = parser().astSync(attr.toString()).first.first;
t.deepEqual(reparsed.value, value);
t.deepEqual(reparsed.quoteMark, quoteMark);
});
}

ava("Attribute constructor keeps an explicit raw value", (t) => {
const attr = parser.attribute({
attribute: "href",
operator: "=",
value: "a:b",
quoteMark: '"',
raws: { value: '"a\\3A b"' },
});
t.deepEqual(attr.toString(), '[href="a\\3A b"]');
});

ava("Parsed attributes keep their original raw value state", (t) => {
for (const input of ["[href=foo]", '[href="foo"]', "[href=@{foo}]", "[href=a\\:b]"]) {
const attr = parser().astSync(input).first.first;
t.deepEqual(attr.toString(), input);
t.deepEqual(attr.clone().toString(), input);
if (!input.includes("\\") && !input.includes('"')) {
t.deepEqual(attr.raws.value, undefined);
}
}
});
9 changes: 8 additions & 1 deletion src/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -518,7 +518,14 @@ export default class Parser {
}
unescapeProp(node, "attribute");
unescapeProp(node, "namespace");
this.newNode(new Attribute(node));
const hasRawValue = node.raws && node.raws.value !== undefined;
const attribute = new Attribute(node);
// Preserve the parsed spelling, including non-standard syntax, rather
// than the quoting and escaping used for API-created attributes.
if (!hasRawValue) {
delete attribute.raws.value;
}
this.newNode(attribute);
this.position++;
}

Expand Down
5 changes: 5 additions & 0 deletions src/selectors/attribute.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,11 @@ export default class Attribute extends Namespace {
),
});
this._constructed = true;
// A value given with a quote mark is unescaped, so it still needs quoting
// and escaping for that quote mark, unless its raw spelling was given too.
if (typeof this._value === "string" && this.raws.value === undefined) {
this._syncRawValue();
}
}

/**
Expand Down
Loading