All files / src/formaters numberedStyles.ts

100% Statements 20/20
100% Branches 4/4
100% Functions 6/6
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49                        5x 5x           4x   4x 4x   3x 8x 8x     3x       10x 10x 10x 10x   17x 17x 10x   10x            
import type { TextStyle } from 'react-native'
 
import type { FormaterBase, FormaterCreation } from './formaterBase'
import type { GenerateRegex, HighlightedTextStyles } from '../types'
 
export class NumberedStyles implements FormaterBase {
  constructor(
    readonly styles: HighlightedTextStyles,
    readonly regex: ReturnType<GenerateRegex>,
  ) {}
 
  validate(text: string): boolean {
    const stylesIsArray = Array.isArray(this.styles)
    if (!stylesIsArray) return false
 
    const {
      TEXT_AMONG_BRACKETS,
      TEXT_WITH_BRACKETS,
      KEY_VALUE_NUMBER,
    } = this.regex
 
    const textIsHighlighted = TEXT_WITH_BRACKETS.test(text)
    if (!textIsHighlighted) return false
 
    const textIsKeyValue = text.split(TEXT_AMONG_BRACKETS).some(t => {
      const textIsKeyValueNumber = KEY_VALUE_NUMBER.test(t)
      return textIsKeyValueNumber
    })
 
    return textIsKeyValue
  }
 
  create(text: string): FormaterCreation {
    const { TEXT_AMONG_BRACKETS } = this.regex
    const pureText = text.replace(TEXT_AMONG_BRACKETS, '$1')
    const keysAndText = pureText.split('=')
    const keys = keysAndText[0]
      .split(',')
      .map(stringNumbers => parseInt(stringNumbers) - 1)
    const styles = keys.map(key => (this.styles as TextStyle[])[key])
    const finalText = keysAndText[1]
 
    return {
      text: finalText,
      styles,
    }
  }
}