2018-05-14 20:52:10 +00:00
|
|
|
import React from 'react';
|
|
|
|
|
2019-01-14 21:49:58 +00:00
|
|
|
import { RenderTextCallbackType } from '../../types/Util';
|
2018-05-18 21:48:20 +00:00
|
|
|
|
2020-08-20 18:23:09 +00:00
|
|
|
export interface Props {
|
2018-05-14 20:52:10 +00:00
|
|
|
text: string;
|
2018-05-18 21:48:20 +00:00
|
|
|
/** Allows you to customize now non-newlines are rendered. Simplest is just a <span>. */
|
2019-01-14 21:49:58 +00:00
|
|
|
renderNonNewLine?: RenderTextCallbackType;
|
2018-05-14 20:52:10 +00:00
|
|
|
}
|
|
|
|
|
2018-05-22 19:31:43 +00:00
|
|
|
export class AddNewLines extends React.Component<Props> {
|
2018-05-18 21:48:20 +00:00
|
|
|
public static defaultProps: Partial<Props> = {
|
2018-06-27 20:53:49 +00:00
|
|
|
renderNonNewLine: ({ text }) => text,
|
2018-05-18 21:48:20 +00:00
|
|
|
};
|
|
|
|
|
2020-09-14 19:51:27 +00:00
|
|
|
public render():
|
|
|
|
| JSX.Element
|
|
|
|
| string
|
|
|
|
| null
|
|
|
|
| Array<JSX.Element | string | null> {
|
2018-05-18 21:48:20 +00:00
|
|
|
const { text, renderNonNewLine } = this.props;
|
2020-09-14 19:51:27 +00:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
2018-05-14 20:52:10 +00:00
|
|
|
const results: Array<any> = [];
|
|
|
|
const FIND_NEWLINES = /\n/g;
|
|
|
|
|
2018-05-18 21:48:20 +00:00
|
|
|
// We have to do this, because renderNonNewLine is not required in our Props object,
|
|
|
|
// but it is always provided via defaultProps.
|
|
|
|
if (!renderNonNewLine) {
|
2020-09-14 19:51:27 +00:00
|
|
|
return null;
|
2018-05-18 21:48:20 +00:00
|
|
|
}
|
|
|
|
|
2018-05-14 20:52:10 +00:00
|
|
|
let match = FIND_NEWLINES.exec(text);
|
|
|
|
let last = 0;
|
|
|
|
let count = 1;
|
|
|
|
|
|
|
|
if (!match) {
|
2018-05-18 21:48:20 +00:00
|
|
|
return renderNonNewLine({ text, key: 0 });
|
2018-05-14 20:52:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
while (match) {
|
|
|
|
if (last < match.index) {
|
|
|
|
const textWithNoNewline = text.slice(last, match.index);
|
2020-09-14 19:51:27 +00:00
|
|
|
count += 1;
|
|
|
|
results.push(renderNonNewLine({ text: textWithNoNewline, key: count }));
|
2018-05-14 20:52:10 +00:00
|
|
|
}
|
|
|
|
|
2020-09-14 19:51:27 +00:00
|
|
|
count += 1;
|
|
|
|
results.push(<br key={count} />);
|
2018-05-14 20:52:10 +00:00
|
|
|
|
|
|
|
last = FIND_NEWLINES.lastIndex;
|
|
|
|
match = FIND_NEWLINES.exec(text);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (last < text.length) {
|
2020-09-14 19:51:27 +00:00
|
|
|
count += 1;
|
|
|
|
results.push(renderNonNewLine({ text: text.slice(last), key: count }));
|
2018-05-14 20:52:10 +00:00
|
|
|
}
|
|
|
|
|
2018-05-18 21:48:20 +00:00
|
|
|
return results;
|
2018-05-14 20:52:10 +00:00
|
|
|
}
|
|
|
|
}
|