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

Allow numbers to be used as values in styleMap() #3788

Merged
merged 3 commits into from Apr 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/slimy-clouds-roll.md
@@ -0,0 +1,6 @@
---
'lit-html': patch
'lit': patch
---

Allow numbers to be used as values in styleMap()
9 changes: 6 additions & 3 deletions packages/lit-html/src/directives/style-map.ts
Expand Up @@ -21,7 +21,7 @@ import {
* for CSSStyleDeclaration like `backgroundColor`.
*/
export interface StyleInfo {
[name: string]: string | undefined | null;
[name: string]: string | number | undefined | null;
}

const important = 'important';
Expand Down Expand Up @@ -101,11 +101,14 @@ class StyleMapDirective extends Directive {
const value = styleInfo[name];
if (value != null) {
this._previousStyleProperties.add(name);
const isImportant = value.endsWith(importantFlag);
const isImportant =
typeof value === 'string' && value.endsWith(importantFlag);
if (name.includes('-') || isImportant) {
style.setProperty(
name,
isImportant ? value.slice(0, flagTrim) : value,
isImportant
? (value as string).slice(0, flagTrim)
: (value as string),
isImportant ? important : ''
);
} else {
Expand Down
16 changes: 14 additions & 2 deletions packages/lit-html/src/test/directives/style-map_test.ts
Expand Up @@ -79,15 +79,27 @@ suite('styleMap', () => {
});

test('adds and updates properties', () => {
renderStyleMap({marginTop: '2px', 'padding-bottom': '4px', opacity: '0.5'});
renderStyleMap({
marginTop: '2px',
'padding-bottom': '4px',
opacity: '0.5',
'z-index': 10,
});
const el = container.firstElementChild as HTMLElement;
assert.equal(el.style.marginTop, '2px');
assert.equal(el.style.paddingBottom, '4px');
assert.equal(el.style.opacity, '0.5');
augustjk marked this conversation as resolved.
Show resolved Hide resolved
renderStyleMap({marginTop: '4px', paddingBottom: '8px', opacity: '0.55'});
assert.equal(el.style.zIndex, '10');
renderStyleMap({
marginTop: '4px',
paddingBottom: '8px',
opacity: '0.55',
'z-index': 1,
});
assert.equal(el.style.marginTop, '4px');
assert.equal(el.style.paddingBottom, '8px');
assert.equal(el.style.opacity, '0.55');
justinfagnani marked this conversation as resolved.
Show resolved Hide resolved
assert.equal(el.style.zIndex, '1');
});

test('removes properties', () => {
Expand Down