From 47941c4d7e6883fe9f2ba867b62f36d00cc4fb17 Mon Sep 17 00:00:00 2001 From: Nate Moore Date: Fri, 17 Jun 2022 22:11:02 -0500 Subject: [PATCH] feat: add support for object-based styles --- .changeset/sweet-dodos-mix.md | 5 +++++ packages/astro/src/runtime/server/index.ts | 6 ++++++ 2 files changed, 11 insertions(+) create mode 100644 .changeset/sweet-dodos-mix.md diff --git a/.changeset/sweet-dodos-mix.md b/.changeset/sweet-dodos-mix.md new file mode 100644 index 000000000..a6f1008f0 --- /dev/null +++ b/.changeset/sweet-dodos-mix.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Add support for object-based styles diff --git a/packages/astro/src/runtime/server/index.ts b/packages/astro/src/runtime/server/index.ts index 6c7b12699..588de9ecf 100644 --- a/packages/astro/src/runtime/server/index.ts +++ b/packages/astro/src/runtime/server/index.ts @@ -405,6 +405,8 @@ export function createAstro( }; } +const kebab = (k: string) => k.toLowerCase() === k ? k : k.replace(/[A-Z]/g, match => `-${match.toLowerCase()}`); +const toStyleString = (obj: Record) => Object.entries(obj).map(([k, v]) => `${kebab(k)}:${v}`).join(';') const toAttributeString = (value: any, shouldEscape = true) => shouldEscape ? String(value).replace(/&/g, '&').replace(/"/g, '"') : value; @@ -437,6 +439,10 @@ Make sure to use the static attribute syntax (\`${key}={value}\`) instead of the return markHTMLString(` ${key.slice(0, -5)}="${toAttributeString(serializeListValue(value))}"`); } + if (key === 'style' && typeof value === 'object') { + return markHTMLString(` ${key}="${toStyleString(value)}"`); + } + // Boolean values only need the key if (value === true && (key.startsWith('data-') || htmlBooleanAttributes.test(key))) { return markHTMLString(` ${key}`);