All files / src/formaters normalStyles.ts

100% Statements 25/25
100% Branches 10/10
100% Functions 5/5
100% Lines 21/21

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 50 51 52 53 54 55 56 57 58 59 60            9x               5x 5x             4x   4x 4x   3x 7x 7x   6x 6x   5x     3x       10x 10x 10x   10x             10x 9x 9x 9x        
import type { TextStyle } from 'react-native'
 
import type { FormaterBase, FormaterCreation } from './formaterBase'
import type { GenerateRegex, HighlightedTextStyles } from '../types'
 
export class NormalStyles implements FormaterBase {
  private currentStyle = 0
 
  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,
      KEY_VALUE_TEXT,
    } = 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)
      if (textIsKeyValueNumber) return true
 
      const textIsKeyValueText = KEY_VALUE_TEXT.test(t)
      if (textIsKeyValueText) return true
 
      return false
    })
 
    return !textIsKeyValue
  }
 
  create(text: string): FormaterCreation {
    const { TEXT_AMONG_BRACKETS } = this.regex
    const pureText = text.replace(TEXT_AMONG_BRACKETS, '$1')
    const style = this.getStyle()
 
    return {
      text: pureText,
      styles: style,
    }
  }
 
  private getStyle(): TextStyle | undefined {
    if (this.currentStyle < this.styles.length) {
      const style = (this.styles as TextStyle[])[this.currentStyle]
      this.currentStyle++
      return style
    }
  }
}