mirror of
https://github.com/signalapp/Signal-Desktop.git
synced 2026-05-01 22:01:49 +01:00
Refactor link/emoji/newline components for composability
This commit is contained in:
@@ -1,27 +1,43 @@
|
||||
import React from 'react';
|
||||
|
||||
import { RenderTextCallback } from '../../types/Util';
|
||||
|
||||
interface Props {
|
||||
text: string;
|
||||
/** Allows you to customize now non-newlines are rendered. Simplest is just a <span>. */
|
||||
renderNonNewLine?: RenderTextCallback;
|
||||
}
|
||||
|
||||
export class AddNewLines extends React.Component<Props, {}> {
|
||||
public static defaultProps: Partial<Props> = {
|
||||
renderNonNewLine: ({ text, key }) => <span key={key}>{text}</span>,
|
||||
};
|
||||
|
||||
public render() {
|
||||
const { text } = this.props;
|
||||
const { text, renderNonNewLine } = this.props;
|
||||
const results: Array<any> = [];
|
||||
const FIND_NEWLINES = /\n/g;
|
||||
|
||||
// We have to do this, because renderNonNewLine is not required in our Props object,
|
||||
// but it is always provided via defaultProps.
|
||||
if (!renderNonNewLine) {
|
||||
return;
|
||||
}
|
||||
|
||||
let match = FIND_NEWLINES.exec(text);
|
||||
let last = 0;
|
||||
let count = 1;
|
||||
|
||||
if (!match) {
|
||||
return <span>{text}</span>;
|
||||
return renderNonNewLine({ text, key: 0 });
|
||||
}
|
||||
|
||||
while (match) {
|
||||
if (last < match.index) {
|
||||
const textWithNoNewline = text.slice(last, match.index);
|
||||
results.push(<span key={count++}>{textWithNoNewline}</span>);
|
||||
results.push(
|
||||
renderNonNewLine({ text: textWithNoNewline, key: count++ })
|
||||
);
|
||||
}
|
||||
|
||||
results.push(<br key={count++} />);
|
||||
@@ -32,9 +48,9 @@ export class AddNewLines extends React.Component<Props, {}> {
|
||||
}
|
||||
|
||||
if (last < text.length) {
|
||||
results.push(<span key={count++}>{text.slice(last)}</span>);
|
||||
results.push(renderNonNewLine({ text: text.slice(last), key: count++ }));
|
||||
}
|
||||
|
||||
return <span>{results}</span>;
|
||||
return results;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user