Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow objects/arrays for style attribute #15311

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/green-starfishes-yawn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

feat: allow `style` attribute to be an object or array
70 changes: 69 additions & 1 deletion documentation/docs/03-template-syntax/17-style.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,75 @@
---
title: style:
title: style and style:
---

There are two ways to set styles on elements: the `style` attribute, and the `style:` directive.

## Attributes

Primitive values are treated like any other attribute:

```svelte
<div style={big ? 'font-size:2em' : 'font-size:1.2em'}>...</div>
```

### Objects and arrays

Since Svelte 5.XX, `style` can be an object or array, and is converted to a string according to the following rules :

If the value is an

If the value is an object, the key/value are converted to CSS properties if the value is not-null and not-empty.

```svelte
<!-- equivalent to <div style="color:red;display:inline"> -->
<div style={{ color: 'red', display: 'inline', background: null }}>...</div>
```

> [!NOTE]
> The CSS properties are case-insensitive and use `kebab-case`, which requires quoting key's name in JavaScript.
> In order to avoid this, object keys will be 'converted' according to the following rules :
> * Uppercase keys like `COLOR` will be converted to the lowercase format `color`.
> * `camelCase` keys like `fontSize` will be converted to the kebab-case format `font-size`.
> * `snake_case` keys like `border_color` will be converted to the kebab-case format `border-color`.
> Note that this will not apply to key that starts with a double hyphens, because CSS variable don't have naming rules and are case-sensitive (`--myvar` is different from `--myVar`).
> But we can use a double underscores to enable the same rules. Ex: `__myVar` or `__my_var` will be converted to `--my-var`.

If the value is an array, the truthy values are combined, string are passed without change, and array/objects are flatten :

```svelte
<!-- equivalent to <div style="color:red;display:inline;--my-var:0;font-size:2em;background: black"> -->
<div style={['color:red', {display:'inline'}, [{__my_var: 0, fontSize: '2em'}, 'background: black']]}>...</div>
```

This is useful for combining local styles with props, for example:

```svelte
<!--- file: Button.svelte --->
<script>
let props = $props();
</script>

<button {...props} style={[props.style, {color:'red', background:'black'}]}>
{@render props.children?.()}
</button>
```


Svelte also exposes the `StyleValue` type, which is the type of value that the `style` attribute on elements accept. This is useful if you want to use a type-safe class name in component props:

```svelte
<script lang="ts">
import type { StyleValue } from 'svelte/elements';

const props: { style: StyleValue } = $props();
</script>

<div style={[props.style, {color: 'red'}]}>...</div>
```


## The `style:` directive

The `style:` directive provides a shorthand for setting multiple styles on an element.

