Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update trunk with upstream version 3.2.0 #25

Closed
wants to merge 530 commits into from
Closed

Conversation

fluiddot
Copy link

@fluiddot fluiddot commented Jun 5, 2023

This PR updates trunk with upstream version 3.2.0 (commit: software-mansion@663ee74).

Based on https://docs.swmansion.com/react-native-reanimated/docs/guide/migration-from-2.x/ there are breaking changes from 2.x to 3.x.

NOTE: I found tons of file conflicts with trunk when creating this PR, I rebased with trunk and solve all of them using changes coming from the upstream repository.

graszka22 and others added 30 commits June 5, 2023 18:56
…are-mansion#3901)

<!-- Thanks for submitting a pull request! We appreciate you spending the time to work on these changes. Please follow the template so that the reviewers can easily understand what the code changes affect. -->

## Summary

Fixes software-mansion#3689

## Test plan

Run `DefaultAnimations` example, change device orientation, run for example `SlideInLeft` animation.
…software-mansion#3921)

## Summary

Fixes software-mansion#3800

The type `REAHasAnimationBlock` is defined as:
```obj-c
typedef BOOL (^REAHasAnimationBlock)(NSNumber *_Nonnull tag, NSString *_Nonnull type);
```
but lambda from code had `bool (^REAHasAnimationBlock)(NSNumber *_Nonnull tag, NSString *_Nonnull type)` type and it was breaking some build configurations.
…on#3922)

<!-- Thanks for submitting a pull request! We appreciate you spending
the time to work on these changes. Please follow the template so that
the reviewers can easily understand what the code changes affect. -->

## Summary
Fixes issues when bundling web apps using reanimated due to relative
path to `package.json` being wrongly resolved in prebuild reanimated
modules.

<!-- Explain the motivation for this PR. Include "Fixes #<number>" if
applicable. -->
## Summary

This PR fixes a crash on Fabric in `ensureYogaChildrenAlighment`.

Original crash:
<img width="1624" alt="Zrzut ekranu 2023-01-10 o 13 43 50" src="https://user-images.githubusercontent.com/20516055/211556442-eb4819e8-6bf7-4d09-a4e3-daea10cd258c.png">
<img width="723" alt="Zrzut ekranu 2023-01-10 o 13 44 11" src="https://user-images.githubusercontent.com/20516055/211556594-5e650600-6d62-41ea-8023-079df51c1337.png">

After moving `shadowTreeCloner.updateYogaChildren();` to the scope with the lock:
<img width="1624" alt="Zrzut ekranu 2023-01-10 o 13 42 12" src="https://user-images.githubusercontent.com/20516055/211556582-47b8275e-73c6-4646-adda-7210dad3df09.png">

After 619a6a0 I was no longer able to reproduce the crash.

## Test plan

1. Change number of circles in BokehExample to 500
2. Launch FabricExample
3. Reload the app a few times with an interval of 2 seconds
## Summary

Just a rename.

## Test plan

Just check if it compiles.
…sion#3947)

<!-- Thanks for submitting a pull request! We appreciate you spending
the time to work on these changes. Please follow the template so that
the reviewers can easily understand what the code changes affect. -->

## Summary
Adds a warning for style animations missing initial values.

<!-- Explain the motivation for this PR. Include "Fixes #<number>" if
applicable. -->
<!-- Thanks for submitting a pull request! We appreciate you spending
the time to work on these changes. Please follow the template so that
the reviewers can easily understand what the code changes affect. -->

## Summary

- Added `useAnimatedSensor` for the web implementation

## Test plan

