1. /**
    
  2.  * Copyright (c) Meta Platforms, Inc. and affiliates.
    
  3.  *
    
  4.  * This source code is licensed under the MIT license found in the
    
  5.  * LICENSE file in the root directory of this source tree.
    
  6.  */
    
  7. 
    
  8. /**
    
  9.  * These variables store information about text content of a target node,
    
  10.  * allowing comparison of content before and after a given event.
    
  11.  *
    
  12.  * Identify the node where selection currently begins, then observe
    
  13.  * both its text content and its current position in the DOM. Since the
    
  14.  * browser may natively replace the target node during composition, we can
    
  15.  * use its position to find its replacement.
    
  16.  *
    
  17.  *
    
  18.  */
    
  19. 
    
  20. let root = null;
    
  21. let startText = null;
    
  22. let fallbackText = null;
    
  23. 
    
  24. export function initialize(nativeEventTarget) {
    
  25.   root = nativeEventTarget;
    
  26.   startText = getText();
    
  27.   return true;
    
  28. }
    
  29. 
    
  30. export function reset() {
    
  31.   root = null;
    
  32.   startText = null;
    
  33.   fallbackText = null;
    
  34. }
    
  35. 
    
  36. export function getData() {
    
  37.   if (fallbackText) {
    
  38.     return fallbackText;
    
  39.   }
    
  40. 
    
  41.   let start;
    
  42.   const startValue = startText;
    
  43.   const startLength = startValue.length;
    
  44.   let end;
    
  45.   const endValue = getText();
    
  46.   const endLength = endValue.length;
    
  47. 
    
  48.   for (start = 0; start < startLength; start++) {
    
  49.     if (startValue[start] !== endValue[start]) {
    
  50.       break;
    
  51.     }
    
  52.   }
    
  53. 
    
  54.   const minEnd = startLength - start;
    
  55.   for (end = 1; end <= minEnd; end++) {
    
  56.     if (startValue[startLength - end] !== endValue[endLength - end]) {
    
  57.       break;
    
  58.     }
    
  59.   }
    
  60. 
    
  61.   const sliceTail = end > 1 ? 1 - end : undefined;
    
  62.   fallbackText = endValue.slice(start, sliceTail);
    
  63.   return fallbackText;
    
  64. }
    
  65. 
    
  66. export function getText() {
    
  67.   if ('value' in root) {
    
  68.     return root.value;
    
  69.   }
    
  70.   return root.textContent;
    
  71. }