Skip to content

Commit ddaa8e9

Browse files
authored
(feat) transform number attrs (#428)
#366 When 1. an attribute expects input of number only 2. its value is of type number 3. attribute is written as string then transform it Example: `<div tabindex="1"></div>` --> `<div tabindex={1}></div>`
1 parent c03b6ad commit ddaa8e9

File tree

3 files changed

+47
-2
lines changed

3 files changed

+47
-2
lines changed

packages/svelte2tsx/src/htmlxtojsx.ts

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,28 @@ const oneWayBindingAttributes: Map<string, ElementType> = new Map(
1717
),
1818
);
1919

20+
/**
21+
* List taken from `svelte-jsx.d.ts` by searching for all attributes of type number
22+
*/
23+
const numberOnlyAttributes = new Set([
24+
'cols',
25+
'colspan',
26+
'high',
27+
'low',
28+
'marginheight',
29+
'marginwidth',
30+
'minlength',
31+
'maxlength',
32+
'optimum',
33+
'rows',
34+
'rowspan',
35+
'size',
36+
'span',
37+
'start',
38+
'tabindex',
39+
'results',
40+
]);
41+
2042
const beforeStart = (start: number) => start - 1;
2143

2244
type Walker = (node: Node, parent: Node, prop: string, index: number) => void;
@@ -387,8 +409,27 @@ export function convertHtmlxToJsx(
387409
const endsWithQuote =
388410
htmlx.lastIndexOf('"', attrVal.end) === attrVal.end - 1 ||
389411
htmlx.lastIndexOf("'", attrVal.end) === attrVal.end - 1;
390-
if (attrVal.end == attr.end && !endsWithQuote) {
391-
//we are not quoted. Add some
412+
const needsQuotes = attrVal.end == attr.end && !endsWithQuote;
413+
414+
const hasBrackets =
415+
htmlx.lastIndexOf('}', attrVal.end) === attrVal.end - 1 ||
416+
htmlx.lastIndexOf('}"', attrVal.end) === attrVal.end - 1 ||
417+
htmlx.lastIndexOf("}'", attrVal.end) === attrVal.end - 1;
418+
const needsNumberConversion =
419+
!hasBrackets &&
420+
parent.type === 'Element' &&
421+
numberOnlyAttributes.has(attr.name.toLowerCase()) &&
422+
!isNaN(attrVal.data);
423+
424+
if (needsNumberConversion) {
425+
if (needsQuotes) {
426+
str.prependRight(equals + 1, '{');
427+
str.appendLeft(attr.end, '}');
428+
} else {
429+
str.overwrite(equals + 1, equals + 2, '{');
430+
str.overwrite(attr.end - 1, attr.end, '}');
431+
}
432+
} else if (needsQuotes) {
392433
str.prependRight(equals + 1, '"');
393434
str.appendLeft(attr.end, '"');
394435
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
<><SomeComponent tabindex="1" />
2+
<div tabindex={1} maxlength={1} minlength={1} span={1} role="none"></div></>
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
<SomeComponent tabindex="1" />
2+
<div tabindex="1" maxlength=1 minlength={1} span="{1}" role="none"></div>

0 commit comments

Comments
 (0)