propsFactory.mjs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Types
  2. // eslint-disable-line vue/prefer-import-from-vue
  3. /**
  4. * Creates a factory function for props definitions.
  5. * This is used to define props in a composable then override
  6. * default values in an implementing component.
  7. *
  8. * @example Simplified signature
  9. * (props: Props) => (defaults?: Record<keyof props, any>) => Props
  10. *
  11. * @example Usage
  12. * const makeProps = propsFactory({
  13. * foo: String,
  14. * })
  15. *
  16. * defineComponent({
  17. * props: {
  18. * ...makeProps({
  19. * foo: 'a',
  20. * }),
  21. * },
  22. * setup (props) {
  23. * // would be "string | undefined", now "string" because a default has been provided
  24. * props.foo
  25. * },
  26. * }
  27. */
  28. export function propsFactory(props, source) {
  29. return defaults => {
  30. return Object.keys(props).reduce((obj, prop) => {
  31. const isObjectDefinition = typeof props[prop] === 'object' && props[prop] != null && !Array.isArray(props[prop]);
  32. const definition = isObjectDefinition ? props[prop] : {
  33. type: props[prop]
  34. };
  35. if (defaults && prop in defaults) {
  36. obj[prop] = {
  37. ...definition,
  38. default: defaults[prop]
  39. };
  40. } else {
  41. obj[prop] = definition;
  42. }
  43. if (source && !obj[prop].source) {
  44. obj[prop].source = source;
  45. }
  46. return obj;
  47. }, {});
  48. };
  49. }
  50. //# sourceMappingURL=propsFactory.mjs.map