Commit Graph

372 Commits

Author SHA1 Message Date
acdlite 76bf9a9ff3 Move all markRef calls into begin phase (#28375)
Certain fiber types may have a ref attached to them. The main ones are
HostComponent and ClassComponent. During the render phase, we check if a
ref was passed to it, and if so, we schedule a Ref effect: `markRef`.

Currently, we're not consistent about whether we call `markRef` in the
begin phase or the complete phase. For some fiber types, I found that
`markRef` was called in both phases, causing redundant work.

After some investigation, I don't believe it's necessary to call
`markRef` in both the begin phase and the complete phase, as long as you
don't bail out before calling `markRef`.

I though that maybe it had to do with the
`attemptEarlyBailoutIfNoScheduledUpdates` branch, which is a fast path
that skips the regular begin phase if no new props, state, or context
were passed. But if the props haven't changed (referentially — the
`memo` and `shouldComponentUpdate` checks happen later), then it follows
that the ref couldn't have changed either. This is true even in the old
`createElement` runtime where `ref` is stored on the element instead of
as a prop, because there's no way to pass a new ref to an element
without also passing new props. You might argue this is a leaky
assumption, but since we're shifting ref to be just a regular prop
anyway, I think it's the correct way to think about it going forward.

I think the pattern of calling `markRef` in the complete phase may have
been left over from an earlier iteration of the implementation before
the bailout logic was structured like it is today.

So, I removed all the `markRef` calls from the complete phase. In the
case of ScopeComponent, which had no corresponding call in the begin
phase, I added one.

We already had a test that asserted that a ref is reattached even if the
component bails out, but I added some new ones to be extra safe.

The reason I'm changing this this is because I'm working on a different
change to move the ref handling logic in `coerceRef` to happen in render
phase of the component that accepts the ref, instead of during the
parent's reconciliation.

