formatProp.js.flow 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /* @flow */
  2. import spacer from './spacer';
  3. import formatPropValue from './formatPropValue';
  4. import type { Options } from './../options';
  5. export default (
  6. name: string,
  7. hasValue: boolean,
  8. value: any,
  9. hasDefaultValue: boolean,
  10. defaultValue: any,
  11. inline: boolean,
  12. lvl: number,
  13. options: Options
  14. ): {
  15. attributeFormattedInline: string,
  16. attributeFormattedMultiline: string,
  17. isMultilineAttribute: boolean,
  18. } => {
  19. if (!hasValue && !hasDefaultValue) {
  20. throw new Error(
  21. `The prop "${name}" has no value and no default: could not be formatted`
  22. );
  23. }
  24. const usedValue = hasValue ? value : defaultValue;
  25. const { useBooleanShorthandSyntax, tabStop } = options;
  26. const formattedPropValue = formatPropValue(usedValue, inline, lvl, options);
  27. let attributeFormattedInline = ' ';
  28. let attributeFormattedMultiline = `\n${spacer(lvl + 1, tabStop)}`;
  29. const isMultilineAttribute = formattedPropValue.includes('\n');
  30. if (
  31. useBooleanShorthandSyntax &&
  32. formattedPropValue === '{false}' &&
  33. !hasDefaultValue
  34. ) {
  35. // If a boolean is false and not different from it's default, we do not render the attribute
  36. attributeFormattedInline = '';
  37. attributeFormattedMultiline = '';
  38. } else if (useBooleanShorthandSyntax && formattedPropValue === '{true}') {
  39. attributeFormattedInline += `${name}`;
  40. attributeFormattedMultiline += `${name}`;
  41. } else {
  42. attributeFormattedInline += `${name}=${formattedPropValue}`;
  43. attributeFormattedMultiline += `${name}=${formattedPropValue}`;
  44. }
  45. return {
  46. attributeFormattedInline,
  47. attributeFormattedMultiline,
  48. isMultilineAttribute,
  49. };
  50. };