2023-01-03 19:55:46 +00:00
|
|
|
// Copyright 2018 Signal Messenger, LLC
|
2020-10-30 20:34:04 +00:00
|
|
|
// SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2018-05-14 20:52:10 +00:00
|
|
|
import React from 'react';
|
|
|
|
|
2021-10-26 19:15:33 +00:00
|
|
|
import type { RenderTextCallbackType } from '../../types/Util';
|
2018-05-18 21:48:20 +00:00
|
|
|
|
2021-01-14 18:07:05 +00:00
|
|
|
export type 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;
|
2021-01-14 18:07:05 +00:00
|
|
|
};
|
2018-05-14 20:52:10 +00:00
|
|
|
|
2022-11-10 04:59:36 +00:00
|
|
|
const defaultRenderNonNewLine: RenderTextCallbackType = ({ text }) => text;
|
2018-05-18 21:48:20 +00:00
|
|
|
|
2022-11-10 04:59:36 +00:00
|
|
|
export class AddNewLines extends React.Component<Props> {
|
2021-11-12 23:44:20 +00:00
|
|
|
public override render():
|
2020-09-14 19:51:27 +00:00
|
|
|
| JSX.Element
|
|
|
|
| string
|
|
|
|
| null
|
|
|
|
| Array<JSX.Element | string | null> {
|
2022-11-10 04:59:36 +00:00
|
|
|
const { text, renderNonNewLine = defaultRenderNonNewLine } = this.props;
|
|
|
|
const results: Array<JSX.Element | string> = [];
|
2018-05-14 20:52:10 +00:00
|
|
|
const FIND_NEWLINES = /\n/g;
|
|
|
|
|
|
|
|
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
|
|
|
}
|
|
|
|
}
|