```svelte
Expand Down
8 changes: 6 additions & 2 deletions packages/svelte/elements.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -764,7 +764,7 @@ export interface HTMLAttributes<T extends EventTarget> extends AriaAttributes, D
placeholder?: string | undefined | null;
slot?: string | undefined | null;
spellcheck?: Booleanish | undefined | null;
style?: string | undefined | null;
style?: StyleValue | undefined | null;
tabindex?: number | undefined | null;
title?: string | undefined | null;
translate?: 'yes' | 'no' | '' | undefined | null;
Expand Down Expand Up @@ -1534,7 +1534,7 @@ export interface SVGAttributes<T extends EventTarget> extends AriaAttributes, DO
method?: 'align' | 'stretch' | undefined | null;
min?: number | string | undefined | null;
name?: string | undefined | null;
style?: string | undefined | null;
style?: StyleValue | undefined | null;
target?: string | undefined | null;
type?: string | undefined | null;
width?: number | string | undefined | null;
Expand Down Expand Up @@ -2062,3 +2062,7 @@ export interface SvelteHTMLElements {
}

export type ClassValue = string | import('clsx').ClassArray | import('clsx').ClassDictionary;

type StyleDictionary = Record<string, any>;
type StyleArray = StyleValue[];
export type StyleValue = StyleArray | StyleDictionary | string | number | null | undefined;
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,19 @@ export function Attribute(node, context) {
node.metadata.needs_clsx = true;
}

// style={[...]} or style={{...}} or `style={x}` need cssx to resolve the style
if (
node.name === 'style' &&
!Array.isArray(node.value) &&
node.value !== true &&
node.value.expression.type !== 'Literal' &&
node.value.expression.type !== 'TemplateLiteral' &&
node.value.expression.type !== 'BinaryExpression'
) {
// TODO ??? mark_subtree_dynamic(context.path);
node.metadata.needs_cssx = true;
}

if (node.value !== true) {
for (const chunk of get_attribute_chunks(node.value)) {
if (chunk.type !== 'ExpressionTag') continue;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,10 @@ function build_element_attribute_update_assignment(
} else if (is_dom_property(name)) {
update = b.stmt(b.assignment('=', b.member(node_id, name), value));
} else {
if (attribute.metadata.needs_cssx) {
value = b.call('$.cssx', value);
}

const callee = name.startsWith('xlink') ? '$.set_xlink_attribute' : '$.set_attribute';
update = b.stmt(
b.call(
Expand Down Expand Up @@ -635,6 +639,11 @@ function build_custom_element_attribute_update_assignment(node_id, attribute, co
value = b.call('$.clsx', value);
}

// We assume that noone's going to redefine the semantics of the style attribute on custom elements, i.e. it's still used for CSS styles
if (name === 'style' && attribute.metadata.needs_cssx) {
value = b.call('$.cssx', value);
}

const update = b.stmt(b.call('$.set_custom_element_data', node_id, b.literal(name), value));

if (has_state) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,11 +108,25 @@ export function build_element_attributes(node, context) {
} else {
attributes.push(attribute);
}
} else {
if (attribute.name === 'style') {
style_index = attributes.length;
}
} else if (attribute.name === 'style') {
style_index = attributes.length;

if (attribute.metadata.needs_cssx) {
const clsx_value = b.call(
'$.cssx',
/** @type {AST.ExpressionTag} */ (attribute.value).expression
);
attributes.push({
...attribute,
value: {
.../** @type {AST.ExpressionTag} */ (attribute.value),
expression: clsx_value
}
});
} else {
attributes.push(attribute);
}
} else {
attributes.push(attribute);
}
}
Expand Down
3 changes: 2 additions & 1 deletion packages/svelte/src/compiler/phases/nodes.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ export function create_attribute(name, start, end, value) {
value,
metadata: {
delegated: null,
needs_clsx: false
needs_clsx: false,
needs_cssx: false
}
};
}
Expand Down
2 changes: 2 additions & 0 deletions packages/svelte/src/compiler/types/template.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,8 @@ export namespace AST {
delegated: null | DelegatedEvent;
/** May be `true` if this is a `class` attribute that needs `clsx` */
needs_clsx: boolean;
/** May be `true` if this is a `style` attribute that needs `cssx` */
needs_cssx: boolean;
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
set_active_effect,
set_active_reaction
} from '../../runtime.js';
import { clsx } from '../../../shared/attributes.js';
import { clsx, cssx } from '../../../shared/attributes.js';

/**
* The value/checked attribute in the template actually corresponds to the defaultValue property, so we need
Expand Down Expand Up @@ -291,6 +291,10 @@ export function set_attributes(
next.class = clsx(next.class);
}

if (next.style) {
next.style = cssx(next.style);
}

if (css_hash !== undefined) {
next.class = next.class ? next.class + ' ' + css_hash : css_hash;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/svelte/src/internal/client/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ export {
$window as window,
$document as document
} from './dom/operations.js';
export { attr, clsx } from '../shared/attributes.js';
export { attr, clsx, cssx } from '../shared/attributes.js';
export { snapshot } from '../shared/clone.js';
export { noop, fallback } from '../shared/utils.js';
export {
Expand Down
8 changes: 6 additions & 2 deletions packages/svelte/src/internal/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
/** @import { Component, Payload, RenderOutput } from '#server' */
/** @import { Store } from '#shared' */
export { FILENAME, HMR } from '../../constants.js';
import { attr, clsx } from '../shared/attributes.js';
import { attr, clsx, cssx } from '../shared/attributes.js';
import { is_promise, noop } from '../shared/utils.js';
import { subscribe_to_store } from '../../store/utils.js';
import {
Expand Down Expand Up @@ -204,6 +204,10 @@ export function css_props(payload, is_html, props, component, dynamic = false) {
* @returns {string}
*/
export function spread_attributes(attrs, classes, styles, flags = 0) {
if (attrs.style) {
attrs.style = cssx(attrs.style);
}

if (styles) {
attrs.style = attrs.style
? style_object_to_string(merge_styles(/** @type {string} */ (attrs.style), styles))
Expand Down Expand Up @@ -552,7 +556,7 @@ export function props_id(payload) {
return uid;
}

export { attr, clsx };
export { attr, clsx, cssx };

export { html } from './blocks/html.js';

Expand Down
43 changes: 43 additions & 0 deletions packages/svelte/src/internal/shared/attributes.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,46 @@ export function clsx(value) {
return value ?? '';
}
}

/**
* Format a CSS key/value
* @param {[string,any]} value
* @returns {string|null}
*/
function cssx_format([k, v]) {
if (v == null) {
return null;
}
v = ('' + v).trim();
if (v === '') {
return null;
}
if (k[0] !== '-' && k[1] !== '-') {
k = k
.replaceAll('_', '-')
.replaceAll(/(?<=[a-z])[A-Z](?=[a-z])/g, (c) => '-' + c)
.toLowerCase();
}
return k + ':' + v;
}

/**
* Build a style attributes based on arrays/objects/strings
* @param {any} value
* @returns {string|null}
*/
export function cssx(value) {
if (value == null) {
return null;
}
if (typeof value === 'object') {
if (value instanceof CSSStyleDeclaration) {
// Special case for CSSStyleDeclaration
return value.cssText;
}
return (Array.isArray(value) ? value.map(cssx) : Object.entries(value).map(cssx_format))
.filter((v) => v)
.join(';');
}
return value;
}
93 changes: 93 additions & 0 deletions packages/svelte/tests/runtime-runes/samples/cssx/_config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { flushSync } from 'svelte';
import { test } from '../../test';

export default test({
html: `
<div style="font-size:2em;color:red;--my-var:0">style1</div>
<div style="font-size:2em;color:red;--MY-VAR:0">style2</div>
<div style="font-size:2em;color:red;--MyVar:0">style3</div>
<div style="font-size:2em;color:red;--my-var:0">style4</div>
<div style="font-weight: bold;border-width: 3px; border-color: blue;COLOR: red">style5</div>
<div style="font-size:2em;color:red;--my-var:0;font-weight: bold;border-width: 3px; border-color: blue;COLOR: red;opacity: 0">style6</div>
<div style="font-size:2em;color:red;--my-var:0;font-weight: bold;border-width: 3px; border-color: blue;COLOR: red;opacity: 0">spread</div>
<div style="--bg-color:red;opacity:0.5;font-size:1em"></div>

