-
Notifications
You must be signed in to change notification settings - Fork 0
feat: highlight text #40
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
anhle10051996
wants to merge
3
commits into
develop
Choose a base branch
from
feat/high-light-text
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| import type {ComponentMeta, ComponentStory} from '@storybook/react' | ||
| import React from 'react' | ||
|
|
||
| import {HighlightText} from 'rn-base-component' | ||
|
|
||
| export default { | ||
| title: 'components/HighlightText', | ||
| component: HighlightText, | ||
| } as ComponentMeta<typeof HighlightText> | ||
|
|
||
| export const Basic: ComponentStory<typeof HighlightText> = args => <HighlightText {...args} /> | ||
|
|
||
| Basic.args = { | ||
| textToHighlight: 'Hello STS Tea123123m!', | ||
| searchWords: ['Hello', 'Tea'], | ||
| highlightTextStyle: {backgroundColor: 'yellow'}, | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| import {render} from '@testing-library/react-native' | ||
| import React from 'react' | ||
| import {StyleSheet} from 'react-native' | ||
| import type {ReactTestInstance} from 'react-test-renderer' | ||
| import HighlightText from '../components/HighlightText/HighlightText' | ||
|
|
||
| describe('HighlightText', () => { | ||
| const textToHighlight = 'Lorem ipsum dolor sit amet consectetur adipiscing elit' | ||
huydosgtech marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| const searchWords = ['ipsum', 'adipiscing'] | ||
| it('should render correctly', () => { | ||
| const {getByTestId} = render( | ||
| <HighlightText textToHighlight={textToHighlight} searchWords={searchWords} />, | ||
| ) | ||
| expect(getByTestId('container')).toBeDefined() | ||
| }) | ||
|
|
||
| it('renders highlighted and non-highlighted text correctly', () => { | ||
| const {getByTestId, getAllByTestId} = render( | ||
| <HighlightText textToHighlight={textToHighlight} searchWords={searchWords} />, | ||
| ) | ||
|
|
||
| const container = getByTestId('container') | ||
| expect(container).toBeTruthy() | ||
| const renderedTexts = getAllByTestId('text') | ||
| expect(renderedTexts).toHaveLength(5) | ||
|
|
||
| const firstText = container.children[0] as ReactTestInstance | ||
| const highlightedText = container.children[1] as ReactTestInstance | ||
| const lastText = container.children[2] as ReactTestInstance | ||
|
|
||
| expect(firstText?.props.children).toBe('Lorem ') | ||
| expect(highlightedText?.props.children).toBe('ipsum') | ||
| expect(lastText?.props?.children).toBe(' dolor sit amet consectetur ') | ||
| }) | ||
|
|
||
| it('applies custom styles correctly', () => { | ||
| const highlightTextStyle = {backgroundColor: 'yellow'} | ||
| const normalTextStyle = {backgroundColor: 'red'} | ||
|
|
||
| const {getAllByTestId} = render( | ||
| <HighlightText | ||
| textToHighlight={textToHighlight} | ||
| searchWords={searchWords} | ||
| highlightTextStyle={highlightTextStyle} | ||
| normalTextStyle={normalTextStyle} | ||
| />, | ||
| ) | ||
|
|
||
| const renderedTexts = getAllByTestId('text') | ||
|
|
||
| const firstText = renderedTexts[0] as ReactTestInstance | ||
| const highlightedText = renderedTexts[1] as ReactTestInstance | ||
| const lastText = renderedTexts[2] as ReactTestInstance | ||
|
|
||
| expect(StyleSheet.flatten(firstText.props.style)).toEqual(normalTextStyle) | ||
| expect(StyleSheet.flatten(highlightedText.props.style)).toEqual(highlightTextStyle) | ||
| expect(StyleSheet.flatten(lastText.props.style)).toEqual(normalTextStyle) | ||
| }) | ||
| }) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| import React from 'react' | ||
| import {StyleProp, Text, TextStyle} from 'react-native' | ||
| import styled from 'styled-components/native' | ||
| import type {ITheme} from '../../theme' | ||
| import {findAll} from './utils' | ||
|
|
||
| type CustomTextStyleProp = StyleProp<TextStyle> | Array<StyleProp<TextStyle>> | ||
|
|
||
| export type Theme = { | ||
| theme?: ITheme | ||
| } | ||
|
|
||
| export type HighlightTextProps = { | ||
| /** | ||
| * Text to highlight | ||
| */ | ||
| textToHighlight: string | ||
| /** | ||
| * Array of search words | ||
| */ | ||
| searchWords: Array<string> | ||
| /** | ||
| * custom function to process each word and text to highlight | ||
| * default: undefined | ||
| */ | ||
| sanitize?: (string: string) => string | ||
| /** | ||
| * Escape special characters | ||
| * default: false | ||
| */ | ||
| autoEscape?: boolean | ||
| /** | ||
| * Styles applied to sentence | ||
| * default: undefined | ||
| */ | ||
| textWrapperStyle?: CustomTextStyleProp | ||
| /** | ||
| * Styles applied to normal text | ||
| * default: undefined | ||
| */ | ||
| normalTextStyle?: CustomTextStyleProp | ||
| /** | ||
| * Styles applied to highlight text | ||
| * default: undefined | ||
| */ | ||
| highlightTextStyle?: CustomTextStyleProp | ||
| } | ||
|
|
||
| const HighlightText: React.FC<HighlightTextProps> = ({ | ||
| textToHighlight, | ||
| searchWords, | ||
| sanitize, | ||
| autoEscape = false, | ||
| textWrapperStyle, | ||
| normalTextStyle, | ||
| highlightTextStyle, | ||
| ...props | ||
| }) => { | ||
| const chunks = findAll({textToHighlight, searchWords, sanitize, autoEscape}) | ||
| return ( | ||
| <TextWrapper style={textWrapperStyle} testID="container" {...props}> | ||
huydosgtech marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| {chunks.map((chunk, index) => { | ||
| const text = textToHighlight.substring(chunk.start, chunk.end) | ||
|
|
||
| return !chunk.highlight ? ( | ||
| <Text style={normalTextStyle} key={index} testID="text"> | ||
| {text} | ||
| </Text> | ||
| ) : ( | ||
| <Highlight testID="text" key={index} style={chunk.highlight && highlightTextStyle}> | ||
| {text} | ||
| </Highlight> | ||
| ) | ||
| })} | ||
| </TextWrapper> | ||
| ) | ||
| } | ||
|
|
||
| const TextWrapper = styled(Text)({}) | ||
| const Highlight = styled(Text)(({theme}: Theme) => ({ | ||
| color: theme?.colors?.darkText, | ||
| fontWeight: theme?.fontWeights?.extrabold, | ||
| backgroundColor: theme?.colors?.white, | ||
| })) | ||
|
|
||
| HighlightText.displayName = 'HighlightText' | ||
| export default HighlightText | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,169 @@ | ||
| export type Chunk = { | ||
| highlight: boolean | ||
| start: number | ||
| end: number | ||
| } | ||
|
|
||
| /** | ||
| * Creates an array of chunk objects representing both higlightable and non highlightable pieces of text that match each search word. | ||
| * @return Array of "chunks" (where a Chunk is { start:number, end:number, highlight:boolean }) | ||
| */ | ||
| export const findAll = ({ | ||
| autoEscape, | ||
| caseSensitive = false, | ||
| findChunks = defaultFindChunks, | ||
| sanitize, | ||
| searchWords, | ||
| textToHighlight, | ||
| }: { | ||
| autoEscape?: boolean | ||
| caseSensitive?: boolean | ||
| findChunks?: typeof defaultFindChunks | ||
| sanitize?: typeof defaultSanitize | ||
| searchWords: Array<string> | ||
| textToHighlight: string | ||
| }): Array<Chunk> => | ||
| fillInChunks({ | ||
| chunksToHighlight: combineChunks({ | ||
| chunks: findChunks({ | ||
| autoEscape, | ||
| caseSensitive, | ||
| sanitize, | ||
| searchWords, | ||
| textToHighlight, | ||
| }), | ||
| }), | ||
| totalLength: textToHighlight ? textToHighlight.length : 0, | ||
| }) | ||
|
|
||
| /** | ||
| * Takes an array of {start:number, end:number} objects and combines chunks that overlap into single chunks. | ||
| * @return {start:number, end:number}[] | ||
| */ | ||
| export const combineChunks = ({chunks}: {chunks: Array<Chunk>}): Array<Chunk> => { | ||
| const res: Array<Chunk> = chunks | ||
| .sort((first, second) => first.start - second.start) | ||
| .reduce((processedChunks: Chunk[], nextChunk) => { | ||
| // First chunk just goes straight in the array... | ||
| if (processedChunks.length === 0) { | ||
| return [nextChunk] | ||
| } else { | ||
| // ... subsequent chunks get checked to see if they overlap... | ||
| const prevChunk = processedChunks.pop() | ||
| if (prevChunk && nextChunk.start <= prevChunk.end) { | ||
| // It may be the case that prevChunk completely surrounds nextChunk, so take the | ||
| // largest of the end indeces. | ||
| const endIndex = Math.max(prevChunk.end, nextChunk.end) | ||
| processedChunks.push({highlight: false, start: prevChunk.start, end: endIndex}) | ||
| } else { | ||
| if (prevChunk) { | ||
| processedChunks.push(prevChunk, nextChunk) | ||
| } | ||
| } | ||
| return processedChunks | ||
| } | ||
| }, []) | ||
|
|
||
| return res | ||
| } | ||
|
|
||
| /** | ||
| * Examine text for any matches. | ||
| * If we find matches, add them to the returned array as a "chunk" object ({start:number, end:number}). | ||
| * @return {start:number, end:number}[] | ||
| */ | ||
| const defaultFindChunks = ({ | ||
| autoEscape, | ||
| caseSensitive, | ||
| sanitize = defaultSanitize, | ||
| searchWords, | ||
| textToHighlight, | ||
| }: { | ||
| autoEscape?: boolean | ||
| caseSensitive?: boolean | ||
| sanitize?: typeof defaultSanitize | ||
| searchWords: Array<string> | ||
| textToHighlight: string | ||
| }): Array<Chunk> => { | ||
| textToHighlight = sanitize(textToHighlight) | ||
|
|
||
| return searchWords | ||
| .filter(searchWord => searchWord) // Remove empty words | ||
| .reduce((chunks: Array<Chunk>, searchWord) => { | ||
| searchWord = sanitize(searchWord) | ||
|
|
||
| if (autoEscape) { | ||
| searchWord = escapeRegExpFn(searchWord) | ||
| } | ||
|
|
||
| const regex = new RegExp(searchWord, caseSensitive ? 'g' : 'gi') | ||
|
|
||
| let match | ||
| while ((match = regex.exec(textToHighlight))) { | ||
| const start = match.index | ||
| const end = regex.lastIndex | ||
| // We do not return zero-length matches | ||
| if (end > start) { | ||
| chunks.push({highlight: false, start, end}) | ||
| } | ||
|
|
||
| // Prevent browsers like Firefox from getting stuck in an infinite loop | ||
| // See http://www.regexguru.com/2008/04/watch-out-for-zero-length-matches/ | ||
| if (match.index === regex.lastIndex) { | ||
| regex.lastIndex++ | ||
| } | ||
| } | ||
|
|
||
| return chunks | ||
| }, []) | ||
| } | ||
| // Allow the findChunks to be overridden in findAll, | ||
| // but for backwards compatibility we export as the old name | ||
| export {defaultFindChunks as findChunks} | ||
|
|
||
| /** | ||
| * Given a set of chunks to highlight, create an additional set of chunks | ||
| * to represent the bits of text between the highlighted text. | ||
| * @param chunksToHighlight {start:number, end:number}[] | ||
| * @param totalLength number | ||
| * @return {start:number, end:number, highlight:boolean}[] | ||
| */ | ||
| export const fillInChunks = ({ | ||
| chunksToHighlight, | ||
| totalLength, | ||
| }: { | ||
| chunksToHighlight: Array<Chunk> | ||
| totalLength: number | ||
| }): Array<Chunk> => { | ||
| const allChunks: Array<Chunk> = [] | ||
| const append = (start: number, end: number, highlight: boolean) => { | ||
| if (end - start > 0) { | ||
| allChunks.push({ | ||
| start, | ||
| end, | ||
| highlight, | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| if (chunksToHighlight.length === 0) { | ||
| append(0, totalLength, false) | ||
| } else { | ||
| let lastIndex = 0 | ||
| chunksToHighlight.forEach(chunk => { | ||
| append(lastIndex, chunk.start, false) | ||
| append(chunk.start, chunk.end, true) | ||
| lastIndex = chunk.end | ||
| }) | ||
| append(lastIndex, totalLength, false) | ||
| } | ||
| return allChunks | ||
| } | ||
|
|
||
| function defaultSanitize(string: string): string { | ||
| return string | ||
| } | ||
|
|
||
| function escapeRegExpFn(string: string): string { | ||
| return string.replace(/[-[\]{}()*+?.,\\^$|]/g, '\\$&') | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.