diff options
author | Ivan Chen <ivan@tagg.id> | 2021-05-05 18:36:39 -0400 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-05-05 18:36:39 -0400 |
commit | c9d32e68fbb9d1bc175722bfda49454a6f627eae (patch) | |
tree | 5f7b3cf0937ca073f03dde2f84ce5c0e50a038a3 /src/utils/comments.tsx | |
parent | d4a04e31144f6cfaebb0b892e3593bb02bd49ed5 (diff) | |
parent | 32a61c00756afb1aee0eb471ed643f24da1d3e85 (diff) |
Merge pull request #401 from IvanIFChen/tma296-add-mentions
[TMA-296] Add mentions
Diffstat (limited to 'src/utils/comments.tsx')
-rw-r--r-- | src/utils/comments.tsx | 87 |
1 files changed, 87 insertions, 0 deletions
diff --git a/src/utils/comments.tsx b/src/utils/comments.tsx new file mode 100644 index 00000000..a71e3857 --- /dev/null +++ b/src/utils/comments.tsx @@ -0,0 +1,87 @@ +import React from 'react'; +import {StyleProp, Text, TextStyle} from 'react-native'; +import { + isMentionPartType, + parseValue, + Part, + PartType, +} from 'react-native-controlled-mentions'; +import TaggTypeahead from '../components/common/TaggTypeahead'; +import {TAGG_LIGHT_BLUE} from '../constants'; +import {UserType} from '../types'; + +/** + * Part renderer + * + * https://github.com/dabakovich/react-native-controlled-mentions#rendering-mentioninputs-value + */ +const renderPart = ( + part: Part, + index: number, + handlePress: (user: UserType) => void, +) => { + // Just plain text + if (!part.partType) { + return <Text key={index}>{part.text}</Text>; + } + + // Mention type part + if (isMentionPartType(part.partType)) { + return ( + <Text + key={`${index}-${part.data?.trigger}`} + style={part.partType.textStyle} + onPress={() => { + if (part.data) { + handlePress({ + userId: part.data.id, + username: part.data.name, + }); + } + }}> + {part.text} + </Text> + ); + } + + // Other styled part types + return ( + <Text key={`${index}-pattern`} style={part.partType.textStyle}> + {part.text} + </Text> + ); +}; + +interface RenderProps { + value: string; + styles: StyleProp<TextStyle>; + onPress: (user: UserType) => void; +} + +/** + * Value renderer. Parsing value to parts array and then mapping the array using 'renderPart' + * + * https://github.com/dabakovich/react-native-controlled-mentions#rendering-mentioninputs-value + */ +export const renderTextWithMentions: React.FC<RenderProps> = ({ + value, + styles, + onPress, +}) => { + const {parts} = parseValue(value, mentionPartTypes); + return ( + <Text style={styles}> + {parts.map((part, index) => renderPart(part, index, onPress))} + </Text> + ); +}; + +export const mentionPartTypes: PartType[] = [ + { + trigger: '@', + renderSuggestions: (props) => <TaggTypeahead {...props} />, + allowedSpacesCount: 0, + isInsertSpaceAfterMention: true, + textStyle: {color: TAGG_LIGHT_BLUE}, + }, +]; |