Skip to content

Commit

Permalink
refactor: improve serializing of object to html attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
thetutlage committed Aug 14, 2023
1 parent c6c60a2 commit 5d6b39d
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 5 deletions.
11 changes: 6 additions & 5 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,19 +275,20 @@ export function stringifyAttributes(props: any, namespace?: string): string {
}

const propInfo = find(html, key)
const attribute = propInfo.attribute

/**
* Ignore svg elements and their attributes
* Ignore unknown attributes
*/
if (!propInfo || propInfo.space === 'svg') {
if (!propInfo) {
return result
}

const attribute = propInfo.attribute

/**
* Boolean properties
*/
if (propInfo.boolean) {
if (value === true) {
result.push(attribute)
return result
}
Expand All @@ -303,7 +304,7 @@ export function stringifyAttributes(props: any, namespace?: string): string {
value = `"${classNames(value)}"`
} else if (Array.isArray(value)) {
value = `"${value.join(propInfo.commaSeparated ? ',' : ' ')}"`
} else if (!propInfo.booleanish && !propInfo.number) {
} else {
value = `"${String(value)}"`
}

Expand Down
56 changes: 56 additions & 0 deletions tests/globals/attrs.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,62 @@ test.group('Template | toAttributes', () => {
)
})

test('handle overloaded boolean properties', async ({ assert }) => {
const processor = new Processor()
const compiler = new Compiler(loader, tags, processor, { cache: false })
const template = new Template(compiler, edgeGlobals, {}, processor)

const html = await template.renderRaw(
dedent`
<button {{
html.attrs({
download: true
})
}}>
Click here
</button>
`,
{}
)

assert.stringEqual(
html,
dedent`
<button download>
Click here
</button>
`
)
})

test('handle overloaded boolean properties with explicit value', async ({ assert }) => {
const processor = new Processor()
const compiler = new Compiler(loader, tags, processor, { cache: false })
const template = new Template(compiler, edgeGlobals, {}, processor)

const html = await template.renderRaw(
dedent`
<button {{
html.attrs({
download: 'sample.pdf'
})
}}>
Click here
</button>
`,
{}
)

assert.stringEqual(
html,
dedent`
<button download="sample.pdf">
Click here
</button>
`
)
})

test('allow non-standard attributes', async ({ assert }) => {
const processor = new Processor()
const compiler = new Compiler(loader, tags, processor, { cache: false })
Expand Down

0 comments on commit 5d6b39d

Please sign in to comment.