Commit Graph

296 Commits

Author SHA1 Message Date
acdlite dd401dc3e8 useFormState's permalink option changes form target (#27302)
When the `permalink` option is passed to `useFormState`, and the form is
submitted before it has hydrated, the permalink will be used as the
target of the form action, enabling MPA-style form submissions.

(Note that submitting a form without hydration is a feature of Server
Actions; it doesn't work with regular client actions.)

It does not have any effect after the form has hydrated.

DiffTrain build for [ddff504695](https://github.com/facebook/react/commit/ddff504695f33c19e8c0792bff82bd8f8b8f7c05)
2023-08-29 16:03:42 +00:00
hoxyq c4d091a1dc fix: devtools source field disappears after component remount (#27297)
## Summary

Fixes: https://github.com/facebook/react/issues/27296

On actions that cause a component to change its signature, and therefore
to remount, the `_debugSource` property of the fiber updates in delay
and causes the `devtools` source field to vanish.

This issue happens in
https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactFiberBeginWork.js

```js
function beginWork(
  current: Fiber | null,
  workInProgress: Fiber,
  renderLanes: Lanes,
): Fiber | null {
  if (__DEV__) {
    if (workInProgress._debugNeedsRemount && current !== null) {
      // This will restart the begin phase with a new fiber.
      return remountFiber(
        current,
        workInProgress,
        createFiberFromTypeAndProps(
          workInProgress.type,
          workInProgress.key,
          workInProgress.pendingProps,
          workInProgress._debugOwner || null,
          workInProgress.mode,
          workInProgress.lanes,
        ),
      );
    }
  }

  // ...
```

`remountFiber` uses the 3rd parameter as the new fiber
(`createFiberFromTypeAndProps(...)`), but this parameter doesn’t contain
a `_debugSource`.

## How did you test this change?

Tested by monkey patching
`./node_modules/react-dom/cjs/react-dom.development.js`:
<img width="1749" alt="image"
src="https://github.com/facebook/react/assets/75563024/ccaf7fab-4cc9-4c05-a48b-64db6f55dc23">

https://github.com/facebook/react/assets/75563024/0650ae5c-b277-44d1-acbb-a08d98bd38e0

DiffTrain build for [eaa696876e](https://github.com/facebook/react/commit/eaa696876ee40bb048727aefe995be1bbb7384a8)
2023-08-29 15:47:57 +00:00
acdlite eeb35792f2 Client implementation of useFormState (#27278)
This implements useFormState in Fiber. (It does not include any
progressive enhancement features; those will be added later.)

useFormState is a hook for tracking state produced by async actions. It
has a signature similar to useReducer, but instead of a reducer, it
accepts an async action function.

```js
async function action(prevState, payload) {
  // ..
}
const [state, dispatch] = useFormState(action, initialState)
```

Calling dispatch runs the async action and updates the state to the
returned value.

Async actions run before React's render cycle, so unlike reducers, they
can contain arbitrary side effects.

DiffTrain build for [456d153bb5](https://github.com/facebook/react/commit/456d153bb582798effa76c09bec2405ab2e392cf)
2023-08-28 15:10:46 +00:00
acdlite a7a6a73c44 Fix mount-or-update check in rerenderOptimistic (#27277)
I noticed this was wrong because it should call updateWorkInProgressHook
before it checks if currentHook is null.

DiffTrain build for [9a01c8b54e](https://github.com/facebook/react/commit/9a01c8b54e91c588391070c65701342e4e361ea7)
2023-08-28 15:09:55 +00:00
acdlite b1f8e0d638 Selective Hydration: Don't suspend if showing fallback (#27230)
A transition that flows into a dehydrated boundary should not suspend if
the boundary is showing a fallback.

This is related to another issue where Fizz streams in the initial HTML
after a client navigation has already happened. That issue is not fixed
by this commit, but it does make it less likely. Need to think more
about the larger issue.

DiffTrain build for [ab31a9ed28](https://github.com/facebook/react/commit/ab31a9ed28d340172440e4b12e27d2af689249b3)
2023-08-25 00:09:28 +00:00
acdlite 2bd9065dd7 Scaffolding for useFormState (#27270)
This exposes, but does not yet implement, a new experimental API called
useFormState. It's gated behind the enableAsyncActions flag.

useFormState has a similar signature to useReducer, except instead of a
reducer it accepts an (async) action function. React will wait until the
promise resolves before updating the state:

```js
async function action(prevState, payload) {
  // ..
}
const [state, dispatch] = useFormState(action, initialState)
```

When used in combination with Server Actions, it will also support
progressive enhancement — a form that is submitted before it has
hydrated will have its state transferred to the next page. However, like
the other action-related hooks, it works with fully client-driven
actions, too.

DiffTrain build for [b4cdd3e892](https://github.com/facebook/react/commit/b4cdd3e8922713f8c9817b004a0dc51be47bc5df)
2023-08-23 15:05:09 +00:00
acdlite c1e19bbad3 Fix: Stylesheet in error UI suspends indefinitely (#27265)
This fixes the regression test added in the previous commit. The
"Suspensey commit" implementation relies on the
`shouldRemainOnPreviousScreen` function to determine whether to 1)
suspend the commit 2) activate a parent fallback and schedule a retry.
The issue was that we were sometimes attempting option 2 even when there
was no parent fallback.

Part of the reason this bug landed is due to how `throwException` is
structured. In the case of Suspensey commits, we pass a special "noop"
thenable to `throwException` as a way to trigger the Suspense path. This
special thenable must never have a listener attached to it. This is not
a great way to structure the logic, it's just a consequence of how the
code evolved over time. We should refactor it into multiple functions so
we can trigger a fallback directly without having to check the type. In
the meantime, I added an internal warning to help detect similar
mistakes in the future.

DiffTrain build for [dd480ef923](https://github.com/facebook/react/commit/dd480ef923930c8906a02664b01bcdea50707b5d)
2023-08-22 15:27:25 +00:00
gnoff 0fe197bb3e [Float][Flight][Fizz][Fiber] Implement preloadModule and preinitModule (#27220)
Stacked on #27224

### Implements `ReactDOM.preloadModule()`
`preloadModule` is a function to preload modules of various types.
Similar to `preload` this is useful when you expect to use a Resource
soon but can't render that resource directly. At the moment the only
sensible module to preload is script modules along with some other `as`
variants such as `as="serviceworker"`. In the future when there is some
notion of how to preload style module script or json module scripts this
API will be extended to support those as well.

##### Arguments
1. `href: string` -> the href or src value you want to preload.
2. `options?: {...}` ->
2.1. `options.as?: string` -> the `as` property the modulepreload link
should render with. If not provided it will be omitted which will cause
the modulepreload to be treated like a script module
2.2. `options.crossOrigin?: string` -> modules always load with CORS but
you can provide `use-credentials` if you want to change the default
behavior
2.3. `options.integrity?: string` -> an integrity hash for subresource
integrity APIs

##### Rendering
each preloaded module will emit a `<link rel="modulepreload" href="..."
/>`
if `as` is specified and is something other than `"script"` the as
attribute will also be included
if crossOrigin or integrity as specified their attributes will also be
included

During SSR these script tags will be emitted before content. If we have
not yet flushed the document head they will be emitted there after
things that block paint such as font preloads, img preloads, and
stylesheets.

On the client these link tags will be appended to the document.head.

### Implements `ReactDOM.preinitModule()`
`preinitModule` is a function to loading module scripts before they are
required. It has the same use cases as `preinit`.

During SSR you would use this to tell the browsers to start fetching
code that will be used without having to wait for bootstrapping to
initiate module fetches.

ON the client you would use this to start fetching a module script early
for an anticipated navigation or other event that is likely to depend on
this module script.

the `as` property for Float methods drew inspiration from the `as`
attribute of the `<link rel="preload" ... >` tag but it is used as a
sort of tag for the kind of thing being targetted by Float methods. For
`preinitModule` we currently only support `as: "script"` and this is
also the assumed default type so you current never need to specify this
`as` value. In the future `preinitModule` will support additional module
script types such as `style` or `json`. The support of these types will
correspond to [Module Import
Attributes](https://github.com/tc39/proposal-import-attributes).

##### Arguments
1. `href: string` -> the href or src value you want to preinitialize
2. `options?: {...}` ->
2.1 `options.as?: string` -> only supports `script` and this is the
default behavior. Until we support import attributes such as `json` and
`style` there will not be much reason to provide an `as` option.
2.2. `options.crossOrigin?: string`: modules always load with CORS but
you can provide `use-credentials` if you want to change the default
behavior
2.3 `options.integrity?: string` -> an integrity hash for subresource
integrity APIs

##### Rendering
each preinitialized `script` module will emit a `<script type="module"
async="" src"...">` During SSR these will appear behind display blocking
resources such as font preloads, img preloads, and stylesheets. In the
browser these will be appende to the head.

Note that for other `as` types the rendered output will be slightly
different. `<script type="module">import "..." with {type: "json"
}</script>`. Since this tag is an inline script variants of React that
do not use inline scripts will simply omit these preinitialization tags
from the SSR output. This is not implemented in this PR but will appear
in a future update.

DiffTrain build for [e505316920](https://github.com/facebook/react/commit/e50531692010bbda2a4627b07c7c810c3770a52a)
2023-08-17 17:35:00 +00:00
sebmarkbage 5cc1661577 Add Postpone API (#27238)
This adds an experimental `unstable_postpone(reason)` API.

Currently we don't have a way to model effectively an Infinite Promise.
I.e. something that suspends but never resolves. The reason this is
useful is because you might have something else that unblocks it later.
E.g. by updating in place later, or by client rendering.

On the client this works to model as an Infinite Promise (in fact,
that's what this implementation does). However, in Fizz and Flight that
doesn't work because the stream needs to end at some point. We don't
have any way of knowing that we're suspended on infinite promises. It's
not enough to tag the promises because you could await those and thus
creating new promises. The only way we really have to signal this
through a series of indirections like async functions, is by throwing.
It's not 100% safe because these values can be caught but it's the best
we can do.

Effectively `postpone(reason)` behaves like a built-in [Catch
Boundary](https://github.com/facebook/react/pull/26854). It's like
`raise(Postpone, reason)` except it's built-in so it needs to be able to
be encoded and caught by Suspense boundaries.

In Flight and Fizz these behave pretty much the same as errors. Flight
just forwards it to retrigger on the client. In Fizz they just trigger
client rendering which itself might just postpone again or fill in the
value. The difference is how they get logged.

In Flight and Fizz they log to `onPostpone(reason)` instead of
`onError(error)`. This log is meant to help find deopts on the server
like finding places where you fall back to client rendering. The reason
that you pass in is for that purpose to help the reason for any deopts.

I do track the stack trace in DEV but I don't currently expose it to
`onPostpone`. This seems like a limitation. It might be better to expose
the Postpone object which is an Error object but that's more of an
implementation detail. I could also pass it as a second argument.

On the client after hydration they don't get passed to
`onRecoverableError`. There's no global `onPostpone` API to capture
postponed things on the client just like there's no `onError`. At that
point it's just assumed to be intentional. It doesn't have any `digest`
or reason passed to the client since it's not logged.

There are some hacky solutions that currently just tries to reuse as
much of the existing code as possible but should be more properly
implemented.
- Fiber is currently just converting it to a fake Promise object so that
it behaves like an infinite Promise.
- Fizz is encoding the magic digest string `"POSTPONE"` in the HTML so
we know to ignore it but it should probably just be something neater
that doesn't share namespace with digests.

Next I plan on using this in the `/static` entry points for additional
features.

Why "postpone"? It's basically a synonym to "defer" but we plan on using
"defer" for other purposes and it's overloaded anyway.

DiffTrain build for [ac1a16c67e](https://github.com/facebook/react/commit/ac1a16c67e268fcb2c52e91717cbc918c7c24446)
2023-08-17 17:32:07 +00:00
gnoff d03f8fbb1b Float integrity bugfix (#27224)
Stacked on #27223

When a script resource adopts certain props from a preload for that
resource the integrity prop was incorrectly getting assinged to the
referrerPolicy prop instead. This is now fixed.

DiffTrain build for [0fb5b61ac6](https://github.com/facebook/react/commit/0fb5b61ac6951a492242618e4ace6c1826335efc)
2023-08-14 17:15:47 +00:00
acdlite e09bb3d726 Bugfix: Fix crash when suspending in shell during useSES re-render (#27199)
This adds a regression test for a bug where, after a store mutation, the
updated data causes the shell of the app to suspend.

When re-rendering due to a concurrent store mutation, we must check for
the RootDidNotComplete exit status again.

As a follow-up, I'm going to look into to cleaning up the places where
we check the exit status, so bugs like these are less likely. I think we
might be able to combine most of it into a single switch statement.

DiffTrain build for [201becd3d2](https://github.com/facebook/react/commit/201becd3d294b38824930a818e3412c6e04ba2eb)
2023-08-08 18:16:03 +00:00
noahlemen 1cb6c1f01b export dynamic disableSchedulerTimeoutInWorkLoop flag in www (#27117)
## Summary

This was not exposed as a dynamic flag in the build for facebook www. By
adding it, we'll be able to roll this out incrementally before cleaning
up this code altogether.

## How did you test this change?

`yarn build`

Before changes, `disableSchedulerTimeoutInWorkLoop` flag is not included
in ReactDOM-* build output for facebook www. Afterwards, it is included.

DiffTrain build for [9f4fbec5f7](https://github.com/facebook/react/commit/9f4fbec5f7bb639be6dac438f9da5f032ae12c15)
2023-07-17 19:49:57 +00:00
gnoff b7038da0f0 Add referrerPolicy option to ReactDOM.preload() (#27096)
DiffTrain build for [9377e10105](https://github.com/facebook/react/commit/9377e10105b41976c77c7f664f2363cb8c41ac8a)
2023-07-12 21:37:49 +00:00
acdlite d8c7f591c9 Detect and warn about native async function components in development (#27031)
Adds a development warning to complement the error introduced by
https://github.com/facebook/react/pull/27019.

We can detect and warn about async client components by checking the
prototype of the function. This won't work for environments where async
functions are transpiled, but for native async functions, it allows us
to log an earlier warning during development, including in cases that
don't trigger the infinite loop guard added in
https://github.com/facebook/react/pull/27019. It does not supersede the
infinite loop guard, though, because that mechanism also prevents the
app from crashing.

I also added a warning for calling a hook inside an async function. This
one fires even during a transition. We could add a corresponding warning
to Flight, since hooks are not allowed in async Server Components,
either. (Though in both environments, this is better handled by a lint
rule.)

DiffTrain build for [5c8dabf886](https://github.com/facebook/react/commit/5c8dabf8864e1d826c831d6096b2dfa66309961a)
2023-07-02 02:49:24 +00:00
kassens 023fffcfff Revert "Fix: Detect infinite update loops caused by render phase updates (#26625)" (#27027)
This reverts commit 822386f252.

This broke a number of tests when synced internally. We'll need to
investigate the breakages before relanding this.

DiffTrain build for [7f362de158](https://github.com/facebook/react/commit/7f362de1588d98438787d652941533e21f2f332d)
2023-06-30 16:57:00 +00:00
acdlite 569cd7f8a4 Detect crashes caused by Async Client Components (#27019)
Suspending with an uncached promise is not yet supported. We only
support suspending on promises that are cached between render attempts.
(We do plan to partially support this in the future, at least in certain
constrained cases, like during a route transition.)

This includes the case where a component returns an uncached promise,
which is effectively what happens if a Client Component is authored
using async/await syntax.

This is an easy mistake to make in a Server Components app, because
async/await _is_ available in Server Components.

In the current behavior, this can sometimes cause the app to crash with
an infinite loop, because React will repeatedly keep trying to render
the component, which will result in a fresh promise, which will result
in a new render attempt, and so on. We have some strategies we can use
to prevent this — during a concurrent render, we can suspend the work
loop until the promise resolves. If it's not a concurrent render, we can
show a Suspense fallback and try again at concurrent priority.

There's one case where neither of these strategies work, though: during
a sync render when there's no parent Suspense boundary. (We refer to
this as the "shell" of the app because it exists outside of any loading
UI.)

Since we don't have any great options for this scenario, we should at
least error gracefully instead of crashing the app.

So this commit adds a detection mechanism for render loops caused by
async client components. The way it works is, if an app suspends
repeatedly in the shell during a synchronous render, without committing
anything in between, we will count the number of attempts and eventually
trigger an error once the count exceeds a threshold.

In the future, we will consider ways to make this case a warning instead
of a hard error.

See https://github.com/facebook/react/issues/26801 for more details.

DiffTrain build for [fc801116c8](https://github.com/facebook/react/commit/fc801116c80b68f7ebdaf66ac77d5f2dcd9e50eb)
2023-06-29 20:10:43 +00:00
acdlite f2e8115259 Fix: Detect infinite update loops caused by render phase updates (#26625)
This PR contains a regression test and two separate fixes: a targeted
fix, and a more general one that's designed as a last-resort guard
against these types of bugs (both bugs in app code and bugs in React).

I confirmed that each of these fixes separately are sufficient to fix
the regression test I added.

We can't realistically detect all infinite update loop scenarios because
they could be async; even a single microtask can foil our attempts to
detect a cycle. But this improves our strategy for detecting the most
common kind.

See commit messages for more details.

DiffTrain build for [822386f252](https://github.com/facebook/react/commit/822386f252fd1f0e949efa904a1ed790133329f7)
2023-06-27 17:32:08 +00:00
noahlemen c7d703ebb8 Remove useMutableSource (#27011)
## Summary

This PR cleans up `useMutableSource`. This has been blocked by a
remaining dependency internally at Meta, but that has now been deleted.

<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->

## How did you test this change?

```
yarn flow
yarn lint
yarn test --prod
```

<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
  If you leave this empty, your PR will very likely be closed.
-->

DiffTrain build for [80d9a40114](https://github.com/facebook/react/commit/80d9a40114bb43c07d021e8254790852f450bd2b)
2023-06-27 16:50:41 +00:00
tyao1 b52e425597 Fix disableStrictPassiveEffect not working under Suspense (#26989)
In https://github.com/facebook/react/pull/26914 I added an extra logic
to turn off double useEffect if there is an `Offscreen`
tag. But `Suspense` uses `Offscreen` tag internally and that turns off
`disableStrictPassiveEffect` for everything.

DiffTrain build for [70e998a106](https://github.com/facebook/react/commit/70e998a1064cc1e8e8f9103e0c00d37fbbcf71c1)
2023-06-22 20:18:31 +00:00
tyao1 ec1a04575d Add a temporary internal option to disable double useEffect in legacy strict mode (#26914)
<!--
  Thanks for submitting a pull request!
We appreciate you spending the time to work on these changes. Please
provide enough information so that others can review your pull request.
The three fields below are mandatory.

Before submitting a pull request, please make sure the following is
done:

1. Fork [the repository](https://github.com/facebook/react) and create
your branch from `main`.
  2. Run `yarn` in the repository root.
3. If you've fixed a bug or added code that should be tested, add tests!
4. Ensure the test suite passes (`yarn test`). Tip: `yarn test --watch
TestName` is helpful in development.
5. Run `yarn test --prod` to test in the production environment. It
supports the same options as `yarn test`.
6. If you need a debugger, run `yarn test --debug --watch TestName`,
open `chrome://inspect`, and press "Inspect".
7. Format your code with
[prettier](https://github.com/prettier/prettier) (`yarn prettier`).
8. Make sure your code lints (`yarn lint`). Tip: `yarn linc` to only
check changed files.
  9. Run the [Flow](https://flowtype.org/) type checks (`yarn flow`).
  10. If you haven't already, complete the CLA.

Learn more about contributing:
https://reactjs.org/docs/how-to-contribute.html
-->

## Summary

<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->
We are upgrading React 17 codebase to React18, and `StrictMode` has been
great for surfacing potential production bugs on React18 for class
components. There are non-trivial number of test failures caused by
double `useEffect` in StrictMode. To prioritize surfacing and fixing
issues that will break in production now, we need a flag to turn off
double `useEffect` for now in StrictMode temporarily. This is a
Meta-only hack for rolling out `createRoot` and we will fast follow to
remove it and use full strict mode.

## How did you test this change?

<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
  If you leave this empty, your PR will very likely be closed.
-->
jest

DiffTrain build for [254cbdbd6d](https://github.com/facebook/react/commit/254cbdbd6d851a30bf3b649a6cb7c52786766fa4)
2023-06-21 18:20:59 +00:00
sebmarkbage 4a74dd599a Ensure updates are applied when diffInCommitPhase is on (#26977)
When we diffInCommitPhase there's no updatePayload, which caused no
update to be applied.

This is unfortunate because it would've been a lot easier to see this
oversight if we didn't have to support both flags.

I also carified that updateHostComponent is unnecessary in the new flag.
We reuse updateHostComponent for HostSingleton and HostHoistables since
it has a somewhat complex path but that means you have to remember when
editing updateHostComponent that it's not just used for that tag.
Luckily with the new flag, this is actually unnecessary since we just
need to mark it for update if any props have changed and then we diff it
later.

DiffTrain build for [d1c8cdae3b](https://github.com/facebook/react/commit/d1c8cdae3b20a670ee91b684e8e0ad0c400ae51c)
2023-06-20 01:29:40 +00:00
kassens 063f0e3001 [flow] upgrade to 0.209.0 (#26958)
Small update keeping us current with the latest version of Flow.

Flow changelog: https://github.com/facebook/flow/blob/main/Changelog.md

DiffTrain build for [613e6f5fca](https://github.com/facebook/react/commit/613e6f5fca3a7a63d115988d6312beb84d37b4db)
2023-06-16 14:02:53 +00:00
gnoff fc485c376b [Float][Fizz][Fiber] support imagesrcset and imagesizes for ReactDOM.preload() (#26940)
For float methods the href argument is usually all we need to uniquely
key the request. However when preloading responsive images it is
possible that you may need more than one preload for differing
imagesizes attributes. When using imagesrcset for preloads the href
attribute acts more like a fallback href. For keying purposes the
imagesrcset becomes the primary key conceptually.

This change updates the keying logic for `ReactDOM.preload()` when you
pass `{as: "image"}`

1. If `options.imageSrcSet` is a non-emtpy string the key is defined as
`options.imageSrcSet + options.imageSizes`. The `href` argument is still
required but does not participate in keying.
2. If `options.imageSrcSet` is empty, missing, or an invalid format the
key is defined as the `href`. Changing the `options.imageSizes` does not
affect the key as this option is inert when not using
`options.imageSrcSet`

Additionally, currently there is a bug in webkit (Safari) that causes
preload links to fail to use imageSrcSet and fallback to href even when
the browser will correctly resolve srcset on an `<img>` tag. Because the
drawbacks of preloading the wrong image (href over imagesrcset) in a
modern browser outweight the drawbacks of not preloading anything for
responsive images in browsers that do not support srcset at all we will
omit the `href` attribute whenever `options.imageSrcSet` is provided. We
still require you provide an href since we want to be able to revert
this behavior once all major browsers support it

bug link: https://bugs.webkit.org/show_bug.cgi?id=231150

DiffTrain build for [fc929cf4ea](https://github.com/facebook/react/commit/fc929cf4ead35f99c4e9612a95e8a0bb8f5df25d)
2023-06-15 21:56:16 +00:00
gnoff b437e4d88b [Float] Nonce preload support (#26939)
Some browsers, with some CSP configuration, will not preload a script if
the prelaod link tag does not provide a valid nonce attribute. This
change adds the ability to specify a nonce for `ReactDOM.preload(..., {
as: "script" })`

DiffTrain build for [86acc10f25](https://github.com/facebook/react/commit/86acc10f2596e1a6fe2fd57a5b325de85175800b)
2023-06-15 20:46:42 +00:00
gnoff 650431a15f [Fizz][Float] stop automatically preloading scripts that are not script resources (#26877)
Currently we preload all scripts that are not hoisted. One of the
original reasons for this is we stopped SSR rendering async scripts that
had an onLoad/onError because we needed to be able to distinguish
between Float scripts and non-Float scripts during hydration. Hydration
has been refactored a bit and we can not get around this limitation so
we can just emit the async script in place. However, sync and defer
scripts are also preloaded. While this is sometimes desirable it is not
universally so and there are issues with conveying priority properly
(see fetchpriority) so with this change we remove the automatic
preloading of non-Float scripts altogether.

For this change to make sense we also need to emit async scripts with
loading handlers during SSR. we previously only preloaded them during
SSR because it was necessary to keep async scripts as unambiguously
resources when hydrating. One ancillary benefit was that load handlers
would always fire b/c there was no chance the script would run before
hydration. With this change we go back to having the ability to have
load handlers fired before hydration. This is already a problem with
images and we don't have a generalized solution for it however our
likely approach to this sort of thing where you need to wait for a
script to load is to use something akin to `importScripts()` rather than
rendering a script with onLoad.

DiffTrain build for [e1ad4aa361](https://github.com/facebook/react/commit/e1ad4aa3615333009d76f947ff05ddeff01039c6)
2023-06-01 20:39:44 +00:00
gnoff ee61e4af9e [Float] support fetchpriority on ReactDOM.preload() and ReactDOM.preinit() (#26880)
exposes fetchPriority as an option for `ReactDOM.preload()` and
`ReactDOM.preinit()`

the typings should be `'high' | 'low' | 'auto'`

DiffTrain build for [042d8f606c](https://github.com/facebook/react/commit/042d8f606ce643d2eca955badbf07ea5b8ac266c)
2023-06-01 20:17:46 +00:00
tyao1 d6f9de5ae1 Always trigger componentWillUnmount in StrictMode (#26842)
<!--
  Thanks for submitting a pull request!
We appreciate you spending the time to work on these changes. Please
provide enough information so that others can review your pull request.
The three fields below are mandatory.

Before submitting a pull request, please make sure the following is
done:

1. Fork [the repository](https://github.com/facebook/react) and create
your branch from `main`.
  2. Run `yarn` in the repository root.
3. If you've fixed a bug or added code that should be tested, add tests!
4. Ensure the test suite passes (`yarn test`). Tip: `yarn test --watch
TestName` is helpful in development.
5. Run `yarn test --prod` to test in the production environment. It
supports the same options as `yarn test`.
6. If you need a debugger, run `yarn test --debug --watch TestName`,
open `chrome://inspect`, and press "Inspect".
7. Format your code with
[prettier](https://github.com/prettier/prettier) (`yarn prettier`).
8. Make sure your code lints (`yarn lint`). Tip: `yarn linc` to only
check changed files.
  9. Run the [Flow](https://flowtype.org/) type checks (`yarn flow`).
  10. If you haven't already, complete the CLA.

Learn more about contributing:
https://reactjs.org/docs/how-to-contribute.html
-->

## Summary

<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->
In StrictMode, React currently only triggers `componentWillUnmount` if
`componentDidMount` is defined. This would miss detecting issues like
initializing resources in constructor or componentWillMount, for
example:
```
class Component {
  constructor() {
     this._subscriptions = new Subscriptions();
  }
  componentWillUnmount() {
     this._subscriptions.reset();
  }
}
```

The PR makes `componentWillUnmount` always run in StrictMode.

## How did you test this change?

<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
  If you leave this empty, your PR will very likely be closed.
-->
`yarn test ci`

DiffTrain build for [811022232e](https://github.com/facebook/react/commit/811022232efed62a3c943701bc99d18655bc78b3)
2023-06-01 17:40:28 +00:00
rickhanlonii 9908c7d696 Clean up enableSyncDefaultUpdates flag a bit (#26858)
## Overview

Does a few things:
- Renames `enableSyncDefaultUpdates` to
`forceConcurrentByDefaultForTesting`
- Changes the way it's used so it's dead-code eliminated separate from
`allowConcurrentByDefault`
- Deletes a bunch of the gated code

The gates that are deleted are unnecessary now. We were keeping them
when we originally thought we would come back to being concurrent by
default. But we've shifted and now sync-by default is the desired
behavior long term, so there's no need to keep all these forked tests
around.

I'll follow up to delete more of the forked behavior if possible.
Ideally we wouldn't need this flag even if we're still using
`allowConcurrentByDefault`.

DiffTrain build for [018c58c9c6](https://github.com/facebook/react/commit/018c58c9c65452cff25aaf1f38f78a9b90d8e5c1)
2023-06-01 13:31:21 +00:00
gnoff 4d066bfea8 [Fiber][Float] preinitialized stylesheets should support integrity option (#26881)
preinitialized stylesheets did not render the integrity option on the
client implementation of Float. This was an oversight.

DiffTrain build for [e1e68b9f7f](https://github.com/facebook/react/commit/e1e68b9f7ffecf98e1b625cfe3ab95741be1417b)
2023-05-31 20:54:08 +00:00
gnoff 0b1cce0a5d [Fiber] retain scripts on clearContainer and clearSingleton (#26871)
clearContainer and clearSingleton both assumed scripts could be safely
removed from the DOM because normally once a script has been inserted
into the DOM it is executable and removing it, even synchronously, will
not prevent it from running. However There is an edge case in a couple
browsers (Chrome at least) where during HTML streaming if a script is
opened and not yet closed the script will be inserted into the document
but not yet executed. If the script is removed from the document before
the end tag is parsed then the script will not run. This change causes
clearContainer and clearSingleton to retain script elements. This is
generally thought to be safe because if we are calling these methods we
are no longer hydrating the container or the singleton and the scripts
execution will happen regardless.

DiffTrain build for [1cea384480](https://github.com/facebook/react/commit/1cea384480a6dea80128e5e0ddb714df7bea1520)
2023-05-30 20:18:47 +00:00
rickhanlonii abcb33d39c Update enableSyncDefaultUpdates for www (#26857)
If this is false, it dead code eliminates the path to use the root flag.
Will follow up to clean this up.

DiffTrain build for [0210f0b082](https://github.com/facebook/react/commit/0210f0b082c95f5aec08f356d796c512eab44fc4)
2023-05-26 01:38:07 +00:00
rickhanlonii d0559b8b8a Move enableSyncDefaultUpdates to test config (#26847)
DiffTrain build for [ee4233bdbc](https://github.com/facebook/react/commit/ee4233bdbc71a7e09395a613c7dde01194d2a830)
2023-05-24 22:30:55 +00:00
acdlite 2c5d055496 Lower Suspense throttling heuristic to 300ms (#26803)
Now that the throttling mechanism applies more often, we've decided to
lower this a tad to ensure it's not noticeable. The idea is it should be
just large enough to prevent jank when lots of different parts of the UI
load in rapid succession, but not large enough to make the UI feel
sluggish. There's no perfect number, it's just a heuristic.

DiffTrain build for [f8de255e94](https://github.com/facebook/react/commit/f8de255e94540f9018d8196b3a34da500707c39b)
2023-05-16 20:05:29 +00:00
acdlite 7b59f84660 Fix Suspense throttling mechanism (#26802)
The throttling mechanism for fallbacks should apply to both their
appearance _and_ disappearance.

This was mostly addressed by #26611. See that PR for additional context.

However, a flaw in the implementation is that we only update the the
timestamp used for throttling when the fallback initially appears. We
don't update it when the real content pops in. If lots of content in
separate Suspense trees loads around the same time, you can still get
jank.

The issue is fixed by updating the throttling timestamp whenever the
visibility of a fallback changes. Not just when it appears.

DiffTrain build for [4bfcd02b2c](https://github.com/facebook/react/commit/4bfcd02b2cebcb390f5aff0d7747c60a55012d5d)
2023-05-16 19:09:44 +00:00
sophiebits 646a30e8a1 Fix uSES hydration in strict mode (#26791)
Previously, we'd call and use getSnapshot on the second render resulting
in `Warning: Text content did not match. Server: "Nay!" Client: "Yay!"`
and then `Error: Text content does not match server-rendered HTML.`.

Fixes #26095. Closes #26113. Closes #25650.

---------

Co-authored-by: eps1lon <silbermann.sebastian@gmail.com>

DiffTrain build for [4cd7065665](https://github.com/facebook/react/commit/4cd7065665ea2cf33c306265c8d817904bb401ca)
2023-05-12 21:22:56 +00:00
kassens 3df08cb0ac Flow upgrade to 0.205.1 (#26796)
Just a small upgrade to keep us current and remove unused suppressions
(probably fixed by some upgrade since).

- `*` is no longer allowed and has been an alias for `any` for a while
now.

DiffTrain build for [fda1f0b902](https://github.com/facebook/react/commit/fda1f0b902b527089fe5ae7b3aa573c633166ec9)
2023-05-09 14:53:56 +00:00
acdlite 098e6fd1b6 useOptimisticState -> useOptimistic (#26772)
Drop the "state". Just "useOptimistic". It's cleaner.

This is still an experimental API. May not be the final name.

DiffTrain build for [b7972822b5](https://github.com/facebook/react/commit/b7972822b5887d05ae772ef757a453265b4b7aec)
2023-05-03 18:31:56 +00:00
sebmarkbage 6476ee0531 Allow forms to skip hydration of hidden inputs (#26735)
This allows us to emit extra ephemeral data that will only be used on
server rendered forms.

First I refactored the shouldSkip functions to now just do that work
inside the canHydrate methods. This makes the Config bindings a little
less surface area but it also helps us optimize a bit since we now can
look at the code together and find shared paths.

canHydrate returns the instance if it matches, that used to just be
there to refine the type but it can also be used to just return a
different instance later that we find. If we don't find one, we'll bail
out and error regardless so no need to skip past anything.

DiffTrain build for [67f4fb0213](https://github.com/facebook/react/commit/67f4fb02130b1fe1856289e3b66bb0b8cca57ff7)
2023-05-01 19:41:06 +00:00
acdlite 655915c681 Implement experimental_useOptimisticState (#26740)
This adds an experimental hook tentatively called useOptimisticState.
(The actual name needs some bikeshedding.)

The headline feature is that you can use it to implement optimistic
updates. If you set some optimistic state during a transition/action,
the state will be automatically reverted once the transition completes.

Another feature is that the optimistic updates will be continually
rebased on top of the latest state.

It's easiest to explain with examples; we'll publish documentation as
the API gets closer to stabilizing. See tests for now.

Technically the use cases for this hook are broader than just optimistic
updates; you could use it implement any sort of "pending" state, such as
the ones exposed by useTransition and useFormStatus. But we expect
people will most often reach for this hook to implement the optimistic
update pattern; simpler cases are covered by those other hooks.

DiffTrain build for [491aec5d61](https://github.com/facebook/react/commit/491aec5d6113ce5bae7c10966bc38a4a8fc091a8)
2023-05-01 17:24:18 +00:00
gnoff 59f00e19a3 Preinits should support a nonce option (#26744)
Currently there is no way to provide a nonce when using
`ReactDOM.preinit(..., { as: 'script' })`

This PR adds `nonce?: string` as an option

While implementing this PR I added a test to also show you can pass
`integrity`. This test isn't directly related to the nonce change.

DiffTrain build for [b12bea62d9](https://github.com/facebook/react/commit/b12bea62d9cfd9a925f28cb2c93daeda3865a64e)
2023-04-28 23:02:37 +00:00
josephsavona db78d9be34 Handle line endings correctly on Windows in build script for RN (#26727)
## Summary

We added some post-processing in the build for RN in #26616 that broke
for users on Windows due to how line endings were handled to the regular
expression to insert some directives in the docblock. This fixes that
problem, reported in #26697 as well.

## How did you test this change?

Verified files are still built correctly on Mac/Linux. Will ask for help
to test on Windows.

DiffTrain build for [f87e97a0a6](https://github.com/facebook/react/commit/f87e97a0a67fa7cfd7e6f2ec985621c0e825cb23)
2023-04-25 22:05:15 +00:00
kassens 6c615dc833 Squash of #26573, #26580, #26583, #26594, #26595, #26596, #26627
- Refactor some controlled component stuff (#26573)
- Don't update textarea defaultValue and input checked unnecessarily (#26580)
- Diff properties in the commit phase instead of generating an update payload (#26583)
- Move validation of text nesting into ReactDOMComponent  (#26594)
- Remove initOption special case (#26595)
- Use already extracted values instead of reading off props for controlled components (#26596)
- Fix input tracking bug (#26627)

DiffTrain build for [ded4a785b875d384f78efa28279550d86d93f54f](https://github.com/facebook/react/commit/ded4a785b875d384f78efa28279550d86d93f54f)
2023-04-21 18:37:22 +00:00
kassens dccdf22b11 Refactor some controlled component stuff (#26573)
This is mainly renaming some stuff. The behavior change is
hasOwnProperty to nullish check.

I had a bigger refactor that was a dead-end but might as well land this
part and see if I can pick it up later.

DiffTrain build for [e48e771805c44929e0beb6fa138822a20765a3aa](https://github.com/facebook/react/commit/e48e771805c44929e0beb6fa138822a20765a3aa)
2023-04-21 14:09:07 +00:00
kassens 6433b78fee Clean up discrete event replaying (#26558)
This reverts commit cc958d2b1b.

DiffTrain build for [7ecfd6dc036fd923e7bdfd090e0956b1eca4323a](https://github.com/facebook/react/commit/7ecfd6dc036fd923e7bdfd090e0956b1eca4323a)
2023-04-20 18:40:30 +00:00
kassens f504564195 Remove no-fallthrough lint suppressions (#26553)
This reverts commit 5f0684807e.

DiffTrain build for [6bb84216807f5386d8a83baf9ee464358a68c7bd](https://github.com/facebook/react/commit/6bb84216807f5386d8a83baf9ee464358a68c7bd)
2023-04-20 18:31:04 +00:00
kassens 3f62582404 Put common aliases in Map/Set instead of switch over strings (#26551)
This reverts commit cb3fb01cc3.

DiffTrain build for [1ef9912cc096fa471019a54eff4999b36856288c](https://github.com/facebook/react/commit/1ef9912cc096fa471019a54eff4999b36856288c)
2023-04-20 17:09:08 +00:00
kassens 702cd33bd7 Remove findInstanceBlockingEvent unused parameters (#26534)
This reverts commit 682e67edd4.

DiffTrain build for [90fa6be2509f68fa05897324e6adbab57de30c0f](https://github.com/facebook/react/commit/90fa6be2509f68fa05897324e6adbab57de30c0f)
2023-04-20 17:02:20 +00:00
kassens 008dc81da7 Refactor DOM Bindings Completely Off of DOMProperty Meta Programming (#26546)
This reverts commit f41ddb6645.

DiffTrain build for [f506c332bbece40ca884cdb1f81345732ab0d3d3](https://github.com/facebook/react/commit/f506c332bbece40ca884cdb1f81345732ab0d3d3)
2023-04-20 15:54:55 +00:00
kassens 1f49af93f1 Fix: Move destroy field to shared instance object (#26561)
This reverts commit d41e5c2c3c.

DiffTrain build for [1d3ffd9d9addb4aa0988b92ee6917c07c3c261ae](https://github.com/facebook/react/commit/1d3ffd9d9addb4aa0988b92ee6917c07c3c261ae)
2023-04-20 15:27:55 +00:00
kassens 38b20a32d3 Fix suspense replaying forward refs (#26535)
This reverts commit adac7b1e8d.

DiffTrain build for [2f18eb0ac63fdcaed3f1d4e3c375a559a552c09a](https://github.com/facebook/react/commit/2f18eb0ac63fdcaed3f1d4e3c375a559a552c09a)
2023-04-20 15:22:14 +00:00