DiffTrain build for [c820097716](https://github.com/facebook/react/commit/c820097716c3d9765bf85bf58202a4975d99e450)
2024-02-20 02:11:26 +00:00
sebmarkbage 43967e7833 Include the function name for context on invalid function child (#28362)
Also warn for symbols.

It's weird because for objects we throw a hard error but functions we do
a dev only check. Mainly because we have an object branch anyway.

In the object branch we have some built-ins that have bad errors like
forwardRef and memo but since they're going to become functions later, I
didn't bother updating those. Once they're functions those names will be
part of this.

DiffTrain build for [c1fd2a91b1](https://github.com/facebook/react/commit/c1fd2a91b1042c137d750be85e5998f699a54d2a)
2024-02-17 21:46:58 +00:00
jackpope 0db83ce329 Add useModernStrictMode as dynamic flag on www (#28346)
## Summary

Preparing modern strict mode rollout with dynamic feature flag

## How did you test this change?

![Screenshot 2024-02-15 at 10 09
49 AM](https://github.com/facebook/react/assets/8965173/9e90efc2-3578-4e63-ae2c-63d4a4e194b3)

DiffTrain build for [ef72271c2d](https://github.com/facebook/react/commit/ef72271c2d1234c9d1e1358f8083021089a50faa)
2024-02-16 20:22:50 +00:00
gnoff 651e755265 stash the component stack on the thrown value and reuse (#25790)
ErrorBoundaries are currently not fully composable. The reason is if you
decide your boundary cannot handle a particular error and rethrow it to
higher boundary the React runtime does not understand that this throw is
a forward and it recreates the component stack from the Boundary
position. This loses fidelity and is especially bad if the boundary is
limited it what it handles and high up in the component tree.

This implementation uses a WeakMap to store component stacks for values
that are objects. If an error is rethrown from an ErrorBoundary the
stack will be pulled from the map if it exists. This doesn't work for
thrown primitives but this is uncommon and stashing the stack on the
primitive also wouldn't work

DiffTrain build for [a9cc32511a](https://github.com/facebook/react/commit/a9cc32511a12c261ee719e5383818182800d6af4)
2024-02-16 04:48:29 +00:00
gaearon b19c9fedc2 Remove non-JSX propTypes checks (#28326)
Removes all `propTypes` validation called from outside the JSX
factories. Haven't touched JSX.

Tests that verify related behavior are stripped down to the
non-`propTypes` logic.

DiffTrain build for [fea900e454](https://github.com/facebook/react/commit/fea900e45447214ddd6ef69076ab7e38433b5ffd)
2024-02-16 00:40:11 +00:00
gaearon 3322b72f3d Remove propTypes checks for legacy context (#28324)
Part of https://github.com/facebook/react/pull/28207, this is easy to
land in isolation.

The approach I'm taking is slightly different — instead of leaving
validation on for legacy context, I disable the validation (it's
DEV-only) and leave just the parts that drive the runtime logic. I.e.
`contexTypes` and `childContextTypes` *values* are now ignored, the keys
are used just like before.

DiffTrain build for [64e755d737](https://github.com/facebook/react/commit/64e755d7374d753c75dc16ba1a4a09ce7b8689dd)
2024-02-14 16:27:15 +00:00
rickhanlonii 7b5320203d Land enableAsyncActions enableFormActions in www (#28315)
DiffTrain build for [5d445b50a6](https://github.com/facebook/react/commit/5d445b50a670d6cdc52943ca4e5ab3422792c57c)
2024-02-13 16:53:52 +00:00
rickhanlonii 1985f4f852 Switch <Context> to mean <Context.Provider> (#28226)
Previously, `<Context>` was equivalent to `<Context.Consumer>`. However,
since the introduction of Hooks, the `<Context.Consumer>` API is rarely
used. The goal here is to make the common case cleaner:

```js
const ThemeContext = createContext('light')

function App() {
  return (
    <ThemeContext value="dark">
      ...
    </ThemeContext>
  )
}

function Button() {
  const theme = use(ThemeContext)
  // ...
}
```

This is technically a breaking change, but we've been warning about
rendering `<Context>` directly for several years by now, so it's
unlikely much code in the wild depends on the old behavior. [Proof that
it warns today (check
console).](https://codesandbox.io/p/sandbox/peaceful-nobel-pdxtfl)

---

**The relevant commit is 5696782b428a5ace96e66c1857e13249b6c07958.** It
switches `createContext` implementation so that `Context.Provider ===
Context`.

The main assumption that changed is that a Provider's fiber type is now
the context itself (rather than an intermediate object). Whereas a
Consumer's fiber type is now always an intermediate object (rather than
it being sometimes the context itself and sometimes an intermediate
object).

My methodology was to start with the relevant symbols, work tags, and
types, and work my way backwards to all usages.

This might break tooling that depends on inspecting React's internal
fields. I've added DevTools support in the second commit. This didn't
need explicit versioning—the structure tells us enough.

DiffTrain build for [14fd9630ee](https://github.com/facebook/react/commit/14fd9630ee04387f4361da289393234e2b7d93b6)
2024-02-13 15:10:06 +00:00
sebmarkbage 56e29e3916 [Fiber] Transfer _debugInfo from Arrays, Lazy, Thenables and Elements to the inner Fibers. (#28286)
That way we can use it for debug information like component stacks and
DevTools. I used an extra stack argument in Child Fiber to track this as
it's flowing down since it's not just elements where we have this info
readily available but parent arrays and lazy can merge this into the
Fiber too. It's not great that this is a dev-only argument and I could
track it globally but seems more likely to make mistakes.

It is possible for the same debug info to appear for multiple child
fibers like when it's attached to a fragment or a lazy that resolves to
a fragment at the root. The object identity could be used in these
scenarios to infer if that's really one server component that's a parent
of all children or if each child has a server component with the same
name.

This is effectively a public API because you can use it to stash
information on Promises from a third-party service - not just Server
Components. I started outline the types for this for some things I was
planning to add but it's not final.

I was also planning on storing it from `use(thenable)` for when you
suspend on a Promise. However, I realized that there's no Hook instance
for those to stash it on. So it might need a separate data structure to
stash the previous pass over of `use()` that resets each render.

No tests yet since I didn't want to test internals but it'll be covered
once we have debugging features like component stacks.

DiffTrain build for [3f93ca1c8d](https://github.com/facebook/react/commit/3f93ca1c8dec1fd85df4dbb748a2df9438fc699f)
2024-02-12 20:01:52 +00:00
sebmarkbage 23457ab231 Suspend Thenable/Lazy if it's used in React.Children and unwrap (#28284)
This pains me because `React.Children` is really already
pseudo-deprecated.

`React.Children` takes any children that `React.Node` takes. We now
support Lazy and Thenable in this position elsewhere, but it errors in
`React.Children`.

This becomes an issue with async Server Components which can resolve
into a Lazy and in the future Lazy will just become Thenables. Which
causes this to error.

There are a few different semantics we could have:

1) Error like we already do (#28280). `React.Children` is about
introspecting children. It was always sketchy because you can't
introspect inside an abstraction anyway. With Server Components we fold
away the components so you can actually introspect inside of them kind
of but what they do is an implementation detail and you should be able
to turn it into a Client Component at any point. The type of an Element
passing the boundary actually reduces to `React.Node`.
2) Suspend and unwrap the Node (this PR). If we assume that Children is
called inside of render, then throwing a Promise if it's not already
loaded or unwrapping would treat it as if it wasn't there. Just like if
you rendered it in React. This lets you introspect what's inside which
isn't really something you should be able to do. This isn't compatible
with deprecating throwing-a-Promise and enable static compilation like
`use()` does. We'd have to deprecate `React.Children` before doing that
which we might anyway.
3) Wrap in a Fragment. If a Server Component was instead a Client
Component, you couldn't introspect through it anyway. Another
alternative might be to let it pass through but then it wouldn't be
given a flat key. We could also wrap it in a Fragment that is keyed.
That way you're always seeing an element. The issue with this solution
is that it wouldn't see the key of the Server Component since that gets
forwarded to the child that is yet to resolve. The nice thing about that
strategy is it doesn't depend on throw-a-Promise but it might not be
keyed correctly when things move.

DiffTrain build for [9e7944f67c](https://github.com/facebook/react/commit/9e7944f67c72b9a69a8db092ba6bd99fe9c731e2)
2024-02-12 18:44:25 +00:00
kassens e0e832eabb Add infinite update loop detection (#28279)
This is a partial redo of https://github.com/facebook/react/pull/26625.
Since that was unlanded due to some detected breakages. This now
includes a feature flag to be careful in rolling this out.

DiffTrain build for [d8c1fa6b0b](https://github.com/facebook/react/commit/d8c1fa6b0b8da0512cb5acab9cd4f242451392f3)
2024-02-09 16:19:24 +00:00
sebmarkbage 64de3b0154 Throw a better error when Lazy/Promise is used in React.Children (#28280)
We could in theory actually support this case by throwing a Promise when
it's used inside a render. Allowing it to be synchronously unwrapped.
However, it's a bit sketchy because we officially only support this in
the render's child position or in `use()`.

Another alternative could be to actually pass the Promise/Lazy to the
callback so that you can reason about it and just return it again or
even unwrapping with `use()` - at least for the forEach case maybe.

DiffTrain build for [e41ee9ea70](https://github.com/facebook/react/commit/e41ee9ea70f8998144fdd959ac11fd7a40e4ee20)
2024-02-08 22:14:59 +00:00
acdlite 3b33617b80 Delete more redundant JSX code (#28276)
Found another redundant implementation of JSX code. Not being used
anywhere so safe to delete.

DiffTrain build for [d3def47935](https://github.com/facebook/react/commit/d3def47935e8912c197f78c78c97c2476fa1a77a)
2024-02-08 16:08:53 +00:00
sebmarkbage 82dd48d0a1 Remove __self and __source location from elements (#28265)
Along with all the places using it like the `_debugSource` on Fiber.
This still lets them be passed into `createElement` (and JSX dev
runtime) since those can still be used in existing already compiled code
and we don't want that to start spreading to DOM attributes.

We used to have a DEV mode that compiles the source location of JSX into
the compiled output. This was nice because we could get the actual call
site of the JSX (instead of just somewhere in the component). It had a
bunch of issues though:

- It only works with JSX.
- The way this source location is compiled is different in all the
pipelines along the way. It relies on this transform being first and the
source location we want to extract but it doesn't get preserved along
source maps and don't have a way to be connected to the source hosted by
the source maps. Ideally it should just use the mechanism other source
maps use.
- Since it's expensive it only works in DEV so if it's used for
component stacks it would vary between dev and prod.
- It only captures the callsite of the JSX and not the stack between the
component and that callsite. In the happy case it's in the component but
not always.

Instead, we have another zero-cost trick to extract the call site of
each component lazily only if it's needed. This ensures that component
stacks are the same in DEV and PROD. At the cost of worse line number
information.

The better way to get the JSX call site would be to get it from `new
Error()` or `console.createTask()` inside the JSX runtime which can
capture the whole stack in a consistent way with other source mappings.
We might explore that in the future.

This removes source location info from React DevTools and React Native
Inspector. The "jump to source code" feature or inspection can be made
lazy instead by invoking the lazy component stack frame generation. That
way it can be made to work in prod too. The filtering based on file path
is a bit trickier.

When redesigned this UI should ideally also account for more than one
stack frame.

With this change the DEV only Babel transforms are effectively
deprecated since they're not necessary for anything.

DiffTrain build for [37d901e2b8](https://github.com/facebook/react/commit/37d901e2b81e12d40df7012c6f8681b8272d2555)
2024-02-07 21:42:46 +00:00
acdlite 126187e9cd jsx(): Treat __self and __source as normal props (#28257)
These used to be reserved props because the classic React.createElement
runtime passed this data as props, whereas the jsxDEV() runtime passes
them as separate arguments.

This brings us incrementally closer to being able to pass the props
object directly through to React instead of cloning a subset into a new
object.

The React.createElement runtime is unaffected.

DiffTrain build for [91caa96e42](https://github.com/facebook/react/commit/91caa96e4261704d42333f5e02ba32d870379fc4)
2024-02-07 01:07:46 +00:00
acdlite de5b760022 jsx(): Inline reserved prop checks (#28262)
The JSX runtime (both the new one and the classic createElement runtime)
check for reserved props like `key` and `ref` by doing a lookup in a
plain object map with `hasOwnProperty`.

There are only a few reserved props so this inlines the checks instead.

DiffTrain build for [1beb94133a](https://github.com/facebook/react/commit/1beb94133a93a433669a893aef02dd5afec07394)
2024-02-07 00:01:39 +00:00
acdlite aa5199bf97 Delete duplicate jsx() implementation (#28258)
Not sure how this happened but there are two identical implementations
of the jsx and jsxDEV functions. One of them was unreachable. I deleted
that one.

DiffTrain build for [6692445759](https://github.com/facebook/react/commit/66924457594bc28eb2f3f39c7c61d54b931c188e)
2024-02-06 20:09:46 +00:00
eps1lon a52f42714f Ensure useState and useReducer initializer functions are double invoked in StrictMode (#28248)
DiffTrain build for [97fd3e7064](https://github.com/facebook/react/commit/97fd3e7064b162f05b1bac3962ed10c6559c346c)
2024-02-06 16:57:47 +00:00
gsathya 47b1b75d09 Patch devtools before running useMemo function in strict mode (#28249)
This fixes a regression https://github.com/facebook/react/pull/25583
where we stopped patching before calling useMemo function.

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

DiffTrain build for [db120f69ec](https://github.com/facebook/react/commit/db120f69ec7a0b8c7f38ca7a1ddb1886de92e465)
2024-02-06 16:50:17 +00:00
gaearon c178d6f4b1 [Flight] Delete Server Context (#28225)
Server Context was never documented, and has been deprecated in
https://github.com/facebook/react/pull/27424.

This PR removes it completely, including the implementation code.

Notably, `useContext` is removed from the shared subset, so importing it
from a React Server environment would now should be a build error in
environments that are able to enforce that.

DiffTrain build for [472854820b](https://github.com/facebook/react/commit/472854820bfd0058dfc85524051171c7b7c998c1)
2024-02-05 22:44:00 +00:00
gnoff 55b1962e67 add RSC entrypoint for jsx-runtime (#28217)
Adds a new entrypoint for the production jsx-runtime when using
react-server condition. Currently the entrypoints are the same but in
the future we will potentially change the implementation of the runtime
in ways that can only be optimized for react-server constraints and we
want to have the entrypoint already separated so environments using it
will be pulling in the right version

DiffTrain build for [00f9acb12c](https://github.com/facebook/react/commit/00f9acb12c036ef24a2b6d7957d75359c6280087)
2024-02-02 21:43:43 +00:00
rickhanlonii 7bfb304cc6 Remove createRootStrictEffectsByDefault flag (#28102)
There's no need to separate strict mode from strict effects mode any
more.

I didn't clean up the `StrictEffectMode` fiber flag, because it's used
to prevent strict effects in legacy mode. I could replace those checks
with `LegacyMode` checks, but when we remove legacy mode, we can remove
that flag and condense them into one StrictMode flag away.

DiffTrain build for [3d1da1f9ab](https://github.com/facebook/react/commit/3d1da1f9ab7d54984c096e6a04c8729f3a50fd8a)
2024-02-01 19:59:11 +00:00
eps1lon 5f663581bc Restore old behavior for empty href props on anchor tags (#28124)
Treat `<a href="" />` the same with and without
`enableFilterEmptyStringAttributesDOM`

in https://github.com/facebook/react/pull/18513 we started to warn and
ignore for empty `href` and `src` props since it usually hinted at a
mistake. However, for anchor tags there's a valid use case since `<a
href=""></a>` will by spec render a link to the current page. It could
be used to reload the page without having to rely on browser
affordances.

The implementation for Fizz is in the spirit of
https://github.com/facebook/react/pull/21153. I gated the fork behind
the flag so that the fork is DCE'd when the flag is off.

DiffTrain build for [f3ce87ab65](https://github.com/facebook/react/commit/f3ce87ab650f07774e1df9bc3f8033e023973d10)
2024-01-30 23:48:54 +00:00
rickhanlonii 3cc608a8e7 Update www flags (#28150)
Adds an experiment for `enableFormActions` and hardcodes
`enableCustomElementPropertySupport` on www since this is shipped.

DiffTrain build for [417188314d](https://github.com/facebook/react/commit/417188314dd1d6df54efc8cd6a0c5d4830615888)
2024-01-30 19:29:43 +00:00
acdlite ec00d40eaa Always warn if client component suspends with an uncached promise (#28159)
Previously we only warned during a synchronous update, because we
eventually want to support async client components in controlled
scenarios, like during navigations. However, we're going to warn in all
cases for now until we figure out how that should work.

DiffTrain build for [178f435194](https://github.com/facebook/react/commit/178f4351947a842ff0b56700e9115b25ae8f20d0)
2024-01-30 19:28:23 +00:00
gnoff bc0fa9ecd7 [Fiber] Use a safer strategy to track the last precedence (#28110)
Uses a safer strategy to track the last precedence to avoid the need to
consistently remember to preprend `'p'` to the precedence value

DiffTrain build for [1c958aa4ab](https://github.com/facebook/react/commit/1c958aa4abf9e6b638489b1d73cdb1b6dc7c3ab6)
2024-01-30 18:15:00 +00:00
rickhanlonii 52a1078a24 Remove outdated enableSchedulerDebugging flag (#28101)
This flag was moved to the scheduler feature flags, so these flags don't
do anything.

DiffTrain build for [766eac46bb](https://github.com/facebook/react/commit/766eac46bb52bda28f87c11740214a4444ca881b)
2024-01-26 21:57:53 +00:00
acdlite c6f9c3abf5 Capture React.startTransition errors and pass to reportError (#28111)
To make React.startTransition more consistent with the hook form of
startTransition, we capture errors thrown by the scope function and pass
them to the global reportError function. (This is also what we do as a
default for onRecoverableError.)

This is a breaking change because it means that errors inside of
startTransition will no longer bubble up to the caller. You can still
catch the error by putting a try/catch block inside of the scope
function itself.

We do the same for async actions to prevent "unhandled promise
rejection" warnings.

The motivation is to avoid a refactor hazard when changing from a sync
to an async action, or from useTransition to startTransition.

DiffTrain build for [60f190a559](https://github.com/facebook/react/commit/60f190a55948a7512d4e2a336f03b45fd38d6a80)
2024-01-26 17:15:15 +00:00
gnoff c53cad6bbe fix incorrect insertion order of stylesheets (#28108)
## Summary

In the precendences Map every key is prefixed with `p`. This fixes one
case where this is missing.

## 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.
-->

DiffTrain build for [763612647c](https://github.com/facebook/react/commit/763612647ceb66d95f728af896ca5e18a8181db8)
2024-01-26 16:00:50 +00:00
acdlite bd16b96a44 Async action support for React.startTransition (#28097)
This adds support for async actions to the "isomorphic" version of
startTransition (i.e. the one exported by the "react" package).
Previously, async actions were only supported by the startTransition
that is returned from the useTransition hook.

The interesting part about the isomorphic startTransition is that it's
not associated with any particular root. It must work with updates to
arbitrary roots, or even arbitrary React renderers in the same app. (For
example, both React DOM and React Three Fiber.)

The idea is that React.startTransition should behave as if every root
had an implicit useTransition hook, and you composed together all the
startTransitions provided by those hooks. Multiple updates to the same
root will be batched together. However, updates to one root will not be
batched with updates to other roots.

Features like useOptimistic work the same as with the hook version.

There is one difference from from the hook version of startTransition:
an error triggered inside an async action cannot be captured by an error
boundary, because it's not associated with any particular part of the
tree. You should handle errors the same way you would in a regular
event, e.g. with a global error event handler, or with a local
`try/catch`.

DiffTrain build for [85b296e9b6](https://github.com/facebook/react/commit/85b296e9b6ded4accd9ec3389297f95091fb1ac0)
2024-01-26 02:59:47 +00:00
acdlite 69fea0b202 Batch async actions even if useTransition is unmounted (#28078)
If there are multiple updates inside an async action, they should all be
rendered in the same batch, even if they are separate by an async
operation (`await`). We currently implement this by suspending in the
`useTransition` hook to block the update from committing until all
possible updates have been scheduled by the action. The reason we did it
this way is so you can "cancel" an action by navigating away from the UI
that triggered it.

The problem with that approach, though, is that even if you navigate
away from the `useTransition` hook, the action may have updated shared
parts of the UI that are still in the tree. So we may need to continue
suspending even after the `useTransition` hook is deleted.

In other words, the lifetime of an async action scope is longer than the
lifetime of a particular `useTransition` hook.

The solution is to suspend whenever _any_ update that is part of the
async action scope is unwrapped during render. So, inside useState and
useReducer.

This fixes a related issue where an optimistic update is reverted before
the async action has finished, because we were relying on the
`useTransition` hook to prevent the optimistic update from finishing.

This also prepares us to support async actions being passed to the
non-hook form of `startTransition` (though this isn't implemented yet).

DiffTrain build for [11c9fd0c53](https://github.com/facebook/react/commit/11c9fd0c53133f24f5270d36591b65b8fc2ebd25)
2024-01-25 04:59:52 +00:00
rickhanlonii 605ae6d45e Convert ReactDOMTestSelectors-test.js to createRoot (#27993)
Straightforward adding createRoot and act

DiffTrain build for [4217d324ae](https://github.com/facebook/react/commit/4217d324ae5766b3201e682bb4d67b8855652694)
2024-01-24 04:06:34 +00:00
acdlite f10aaf1267 Fix: useOptimistic should return passthrough value when there are no updates pending (#27936)
This fixes a bug that happened when the canonical value passed to
useOptimistic without an accompanying call to setOptimistic. In this
scenario, useOptimistic should pass through the new canonical value.

I had written tests for the more complicated scenario, where a new value
is passed while there are still pending optimistic updates, but not this
simpler one.

DiffTrain build for [60a927d04a](https://github.com/facebook/react/commit/60a927d04ad3888facebcdf7da620aa1cfc9528f)
2024-01-14 02:42:16 +00:00
sebmarkbage 990d5cc255 Use getComponentNameFromType for debug info for the key warning (#27930)
If this is a client reference we shouldn't dot into it, which would
throw in the proxy.

Interestingly our client references don't really have a `name`
associated with them for debug information so a component type doesn't
show up in error logs even though it seems like it should.

DiffTrain build for [0ac3ea471f](https://github.com/facebook/react/commit/0ac3ea471fbcb7d79bc7d36179e960c72c779e76)
2024-01-11 22:29:18 +00:00
acdlite f748f7366c Fix: useDeferredValue initialValue suspends forever without switching to final (#27888)
Fixes a bug in the experimental `initialValue` option for
`useDeferredValue` (added in #27500).

If rendering the `initialValue` causes the tree to suspend, React should
skip it and switch to rendering the final value instead. It should not
wait for `initialValue` to resolve.

This is not just an optimization, because in some cases the initial
value may _never_ resolve — intentionally. For example, if the
application does not provide an instant fallback state. This capability
is, in fact, the primary motivation for the `initialValue` API.

I mostly implemented this correctly in the original PR, but I missed
some cases where it wasn't working:

- If there's no Suspense boundary between the `useDeferredValue` hook
and the component that suspends, and we're not in the shell of the
transition (i.e. there's a parent Suspense boundary wrapping the
`useDeferredValue` hook), the deferred task would get incorrectly
dropped.
- Similarly, if there's no Suspense boundary between the
`useDeferredValue` hook and the component that suspends, and we're
rendering a synchronous update, the deferred task would get incorrectly
dropped.

What these cases have in common is that it causes the `useDeferredValue`
hook itself to be replaced by a Suspense fallback. The fix was the same
for both. (It already worked in cases where there's no Suspense fallback
at all, because those are handled differently, at the root.)

The way I discovered this was when investigating a particular bug in
Next.js that would happen during a 'popstate' transition (back/forward),
but not during a regular navigation. That's because we render popstate
transitions synchronously to preserve browser's scroll position — which
in this case triggered the second scenario above.

DiffTrain build for [f1039be4a4](https://github.com/facebook/react/commit/f1039be4a48384e7e4b0a87d4d92c48e900053b9)
2024-01-08 04:22:01 +00:00
kassens 9996001938 Add feature flags for expiration times (#27821)
It seems worthwhile to me to run a test to experiment with different
expiration times. This moves the expiration times for scheduler and
reconciler into FeatureFlags for the facebook build. Non-facebook should
not be affected by these changes.

DiffTrain build for [0cdfef19b9](https://github.com/facebook/react/commit/0cdfef19b96cc6202d48e0812b5069c286d12b04)
2023-12-11 15:03:05 +00:00
kassens 235d6d7ad4 [ci] try to fix commit_artifacts step (#27817)
Tries to fix the failure from
https://github.com/facebook/react/actions/runs/7142005723/job/19450371514

I think it failed because we cannot `mv` into a folder with existing
files or folders.

DiffTrain build for [d3ed07bce0](https://github.com/facebook/react/commit/d3ed07bce036df61fbce52151f1531a5762ba6d6)
2023-12-08 17:43:31 +00:00
hoxyq c35082fd80 fix: select console error to not suggest to set readonly to true (#27740)
fix #27657

added test in the `ReactDOMSELECT-test.js` to not allow regession to
happen in future.

After changes this is what the error message looks like

https://github.com/facebook/react/assets/72331432/53dcbe2a-70d2-43d2-a52d-a4fc389fdfbf

DiffTrain build for [5dd35968be](https://github.com/facebook/react/commit/5dd35968bef791ccc5948c657fabf191a77fff3f)
2023-12-01 16:00:15 +00:00
kassens 62b9d0a15f [cleanup] remove enableHostSingletons feature flag (#27583)
The flag is enabled everywhere, I think we can remove it now.

DiffTrain build for [1a65d036ef](https://github.com/facebook/react/commit/1a65d036ef057b07a6b15f5604e399f91bc5ed73)
2023-11-16 22:47:06 +00:00
kassens 9e50f2a78b Add a feature flag to enable expiration of retry lanes (#27694)
An attempt to see if we can bring back expiration of retry lanes to
avoid cases resolving Suspense can be starved by frequent updates.

In the past, this caused increase browser crashes, but a lot of time has
passed since then. Just trying if we can re-enable this.

Old PR that reverted adding the timeout:
https://github.com/facebook/react/pull/21300

DiffTrain build for [593ecee66a](https://github.com/facebook/react/commit/593ecee66a609d4a4c2b36b39b1e5e23b2456dd1)
2023-11-14 15:20:17 +00:00
kassens 6bab074fd2 Small cleanup in ReactFiberCompleteWork (#27681)
These are all functionally equivalent changes.

- remove double negation and more explicit naming of
`hadNoMutationsEffects`
- use docblock syntax that's consumed by Flow
- remove useless cast

DiffTrain build for [c4c87e049b](https://github.com/facebook/react/commit/c4c87e049b891ebc38a7a14b8c93285c877e90af)
2023-11-10 15:25:47 +00:00
hoxyq c65ae2687c refactor[ci/build]: preserve header format in artifacts (#27671)
In order to make Haste work with React's artifacts, It is important to
keep headers in this format:
```
/**
* ...
...
* ...
*/
```

For optimization purposes, Closure compiler will actually modify these
headers by removing * prefixes, which is expected.
We should pass sources to the compiler without license headers, with
these changes the current flow will be:
1. Apply top-level definitions. For UMD-bundles, for example, or
DEV-only bundles (e. g. `if (__DEV__) { ...`)
2. Apply licence headers for artifacts with sourcemaps: oss-production
and oss-profiling bundles, they don't need to preserve the header format
to comply with Haste. We need to apply these headers before passing
sources to Closure, so it can build correct mappings for sourcemaps.
3. Pass these sources to closure compiler for minification and
sourcemaps building.
4. Apply licence headers for artifacts without sourcemaps: dev bundles,
fb bundles. This way the header style will be preserved and not changed
by Closure.

DiffTrain build for [c47c306a7a](https://github.com/facebook/react/commit/c47c306a7a23d3c796b148d303764e2832da480c)
2023-11-09 16:05:29 +00:00
mofeiZ 0367178d64 Update stack diffing algorithm in describeNativeComponentFrame (#27132)
## Summary

There's a bug with the existing stack comparison algorithm in
`describeNativeComponentFrame` — specifically how it attempts to find a
common root frame between the control and sample stacks. This PR
attempts to fix that bug by injecting a frame that can have a guaranteed
string in it for us to search for in both stacks to find a common root.

## Brief Background/How it works now

Right now `describeNativeComponentFrame` does the following to leverage
native browser/VM stack frames to get details (e.g. script path, row and
col #s) for a single component:
1. Throwing and catching a control error in the function
2. Calling the component which should eventually throw an error (most of
the time), that we'll catch as our sample error.
3. Diffing the stacks in the control and sample errors to find the line
which should represent our component call.

## What's broken

To account for potential stack trace truncation, the stack diffing
algorithm first attempts to find a common "root" frame by inspecting the
earliest frame of the sample stack and searching for an identical frame
in the control stack starting from the bottom. However, there are a
couple of scenarios which I've hit that cause the above approach to not
work correctly.

First, it's possible that for render passes of extremely large component
trees to have a lot of repeating internal react function calls, which
can result in an incorrect common or "root" frame found. Here's a small
example from a stack trace using React Fizz for SSR.
Our control frame can look like this:
```
Error:
    at Fake (...)
    at construct (native)
    at describeNativeComponentFrame (...)
    at describeClassComponentFrame (...)
    at getStackByComponentStackNode (...)
    at getCurrentStackInDEV (...)
    at renderNodeDestructive (...)
    at renderElement (...)
    at renderNodeDestructiveImpl (...) // <-- Actual common root frame with the sample stack
    at renderNodeDestructive (...)
    at renderElement (...)
    at renderNodeDestructiveImpl (...) // <-- Incorrectly chosen common root frame
    at renderNodeDestructive (...)
```

And our sample stack can look like this:
```
Error:
    at set (...)
    at PureComponent (...)
    at call (native)
    at apply (native)
    at ErrorBoundary (...)
    at construct (native)
    at describeNativeComponentFrame (...)
    at describeClassComponentFrame (...)
    at getStackByComponentStackNode (...)
    at getCurrentStackInDEV (...)
    at renderNodeDestructive (...)
    at renderElement (...)
    at renderNodeDestructiveImpl (...) // <-- Root frame that's common in the control stack
```

Here you can see that the earliest trace in the sample stack, the
`renderNodeDestructiveImpl` call, can exactly match with multiple
`renderNodeDestructiveImpl` calls in the control stack (including file
path and line + col #s). Currently the algorithm will chose the
earliest/last frame with the `renderNodeDestructiveImpl` call (which is
the second last frame in our control stack), which is incorrect. The
actual matching frame in the control stack is the latest or first frame
(when traversing from the top) with the `renderNodeDestructiveImpl`
call. This leads to the rest of the stack diffing associating an
incorrect frame (`at getStackByComponentStackNode (...)`) for the
component.

Another issue with this approach is that it assumes all VMs will
truncate stack traces at the *bottom*, [which isn't the case for the
Hermes
VM](https://github.com/facebook/hermes/blob/df07cf713a84a4434c83c08cede38ba438dc6aca/lib/VM/JSError.cpp#L688-L699)
which **truncates stack traces in the middle**, placing a

```
    at renderNodeDestructiveImpl (...)
    ... skipping {n} frames
    at renderNodeDestructive (...)
```

line in the middle of the stack trace for all stacks that contain more
than 100 traces. This causes stack traces for React Native apps using
the Hermes VM to potentially break for large component trees. Although
for this specific case with Hermes, it's possible to account for this by
either manually grepping and removing the `... skipping` line and
everything below it (see draft PR: #26999), or by implementing the
non-standard `prepareStackTrace` API which Hermes also supports to
manually generate a stack trace that truncates from the bottom ([example
implementation](https://github.com/facebook/react/compare/main...KarimP:react:component-stack-hermes-fix)).

## The Fix

I found different ways to go about fixing this. The first was to search
for a common stack frame starting from the top/latest frame. It's a
relatively small change ([see
implementation](https://github.com/facebook/react/compare/main...KarimP:react:component-stack-fix-2)),
although it is less performant by being n^2 (albeit with `n`
realistically being <= 5 here). It's also a bit more buggy for class
components given that different VMs insert a different amount of
additional lines for new/construct calls...

Another fix would be to actually implement a [longest common
substring](https://en.wikipedia.org/wiki/Longest_common_substring)
algorithm, which can also be roughly n^2 time (assuming the longest
common substring between control and sample will be most of the sample
frame).

The fix I ended up going with was have the lines that throw the control
error and the lines that call/instantiate the component be inside a
distinct method under an object property
(`"DescribeNativeComponentFrameRoot"`). All major VMs (Safari's
JavaScriptCore, Firefox's SpiderMonkey, V8, Hermes, and Bun) should
display the object property name their stack trace. I've also set the
`name` and `displayName` properties for method as well to account for
minification, any advanced optimizations (e.g. key crushing), and VM
inconsistencies (both Bun and Safari seem to exclusively use the value
under `displayName` and not `name` in traces for methods defined under
an object's own property...).

We can then find this "common" frame by simply finding the line that has
our special method name (`"DescribeNativeComponentFrameRoot"`), and the
rest of the code to determine the actual component line works as
expected. If by any chance we don't find a frame with our special method
name in either control or sample stack traces, we then revert back to
the existing approach mentioned above by searching for the last line of
the sample frame in the control frame.

## How did you test this change?

1. There are bunch of existing tests that ensure a properly formatted
component trace is logged for certain scenarios, so I ensured the
existing full test suite passed
2. I threw an error in a component that's deep in the component
hierarchy of a large React app (facebook) to ensure there's stack trace
truncation, and ensured the correct component stack trace was logged for
Chrome, Safari, and Firefox, and with and without minification.
3. Ran a large React app (facebook) on the Hermes VM, threw an error in
a component that's deep in the component hierarchy, and ensured that
component frames are generated despite stack traces being truncated in
the middle.

DiffTrain build for [88b00dec47](https://github.com/facebook/react/commit/88b00dec4778ffa230cceca81af3328f49e1efd9)
2023-11-08 16:50:30 +00:00
hoxyq c7e4e4f3fb Generate sourcemaps for production build artifacts (#26446)
<!--
  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

This PR updates the Rollup build pipeline to generate sourcemaps for
production build artifacts like `react-dom.production.min.js`.

It requires the Rollup v3 changes that were just merged in #26442 .

Sourcemaps are currently _only_ generated for build artifacts that are
_truly_ "production" - no sourcemaps will be generated for development,
profiling, UMD, or `shouldStayReadable` artifacts.

The generated sourcemaps contain the bundled source contents right
before that chunk was minified by Closure, and _not_ the original source
files like `react-reconciler/src/*`. This better reflects the actual
code that is running as part of the bundle, with all the feature flags
and transformations that were applied to the source files to generate
that bundle. The sourcemaps _do_ still show comments and original
function names, thus improving debuggability for production usage.

Fixes #20186 .

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

This allows React users to actually debug a readable version of the
React bundle in production scenarios. It also allows other tools like
[Replay](https://replay.io) to do a better job inspecting the React
source when stepping through.

## How did you test this change?

- Generated numerous sourcemaps with various combinations of the React
bundle selections
- Viewed those sourcemaps in
https://evanw.github.io/source-map-visualization/ and confirmed via the
visualization that the generated mappings appear to be correct

I've attached a set of production files + their sourcemaps here:

[react-sourcemap-examples.zip](https://github.com/facebook/react/files/11023466/react-sourcemap-examples.zip)

You can drag JS+sourcemap file pairs into
https://evanw.github.io/source-map-visualization/ for viewing.

Examples:

- `react.production.min.js`:

![image](https://user-images.githubusercontent.com/1128784/226478247-e5cbdee0-83fd-4a19-bcf1-09961d3c7da4.png)

- `react-dom.production.min.js`:

![image](https://user-images.githubusercontent.com/1128784/226478433-b5ccbf0f-8f68-42fe-9db9-9ecb97770d46.png)

- `use-sync-external-store/with-selector.production.min.js`:

![image](https://user-images.githubusercontent.com/1128784/226478565-bc74699d-db14-4c39-9e2d-b775f8755561.png)

<!--
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 [2c8a139a59](https://github.com/facebook/react/commit/2c8a139a593e0294c3a6953d74b451bd05fdcfca)
2023-11-07 19:06:24 +00:00
acdlite 0d03ff9eac [useFormState] Allow sync actions (#27571)
Updates useFormState to allow a sync function to be passed as an action.

A form action is almost always async, because it needs to talk to the
server. But since we support client-side actions, too, there's no reason
we can't allow sync actions, too.

I originally chose not to allow them to keep the implementation simpler
but it's not really that much more complicated because we already
support this for actions passed to startTransition. So now it's
consistent: anywhere an action is accepted, a sync client function is a
valid input.

DiffTrain build for [77c4ac2ce8](https://github.com/facebook/react/commit/77c4ac2ce88736bbdfe0b29008b5df931c2beb1e)
2023-11-01 03:38:26 +00:00
sophiebits 8c6e716990 validateDOMNesting: Allow hr as child of select (#27632)
fix #27572

---------

Co-authored-by: Sophie Alpert <git@sophiebits.com>

DiffTrain build for [ca16c26356](https://github.com/facebook/react/commit/ca16c26356221a4b52185d7425d77675f0307250)
2023-10-31 21:48:19 +00:00
gnoff 21d5f5f8e8 [Float][Fiber] Fixes incorrect boolean logic around loading states for stylesheets (#27610)
the loading states of stylesheets found in the DOM during preinit should
be assumed to be loaded

DiffTrain build for [3e09c27b88](https://github.com/facebook/react/commit/3e09c27b880e1fecdb1eca5db510ecce37ea6be2)
2023-10-27 15:55:27 +00:00
gnoff 6a86afb87e [Fizz] Do not reinsert stylesheets after initial insert (#27586)
The loading state tracking for suspensey CSS is too complicated. Prior
to this change it had a state it could enter into where a stylesheet was
already in the DOM but the loading state did not know it was inserted
causing a later transition to try to insert it again.

This fix is to add proper tracking of insertions on the codepaths that
were missing it. It also modifies the logic of when to suspend based on
whether the stylesheet has already been inserted or not.

This is not 100% correct semantics however because a prior commit could
have inserted a stylesheet and a later transition should ideally be able
to wait on that load before committing. I haven't attempted to fix this
yet however because the loading state tracking is too complicated as it
is and requires a more thorough refactor. Additionally it's not
particularly valuable to delay a transition on a loading stylesheet when
a previous commit also relied on that stylesheet but didn't wait for it
b/c it was sync. I will follow up with an improvement PR later

fixes: https://github.com/facebook/react/issues/27585

DiffTrain build for [a9985529f1](https://github.com/facebook/react/commit/a9985529f1aa55477f0feafe2398d36707cf6108)
2023-10-25 18:56:13 +00:00
acdlite 857a68d62b useDeferredValue has higher priority than partial hydration (#27550)
By default, partial hydration is given the lowest possible priority,
because until a tree is updated, the server-rendered HTML is assumed to
match the final resolved HTML.

However, this isn't completely true because a component may choose to
"upgrade" itself upon hydration. The simplest example is a component
that calls setState in a useEffect to switch to a richer implementation
of the UI. Another example is a component that doesn't have a server-
rendered implementation, so it intentionally suspends to force a client-
only render.

useDeferredValue is an example, too: the server only renders the first
pass (the initialValue) argument, and relies on the client to upgrade to
the final value.

What we should really do in these cases is emit some information into
the Fizz stream so that Fiber knows to prioritize the hydration of
certain trees. We plan to add a mechanism for this in the future.

In the meantime, though, we can at least ensure that the priority of the
upgrade task is correct once it's "discovered" during hydration. In this
case, the priority of the task spawned by useDeferredValue should have
Transition priority, not Offscreen priority.

DiffTrain build for [779d59374e](https://github.com/facebook/react/commit/779d59374e8e852ce00728d895156a7574e1b456)
2023-10-23 17:54:55 +00:00
acdlite dc239e6aa6 Bugfix: useDeferredValue loop during popstate transition (#27559)
During a popstate event, we attempt to render updates synchronously even
if they are transitions, to preserve scroll position if possible. We do
this by entangling the transition lane with the Sync lane.

However, if rendering the transition spawns additional transition
updates (e.g. a setState inside useEffect), there's no reason to render
those synchronously, too. We should use the normal transition behavior.

This fixes an issue where useDeferredValue during a popstate event would
spawn a transition update that was itself also synchronous.

DiffTrain build for [6db7f4209e](https://github.com/facebook/react/commit/6db7f4209e6f32ebde298a0b7451710dd6aa3e19)
2023-10-21 16:16:22 +00:00