All files / framework/strings String.tsx

95.65% Statements 22/23
88.89% Branches 8/9
100% Functions 3/3
95.65% Lines 22/23

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 61 62 63 64 65 66 67 68 69 70 71 72              1093x 1093x 1093x   1093x             1093x 63451x   63262x     176419x 176389x     30x   30x 22x     8x                         1093x 2388x 2388x   2388x 2388x   2367x           21x 21x             1093x      
/*
 * Copyright 2021 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import React from 'react'
import { render } from 'mustache'
import { get } from 'lodash-es'
 
import { useStringsContext, StringKeys } from './StringsContext'
 
export interface UseStringsReturn {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  getString(key: StringKeys, vars?: Record<string, any>): string
}
 
export function useStrings(): UseStringsReturn {
  const { data: strings, getString } = useStringsContext()
 
  return {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    getString(key: StringKeys, vars: Record<string, any> = {}) {
      if (typeof getString === 'function') {
        return getString(key, vars)
      }
 
      const template = get(strings, key)
 
      if (typeof template !== 'string') {
        throw new Error(`No valid template with id "${key}" found in any namespace`)
      }
 
      return render(template, { ...vars, $: strings })
    }
  }
}
 
export interface StringProps extends React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement> {
  stringID: StringKeys
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  vars?: Record<string, any>
  useRichText?: boolean
  tagName: keyof JSX.IntrinsicElements
}
 
export function String(props: StringProps): React.ReactElement | null {
  const { stringID, vars, useRichText, tagName: Tag, ...rest } = props
  const { getString } = useStrings()
 
  try {
    const text = getString(stringID, vars)
 
    return useRichText ? (
      <Tag {...(rest as unknown)} dangerouslySetInnerHTML={{ __html: text }} />
    ) : (
      <Tag {...(rest as unknown)}>{text}</Tag>
    )
  } catch (e) {
    Eif (process.env.NODE_ENV !== 'production') {
      return <Tag style={{ color: 'var(--red-500)' }}>{e.message}</Tag>
    }
 
    return null
  }
}
 
String.defaultProps = {
  tagName: 'span'
}