import { AffectedMentionIndexes, Mentions, Message, Selection } from './types'; const arrayInsertAt = (pos: number, value: T, arr: T[]): T[] => { return arr.slice(0, pos).concat([value]).concat(arr.slice(pos)); }; const stringReplace = (from: number, to: number, value: string, str: string): string => { return str.substring(0, from).concat(value).concat(str.substring(to)); }; const deserialize = (message: Message): [string, Mentions] => { const text = message.map(char => char.text).join(''); let startOffset = 0; const mentions = message.reduce((current, { ref, text }) => { const endOffset = startOffset + text.length; const result = ref !== undefined ? current.concat([ { id: ref, name: text, offset: [startOffset, endOffset + 1], }, ]) : current; startOffset = endOffset; return result; }, [] as Mentions); return [text, mentions]; }; const serialize = (text: string, mentions: Mentions): Message => { let startIndex = 0; const mentionMessage = mentions.reduce((current, { id, offset }) => { const [startOffset, endOffset] = offset; const result = current.concat([ { ref: undefined, text: text.substring(startIndex, startOffset), }, { ref: id, text: text.substring(startOffset, endOffset - 1), }, ]); startIndex = endOffset - 1; return result; }, [] as Message); return mentionMessage.concat([ { ref: undefined, text: text.substring(startIndex), }, ]); }; const getAffectedMentionIndexes = (selection: Selection, mentions: Mentions): AffectedMentionIndexes => { const [startSelection, endSelection] = selection; const affectedIndexes = mentions.reduce( (current, { offset }, index): AffectedMentionIndexes => { const [startOffset, endOffset] = offset; const [selectedIndexes, unselectedIndexes] = current; const isSelected = startOffset < endSelection && endOffset > startSelection; const isUnselected = startOffset >= endSelection; if (isSelected) { return [selectedIndexes.concat([index]), unselectedIndexes]; } if (isUnselected) { return [selectedIndexes, unselectedIndexes.concat([index])]; } return current; }, [[], []] as AffectedMentionIndexes, ); return affectedIndexes; }; export { arrayInsertAt, stringReplace, deserialize, serialize, getAffectedMentionIndexes };