import flatten from 'lodash/flatten';
import { SEGMENT_RAW, SEGMENT_LINE_BREAK } from '../../data/enum/SegmentType';
import { processMatches } from './index';
import { LINE_BREAKS_REGEX } from '../../data/regexPatterns';
/**
* Detects urls in all SEGMENT_RAW message segments using the `linkify-it` module and converts them
* into a SEGMENT_URL.
* @param input {Array<Object>} An array of message segments
* @returns {Array<Object>} The processed array of message segments
*/
const detectLineBreak = () => input =>
flatten(
input.map(segment => {
const { type, data } = segment;
switch (type) {
case SEGMENT_RAW: {
const match = data.match(LINE_BREAKS_REGEX);
if (match) {
const dataMatch = [];
let lastIndex = 0;
match.forEach(lineBreak => {
const index = data.indexOf(lineBreak, lastIndex);
lastIndex = index + lineBreak.length;
return dataMatch.push({
index,
lastIndex,
});
});
return processMatches(dataMatch, segment, SEGMENT_LINE_BREAK);
}
return segment;
}
default:
return segment;
}
}),
);
export default detectLineBreak;