All files / utils/algorithms get-translate-from-element.util.js

54% Statements 27/50
50% Branches 1/2
50% Functions 1/2
54% Lines 27/50

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 511x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x                   1x 1x 1x 1x 1x                              
import { traverseUpDomWithSlots } from './traverse-up-dom.js'
 
/**
 * Check whether the element is translatable
 *
 * It respects the `translate` global attribute:
 *
 * >   The translate attribute is an enumerated attribute that is used to
 * > specify whether an element's attribute values and the values of its
 * > Text node children are to be translated when the page is localized,
 * > or whether to leave them unchanged.
 *
 * The translate will apply to all elements, including non-HTML elements
 * @see https://html.spec.whatwg.org/multipage/dom.html#attr-translate
 * @param {Element} element - t
 * @returns {boolean} true if element is translatable, false otherwise
 */
export function isElementTranslatable (element) {
  // the vast majority of element are HTMLElement, so validating it first is good
  if (element instanceof HTMLElement) {
    return element.translate
  }
  if (element == null) {
    return false
  }
  for (const node of traverseUpDomWithSlots(element)) {
    const value = translateValue(node)
    if (value != null) { return value }
  }
  return true
}
 
/**
 * @param {Element} element - target element, may have `translate` attribute defined or not
 * @returns {boolean | null} null if translateValue is invalid, true if translate is enabled, false otherwise
 */
function translateValue (element) {
  if (element instanceof HTMLElement) {
    return element.translate
  }
  const translateValue = element.getAttribute('translate')

  if (translateValue === '' || translateValue === 'yes') {
    return true
  } else if (translateValue === 'no') {
    return false
  }

  return null
}