Skip to content

Commit

Permalink
fix: HTML/SVG boolean attributes (withastro#2538)
Browse files Browse the repository at this point in the history
* fix: HTML/SVG boolean attributes

* fix: update case-sensitivity of attributes

* Update packages/astro/src/runtime/server/index.ts

Co-authored-by: Jonathan Neal <[email protected]>

Co-authored-by: Jonathan Neal <[email protected]>
  • Loading branch information
natemoo-re and jonathantneal authored Feb 4, 2022
1 parent 3dbf654 commit a2f5535
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/runtime/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ export { createMetadata } from './metadata.js';
export { escapeHTML, unescapeHTML } from './escape.js';

const voidElementNames = /^(area|base|br|col|command|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)$/i;
const htmlBooleanAttributes = /^(allowfullscreen|async|autofocus|autoplay|controls|default|defer|disabled|disablepictureinpicture|disableremoteplayback|formnovalidate|hidden|loop|nomodule|novalidate|open|playsinline|readonly|required|reversed|scoped|seamless|itemscope)$/i;
const htmlEnumAttributes = /^(contenteditable|draggable|spellcheck|value)$/i;
// Note: SVG is case-sensitive!
const svgEnumAttributes = /^(autoReverse|externalResourcesRequired|focusable|preserveAlpha)$/i;

// INVESTIGATE:
// 2. Less anys when possible and make it well known when they are needed.
Expand Down Expand Up @@ -327,10 +331,17 @@ const STATIC_DIRECTIVES = new Set(['set:html', 'set:text']);

// A helper used to turn expressions into attribute key/value
export function addAttribute(value: any, key: string) {
if (value == null || value === false) {
if (value == null) {
return '';
}

if (value === false) {
if (htmlEnumAttributes.test(key) || svgEnumAttributes.test(key)) {
return unescapeHTML(` ${key}="false"`);
}
return ''
}

// compiler directives cannot be applied dynamically, log a warning and ignore.
if (STATIC_DIRECTIVES.has(key)) {
// eslint-disable-next-line no-console
Expand All @@ -345,8 +356,8 @@ Make sure to use the static attribute syntax (\`${key}={value}\`) instead of the
return unescapeHTML(` ${key.slice(0, -5)}="${toAttributeString(serializeListValue(value))}"`);
}

// Boolean only needs the key
if (value === true && key.startsWith('data-')) {
// Boolean values only need the key
if (value === true && (key.startsWith('data-') || htmlBooleanAttributes.test(key))) {
return unescapeHTML(` ${key}`);
} else {
return unescapeHTML(` ${key}="${toAttributeString(value)}"`);
Expand Down

0 comments on commit a2f5535

Please sign in to comment.