Commit Graph

16242 Commits

Author SHA1 Message Date
sebmarkbage a5e6d678ba [Fiber] Color Performance Track Entries by Self Time (#30984)
Stacked on #30983.

This colors each component entry by its self time from light to dark
depending on how long it took. If it took longer than a cut off we color
it red (the error color).

<img width="435" alt="Screenshot 2024-09-16 at 11 48 15 PM"
src="https://github.com/user-attachments/assets/5d0bda83-6205-40e9-bec1-b81db2d48b2d">

DiffTrain build for [8dfbd16fce](https://github.com/facebook/react/commit/8dfbd16fce9077ab4e5fe85a7b86fa7c97a5ae04)
2024-09-17 13:43:35 -07:00
sebmarkbage 7b7ffbd4b5 [Fiber] Log Component Effects to Performance Track (#30983)
Stacked on #30981. Same as #30967 but for effects.

This logs a tree of components using `performance.measure()`.

In addition to the previous render phase this logs one tree for each
commit phase:

- Mutation Phase
- Layout Effect
- Passive Unmounts
- Passive Mounts

I currently skip the Before Mutation phase since the snapshots are so
unusual it's not worth creating trees for those.

The mechanism is that I reuse the timings we track for
`enableProfilerCommitHooks`. I track first and last effect timestamp
within each component subtree. Then on the way up do we log the entry.
This means that we don't include overhead to find our way down to a
component and that we don't need to add any additional overhead by
reading timestamps.

To ensure that the entries get ordered correctly we need to ensure that
the start time of each parent is slightly before the inner one.

DiffTrain build for [e1c20902c3](https://github.com/facebook/react/commit/e1c20902c39d1dfe2649185622f2f21b526e2be2)
2024-09-17 13:22:20 -07:00
sebmarkbage 2acc36c953 Don't read currentTransition back from internals (#30991)
This code is weird. It reads back the transition that it just set from
the shared internals. It's almost like it expects it to be a getter or
something.

This avoids that and makes it consistent with what ReactFiberHooks
already does.

DiffTrain build for [15da917451](https://github.com/facebook/react/commit/15da9174518f18f82869767ebe2a21be2fc8bd90)
2024-09-17 12:32:15 -07:00
sebmarkbage e70db3db9b [Fiber] Optimize enableProfilerCommitHooks by Collecting Elapsed Effect Duration in Module Scope (#30981)
Stacked on #30979.

The problem with the previous approach is that it recursively walked the
tree up to propagate the resulting time from recording a layout effect.

Instead, we keep a running count of the effect duration on the module
scope. Then we reset it when entering a nested Profiler and then we add
its elapsed count when we exit the Profiler.

This also fixes a bug where we weren't previously including unmount
times for some detached trees since they couldn't bubble up to find the
profiler.

DiffTrain build for [4549be0f84](https://github.com/facebook/react/commit/4549be0f846e7df5a4eaabf06369d93bd120271e)
2024-09-17 12:19:38 -07:00
mvitousek 905f7f3c7b [compiler][playground] create playground API in pipeline, and allow spaces in pass names
Summary:
1. Minor refactor to provide a stable API for calling the compiler from the playground
2. Allows spaces in pass names without breaking the appearance of the playground by replacing spaces with &nbsp; in pass tabs

ghstack-source-id: 12a43ad86c
Pull Request resolved: https://github.com/facebook/react/pull/30988

DiffTrain build for [7b56a54298](https://github.com/facebook/react/commit/7b56a542987890f618eeda4e4906fbf1f1df2213)
2024-09-17 11:13:16 -07:00
mofeiZ 9901f5a098 [compiler][eslint] Report bailout diagnostics with correct column # (#30977)
Compiler bailout diagnostics should now highlight only the first line of
the source location span.

(Resubmission of #30423 which was reverted due to invalid column
number.)

DiffTrain build for [a99d8e8d97](https://github.com/facebook/react/commit/a99d8e8d97055127a8ad7b01835d2660154689ed)
2024-09-16 13:03:43 -07:00
sebmarkbage 5776f4e27e Remove execution context check from shouldProfile (#30971)
I don't know why this is here since all these callsites are within the
CommitWork/CommitEffects helpers.

This should help with inlining.

DiffTrain build for [8152e5cd27](https://github.com/facebook/react/commit/8152e5cd27721e792f395c0b62c8a7769a54777a)
2024-09-16 12:07:15 -07:00
mvitousek f5d6218384 [compiler] Implement support for hoisted and recursive functions
Summary:
Introduces a new binding kind for functions that allows them to be hoisted. Also has the result of causing all nested function declarations to be outputted as function declarations, not as let bindings.

ghstack-source-id: fa40d4909f
Pull Request resolved: https://github.com/facebook/react/pull/30922

DiffTrain build for [d7167c3505](https://github.com/facebook/react/commit/d7167c35059bc6a0ad84eb34e65b3b66328d5dd8)
2024-09-16 11:20:30 -07:00
mvitousek 2f4fba4d70 [compiler] Allow all hooks to take callbacks which access refs, but ban hooks from taking direct ref value arguments
Summary:
This brings the behavior of ref mutation within hook callbacks into alignment with the behavior of global mutations--that is, we allow all hooks to take callbacks that may mutate a ref. This is potentially unsafe if the hook eagerly calls its callback, but the alternative is excessively limiting (and inconsistent with other enforcement).

This also bans *directly* passing a ref.current value to a hook, which was previously allowed.

ghstack-source-id: e66ce7123e
Pull Request resolved: https://github.com/facebook/react/pull/30917

DiffTrain build for [e78c9362c0](https://github.com/facebook/react/commit/e78c9362c014dccaed5ff193106e44d7d072dc32)
2024-09-16 11:04:44 -07:00
javache 6ba137bf82 [react-native] Fix misleading crash when view config is not found (#30970)
## Summary

When a view config can not be found, it currently errors with
`TypeError: Cannot read property 'bubblingEventTypes' of null`. Instead
invariant at the correct location and prevent further processing of the
null viewConfig to improve the error logged.

## How did you test this change?

Build and run RN playground app referencing an invalid native view
through `requireNativeComponent`.

DiffTrain build for [26855e4680](https://github.com/facebook/react/commit/26855e4680dedb21f2c73a069ed691822a242db1)
2024-09-16 09:58:01 -07:00
hoxyq a8693bec36 fix: add Error prefix to Error objects names (#30969)
This fixes printing Error objects in Chrome DevTools.

I've observed that Chrome DevTools is not source mapping and linkifying
URLs, when was running this on larger apps. Chrome DevTools talks to V8
via Chrome DevTools protocol, every object has a corresponding
[`RemoteObject`](https://chromedevtools.github.io/devtools-protocol/tot/Runtime/#type-RemoteObject).

When Chrome DevTools sees that Error object is printed in the console,
it will try to prettify it. `description` field of the corresponding
`RemoteObject` for the `Error` JavaScript object is a combination of
`Error` `name`, `message`, `stack` fields. This is not just a raw
`stack` field, so our prefix for this field just doesn't work. [V8 is
actually filtering out first line of the `stack` field, it only keeps
the stack frames as a string, and then this gets prefixed by `name` and
`message` fields, if they are
available](https://source.chromium.org/chromium/chromium/src/+/main:v8/src/inspector/value-mirror.cc;l=252-311;drc=bdc48d1b1312cc40c00282efb1c9c5f41dcdca9a?fbclid=IwZXh0bgNhZW0CMTEAAR1tMm5YC4jqowObad1qXFT98X4RO76CMkCGNSxZ8rVsg6k2RrdvkVFL0i4_aem_e2fRrqotKdkYIeWlJnk0RA).
As an illustration, this:
```
const fakeError = new Error('');
fakeError.name = 'Stack';
fakeError.stack = 'Error Stack:' + stack;
```

will be formatted by `V8` as this `RemoteObject`:
```
{
  ...
  description: 'Stack: ...',
  ...
}
```

Notice that there is no `Error` prefix, that was previously added.
Because of this, [Chrome DevTools won't even try to symbolicate the
stack](https://github.com/ChromeDevTools/devtools-frontend/blob/ee4729d2ccdf5c6715ee40e6697f5464829e3f9a/front_end/panels/console/ErrorStackParser.ts#L33-L35),
because it doesn't have such prefix.

DiffTrain build for [9f4e4611ea](https://github.com/facebook/react/commit/9f4e4611ead28d34f7f598c9bd12424cf68f5781)
2024-09-16 09:51:18 -07:00
sebmarkbage 07973576bd [Fiber] Log Component Renders to Custom Performance Track (#30967)
Stacked on #30960 and #30966. Behind the enableComponentPerformanceTrack
flag.

This is the first step of performance logging. This logs the start and
end time of a component render in the passive effect phase. We use the
data we're already tracking on components when the Profiler component or
DevTools is active in the Profiling or Dev builds. By backdating this
after committing we avoid adding more overhead in the hot path. By only
logging things that actually committed, we avoid the costly unwinding of
an interrupted render which was hard to maintain in earlier versions.

We already have the start time but we don't have the end time. That's
because `actualStartTime + actualDuration` isn't enough since
`actualDuration` counts the actual CPU time excluding yields and
suspending in the render.

Instead, we infer the end time to be the start time of the next sibling
or the complete time of the whole root if there are no more siblings. We
need to pass this down the passive effect tree. This will mean that any
overhead and yields are attributed to this component's span. In a follow
up, we'll need to start logging these yields to make it clear that this
is not part of the component's self-time.

In follow ups, I'll do the same for commit phases. We'll also need to
log more information about the phases in the top track. We'll also need
to filter out more components from the trees that we don't need to
highlight like the internal Offscreen components. It also needs polish
on colors etc.

Currently, I place the components into separate tracks depending on
which lane currently committed. That way you can see what was blocking
Transitions or Suspense etc. One problem that I've hit with the new
performance.measure extensions is that these tracks show up in the order
they're used which is not the order of priority that we use. Even when
you add fake markers they have to actually be within the performance run
since otherwise the calls are noops so it's not enough to do that once.

However, I think this visualization is actually not good because these
trees end up so large that you can't see any other lanes once you expand
one. Therefore, I think in a follow up I'll actually instead switch to a
model where Components is a single track regardless of lane since we
don't currently have overlap anyway. Then the description about what is
actually rendering can be separate lanes.

<img width="1512" alt="Screenshot 2024-09-15 at 10 55 55 PM"
src="https://github.com/user-attachments/assets/5ca3fa74-97ce-40c7-97f7-80c1dd7d6470">

<img width="1512" alt="Screenshot 2024-09-15 at 10 56 27 PM"
src="https://github.com/user-attachments/assets/557ad65b-4190-465f-843c-0bc6cbb9326d">

DiffTrain build for [f2df5694f2](https://github.com/facebook/react/commit/f2df5694f2be141954f22618fd3ad035203241a3)
2024-09-16 08:53:04 -07:00
sebmarkbage be5e283e53 Add enableComponentPerformanceTrack Flag (#30960)
This flag will be used to gate a new timeline profiler that's integrate
with the Performance Tab and the new performance.measure extensions in
Chrome.

It replaces the existing DevTools feature so this disables
enableSchedulingProfiler when it is enabled since they can interplay in
weird ways potentially.

This means that experimental React now disable scheduling profiler and
enables this new approach.

DiffTrain build for [0eab377a96](https://github.com/facebook/react/commit/0eab377a96099f0121009c8968c49d13d4e00bd1)
2024-09-16 08:17:42 -07:00
hoxyq 2875993c07 fix[rdt/fiber/renderer.js]: getCurrentFiber can be injected as null (#30968)
In production artifacts for `18.x.x` `getCurrentFiber` can actually be
injected as `null`. Updated `getComponentStack` and `onErrorOrWarning`
implementations to support this.

![Screenshot 2024-09-16 at 10 52
00](https://github.com/user-attachments/assets/a0c773aa-ebbf-4fd5-95c4-cac3cc0c203f)

DiffTrain build for [8cf64620c7](https://github.com/facebook/react/commit/8cf64620c7dd4ec7e72aa16ee2d5f15eb3420b92)
2024-09-16 06:54:58 -07:00
gnoff a53353a14d [Flight] Start initial work immediately (#30961)
In a past update we made render and prerender have different work
scheduling behavior because these methods are meant to be used in
differeent environments with different performance tradeoffs in mind.
For instance to prioritize streaming we want to allow as much IO to
complete before triggering a round of work because we want to flush as
few intermediate UI states. With Prerendering there will never be any
intermediate UI states so we can more aggressively render tasks as they
complete.

One thing we've found is that even during render we should ideally kick
off work immediately. This update normalizes the intitial work for
render and prerender to start in a microtask. Choosing microtask over
sync is somewhat arbitrary but there really isn't a reason to make them
different between render/prerender so for now we'll unify them and keep
it as a microtask for now.

This change also updates pinging behavior. If the request is still in
the initial task that spawned it then pings will schedule on the
microtask queue. This allows immediately available async APIs to resolve
right away. The concern with doing this for normal pings is that it
might crowd out IO events but since this is the initial task there would
be IO to already be scheduled.

DiffTrain build for [fc5ef50da8](https://github.com/facebook/react/commit/fc5ef50da8e975a569622d477f1fed54cb8b193d)
2024-09-14 09:32:59 -07:00
gnoff 36ded714ec Fix nodeName to UPPERCASE in insertStylesheetIntoRoot (#28255)
## Summary

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

<img width="518" alt="image"
src="https://github.com/facebook/react/assets/18693190/6d12df76-7dae-403b-b486-4940992abe8d">

The condition `node.nodeName === 'link'` is always `false`, because
`node.nodeName` is Uppercase in specification. And the condition
`node.nodeName === 'LINK'` is unnecessary, because Fizz hoists tags when
it's `media` attribute is `"not all"`, whether it is a `link` or a
`style` (line 36):

https://github.com/facebook/react/blob/18cbcbf783377c5a22277a63ae41af54504502e0/packages/react-dom-bindings/src/server/fizz-instruction-set/ReactDOMFizzInstructionSetExternalRuntime.js#L30-L44

https://github.com/facebook/react/blob/18cbcbf783377c5a22277a63ae41af54504502e0/packages/react-dom-bindings/src/server/fizz-instruction-set/ReactDOMFizzInstructionSetInlineSource.js#L30-L44

DiffTrain build for [b75cc078c5](https://github.com/facebook/react/commit/b75cc078c5fda0d57135523a7a2f4e8d1536472f)
2024-09-14 08:25:42 -07:00
sebmarkbage a2485b7960 [Fiber] Profiler - Use two separate functions instead of branch by flag (#30957)
Nit: I don't trust flags in hot code. While it can take somewhat longer
to compile two functions and JIT them. After that they don't need to
check branches. Also makes it clearer the purpose.

DiffTrain build for [3d95c43b89](https://github.com/facebook/react/commit/3d95c43b8967d4dda1ec9a22f0d9ea4999fee8b8)
2024-09-13 18:58:53 -07:00
gnoff c8d8c3ea5e [Flight] properly track pendingChunks when changing environment names (#30958)
When the environment name changes for a chunk we issue a new debug chunk
which updates the environment name. This chunk was not beign included in
the pendingChunks count so the count was off when flushing

DiffTrain build for [6774caa379](https://github.com/facebook/react/commit/6774caa37973e3e26d60f100971e5e785fd12235)
2024-09-13 16:02:52 -07:00
sebmarkbage 0252a0b7cb [Flight] Respect async flag in client manifest (#30959)
In #26624, the ability to mark a client reference module as `async` in
the React client manifest was removed because it was not utilized by
Webpack, neither in `ReactFlightWebpackPlugin` nor in Next.js. However,
some bundlers and frameworks are sophisticated enough to properly handle
and identify async ESM modules (e.g., client component modules with
top-level `await`), most notably Turbopack in Next.js. Therefore, we
need to consider the `async` flag in the client manifest when resolving
the client reference metadata on the server. The SSR manifest cannot
override this flag, meaning that if a module is async, it must remain
async in all client environments.

x-ref: https://github.com/vercel/next.js/pull/70022

DiffTrain build for [5deb78223a](https://github.com/facebook/react/commit/5deb78223a269a6cb1706da8ec6aad8c007cab03)
2024-09-13 13:40:38 -07:00
josephsavona d65fb06955 fix: restore selection should consider the window of the container (#30951)
## Summary

Fixes #30864

Before this PR the active elemen was always taken from the global
`window`. This is incorrect if the renderer is in one window rendering
into a container element in another window. The changes in this PR adds
another code branch to use a `defaultView` of the container element if
it exists so that `restoreSelection` after a commit will actually
restore to the correct window.

## How did you test this change?

I patched these changes to the repro repo in the linked issue #39864
https://github.com/ling1726/react-child-window-focus-repro/blob/master/patches/react-dom%2B18.3.1.patch.

I followed the same repro steps in the linked issue and and could not
repro the reported problem. Attaching screen recordings below:

Before
![focus
repro](https://github.com/user-attachments/assets/81c4b4f9-08b5-4356-8251-49b909771f3f)

After

![after](https://github.com/user-attachments/assets/84883032-5558-4650-9b9a-bd4d5fd9cb13)

DiffTrain build for [d9c4920e8b](https://github.com/facebook/react/commit/d9c4920e8b3fff3d3da24d14adf7ac884aee55b2)
2024-09-13 13:36:35 -07:00
rickhanlonii 9d3ed27e04 Call cleanup of insertion effects when hidden (#30954)
Insertion effects do not unmount when a subtree is removed while
offscreen.

Current behavior for an insertion effect is if the component goes

- *visible -> removed:* calls insertion effect cleanup
- *visible -> offscreen -> removed:* insertion effect cleanup is never
called

This makes it so we always call insertion effect cleanup when removing
the component.

Likely also fixes https://github.com/facebook/react/issues/26670

---------

Co-authored-by: Rick Hanlon <rickhanlonii@fb.com>

DiffTrain build for [d3d4d3a46b](https://github.com/facebook/react/commit/d3d4d3a46b014ab0f6edc443c19fcdba09105f20)
2024-09-13 13:25:39 -07:00
sebmarkbage 037b2e3088 [Fiber] Set profiler values to doubles (#30942)
At some point this trick was added to initialize the value first to NaN
and then replace them with zeros and negative ones.

This is to address the issue noted in
https://github.com/facebook/react/issues/14365 where these hidden
classes can be initialized to SMIs at first and then deopt when we
realize they're actually doubles.

However, this fix has been long broken and has deopted the profiling
build for years because closure compiler optimizes out the first write.

I'm not sure because I haven't A/B-tested this in the JIT yet but I
think we can use negative zero and -1.1 as the initial values instead
since they're not simple integers. Negative zero `===` zero (but not
Object.is) so is the same as far as our code is concerned. The negative
value is just `< 0` comparisons.

DiffTrain build for [94e4acaa14](https://github.com/facebook/react/commit/94e4acaa1477e65cac02ba86058cde0afe4c8f1f)
2024-09-13 09:33:56 -07:00
sebmarkbage fadd1eee06 [Fizz] Add resumeAndPrerender to Static Rendering (#30950)
This is only in the same experimental exports as `resume`. Useful with
Postpone/Halt.

We already have `prerender()` to create a partial tree with postponed
state. We also have `resume()` to dynamically resume such a tree.

This lets you do a new prerender by resuming an already existing
postponed state. Basically creating a chain of preludes. The next
prelude would include the scripts to patch up the document.

This mostly just works since both prerender and resume are already
implemented using the same code so we just enable both at the root. I'm
sure we'll find some edge cases since this wasn't considered when it was
first written but so far I've only found an unrelated existing bug with
`keyPath` fixed here.

DiffTrain build for [473522093d](https://github.com/facebook/react/commit/473522093d3dd95582729d01cd5c0d15dcc9cd3b)
2024-09-12 07:58:29 -07:00
acdlite ed8cad438e Start prerendering Suspense retries immediately (#30934)
When a component suspends and is replaced by a fallback, we should start
prerendering the fallback immediately, even before any new data is
received. During the retry, we can enter prerender mode directly if
we're sure that no new data was received since we last attempted to
render the boundary.

To do this, when completing the fallback, we leave behind a pending
retry lane on the Suspense boundary. Previously we only did this once a
promise resolved, but by assigning a lane during the complete phase, we
will know that there's speculative work to be done.

Then, upon committing the fallback, we mark the retry lane as suspended
— but only if nothing was pinged or updated in the meantime. That allows
us to immediately enter prerender mode (i.e. render without skipping any
siblings) when performing the retry.

DiffTrain build for [d6cb4e7713](https://github.com/facebook/react/commit/d6cb4e771341ff82489c00f4907990cb8a75696b)
2024-09-11 08:49:16 -07:00
sebmarkbage c63274417d [Fizz] Use RequestInstance constructor for resuming (#30947)
We added enough fields to need a constructor instead of inline object in
V8.

We didn't update the resumeRequest path though so it wasn't using the
constructor and had a different hidden class.

DiffTrain build for [1bb056363c](https://github.com/facebook/react/commit/1bb056363c02fa9d188cc1122595d1587aa59d86)
2024-09-11 08:43:01 -07:00
sebmarkbage b8a98add1f [Fiber] Don't call performance.now() twice in a row (#30936)
DiffTrain build for [a5a7f1063e](https://github.com/facebook/react/commit/a5a7f1063e6f190c64c779b2aa54d28fb7b92cfb)
2024-09-10 13:54:18 -07:00
acdlite bf9385a46c Prerender during same pass if blocked anyway (#30879)
If something suspends in the shell — i.e. we won't replace the suspended
content with a fallback — we might as well prerender the siblings during
the current render pass, instead of spawning a separate prerender pass.

This is implemented by setting the "is prerendering" flag to true
whenever we suspend in the shell. But only if we haven't already skipped
over some siblings, because if so, then we need to schedule a separate
prerender pass regardless.

DiffTrain build for [66cf2cfc8a](https://github.com/facebook/react/commit/66cf2cfc8a8c4b09d2b783fd7302ae6b24150935)
2024-09-10 10:30:55 -07:00
sebmarkbage 4d30e52d65 [DevTools] Use Unicode Atom Symbol instead of Atom Emoji (#30832)
This reverts #19603.

Before:
<img width="724" alt="Screenshot 2024-08-28 at 12 07 29 AM"
src="https://github.com/user-attachments/assets/0613088f-c013-4f1c-92c3-fbdae8c1f109">

After:
<img width="771" alt="Screenshot 2024-08-28 at 12 08 13 AM"
src="https://github.com/user-attachments/assets/eef21bee-d11f-4f0a-9147-053a163f720f">

Consensus seems to be that while the purple on is a bit clearer and
easier to read. The purple is not on brand so it doesn't look like
React. It looks ugly. It's distracting (too eye catching). Taking away
attention from other tabs in an unfair way.

It also gets worse with more tabs added. We plan on both adding another
tab and panes inside other tabs (elements/sources) soon. Each needs to
be marked somehow as part of React but spelling it out is too long.
Putting inside a second tab means two clicks and takes away real-estate
from our extension and doesn't solve the problem with extension panes in
other tabs. We also plan on adding multiple different tracks to the
Performance tab which also needs a name other than just React and
spelling out React as a prefix is too long. The Emoji is too
distracting. So it seems best to uniformly apply the symbol - albeit it
might just look like a dot to many.

Dark mode looks close to on brand:

<img width="1089" alt="Screenshot 2024-08-28 at 12 32 50 AM"
src="https://github.com/user-attachments/assets/7175a540-4241-4c26-9e4d-4d367873af57">

DiffTrain build for [d160aa0fbb](https://github.com/facebook/react/commit/d160aa0fbb1bd2d00ea8c771c551c9cb5b47f1e9)
2024-09-09 21:16:50 -07:00
josephsavona eb67bf1b96 Fix useMemoCache with setState in render
Fixes the bug that @alexmckenley and @mofeiZ found where setState-in-render can reset useMemoCache and cause an infinite loop. The bug was that renderWithHooksAgain() was not resetting hook state when rerendering (so useMemo values were preserved) but was resetting the updateQueue. This meant that the entire memo cache was cleared on a setState-in-render.

The fix here is to call a new helper function to clear the update queue. It nulls out other properties, but for memoCache it just sets the index back to zero.

ghstack-source-id: fc0947ce21
Pull Request resolved: https://github.com/facebook/react/pull/30889

DiffTrain build for [727b361528](https://github.com/facebook/react/commit/727b3615287074ddaa28069bfbd2dfee8cf73575)
2024-09-06 14:40:38 -07:00
sebmarkbage 716cd41764 [Fiber] Move runWithFiberInDEV from CommitWork to CommitEffects (#30882)
Stacked on #30881.

Move `runWithFiberInDEV` from the recursive part of the commit phase and
instead wrap each call into user space. These should really map 1:1 with
where we're using `try/catch` since that's where we're calling into user
space.

The goal of this is to avoid the extra stack frames added by
`enableOwnerStacks` in the recursive parts to avoid stack overflow. This
way we only have a couple of extra at the end of the stack instead of a
couple of extra at every depth of the tree.

DiffTrain build for [a03254bc60](https://github.com/facebook/react/commit/a03254bc60b06c535c37e43c53b1fd40757b2ef4)
2024-09-05 18:04:06 -07:00
sebmarkbage 087bb0f0c0 [Fiber] Extract Functions that Call User Space and Host Configs in Commit to Separate Modules (#30881)
This is mostly just moves and same code extracted into utility
functions.

This is to help clarify what needs to be wrapped in try/catch and
runWithFiberInDEV. I'll do the runWithFiberInDEV changes in a follow up.

This leaves ReactCommitWork mostly to do matching on the tag and the
recursive loops.

DiffTrain build for [fe03c56d1e](https://github.com/facebook/react/commit/fe03c56d1e51379a18676b04cf185e76f04cd457)
2024-09-05 18:02:02 -07:00
acdlite 58fa44d4ba Schedule prerender after something suspends (#30800)
Adds the concept of a "prerender". These special renders are spawned
whenever something suspends (and we're not already prerendering).

The purpose is to move speculative rendering work into a separate phase
that does not block the UI from updating. For example, during a
transition, if something suspends, we should not speculatively prerender
siblings that will be replaced by a fallback in the UI until *after* the
fallback has been shown to the user.

DiffTrain build for [e10e868182](https://github.com/facebook/react/commit/e10e8681824e56c10fdb14e0359d878bcd748937)
2024-09-04 11:04:04 -07:00
acdlite 8e6990ed7c Temporarily disable suspending during work loop (#30762)
### Based on

- #30761
- #30759

---

`use` has an optimization where in some cases it can suspend the work
loop during the render phase until the data has resolved, rather than
unwind the stack and lose context. However, the current implementation
is not compatible with sibling prerendering. So I've temporarily
disabled it until the sibling prerendering has been refactored. We will
add it back in a later step.

DiffTrain build for [8b4c54c00f](https://github.com/facebook/react/commit/8b4c54c00f5c047a72a4cecc2689196786c3e5ff)
2024-09-04 09:47:07 -07:00
sebmarkbage 4b439b0743 [Fiber] Stash ThenableState on the Dependencies Object for Use By DevTools (#30866)
This lets us track what a Component might suspend on from DevTools. We
could already collect this by replaying a component's Hooks but that
would be expensive to collect from a whole tree.

The thenables themselves might contain useful information but mainly
we'd want access to the `_debugInfo` on the thenables which might
contain additional information from the server.

https://github.com/facebook/react/blob/19bd26beb689e554fceb0b929dc5199be8cba594/packages/shared/ReactTypes.js#L114

In a follow up we should really do something similar in Flight to
transfer `use()` on the debugInfo of that Server Component.

DiffTrain build for [8d68da3f73](https://github.com/facebook/react/commit/8d68da3f7396064614f34b84881fe8833b6039ac)
2024-09-03 13:12:48 -07:00
sebmarkbage fa5cb1600c Spawn new task if we hit stack overflow (#30419)
If we see the "Maximum call stack size exceeded" error we know we've hit
stack overflow. We can recover from this by spawning a new task and
trying again. Effectively a zero-cost trampoline in the normal case. The
new task will have a clean stack. If you have a lot of siblings at the
same depth that hits the limit you can end up hitting this once for each
sibling but within that new sibling you're unlikely to hit this again.
So it's not too expensive.

If it errors again in the retryTask pass, the other error handling takes
over which causes this to be able to still not infinitely stall. E.g.
when the component itself throws an error like this.

It's still better to increase the stack limit for performance if you
have a really deep tree but it doesn't really hurt to be able to recover
since it's zero cost when it doesn't happen.

We could do the same thing for Flight. Those trees don't tend to be as
deep but could happen.

DiffTrain build for [96aca5f4f3](https://github.com/facebook/react/commit/96aca5f4f3d7fbe0c13350f90031d8ec4c060ccb)
2024-08-27 10:18:58 -07:00
poteto f5a54b1e75 [ez] Remove trailing space from babel-refresh header
ghstack-source-id: d78c53462b
Pull Request resolved: https://github.com/facebook/react/pull/30806

DiffTrain build for [dcae56f8b7](https://github.com/facebook/react/commit/dcae56f8b72f625d8affe5729ca9991b31a492ac)
2024-08-26 10:34:06 -07:00
acdlite 800cc35d48 Fix: Synchronous popstate transitions (#30759)
This is a refactor of the fix in #27505.

When a transition update is scheduled by a popstate event, (i.e. a back/
forward navigation) we attempt to render it synchronously even though
it's a transition, since it's likely the previous page's data is cached.

In #27505, I changed the implementation so that it only "upgrades" the
priority of the transition for a single attempt. If the attempt
suspends, say because the data is not cached after all, from then on it
should be treated as a normal transition.

But it turns out #27505 did not work as intended, because it relied on
marking the root with pending synchronous work (root.pendingLanes),
which was never cleared until the popstate update completed.

The test scenarios I wrote accidentally worked for a different reason
related to suspending the work loop, which I'm currently in the middle
of refactoring.

DiffTrain build for [ee7f6757c4](https://github.com/facebook/react/commit/ee7f6757c446c4e79ecc7e2bc22b8c9b712834b7)
2024-08-23 09:38:02 -07:00
poteto d1fee4a2fe [ez] Add noformat etc headers into some files
These are only needed internally so I'm opting to just do it in the
commit artifacts job instead of amending the build config.

ghstack-source-id: 6a5382b028
Pull Request resolved: https://github.com/facebook/react/pull/30775

DiffTrain build for [1d989965a6](https://github.com/facebook/react/commit/1d989965a6aac11d71ecf28030796f5475a86642)
2024-08-21 08:57:13 -07:00
gnoff d533aef7ab [Fizz] use microtasks rather than tasks when scheduling work while prerendering (#30770)
Similar to https://github.com/facebook/react/pull/30768 we want to
schedule work during prerendering in microtasks both for the root task
and pings. We continue to schedule flushes as Tasks to allow as much
work to be batched up as possible.

DiffTrain build for [ab24f643d0](https://github.com/facebook/react/commit/ab24f643d0809ee09a7499862fef135fb09a0225)
2024-08-21 08:03:00 -07:00
gnoff d094ee1eec [Fizz][Static] when aborting a prerender halt unfinished boundaries instead of erroring (#30732)
When we introduced prerendering for flight we modeled an abort of a
flight prerender as having unfinished rows. This is similar to how
postpone was already implemented when you postponed from "within" a
prerender using React.unstable_postpone. However when aborting with a
postponed instance every boundary would be eagerly marked for client
rendering which is more akin to prerendering and then resuming with an
aborted signal.

The insight with the flight work was that it's not so much the postpone
that describes the intended semantics but the abort combined with a
prerender. So like in flight when you abort a prerender and enableHalt
is enabled boundaries and the shell won't error for any reason. Fizz
will still call onPostpone and onError according to the abort reason but
the consuemr of the prerender should expect to resume it before trying
to use it.

DiffTrain build for [85180b8cf8](https://github.com/facebook/react/commit/85180b8cf84274795986c8f2c8473f8816db8b7b)
2024-08-20 13:42:54 -07:00
gnoff 7420875c72 [Fizz] track postpones when aborting boundaries with a postpone (#30751)
When aborting with a postpone value boundaries are put into client
rendered mode even during prerenders. This doesn't follow the postpoen
semantics of the rest of fizz where during a prerender a postpone is
tracked and it will leave holes in tracked postpone state that can be
resumed. This change updates this behavior to match the postpones
semantics between aborts and imperative postpones.

DiffTrain build for [2505bf9b34](https://github.com/facebook/react/commit/2505bf9b3400c6a00381e86d30b495935f5339df)
2024-08-20 09:58:23 -07:00
gnoff 6f94ca81fd [Fizz] handle throwing after abort during render (#30730)
It is possible to throw after aborting during a render and we were not
properly tracking this. We use an AbortSigil to mark whether a rendering
task needs to abort but the throw interrupts that and we end up handling
an error on the error pathway instead.

This change reworks the abort-while-rendering support to be robust to
throws after calling abort

DiffTrain build for [7954db9398](https://github.com/facebook/react/commit/7954db9398b9afa962167577a6c6940be3856c39)
2024-08-16 18:39:11 -07:00
gaearon b41f0cd50d [Fresh] Always reset useMemoCache on Fast Refresh (#30700)
Stacked on https://github.com/facebook/react/pull/30662.

Alternative to https://github.com/facebook/react/pull/30663 and
https://github.com/facebook/react/pull/30677.

During a Fast Refresh, we always want to evict the memo cache, same as
we do with normal `useMemo`. The mechanism used by `useMemo` and other
Hooks is this module-level variable:

https://github.com/facebook/react/blob/fca5d655d78917400a2722287351c20938166669/packages/react-reconciler/src/ReactFiberHooks.js#L304-L307

which has DEV-only behavior as if the dependencies are always different:

https://github.com/facebook/react/blob/fca5d655d78917400a2722287351c20938166669/packages/react-reconciler/src/ReactFiberHooks.js#L451-L460

The `useMemoCache` Hook doesn't use a dependency array but conceptually
I think we want the same behavior.

## Test Plan

The test passes.

---------

Co-authored-by: Lauren Tan <poteto@users.noreply.github.com>

DiffTrain build for [7e8a06cf4c](https://github.com/facebook/react/commit/7e8a06cf4c628be45171da52c1a8e97f9869b7ee)
2024-08-14 17:11:16 -07:00
jackpope e3cf3d59b4 Fix unstable_useContextWithBailout dispatcher assignment (#30692)
One more copy pasta fix

Assignments are unique now
```
% cat packages/react-reconciler/src/ReactFiberHooks.js | grep .unstable_useContextWithBailout
function unstable_useContextWithBailout<T>(
  (ContextOnlyDispatcher: Dispatcher).unstable_useContextWithBailout =
  (HooksDispatcherOnMount: Dispatcher).unstable_useContextWithBailout =
    unstable_useContextWithBailout;
  (HooksDispatcherOnUpdate: Dispatcher).unstable_useContextWithBailout =
    unstable_useContextWithBailout;
  (HooksDispatcherOnRerender: Dispatcher).unstable_useContextWithBailout =
    unstable_useContextWithBailout;
    (HooksDispatcherOnMountInDEV: Dispatcher).unstable_useContextWithBailout =
        return unstable_useContextWithBailout(context, select);
    (HooksDispatcherOnMountWithHookTypesInDEV: Dispatcher).unstable_useContextWithBailout =
        return unstable_useContextWithBailout(context, select);
    (HooksDispatcherOnUpdateInDEV: Dispatcher).unstable_useContextWithBailout =
        return unstable_useContextWithBailout(context, select);
    (HooksDispatcherOnRerenderInDEV: Dispatcher).unstable_useContextWithBailout =
        return unstable_useContextWithBailout(context, select);
    (InvalidNestedHooksDispatcherOnMountInDEV: Dispatcher).unstable_useContextWithBailout =
        return unstable_useContextWithBailout(context, select);
    (InvalidNestedHooksDispatcherOnUpdateInDEV: Dispatcher).unstable_useContextWithBailout =
        return unstable_useContextWithBailout(context, select);
    (InvalidNestedHooksDispatcherOnRerenderInDEV: Dispatcher).unstable_useContextWithBailout =
        return unstable_useContextWithBailout(context, select);
```

DiffTrain build for [0ad0fac1dc](https://github.com/facebook/react/commit/0ad0fac1dc11db8d5a6831987fb0324cd6d59498)
2024-08-14 08:13:51 -07:00
jackpope b903fc08c5 Fix unstable_useContextWithBailout incorrect dispatcher assignment (#30673)
Fixing a mistaken copy from another dispatcher property assignment

DiffTrain build for [d48603a525](https://github.com/facebook/react/commit/d48603a52564675ce02152fff245e38b6816da47)
2024-08-13 08:40:45 -07:00
kassens 3221ff0d9f Remove flag enableUseDeferredValueInitialArg (#30595)
This is enabled everywhere for a while and I don't think we'd be backing
this out of 19. Seems like it's good to clean up to me.

DiffTrain build for [65903583d2](https://github.com/facebook/react/commit/65903583d2ab45aea45bdd23ed0b5dc214ff3c1c)
2024-08-05 08:32:25 -07:00
eps1lon 76d8d060b5 [Devtools] Ensure initial read of useFormStatus returns NotPendingTransition (#28728)
DiffTrain build for [88ee14ffa5](https://github.com/facebook/react/commit/88ee14ffa57beb0689f26f0c52c357e3ac446af8)
2024-08-01 02:03:31 -07:00
gnoff c8a80954f1 [Fizz] Update postpone abort semantics when prerendering (#30541)
When aborting with a postpone value in Fizz if any tasks are still
pending in the root while prerendering the prerender will fatally error.
This is different from postponing imperatively in a root task and really
the semantics should be the same. This change updates React to treat an
abort with a postpone value as a postponed root rather than a fatal
error.

DiffTrain build for [a7d1240c96](https://github.com/facebook/react/commit/a7d1240c962d2fdeac3ba31f1fdc12b5be4bbd2e)
2024-07-31 08:40:57 -07:00
gaearon 57f6b8f122 Remove RefreshRuntime.findAffectedHostInstances (#30538)
I originally added this with a plan to visualize which nodes got updated
after a Fast Refresh. I didn't end up implementing that part, and to my
knowledge, no actively used integration actually does that or use this
method.

- [Webpack plugin doesn't use
it](https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/f1c8b9a44198449093ca95f85af5df97925e1cfc/lib/runtime/RefreshUtils.js)
- [RN doesn't use
it](https://github.com/facebook/react-native/blob/23c5c42de01953ed7b8e8938c2d3a8fac82250a0/packages/react-native/Libraries/Core/setUpReactRefresh.js)
- [Global GitHub code
search](https://github.com/search?q=findAffectedHostInstances&type=code&p=1)
only shows copies of this code and the type definition based on it, but
not actual calls to it

We should be able to delete this without a problem.

DiffTrain build for [96f3093bec](https://github.com/facebook/react/commit/96f3093becc1f26e06549b9a54b93db9df8f5689)
2024-07-30 14:14:59 -07:00
sebmarkbage 53526c55b1 [Fiber] Make DevTools Config use Static Injection (#30522)
We use static dependency injection. We shouldn't use this dynamic
dependency injection we do for DevTools internals. There's also meta
programming like spreading and stuff that isn't needed.

This moves the config from `injectIntoDevTools` to the FiberConfig so it
can be statically resolved.

Closure Compiler has some trouble generating optimal code for this
anyway so ideally we'd refactor this further but at least this is better
and saves a few bytes and avoids some code paths (when minified).

DiffTrain build for [146df7c311](https://github.com/facebook/react/commit/146df7c311831a1d5b35f3783dae4a7030638fcf)
2024-07-30 12:11:01 -07:00