runtime.mjs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { isObject } from "../../types.mjs";
  2. import { hasOwn } from "../../objects.mjs";
  3. import { fromPairs } from "lodash-unified";
  4. import { warn } from "vue";
  5. //#region ../../packages/utils/vue/props/runtime.ts
  6. const epPropKey = "__epPropKey";
  7. const definePropType = (val) => val;
  8. const isEpProp = (val) => isObject(val) && !!val[epPropKey];
  9. /**
  10. * @description Build prop. It can better optimize prop types
  11. * @description 生成 prop,能更好地优化类型
  12. * @example
  13. // limited options
  14. // the type will be PropType<'light' | 'dark'>
  15. buildProp({
  16. type: String,
  17. values: ['light', 'dark'],
  18. } as const)
  19. * @example
  20. // limited options and other types
  21. // the type will be PropType<'small' | 'large' | number>
  22. buildProp({
  23. type: [String, Number],
  24. values: ['small', 'large'],
  25. validator: (val: unknown): val is number => typeof val === 'number',
  26. } as const)
  27. @link see more: https://github.com/element-plus/element-plus/pull/3341
  28. */
  29. const buildProp = (prop, key) => {
  30. if (!isObject(prop) || isEpProp(prop)) return prop;
  31. const { values, required, default: defaultValue, type, validator } = prop;
  32. const epProp = {
  33. type,
  34. required: !!required,
  35. validator: values || validator ? (val) => {
  36. let valid = false;
  37. let allowedValues = [];
  38. if (values) {
  39. allowedValues = Array.from(values);
  40. if (hasOwn(prop, "default")) allowedValues.push(defaultValue);
  41. valid ||= allowedValues.includes(val);
  42. }
  43. if (validator) valid ||= validator(val);
  44. if (!valid && allowedValues.length > 0) {
  45. const allowValuesText = [...new Set(allowedValues)].map((value) => JSON.stringify(value)).join(", ");
  46. warn(`Invalid prop: validation failed${key ? ` for prop "${key}"` : ""}. Expected one of [${allowValuesText}], got value ${JSON.stringify(val)}.`);
  47. }
  48. return valid;
  49. } : void 0,
  50. [epPropKey]: true
  51. };
  52. if (hasOwn(prop, "default")) epProp.default = defaultValue;
  53. return epProp;
  54. };
  55. const buildProps = (props) => fromPairs(Object.entries(props).map(([key, option]) => [key, buildProp(option, key)]));
  56. //#endregion
  57. export { buildProp, buildProps, definePropType, epPropKey, isEpProp };
  58. //# sourceMappingURL=runtime.mjs.map