Skip to content

Fix error allowing invalid fontWeight values #1

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

Closed
wants to merge 1 commit into from
Closed
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
9 changes: 9 additions & 0 deletions .changeset/plenty-icons-enjoy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@emotion/serialize': major
---

What: Fix error allowing invalid fontWeight values

Why: The `fontweight` property of CSSObject allows invalid values (e.g. 'wrong'). It's expected behavior is to show an error.

How: Add `validFontWeight` type to `StrictCSSProperties`, declaring which values are only allowed.
39 changes: 38 additions & 1 deletion packages/serialize/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,29 @@ type Cursor = {
next?: Cursor
}

export type CSSProperties = CSS.PropertiesFallback<number | string>
type ValidFontWeight =
| 'normal'
| 'bold'
| 'lighter'
| 'bolder'
| 100
| 200
| 300
| 400
| 500
| 600
| 700
| 800
| 900

type StrictCSSProperties = Omit<
CSS.PropertiesFallback<number | string>,
'fontWeight'
> & {
fontWeight?: ValidFontWeight
}

export type CSSProperties = StrictCSSProperties
export type CSSPropertiesWithMultiValues = {
[K in keyof CSSProperties]:
| CSSProperties[K]
Expand Down Expand Up @@ -91,6 +113,13 @@ const processStyleName = /* #__PURE__ */ memoize((styleName: string) =>
: styleName.replace(hyphenateRegex, '-$&').toLowerCase()
)

const isValidFontWeight = (value: any): value is ValidFontWeight => {
if (typeof value === 'number') {
return value >= 100 && value <= 900 && value % 100 === 0
}
return ['normal', 'bold', 'lighter', 'bolder'].includes(value)
}

let processStyleValue = (
key: string,
value: string | number
Expand Down Expand Up @@ -149,6 +178,14 @@ if (isDevelopment) {
}
}

if (key === 'fontWeight') {
if (!isValidFontWeight(value)) {
throw new Error(
`Invalid font-weight value: ${value}. Valid values are: normal, bold, lighter, bolder, or numbers 100-900 in increments of 100.`
)
}
}

const processed = oldProcessStyleValue(key, value)

if (
Expand Down