ant-design-vue/components/form/utils/valueUtil.ts

62 lines
1.8 KiB
TypeScript
Raw Normal View History

2020-07-13 15:55:46 +00:00
import { toArray } from './typeUtil';
2021-06-26 01:35:40 +00:00
import type { InternalNamePath, NamePath } from '../interface';
2020-07-13 15:55:46 +00:00
/**
* Convert name to internal supported format.
* This function should keep since we still thinking if need support like `a.b.c` format.
* 'a' => ['a']
* 123 => [123]
* ['a', 123] => ['a', 123]
*/
export function getNamePath(path: NamePath | null): InternalNamePath {
2020-07-13 15:55:46 +00:00
return toArray(path);
}
export function containsNamePath(namePathList: InternalNamePath[], namePath: InternalNamePath) {
2020-07-13 15:55:46 +00:00
return namePathList && namePathList.some(path => matchNamePath(path, namePath));
}
function isObject(obj: any) {
2020-07-13 15:55:46 +00:00
return typeof obj === 'object' && obj !== null && Object.getPrototypeOf(obj) === Object.prototype;
}
/**
* Copy values into store and return a new values object
* ({ a: 1, b: { c: 2 } }, { a: 4, b: { d: 5 } }) => { a: 4, b: { c: 2, d: 5 } }
*/
function internalSetValues<T>(store: T, values: T): T {
const newStore: T = (Array.isArray(store) ? [...store] : { ...store }) as T;
2020-07-13 15:55:46 +00:00
if (!values) {
return newStore;
}
Object.keys(values).forEach(key => {
const prevValue = newStore[key];
const value = values[key];
// If both are object (but target is not array), we use recursion to set deep value
const recursive = isObject(prevValue) && isObject(value);
newStore[key] = recursive ? internalSetValues(prevValue, value || {}) : value;
});
return newStore;
}
export function setValues<T>(store: T, ...restValues: T[]): T {
return restValues.reduce(
(current: T, newStore: T) => internalSetValues(current, newStore),
store,
);
2020-07-13 15:55:46 +00:00
}
export function matchNamePath(
namePath: InternalNamePath,
changedNamePath: InternalNamePath | null,
) {
2020-07-13 15:55:46 +00:00
if (!namePath || !changedNamePath || namePath.length !== changedNamePath.length) {
return false;
}
return namePath.every((nameUnit, i) => changedNamePath[i] === nameUnit);
}