|
|
import { InterpolatorConfig } from '@react-spring/types' |
|
|
|
|
|
import { getFluidValue } from './fluids' |
|
|
import { createInterpolator } from './createInterpolator' |
|
|
import { colorToRgba } from './colorToRgba' |
|
|
import * as G from './globals' |
|
|
import { |
|
|
cssVariableRegex, |
|
|
colorRegex, |
|
|
unitRegex, |
|
|
numberRegex, |
|
|
rgbaRegex, |
|
|
} from './regexs' |
|
|
import { variableToRgba } from './variableToRgba' |
|
|
|
|
|
|
|
|
let namedColorRegex: RegExp |
|
|
|
|
|
|
|
|
|
|
|
const rgbaRound = (_: any, p1: number, p2: number, p3: number, p4: number) => |
|
|
`rgba(${Math.round(p1)}, ${Math.round(p2)}, ${Math.round(p3)}, ${p4})` |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export const createStringInterpolator = ( |
|
|
config: InterpolatorConfig<string> |
|
|
) => { |
|
|
if (!namedColorRegex) |
|
|
namedColorRegex = G.colors |
|
|
? |
|
|
new RegExp(`(${Object.keys(G.colors).join('|')})(?!\\w)`, 'g') |
|
|
: |
|
|
/^\b$/ |
|
|
|
|
|
|
|
|
const output = config.output.map(value => { |
|
|
return getFluidValue(value) |
|
|
.replace(cssVariableRegex, variableToRgba) |
|
|
.replace(colorRegex, colorToRgba) |
|
|
.replace(namedColorRegex, colorToRgba) |
|
|
}) |
|
|
|
|
|
|
|
|
const keyframes = output.map(value => value.match(numberRegex)!.map(Number)) |
|
|
|
|
|
|
|
|
const outputRanges = keyframes[0].map((_, i) => |
|
|
keyframes.map(values => { |
|
|
if (!(i in values)) { |
|
|
throw Error('The arity of each "output" value must be equal') |
|
|
} |
|
|
return values[i] |
|
|
}) |
|
|
) |
|
|
|
|
|
|
|
|
const interpolators = outputRanges.map(output => |
|
|
createInterpolator({ ...config, output }) |
|
|
) |
|
|
|
|
|
|
|
|
return (input: number) => { |
|
|
|
|
|
const missingUnit = |
|
|
!unitRegex.test(output[0]) && |
|
|
output.find(value => unitRegex.test(value))?.replace(numberRegex, '') |
|
|
|
|
|
let i = 0 |
|
|
return output[0] |
|
|
.replace( |
|
|
numberRegex, |
|
|
() => `${interpolators[i++](input)}${missingUnit || ''}` |
|
|
) |
|
|
.replace(rgbaRegex, rgbaRound) |
|
|
} |
|
|
} |
|
|
|