Add support for passing scalars to vector props (#228)
Co-authored-by: Andrew Prifer <AndrewPrifer@users.noreply.github.com>
This commit is contained in:
parent
7b337a9731
commit
2854881e17
1 changed files with 38 additions and 9 deletions
|
@ -31,6 +31,14 @@ type Vector3 = {
|
||||||
z: number
|
z: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isNumber(value: any) {
|
||||||
|
return typeof value === 'number' && isFinite(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function isVectorObject(value: any) {
|
||||||
|
return (['x', 'y', 'z'] as const).every((axis) => isNumber(value[axis]))
|
||||||
|
}
|
||||||
|
|
||||||
export const createVector = (components?: [number, number, number]) => {
|
export const createVector = (components?: [number, number, number]) => {
|
||||||
return components
|
return components
|
||||||
? {x: components[0], y: components[1], z: components[2]}
|
? {x: components[0], y: components[1], z: components[2]}
|
||||||
|
@ -47,16 +55,37 @@ export const createVectorPropConfig = (
|
||||||
{nudgeMultiplier = 0.01} = {},
|
{nudgeMultiplier = 0.01} = {},
|
||||||
): PropConfig<Vector3> => ({
|
): PropConfig<Vector3> => ({
|
||||||
parse: (props) => {
|
parse: (props) => {
|
||||||
const vector = props[key]
|
const propValue = props[key]
|
||||||
? Array.isArray(props[key])
|
// if prop exists
|
||||||
? createVector(props[key] as any)
|
const vector = !propValue
|
||||||
: {
|
? defaultValue
|
||||||
x: props[key].x,
|
: // if prop is an array
|
||||||
y: props[key].y,
|
Array.isArray(propValue)
|
||||||
z: props[key].z,
|
? createVector(propValue as any)
|
||||||
}
|
: // if prop is a scalar
|
||||||
: defaultValue
|
isNumber(propValue)
|
||||||
|
? {
|
||||||
|
x: propValue,
|
||||||
|
y: propValue,
|
||||||
|
z: propValue,
|
||||||
|
}
|
||||||
|
: // if prop is a threejs Vector3
|
||||||
|
isVectorObject(propValue)
|
||||||
|
? {
|
||||||
|
x: propValue.x,
|
||||||
|
y: propValue.y,
|
||||||
|
z: propValue.z,
|
||||||
|
}
|
||||||
|
: // show a warning and return defaultValue
|
||||||
|
(console.warn(
|
||||||
|
`Couldn't parse prop %c${key}={${JSON.stringify(
|
||||||
|
propValue,
|
||||||
|
)}}%c, falling back to default value.`,
|
||||||
|
'background: black; color: white',
|
||||||
|
),
|
||||||
|
defaultValue)
|
||||||
;(['x', 'y', 'z'] as const).forEach((axis) => {
|
;(['x', 'y', 'z'] as const).forEach((axis) => {
|
||||||
|
// e.g. r3f also accepts prop keys like "scale-x"
|
||||||
if (props[`${key}-${axis}` as any])
|
if (props[`${key}-${axis}` as any])
|
||||||
vector[axis] = props[`${key}-${axis}` as any]
|
vector[axis] = props[`${key}-${axis}` as any]
|
||||||
})
|
})
|
||||||
|
|
Loading…
Reference in a new issue