2023-01-03 11:55:46 -08:00
|
|
|
// Copyright 2018 Signal Messenger, LLC
|
2020-10-30 15:34:04 -05:00
|
|
|
// SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2018-05-14 13:52:10 -07:00
|
|
|
import React from 'react';
|
|
|
|
|
2021-10-26 14:15:33 -05:00
|
|
|
import type { RenderTextCallbackType } from '../../types/Util';
|
2018-05-18 14:48:20 -07:00
|
|
|
|
2021-01-14 12:07:05 -06:00
|
|
|
export type Props = {
|
2018-05-14 13:52:10 -07:00
|
|
|
text: string;
|
2023-04-10 09:31:45 -07:00
|
|
|
/** Allows you to customize how non-newlines are rendered. Simplest is just a <span>. */
|
2019-01-14 13:49:58 -08:00
|
|
|
renderNonNewLine?: RenderTextCallbackType;
|
2021-01-14 12:07:05 -06:00
|
|
|
};
|
2018-05-14 13:52:10 -07:00
|
|
|
|
2022-11-09 20:59:36 -08:00
|
|
|
const defaultRenderNonNewLine: RenderTextCallbackType = ({ text }) => text;
|
2018-05-18 14:48:20 -07:00
|
|
|
|
2023-04-12 16:17:56 -07:00
|
|
|
export function AddNewLines({
|
|
|
|
text,
|
|
|
|
renderNonNewLine = defaultRenderNonNewLine,
|
|
|
|
}: Props): JSX.Element {
|
|
|
|
const results: Array<JSX.Element | string> = [];
|
|
|
|
const FIND_NEWLINES = /\n/g;
|
|
|
|
|
|
|
|
let match = FIND_NEWLINES.exec(text);
|
|
|
|
let last = 0;
|
|
|
|
let count = 1;
|
|
|
|
|
|
|
|
if (!match) {
|
|
|
|
return <>{renderNonNewLine({ text, key: 0 })}</>;
|
|
|
|
}
|
2018-05-14 13:52:10 -07:00
|
|
|
|
2023-04-12 16:17:56 -07:00
|
|
|
while (match) {
|
|
|
|
if (last < match.index) {
|
|
|
|
const textWithNoNewline = text.slice(last, match.index);
|
2020-09-14 12:51:27 -07:00
|
|
|
count += 1;
|
2023-04-12 16:17:56 -07:00
|
|
|
results.push(renderNonNewLine({ text: textWithNoNewline, key: count }));
|
2018-05-14 13:52:10 -07:00
|
|
|
}
|
|
|
|
|
2023-04-12 16:17:56 -07:00
|
|
|
count += 1;
|
|
|
|
results.push(<br key={count} />);
|
|
|
|
|
|
|
|
last = FIND_NEWLINES.lastIndex;
|
|
|
|
match = FIND_NEWLINES.exec(text);
|
|
|
|
}
|
2018-05-14 13:52:10 -07:00
|
|
|
|
2023-04-12 16:17:56 -07:00
|
|
|
if (last < text.length) {
|
|
|
|
count += 1;
|
|
|
|
results.push(renderNonNewLine({ text: text.slice(last), key: count }));
|
2018-05-14 13:52:10 -07:00
|
|
|
}
|
2023-04-12 16:17:56 -07:00
|
|
|
|
|
|
|
return <>{results}</>;
|
2018-05-14 13:52:10 -07:00
|
|
|
}
|