tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

initial-letter-variants.js (2118B)


      1 window.addEventListener('load', setupInitialLetterTestVariants);
      2 
      3 function setupInitialLetterTestVariants() {
      4  const search = window.location.search;
      5  if (!search) {
      6    return;
      7  }
      8  const params = new URLSearchParams(search);
      9  const classes = params.getAll('class')
     10                  .flatMap(value => value.split(','))
     11                  .filter(value => value);
     12  let text = params.getAll('text').join('');
     13  if (!text) {
     14    if (classes.indexOf('no-descent') >= 0) {
     15      text = '\xC9\xC9M\xC9';
     16    } else if (classes.indexOf('no-ascent') >= 0) {
     17      text = 'ppMp';
     18    }
     19  }
     20 
     21  for (const element of document.getElementsByClassName('sample')) {
     22    element.classList.add(...classes);
     23    if (text) {
     24      replaceTextStart(element, text);
     25    }
     26  }
     27 }
     28 
     29 // Replace the start of the text content of the node.
     30 // Returns the number of characters replaced.
     31 //
     32 // For example,
     33 // `replaceTextStart(element, 'XY')` to the content:
     34 // ```
     35 // <div>ABC</div>
     36 // ```
     37 // produces:
     38 // ```
     39 // <div>XYC</div>
     40 // ```
     41 //
     42 // It has a limited support for separated text nodes and collapsible spaces.
     43 function replaceTextStart(node, text) {
     44  if (node.nodeType == Node.TEXT_NODE) {
     45    const content = node.nodeValue;
     46    const trimmed_content = content.trimStart();
     47    if (!trimmed_content) {
     48      return 0;
     49    }
     50    const leading_spaces_len = content.length - trimmed_content.length;
     51    const len = Math.min(text.length, trimmed_content.length);
     52    node.nodeValue = content.substring(0, leading_spaces_len) +
     53                     text.substring(0, len) +
     54                     trimmed_content.substring(len);
     55    return len;
     56  }
     57 
     58  if (node.nodeType == Node.ELEMENT_NODE && node.className.indexOf('fake') >= 0) {
     59    // If this is a fake initial letter, pretend that one character is replaced.
     60    return 1;
     61  }
     62 
     63  let total_replaced = 0;
     64  for (const child of node.childNodes) {
     65    const replaced = replaceTextStart(child, text);
     66    if (replaced) {
     67      total_replaced += replaced;
     68      text = text.substring(replaced);
     69      if (!text) {
     70        return total_replaced;
     71      }
     72    }
     73  }
     74  return total_replaced;
     75 }