- Used chrome on the android device to check if the sensor returns
correct data
…s runtimes (software-mansion#3930)

## Summary

This PR changes the way we extract code string and additional metadata
for worklets and the way we pass it later on between runtimes such that
we can save on allocating code strings that tend to be relatively big
and waste precious time on allocating those strings.

The scope of the change includes:
1. Changes in plugin code, we no longer assign code string directly to
worklet function objects, instead we extract a metadata object and
define in in the program context (at the main file level). The metadata
includes things that are static, like the code converted to string
(formerly "asString", location, source map and stack details data). We
then reference that metadata object and assign it to the worklet object
under `__initData` field.
2. We update "Core Functions" that need to access code string such that
it fetches the string from a new location – `__initData.code`
3. We refactor the concept of "retaining values" and only conditionally
retain JS values on the UI runtime from the shareable. The purpose of
this change is that we can be sure the initData is persisted on the UI
runtime and not recreated each time the worklet it passed to be executed
on the UI runtime. We add additional flag `shouldRetain` to the
`makeShareableClone` JSI method that allows us to control this behavior.
The refactoring updates the inheritance scheme and makes
`ShareableObjects` etc no longer inherit `RetainingShareable` but
instead we only use `RetainingShareable` when the flag is set. This
change also deletes the previous behavior where we'd use weak objects to
keep the reference to the JS Value as we are unsure about
positive/negative impact of that code (we know it impacts GC times
negatively but not sure if this time is counterbalanced by saving on the
time to convert the values)

## Test plan

Plugin tests needs to be updated. Wanted to put this change out for
others to test.
…ge (software-mansion#3956)

## Summary

Fixes software-mansion#3952.

## Test plan

1. Build Reanimated 2 package on CI
2. Create a new RN 0.70.6 app with Reanimated
3. Copy BokehExample to App.js
4. Build the app in release mode for Android
5. Check if the runtime error is gone
<!-- Thanks for submitting a pull request! We appreciate you spending
the time to work on these changes. Please follow the template so that
the reviewers can easily understand what the code changes affect. -->

## Summary

This PR provides a better error message in cases like software-mansion#3943.

<!-- Explain the motivation for this PR. Include "Fixes #<number>" if
applicable. -->

## Test plan

<!-- Provide a minimal but complete code snippet that can be used to
test out this change along with instructions how to run it and a
description of the expected behavior. -->
…software-mansion#3938)

<!-- Thanks for submitting a pull request! We appreciate you spending
the time to work on these changes. Please follow the template so that
the reviewers can easily understand what the code changes affect. -->

## Summary

Fixes software-mansion#3937.

## Test plan

<!-- Provide a minimal but complete code snippet that can be used to
test out this change along with instructions how to run it and a
description of the expected behavior. -->

Co-authored-by: Thanh Tran <thanh@lhts.io>
…sion#3945)

## Summary

I have a `libglog.so` in my default path so CMAKE takes it instead of
provided one.
Build failed then.

## Test plan

Put `libglog.so` in another architecture in your default path and you
will see how linker fails.
## Summary

This PR provides a new better implementation of `isAnimated` utility
function as the previous version was very poorly written. The old
implementation holds a queue of props to be checked and thus needs to
allocate and populate a new array on each call, whereas the new
implementation uses recursion instead &ndash; however, in most of the
real-world cases, it is never called recursively. Since `isAnimated` is
used very frequently throughout the codebase, previously it took ~7% of
total execution time. After the changes, it dropped down to ~3%.

Co-authored-by: @kmagiera

## Test plan

Just check if BokehExample works.
…on#3950)

## Summary

This PR contains two little optimizations in `styleUpdater`:

1. Since we never use `oldValues` again (because references the same
object as `state.last` does before we overwrite it in the very same
line), we can re-use this instance instead of creating a new one.
2. Since we just calculated the difference between the new and old
styles, we can overwrite `oldValues` just with `diff` instead of
`newValues` because the values that are not present in `diff` are the
same in `oldValues` and `newValues`.

Co-authored-by: @kmagiera

## Test plan

Just check if BokehExample works.
…oftware-mansion#3940)

<!-- Thanks for submitting a pull request! We appreciate you spending
the time to work on these changes. Please follow the template so that
the reviewers can easily understand what the code changes affect. -->

## Summary

Fixes a bug when changing keyboard language on iOS:

Bug:

https://user-images.githubusercontent.com/6280457/212095624-4df7e0b0-d3e6-4bdd-8378-ad8c077e6fb2.mp4

Fixed bug:


https://user-images.githubusercontent.com/6280457/212096575-aa36cb88-fee5-4f4c-bd37-676973834d48.mp4

Fixes
software-mansion#3721

`useAnimatedKeyboard` reported invalid keyboard height in that case,
because we invalided display link too early, in `stopAnimation` and we
reported the height before suggestions bar appeared. In the next frame
the suggestion bar appears and we can calculate correct keyboard height.

## Test plan

Run AnimatedKeyboardExample, bring up the keyboard and change keyboard
language. The text input should be above the keyboard in correct
position.

<details>
<summary>Example for switching between numeric/regular
keyboard:</summary>


```js
import React from 'react';

import { TextInput, View, StyleSheet } from 'react-native';

import { useAnimatedKeyboard, useAnimatedStyle } from 'react-native-reanimated';

export default function App() {
  const { height } = useAnimatedKeyboard();

  useAnimatedStyle(() => {
    console.log('HEIGHT', height.value);
    return {};
  });

  return (
    <View style={styles.container}>
      <TextInput style={styles.input} keyboardType="default" />
      <TextInput style={styles.input} keyboardType="number-pad" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    padding: 20,
  },
  input: {
    borderBottomWidth: 1,
    borderBottomColor: '#ccc',
    marginBottom: 20,
    backgroundColor: '#ddd',
    height: 50,
  },
});
```
</details>
<!-- Thanks for submitting a pull request! We appreciate you spending
the time to work on these changes. Please follow the template so that
the reviewers can easily understand what the code changes affect. -->

## Summary

Fixes
software-mansion#3631
Fixes the issue with translucent StatusBar on Android by adding the
option `isStatusBarTranslucentAndroid` in `useAnimatedKeyboard`. It is
the same solution as the one mentioned in the issue:
kirillzyusko/react-native-keyboard-controller@2a7c92f

## Test plan

There is an excellent example in the issue that reproduces the problem:
https://github.com/ChildishForces/reanimated-bug-repro
I tested on real Android device with Android 12 and RN 71.
I think it would be nice to also test on RN < 70 because the bottom
padding may behave differently.
<!-- Thanks for submitting a pull request! We appreciate you spending
the time to work on these changes. Please follow the template so that
the reviewers can easily understand what the code changes affect. -->

## Summary

JSI's `asBool` was only added in RN 69. This PR changes `asBool` to
`getBool` call in order to support older RN versions.

## Test plan

<!-- Provide a minimal but complete code snippet that can be used to
test out this change along with instructions how to run it and a
description of the expected behavior. -->
<!-- Thanks for submitting a pull request! We appreciate you spending
the time to work on these changes. Please follow the template so that
the reviewers can easily understand what the code changes affect. -->

## Summary

<!-- Explain the motivation for this PR. Include "Fixes #<number>" if
applicable. -->

Applied requested changes to software-mansion#3955 after late code review. 
- Removed unnecessary if condition inside callback.
- Fixed unit conversion bug

## Test plan

- Chrome on the android device.
## Summary

We have a typo on
`react-native-reanimated/lib/commonjs/reanimated2/mock`, where
`FadeInDown` is typed wrong, and mocked as `FadFadeInDown`. This PR
fixes it.

## Test plan

I'm mocking Reanimated on jest in this way, on the new version:
```ts
jest.mock('react-native-reanimated', () => {
  return {
    ...jest.requireActual('react-native-reanimated/mock'),
    ...jest.requireActual(
      'react-native-reanimated/lib/commonjs/reanimated2/mock',
    ),
  };
});
```

But, as this typo makes the Reanimated2 mocks not contain the FadeInDown
method, Jest throws this error on files that use this Fade.

<img width="670" alt="Captura de Tela 2023-01-18 às 15 13 44"
src="https://user-images.githubusercontent.com/50031755/213261421-b533f182-cb27-48aa-9360-77881394d865.png">

I'm currently fixing it with patch-package, while that isn't officially
merged and released. The issue is still present after updating to
3.0.0-rc.10
…nsion#3972)

## Summary

This PR updates react-native to 0.71.0 as well as other third-party
libraries to the latest versions both in Example and FabricExample apps.

## Test plan

Run Example and FabricExample apps on Android and iOS in debug and
release mode.
…nsion#3973)

Bumps [activesupport](https://github.com/rails/rails) from 6.1.5 to
6.1.7.1.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/rails/rails/releases">activesupport's
releases</a>.</em></p>
<blockquote>
<h2>v6.1.7.1</h2>
<h2>Active Support</h2>
<ul>
<li>
<p>Avoid regex backtracking in Inflector.underscore</p>
<p>[CVE-2023-22796]</p>
</li>
</ul>
<h2>Active Model</h2>
<ul>
<li>No changes.</li>
</ul>
<h2>Active Record</h2>
<ul>
<li>
<p>Make sanitize_as_sql_comment more strict</p>
<p>Though this method was likely never meant to take user input, it was
attempting sanitization. That sanitization could be bypassed with
carefully crafted input.</p>
<p>This commit makes the sanitization more robust by replacing any
occurrances of &quot;/<em>&quot; or &quot;</em>/&quot; with &quot;/
<em>&quot; or &quot;</em> /&quot;. It also performs a
first pass to remove one surrounding comment to avoid compatibility
issues for users relying on the existing removal.</p>
<p>This also clarifies in the documentation of annotate that it should
not
be provided user input.</p>
<p>[CVE-2023-22794]</p>
</li>
<li>
<p>Added integer width check to PostgreSQL::Quoting</p>
<p>Given a value outside the range for a 64bit signed integer type
PostgreSQL will treat the column type as numeric. Comparing
integer values against numeric values can result in a slow
sequential scan.</p>
<p>This behavior is configurable via
ActiveRecord::Base.raise_int_wider_than_64bit which defaults to
true.</p>
<p>[CVE-2022-44566]</p>
</li>
</ul>
<h2>Action View</h2>
<ul>
<li>No changes.</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/rails/rails/commit/c443466a99f8ed951605fb4993a01de5e41349a4"><code>c443466</code></a>
Version 6.1.7.1</li>
<li><a
href="https://github.com/rails/rails/commit/a7cda7e6aa5334ab41b1f4b0f671be931be946ef"><code>a7cda7e</code></a>
Avoid regex backtracking in Inflector.underscore</li>
<li><a
href="https://github.com/rails/rails/commit/9ab33753b6bab1809fc73d35b98a5c1d0c96ba1b"><code>9ab3375</code></a>
Version 6.1.7</li>
<li><a
href="https://github.com/rails/rails/commit/ad24aa5b68db8d9dd9323d472f2d0c157c08c510"><code>ad24aa5</code></a>
add test for keyword arguments in
ActiveSupport::CurrentAttributes.method_mis...</li>
<li><a
href="https://github.com/rails/rails/commit/11e0b892d3c88ffe7f9b6bae7bd6f2ae9ce06966"><code>11e0b89</code></a>
fix ActiveSupport::CurrentAttributes.method_missing for Ruby 3</li>
<li><a
href="https://github.com/rails/rails/commit/f05ac78bfc9d172abaa86a9da139c7933e4e79c5"><code>f05ac78</code></a>
Merge branch '6-1-sec' into 6-1-stable</li>
<li><a
href="https://github.com/rails/rails/commit/dc1242fd5a4d91e63846ab552a07e19ebf8716ac"><code>dc1242f</code></a>
Preparing for 6.1.6.1 release</li>
<li><a
href="https://github.com/rails/rails/commit/0bce40f3dd5aa1fb5bb8611e3ad8179222f80e40"><code>0bce40f</code></a>
updating version and changelog</li>
<li><a
href="https://github.com/rails/rails/commit/d42b549de66988eecfca36e5581885e82d1b6d87"><code>d42b549</code></a>
Preparing for 6.1.6 release</li>
<li><a
href="https://github.com/rails/rails/commit/147557dc16a5bd8bab96f999f359a570232e1873"><code>147557d</code></a>
Preparing for 6.1.6 release</li>
<li>Additional commits viewable in <a
href="https://github.com/rails/rails/compare/v6.1.5...v6.1.7.1">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=activesupport&package-manager=bundler&previous-version=6.1.5&new-version=6.1.7.1)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
- `@dependabot use these labels` will set the current labels as the
default for future PRs for this repo and language
- `@dependabot use these reviewers` will set the current reviewers as
the default for future PRs for this repo and language
- `@dependabot use these assignees` will set the current assignees as
the default for future PRs for this repo and language
- `@dependabot use this milestone` will set the current milestone as the
default for future PRs for this repo and language

You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/software-mansion/react-native-reanimated/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
<!-- Thanks for submitting a pull request! We appreciate you spending
the time to work on these changes. Please follow the template so that
the reviewers can easily understand what the code changes affect. -->

## Summary

This PR extends
software-mansion#3801 by
introducing layout animation types and modifiers that those animation
types require to be fully functional.

Currently, the tests fail with something like:
```
TypeError: Cannot read properties of undefined (reading 'delay')

 > 107 |   const transition = CurvedTransition.delay(10).duration(10),
       |                                       ^
```

## Test plan

Creating a test (e.g. using React Native Testing Library) of a component
containing any of the freshly added layout animation types and / or
chained modifiers they support. E.g.:
```tsx
const MyComponent = () => (
  <Animated.View layout={CurvedTransition.delay(10).duration(10)} />
)

test('test the test', () => {
  const screen = render(<MyComponent />)
})
```
The above example fails before the patch from this PR is introduced and
succeeds afterward.


## Question

One question to resolve is how closely the mocks should match the real
api in the context of which modifiers apply to witch animation types
(e.g. not all animation types support `.stiffness()`). Doing so would
require more complex mocks that are also harder to maintain for the need
to keeping them in sync. An alternative, simpler approach is to add all
the modifiers to all the animations - I figure it's okay since these
kinds of mocks are not directly consumed in the tests - they just serve
enabling test-rendering components utilising layout animations without
errors. The latter is the approach I went with, but lmk if you think the
other one is a better fit.
## Summary

This PR bumps react-native from 0.71.0 to 0.71.1 in Example and
FabricExample.

## Test plan

✅ Checked on Example and FabricExample on Android and iOS in debug mode.
## Summary

This PR simplifies code in `NativeProxy.cpp` by replacing `*runtime_`
and `runtime_->` with `rt` and `rt.`, respecively.

## Test plan

Check if Example works on Android.
## Summary

This PR applies code review suggestions from software-mansion#3438.

## Test plan

Build Example app and check if Article progress example works.
## Summary

This PR removes an outdated React Native version check when Fabric is
enabled in C++ code since there already exists such mechanism in Android
build scripts (see
[here](https://github.com/software-mansion/react-native-reanimated/blob/ef888c2cc941d5175b9ac007a237a00ea4c2593d/android/build.gradle#L595-L604)),
as well as adds an analogous check on iOS.

## Test plan

Check if FabricExample works on Android and iOS.
…oot view (software-mansion#3988)

<!-- Thanks for submitting a pull request! We appreciate you spending
the time to work on these changes. Please follow the template so that
the reviewers can easily understand what the code changes affect. -->

## Summary

Fixes software-mansion#3873
`getScrollableNode()` works not only on FlashLists, but also on RN
scrollable components (ScrollView, Flatlist). It's brought back from
[there](software-mansion@5829e95#diff-fdad18d3281131f92aa76c0969f84d27f2314251842763fedbc756df07b1eab7L234)


## Test plan

<!-- Provide a minimal but complete code snippet that can be used to
test out this change along with instructions how to run it and a
description of the expected behavior. -->
- tested on the repro from the issue
(https://github.com/diogoquintas/reanimated-scroll-issue)
- tested on several examples from the example app (examples related to
scroll events and events in general for example chat heads)
- tested on FlashList
tomekzaw and others added 24 commits June 5, 2023 18:56
## Summary

Currently, the header back button disappears on page reload. This PR
adds a back button that navigates to the home screen on each example
screen.

## Acknowledgements

Thanks @kacperkapusciak for showing me `headerLeft` prop and
`@react-navigation/elements` package.

## Test plan

1. Open WebExample
2. Open Bubbles example 
3. Reload the page
4. Verify that header back button is visible
<!-- Thanks for submitting a pull request! We appreciate you spending
the time to work on these changes. Please follow the template so that
the reviewers can easily understand what the code changes affect. -->

## Summary

Smol fix after software-mansion#4438

## Test plan

<!-- Provide a minimal but complete code snippet that can be used to
test out this change along with instructions how to run it and a
description of the expected behavior. -->
## Summary

This PR changes nightly version numbering from
`0.0.0-yyyymmdd-commithash` to
`<x>.<y+1>.<z>-nightly-yyyymmdd-commithash` to keep things analogous to
react-native (see
[here](https://www.npmjs.com/package/react-native?activeTab=versions))
as well as to fix failing Android builds due to conditionals in
build.gradle and RNReanimated.podspec which use major version for build
config.

## Test plan

1. Clone the repository
2. Run `node scripts/set-nightly-version.js`
3. Check if the version in `package.json` and `jsVersion.ts` starts with
`3.2.0-nightly-`
## Summary

This PR adds `runOnUI` to the list of automatically workletized
functions as suggested by @kacperkapusciak.

Previously, the following code:

```tsx
runOnUI(() => {
  console.log('Hello from the UI thread!');
})();
```

would throw the following error:

```
Error: runOnUI() can only be used on worklets, js engine: hermes
```

because the function passed to `runOnUI` needs to be marked as worklet:

```diff
 runOnUI(() => {
+  'worklet';
   console.log('Hello from the UI thread!');
 })();
```

After this change, the `'worklet';` directive can be omitted and the
function will be automatically workletized by the Reanimated Babel
plugin.

## Test plan

<details>
<summary>App.tsx</summary>

```tsx
import { Button, StyleSheet, View } from 'react-native';

import React from 'react';
import { runOnUI } from 'react-native-reanimated';

export default function App() {
  const handlePress = () => {
    runOnUI(() => {
      console.log('Hello from the UI thread!');
    })();
  };

  return (
    <View style={styles.container}>
      <Button title="Click me" onPress={handlePress} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});
```

</details>
## Summary

This draft PR moves off of `setNativeProps` in favor of editing DOM
nodes directly.

Closes software-mansion#4335, related to software-mansion#2756.

## Test plan

<details>
<summary>App.tsx</summary>

```tsx
import Animated, {
  useSharedValue,
  withTiming,
  useAnimatedStyle,
  cancelAnimation,
  withRepeat,
  interpolateColor,
} from 'react-native-reanimated';
import { View, StyleSheet } from 'react-native';
import React, { useEffect } from 'react';

export default function AnimatedStyleUpdateExample(): React.ReactElement {
  const randomWidth = useSharedValue(0);

  useEffect(() => {
    cancelAnimation(randomWidth);
    randomWidth.value = withRepeat(withTiming(1), -1, true);
  }, [randomWidth]);

  const style = useAnimatedStyle(() => {
    return {
      width: randomWidth.value * 100,
      height: randomWidth.value * 100,
      backgroundColor: interpolateColor(
        randomWidth.value,
        [0, 1],
        ['red', 'lime']
      ),
      transform: [{ rotate: `${randomWidth.value * 180}deg` }],
    };
  });

  return (
    <View style={styles.container}>
      <Animated.View style={style} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});
```

</details>


https://github.com/software-mansion/react-native-reanimated/assets/20516055/93b8096f-2a4d-4c61-848d-f483d612ac13
## Summary

In software-mansion#4270
withDecay rubberBandFactor got fixed on the Web with a fix where
velocity got multiplied by `1000` to overcome an issue present in RNGH.

This got addressed in
software-mansion/react-native-gesture-handler#2443
and released in Gesture Handler 2.10 thus making the fix unnecessary.

## Recordings

### Before with RNGH 2.10


https://github.com/software-mansion/react-native-reanimated/assets/39658211/3caf7961-3f0e-4a00-9889-18da33dbfd32

### After with RNGH 2.10


https://github.com/software-mansion/react-native-reanimated/assets/39658211/2ca02d9f-bfd6-4e13-83c2-aaa6312e8e6a


## Test plan

Run this snippet in WebExample

<details open>
<summary>Code example</summary>

```jsx
import React from 'react';
import {StyleSheet, View} from 'react-native';
import Animated, {
  useAnimatedStyle,
  useSharedValue,
  withDecay,
} from 'react-native-reanimated';
import {
  Gesture,
  GestureDetector,
  GestureHandlerRootView,
} from 'react-native-gesture-handler';

const SIZE = 120;

export default function App() {
  const offset = useSharedValue(0);
  const width = useSharedValue(0);

  const onLayout = event => {
    width.value = event.nativeEvent.layout.width;
  };

  const pan = Gesture.Pan()
    .onChange(event => {
      // highlight-next-line
      offset.value += event.changeX;
    })
    .onFinalize(event => {
      // highlight-start
      offset.value = withDecay({
        velocity: event.velocityX,
        rubberBandEffect: true,
        clamp: [-(width.value / 2) + SIZE / 2, width.value / 2 - SIZE / 2],
      });
      // highlight-end
    });

  const animatedStyles = useAnimatedStyle(() => ({
    transform: [{translateX: offset.value}],
  }));

  return (
    <GestureHandlerRootView style={styles.container}>
      <View onLayout={onLayout} style={styles.wrapper}>
        <GestureDetector gesture={pan}>
          <Animated.View style={[styles.box, animatedStyles]} />
        </GestureDetector>
      </View>
    </GestureHandlerRootView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    height: '100%',
  },
  wrapper: {
    flex: 1,
    width: '100%',
    alignItems: 'center',
    justifyContent: 'center',
  },
  box: {
    height: SIZE,
    width: SIZE,
    backgroundColor: '#b58df1',
    borderRadius: 20,
    cursor: 'grab',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

```

</details>
For better DX and consistency with the docs (current and the new ones)
I've decided to rename the first argument of `useScrollViewOffset`,
`measure`, `getRelativeCoords`, and `scrollTo` to `animatedRef`.

### Motivation

Just `ref` as an argument indicates that a plain `const ref =
React.useRef()` works with these functions leading to a confusing
developer experience.

Also, `aref` is a bit cryptic and a hard thing to look up on the
Internet when just starting to learn Reanimated.
## Prelude

We have waited for it a long time. 

Here it is.

A perfect summary of weeks time of our work and research - two line fix.

## Summary

Ever since we've adopted CommonJS as target for our built JavaScript
files we made it very difficult to our users to properly use Jest with
Reanimated. This is due to fact that Reanimated Babel plugin is prone to
break hoisting and this becomes critical in CommonJS. This issue had
never surfaced before because we were building only for ES modules which
can handle the way our plugin works. Therefore, after many talks we've
decided to drop support for CommonJS and revert to ES modules only.

Refer to software-mansion#4449 for _slightly_ more information.

This is likely to fix (I want to wait for confirmation):
- software-mansion#4347,
- software-mansion#4197,
- software-mansion#4185,
- software-mansion#4175,
- software-mansion#4136,
- software-mansion#4001,
- software-mansion#3971.

## Test plan

- I tested it on the [original
repro](https://github.com/kylebake/ReanimatedTestBug) that began this
voyage. I recommend using [my
fork](https://github.com/tjzel/Reanimated-jest-commonjs-issue) since
that repro had some errors coming from used versions of React-Native and
Jest.
__Make sure you use Node 18.15 for it.__
- I also tested it on my university
[app](https://github.com/MeowdoptMe/MeowdoptMeApp) that actively uses
Jest and Reanimated and using tarball from this PR fixed Jest issues.
## Summary

Smol fix after software-mansion#4352 because `react-native-web` may not be installed.

## Test plan

<!-- Provide a minimal but complete code snippet that can be used to
test out this change along with instructions how to run it and a
description of the expected behavior. -->
<!-- Thanks for submitting a pull request! We appreciate you spending
the time to work on these changes. Please follow the template so that
the reviewers can easily understand what the code changes affect. -->

## Summary

Values returned by the `prepare` function inside `useAnimatedReaction`
are assigned to the `previous` shared value. Even though it is only read
from the UI thread, those values are cloned so that they can be read
from the JS thread. This process turns out to be a tad problematic when
dealing with large objects, as it can take a significant amount of time.

This PR sets the `oneWayReadsOnly` flag when creating `previous` to
true, disabling the cloning process and reducing the performance impact
of the hook.

## Test plan

<details>
<summary>
Here's a simple reproduction for this problem
</summary>

```jsx
import React from 'react';
import {SafeAreaView} from 'react-native';
import {
  Gesture,
  GestureDetector,
  GestureHandlerRootView,
} from 'react-native-gesture-handler';
import Animated, {
  useAnimatedReaction,
  useAnimatedStyle,
  useSharedValue,
} from 'react-native-reanimated';

const largeArray = new Array(1000).fill(0).map((_, i) => i);

function Bar(props: any) {
  const backgroundColor = useSharedValue('#ff0000ff');

  useAnimatedReaction(
    () => {
      return [props.isScrolling.value, largeArray];
    },
    ([isScrolling]) => {
      if (isScrolling) {
        backgroundColor.value = '#00ff00ff';
      } else {
        backgroundColor.value = '#ff0000ff';
      }
    },
  );

  const style = useAnimatedStyle(() => {
    return {
      transform: [
        {translateX: props.scrollX.value},
        {translateY: props.scrollY.value},
      ],
      backgroundColor: backgroundColor.value,
    };
  });

  return (
    <Animated.View
      style={[
        {width: 300, height: 50, backgroundColor: 'red', marginTop: 8},
        style,
      ]}
    />
  );
}

const items = new Array(50).fill(0).map((_, i) => i);

export default function App() {
  const scrollX = useSharedValue(0);
  const scrollY = useSharedValue(0);
  const isScrolling = useSharedValue(false);

  const pan = Gesture.Pan()
    .onStart(() => {
      isScrolling.value = true;
    })
    .onEnd(() => {
      isScrolling.value = false;
    })
    .onChange(e => {
      scrollX.value += e.changeX;
      scrollY.value += e.changeY;
    })
    .runOnJS(true);

  return (
    <SafeAreaView style={{flex: 1}}>
      <GestureHandlerRootView style={{flex: 1}}>
        <GestureDetector gesture={pan}>
          <Animated.View style={{flex: 1}}>
            {items.map(item => (
              <Bar
                key={item}
                scrollX={scrollX}
                scrollY={scrollY}
                isScrolling={isScrolling}
              />
            ))}
          </Animated.View>
        </GestureDetector>
      </GestureHandlerRootView>
    </SafeAreaView>
  );
}

```
</details>
## Summary

PR fixed problem with `Cannot read property 'apply' of undefined` during
usage of Chrome Debugger on Android

Fixes
software-mansion#3951
## Summary

This PR fixes bundling error which appeared after software-mansion#4468.

```
error: Error: Unable to resolve module path from /Users/tomekzaw/RNOS/Jest/react-native-reanimated/node_modules/jest-message-util/build/index.js: path could not be found within the project or in these directories:
  ../node_modules
```

```
../node_modules/jest-util/build/requireOrImportModule.js:Invalid call at line 55: import(moduleUrl.href)
```

## Test plan

<!-- Provide a minimal but complete code snippet that can be used to
test out this change along with instructions how to run it and a
description of the expected behavior. -->
<!-- Thanks for submitting a pull request! We appreciate you spending
the time to work on these changes. Please follow the template so that
the reviewers can easily understand what the code changes affect. -->

## Summary

<!-- Explain the motivation for this PR. Include "Fixes #<number>" if
applicable. -->

Fixes software-mansion#3769

Each time `componentDidUpdate` is triggered we have to subscribe for
events again. However we used to use the same viewTag, although the
viewTag may change each time the view is updated. This mean that the
given view will stop receiving any events.

Look at the above-linked issue to see the description of bug in the
recordings. In the console you can see viewTag used to subscribe for
events. In a buggy example it doesn't change when you modify the
orientation of the scroll.
<table>
<tr><td>BEFORE</td><td>


https://github.com/software-mansion/react-native-reanimated/assets/56199675/e8db724a-620f-4da1-ac44-bdc73e4d936b

</td></tr>
<tr><td>AFTER</td><td>


https://github.com/software-mansion/react-native-reanimated/assets/56199675/b2a8d2c1-0476-4ddf-b543-b7c0b768389e


</td></tr>
</table>  

## Test plan

<!-- Provide a minimal but complete code snippet that can be used to
test out this change along with instructions how to run it and a
description of the expected behavior. -->
Tested on example from the issue: https://snack.expo.dev/fTGYvJ2t5

Co-authored-by: Aleksandra Cynk <aleksandracynk@swmansion.com>
<!-- Thanks for submitting a pull request! We appreciate you spending
the time to work on these changes. Please follow the template so that
the reviewers can easily understand what the code changes affect. -->

## Summary

- Fixes software-mansion#4256

### Problem

If the scrollable component is not root, UI `scrollTo` doesn't work on
Fabric.

software-mansion#4384 - It was fixed here for Paper, but after this change app crashes
on Fabric, because `getScrollableNode` in both architectures returns
viewTag as a number, not component. It's working for Paper, because we
are passing either component or number to `findNodeHandle` method, but
on Fabric we need component ref.

### Fix
 
Instead of `getScrollableNode`, we can use `getNativeScrollRef` and get
scrollable reference.


### TODO

Unfortunately this method is not implemented yet for `Flash-list` ->
https://shopify.github.io/flash-list/docs/usage#:~:text=Unsupported%20methods%3A
so for now, UI `scrollTo` on FlashList works only for Paper
Architecture.

## Test plan

ScrollToExample:

- Paper, ScrollView
- Paper, FlatList
- Fabric, ScrollView
- Fabric, FlatList

---------

Co-authored-by: Tomek Zawadzki <tomasz.zawadzki@swmansion.com>
…e-mansion#4475)

## Summary

This PR improves the developer experience when playing around with
Reanimated's internals takes a very bad turn.

Currently, while cloning shareables, we check for cycles by storing the
cloned object at some depth:

https://github.com/software-mansion/react-native-reanimated/blob/4ebd011650e932af12150ed37c27c1cb66d00fd9/src/reanimated2/shareables.ts#L103
Sometimes (not exactly sure when) we clear this variable so we don't
hold it forever:

https://github.com/software-mansion/react-native-reanimated/blob/4ebd011650e932af12150ed37c27c1cb66d00fd9/src/reanimated2/shareables.ts#L110
However, it may happen that while we're deep down in the tree, the
function will be called with `depth = 0` which resets the store and thus
breaks our cyclic object detection mechanism, resulting in a well-known
"Maximum call stack exceeded" error, like here:


![](https://github.com/software-mansion/react-native-reanimated/assets/20516055/6558d757-6fd1-4da5-8db2-3048fbca76f8)

Here's the place where we call `makeShareableClone` recursively without
passing `depth`:


https://github.com/software-mansion/react-native-reanimated/blob/4ebd011650e932af12150ed37c27c1cb66d00fd9/src/reanimated2/shareables.ts#L157-L160

This PR adds the missing argument.

| Before | After |
|:-:|:-:|
| <img width="503" alt="Zrzut ekranu 2023-05-18 o 17 55 30"
src="https://github.com/software-mansion/react-native-reanimated/assets/20516055/bc54b12d-a6cb-4ae3-ad00-18242d85f2c7">
| <img width="503" alt="Zrzut ekranu 2023-05-18 o 17 55 37"
src="https://github.com/software-mansion/react-native-reanimated/assets/20516055/033646e9-6370-49a3-89b1-17adb7833c17">
|

## Test plan

1. Add `'worklet';` directive in `runOnUI` function in `threads.ts`
2. Comment out `makeShareableCloneRecursive(worklet);` inside `runOnUI`
function body
3. Call the following code:
```ts
runOnUI(() => {
  'worklet';
  console.log(_WORKLET, 'Hello from the UI thread!');
  runOnUI;
})();
```
<!-- Thanks for submitting a pull request! We appreciate you spending
the time to work on these changes. Please follow the template so that
the reviewers can easily understand what the code changes affect. -->

## Summary

Bumped version to 0.72.0-rc.3

## Test plan

- Example
- Fabric Example

---------

Co-authored-by: Tomek Zawadzki <tomasz.zawadzki@swmansion.com>
Co-authored-by: Tomek Zawadzki <tomekzawadzki98@gmail.com>
## Summary

We have decided to introduce two new config props - damping ratio and
duration to make usage of `withSpring` easier.

```mermaid
  graph LR;
      A[Use<br>withSpring<br>animation] --> B;
      B{Did user provide<br>config with duration or<br>dampingRatio?} --YES-->C[Calculate spring movement using default or provided<br>mass and damping. Defaults:<br>damping 10, mass 1];
      B--NO-->D[Calculate spring movement using default or provided<br>duration and damping ratio. Defaults:<br>duration: 2, dampingRatio: 0.5];
```

### Implementation
When starting an animation with predefined duration we have to find a
mass that would give us the expected duration. Thus we have to solve a
simple numeric equation. We do it with bisection, since Newton method
appears to be much slower in this case (it happens, when finding roots
of functions that grow really fast 📈)

<details><summary>Testing that Newton's method is much slower</summary>


https://user-images.githubusercontent.com/56199675/233330812-5eb31550-f77d-4b68-8765-5131ba18c2d1.mov
</details> 

## Recordings
In all the examples below duration is set to 5000ms

<table>
<tr><td>dampingRatio=1</td><td>dampingRatio=0.5</td></tr>
<tr><td>


https://user-images.githubusercontent.com/56199675/233336875-b2666629-f3e9-403e-b629-fd44efba0dea.mov</td><td>


https://user-images.githubusercontent.com/56199675/233337127-433077d3-2017-4fde-8c1e-647c0ab52600.mov

</td></tr>
<tr><td>dampingRatio=1000</td><td>dampingRatio=0.1</td></tr>
<tr><td>


https://user-images.githubusercontent.com/56199675/233337155-a8f07c34-d65e-4161-ba47-b8fc9992482a.mov

</td><td>


https://user-images.githubusercontent.com/56199675/233337200-67b1719e-5963-4e65-b187-551cf80966cf.mov

</td></tr>
</table>

## Test plan


Run demo

---------

Co-authored-by: Aleksandra Cynk <aleksandracynk@Aleksandras-MacBook-Pro.local>
Co-authored-by: Aleksandra Cynk <aleksandracynk@swmansion.com>
### Motivation

This PR adds a banner to the New Reanimated Docs on the existing docs.
This makes it easier for people to access and test the new site.
Additionaly it links to the discussion where people can leave feedback
regarding the new docs.

This PR removes the 2023 App.js Conf announcement bar. 

### Images 


![image](https://github.com/software-mansion/react-native-reanimated/assets/39658211/356b777c-1c51-4490-9a0e-6204d9965335)
<!-- Thanks for submitting a pull request! We appreciate you spending
the time to work on these changes. Please follow the template so that
the reviewers can easily understand what the code changes affect. -->

## Summary

<!-- Explain the motivation for this PR. Include "Fixes #<number>" if
applicable. -->
This slightly improves performance.

## Test plan

<!-- Provide a minimal but complete code snippet that can be used to
test out this change along with instructions how to run it and a
description of the expected behavior. -->
Tested that app still works

---------

Co-authored-by: Aleksandra Cynk <aleksandracynk@swmansion.com>
…n#4477)

## Summary

This PR adds a check that throws an error with a developer-friendly
message when trying to call `runOnUI` function from a worklet which is
already running on the UI runtime.

## Motivation

It's difficult to decide what's the expected behavior of `runOnUI` in
such case:
* If the function should be scheduled for the current animation frame,
use `queueMicrotask`.
* If the function should be scheduled for the next animation frame, use
`requestAnimationFrame`.
* If the function should be executed immediately, simply call it
synchronously.

Note that neither `setTimeout` nor `setInterval` are implemented on the
UI runtime. Also, `setImmediate` is not available as well as it's not a
part of the standard.

## Implementation

Currently, calling `runOnUI` on the UI thread throws an error "Tried to
synchronously call..." because `runOnUI` is not marked as a worklet.
Adding `'worklet';` directive causes "cannot add new property" error
because `_runOnUIQueue` gets frozen while cloning the worklet to the UI
runtime. This PR adds `_runOnUIQueue` to the whitelisted identifiers in
Reanimated Babel plugin so it doesn't get captured into the closure,
thus doesn't need to be cloned and frozen.

## Alternatives

We could replace all occurrences of `_runOnUIQueue` with
`global._runOnUIQueue` so that the queue isn't captured into worklet
closure and thus doesn't get frozen. Another option would be simply to
whitelist `runOnUI` function but it wouldn't work properly when aliased.
 
## Test plan

<details>
<summary>App.tsx</summary>

```tsx
import { Button, StyleSheet, View } from 'react-native';

import React from 'react';
import { runOnUI } from 'react-native-reanimated';

export default function App() {
  const handlePress = () => {
    runOnUI(() => {
      'worklet';
      console.log(_WORKLET, 'Hello from the UI thread!');
      runOnUI(() => {
        'worklet';
        console.log(_WORKLET, 'Hello from the UI thread again!');
      })();
    })();
  };

  return (
    <View style={styles.container}>
      <Button title="Click me" onPress={handlePress} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});
```

</details>

```ts
runOnUI(() => {
  'worklet';
  console.log(_WORKLET, 'Hello from the UI thread!');
  runOnUI(() => {
    'worklet';
    console.log(_WORKLET, 'Hello from the UI thread again!');
  })();
})();
```

Your beautiful eyes should see the following error:

<img width="503" alt="error"
src="https://github.com/software-mansion/react-native-reanimated/assets/20516055/2a158606-7957-432d-9336-ab9ea8323402">
## Summary

This PR fixes the following error which appeared after software-mansion#4477.

<img width="779" alt="error"
src="https://github.com/software-mansion/react-native-reanimated/assets/20516055/4d5f7a2f-1f59-43ac-bce2-7ae8ed6bccf0">

## Test plan

Check if WebExample works.
<!-- Thanks for submitting a pull request! We appreciate you spending
the time to work on these changes. Please follow the template so that
the reviewers can easily understand what the code changes affect. -->

## Summary

This PR moves logic from `useScrollViewOffset` hook to
`Animated.ScrollView` prop.

The API of `useScrollViewOffset` is a bit cumbersome, because we need to
pass the same `ref` to both `ScrollView` and hook.

Now we just need to pass variable with type `ScrollValue<number>` to
`Animated.ScrollView` and when Scroll View changes its position, our
value is updated

## Test plan

- Example app
<!-- Thanks for submitting a pull request! We appreciate you spending
the time to work on these changes. Please follow the template so that
the reviewers can easily understand what the code changes affect. -->

## Summary

<!-- Explain the motivation for this PR. Include "Fixes #<number>" if
applicable. -->

<table>
<tr><td>BEFORE</td><td>AFTER</td></tr>
<tr><td>



https://github.com/software-mansion/react-native-reanimated/assets/56199675/1ab3bab9-b6cc-4524-a9a4-dd5fc3d2583b



</td><td>


https://github.com/software-mansion/react-native-reanimated/assets/56199675/d838c02a-217f-4d87-b1fa-22cd733ca413

</td></tr>
</table>

## Test plan

<!-- Provide a minimal but complete code snippet that can be used to
test out this change along with instructions how to run it and a
description of the expected behavior. -->
Run "Chat Heads" example

Co-authored-by: Aleksandra Cynk <aleksandracynk@swmansion.com>
## Summary

Update of package.json and lock files.
@fluiddot fluiddot self-assigned this Jun 5, 2023
@fluiddot fluiddot force-pushed the trunk branch 2 times, most recently from c1e7a1b to 70fea4d Compare June 6, 2023 08:12
@fluiddot fluiddot closed this Jun 6, 2023
@fluiddot fluiddot deleted the upstream-3.2.0 branch June 6, 2023 10:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet