signal-desktop/ts/components/conversation/AddNewLines.tsx

52 lines
1.2 KiB
TypeScript
Raw Normal View History

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
import React from 'react';
import type { RenderTextCallbackType } from '../../types/Util';
export type Props = {
text: string;
/** Allows you to customize how non-newlines are rendered. Simplest is just a <span>. */
2019-01-14 21:49:58 +00:00
renderNonNewLine?: RenderTextCallbackType;
};
2022-11-10 04:59:36 +00:00
const defaultRenderNonNewLine: RenderTextCallbackType = ({ text }) => text;
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 })}</>;
}
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 }));
}
count += 1;
results.push(<br key={count} />);
last = FIND_NEWLINES.lastIndex;
match = FIND_NEWLINES.exec(text);
}
if (last < text.length) {
count += 1;
results.push(renderNonNewLine({ text: text.slice(last), key: count }));
}
return <>{results}</>;
}