formatPropValue.js.flow 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /* @flow */
  2. import { isPlainObject } from 'is-plain-object';
  3. import { isValidElement } from 'react';
  4. import formatComplexDataStructure from './formatComplexDataStructure';
  5. import formatFunction from './formatFunction';
  6. import formatTreeNode from './formatTreeNode';
  7. import type { Options } from './../options';
  8. import parseReactElement from './../parser/parseReactElement';
  9. const escape = (s: string): string => s.replace(/"/g, '"');
  10. const formatPropValue = (
  11. propValue: any,
  12. inline: boolean,
  13. lvl: number,
  14. options: Options
  15. ): string => {
  16. if (typeof propValue === 'number') {
  17. return `{${String(propValue)}}`;
  18. }
  19. if (typeof propValue === 'string') {
  20. return `"${escape(propValue)}"`;
  21. }
  22. // > "Symbols (new in ECMAScript 2015, not yet supported in Flow)"
  23. // @see: https://flow.org/en/docs/types/primitives/
  24. // $FlowFixMe: Flow does not support Symbol
  25. if (typeof propValue === 'symbol') {
  26. const symbolDescription = propValue
  27. .valueOf()
  28. .toString()
  29. .replace(/Symbol\((.*)\)/, '$1');
  30. if (!symbolDescription) {
  31. return `{Symbol()}`;
  32. }
  33. return `{Symbol('${symbolDescription}')}`;
  34. }
  35. if (typeof propValue === 'function') {
  36. return `{${formatFunction(propValue, options)}}`;
  37. }
  38. if (isValidElement(propValue)) {
  39. return `{${formatTreeNode(
  40. parseReactElement(propValue, options),
  41. true,
  42. lvl,
  43. options
  44. )}}`;
  45. }
  46. if (propValue instanceof Date) {
  47. if (isNaN(propValue.valueOf())) {
  48. return `{new Date(NaN)}`;
  49. }
  50. return `{new Date("${propValue.toISOString()}")}`;
  51. }
  52. if (isPlainObject(propValue) || Array.isArray(propValue)) {
  53. return `{${formatComplexDataStructure(propValue, inline, lvl, options)}}`;
  54. }
  55. return `{${String(propValue)}}`;
  56. };
  57. export default formatPropValue;