formatComplexDataStructure.js.flow 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /* @flow */
  2. import { isValidElement } from 'react';
  3. import { prettyPrint } from '@base2/pretty-print-object';
  4. import sortObject from './sortObject';
  5. import parseReactElement from './../parser/parseReactElement';
  6. import formatTreeNode from './formatTreeNode';
  7. import formatFunction from './formatFunction';
  8. import spacer from './spacer';
  9. import type { Options } from './../options';
  10. export default (
  11. value: Object | Array<any>,
  12. inline: boolean,
  13. lvl: number,
  14. options: Options
  15. ): string => {
  16. const normalizedValue = sortObject(value);
  17. const stringifiedValue = prettyPrint(normalizedValue, {
  18. transform: (currentObj, prop, originalResult) => {
  19. const currentValue = currentObj[prop];
  20. if (currentValue && isValidElement(currentValue)) {
  21. return formatTreeNode(
  22. parseReactElement(currentValue, options),
  23. true,
  24. lvl,
  25. options
  26. );
  27. }
  28. if (typeof currentValue === 'function') {
  29. return formatFunction(currentValue, options);
  30. }
  31. return originalResult;
  32. },
  33. });
  34. if (inline) {
  35. return stringifiedValue
  36. .replace(/\s+/g, ' ')
  37. .replace(/{ /g, '{')
  38. .replace(/ }/g, '}')
  39. .replace(/\[ /g, '[')
  40. .replace(/ ]/g, ']');
  41. }
  42. // Replace tabs with spaces, and add necessary indentation in front of each new line
  43. return stringifiedValue
  44. .replace(/\t/g, spacer(1, options.tabStop))
  45. .replace(/\n([^$])/g, `\n${spacer(lvl + 1, options.tabStop)}$1`);
  46. };