All files token.ts

99.23% Statements 130/131
82.6% Branches 38/46
100% Functions 35/35
99.21% Lines 126/127

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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378                                            5x 5x 5x   5x 5x 5x   5x           5x 5x 5x   5x     75x   5x 24x   24x       1x         23x               1x     24x             18x             5x                   6x       6x 3x 3x     6x             5x 6x           5x         81x 81x   81x 66x   75x             81x     5x 6x         5x 72x 90x   90x 6x         5x 69x 69x   207x 69x   69x 60x 9x 9x                 5x 75x           5x 99x   5x 24x   24x 30x   30x 24x                   24x     5x       75x 75x   234x     75x       5x       75x   75x 234x 234x     75x     5x     234x   5x       75x   234x           75x     5x       75x 75x   75x         75x       5x       25x 25x 25x   25x 2x 2x   2x 6x 6x   6x 6x         72x     25x       5x       25x 25x 25x   25x 2x   6x 6x   6x                   23x         5x 47x 51x 24x       23x       24x 24x       24x                   25x   25x 25x       25x 75x                     25x 25x 75x     25x 25x      
import { Tweenable } from './tweenable'
 
import { EasingKey, EasingObject, isEasingKey, TweenState } from './types'
 
declare module './tweenable' {
  interface Tweenable {
    /**
     * @ignore
     */
    _tokenData?: FormatSignature
  }
}
 
interface FormatSignature {
  [propertyName: string]: {
    formatString: string
    chunkNames: string[]
  }
}
 
type PropertyChunks = { [chunkName: string]: string | number }
 
const R_NUMBER_COMPONENT = /(\d|-|\.)/
const R_FORMAT_CHUNKS = /([^\-0-9.]+)/g
const R_UNFORMATTED_VALUES = /[0-9.-]+/g
 
const R_RGBA = (() => {
  const number = R_UNFORMATTED_VALUES.source
  const comma = /,\s*/.source
 
  return new RegExp(
    `rgba?\\(${number}${comma}${number}${comma}${number}(${comma}${number})?\\)`,
    'g'
  )
})()
 
