ant-design-vue/components/_util/util.ts

66 lines
2.2 KiB
TypeScript
Raw Normal View History

2020-09-18 04:15:01 +00:00
export const isFunction = (val: unknown): val is Function => typeof val === 'function';
2020-08-31 08:53:19 +00:00
export const isArray = Array.isArray;
2020-09-18 04:15:01 +00:00
export const isString = (val: unknown): val is string => typeof val === 'string';
export const isSymbol = (val: unknown): val is symbol => typeof val === 'symbol';
export const isObject = (val: unknown): val is object => val !== null && typeof val === 'object';
2020-06-12 10:27:07 +00:00
const onRE = /^on[^a-z]/;
2020-09-18 04:15:01 +00:00
const isOn = (key: string) => onRE.test(key);
2020-06-12 10:27:07 +00:00
const cacheStringFunction = fn => {
const cache = Object.create(null);
return str => {
const hit = cache[str];
return hit || (cache[str] = fn(str));
};
};
const camelizeRE = /-(\w)/g;
const camelize = cacheStringFunction(str => {
return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
});
const hyphenateRE = /\B([A-Z])/g;
2020-09-18 04:15:01 +00:00
const hyphenate = cacheStringFunction((str: string) => {
2020-06-12 10:27:07 +00:00
return str.replace(hyphenateRE, '-$1').toLowerCase();
});
2020-09-18 04:15:01 +00:00
const capitalize = cacheStringFunction((str: string) => {
2020-06-12 10:27:07 +00:00
return str.charAt(0).toUpperCase() + str.slice(1);
});
const hasOwnProperty = Object.prototype.hasOwnProperty;
2020-09-18 04:15:01 +00:00
const hasOwn = (val: object, key: string) => hasOwnProperty.call(val, key);
2020-06-12 10:27:07 +00:00
// change from vue sourcecode
2020-06-17 16:19:14 +00:00
function resolvePropValue(options, props, key, value) {
2020-06-12 10:27:07 +00:00
const opt = options[key];
if (opt != null) {
const hasDefault = hasOwn(opt, 'default');
// default values
if (hasDefault && value === undefined) {
const defaultValue = opt.default;
value = opt.type !== Function && isFunction(defaultValue) ? defaultValue() : defaultValue;
}
// boolean casting
if (opt[0 /* shouldCast */]) {
2020-06-17 16:19:14 +00:00
if (!hasOwn(props, key) && !hasDefault) {
2020-06-12 10:27:07 +00:00
value = false;
2020-06-17 16:19:14 +00:00
} else if (opt[1 /* shouldCastTrue */] && (value === '' || value === hyphenate(key))) {
2020-06-12 10:27:07 +00:00
value = true;
}
}
}
return value;
}
2020-09-28 03:47:15 +00:00
export function getDataAndAriaProps(props: Record<string, unknown>) {
return Object.keys(props).reduce((memo: Record<string, unknown>, key: string) => {
if (key.substr(0, 5) === 'data-' || key.substr(0, 5) === 'aria-') {
memo[key] = props[key];
}
return memo;
}, {});
}
2020-06-12 10:27:07 +00:00
export { isOn, cacheStringFunction, camelize, hyphenate, capitalize, resolvePropValue };