Refactor link/emoji/newline components for composability
This commit is contained in:
parent
a5416e42c4
commit
d9e5338dff
11 changed files with 295 additions and 95 deletions
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue