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:
parent
46085e6d8c
commit
005751a920
3 changed files with 23 additions and 0 deletions
5
.changeset/few-papayas-swim.md
Normal file
5
.changeset/few-papayas-swim.md
Normal file
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
'astro': patch
|
||||
---
|
||||
|
||||
Add the `escapeHTML` utility to `astro/internal`
|
3
packages/astro/src/runtime/server/escape.ts
Normal file
3
packages/astro/src/runtime/server/escape.ts
Normal 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] + ';')
|
|
@ -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, '&').replace(/"/g, '"');
|
||||
|
||||
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))}"`;
|
||||
|
|
Loading…
Reference in a new issue