1 | import { sharedConfigResolver } from './sharedConfigResolver'
|
---|
2 | import { ConfigResolverMap } from '../actions'
|
---|
3 | import { GestureKey, InternalConfig, UserGestureConfig } from '../types'
|
---|
4 |
|
---|
5 | export type Resolver = (x: any, key: string, obj: any) => any
|
---|
6 | export type ResolverMap = { [k: string]: Resolver | ResolverMap | boolean }
|
---|
7 |
|
---|
8 | export function resolveWith<T extends { [k: string]: any }, V extends { [k: string]: any }>(
|
---|
9 | config: Partial<T> = {},
|
---|
10 | resolvers: ResolverMap
|
---|
11 | ): V {
|
---|
12 | const result: any = {}
|
---|
13 |
|
---|
14 | for (const [key, resolver] of Object.entries(resolvers)) {
|
---|
15 | switch (typeof resolver) {
|
---|
16 | case 'function':
|
---|
17 | if (process.env.NODE_ENV === 'development') {
|
---|
18 | const r = resolver.call(result, config[key], key, config)
|
---|
19 | // prevents deprecated resolvers from applying in dev mode
|
---|
20 | if (!Number.isNaN(r)) result[key] = r
|
---|
21 | } else {
|
---|
22 | result[key] = resolver.call(result, config[key], key, config)
|
---|
23 | }
|
---|
24 | break
|
---|
25 | case 'object':
|
---|
26 | result[key] = resolveWith(config[key], resolver)
|
---|
27 | break
|
---|
28 | case 'boolean':
|
---|
29 | if (resolver) result[key] = config[key]
|
---|
30 | break
|
---|
31 | }
|
---|
32 | }
|
---|
33 |
|
---|
34 | return result
|
---|
35 | }
|
---|
36 |
|
---|
37 | export function parse(newConfig: UserGestureConfig, gestureKey?: GestureKey, _config: any = {}): InternalConfig {
|
---|
38 | const { target, eventOptions, window, enabled, transform, ...rest } = newConfig as any
|
---|
39 |
|
---|
40 | _config.shared = resolveWith({ target, eventOptions, window, enabled, transform }, sharedConfigResolver)
|
---|
41 |
|
---|
42 | if (gestureKey) {
|
---|
43 | const resolver = ConfigResolverMap.get(gestureKey)!
|
---|
44 | _config[gestureKey] = resolveWith({ shared: _config.shared, ...rest }, resolver)
|
---|
45 | } else {
|
---|
46 | for (const key in rest) {
|
---|
47 | const resolver = ConfigResolverMap.get(key as GestureKey)!
|
---|
48 |
|
---|
49 | if (resolver) {
|
---|
50 | _config[key] = resolveWith({ shared: _config.shared, ...rest[key] }, resolver)
|
---|
51 | } else if (process.env.NODE_ENV === 'development') {
|
---|
52 | if (!['drag', 'pinch', 'scroll', 'wheel', 'move', 'hover'].includes(key)) {
|
---|
53 | if (key === 'domTarget') {
|
---|
54 | throw Error(`[@use-gesture]: \`domTarget\` option has been renamed to \`target\`.`)
|
---|
55 | }
|
---|
56 | // eslint-disable-next-line no-console
|
---|
57 | console.warn(
|
---|
58 | `[@use-gesture]: Unknown config key \`${key}\` was used. Please read the documentation for further information.`
|
---|
59 | )
|
---|
60 | }
|
---|
61 | }
|
---|
62 | }
|
---|
63 | }
|
---|
64 | return _config
|
---|
65 | }
|
---|