Add escapeHTML to astro/internal (#2479)

* feat: add escapeHTML to astro/internal

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

Co-authored-by: Jonathan Neal <jonathantneal@hotmail.com>

* Update escape.ts

Co-authored-by: Jonathan Neal <jonathantneal@hotmail.com>
This commit is contained in:
Nate Moore 2022-01-27 20:36:47 -06:00 committed by GitHub
parent 46085e6d8c
commit 005751a920
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 23 additions and 0 deletions

View file

@ -0,0 +1,5 @@
---
'astro': patch
---
Add the `escapeHTML` utility to `astro/internal`

View file

@ -0,0 +1,3 @@
const entities = { '"': 'quot', '&': 'amp', '\'': 'apos', '<': 'lt', '>': 'gt' } as const
export const escapeHTML = (string: any) => string.replace(/["'&<>]/g, (char: keyof typeof entities) => '&' + entities[char] + ';')

View file

@ -5,6 +5,7 @@ import shorthash from 'shorthash';
import { extractDirectives, generateHydrateScript } from './hydration.js';
import { serializeListValue } from './util.js';
export { createMetadata } from './metadata.js';
export { escapeHTML } from './escape.js';
export type { Metadata } from './metadata';
const voidElementNames = /^(area|base|br|col|command|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)$/i;
@ -308,12 +309,26 @@ export function createAstro(filePathname: string, site: string, projectRootStr:
const toAttributeString = (value: any) => String(value).replace(/&/g, '&#38;').replace(/"/g, '&#34;');
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) {
return '';
}
// compiler directives cannot be applied dynamically, log a warning and ignore.
if (STATIC_DIRECTIVES.has(key)) {
// eslint-disable-next-line no-console
console.warn(`[astro] The "${key}" directive cannot be applied dynamically at runtime. It will not be rendered as an attribute.
Make sure to use the static attribute syntax (\`${key}={value}\`) instead of the dynamic spread syntax (\`{...{ "${key}": value }}\`).`);
return '';
}
// support "class" from an expression passed into an element (#782)
if (key === 'class:list') {
return ` ${key.slice(0, -5)}="${toAttributeString(serializeListValue(value))}"`;