From 3098e4a792acd5f6cd7bf624f2480320799e307f Mon Sep 17 00:00:00 2001 From: Felippe Rodrigo Puhle Date: Wed, 21 Oct 2020 17:09:21 -0300 Subject: [PATCH] Allow using a function to generate styles --- README.md | 13 ++++++++++++- src/ParsedText.d.ts | 5 ++++- src/lib/TextExtraction.js | 11 ++++++++--- 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index e06493f..bdc6443 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,14 @@ import ParsedText from 'react-native-parsed-text'; class Example extends React.Component { static displayName = 'Example'; + getEmailStyle(email, matchIndex /*: number*/) { + if (email.includes('@gmail.com')) { + return [styles.email, styles.gmail]; + } + + return styles.email; + } + handleUrlPress(url, matchIndex /*: number*/) { LinkingIOS.openURL(url); } @@ -71,7 +79,7 @@ class Example extends React.Component { [ {type: 'url', style: styles.url, onPress: this.handleUrlPress}, {type: 'phone', style: styles.phone, onPress: this.handlePhonePress}, - {type: 'email', style: styles.email, onPress: this.handleEmailPress}, + {type: 'email', style: this.getEmailStyle, onPress: this.handleEmailPress}, {pattern: /Bob|David/, style: styles.name, onPress: this.handleNamePress}, {pattern: /\[(@[^:]+):([^\]]+)\]/i, style: styles.username, onPress: this.handleNamePress, renderText: this.renderText}, {pattern: /42/, style: styles.magicNumber}, @@ -106,6 +114,9 @@ const styles = StyleSheet.create({ email: { textDecorationLine: 'underline', }, + gmail: { + color: 'orange', + }, text: { color: 'black', diff --git a/src/ParsedText.d.ts b/src/ParsedText.d.ts index 5e63fbe..d829fc9 100644 --- a/src/ParsedText.d.ts +++ b/src/ParsedText.d.ts @@ -5,10 +5,13 @@ declare module 'react-native-parsed-text' { interface BaseParseShape extends Pick< TextProps, - Exclude + Exclude > { /** arbitrary function to rewrite the matched string into something else */ renderText?: (matchingString: string, matches: string[]) => string; + style?: + | TextProps['style'] + | ((text: string, index: number) => TextProps['style']); onPress?: (text: string, index: number) => void; onLongPress?: (text: string, index: number) => void; } diff --git a/src/lib/TextExtraction.js b/src/lib/TextExtraction.js index 9dea4ec..ef78f77 100644 --- a/src/lib/TextExtraction.js +++ b/src/lib/TextExtraction.js @@ -121,12 +121,17 @@ class TextExtraction { return; } - if (typeof matchedPattern[key] === 'function') { + const value = matchedPattern[key]; + const isFunction = typeof value === 'function'; + + if (key === 'style') { + props[key] = isFunction ? value(text, index) : value; + } else if (isFunction) { // Support onPress / onLongPress functions - props[key] = () => matchedPattern[key](text, index); + props[key] = () => value(text, index); } else { // Set a prop with an arbitrary name to the value in the match-config - props[key] = matchedPattern[key]; + props[key] = value; } });