fix: improve spreading of attributes (#11177)

* fix: improve spreading of attributes

* twak
pull/11176/head
Dominic Gannaway 8 months ago committed by GitHub
parent d061f2f137
commit 2fa095b61e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -0,0 +1,5 @@
---
"svelte": patch
---
fix: improve spreading of attributes

@ -104,6 +104,9 @@ export function set_attributes(element, prev, attrs, lowercase_attributes, css_h
var setters = map_get(setters_cache, element.nodeName);
if (!setters) map_set(setters_cache, element.nodeName, (setters = get_setters(element)));
// @ts-expect-error
var attributes = /** @type {Record<string, unknown>} **/ (element.__attributes ??= {});
for (key in next) {
var value = next[key];
if (value === prev?.[key]) continue;
@ -140,6 +143,7 @@ export function set_attributes(element, prev, attrs, lowercase_attributes, css_h
}
}
} else if (value == null) {
attributes[key] = null;
element.removeAttribute(key);
} else if (key === 'style') {
element.style.cssText = value + '';

@ -0,0 +1,23 @@
import { flushSync } from 'svelte';
import { test } from '../../test';
export default test({
async test({ assert, target }) {
const btn = target.querySelector('button');
flushSync(() => {
btn?.click();
});
assert.htmlEqual(target.innerHTML, `<button>Toggle</button><h1>Style: not red</h1>`);
flushSync(() => {
btn?.click();
});
assert.htmlEqual(
target.innerHTML,
`<button>Toggle</button><h1 data-red="true">Style: red</h1>`
);
}
});

@ -0,0 +1,11 @@
<script>
let isRed = $state(true)
const attributes = $derived({
'data-red': isRed ? true : undefined
});
</script>
<button onclick={() => isRed = !isRed }>Toggle</button>
<h1 {...attributes}>Style: {isRed ? 'red' : 'not red'}</h1>
Loading…
Cancel
Save