Skip to content

Commit 173cbca

Browse files
feat: add units to bare numbers when interpolating (#1473)
Co-authored-by: Josh <[email protected]>
1 parent d64db1d commit 173cbca

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

packages/shared/src/createInterpolator.test.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,15 @@ describe('Interpolation', () => {
129129
expect(interpolation(1)).toBe('100deg')
130130
})
131131

132+
it('should interpolate between number and unit', () => {
133+
const interpolation = createInterpolator({
134+
range: [0, 1],
135+
output: ['0', '100%'],
136+
})
137+
138+
expect(interpolation(0.5)).toBe('50%')
139+
})
140+
132141
it('should support a mix of color patterns', () => {
133142
const interpolation = createInterpolator({
134143
range: [0, 1, 2],

packages/shared/src/stringInterpolation.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ const numberRegex = /[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?/g
1212
// Taken from https://gist.github.com/olmokramer/82ccce673f86db7cda5e
1313
const colorRegex = /(#(?:[0-9a-f]{2}){2,4}|(#[0-9a-f]{3})|(rgb|hsl)a?\((-?\d+%?[,\s]+){2,3}\s*[\d\.]+%?\))/gi
1414

15+
// Gets numbers with units when specified
16+
const unitRegex = new RegExp(`(${numberRegex.source})(%|[a-z]+)`, 'i')
17+
1518
// Covers color names (transparent, blue, etc.)
1619
let namedColorRegex: RegExp
1720

@@ -68,9 +71,17 @@ export const createStringInterpolator = (
6871

6972
// Use the first `output` as a template for each call
7073
return (input: number) => {
74+
// Convert numbers to units if available (allows for ["0", "100%"])
75+
const missingUnit =
76+
!unitRegex.test(output[0]) &&
77+
output.find(value => unitRegex.test(value))?.replace(numberRegex, '')
78+
7179
let i = 0
7280
return output[0]
73-
.replace(numberRegex, () => String(interpolators[i++](input)))
81+
.replace(
82+
numberRegex,
83+
() => `${interpolators[i++](input)}${missingUnit || ''}`
84+
)
7485
.replace(rgbaRegex, rgbaRound)
7586
}
7687
}

0 commit comments

Comments
 (0)