LogBoxMessage.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @flow strict-local
  8. * @format
  9. */
  10. 'use strict';
  11. import * as React from 'react';
  12. import Text from '../../Text/Text';
  13. import type {TextStyleProp} from '../../StyleSheet/StyleSheet';
  14. import type {Message} from '../Data/parseLogBoxLog';
  15. type Props = {
  16. message: Message,
  17. style: TextStyleProp,
  18. plaintext?: ?boolean,
  19. maxLength?: ?number,
  20. ...
  21. };
  22. const cleanContent = content =>
  23. content.replace(/^(TransformError |Warning: (Warning: )?|Error: )/g, '');
  24. function LogBoxMessage(props: Props): React.Node {
  25. const {content, substitutions}: Message = props.message;
  26. if (props.plaintext === true) {
  27. return <Text>{cleanContent(content)}</Text>;
  28. }
  29. const maxLength = props.maxLength != null ? props.maxLength : Infinity;
  30. const substitutionStyle: TextStyleProp = props.style;
  31. const elements = [];
  32. let length = 0;
  33. const createUnderLength = (key, message, style) => {
  34. let cleanMessage = cleanContent(message);
  35. if (props.maxLength != null) {
  36. cleanMessage = cleanMessage.slice(0, props.maxLength - length);
  37. }
  38. if (length < maxLength) {
  39. elements.push(
  40. <Text key={key} style={style}>
  41. {cleanMessage}
  42. </Text>,
  43. );
  44. }
  45. length += cleanMessage.length;
  46. };
  47. const lastOffset = substitutions.reduce((prevOffset, substitution, index) => {
  48. const key = String(index);
  49. if (substitution.offset > prevOffset) {
  50. const prevPart = content.substr(
  51. prevOffset,
  52. substitution.offset - prevOffset,
  53. );
  54. createUnderLength(key, prevPart);
  55. }
  56. const substititionPart = content.substr(
  57. substitution.offset,
  58. substitution.length,
  59. );
  60. createUnderLength(key + '.5', substititionPart, substitutionStyle);
  61. return substitution.offset + substitution.length;
  62. }, 0);
  63. if (lastOffset < content.length) {
  64. const lastPart = content.substr(lastOffset);
  65. createUnderLength('-1', lastPart);
  66. }
  67. return <>{elements}</>;
  68. }
  69. export default LogBoxMessage;