<div style="font-size:2em;color:red;--my-var:0">child1:style1</div>
<div style="font-size:2em;color:red;--MY-VAR:0">child1:style2</div>
<div style="font-size:2em;color:red;--MyVar:0">child1:style3</div>
<div style="font-size:2em;color:red;--my-var:0">child1:style4</div>
<div style="font-weight: bold;border-width: 3px; border-color: blue;COLOR: red">child1:style5</div>
<div style="font-size:2em;color:red;--my-var:0;font-weight: bold;border-width: 3px; border-color: blue;COLOR: red;opacity: 0">child1:style6</div>
<div style="font-size:2em;color:red;--my-var:0;font-weight: bold;border-width: 3px; border-color: blue;COLOR: red;opacity: 0">child1:spread</div>
<div style="--bg-color:red;opacity:0.5;font-size:1em">child1:</div>

<div style="font-size:2em;color:red;--my-var:0">child2:style1</div>
<div style="font-size:2em;color:red;--MY-VAR:0">child2:style2</div>
<div style="font-size:2em;color:red;--MyVar:0">child2:style3</div>
<div style="font-size:2em;color:red;--my-var:0">child2:style4</div>
<div style="font-weight: bold;border-width: 3px; border-color: blue;COLOR: red">child2:style5</div>
<div style="font-size:2em;color:red;--my-var:0;font-weight: bold;border-width: 3px; border-color: blue;COLOR: red;opacity: 0">child2:style6</div>
<div style="font-size:2em;color:red;--my-var:0;font-weight: bold;border-width: 3px; border-color: blue;COLOR: red;opacity: 0">child2:spread</div>
<div style="--bg-color:red;opacity:0.5;font-size:1em">child2:</div>

