From e79ee800ae7285515a8babeef9ea2dd8af4e4e23 Mon Sep 17 00:00:00 2001
From: Simon H <5968653+dummdidumm@users.noreply.github.com>
Date: Tue, 9 Mar 2021 18:44:58 +0100
Subject: [PATCH] (fix) sanitize leading invalid attribute chars (#863)
They are valid for Svelte, but invalid for JSX
#862
---
.../src/htmlxtojsx/nodes/attribute.ts | 19 +++++++++++++++++++
.../attribute-invalid-jsx-name/expected.jsx | 2 ++
.../attribute-invalid-jsx-name/input.svelte | 2 ++
3 files changed, 23 insertions(+)
create mode 100644 packages/svelte2tsx/test/htmlx2jsx/samples/attribute-invalid-jsx-name/expected.jsx
create mode 100644 packages/svelte2tsx/test/htmlx2jsx/samples/attribute-invalid-jsx-name/input.svelte
diff --git a/packages/svelte2tsx/src/htmlxtojsx/nodes/attribute.ts b/packages/svelte2tsx/src/htmlxtojsx/nodes/attribute.ts
index f9695b5e3..44dc911f6 100644
--- a/packages/svelte2tsx/src/htmlxtojsx/nodes/attribute.ts
+++ b/packages/svelte2tsx/src/htmlxtojsx/nodes/attribute.ts
@@ -105,6 +105,12 @@ export function handleAttribute(htmlx: string, str: MagicString, attr: Node, par
}
const equals = htmlx.lastIndexOf('=', attrVal.start);
+
+ const sanitizedName = sanitizeLeadingChars(attr.name);
+ if (sanitizedName !== attr.name) {
+ str.overwrite(attr.start, equals, sanitizedName);
+ }
+
if (attrVal.type == 'Text') {
const endsWithQuote =
htmlx.lastIndexOf('"', attrVal.end) === attrVal.end - 1 ||
@@ -166,3 +172,16 @@ export function handleAttribute(htmlx: string, str: MagicString, attr: Node, par
str.appendLeft(attr.end, '`}');
}
}
+
+function sanitizeLeadingChars(attrName: string): string {
+ let sanitizedName = '';
+ for (let i = 0; i < attrName.length; i++) {
+ if (/[A-Za-z$_]/.test(attrName[i])) {
+ sanitizedName += attrName.substr(i);
+ return sanitizedName;
+ } else {
+ sanitizedName += '_';
+ }
+ }
+ return sanitizedName;
+}
diff --git a/packages/svelte2tsx/test/htmlx2jsx/samples/attribute-invalid-jsx-name/expected.jsx b/packages/svelte2tsx/test/htmlx2jsx/samples/attribute-invalid-jsx-name/expected.jsx
new file mode 100644
index 000000000..febcc007e
--- /dev/null
+++ b/packages/svelte2tsx/test/htmlx2jsx/samples/attribute-invalid-jsx-name/expected.jsx
@@ -0,0 +1,2 @@
+<>