const R_RGBA_PREFIX = /^.*\(/
const R_HEX = /#([0-9]|[a-f]){3,6}/gi
const VALUE_PLACEHOLDER = 'VAL'
 
const getFormatChunksFrom = (
  rawValues: number[],
  prefix: string
): Array<string> => rawValues.map((_val, i) => `_${prefix}_${i}`)
 
const getFormatStringFrom = (formattedString: string): string => {
  let chunks = formattedString.match(R_FORMAT_CHUNKS)
 
  if (!chunks) {
    // chunks will be null if there were no tokens to parse in
    // formattedString (for example, if formattedString is '2').  Coerce
    // chunks to be useful here.
    chunks = ['', '']
 
    // If there is only one chunk, assume that the string is a number
    // followed by a token...
    // NOTE: This may be an unwise assumption.
  } else if (
    chunks.length === 1 ||
    // ...or if the string starts with a number component (".", "-", or a
    // digit)...
    formattedString.charAt(0).match(R_NUMBER_COMPONENT)
  ) {
    // ...prepend an empty string here to make sure that the formatted number
    // is properly replaced by VALUE_PLACEHOLDER
    chunks.unshift('')
  }
 
  return chunks.join(VALUE_PLACEHOLDER)
}
 
/**
 * Convert a base-16 number to base-10.
 */
function hexToDec(hex: string): number {
  return parseInt(hex, 16)
}
 
/**
 * Convert a hexadecimal string to an array with three items, one each for
 * the red, blue, and green decimal values.
 */
const hexToRGBArray = (
  /**
   * A hexadecimal string.
   */
  hex: string
): /**
 * The converted Array of RGB values if `hex` is a valid string, or an Array of
 * three 0's.
 */
Array<number> => {
  hex = hex.replace(/#/, '')
 
  // If the string is a shorthand three digit hex notation, normalize it to
  // the standard six digit notation
  if (hex.length === 3) {
    const [r, g, b] = hex.split('')
    hex = r + r + g + g + b + b
  }
 
  return [
    hexToDec(hex.substring(0, 2)),
    hexToDec(hex.substring(2, 4)),
    hexToDec(hex.substring(4, 6)),
  ]
}
 
const convertHexToRGB = (hexString: string): string =>
  `rgb(${hexToRGBArray(hexString).join(',')})`
 
/**
 * TODO: Can this be rewritten to leverage String#replace more efficiently?
 * Runs a filter operation on all chunks of a string that match a RegExp.
 */
const filterStringChunks = (
  pattern: RegExp,
  unfilteredString: string,
  filter: (filter: string) => string
): string => {
  const patternMatches = unfilteredString.match(pattern)
  let filteredString = unfilteredString.replace(pattern, VALUE_PLACEHOLDER)
 
  if (patternMatches) {
    patternMatches.forEach(
      match =>
        (filteredString = filteredString.replace(
          VALUE_PLACEHOLDER,
          filter(match)
        ))
    )
  }
 
  return filteredString
}
 
const sanitizeHexChunksToRGB = (str: string): string =>
  filterStringChunks(R_HEX, str, convertHexToRGB)
 
/**
 * Convert all hex color values within a string to an rgb string.
 */
const sanitizeObjectForHexProps = (stateObject: TweenState) => {
  for (const prop in stateObject) {
    const currentProp = stateObject[prop]
 
    if (typeof currentProp === 'string' && currentProp.match(R_HEX)) {
      stateObject[prop] = sanitizeHexChunksToRGB(currentProp)
    }
  }
}
 
const sanitizeRGBAChunk = (rgbChunk: string): string => {
  const rgbaRawValues = rgbChunk.match(R_UNFORMATTED_VALUES) ?? []
  const rgbNumbers = rgbaRawValues
    .slice(0, 3)
    .map(rgbChunk => Math.floor(Number(rgbChunk)))
  const prefix = rgbChunk.match(R_RGBA_PREFIX)?.[0]
 
  if (rgbaRawValues.length === 3) {
    return `${prefix}${rgbNumbers.join(',')})`
  } else Eif (rgbaRawValues.length === 4) {
    return `${prefix}${rgbNumbers.join(',')},${rgbaRawValues[3]})`
  }
 
  throw new Error(`Invalid rgbChunk: ${rgbChunk}`)
}
 
/**
 * Check for floating point values within rgb strings and round them.
 */
const sanitizeRGBChunks = (formattedString: string): string =>
  filterStringChunks(R_RGBA, formattedString, sanitizeRGBAChunk)
 
/**
 * NOTE: It's the duty of the caller to convert the Array elements of the
 * return value into numbers.  This is a performance optimization.
 */
const getValuesFrom = (formattedString: string): Array<string> =>
  formattedString.match(R_UNFORMATTED_VALUES) ?? []
 
const getFormatSignatures = (stateObject: TweenState): FormatSignature => {
  const signatures: FormatSignature = {}
 
  for (const propertyName in stateObject) {
    const property = stateObject[propertyName]
 
    if (typeof property === 'string') {
      signatures[propertyName] = {
        formatString: getFormatStringFrom(property),
        chunkNames: getFormatChunksFrom(
          getValuesFrom(property)?.map(Number),
          propertyName
        ),
      }
    }
  }
 
  return signatures
}
 
const expandFormattedProperties = (
  stateObject: TweenState,
  formatSignatures: FormatSignature
) => {
  for (const propertyName in formatSignatures) {
    getValuesFrom(String(stateObject[propertyName])).forEach(
      (number, i) =>
        (stateObject[formatSignatures[propertyName].chunkNames[i]] = +number)
    )
 
    delete stateObject[propertyName]
  }
}
 
const extractPropertyChunks = (
  stateObject: TweenState,
  chunkNames: string[]
): PropertyChunks => {
  const extractedValues: PropertyChunks = {}
 
  chunkNames.forEach(chunkName => {
    extractedValues[chunkName] = stateObject[chunkName]
    delete stateObject[chunkName]
  })
 
  return extractedValues
}
 
const getValuesList = (
  stateObject: TweenState,
  chunkNames: Array<string>
): Array<number> => chunkNames.map(chunkName => Number(stateObject[chunkName]))
 
const getFormattedValues = (
  formatString: string,
  rawValues: Array<number>
): string => {
  rawValues.forEach(
    rawValue =>
      (formatString = formatString.replace(
        VALUE_PLACEHOLDER,
        String(+rawValue.toFixed(4))
      ))
  )
 
  return formatString
}
 
const collapseFormattedProperties = (
  stateObject: TweenState,
  formatSignature: FormatSignature
) => {
  for (const prop in formatSignature) {
    const { chunkNames, formatString } = formatSignature[prop]
 
    const currentProp = getFormattedValues(
      formatString,
      getValuesList(extractPropertyChunks(stateObject, chunkNames), chunkNames)
    )
 
    stateObject[prop] = sanitizeRGBChunks(currentProp)
  }
}
 
const expandEasingObject = (
  easingObject: EasingObject,
  formatSignature: FormatSignature
) => {
  for (const prop in formatSignature) {
    const { chunkNames } = formatSignature[prop]
    const easing = easingObject[prop]
 
    if (typeof easing === 'string') {
      const easingNames = easing.split(' ')
      const defaultEasing = easingNames[easingNames.length - 1]
 
      for (let i = 0; i < chunkNames.length; i++) {
        const chunkName = chunkNames[i]
        const easingName = easingNames[i] ?? defaultEasing
 
        Eif (isEasingKey(easingName)) {
          easingObject[chunkName] = easingName
        }
      }
    } else {
      // easing is a function
      chunkNames.forEach(chunkName => (easingObject[chunkName] = easing))
    }
 
    delete easingObject[prop]
  }
}
 
const collapseEasingObject = (
  easingObject: EasingObject,
  formatSignature: FormatSignature
) => {
  for (const prop in formatSignature) {
    const { chunkNames } = formatSignature[prop]
    const firstEasing = easingObject[chunkNames[0]]
 
    if (typeof firstEasing === 'string') {
      easingObject[prop] = chunkNames
        .map(chunkName => {
          const easingName = easingObject[chunkName]
          delete easingObject[chunkName]
 
          return easingName
        })
        // This typecast isn't accurate, but the logic works and it's performant.
        //
        // TODO: In a future major version, drop support for a single string
        // containing a space-separated list of EasingKeys and add support for an
        // Array of EasingKeys.
        .join(' ') as EasingKey
    } else {
      // firstEasing is a function
      easingObject[prop] = firstEasing
    }
  }
}
 
export const doesApply = (tweenable: Tweenable): boolean => {
  for (const key in tweenable._currentState) {
    if (typeof tweenable._currentState[key] === 'string') {
      return true
    }
  }
 
  return false
}
 
export function tweenCreated(tweenable: Tweenable) {
  const { _currentState, _originalState, _targetState } = tweenable
  ;[_currentState, _originalState, _targetState].forEach(
    sanitizeObjectForHexProps
  )
 
  tweenable._tokenData = getFormatSignatures(_currentState)
}
 
export function beforeTween(tweenable: Tweenable) {
  const {
    _currentState,
    _originalState,
    _targetState,
    _easing,
    _tokenData,
  } = tweenable
 
  Eif (typeof _easing !== 'function' && _tokenData) {
    expandEasingObject(_easing, _tokenData)
  }
 
  // eslint-disable-next-line @typescript-eslint/no-extra-semi
  ;[_currentState, _originalState, _targetState].forEach(state =>
    expandFormattedProperties(state, _tokenData ?? {})
  )
}
 
export function afterTween(tweenable: Tweenable) {
  const {
    _currentState,
    _originalState,
    _targetState,
    _easing,
    _tokenData,
  } = tweenable
  ;[_currentState, _originalState, _targetState].forEach(state =>
    collapseFormattedProperties(state, _tokenData ?? {})
  )
 
  Eif (typeof _easing !== 'function' && _tokenData) {
    collapseEasingObject(_easing, _tokenData)
  }
}