<applied-to-custom-element style="font-size:2em;color:red;--my-var:0">style1</applied-to-custom-element>
<applied-to-custom-element style="font-size:2em;color:red;--MY-VAR:0">style2</applied-to-custom-element>
<applied-to-custom-element style="font-size:2em;color:red;--MyVar:0">style3</applied-to-custom-element>
<applied-to-custom-element style="font-size:2em;color:red;--my-var:0">style4</applied-to-custom-element>
<applied-to-custom-element style="font-weight: bold;border-width: 3px; border-color: blue;COLOR: red">style5</applied-to-custom-element>
<applied-to-custom-element style="font-size:2em;color:red;--my-var:0;font-weight: bold;border-width: 3px; border-color: blue;COLOR: red;opacity: 0">style6</applied-to-custom-element>
<applied-to-custom-element style="font-size:2em;color:red;--my-var:0;font-weight: bold;border-width: 3px; border-color: blue;COLOR: red;opacity: 0">spread</applied-to-custom-element>
<applied-to-custom-element style="--bg-color:red;opacity:0.5;font-size:1em"></applied-to-custom-element>

<button>update</button>
`,
test({ assert, target }) {
const button = target.querySelector('button');

button?.click();
flushSync();

assert.htmlEqual(
target.innerHTML,
`
<div style="font-size:2em;color:red;--my-var:0">style1</div>
<div style="font-size:2em;color:red;--MY-VAR:0">style2</div>
<div style="font-size:2em;color:red;--MyVar:0">style3</div>
<div style="font-size:2em;color:red;--my-var:0">style4</div>
<div style="font-weight: bold;border-width: 3px; border-color: blue;COLOR: red">style5</div>
<div style="font-size:2em;color:red;--my-var:0;font-weight: bold;border-width: 3px; border-color: blue;COLOR: red;opacity: 0">style6</div>
<div style="font-size:2em;color:red;--my-var:0;font-weight: bold;border-width: 3px; border-color: blue;COLOR: red;opacity: 0">spread</div>
<div style="--bg-color:blue;display:inline-block;opacity:0.75"></div>

<div style="font-size:2em;color:red;--my-var:0">child1:style1</div>
<div style="font-size:2em;color:red;--MY-VAR:0">child1:style2</div>
<div style="font-size:2em;color:red;--MyVar:0">child1:style3</div>
<div style="font-size:2em;color:red;--my-var:0">child1:style4</div>
<div style="font-weight: bold;border-width: 3px; border-color: blue;COLOR: red">child1:style5</div>
<div style="font-size:2em;color:red;--my-var:0;font-weight: bold;border-width: 3px; border-color: blue;COLOR: red;opacity: 0">child1:style6</div>
<div style="font-size:2em;color:red;--my-var:0;font-weight: bold;border-width: 3px; border-color: blue;COLOR: red;opacity: 0">child1:spread</div>
<div style="--bg-color:blue;display:inline-block;opacity:0.75">child1:</div>

<div style="font-size:2em;color:red;--my-var:0">child2:style1</div>
<div style="font-size:2em;color:red;--MY-VAR:0">child2:style2</div>
<div style="font-size:2em;color:red;--MyVar:0">child2:style3</div>
<div style="font-size:2em;color:red;--my-var:0">child2:style4</div>
<div style="font-weight: bold;border-width: 3px; border-color: blue;COLOR: red">child2:style5</div>
<div style="font-size:2em;color:red;--my-var:0;font-weight: bold;border-width: 3px; border-color: blue;COLOR: red;opacity: 0">child2:style6</div>
<div style="font-size:2em;color:red;--my-var:0;font-weight: bold;border-width: 3px; border-color: blue;COLOR: red;opacity: 0">child2:spread</div>
<div style="--bg-color:blue;display:inline-block;opacity:0.75">child2:</div>

<applied-to-custom-element style="font-size:2em;color:red;--my-var:0">style1</applied-to-custom-element>
<applied-to-custom-element style="font-size:2em;color:red;--MY-VAR:0">style2</applied-to-custom-element>
<applied-to-custom-element style="font-size:2em;color:red;--MyVar:0">style3</applied-to-custom-element>
<applied-to-custom-element style="font-size:2em;color:red;--my-var:0">style4</applied-to-custom-element>
<applied-to-custom-element style="font-weight: bold;border-width: 3px; border-color: blue;COLOR: red">style5</applied-to-custom-element>
<applied-to-custom-element style="font-size:2em;color:red;--my-var:0;font-weight: bold;border-width: 3px; border-color: blue;COLOR: red;opacity: 0">style6</applied-to-custom-element>
<applied-to-custom-element style="font-size:2em;color:red;--my-var:0;font-weight: bold;border-width: 3px; border-color: blue;COLOR: red;opacity: 0">spread</applied-to-custom-element>
<applied-to-custom-element style="--bg-color:blue;display:inline-block;opacity:0.75"></applied-to-custom-element>

<button>update</button>
`
);
}
});
Loading
Loading