// Copyright (c) 2004-present, Facebook, Inc.

// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.

package com.facebook.react.views.scroll;

import android.content.Context;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import com.facebook.react.modules.i18nmanager.I18nUtil;

/** Container of Horizontal scrollViews that supports RTL scrolling. */
public class ReactHorizontalScrollContainerView extends ViewGroup {

  private int mLayoutDirection;

  public ReactHorizontalScrollContainerView(Context context) {
    super(context);
    mLayoutDirection =
        I18nUtil.getInstance().isRTL(context) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
  }

  @Override
  protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    if (mLayoutDirection == LAYOUT_DIRECTION_RTL) {
      // When the layout direction is RTL, we expect Yoga to give us a layout
      // that extends off the screen to the left so we re-center it with left=0
      int newLeft = 0;
      int width = right - left;
      int newRight = newLeft + width;
      setLeft(newLeft);
      setRight(newRight);

      // Fix the ScrollX position when using RTL language
      int offsetX = computeHorizontalScrollRange() - getScrollX();

      // Call with the present values in order to re-layout if necessary
      HorizontalScrollView parent = (HorizontalScrollView) getParent();
      parent.scrollTo(offsetX, parent.getScrollY());
    }
  }
}

@@ -545,16 +545,45 @@
 rection;
+%0A  private int mCurrentWidth;
 %0A%0A  publ
@@ -775,16 +775,39 @@
 ON_LTR;%0A
+    mCurrentWidth = 0;%0A
   %7D%0A%0A  @
@@ -1260,134 +1260,8 @@
 );%0A%0A
-      // Fix the ScrollX position when using RTL language%0A      int offsetX = computeHorizontalScrollRange() - getScrollX();%0A%0A
     
@@ -1401,16 +1401,144 @@
 rent();%0A
+      // Fix the ScrollX position when using RTL language%0A      int offsetX = parent.getScrollX() + getWidth() - mCurrentWidth;%0A
       pa
@@ -1586,14 +1586,46 @@
 ));%0A
-
     %7D%0A
+    mCurrentWidth = getWidth();%0A
   %7D%0A

Fix Horizontal ScrollView's scroll position during layout changes