From b4af7599d5b770a41e8af899272c307f7fc7f9ad Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Wed, 25 Nov 2026 17:39:10 +0700 Subject: [PATCH] perf(app): keep overlays and long-running sessions fast (#10778) A dev window open for a few hours took twice as long to open the sidebar hover card as a fresh one. Three dependencies produced the cost: - Unistyles 3.2.4 web rewrote the whole stylesheet on every class add or remove. Backport upstream PR jpudysz/react-native-unistyles#1354 (3.8.0): classes become CSSOM rule inserts and deletes. - @gorhom/portal kept all portal state in one context value at the app root, so each portal change made React search every mounted fiber. Portal state now lives in a store each PortalHost subscribes to. Also backport gorhom/react-native-portal#62 so closing one overlay no longer remounts later overlays in the same host. - React 19.2 development builds never cleared their render timings. Backport the React 19.3.0 clearMeasures change. The shared stylesheet e2e helper counts rules inserted, deleted and edited for the whole interaction, so transient and in-place changes fail the explorer resize spec. Supersedes #10605. Co-authored-by: Marcel W. Wysocki --- docs/floating-panels.md | 16 + docs/unistyles.md | 11 +- .../explorer-resize-performance.spec.ts | 54 +- .../app/e2e/browser/sidebar-workspace.spec.ts | 30 + .../e2e/support/helpers/shared-stylesheet.ts | 151 + .../floating-panel-overlap.browser.test.tsx | 118 +- ...eact-development-measures.browser.test.tsx | 41 + patches/@gorhom+portal+1.0.14.patch | 468 +++ patches/react-dom+19.2.3.patch | 170 + patches/react-native-unistyles+3.2.4.patch | 2833 +++++++++++++---- scripts/postinstall-patches.mjs | 19 + 11 files changed, 3314 insertions(+), 597 deletions(-) create mode 100644 packages/app/e2e/support/helpers/shared-stylesheet.ts create mode 100644 packages/app/src/performance/react-development-measures.browser.test.tsx create mode 100644 patches/@gorhom+portal+1.0.14.patch create mode 100644 patches/react-dom+19.2.3.patch diff --git a/docs/floating-panels.md b/docs/floating-panels.md index 0d49f74b8c..2443d731c3 100644 --- a/docs/floating-panels.md +++ b/docs/floating-panels.md @@ -146,6 +146,22 @@ quietly relying on: The fix for transforms is Gotcha 3. The fix for context is Gotcha 7. +### The portal patch + +`patches/@gorhom+portal+1.0.14.patch` moves portal state out of the provider's +context value and into a store each `PortalHost` subscribes to. Upstream keeps +every host's portals in one context value at the app root, so each portal mount, +update and unmount changed that value and React searched every mounted fiber +for consumers. That cost grows with the retained panels: a hover card took +about 3 ms of it in a fresh window and 16 ms after a few hours. With the store, +a portal change renders only its own host. + +Do not put per-overlay state in a context that wraps the app for the same +reason. Give the consumers a store to subscribe to. + +The patch also keys each portal in its host (upstream PR #62). Without the key, +closing one overlay remounted every later overlay in the same host. + ## Gotcha 3 — Keyboard layout and portal anchors `composer/dock` owns the stationary viewport, bottom-anchored surface, composer diff --git a/docs/unistyles.md b/docs/unistyles.md index 98049998ff..f7de4384b5 100644 --- a/docs/unistyles.md +++ b/docs/unistyles.md @@ -86,7 +86,7 @@ mounts—never at module evaluation time. ## Dynamic Pixel Styles On Web -Avoid feeding changing pixel values such as `{ top, left }`, `{ maxHeight }`, or `{ minWidth }` into the `style` prop of Unistyles-managed React Native components on web. The web runtime hashes each distinct style object by value and appends a CSS rule to `#unistyles-web`; those rules are not reclaimed during the page lifetime, so pointer-driven positioning can turn into steady stylesheet growth. +Avoid feeding changing pixel values such as `{ top, left }`, `{ maxHeight }`, or `{ minWidth }` into the `style` prop of Unistyles-managed React Native components on web. The web runtime hashes each distinct style object by value and inserts a CSS rule into `#unistyles-web` for it, then deletes the rule when the last element using it unmounts. Pointer-driven positioning turns into a rule insert and delete per move. Use the inline style escape hatch below for high-churn values. Do not split a component into plain/web/native variants just to keep one measured value out of the CSS registry. Raw DOM wrappers are reserved for real DOM infrastructure, such as terminal hosts, virtualized web rows, or third-party drag wrappers. @@ -224,6 +224,7 @@ Quick confirmation in DevTools console: ```js [...document.styleSheets] .flatMap((s) => [...(s.cssRules || [])]) + .flatMap((r) => (r.cssRules ? [...r.cssRules] : [r])) .map((r) => r.cssText) .filter((t) => t.includes("unistyles") && t.includes("> *")); ``` @@ -366,6 +367,14 @@ colors. Keep this patch until upstream reads the scheme through separate lists. The desktop browser E2E checks both transition directions in an isolated Electron process, because Playwright's focus emulation prevents real hidden-page behavior. +The stylesheet patch backports upstream PR #1354 (3.8.0). Unistyles 3.2.4 rewrote +the whole text of `#unistyles-web` whenever a class was added or removed, and +the browser then restyled the entire document: about 5 ms each time, several +times for one hover card. The backport changes one CSSOM rule per class instead. +The tag therefore has no text; read its rules through `sheet.cssRules`. Classes +without a media query sit inside an `@media all` group. Assert on the stylesheet +in E2E with `packages/app/e2e/support/helpers/shared-stylesheet.ts`. + Register every dependency patch in `scripts/postinstall-patches.mjs`. A file in `patches/` is inert unless that script knows which installed package activates it. diff --git a/packages/app/e2e/browser/explorer-resize-performance.spec.ts b/packages/app/e2e/browser/explorer-resize-performance.spec.ts index ca2ec5bf13..f5884b1fee 100644 --- a/packages/app/e2e/browser/explorer-resize-performance.spec.ts +++ b/packages/app/e2e/browser/explorer-resize-performance.spec.ts @@ -1,17 +1,10 @@ import type { Page } from "@playwright/test"; import { test, expect } from "../support/fixtures"; import { runWorkspaceActionFromCommandCenter } from "../support/helpers/command-center-workspace-actions"; - -interface DragMeasurement { - observer: MutationObserver; - stylesheetMutations: number; -} - -declare global { - interface Window { - __PASEO_EXPLORER_DRAG_MEASUREMENT__?: DragMeasurement; - } -} +import { + readSharedStylesheetChanges, + rememberSharedStylesheet, +} from "../support/helpers/shared-stylesheet"; async function waitForResizePaint(page: Page): Promise { await page.evaluate( @@ -23,23 +16,8 @@ async function waitForResizePaint(page: Page): Promise { } async function beginResizeMeasurement(page: Page): Promise { - await page.evaluate(() => { - const stylesheet = document.getElementById("unistyles-web"); - if (!stylesheet) throw new Error("Shared stylesheet is missing"); - globalThis.__PASEO_RESET_RENDER_PROFILE__!(); - const measurement: DragMeasurement = { - stylesheetMutations: 0, - observer: new MutationObserver((records) => { - measurement.stylesheetMutations += records.length; - }), - }; - measurement.observer.observe(stylesheet, { - childList: true, - subtree: true, - characterData: true, - }); - window.__PASEO_EXPLORER_DRAG_MEASUREMENT__ = measurement; - }); + await page.evaluate(() => globalThis.__PASEO_RESET_RENDER_PROFILE__!()); + await rememberSharedStylesheet(page); } async function previewExplorerResize(page: Page, distance: number) { @@ -61,16 +39,14 @@ async function previewExplorerResize(page: Page, distance: number) { await waitForResizePaint(page); } const during = (await explorer.boundingBox())!.width; - const measurement = await page.evaluate(() => { - const state = window.__PASEO_EXPLORER_DRAG_MEASUREMENT__!; - state.observer.disconnect(); - return { - stylesheetMutations: state.stylesheetMutations, - paneRenders: Object.entries(globalThis.__PASEO_RENDER_PROFILE_REASONS__ ?? {}) + const measurement = { + stylesheetChanges: await readSharedStylesheetChanges(page), + paneRenders: await page.evaluate(() => + Object.entries(globalThis.__PASEO_RENDER_PROFILE_REASONS__ ?? {}) .filter(([id]) => id.startsWith("SplitPaneView:")) .reduce((sum, [, reasons]) => sum + (reasons.render ?? 0), 0), - }; - }); + ), + }; await page.mouse.up(); await waitForResizePaint(page); const after = (await explorer.boundingBox())!.width; @@ -92,7 +68,7 @@ async function expectExplorerWidthSurvivesReload(page: Page, width: number): Pro await expect.poll(async () => (await explorer.boundingBox())?.width).toBeCloseTo(width, 0); } -test("Explorer drag previews without rerendering panes or rewriting the shared stylesheet", async ({ +test("Explorer drag previews without rerendering panes or changing the shared stylesheet", async ({ page, withWorkspace, }) => { @@ -117,9 +93,9 @@ test("Explorer drag previews without rerendering panes or rewriting the shared s ).toBe(true); const grown = await previewExplorerResize(page, -100); const shrunk = await previewExplorerResize(page, 50); - expect(grown.stylesheetMutations).toBe(0); + expect(grown.stylesheetChanges).toEqual({ added: 0, removed: 0, edited: 0, rebuilt: 0 }); expect(grown.paneRenders).toBe(0); - expect(shrunk.stylesheetMutations).toBe(0); + expect(shrunk.stylesheetChanges).toEqual({ added: 0, removed: 0, edited: 0, rebuilt: 0 }); expect(shrunk.paneRenders).toBe(0); await expectExplorerWidthSurvivesReload(page, shrunk.width); }); diff --git a/packages/app/e2e/browser/sidebar-workspace.spec.ts b/packages/app/e2e/browser/sidebar-workspace.spec.ts index b445744046..068b75e213 100644 --- a/packages/app/e2e/browser/sidebar-workspace.spec.ts +++ b/packages/app/e2e/browser/sidebar-workspace.spec.ts @@ -25,6 +25,10 @@ import { projectEquivalenceViewKey } from "../support/helpers/project-view-key"; import { escapeRegex } from "../support/helpers/regex"; import { openFilesPanel } from "../support/helpers/workspace-tabs"; import { seedMockAgentWorkspace } from "../support/helpers/mock-agent"; +import { + readSharedStylesheetChanges, + rememberSharedStylesheet, +} from "../support/helpers/shared-stylesheet"; const GITHUB_REMOTE_URL = "https://github.com/test-owner/test-repo.git"; @@ -429,6 +433,32 @@ test.describe("Sidebar workspace list", () => { } }); + test("workspace hover card opens and closes without rebuilding the shared stylesheet", async ({ + page, + }) => { + const workspace = await seedWorkspace({ repoPrefix: "sidebar-hover-stylesheet-" }); + + try { + await gotoAppShell(page); + await waitForSidebarProject(page, path.basename(workspace.repoPath)); + await movePointerAwayFromWorkspaceHoverCard(page); + await rememberSharedStylesheet(page); + + await openWorkspaceHoverCard(page, workspace.workspaceId); + const opened = await readSharedStylesheetChanges(page); + // The card brings styles nothing else on screen uses, so the stylesheet has to grow. + expect(opened.added).toBeGreaterThan(0); + expect(opened.rebuilt).toBe(0); + + await rememberSharedStylesheet(page); + await movePointerAwayFromWorkspaceHoverCard(page); + await expectWorkspaceHoverCardClosed(page); + expect((await readSharedStylesheetChanges(page)).rebuilt).toBe(0); + } finally { + await workspace.cleanup(); + } + }); + test("workspace hover card closes when the pointer leaves a clicked row", async ({ page }) => { const workspace = await seedWorkspace({ repoPrefix: "sidebar-hover-click-leave-" }); diff --git a/packages/app/e2e/support/helpers/shared-stylesheet.ts b/packages/app/e2e/support/helpers/shared-stylesheet.ts new file mode 100644 index 0000000000..f5cdb0e066 --- /dev/null +++ b/packages/app/e2e/support/helpers/shared-stylesheet.ts @@ -0,0 +1,151 @@ +import type { Page } from "@playwright/test"; + +/** + * The shared stylesheet is `#unistyles-web`: one rule per generated style class, for the whole app. + * Every change to it makes the browser restyle, and replacing a rule that is still in use restyles + * the entire document. A spec remembers the stylesheet, performs an interaction, and reads back + * everything that happened to it in between, including rules that came and went before the read. + */ +export interface SharedStylesheetChanges { + /** Rules inserted, counting ones deleted again before the read. */ + added: number; + /** Rules deleted, counting ones inserted during the interaction. */ + removed: number; + /** Rules whose declarations were changed in place. */ + edited: number; + /** Rules for classes still in use that were thrown away and created again. */ + rebuilt: number; +} + +interface SharedStylesheetRule { + rule: CSSRule; + text: string; +} + +interface SharedStylesheetWatch { + rules: Map; + added: number; + removed: number; + edited: number; + editedRules: Set; +} + +declare global { + interface Window { + __PASEO_SHARED_STYLESHEET_WATCH__?: SharedStylesheetWatch; + } +} + +function readSharedStylesheetRules(): Map { + const tag = document.getElementById("unistyles-web"); + if (!(tag instanceof HTMLStyleElement) || !tag.sheet) { + throw new Error("Shared stylesheet is missing"); + } + const rules = new Map(); + const collect = (list: CSSRuleList, group: string) => { + for (const rule of list) { + if (rule instanceof CSSStyleRule) { + rules.set(`${group}${rule.selectorText}`, { rule, text: rule.cssText }); + } else if (rule instanceof CSSMediaRule) { + collect(rule.cssRules, `${rule.conditionText} `); + } + } + }; + collect(tag.sheet.cssRules, ""); + return rules; +} + +// The CSSOM has no mutation events, so the watch wraps the calls that change a stylesheet and +// counts the ones that land in the shared stylesheet, including changes undone before the read. +// Chromium sets named properties such as `style.width` without an accessor the watch can wrap; +// reading the changes compares rule text to catch those. Installed once per page. +function installSharedStylesheetWatch(): void { + const marker = "__PASEO_SHARED_STYLESHEET_WATCHED__"; + const flags = window as unknown as Record; + if (flags[marker]) return; + flags[marker] = true; + + const isShared = (sheet: CSSStyleSheet | null | undefined) => { + const tag = document.getElementById("unistyles-web"); + return Boolean(sheet) && tag instanceof HTMLStyleElement && sheet === tag.sheet; + }; + const watch = () => window.__PASEO_SHARED_STYLESHEET_WATCH__; + const wrapMethod = ( + prototype: object, + name: string, + owner: (target: Target) => CSSStyleSheet | null | undefined, + record: (target: Target) => void, + ) => { + const original = Reflect.get(prototype, name) as (...args: unknown[]) => unknown; + Reflect.set(prototype, name, function (this: Target, ...args: unknown[]) { + const result = original.apply(this, args); + if (isShared(owner(this))) record(this); + return result; + }); + }; + const countAdded = () => { + const current = watch(); + if (current) current.added += 1; + }; + const countRemoved = () => { + const current = watch(); + if (current) current.removed += 1; + }; + const countEdited = (style: CSSStyleDeclaration) => { + const current = watch(); + if (!current) return; + current.edited += 1; + if (style.parentRule) current.editedRules.add(style.parentRule); + }; + const sheetOf = (sheet: CSSStyleSheet) => sheet; + const groupSheet = (group: CSSGroupingRule) => group.parentStyleSheet; + const declarationSheet = (style: CSSStyleDeclaration) => style.parentRule?.parentStyleSheet; + + wrapMethod(CSSStyleSheet.prototype, "insertRule", sheetOf, countAdded); + wrapMethod(CSSStyleSheet.prototype, "deleteRule", sheetOf, countRemoved); + wrapMethod(CSSGroupingRule.prototype, "insertRule", groupSheet, countAdded); + wrapMethod(CSSGroupingRule.prototype, "deleteRule", groupSheet, countRemoved); + wrapMethod(CSSStyleDeclaration.prototype, "setProperty", declarationSheet, countEdited); + wrapMethod(CSSStyleDeclaration.prototype, "removeProperty", declarationSheet, countEdited); + + const cssText = Object.getOwnPropertyDescriptor(CSSStyleDeclaration.prototype, "cssText"); + const setCssText = cssText?.set; + if (!cssText || !setCssText) throw new Error("CSSStyleDeclaration.cssText has no setter"); + Object.defineProperty(CSSStyleDeclaration.prototype, "cssText", { + ...cssText, + set(this: CSSStyleDeclaration, value: string) { + setCssText.call(this, value); + if (isShared(declarationSheet(this))) countEdited(this); + }, + }); +} + +export async function rememberSharedStylesheet(page: Page): Promise { + await page.evaluate(`(() => { + (${installSharedStylesheetWatch.toString()})(); + window.__PASEO_SHARED_STYLESHEET_WATCH__ = { + rules: (${readSharedStylesheetRules.toString()})(), + added: 0, + removed: 0, + edited: 0, + editedRules: new Set(), + }; + })()`); +} + +export async function readSharedStylesheetChanges(page: Page): Promise { + return page.evaluate(`(() => { + const watch = window.__PASEO_SHARED_STYLESHEET_WATCH__; + if (!watch) throw new Error("Shared stylesheet was not remembered"); + const after = (${readSharedStylesheetRules.toString()})(); + let edited = watch.edited; + let rebuilt = 0; + for (const [selector, { rule, text }] of after) { + const before = watch.rules.get(selector); + if (!before) continue; + if (before.rule !== rule) rebuilt += 1; + else if (before.text !== text && !watch.editedRules.has(rule)) edited += 1; + } + return { added: watch.added, removed: watch.removed, edited, rebuilt }; + })()`); +} diff --git a/packages/app/src/components/ui/floating-panel-overlap.browser.test.tsx b/packages/app/src/components/ui/floating-panel-overlap.browser.test.tsx index ae96ccecee..db5283cbce 100644 --- a/packages/app/src/components/ui/floating-panel-overlap.browser.test.tsx +++ b/packages/app/src/components/ui/floating-panel-overlap.browser.test.tsx @@ -1,15 +1,27 @@ -import React, { act } from "react"; +import React, { act, Profiler, useEffect, useState } from "react"; import { createRoot } from "react-dom/client"; import { describe, expect, test } from "vitest"; -import { Portal, PortalProvider } from "@gorhom/portal"; +import { Portal, PortalHost, PortalProvider } from "@gorhom/portal"; import { FloatingPanelPortalHost, measureFloatingPanelPortalHost } from "./floating-panel-portal"; +async function mount(element: React.ReactElement) { + const container = document.createElement("div"); + container.style.cssText = "position:relative;width:800px;height:600px"; + document.body.appendChild(container); + const root = createRoot(container); + await act(async () => root.render(element)); + return { + container, + render: (next: React.ReactElement) => act(async () => root.render(next)), + unmount: async () => { + await act(async () => root.unmount()); + container.remove(); + }, + }; +} + describe("Floating panel host lifetime", () => { test("removing the newest host preserves the surviving host measurement", async () => { - const container = document.createElement("div"); - container.style.cssText = "position:relative;width:800px;height:600px"; - document.body.appendChild(container); - const root = createRoot(container); function Content({ overlap }: { overlap: boolean }) { return ( @@ -21,20 +33,106 @@ describe("Floating panel host lifetime", () => { ); } + const view = await mount(); try { - await act(async () => root.render()); expect(await measureFloatingPanelPortalHost("workspace")).toMatchObject({ width: 800, height: 600, }); - await act(async () => root.render()); + await view.render(); expect(await measureFloatingPanelPortalHost("workspace")).toMatchObject({ width: 800, height: 600, }); } finally { - await act(async () => root.unmount()); - container.remove(); + await view.unmount(); + } + }); +}); + +const rendered: string[] = []; + +function record(id: string) { + rendered.push(id); +} + +describe("Portal hosts", () => { + test("opening a portal renders its own host and no other", async () => { + let setCardOpen: (open: boolean) => void = () => {}; + function Card() { + const [open, setOpen] = useState(false); + setCardOpen = setOpen; + if (!open) return null; + return ( + +
Workspace
+
+ ); + } + const view = await mount( + + + + + + + + + , + ); + try { + rendered.length = 0; + await act(async () => setCardOpen(true)); + + expect(view.container.querySelector('[data-testid="card"]')?.textContent).toBe("Workspace"); + expect(rendered).toContain("sidebar"); + expect(rendered).not.toContain("workspace"); + + rendered.length = 0; + await act(async () => setCardOpen(false)); + + expect(view.container.querySelector('[data-testid="card"]')).toBeNull(); + expect(rendered).not.toContain("workspace"); + } finally { + await view.unmount(); + } + }); + + test("closing an earlier portal keeps a later portal mounted", async () => { + let menuMounts = 0; + function Menu() { + useEffect(() => { + menuMounts += 1; + }, []); + return
Menu
; + } + function Content({ tooltip }: { tooltip: boolean }) { + return ( + + + {tooltip && ( + + Tooltip + + )} + + + + + ); + } + const view = await mount(); + try { + expect(view.container.querySelector('[data-testid="tooltip"]')).not.toBeNull(); + expect(menuMounts).toBe(1); + + await view.render(); + + expect(view.container.querySelector('[data-testid="tooltip"]')).toBeNull(); + expect(view.container.querySelector('[data-testid="menu"]')).not.toBeNull(); + expect(menuMounts).toBe(1); + } finally { + await view.unmount(); } }); }); diff --git a/packages/app/src/performance/react-development-measures.browser.test.tsx b/packages/app/src/performance/react-development-measures.browser.test.tsx new file mode 100644 index 0000000000..860237911a --- /dev/null +++ b/packages/app/src/performance/react-development-measures.browser.test.tsx @@ -0,0 +1,41 @@ +import React, { act, useState } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, test } from "vitest"; + +let setLabel: (label: string) => void = () => {}; + +function Row({ label }: { label: string }) { + return
{label}
; +} + +function List() { + const [label, setState] = useState("first"); + setLabel = setState; + return ; +} + +function reactMeasures(): PerformanceEntry[] { + return performance + .getEntriesByType("measure") + .filter((entry) => JSON.stringify((entry as PerformanceMeasure).detail ?? "").includes("⚛")); +} + +// React's development build reports renders to the browser's performance timeline. The browser +// keeps every measure for the life of the page, so a long session held millions of them. +test("React's development render timings do not pile up in the performance timeline", async () => { + const container = document.createElement("div"); + document.body.appendChild(container); + const root = createRoot(container); + try { + await act(async () => root.render()); + for (const label of ["second", "third", "fourth"]) { + await act(async () => setLabel(label)); + } + + expect(container.textContent).toBe("fourth"); + expect(reactMeasures()).toHaveLength(0); + } finally { + await act(async () => root.unmount()); + container.remove(); + } +}); diff --git a/patches/@gorhom+portal+1.0.14.patch b/patches/@gorhom+portal+1.0.14.patch new file mode 100644 index 0000000000..7e293fbcb8 --- /dev/null +++ b/patches/@gorhom+portal+1.0.14.patch @@ -0,0 +1,468 @@ +diff --git a/node_modules/@gorhom/portal/lib/commonjs/components/portalHost/PortalHost.js b/node_modules/@gorhom/portal/lib/commonjs/components/portalHost/PortalHost.js +index 72ba2a7..e2f32a5 100644 +--- a/node_modules/@gorhom/portal/lib/commonjs/components/portalHost/PortalHost.js ++++ b/node_modules/@gorhom/portal/lib/commonjs/components/portalHost/PortalHost.js +@@ -34,7 +34,11 @@ const PortalHostComponent = ({ + }, []); //#endregion + //#region render + +- return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, state.map(item => item.node)); //#endregion ++ // Backport of https://github.com/gorhom/react-native-portal/pull/62: without a key, removing a ++ // portal shifts the ones after it and React remounts them. ++ return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, state.map(item => /*#__PURE__*/_react.default.createElement(_react.default.Fragment, { ++ key: item.name ++ }, item.node))); //#endregion + }; + + const PortalHost = /*#__PURE__*/(0, _react.memo)(PortalHostComponent); +diff --git a/node_modules/@gorhom/portal/lib/commonjs/components/portalProvider/PortalProvider.js b/node_modules/@gorhom/portal/lib/commonjs/components/portalProvider/PortalProvider.js +index 3b2a494..af6616e 100644 +--- a/node_modules/@gorhom/portal/lib/commonjs/components/portalProvider/PortalProvider.js ++++ b/node_modules/@gorhom/portal/lib/commonjs/components/portalProvider/PortalProvider.js +@@ -11,9 +11,7 @@ var _PortalHost = require("../portalHost/PortalHost"); + + var _portal = require("../../contexts/portal"); + +-var _constants = require("../../state/constants"); +- +-var _reducer = require("../../state/reducer"); ++var _store = require("../../state/store"); + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + +@@ -24,11 +22,11 @@ const PortalProviderComponent = ({ + shouldAddRootHost = true, + children + }) => { +- const [state, dispatch] = (0, _react.useReducer)(_reducer.reducer, _constants.INITIAL_STATE); ++ const [store] = (0, _react.useState)(_store.createPortalStore); + return /*#__PURE__*/_react.default.createElement(_portal.PortalDispatchContext.Provider, { +- value: dispatch ++ value: store.dispatch + }, /*#__PURE__*/_react.default.createElement(_portal.PortalStateContext.Provider, { +- value: state ++ value: store + }, children, shouldAddRootHost && /*#__PURE__*/_react.default.createElement(_PortalHost.PortalHost, { + name: rootHostName + }))); +diff --git a/node_modules/@gorhom/portal/lib/commonjs/hooks/usePortalState.js b/node_modules/@gorhom/portal/lib/commonjs/hooks/usePortalState.js +index 7a18089..77a8e24 100644 +--- a/node_modules/@gorhom/portal/lib/commonjs/hooks/usePortalState.js ++++ b/node_modules/@gorhom/portal/lib/commonjs/hooks/usePortalState.js +@@ -10,13 +10,15 @@ var _react = require("react"); + var _portal = require("../contexts/portal"); + + const usePortalState = hostName => { +- const state = (0, _react.useContext)(_portal.PortalStateContext); ++ const store = (0, _react.useContext)(_portal.PortalStateContext); + +- if (state === null) { ++ if (store === null) { + throw new Error("'PortalStateContext' cannot be null, please add 'PortalProvider' to the root component."); + } + +- return state[hostName] || []; ++ const getPortals = () => store.getPortals(hostName); ++ ++ return (0, _react.useSyncExternalStore)(store.subscribe, getPortals, getPortals); + }; + + exports.usePortalState = usePortalState; +diff --git a/node_modules/@gorhom/portal/lib/commonjs/state/reducer.js b/node_modules/@gorhom/portal/lib/commonjs/state/reducer.js +index 158e729..cd50661 100644 +--- a/node_modules/@gorhom/portal/lib/commonjs/state/reducer.js ++++ b/node_modules/@gorhom/portal/lib/commonjs/state/reducer.js +@@ -31,17 +31,15 @@ const addUpdatePortal = (state, hostName, portalName, node) => { + */ + + +- const index = state[hostName].findIndex(item => item.name === portalName); +- +- if (index !== -1) { +- state[hostName][index].node = node; +- } else { +- state[hostName].push({ +- name: portalName, +- node +- }); +- } +- ++ // Paseo patch: a changed host gets a new array, so the store can hand each host its own ++ // snapshot and only the host whose portals changed renders. ++ const portals = state[hostName]; ++ const index = portals.findIndex(item => item.name === portalName); ++ const portal = { ++ name: portalName, ++ node ++ }; ++ state[hostName] = index !== -1 ? portals.map(item => item.name === portalName ? portal : item) : [...portals, portal]; + return state; + }; + +@@ -56,7 +54,11 @@ const removePortal = (state, hostName, portalName) => { + } + + const index = state[hostName].findIndex(item => item.name === portalName); +- if (index !== -1) state[hostName].splice(index, 1); ++ ++ if (index !== -1) { ++ state[hostName] = state[hostName].filter(item => item.name !== portalName); ++ } ++ + return state; + }; + +diff --git a/node_modules/@gorhom/portal/lib/commonjs/state/store.js b/node_modules/@gorhom/portal/lib/commonjs/state/store.js +new file mode 100644 +index 0000000..0da9a5c +--- /dev/null ++++ b/node_modules/@gorhom/portal/lib/commonjs/state/store.js +@@ -0,0 +1,34 @@ ++"use strict"; ++ ++Object.defineProperty(exports, "__esModule", { ++ value: true ++}); ++exports.createPortalStore = void 0; ++ ++var _constants = require("./constants"); ++ ++var _reducer = require("./reducer"); ++ ++const NO_PORTALS = []; ++// Paseo patch: portal state lives in a store, outside React state. Held in the provider's context ++// value it changed on every portal add, update and remove, and React then walked every fiber under ++// the provider (the whole app) to find the hosts consuming it. Hosts subscribe here instead. ++const createPortalStore = () => { ++ let state = _constants.INITIAL_STATE; ++ const listeners = new Set(); ++ return { ++ getPortals: hostName => state[hostName] || NO_PORTALS, ++ dispatch: action => { ++ state = (0, _reducer.reducer)(state, action); ++ listeners.forEach(listener => listener()); ++ }, ++ subscribe: listener => { ++ listeners.add(listener); ++ return () => { ++ listeners.delete(listener); ++ }; ++ } ++ }; ++}; ++ ++exports.createPortalStore = createPortalStore; +diff --git a/node_modules/@gorhom/portal/lib/module/components/portalHost/PortalHost.js b/node_modules/@gorhom/portal/lib/module/components/portalHost/PortalHost.js +index d22cc16..e492b4b 100644 +--- a/node_modules/@gorhom/portal/lib/module/components/portalHost/PortalHost.js ++++ b/node_modules/@gorhom/portal/lib/module/components/portalHost/PortalHost.js +@@ -21,7 +21,11 @@ const PortalHostComponent = ({ + }, []); //#endregion + //#region render + +- return /*#__PURE__*/React.createElement(React.Fragment, null, state.map(item => item.node)); //#endregion ++ // Backport of https://github.com/gorhom/react-native-portal/pull/62: without a key, removing a ++ // portal shifts the ones after it and React remounts them. ++ return /*#__PURE__*/React.createElement(React.Fragment, null, state.map(item => /*#__PURE__*/React.createElement(React.Fragment, { ++ key: item.name ++ }, item.node))); //#endregion + }; + + export const PortalHost = /*#__PURE__*/memo(PortalHostComponent); +diff --git a/node_modules/@gorhom/portal/lib/module/components/portalProvider/PortalProvider.js b/node_modules/@gorhom/portal/lib/module/components/portalProvider/PortalProvider.js +index 522a08a..d2e07b6 100644 +--- a/node_modules/@gorhom/portal/lib/module/components/portalProvider/PortalProvider.js ++++ b/node_modules/@gorhom/portal/lib/module/components/portalProvider/PortalProvider.js +@@ -1,19 +1,18 @@ +-import React, { memo, useReducer } from 'react'; ++import React, { memo, useState } from 'react'; + import { PortalHost } from '../portalHost/PortalHost'; + import { PortalDispatchContext, PortalStateContext } from '../../contexts/portal'; +-import { INITIAL_STATE } from '../../state/constants'; +-import { reducer } from '../../state/reducer'; ++import { createPortalStore } from '../../state/store'; + + const PortalProviderComponent = ({ + rootHostName = 'root', + shouldAddRootHost = true, + children + }) => { +- const [state, dispatch] = useReducer(reducer, INITIAL_STATE); ++ const [store] = useState(createPortalStore); + return /*#__PURE__*/React.createElement(PortalDispatchContext.Provider, { +- value: dispatch ++ value: store.dispatch + }, /*#__PURE__*/React.createElement(PortalStateContext.Provider, { +- value: state ++ value: store + }, children, shouldAddRootHost && /*#__PURE__*/React.createElement(PortalHost, { + name: rootHostName + }))); +diff --git a/node_modules/@gorhom/portal/lib/module/hooks/usePortalState.js b/node_modules/@gorhom/portal/lib/module/hooks/usePortalState.js +index c82cc71..daee3ac 100644 +--- a/node_modules/@gorhom/portal/lib/module/hooks/usePortalState.js ++++ b/node_modules/@gorhom/portal/lib/module/hooks/usePortalState.js +@@ -1,12 +1,14 @@ +-import { useContext } from 'react'; ++import { useContext, useSyncExternalStore } from 'react'; + import { PortalStateContext } from '../contexts/portal'; + export const usePortalState = hostName => { +- const state = useContext(PortalStateContext); ++ const store = useContext(PortalStateContext); + +- if (state === null) { ++ if (store === null) { + throw new Error("'PortalStateContext' cannot be null, please add 'PortalProvider' to the root component."); + } + +- return state[hostName] || []; ++ const getPortals = () => store.getPortals(hostName); ++ ++ return useSyncExternalStore(store.subscribe, getPortals, getPortals); + }; + //# sourceMappingURL=usePortalState.js.map +\ No newline at end of file +diff --git a/node_modules/@gorhom/portal/lib/module/state/reducer.js b/node_modules/@gorhom/portal/lib/module/state/reducer.js +index cad5f28..51f7124 100644 +--- a/node_modules/@gorhom/portal/lib/module/state/reducer.js ++++ b/node_modules/@gorhom/portal/lib/module/state/reducer.js +@@ -23,17 +23,15 @@ const addUpdatePortal = (state, hostName, portalName, node) => { + */ + + +- const index = state[hostName].findIndex(item => item.name === portalName); +- +- if (index !== -1) { +- state[hostName][index].node = node; +- } else { +- state[hostName].push({ +- name: portalName, +- node +- }); +- } +- ++ // Paseo patch: a changed host gets a new array, so the store can hand each host its own ++ // snapshot and only the host whose portals changed renders. ++ const portals = state[hostName]; ++ const index = portals.findIndex(item => item.name === portalName); ++ const portal = { ++ name: portalName, ++ node ++ }; ++ state[hostName] = index !== -1 ? portals.map(item => item.name === portalName ? portal : item) : [...portals, portal]; + return state; + }; + +@@ -48,7 +46,11 @@ const removePortal = (state, hostName, portalName) => { + } + + const index = state[hostName].findIndex(item => item.name === portalName); +- if (index !== -1) state[hostName].splice(index, 1); ++ ++ if (index !== -1) { ++ state[hostName] = state[hostName].filter(item => item.name !== portalName); ++ } ++ + return state; + }; + +diff --git a/node_modules/@gorhom/portal/lib/module/state/store.js b/node_modules/@gorhom/portal/lib/module/state/store.js +new file mode 100644 +index 0000000..2c94075 +--- /dev/null ++++ b/node_modules/@gorhom/portal/lib/module/state/store.js +@@ -0,0 +1,23 @@ ++import { INITIAL_STATE } from './constants'; ++import { reducer } from './reducer'; ++const NO_PORTALS = []; ++// Paseo patch: portal state lives in a store, outside React state. Held in the provider's context ++// value it changed on every portal add, update and remove, and React then walked every fiber under ++// the provider (the whole app) to find the hosts consuming it. Hosts subscribe here instead. ++export const createPortalStore = () => { ++ let state = INITIAL_STATE; ++ const listeners = new Set(); ++ return { ++ getPortals: hostName => state[hostName] || NO_PORTALS, ++ dispatch: action => { ++ state = reducer(state, action); ++ listeners.forEach(listener => listener()); ++ }, ++ subscribe: listener => { ++ listeners.add(listener); ++ return () => { ++ listeners.delete(listener); ++ }; ++ } ++ }; ++}; +diff --git a/node_modules/@gorhom/portal/src/components/portalHost/PortalHost.tsx b/node_modules/@gorhom/portal/src/components/portalHost/PortalHost.tsx +index 62a2103..699765e 100644 +--- a/node_modules/@gorhom/portal/src/components/portalHost/PortalHost.tsx ++++ b/node_modules/@gorhom/portal/src/components/portalHost/PortalHost.tsx +@@ -20,7 +20,15 @@ const PortalHostComponent = ({ name }: PortalHostProps) => { + //#endregion + + //#region render +- return <>{state.map(item => item.node)}; ++ // Backport of https://github.com/gorhom/react-native-portal/pull/62: without a key, removing a ++ // portal shifts the ones after it and React remounts them. ++ return ( ++ <> ++ {state.map(item => ( ++ {item.node} ++ ))} ++ ++ ); + //#endregion + }; + +diff --git a/node_modules/@gorhom/portal/src/components/portalProvider/PortalProvider.tsx b/node_modules/@gorhom/portal/src/components/portalProvider/PortalProvider.tsx +index 8350171..f91273a 100644 +--- a/node_modules/@gorhom/portal/src/components/portalProvider/PortalProvider.tsx ++++ b/node_modules/@gorhom/portal/src/components/portalProvider/PortalProvider.tsx +@@ -1,11 +1,10 @@ +-import React, { memo, useReducer } from 'react'; ++import React, { memo, useState } from 'react'; + import { PortalHost } from '../portalHost/PortalHost'; + import { + PortalDispatchContext, + PortalStateContext, + } from '../../contexts/portal'; +-import { INITIAL_STATE } from '../../state/constants'; +-import { reducer } from '../../state/reducer'; ++import { createPortalStore } from '../../state/store'; + import type { PortalProviderProps } from './types'; + + const PortalProviderComponent = ({ +@@ -13,10 +12,10 @@ const PortalProviderComponent = ({ + shouldAddRootHost = true, + children, + }: PortalProviderProps) => { +- const [state, dispatch] = useReducer(reducer, INITIAL_STATE); ++ const [store] = useState(createPortalStore); + return ( +- +- ++ ++ + {children} + {shouldAddRootHost && } + +diff --git a/node_modules/@gorhom/portal/src/contexts/portal.ts b/node_modules/@gorhom/portal/src/contexts/portal.ts +index 2e3a46f..85ff020 100644 +--- a/node_modules/@gorhom/portal/src/contexts/portal.ts ++++ b/node_modules/@gorhom/portal/src/contexts/portal.ts +@@ -1,10 +1,7 @@ + import { createContext } from 'react'; ++import type { PortalStore } from '../state/store'; + import type { ActionTypes } from '../state/types'; +-import type { PortalType } from '../types'; + +-export const PortalStateContext = createContext +-> | null>(null); ++export const PortalStateContext = createContext(null); + export const PortalDispatchContext = + createContext | null>(null); +diff --git a/node_modules/@gorhom/portal/src/hooks/usePortalState.ts b/node_modules/@gorhom/portal/src/hooks/usePortalState.ts +index 64bb180..d9877c3 100644 +--- a/node_modules/@gorhom/portal/src/hooks/usePortalState.ts ++++ b/node_modules/@gorhom/portal/src/hooks/usePortalState.ts +@@ -1,14 +1,16 @@ +-import { useContext } from 'react'; ++import { useContext, useSyncExternalStore } from 'react'; + import { PortalStateContext } from '../contexts/portal'; + + export const usePortalState = (hostName: string) => { +- const state = useContext(PortalStateContext); ++ const store = useContext(PortalStateContext); + +- if (state === null) { ++ if (store === null) { + throw new Error( + "'PortalStateContext' cannot be null, please add 'PortalProvider' to the root component." + ); + } + +- return state[hostName] || []; ++ const getPortals = () => store.getPortals(hostName); ++ ++ return useSyncExternalStore(store.subscribe, getPortals, getPortals); + }; +diff --git a/node_modules/@gorhom/portal/src/state/reducer.ts b/node_modules/@gorhom/portal/src/state/reducer.ts +index 37f2414..1370244 100644 +--- a/node_modules/@gorhom/portal/src/state/reducer.ts ++++ b/node_modules/@gorhom/portal/src/state/reducer.ts +@@ -38,15 +38,15 @@ const addUpdatePortal = ( + /** + * updated portal, if it was already added. + */ +- const index = state[hostName].findIndex(item => item.name === portalName); +- if (index !== -1) { +- state[hostName][index].node = node; +- } else { +- state[hostName].push({ +- name: portalName, +- node, +- }); +- } ++ // Paseo patch: a changed host gets a new array, so the store can hand each host its own ++ // snapshot and only the host whose portals changed renders. ++ const portals = state[hostName]; ++ const index = portals.findIndex(item => item.name === portalName); ++ const portal = { name: portalName, node }; ++ state[hostName] = ++ index !== -1 ++ ? portals.map(item => (item.name === portalName ? portal : item)) ++ : [...portals, portal]; + return state; + }; + +@@ -65,7 +65,9 @@ const removePortal = ( + } + + const index = state[hostName].findIndex(item => item.name === portalName); +- if (index !== -1) state[hostName].splice(index, 1); ++ if (index !== -1) { ++ state[hostName] = state[hostName].filter(item => item.name !== portalName); ++ } + return state; + }; + +diff --git a/node_modules/@gorhom/portal/src/state/store.ts b/node_modules/@gorhom/portal/src/state/store.ts +new file mode 100644 +index 0000000..4acf035 +--- /dev/null ++++ b/node_modules/@gorhom/portal/src/state/store.ts +@@ -0,0 +1,30 @@ ++import { INITIAL_STATE } from './constants'; ++import { reducer } from './reducer'; ++import type { PortalType } from '../types'; ++import type { ActionTypes } from './types'; ++ ++const NO_PORTALS: Array = []; ++ ++// Paseo patch: portal state lives in a store, outside React state. Held in the provider's context ++// value it changed on every portal add, update and remove, and React then walked every fiber under ++// the provider (the whole app) to find the hosts consuming it. Hosts subscribe here instead. ++export const createPortalStore = () => { ++ let state: Record> = INITIAL_STATE; ++ const listeners = new Set<() => void>(); ++ ++ return { ++ getPortals: (hostName: string) => state[hostName] || NO_PORTALS, ++ dispatch: (action: ActionTypes) => { ++ state = reducer(state, action); ++ listeners.forEach(listener => listener()); ++ }, ++ subscribe: (listener: () => void) => { ++ listeners.add(listener); ++ return () => { ++ listeners.delete(listener); ++ }; ++ }, ++ }; ++}; ++ ++export type PortalStore = ReturnType; diff --git a/patches/react-dom+19.2.3.patch b/patches/react-dom+19.2.3.patch new file mode 100644 index 0000000000..91257ac033 --- /dev/null +++ b/patches/react-dom+19.2.3.patch @@ -0,0 +1,170 @@ +diff --git a/node_modules/react-dom/cjs/react-dom-client.development.js b/node_modules/react-dom/cjs/react-dom-client.development.js +index 771ecad..3d9bf72 100644 +--- a/node_modules/react-dom/cjs/react-dom-client.development.js ++++ b/node_modules/react-dom/cjs/react-dom-client.development.js +@@ -4073,6 +4073,8 @@ + ? "Idle" + : "Other"; + } ++ // Paseo backport of React 19.3.0: clear each measure once it is reported. The browser keeps ++ // every measure for the life of the page, so a long development session held millions. + function logComponentTrigger(fiber, startTime, endTime, trigger) { + supportsUserTiming && + ((reusableComponentOptions.start = startTime), +@@ -4088,7 +4090,7 @@ + reusableComponentOptions + ) + ) +- : performance.measure(trigger, reusableComponentOptions)); ++ : performance.measure(trigger, reusableComponentOptions), performance.clearMeasures(trigger)); + } + function logComponentReappeared(fiber, startTime, endTime) { + logComponentTrigger(fiber, startTime, endTime, "Reconnect"); +@@ -4159,7 +4161,7 @@ + : performance.measure( + "\u200b" + name, + reusableComponentOptions +- ))) ++ ), performance.clearMeasures("\u200b" + name))) + : null != selfTime + ? selfTime.run( + console.timeStamp.bind( +@@ -4229,7 +4231,7 @@ + ? debugTask.run( + performance.measure.bind(performance, "\u200b" + name, fiber) + ) +- : performance.measure("\u200b" + name, fiber); ++ : performance.measure("\u200b" + name, fiber), performance.clearMeasures("\u200b" + name); + } + } + } +@@ -4274,7 +4276,7 @@ + startTime + ) + ) +- : performance.measure("\u200b" + name, startTime); ++ : performance.measure("\u200b" + name, startTime), performance.clearMeasures("\u200b" + name); + } + } + } else +@@ -4434,7 +4436,7 @@ + ? debugTask.run( + performance.measure.bind(performance, "Recovered", startTime) + ) +- : performance.measure("Recovered", startTime); ++ : performance.measure("Recovered", startTime), performance.clearMeasures("Recovered"); + } + } + function logErroredRenderPhase(startTime, endTime, lanes, debugTask) { +@@ -4517,7 +4519,7 @@ + ? debugTask.run( + performance.measure.bind(performance, "Errored", startTime) + ) +- : performance.measure("Errored", startTime); ++ : performance.measure("Errored", startTime), performance.clearMeasures("Errored"); + } + } + function logAnimatingPhase(startTime, endTime, debugTask) { +@@ -17111,7 +17113,7 @@ + previousRenderStartTime + ) + ) +- : performance.measure(isSpawnedUpdate, previousRenderStartTime)); ++ : performance.measure(isSpawnedUpdate, previousRenderStartTime), performance.clearMeasures(isSpawnedUpdate)); + } + blockingUpdateTime = -1.1; + blockingUpdateType = 0; +@@ -17248,7 +17250,7 @@ + previousRenderStartTime + ) + ) +- : performance.measure(debugTask, previousRenderStartTime))), ++ : performance.measure(debugTask, previousRenderStartTime), performance.clearMeasures(debugTask))), + (transitionUpdateTime = transitionStartTime = -1.1), + (transitionUpdateType = 0), + (transitionSuspendedTime = -1.1), +diff --git a/node_modules/react-dom/cjs/react-dom-profiling.development.js b/node_modules/react-dom/cjs/react-dom-profiling.development.js +index c8b583c..7fd2231 100644 +--- a/node_modules/react-dom/cjs/react-dom-profiling.development.js ++++ b/node_modules/react-dom/cjs/react-dom-profiling.development.js +@@ -4081,6 +4081,8 @@ + ? "Idle" + : "Other"; + } ++ // Paseo backport of React 19.3.0: clear each measure once it is reported. The browser keeps ++ // every measure for the life of the page, so a long development session held millions. + function logComponentTrigger(fiber, startTime, endTime, trigger) { + supportsUserTiming && + ((reusableComponentOptions.start = startTime), +@@ -4096,7 +4098,7 @@ + reusableComponentOptions + ) + ) +- : performance.measure(trigger, reusableComponentOptions)); ++ : performance.measure(trigger, reusableComponentOptions), performance.clearMeasures(trigger)); + } + function logComponentReappeared(fiber, startTime, endTime) { + logComponentTrigger(fiber, startTime, endTime, "Reconnect"); +@@ -4167,7 +4169,7 @@ + : performance.measure( + "\u200b" + name, + reusableComponentOptions +- ))) ++ ), performance.clearMeasures("\u200b" + name))) + : null != selfTime + ? selfTime.run( + console.timeStamp.bind( +@@ -4237,7 +4239,7 @@ + ? debugTask.run( + performance.measure.bind(performance, "\u200b" + name, fiber) + ) +- : performance.measure("\u200b" + name, fiber); ++ : performance.measure("\u200b" + name, fiber), performance.clearMeasures("\u200b" + name); + } + } + } +@@ -4282,7 +4284,7 @@ + startTime + ) + ) +- : performance.measure("\u200b" + name, startTime); ++ : performance.measure("\u200b" + name, startTime), performance.clearMeasures("\u200b" + name); + } + } + } else +@@ -4442,7 +4444,7 @@ + ? debugTask.run( + performance.measure.bind(performance, "Recovered", startTime) + ) +- : performance.measure("Recovered", startTime); ++ : performance.measure("Recovered", startTime), performance.clearMeasures("Recovered"); + } + } + function logErroredRenderPhase(startTime, endTime, lanes, debugTask) { +@@ -4525,7 +4527,7 @@ + ? debugTask.run( + performance.measure.bind(performance, "Errored", startTime) + ) +- : performance.measure("Errored", startTime); ++ : performance.measure("Errored", startTime), performance.clearMeasures("Errored"); + } + } + function logAnimatingPhase(startTime, endTime, debugTask) { +@@ -17119,7 +17121,7 @@ + previousRenderStartTime + ) + ) +- : performance.measure(isSpawnedUpdate, previousRenderStartTime)); ++ : performance.measure(isSpawnedUpdate, previousRenderStartTime), performance.clearMeasures(isSpawnedUpdate)); + } + blockingUpdateTime = -1.1; + blockingUpdateType = 0; +@@ -17256,7 +17258,7 @@ + previousRenderStartTime + ) + ) +- : performance.measure(debugTask, previousRenderStartTime))), ++ : performance.measure(debugTask, previousRenderStartTime), performance.clearMeasures(debugTask))), + (transitionUpdateTime = transitionStartTime = -1.1), + (transitionUpdateType = 0), + (transitionSuspendedTime = -1.1), diff --git a/patches/react-native-unistyles+3.2.4.patch b/patches/react-native-unistyles+3.2.4.patch index c3da63a8ac..ec921dc957 100644 --- a/patches/react-native-unistyles+3.2.4.patch +++ b/patches/react-native-unistyles+3.2.4.patch @@ -1,322 +1,3 @@ -diff --git a/node_modules/react-native-unistyles/lib/commonjs/web/registry.js b/node_modules/react-native-unistyles/lib/commonjs/web/registry.js -index 120ff60..d1ff102 100644 ---- a/node_modules/react-native-unistyles/lib/commonjs/web/registry.js -+++ b/node_modules/react-native-unistyles/lib/commonjs/web/registry.js -@@ -10,6 +10,17 @@ class UnistylesRegistry { - stylesheets = new Map(); - stylesCache = new Set(); - stylesCounter = new Map(); -+ cleanupGeneration = 0; -+ finalizerTokens = new WeakMap(); -+ finalizationRegistry = typeof FinalizationRegistry === 'undefined' ? undefined : new FinalizationRegistry(({ -+ hash, -+ generation -+ }) => { -+ if (generation !== this.cleanupGeneration) { -+ return; -+ } -+ this.decrementAndMaybeCleanup(hash); -+ }); - disposeListenersMap = new Map(); - dependenciesMap = new Map(); - constructor(services) { -@@ -50,26 +61,48 @@ class UnistylesRegistry { - this.disposeListenersMap.set(stylesheet, dispose); - }; - connect = (ref, hash) => { -- const stylesCounter = this.stylesCounter.get(hash) ?? new Set(); -- stylesCounter.add(ref); -- this.stylesCounter.set(hash, stylesCounter); -+ this.stylesCounter.set(hash, (this.stylesCounter.get(hash) ?? 0) + 1); -+ if (!this.finalizationRegistry) { -+ return; -+ } -+ const token = {}; -+ const tokensByHash = this.finalizerTokens.get(ref) ?? new Map(); -+ const tokens = tokensByHash.get(hash) ?? []; -+ tokens.push(token); -+ tokensByHash.set(hash, tokens); -+ this.finalizerTokens.set(ref, tokensByHash); -+ this.finalizationRegistry.register(ref, { -+ hash, -+ generation: this.cleanupGeneration -+ }, token); - }; - remove = (ref, hash) => { -- const stylesCounter = this.stylesCounter.get(hash) ?? new Set(); -- stylesCounter.delete(ref); -- if (stylesCounter.size === 0) { -- // Move this to the end of the event loop so the element is removed from the DOM -- return Promise.resolve().then(() => { -- // Check if element is still in the DOM -- if (document.querySelector(`.${hash}`)) { -- return false; -- } -- this.css.remove(hash); -- this.stylesCache.delete(hash); -- return true; -- }); -+ const token = this.finalizerTokens.get(ref)?.get(hash)?.pop(); -+ if (token) { -+ this.finalizationRegistry?.unregister(token); -+ } -+ return this.decrementAndMaybeCleanup(hash); -+ }; -+ decrementAndMaybeCleanup = hash => { -+ const next = (this.stylesCounter.get(hash) ?? 0) - 1; -+ if (next > 0) { -+ this.stylesCounter.set(hash, next); -+ return Promise.resolve(false); - } -- return Promise.resolve(false); -+ this.stylesCounter.delete(hash); -+ // Move this to the end of the event loop so the element is removed from the DOM -+ return Promise.resolve().then(() => { -+ // Check if element is still in the DOM -+ if ((this.stylesCounter.get(hash) ?? 0) > 0) { -+ return false; -+ } -+ if (document.querySelector(`.${hash}`)) { -+ return false; -+ } -+ this.css.remove(hash); -+ this.stylesCache.delete(hash); -+ return true; -+ }); - }; - add = (value, forChild) => { - const generatedHash = (0, _utils.generateHash)(value); -@@ -91,7 +124,10 @@ class UnistylesRegistry { - this.css.add(hash, value); - }; - reset = () => { -+ this.cleanupGeneration += 1; -+ this.disposeListenersMap.forEach(dispose => dispose()); - this.css.reset(); -+ this.stylesheets.clear(); - this.stylesCache.clear(); - this.dependenciesMap.clear(); - this.disposeListenersMap.clear(); -diff --git a/node_modules/react-native-unistyles/lib/module/web/registry.js b/node_modules/react-native-unistyles/lib/module/web/registry.js -index 6362f43..8e769f8 100644 ---- a/node_modules/react-native-unistyles/lib/module/web/registry.js -+++ b/node_modules/react-native-unistyles/lib/module/web/registry.js -@@ -6,6 +6,17 @@ export class UnistylesRegistry { - stylesheets = new Map(); - stylesCache = new Set(); - stylesCounter = new Map(); -+ cleanupGeneration = 0; -+ finalizerTokens = new WeakMap(); -+ finalizationRegistry = typeof FinalizationRegistry === 'undefined' ? undefined : new FinalizationRegistry(({ -+ hash, -+ generation -+ }) => { -+ if (generation !== this.cleanupGeneration) { -+ return; -+ } -+ this.decrementAndMaybeCleanup(hash); -+ }); - disposeListenersMap = new Map(); - dependenciesMap = new Map(); - constructor(services) { -@@ -46,26 +57,48 @@ export class UnistylesRegistry { - this.disposeListenersMap.set(stylesheet, dispose); - }; - connect = (ref, hash) => { -- const stylesCounter = this.stylesCounter.get(hash) ?? new Set(); -- stylesCounter.add(ref); -- this.stylesCounter.set(hash, stylesCounter); -+ this.stylesCounter.set(hash, (this.stylesCounter.get(hash) ?? 0) + 1); -+ if (!this.finalizationRegistry) { -+ return; -+ } -+ const token = {}; -+ const tokensByHash = this.finalizerTokens.get(ref) ?? new Map(); -+ const tokens = tokensByHash.get(hash) ?? []; -+ tokens.push(token); -+ tokensByHash.set(hash, tokens); -+ this.finalizerTokens.set(ref, tokensByHash); -+ this.finalizationRegistry.register(ref, { -+ hash, -+ generation: this.cleanupGeneration -+ }, token); - }; - remove = (ref, hash) => { -- const stylesCounter = this.stylesCounter.get(hash) ?? new Set(); -- stylesCounter.delete(ref); -- if (stylesCounter.size === 0) { -- // Move this to the end of the event loop so the element is removed from the DOM -- return Promise.resolve().then(() => { -- // Check if element is still in the DOM -- if (document.querySelector(`.${hash}`)) { -- return false; -- } -- this.css.remove(hash); -- this.stylesCache.delete(hash); -- return true; -- }); -+ const token = this.finalizerTokens.get(ref)?.get(hash)?.pop(); -+ if (token) { -+ this.finalizationRegistry?.unregister(token); -+ } -+ return this.decrementAndMaybeCleanup(hash); -+ }; -+ decrementAndMaybeCleanup = hash => { -+ const next = (this.stylesCounter.get(hash) ?? 0) - 1; -+ if (next > 0) { -+ this.stylesCounter.set(hash, next); -+ return Promise.resolve(false); - } -- return Promise.resolve(false); -+ this.stylesCounter.delete(hash); -+ // Move this to the end of the event loop so the element is removed from the DOM -+ return Promise.resolve().then(() => { -+ // Check if element is still in the DOM -+ if ((this.stylesCounter.get(hash) ?? 0) > 0) { -+ return false; -+ } -+ if (document.querySelector(`.${hash}`)) { -+ return false; -+ } -+ this.css.remove(hash); -+ this.stylesCache.delete(hash); -+ return true; -+ }); - }; - add = (value, forChild) => { - const generatedHash = generateHash(value); -@@ -87,7 +120,10 @@ export class UnistylesRegistry { - this.css.add(hash, value); - }; - reset = () => { -+ this.cleanupGeneration += 1; -+ this.disposeListenersMap.forEach(dispose => dispose()); - this.css.reset(); -+ this.stylesheets.clear(); - this.stylesCache.clear(); - this.dependenciesMap.clear(); - this.disposeListenersMap.clear(); -diff --git a/node_modules/react-native-unistyles/src/web/registry.ts b/node_modules/react-native-unistyles/src/web/registry.ts -index 39e0d9d..a21ba95 100644 ---- a/node_modules/react-native-unistyles/src/web/registry.ts -+++ b/node_modules/react-native-unistyles/src/web/registry.ts -@@ -9,7 +9,24 @@ import { error, extractUnistyleDependencies, generateHash } from './utils' - export class UnistylesRegistry { - private readonly stylesheets = new Map, StyleSheet>() - private readonly stylesCache = new Set() -- private readonly stylesCounter = new Map>() -+ // Use counter instead of Set to avoid retaining detached DOM nodes -+ // FR is a fallback when remove() is missed -+ private readonly stylesCounter = new Map() -+ // Bumped on reset() so stale FR callbacks are ignored -+ private cleanupGeneration = 0 -+ // Per-registration unregister token, so remove() cancels only its own registration -+ private readonly finalizerTokens = new WeakMap>>() -+ // FR isn't available on every runtime - fall back to counter-only cleanup -+ private readonly finalizationRegistry = -+ typeof FinalizationRegistry === 'undefined' -+ ? undefined -+ : new FinalizationRegistry<{ hash: string; generation: number }>(({ hash, generation }) => { -+ if (generation !== this.cleanupGeneration) { -+ return -+ } -+ -+ this.decrementAndMaybeCleanup(hash) -+ }) - private readonly disposeListenersMap = new Map() - private readonly dependenciesMap = new Map, Set>() - readonly css: CSSState -@@ -78,33 +95,61 @@ export class UnistylesRegistry { - } - - connect = (ref: HTMLElement, hash: string) => { -- const stylesCounter = this.stylesCounter.get(hash) ?? new Set() -+ this.stylesCounter.set(hash, (this.stylesCounter.get(hash) ?? 0) + 1) - -- stylesCounter.add(ref) -- this.stylesCounter.set(hash, stylesCounter) -+ if (!this.finalizationRegistry) { -+ return -+ } -+ -+ const token = {} -+ const tokensByHash = this.finalizerTokens.get(ref) ?? new Map>() -+ const tokens = tokensByHash.get(hash) ?? [] -+ -+ tokens.push(token) -+ tokensByHash.set(hash, tokens) -+ this.finalizerTokens.set(ref, tokensByHash) -+ this.finalizationRegistry.register(ref, { hash, generation: this.cleanupGeneration }, token) - } - - remove = (ref: HTMLElement, hash: string) => { -- const stylesCounter = this.stylesCounter.get(hash) ?? new Set() -+ const token = this.finalizerTokens.get(ref)?.get(hash)?.pop() - -- stylesCounter.delete(ref) -+ if (token) { -+ this.finalizationRegistry?.unregister(token) -+ } - -- if (stylesCounter.size === 0) { -- // Move this to the end of the event loop so the element is removed from the DOM -- return Promise.resolve().then(() => { -- // Check if element is still in the DOM -- if (document.querySelector(`.${hash}`)) { -- return false -- } -+ return this.decrementAndMaybeCleanup(hash) -+ } -+ -+ private decrementAndMaybeCleanup = (hash: string): Promise => { -+ const next = (this.stylesCounter.get(hash) ?? 0) - 1 - -- this.css.remove(hash) -- this.stylesCache.delete(hash) -+ if (next > 0) { -+ this.stylesCounter.set(hash, next) - -- return true -- }) -+ return Promise.resolve(false) - } - -- return Promise.resolve(false) -+ // Drop the empty bucket from the Map -+ this.stylesCounter.delete(hash) -+ -+ // Move this to the end of the event loop so the element is removed from the DOM -+ return Promise.resolve().then(() => { -+ // New connect raced in during the microtask -+ if ((this.stylesCounter.get(hash) ?? 0) > 0) { -+ return false -+ } -+ -+ // Check if element is still in the DOM -+ if (document.querySelector(`.${hash}`)) { -+ return false -+ } -+ -+ this.css.remove(hash) -+ this.stylesCache.delete(hash) -+ -+ return true -+ }) - } - - add = (value: UnistylesValues, forChild?: boolean) => { -@@ -126,7 +171,11 @@ export class UnistylesRegistry { - } - - reset = () => { -+ // Invalidate pending FR callbacks from this generation -+ this.cleanupGeneration += 1 -+ this.disposeListenersMap.forEach((dispose) => dispose()) - this.css.reset() -+ this.stylesheets.clear() - this.stylesCache.clear() - this.dependenciesMap.clear() - this.disposeListenersMap.clear() diff --git a/node_modules/react-native-unistyles/android/build.gradle b/node_modules/react-native-unistyles/android/build.gradle index 195954b..c4ac28c 100644 --- a/node_modules/react-native-unistyles/android/build.gradle @@ -329,234 +10,6 @@ index 195954b..c4ac28c 100644 namespace "com.unistyles" defaultConfig { -diff --git a/node_modules/react-native-unistyles/src/core/withUnistyles/withUnistyles.tsx b/node_modules/react-native-unistyles/src/core/withUnistyles/withUnistyles.tsx ---- a/node_modules/react-native-unistyles/src/core/withUnistyles/withUnistyles.tsx -+++ b/node_modules/react-native-unistyles/src/core/withUnistyles/withUnistyles.tsx -@@ -28,13 +28,14 @@ - - return forwardRef, PropsWithUnistyles>((props, ref) => { - const narrowedProps = props as PropsWithUnistyles & UnistyleStyles -+ const { uniProps, ...componentProps } = narrowedProps - const styleClassNames = getClassName(narrowedProps.style, true) - const contentContainerStyleClassNames = getClassName(narrowedProps.contentContainerStyle) - const { proxifiedRuntime, proxifiedTheme } = useProxifiedUnistyles() - - const { key: mappingsKey, ...mappingsProps } = mappings ? mappings(proxifiedTheme, proxifiedRuntime) : {} -- const { key: uniPropsKey, ...unistyleProps } = narrowedProps.uniProps -- ? narrowedProps.uniProps(proxifiedTheme, proxifiedRuntime) -+ const { key: uniPropsKey, ...unistyleProps } = uniProps -+ ? uniProps(proxifiedTheme, proxifiedRuntime) - : {} - - const emptyStyles = narrowedProps.style -@@ -46,7 +47,7 @@ - : undefined - - const combinedProps = { -- ...deepMergeObjects(mappingsProps, unistyleProps, props), -+ ...deepMergeObjects(mappingsProps, unistyleProps, componentProps), - ...(narrowedProps.style - ? { - // Override default component styles with undefined values to reset them -diff --git a/node_modules/react-native-unistyles/src/core/withUnistyles/withUnistyles.native.tsx b/node_modules/react-native-unistyles/src/core/withUnistyles/withUnistyles.native.tsx ---- a/node_modules/react-native-unistyles/src/core/withUnistyles/withUnistyles.native.tsx -+++ b/node_modules/react-native-unistyles/src/core/withUnistyles/withUnistyles.native.tsx -@@ -63,6 +63,7 @@ - - return forwardRef, PropsWithUnistyles>((props, ref) => { - const narrowedProps = props as PropsWithUnistyles & UnistyleStyles -+ const { uniProps, ...componentProps } = narrowedProps - const NativeComponent = Component as ComponentType - - // @ts-ignore we don't know the type of the component -@@ -89,15 +90,15 @@ - }, [narrowedProps.style, narrowedProps.contentContainerStyle]) - - const { key: mappingsKey, ...mappingsProps } = mappings ? mappings(proxifiedTheme, proxifiedRuntime) : {} -- const { key: uniPropsKey, ...unistyleProps } = narrowedProps.uniProps -- ? narrowedProps.uniProps(proxifiedTheme, proxifiedRuntime) -+ const { key: uniPropsKey, ...unistyleProps } = uniProps -+ ? uniProps(proxifiedTheme, proxifiedRuntime) - : {} - - const styleSecrets = getSecrets(narrowedProps.style) - const contentContainerStyleSecrets = getSecrets(narrowedProps.contentContainerStyle) - - const finalProps = { -- ...deepMergeObjects(mappingsProps, unistyleProps, props), -+ ...deepMergeObjects(mappingsProps, unistyleProps, componentProps), - ...(narrowedProps.style - ? { - style: styleSecrets.styles, -diff --git a/node_modules/react-native-unistyles/lib/module/core/withUnistyles/withUnistyles.js b/node_modules/react-native-unistyles/lib/module/core/withUnistyles/withUnistyles.js ---- a/node_modules/react-native-unistyles/lib/module/core/withUnistyles/withUnistyles.js -+++ b/node_modules/react-native-unistyles/lib/module/core/withUnistyles/withUnistyles.js -@@ -13,6 +13,7 @@ - export const withUnistyles = (Component, mappings) => { - return /*#__PURE__*/forwardRef((props, ref) => { - const narrowedProps = props; -+ const { uniProps, ...componentProps } = narrowedProps; - const styleClassNames = getClassName(narrowedProps.style, true); - const contentContainerStyleClassNames = getClassName(narrowedProps.contentContainerStyle); - const { -@@ -26,10 +27,10 @@ - const { - key: uniPropsKey, - ...unistyleProps -- } = narrowedProps.uniProps ? narrowedProps.uniProps(proxifiedTheme, proxifiedRuntime) : {}; -+ } = uniProps ? uniProps(proxifiedTheme, proxifiedRuntime) : {}; - const emptyStyles = narrowedProps.style ? Object.fromEntries(Object.entries(Object.getOwnPropertyDescriptors(narrowedProps.style)).filter(([key]) => !key.startsWith('unistyles') && !key.startsWith('_')).map(([key]) => [key, undefined])) : undefined; - const combinedProps = { -- ...deepMergeObjects(mappingsProps, unistyleProps, props), -+ ...deepMergeObjects(mappingsProps, unistyleProps, componentProps), - ...(narrowedProps.style ? { - // Override default component styles with undefined values to reset them - style: emptyStyles -diff --git a/node_modules/react-native-unistyles/lib/module/core/withUnistyles/withUnistyles.native.js b/node_modules/react-native-unistyles/lib/module/core/withUnistyles/withUnistyles.native.js ---- a/node_modules/react-native-unistyles/lib/module/core/withUnistyles/withUnistyles.native.js -+++ b/node_modules/react-native-unistyles/lib/module/core/withUnistyles/withUnistyles.native.js -@@ -27,6 +27,7 @@ - }; - return /*#__PURE__*/forwardRef((props, ref) => { - const narrowedProps = props; -+ const { uniProps, ...componentProps } = narrowedProps; - const NativeComponent = Component; - - // @ts-ignore we don't know the type of the component -@@ -57,11 +58,11 @@ - const { - key: uniPropsKey, - ...unistyleProps -- } = narrowedProps.uniProps ? narrowedProps.uniProps(proxifiedTheme, proxifiedRuntime) : {}; -+ } = uniProps ? uniProps(proxifiedTheme, proxifiedRuntime) : {}; - const styleSecrets = getSecrets(narrowedProps.style); - const contentContainerStyleSecrets = getSecrets(narrowedProps.contentContainerStyle); - const finalProps = { -- ...deepMergeObjects(mappingsProps, unistyleProps, props), -+ ...deepMergeObjects(mappingsProps, unistyleProps, componentProps), - ...(narrowedProps.style ? { - style: styleSecrets.styles - } : {}), -diff --git a/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles/withUnistyles.js b/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles/withUnistyles.js ---- a/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles/withUnistyles.js -+++ b/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles/withUnistyles.js -@@ -18,6 +18,7 @@ - const withUnistyles = (Component, mappings) => { - return /*#__PURE__*/(0, _react.forwardRef)((props, ref) => { - const narrowedProps = props; -+ const { uniProps, ...componentProps } = narrowedProps; - const styleClassNames = (0, _getClassname.getClassName)(narrowedProps.style, true); - const contentContainerStyleClassNames = (0, _getClassname.getClassName)(narrowedProps.contentContainerStyle); - const { -@@ -31,10 +32,10 @@ - const { - key: uniPropsKey, - ...unistyleProps -- } = narrowedProps.uniProps ? narrowedProps.uniProps(proxifiedTheme, proxifiedRuntime) : {}; -+ } = uniProps ? uniProps(proxifiedTheme, proxifiedRuntime) : {}; - const emptyStyles = narrowedProps.style ? Object.fromEntries(Object.entries(Object.getOwnPropertyDescriptors(narrowedProps.style)).filter(([key]) => !key.startsWith('unistyles') && !key.startsWith('_')).map(([key]) => [key, undefined])) : undefined; - const combinedProps = { -- ...(0, _utils.deepMergeObjects)(mappingsProps, unistyleProps, props), -+ ...(0, _utils.deepMergeObjects)(mappingsProps, unistyleProps, componentProps), - ...(narrowedProps.style ? { - // Override default component styles with undefined values to reset them - style: emptyStyles -diff --git a/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles/withUnistyles.native.js b/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles/withUnistyles.native.js ---- a/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles/withUnistyles.native.js -+++ b/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles/withUnistyles.native.js -@@ -32,6 +32,7 @@ - }; - return /*#__PURE__*/(0, _react.forwardRef)((props, ref) => { - const narrowedProps = props; -+ const { uniProps, ...componentProps } = narrowedProps; - const NativeComponent = Component; - - // @ts-ignore we don't know the type of the component -@@ -62,11 +63,11 @@ - const { - key: uniPropsKey, - ...unistyleProps -- } = narrowedProps.uniProps ? narrowedProps.uniProps(proxifiedTheme, proxifiedRuntime) : {}; -+ } = uniProps ? uniProps(proxifiedTheme, proxifiedRuntime) : {}; - const styleSecrets = getSecrets(narrowedProps.style); - const contentContainerStyleSecrets = getSecrets(narrowedProps.contentContainerStyle); - const finalProps = { -- ...(0, _utils.deepMergeObjects)(mappingsProps, unistyleProps, props), -+ ...(0, _utils.deepMergeObjects)(mappingsProps, unistyleProps, componentProps), - ...(narrowedProps.style ? { - style: styleSecrets.styles - } : {}), -diff --git a/node_modules/react-native-unistyles/lib/commonjs/web/runtime.js b/node_modules/react-native-unistyles/lib/commonjs/web/runtime.js -index 305fa49..5957aa5 100644 ---- a/node_modules/react-native-unistyles/lib/commonjs/web/runtime.js -+++ b/node_modules/react-native-unistyles/lib/commonjs/web/runtime.js -@@ -35,10 +35,17 @@ class UnistylesRuntime { - return this.darkMedia; - } - get colorScheme() { -+ // Read the scheme through fresh lists, never through lightMedia/darkMedia. Chromium defers -+ // MediaQueryList change events while the document is hidden and drops the pending event -+ // of any list whose `matches` was read before the document became visible again, which -+ // would silence the adaptive-theme listeners registered on those two lists. -+ if ((0, _utils.isServer)()) { -+ return _types.ColorScheme.Unspecified; -+ } - switch (true) { -- case this.getLightMedia()?.matches: -+ case window.matchMedia('(prefers-color-scheme: light)').matches: - return _types.ColorScheme.Light; -- case this.getDarkMedia()?.matches: -+ case window.matchMedia('(prefers-color-scheme: dark)').matches: - return _types.ColorScheme.Dark; - default: - return _types.ColorScheme.Unspecified; -diff --git a/node_modules/react-native-unistyles/lib/module/web/runtime.js b/node_modules/react-native-unistyles/lib/module/web/runtime.js -index 7f13a06..c487bee 100644 ---- a/node_modules/react-native-unistyles/lib/module/web/runtime.js -+++ b/node_modules/react-native-unistyles/lib/module/web/runtime.js -@@ -31,10 +31,17 @@ export class UnistylesRuntime { - return this.darkMedia; - } - get colorScheme() { -+ // Read the scheme through fresh lists, never through lightMedia/darkMedia. Chromium defers -+ // MediaQueryList change events while the document is hidden and drops the pending event -+ // of any list whose `matches` was read before the document became visible again, which -+ // would silence the adaptive-theme listeners registered on those two lists. -+ if (isServer()) { -+ return ColorScheme.Unspecified; -+ } - switch (true) { -- case this.getLightMedia()?.matches: -+ case window.matchMedia('(prefers-color-scheme: light)').matches: - return ColorScheme.Light; -- case this.getDarkMedia()?.matches: -+ case window.matchMedia('(prefers-color-scheme: dark)').matches: - return ColorScheme.Dark; - default: - return ColorScheme.Unspecified; -diff --git a/node_modules/react-native-unistyles/src/web/runtime.ts b/node_modules/react-native-unistyles/src/web/runtime.ts -index a16dac0..6519858 100644 ---- a/node_modules/react-native-unistyles/src/web/runtime.ts -+++ b/node_modules/react-native-unistyles/src/web/runtime.ts -@@ -41,8 +41,16 @@ export class UnistylesRuntime { - get colorScheme() { -+ // Read the scheme through fresh lists, never through lightMedia/darkMedia. Chromium defers -+ // MediaQueryList change events while the document is hidden and drops the pending event -+ // of any list whose `matches` was read before the document became visible again, which -+ // would silence the adaptive-theme listeners registered on those two lists. -+ if (isServer()) { -+ return ColorScheme.Unspecified -+ } -+ - switch (true) { -- case this.getLightMedia()?.matches: -+ case window.matchMedia('(prefers-color-scheme: light)').matches: - return ColorScheme.Light -- case this.getDarkMedia()?.matches: -+ case window.matchMedia('(prefers-color-scheme: dark)').matches: - return ColorScheme.Dark - default: - return ColorScheme.Unspecified diff --git a/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+android.kt b/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+android.kt index 0f8d1f0..154a12a 100644 --- a/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+android.kt @@ -761,3 +214,2289 @@ index 01026dc..3786ec4 100644 #else const auto& shadowTreeRegistry = UIManagerBinding::getBinding(rt)->getUIManager().getShadowTreeRegistry(); +diff --git a/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles/withUnistyles.js b/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles/withUnistyles.js +index 5a0d049..36d7db4 100644 +--- a/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles/withUnistyles.js ++++ b/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles/withUnistyles.js +@@ -18,6 +18,7 @@ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r + const withUnistyles = (Component, mappings) => { + return /*#__PURE__*/(0, _react.forwardRef)((props, ref) => { + const narrowedProps = props; ++ const { uniProps, ...componentProps } = narrowedProps; + const styleClassNames = (0, _getClassname.getClassName)(narrowedProps.style, true); + const contentContainerStyleClassNames = (0, _getClassname.getClassName)(narrowedProps.contentContainerStyle); + const { +@@ -31,10 +32,10 @@ const withUnistyles = (Component, mappings) => { + const { + key: uniPropsKey, + ...unistyleProps +- } = narrowedProps.uniProps ? narrowedProps.uniProps(proxifiedTheme, proxifiedRuntime) : {}; ++ } = uniProps ? uniProps(proxifiedTheme, proxifiedRuntime) : {}; + const emptyStyles = narrowedProps.style ? Object.fromEntries(Object.entries(Object.getOwnPropertyDescriptors(narrowedProps.style)).filter(([key]) => !key.startsWith('unistyles') && !key.startsWith('_')).map(([key]) => [key, undefined])) : undefined; + const combinedProps = { +- ...(0, _utils.deepMergeObjects)(mappingsProps, unistyleProps, props), ++ ...(0, _utils.deepMergeObjects)(mappingsProps, unistyleProps, componentProps), + ...(narrowedProps.style ? { + // Override default component styles with undefined values to reset them + style: emptyStyles +diff --git a/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles/withUnistyles.native.js b/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles/withUnistyles.native.js +index abaa2ee..000d8e3 100644 +--- a/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles/withUnistyles.native.js ++++ b/node_modules/react-native-unistyles/lib/commonjs/core/withUnistyles/withUnistyles.native.js +@@ -32,6 +32,7 @@ const withUnistyles = (Component, mappings) => { + }; + return /*#__PURE__*/(0, _react.forwardRef)((props, ref) => { + const narrowedProps = props; ++ const { uniProps, ...componentProps } = narrowedProps; + const NativeComponent = Component; + + // @ts-ignore we don't know the type of the component +@@ -62,11 +63,11 @@ const withUnistyles = (Component, mappings) => { + const { + key: uniPropsKey, + ...unistyleProps +- } = narrowedProps.uniProps ? narrowedProps.uniProps(proxifiedTheme, proxifiedRuntime) : {}; ++ } = uniProps ? uniProps(proxifiedTheme, proxifiedRuntime) : {}; + const styleSecrets = getSecrets(narrowedProps.style); + const contentContainerStyleSecrets = getSecrets(narrowedProps.contentContainerStyle); + const finalProps = { +- ...(0, _utils.deepMergeObjects)(mappingsProps, unistyleProps, props), ++ ...(0, _utils.deepMergeObjects)(mappingsProps, unistyleProps, componentProps), + ...(narrowedProps.style ? { + style: styleSecrets.styles + } : {}), +diff --git a/node_modules/react-native-unistyles/lib/commonjs/web/css/core.js b/node_modules/react-native-unistyles/lib/commonjs/web/css/core.js +index 1e28e32..2bee9e4 100644 +--- a/node_modules/react-native-unistyles/lib/commonjs/web/css/core.js ++++ b/node_modules/react-native-unistyles/lib/commonjs/web/css/core.js +@@ -3,9 +3,15 @@ + Object.defineProperty(exports, "__esModule", { + value: true + }); +-exports.convertToCSS = void 0; ++exports.getClassNameHash = exports.convertToCSS = void 0; + var _pseudo = require("../convert/pseudo"); + var _utils = require("../utils"); ++// hash:hover and hash::before belong to hash. Hashes have no colons, a forChild one keeps ' > *' ++const getClassNameHash = className => { ++ const pseudoIndex = className.indexOf(':'); ++ return pseudoIndex === -1 ? className : className.slice(0, pseudoIndex); ++}; ++exports.getClassNameHash = getClassNameHash; + const convertToCSS = (hash, value, state) => { + Object.entries(value).forEach(([styleKey, styleValue]) => { + if (styleKey[0] === '_') { +diff --git a/node_modules/react-native-unistyles/lib/commonjs/web/css/sheet.js b/node_modules/react-native-unistyles/lib/commonjs/web/css/sheet.js +new file mode 100644 +index 0000000..db1c970 +--- /dev/null ++++ b/node_modules/react-native-unistyles/lib/commonjs/web/css/sheet.js +@@ -0,0 +1,216 @@ ++"use strict"; ++ ++Object.defineProperty(exports, "__esModule", { ++ value: true ++}); ++exports.getSelector = exports.getDeclarations = exports.CSSSheet = void 0; ++var _utils = require("../utils"); ++// Paseo backport of https://github.com/jpudysz/react-native-unistyles/pull/1354 (released in 3.8.0). ++// CSSState used to rewrite the text of the style tag on every added and removed class, and the browser ++// then restyled the whole document. Rules now change one at a time through the CSSOM. ++ ++// Styles without a media query get a group too, so every group is an ordinary child list of one top level rule ++const BASE_MEDIA_QUERY = '@media all'; ++const getSelector = className => `.${className}`; ++exports.getSelector = getSelector; ++const getDeclarations = styles => { ++ let declarations = ''; ++ for (const [propertyKey, value] of styles) { ++ if (value === undefined) { ++ continue; ++ } ++ declarations += `${(0, _utils.hyphenate)(propertyKey)}:${value};`; ++ } ++ return declarations; ++}; ++exports.getDeclarations = getDeclarations; ++const insertRule = (parent, rule, index = parent.cssRules.length) => { ++ try { ++ return parent.cssRules[parent.insertRule(rule, index)]; ++ } catch { ++ // The browser can't parse it, like a pseudo-element it doesn't support yet: a text sheet drops it too ++ return undefined; ++ } ++}; ++const indexOfRule = (parent, rule) => Array.prototype.indexOf.call(parent.cssRules, rule); ++ ++// Keeps the styles of CSSState in the style tag through the CSSOM, never its text, so another runtime keeps its rules ++class CSSSheet { ++ tag = null; ++ sheet = null; ++ groups = new Map(); ++ themes = new Map(); ++ hasServerStyles = false; ++ constructor(themesCSS, styles) { ++ this.themesCSS = themesCSS; ++ this.styles = styles; ++ if ((0, _utils.isServer)()) { ++ return; ++ } ++ const existingTag = document.getElementById('unistyles-web'); ++ if (existingTag) { ++ this.tag = existingTag; ++ // A tag from another runtime has no text, its rules live in the CSSOM ++ this.hasServerStyles = Boolean(this.tag.textContent); ++ this.sheet = this.hasServerStyles ? null : this.tag.sheet; ++ return; ++ } ++ this.tag = document.createElement('style'); ++ this.tag.id = 'unistyles-web'; ++ document.head.appendChild(this.tag); ++ this.sheet = this.tag.sheet; ++ } ++ refresh = () => { ++ const sheet = this.getSheet(); ++ if (sheet) { ++ this.insertGroups(sheet); ++ } ++ }; ++ syncClass = (mediaQuery, className) => { ++ const sheet = this.getSheet(); ++ if (!sheet) { ++ return; ++ } ++ this.insertGroups(sheet); ++ const group = this.groups.get(mediaQuery); ++ if (group) { ++ this.syncGroupClass(group, className, this.styles.get(mediaQuery)?.get(className)); ++ } ++ }; ++ ++ // False only when the browser rejects the theme, so CSSState keeps the CSS that is applied ++ syncTheme = (key, css = this.themesCSS.get(key)) => { ++ const sheet = this.getThemeSheet(); ++ const current = this.themes.get(key); ++ if (!sheet || css === undefined) { ++ return true; ++ } ++ ++ // The theme goes last on every update, so it wins over the same theme of a runtime added to the tag later ++ const rule = insertRule(sheet, css); ++ ++ // Inserted before the old rule goes, so a theme the browser rejects keeps the previous variables ++ if (!rule) { ++ return false; ++ } ++ const currentIndex = current ? indexOfRule(sheet, current) : -1; ++ if (currentIndex >= 0) { ++ sheet.deleteRule(currentIndex); ++ } ++ this.themes.set(key, rule); ++ return true; ++ }; ++ reset = () => { ++ const sheet = this.tag?.sheet; ++ if (sheet && sheet === this.sheet) { ++ this.deleteOwnRules(sheet, new Set(Array.from(this.groups.values(), group => group?.rule))); ++ } ++ this.groups.clear(); ++ }; ++ getSheet = () => { ++ if (!this.tag) { ++ return null; ++ } ++ if (!this.tag.isConnected) { ++ document.head.appendChild(this.tag); ++ } ++ ++ // Another runtime on the tag may have cleared the server text and filled the tag through the CSSOM already ++ if (this.hasServerStyles) { ++ this.hasServerStyles = false; ++ if (this.tag.textContent) { ++ this.tag.textContent = ''; ++ } ++ } ++ const sheet = this.tag.sheet; ++ ++ // A new sheet lost every rule: the server one was replaced, or the tag was rewritten or attached again ++ if (sheet && sheet !== this.sheet) { ++ this.sheet = sheet; ++ this.insertAll(sheet); ++ } ++ return sheet; ++ }; ++ getThemeSheet = () => { ++ if (this.hasServerStyles) { ++ return this.tag?.sheet ?? null; ++ } ++ return this.getSheet(); ++ }; ++ insertAll = sheet => { ++ this.groups.clear(); ++ // A theme added on top of server styles another runtime already replaced is still in this sheet ++ this.deleteOwnRules(sheet, new Set(this.themes.values())); ++ this.themes.clear(); ++ this.themesCSS.forEach((_, key) => this.syncTheme(key)); ++ this.insertGroups(sheet); ++ this.groups.forEach((group, mediaQuery) => { ++ if (!group) { ++ return; ++ } ++ this.styles.get(mediaQuery)?.forEach((styles, className) => this.syncGroupClass(group, className, styles)); ++ }); ++ }; ++ ++ // Every group of the styles map gets created, empty ones too, so a group appended later is always the last one ++ insertGroups = sheet => { ++ if (this.groups.size === this.styles.size) { ++ return; ++ } ++ this.styles.forEach((_, mediaQuery) => { ++ if (this.groups.has(mediaQuery)) { ++ return; ++ } ++ const rule = insertRule(sheet, `${mediaQuery || BASE_MEDIA_QUERY}{}`); ++ this.groups.set(mediaQuery, rule ? { ++ rule, ++ rules: [], ++ classes: new Map(), ++ rejected: new Map() ++ } : null); ++ }); ++ }; ++ syncGroupClass = (group, className, styles) => { ++ const current = group.classes.get(className); ++ if (!styles) { ++ group.rejected.delete(className); ++ if (current) { ++ const index = group.rules.indexOf(current.rule); ++ group.rule.deleteRule(index); ++ group.rules.splice(index, 1); ++ group.classes.delete(className); ++ } ++ return; ++ } ++ const declarations = getDeclarations(styles); ++ if (current) { ++ if (current.declarations !== declarations) { ++ current.rule.style.cssText = declarations; ++ current.declarations = declarations; ++ } ++ return; ++ } ++ if (group.rejected.get(className) === declarations) { ++ return; ++ } ++ const rule = insertRule(group.rule, `${getSelector(className)}{${declarations}}`); ++ if (rule) { ++ group.rules.push(rule); ++ group.classes.set(className, { ++ rule, ++ declarations ++ }); ++ group.rejected.delete(className); ++ return; ++ } ++ group.rejected.set(className, declarations); ++ }; ++ deleteOwnRules = (sheet, rules) => { ++ for (let index = sheet.cssRules.length - 1; index >= 0; index--) { ++ if (rules.has(sheet.cssRules[index])) { ++ sheet.deleteRule(index); ++ } ++ } ++ }; ++} ++exports.CSSSheet = CSSSheet; +diff --git a/node_modules/react-native-unistyles/lib/commonjs/web/css/state.js b/node_modules/react-native-unistyles/lib/commonjs/web/css/state.js +index 7c7214e..d66bc3f 100644 +--- a/node_modules/react-native-unistyles/lib/commonjs/web/css/state.js ++++ b/node_modules/react-native-unistyles/lib/commonjs/web/css/state.js +@@ -7,53 +7,75 @@ exports.CSSState = void 0; + var _convert = require("../convert"); + var _utils = require("../utils"); + var _core = require("./core"); +-const safeGetMap = (map, key) => { +- const nextLevelMap = map.get(key); +- if (!nextLevelMap) { +- const newMap = new Map(); +- map.set(key, newMap); +- return newMap; +- } +- return nextLevelMap; ++var _sheet = require("./sheet"); ++var _utils2 = require("./utils"); ++const forEachClassName = (classNames, callback) => { ++ classNames?.forEach((names, mediaQuery) => names.forEach(className => callback(mediaQuery, className))); + }; ++// Paseo backport of https://github.com/jpudysz/react-native-unistyles/pull/1354 (released in 3.8.0). + class CSSState { +- mainMap = new Map(); +- mqMap = new Map(); +- styleTag = null; ++ mainMap = new Map([['', new Map()]]); + themesCSS = new Map(); ++ owners = new Map(); ++ sheet = new _sheet.CSSSheet(this.themesCSS, this.mainMap); + constructor(services) { + this.services = services; +- if ((0, _utils.isServer)()) { +- return; +- } +- const ssrTag = document.getElementById('unistyles-web'); +- if (ssrTag) { +- this.styleTag = ssrTag; +- return; +- } +- this.styleTag = document.createElement('style'); +- this.styleTag.id = 'unistyles-web'; +- document.head.appendChild(this.styleTag); + } + set = ({ + className, + propertyKey, + value, +- mediaQuery = '', +- isMq ++ mediaQuery = '' + }) => { +- const firstLevelMap = isMq ? this.mqMap : this.mainMap; +- const secondLevelMap = safeGetMap(firstLevelMap, mediaQuery); +- const thirdLevelMap = safeGetMap(secondLevelMap, className); ++ const secondLevelMap = (0, _utils2.safeGetMap)(this.mainMap, mediaQuery); ++ const thirdLevelMap = (0, _utils2.safeGetMap)(secondLevelMap, className); + thirdLevelMap.set(propertyKey, value); ++ ++ // The owner comes from the class name, so hydrated styles have one too ++ const owner = (0, _utils2.safeGetMap)(this.owners, (0, _core.getClassNameHash)(className)); ++ const classNames = owner.get(mediaQuery) ?? new Set(); ++ classNames.add(className); ++ owner.set(mediaQuery, classNames); + }; + add = (hash, values) => { +- (0, _core.convertToCSS)(hash, (0, _convert.convertUnistyles)(values, this.services.runtime), this); +- this.recreate(); +- }; +- recreate = () => { +- if (this.styleTag) { +- this.styleTag.innerText = this.getStyles(); ++ const styles = new Map(); ++ (0, _core.convertToCSS)(hash, (0, _convert.convertUnistyles)(values, this.services.runtime), { ++ set: ({ ++ className, ++ propertyKey, ++ value, ++ mediaQuery = '' ++ }) => { ++ (0, _utils2.safeGetMap)((0, _utils2.safeGetMap)(styles, mediaQuery), className).set(propertyKey, value); ++ } ++ }); ++ const previousClassNames = this.owners.get(hash); ++ forEachClassName(previousClassNames, (mediaQuery, className) => { ++ this.mainMap.get(mediaQuery)?.get(className)?.clear(); ++ }); ++ this.owners.delete(hash); ++ styles.forEach((classes, mediaQuery) => { ++ classes.forEach((properties, className) => { ++ properties.forEach((value, propertyKey) => this.set({ ++ mediaQuery, ++ className, ++ propertyKey, ++ value ++ })); ++ }); ++ }); ++ const classNames = this.owners.get(hash); ++ forEachClassName(previousClassNames, (mediaQuery, className) => { ++ if (!classNames?.get(mediaQuery)?.has(className)) { ++ this.mainMap.get(mediaQuery)?.delete(className); ++ this.sheet.syncClass(mediaQuery, className); ++ } ++ }); ++ forEachClassName(classNames, this.sheet.syncClass); ++ ++ // syncClass already brings back the rules the tag lost, refresh does it when nothing was synced ++ if (!previousClassNames && !classNames) { ++ this.sheet.refresh(); + } + }; + addTheme = (theme, values) => { +@@ -67,62 +89,55 @@ class CSSState { + } + }; + Object.entries(values).forEach(([key, value]) => convertToCSS(key, value)); ++ + if (theme === 'light' || theme === 'dark') { +- this.themesCSS.set(`media ${theme}`, `@media (prefers-color-scheme: ${theme}){:root{${themeVars}}}`); ++ this.setThemeCSS(`media ${theme}`, `@media (prefers-color-scheme: ${theme}){:root{${themeVars}}}`); ++ } ++ this.setThemeCSS(theme, `:root.${theme}{${themeVars}}`); ++ }; ++ setThemeCSS = (key, css) => { ++ if (this.sheet.syncTheme(key, css)) { ++ this.themesCSS.set(key, css); + } +- this.themesCSS.set(theme, `:root.${theme}{${themeVars}}`); + }; + remove = hash => { +- this.mainMap.forEach(styles => { +- styles.delete(hash); ++ const classNames = this.owners.get(hash); ++ this.owners.delete(hash); ++ forEachClassName(classNames, (mediaQuery, className) => { ++ this.mainMap.get(mediaQuery)?.delete(className); ++ this.sheet.syncClass(mediaQuery, className); + }); +- this.mqMap.forEach(styles => { +- styles.delete(hash); +- }); +- this.recreate(); ++ if (!classNames) { ++ this.sheet.refresh(); ++ } + }; + getStyles = () => { + let styles = Array.from(this.themesCSS.entries()).reduce((acc, [, themeCss]) => { + return acc + themeCss; + }, ''); +- const generate = (mediaQuery, secondLevelMap) => { ++ for (const [mediaQuery, secondLevelMap] of this.mainMap) { + if (mediaQuery) { + styles += `${mediaQuery}{`; + } + for (const [className, thirdLevelMap] of secondLevelMap) { +- styles += `.${className}{`; +- for (const [propertyKey, value] of thirdLevelMap) { +- if (value === undefined) { +- continue; +- } +- styles += `${(0, _utils.hyphenate)(propertyKey)}:${value};`; +- } +- styles += '}'; ++ styles += `${(0, _sheet.getSelector)(className)}{${(0, _sheet.getDeclarations)(thirdLevelMap)}}`; + } + if (mediaQuery) { + styles += '}'; + } +- }; +- for (const [mediaQuery, secondLevelMap] of this.mainMap) { +- generate(mediaQuery, secondLevelMap); +- } +- for (const [mediaQuery, secondLevelMap] of this.mqMap) { +- generate(mediaQuery, secondLevelMap); + } + return styles; + }; + getState = () => { +- const getState = map => { +- return Array.from(map).map(([mediaQuery, classNames]) => { +- return [mediaQuery, Array.from(classNames.entries()).map(([className, style]) => { +- return [className, Array.from(style.entries()).map(([property, value]) => { +- return [property, value]; +- })]; ++ const mainState = Array.from(this.mainMap).map(([mediaQuery, classNames]) => { ++ return [mediaQuery, Array.from(classNames.entries()).map(([className, style]) => { ++ return [className, Array.from(style.entries()).map(([property, value]) => { ++ return [property, value]; + })]; +- }); +- }; +- const mainState = getState(this.mainMap); +- const mqState = getState(this.mqMap); ++ })]; ++ }); ++ // Always empty, media query styles live in mainState. Kept for the shape hydrate reads ++ const mqState = []; + const config = this.services.state.getConfig(); + return { + mainState, +@@ -130,11 +145,12 @@ class CSSState { + config + }; + }; +- hydrate = ({ +- mainState, +- mqState +- }) => { +- const hydrateState = (map, isMq = false) => { ++ hydrate = state => { ++ if (state === this.hydratedState) { ++ return; ++ } ++ this.hydratedState = state; ++ const hydrateState = map => { + map.forEach(([mediaQuery, classNames]) => { + classNames.forEach(([className, style]) => { + style.forEach(([propertyKey, value]) => { +@@ -142,19 +158,22 @@ class CSSState { + className, + propertyKey, + value, +- mediaQuery, +- isMq ++ mediaQuery + }); + }); ++ this.sheet.syncClass(mediaQuery, className); + }); + }); + }; +- hydrateState(mainState); +- hydrateState(mqState, true); ++ hydrateState(state.mainState); ++ hydrateState(state.mqState); + }; + reset = () => { +- this.mqMap.clear(); + this.mainMap.clear(); ++ this.mainMap.set('', new Map()); ++ this.owners.clear(); ++ this.hydratedState = undefined; ++ this.sheet.reset(); + }; + } + exports.CSSState = CSSState; +diff --git a/node_modules/react-native-unistyles/lib/commonjs/web/css/utils.js b/node_modules/react-native-unistyles/lib/commonjs/web/css/utils.js +index e525d1b..d3d2c54 100644 +--- a/node_modules/react-native-unistyles/lib/commonjs/web/css/utils.js ++++ b/node_modules/react-native-unistyles/lib/commonjs/web/css/utils.js +@@ -3,8 +3,7 @@ + Object.defineProperty(exports, "__esModule", { + value: true + }); +-exports.safeGetMap = exports.getStylesFromState = void 0; +-var _utils = require("../utils"); ++exports.safeGetMap = void 0; + const safeGetMap = (map, key) => { + const nextLevelMap = map.get(key); + if (!nextLevelMap) { +@@ -15,33 +14,4 @@ const safeGetMap = (map, key) => { + return nextLevelMap; + }; + exports.safeGetMap = safeGetMap; +-const getStylesFromState = state => { +- let styles = ''; +- const generate = (mediaQuery, secondLevelMap) => { +- if (mediaQuery) { +- styles += `${mediaQuery}{`; +- } +- for (const [className, thirdLevelMap] of secondLevelMap) { +- styles += `.${className}{`; +- for (const [propertyKey, value] of thirdLevelMap) { +- if (value === undefined) { +- continue; +- } +- styles += `${(0, _utils.hyphenate)(propertyKey)}:${value};`; +- } +- styles += '}'; +- } +- if (mediaQuery) { +- styles += '}'; +- } +- }; +- for (const [mediaQuery, secondLevelMap] of state.mainMap) { +- generate(mediaQuery, secondLevelMap); +- } +- for (const [mediaQuery, secondLevelMap] of state.mqMap) { +- generate(mediaQuery, secondLevelMap); +- } +- return styles; +-}; +-exports.getStylesFromState = getStylesFromState; + //# sourceMappingURL=utils.js.map +\ No newline at end of file +diff --git a/node_modules/react-native-unistyles/lib/commonjs/web/registry.js b/node_modules/react-native-unistyles/lib/commonjs/web/registry.js +index 120ff60..5e724b2 100644 +--- a/node_modules/react-native-unistyles/lib/commonjs/web/registry.js ++++ b/node_modules/react-native-unistyles/lib/commonjs/web/registry.js +@@ -10,6 +10,17 @@ class UnistylesRegistry { + stylesheets = new Map(); + stylesCache = new Set(); + stylesCounter = new Map(); ++ cleanupGeneration = 0; ++ finalizerTokens = new WeakMap(); ++ finalizationRegistry = typeof FinalizationRegistry === 'undefined' ? undefined : new FinalizationRegistry(({ ++ hash, ++ generation ++ }) => { ++ if (generation !== this.cleanupGeneration) { ++ return; ++ } ++ this.decrementAndMaybeCleanup(hash); ++ }); + disposeListenersMap = new Map(); + dependenciesMap = new Map(); + constructor(services) { +@@ -50,26 +61,48 @@ class UnistylesRegistry { + this.disposeListenersMap.set(stylesheet, dispose); + }; + connect = (ref, hash) => { +- const stylesCounter = this.stylesCounter.get(hash) ?? new Set(); +- stylesCounter.add(ref); +- this.stylesCounter.set(hash, stylesCounter); ++ this.stylesCounter.set(hash, (this.stylesCounter.get(hash) ?? 0) + 1); ++ if (!this.finalizationRegistry) { ++ return; ++ } ++ const token = {}; ++ const tokensByHash = this.finalizerTokens.get(ref) ?? new Map(); ++ const tokens = tokensByHash.get(hash) ?? []; ++ tokens.push(token); ++ tokensByHash.set(hash, tokens); ++ this.finalizerTokens.set(ref, tokensByHash); ++ this.finalizationRegistry.register(ref, { ++ hash, ++ generation: this.cleanupGeneration ++ }, token); + }; + remove = (ref, hash) => { +- const stylesCounter = this.stylesCounter.get(hash) ?? new Set(); +- stylesCounter.delete(ref); +- if (stylesCounter.size === 0) { +- // Move this to the end of the event loop so the element is removed from the DOM +- return Promise.resolve().then(() => { +- // Check if element is still in the DOM +- if (document.querySelector(`.${hash}`)) { +- return false; +- } +- this.css.remove(hash); +- this.stylesCache.delete(hash); +- return true; +- }); ++ const token = this.finalizerTokens.get(ref)?.get(hash)?.pop(); ++ if (token) { ++ this.finalizationRegistry?.unregister(token); ++ } ++ return this.decrementAndMaybeCleanup(hash); ++ }; ++ decrementAndMaybeCleanup = hash => { ++ const next = (this.stylesCounter.get(hash) ?? 0) - 1; ++ if (next > 0) { ++ this.stylesCounter.set(hash, next); ++ return Promise.resolve(false); + } +- return Promise.resolve(false); ++ this.stylesCounter.delete(hash); ++ // Move this to the end of the event loop so the element is removed from the DOM ++ return Promise.resolve().then(() => { ++ // Check if element is still in the DOM ++ if ((this.stylesCounter.get(hash) ?? 0) > 0) { ++ return false; ++ } ++ if (document.querySelector(`.${hash}`)) { ++ return false; ++ } ++ this.css.remove(hash); ++ this.stylesCache.delete(hash); ++ return true; ++ }); + }; + add = (value, forChild) => { + const generatedHash = (0, _utils.generateHash)(value); +@@ -91,7 +124,10 @@ class UnistylesRegistry { + this.css.add(hash, value); + }; + reset = () => { ++ this.cleanupGeneration += 1; ++ this.disposeListenersMap.forEach(dispose => dispose()); + this.css.reset(); ++ this.stylesheets.clear(); + this.stylesCache.clear(); + this.dependenciesMap.clear(); + this.disposeListenersMap.clear(); +diff --git a/node_modules/react-native-unistyles/lib/commonjs/web/runtime.js b/node_modules/react-native-unistyles/lib/commonjs/web/runtime.js +index 305fa49..c6f5fb6 100644 +--- a/node_modules/react-native-unistyles/lib/commonjs/web/runtime.js ++++ b/node_modules/react-native-unistyles/lib/commonjs/web/runtime.js +@@ -35,10 +35,17 @@ class UnistylesRuntime { + return this.darkMedia; + } + get colorScheme() { ++ // Read the scheme through fresh lists, never through lightMedia/darkMedia. Chromium defers ++ // MediaQueryList change events while the document is hidden and drops the pending event ++ // of any list whose `matches` was read before the document became visible again, which ++ // would silence the adaptive-theme listeners registered on those two lists. ++ if ((0, _utils.isServer)()) { ++ return _types.ColorScheme.Unspecified; ++ } + switch (true) { +- case this.getLightMedia()?.matches: ++ case window.matchMedia('(prefers-color-scheme: light)').matches: + return _types.ColorScheme.Light; +- case this.getDarkMedia()?.matches: ++ case window.matchMedia('(prefers-color-scheme: dark)').matches: + return _types.ColorScheme.Dark; + default: + return _types.ColorScheme.Unspecified; +@@ -190,7 +197,6 @@ class UnistylesRuntime { + return (0, _utils.convertTheme)(key, value); + }))); + this.services.registry.css.addTheme(themeName, newTheme); +- this.services.registry.css.recreate(); + } + }; + getTheme = (themeName = this.themeName, CSSVars = false) => { +diff --git a/node_modules/react-native-unistyles/lib/module/core/withUnistyles/withUnistyles.js b/node_modules/react-native-unistyles/lib/module/core/withUnistyles/withUnistyles.js +index 5904a73..673cff6 100644 +--- a/node_modules/react-native-unistyles/lib/module/core/withUnistyles/withUnistyles.js ++++ b/node_modules/react-native-unistyles/lib/module/core/withUnistyles/withUnistyles.js +@@ -13,6 +13,7 @@ import { jsx as _jsx } from "react/jsx-runtime"; + export const withUnistyles = (Component, mappings) => { + return /*#__PURE__*/forwardRef((props, ref) => { + const narrowedProps = props; ++ const { uniProps, ...componentProps } = narrowedProps; + const styleClassNames = getClassName(narrowedProps.style, true); + const contentContainerStyleClassNames = getClassName(narrowedProps.contentContainerStyle); + const { +@@ -26,10 +27,10 @@ export const withUnistyles = (Component, mappings) => { + const { + key: uniPropsKey, + ...unistyleProps +- } = narrowedProps.uniProps ? narrowedProps.uniProps(proxifiedTheme, proxifiedRuntime) : {}; ++ } = uniProps ? uniProps(proxifiedTheme, proxifiedRuntime) : {}; + const emptyStyles = narrowedProps.style ? Object.fromEntries(Object.entries(Object.getOwnPropertyDescriptors(narrowedProps.style)).filter(([key]) => !key.startsWith('unistyles') && !key.startsWith('_')).map(([key]) => [key, undefined])) : undefined; + const combinedProps = { +- ...deepMergeObjects(mappingsProps, unistyleProps, props), ++ ...deepMergeObjects(mappingsProps, unistyleProps, componentProps), + ...(narrowedProps.style ? { + // Override default component styles with undefined values to reset them + style: emptyStyles +diff --git a/node_modules/react-native-unistyles/lib/module/core/withUnistyles/withUnistyles.native.js b/node_modules/react-native-unistyles/lib/module/core/withUnistyles/withUnistyles.native.js +index b89343e..00cde6a 100644 +--- a/node_modules/react-native-unistyles/lib/module/core/withUnistyles/withUnistyles.native.js ++++ b/node_modules/react-native-unistyles/lib/module/core/withUnistyles/withUnistyles.native.js +@@ -27,6 +27,7 @@ export const withUnistyles = (Component, mappings) => { + }; + return /*#__PURE__*/forwardRef((props, ref) => { + const narrowedProps = props; ++ const { uniProps, ...componentProps } = narrowedProps; + const NativeComponent = Component; + + // @ts-ignore we don't know the type of the component +@@ -57,11 +58,11 @@ export const withUnistyles = (Component, mappings) => { + const { + key: uniPropsKey, + ...unistyleProps +- } = narrowedProps.uniProps ? narrowedProps.uniProps(proxifiedTheme, proxifiedRuntime) : {}; ++ } = uniProps ? uniProps(proxifiedTheme, proxifiedRuntime) : {}; + const styleSecrets = getSecrets(narrowedProps.style); + const contentContainerStyleSecrets = getSecrets(narrowedProps.contentContainerStyle); + const finalProps = { +- ...deepMergeObjects(mappingsProps, unistyleProps, props), ++ ...deepMergeObjects(mappingsProps, unistyleProps, componentProps), + ...(narrowedProps.style ? { + style: styleSecrets.styles + } : {}), +diff --git a/node_modules/react-native-unistyles/lib/module/web/css/core.js b/node_modules/react-native-unistyles/lib/module/web/css/core.js +index 2bd36d5..6a321bf 100644 +--- a/node_modules/react-native-unistyles/lib/module/web/css/core.js ++++ b/node_modules/react-native-unistyles/lib/module/web/css/core.js +@@ -2,6 +2,11 @@ + + import { isPseudoClass } from '../convert/pseudo'; + import { getMediaQuery } from '../utils'; ++// hash:hover and hash::before belong to hash. Hashes have no colons, a forChild one keeps ' > *' ++export const getClassNameHash = className => { ++ const pseudoIndex = className.indexOf(':'); ++ return pseudoIndex === -1 ? className : className.slice(0, pseudoIndex); ++}; + export const convertToCSS = (hash, value, state) => { + Object.entries(value).forEach(([styleKey, styleValue]) => { + if (styleKey[0] === '_') { +diff --git a/node_modules/react-native-unistyles/lib/module/web/css/sheet.js b/node_modules/react-native-unistyles/lib/module/web/css/sheet.js +new file mode 100644 +index 0000000..cec10a6 +--- /dev/null ++++ b/node_modules/react-native-unistyles/lib/module/web/css/sheet.js +@@ -0,0 +1,209 @@ ++"use strict"; ++ ++import { hyphenate, isServer } from '../utils'; ++// Paseo backport of https://github.com/jpudysz/react-native-unistyles/pull/1354 (released in 3.8.0). ++// CSSState used to rewrite the text of the style tag on every added and removed class, and the browser ++// then restyled the whole document. Rules now change one at a time through the CSSOM. ++ ++// Styles without a media query get a group too, so every group is an ordinary child list of one top level rule ++const BASE_MEDIA_QUERY = '@media all'; ++export const getSelector = className => `.${className}`; ++export const getDeclarations = styles => { ++ let declarations = ''; ++ for (const [propertyKey, value] of styles) { ++ if (value === undefined) { ++ continue; ++ } ++ declarations += `${hyphenate(propertyKey)}:${value};`; ++ } ++ return declarations; ++}; ++const insertRule = (parent, rule, index = parent.cssRules.length) => { ++ try { ++ return parent.cssRules[parent.insertRule(rule, index)]; ++ } catch { ++ // The browser can't parse it, like a pseudo-element it doesn't support yet: a text sheet drops it too ++ return undefined; ++ } ++}; ++const indexOfRule = (parent, rule) => Array.prototype.indexOf.call(parent.cssRules, rule); ++ ++// Keeps the styles of CSSState in the style tag through the CSSOM, never its text, so another runtime keeps its rules ++export class CSSSheet { ++ tag = null; ++ sheet = null; ++ groups = new Map(); ++ themes = new Map(); ++ hasServerStyles = false; ++ constructor(themesCSS, styles) { ++ this.themesCSS = themesCSS; ++ this.styles = styles; ++ if (isServer()) { ++ return; ++ } ++ const existingTag = document.getElementById('unistyles-web'); ++ if (existingTag) { ++ this.tag = existingTag; ++ // A tag from another runtime has no text, its rules live in the CSSOM ++ this.hasServerStyles = Boolean(this.tag.textContent); ++ this.sheet = this.hasServerStyles ? null : this.tag.sheet; ++ return; ++ } ++ this.tag = document.createElement('style'); ++ this.tag.id = 'unistyles-web'; ++ document.head.appendChild(this.tag); ++ this.sheet = this.tag.sheet; ++ } ++ refresh = () => { ++ const sheet = this.getSheet(); ++ if (sheet) { ++ this.insertGroups(sheet); ++ } ++ }; ++ syncClass = (mediaQuery, className) => { ++ const sheet = this.getSheet(); ++ if (!sheet) { ++ return; ++ } ++ this.insertGroups(sheet); ++ const group = this.groups.get(mediaQuery); ++ if (group) { ++ this.syncGroupClass(group, className, this.styles.get(mediaQuery)?.get(className)); ++ } ++ }; ++ ++ // False only when the browser rejects the theme, so CSSState keeps the CSS that is applied ++ syncTheme = (key, css = this.themesCSS.get(key)) => { ++ const sheet = this.getThemeSheet(); ++ const current = this.themes.get(key); ++ if (!sheet || css === undefined) { ++ return true; ++ } ++ ++ // The theme goes last on every update, so it wins over the same theme of a runtime added to the tag later ++ const rule = insertRule(sheet, css); ++ ++ // Inserted before the old rule goes, so a theme the browser rejects keeps the previous variables ++ if (!rule) { ++ return false; ++ } ++ const currentIndex = current ? indexOfRule(sheet, current) : -1; ++ if (currentIndex >= 0) { ++ sheet.deleteRule(currentIndex); ++ } ++ this.themes.set(key, rule); ++ return true; ++ }; ++ reset = () => { ++ const sheet = this.tag?.sheet; ++ if (sheet && sheet === this.sheet) { ++ this.deleteOwnRules(sheet, new Set(Array.from(this.groups.values(), group => group?.rule))); ++ } ++ this.groups.clear(); ++ }; ++ getSheet = () => { ++ if (!this.tag) { ++ return null; ++ } ++ if (!this.tag.isConnected) { ++ document.head.appendChild(this.tag); ++ } ++ ++ // Another runtime on the tag may have cleared the server text and filled the tag through the CSSOM already ++ if (this.hasServerStyles) { ++ this.hasServerStyles = false; ++ if (this.tag.textContent) { ++ this.tag.textContent = ''; ++ } ++ } ++ const sheet = this.tag.sheet; ++ ++ // A new sheet lost every rule: the server one was replaced, or the tag was rewritten or attached again ++ if (sheet && sheet !== this.sheet) { ++ this.sheet = sheet; ++ this.insertAll(sheet); ++ } ++ return sheet; ++ }; ++ getThemeSheet = () => { ++ if (this.hasServerStyles) { ++ return this.tag?.sheet ?? null; ++ } ++ return this.getSheet(); ++ }; ++ insertAll = sheet => { ++ this.groups.clear(); ++ // A theme added on top of server styles another runtime already replaced is still in this sheet ++ this.deleteOwnRules(sheet, new Set(this.themes.values())); ++ this.themes.clear(); ++ this.themesCSS.forEach((_, key) => this.syncTheme(key)); ++ this.insertGroups(sheet); ++ this.groups.forEach((group, mediaQuery) => { ++ if (!group) { ++ return; ++ } ++ this.styles.get(mediaQuery)?.forEach((styles, className) => this.syncGroupClass(group, className, styles)); ++ }); ++ }; ++ ++ // Every group of the styles map gets created, empty ones too, so a group appended later is always the last one ++ insertGroups = sheet => { ++ if (this.groups.size === this.styles.size) { ++ return; ++ } ++ this.styles.forEach((_, mediaQuery) => { ++ if (this.groups.has(mediaQuery)) { ++ return; ++ } ++ const rule = insertRule(sheet, `${mediaQuery || BASE_MEDIA_QUERY}{}`); ++ this.groups.set(mediaQuery, rule ? { ++ rule, ++ rules: [], ++ classes: new Map(), ++ rejected: new Map() ++ } : null); ++ }); ++ }; ++ syncGroupClass = (group, className, styles) => { ++ const current = group.classes.get(className); ++ if (!styles) { ++ group.rejected.delete(className); ++ if (current) { ++ const index = group.rules.indexOf(current.rule); ++ group.rule.deleteRule(index); ++ group.rules.splice(index, 1); ++ group.classes.delete(className); ++ } ++ return; ++ } ++ const declarations = getDeclarations(styles); ++ if (current) { ++ if (current.declarations !== declarations) { ++ current.rule.style.cssText = declarations; ++ current.declarations = declarations; ++ } ++ return; ++ } ++ if (group.rejected.get(className) === declarations) { ++ return; ++ } ++ const rule = insertRule(group.rule, `${getSelector(className)}{${declarations}}`); ++ if (rule) { ++ group.rules.push(rule); ++ group.classes.set(className, { ++ rule, ++ declarations ++ }); ++ group.rejected.delete(className); ++ return; ++ } ++ group.rejected.set(className, declarations); ++ }; ++ deleteOwnRules = (sheet, rules) => { ++ for (let index = sheet.cssRules.length - 1; index >= 0; index--) { ++ if (rules.has(sheet.cssRules[index])) { ++ sheet.deleteRule(index); ++ } ++ } ++ }; ++} +diff --git a/node_modules/react-native-unistyles/lib/module/web/css/state.js b/node_modules/react-native-unistyles/lib/module/web/css/state.js +index 88e02b3..583aaaa 100644 +--- a/node_modules/react-native-unistyles/lib/module/web/css/state.js ++++ b/node_modules/react-native-unistyles/lib/module/web/css/state.js +@@ -1,55 +1,77 @@ + "use strict"; + + import { convertUnistyles } from '../convert'; +-import { hyphenate, isServer } from '../utils'; +-import { convertToCSS } from './core'; +-const safeGetMap = (map, key) => { +- const nextLevelMap = map.get(key); +- if (!nextLevelMap) { +- const newMap = new Map(); +- map.set(key, newMap); +- return newMap; +- } +- return nextLevelMap; ++import { hyphenate } from '../utils'; ++import { convertToCSS, getClassNameHash } from './core'; ++import { CSSSheet, getDeclarations, getSelector } from './sheet'; ++import { safeGetMap } from './utils'; ++const forEachClassName = (classNames, callback) => { ++ classNames?.forEach((names, mediaQuery) => names.forEach(className => callback(mediaQuery, className))); + }; ++// Paseo backport of https://github.com/jpudysz/react-native-unistyles/pull/1354 (released in 3.8.0). + export class CSSState { +- mainMap = new Map(); +- mqMap = new Map(); +- styleTag = null; ++ mainMap = new Map([['', new Map()]]); + themesCSS = new Map(); ++ owners = new Map(); ++ sheet = new CSSSheet(this.themesCSS, this.mainMap); + constructor(services) { + this.services = services; +- if (isServer()) { +- return; +- } +- const ssrTag = document.getElementById('unistyles-web'); +- if (ssrTag) { +- this.styleTag = ssrTag; +- return; +- } +- this.styleTag = document.createElement('style'); +- this.styleTag.id = 'unistyles-web'; +- document.head.appendChild(this.styleTag); + } + set = ({ + className, + propertyKey, + value, +- mediaQuery = '', +- isMq ++ mediaQuery = '' + }) => { +- const firstLevelMap = isMq ? this.mqMap : this.mainMap; +- const secondLevelMap = safeGetMap(firstLevelMap, mediaQuery); ++ const secondLevelMap = safeGetMap(this.mainMap, mediaQuery); + const thirdLevelMap = safeGetMap(secondLevelMap, className); + thirdLevelMap.set(propertyKey, value); ++ ++ // The owner comes from the class name, so hydrated styles have one too ++ const owner = safeGetMap(this.owners, getClassNameHash(className)); ++ const classNames = owner.get(mediaQuery) ?? new Set(); ++ classNames.add(className); ++ owner.set(mediaQuery, classNames); + }; + add = (hash, values) => { +- convertToCSS(hash, convertUnistyles(values, this.services.runtime), this); +- this.recreate(); +- }; +- recreate = () => { +- if (this.styleTag) { +- this.styleTag.innerText = this.getStyles(); ++ const styles = new Map(); ++ convertToCSS(hash, convertUnistyles(values, this.services.runtime), { ++ set: ({ ++ className, ++ propertyKey, ++ value, ++ mediaQuery = '' ++ }) => { ++ safeGetMap(safeGetMap(styles, mediaQuery), className).set(propertyKey, value); ++ } ++ }); ++ const previousClassNames = this.owners.get(hash); ++ forEachClassName(previousClassNames, (mediaQuery, className) => { ++ this.mainMap.get(mediaQuery)?.get(className)?.clear(); ++ }); ++ this.owners.delete(hash); ++ styles.forEach((classes, mediaQuery) => { ++ classes.forEach((properties, className) => { ++ properties.forEach((value, propertyKey) => this.set({ ++ mediaQuery, ++ className, ++ propertyKey, ++ value ++ })); ++ }); ++ }); ++ const classNames = this.owners.get(hash); ++ forEachClassName(previousClassNames, (mediaQuery, className) => { ++ if (!classNames?.get(mediaQuery)?.has(className)) { ++ this.mainMap.get(mediaQuery)?.delete(className); ++ this.sheet.syncClass(mediaQuery, className); ++ } ++ }); ++ forEachClassName(classNames, this.sheet.syncClass); ++ ++ // syncClass already brings back the rules the tag lost, refresh does it when nothing was synced ++ if (!previousClassNames && !classNames) { ++ this.sheet.refresh(); + } + }; + addTheme = (theme, values) => { +@@ -63,62 +85,55 @@ export class CSSState { + } + }; + Object.entries(values).forEach(([key, value]) => convertToCSS(key, value)); ++ + if (theme === 'light' || theme === 'dark') { +- this.themesCSS.set(`media ${theme}`, `@media (prefers-color-scheme: ${theme}){:root{${themeVars}}}`); ++ this.setThemeCSS(`media ${theme}`, `@media (prefers-color-scheme: ${theme}){:root{${themeVars}}}`); ++ } ++ this.setThemeCSS(theme, `:root.${theme}{${themeVars}}`); ++ }; ++ setThemeCSS = (key, css) => { ++ if (this.sheet.syncTheme(key, css)) { ++ this.themesCSS.set(key, css); + } +- this.themesCSS.set(theme, `:root.${theme}{${themeVars}}`); + }; + remove = hash => { +- this.mainMap.forEach(styles => { +- styles.delete(hash); ++ const classNames = this.owners.get(hash); ++ this.owners.delete(hash); ++ forEachClassName(classNames, (mediaQuery, className) => { ++ this.mainMap.get(mediaQuery)?.delete(className); ++ this.sheet.syncClass(mediaQuery, className); + }); +- this.mqMap.forEach(styles => { +- styles.delete(hash); +- }); +- this.recreate(); ++ if (!classNames) { ++ this.sheet.refresh(); ++ } + }; + getStyles = () => { + let styles = Array.from(this.themesCSS.entries()).reduce((acc, [, themeCss]) => { + return acc + themeCss; + }, ''); +- const generate = (mediaQuery, secondLevelMap) => { ++ for (const [mediaQuery, secondLevelMap] of this.mainMap) { + if (mediaQuery) { + styles += `${mediaQuery}{`; + } + for (const [className, thirdLevelMap] of secondLevelMap) { +- styles += `.${className}{`; +- for (const [propertyKey, value] of thirdLevelMap) { +- if (value === undefined) { +- continue; +- } +- styles += `${hyphenate(propertyKey)}:${value};`; +- } +- styles += '}'; ++ styles += `${getSelector(className)}{${getDeclarations(thirdLevelMap)}}`; + } + if (mediaQuery) { + styles += '}'; + } +- }; +- for (const [mediaQuery, secondLevelMap] of this.mainMap) { +- generate(mediaQuery, secondLevelMap); +- } +- for (const [mediaQuery, secondLevelMap] of this.mqMap) { +- generate(mediaQuery, secondLevelMap); + } + return styles; + }; + getState = () => { +- const getState = map => { +- return Array.from(map).map(([mediaQuery, classNames]) => { +- return [mediaQuery, Array.from(classNames.entries()).map(([className, style]) => { +- return [className, Array.from(style.entries()).map(([property, value]) => { +- return [property, value]; +- })]; ++ const mainState = Array.from(this.mainMap).map(([mediaQuery, classNames]) => { ++ return [mediaQuery, Array.from(classNames.entries()).map(([className, style]) => { ++ return [className, Array.from(style.entries()).map(([property, value]) => { ++ return [property, value]; + })]; +- }); +- }; +- const mainState = getState(this.mainMap); +- const mqState = getState(this.mqMap); ++ })]; ++ }); ++ // Always empty, media query styles live in mainState. Kept for the shape hydrate reads ++ const mqState = []; + const config = this.services.state.getConfig(); + return { + mainState, +@@ -126,11 +141,12 @@ export class CSSState { + config + }; + }; +- hydrate = ({ +- mainState, +- mqState +- }) => { +- const hydrateState = (map, isMq = false) => { ++ hydrate = state => { ++ if (state === this.hydratedState) { ++ return; ++ } ++ this.hydratedState = state; ++ const hydrateState = map => { + map.forEach(([mediaQuery, classNames]) => { + classNames.forEach(([className, style]) => { + style.forEach(([propertyKey, value]) => { +@@ -138,19 +154,22 @@ export class CSSState { + className, + propertyKey, + value, +- mediaQuery, +- isMq ++ mediaQuery + }); + }); ++ this.sheet.syncClass(mediaQuery, className); + }); + }); + }; +- hydrateState(mainState); +- hydrateState(mqState, true); ++ hydrateState(state.mainState); ++ hydrateState(state.mqState); + }; + reset = () => { +- this.mqMap.clear(); + this.mainMap.clear(); ++ this.mainMap.set('', new Map()); ++ this.owners.clear(); ++ this.hydratedState = undefined; ++ this.sheet.reset(); + }; + } + //# sourceMappingURL=state.js.map +\ No newline at end of file +diff --git a/node_modules/react-native-unistyles/lib/module/web/css/utils.js b/node_modules/react-native-unistyles/lib/module/web/css/utils.js +index e46697a..080cde0 100644 +--- a/node_modules/react-native-unistyles/lib/module/web/css/utils.js ++++ b/node_modules/react-native-unistyles/lib/module/web/css/utils.js +@@ -1,6 +1,5 @@ + "use strict"; + +-import { hyphenate } from '../utils'; + export const safeGetMap = (map, key) => { + const nextLevelMap = map.get(key); + if (!nextLevelMap) { +@@ -10,32 +9,4 @@ export const safeGetMap = (map, key) => { + } + return nextLevelMap; + }; +-export const getStylesFromState = state => { +- let styles = ''; +- const generate = (mediaQuery, secondLevelMap) => { +- if (mediaQuery) { +- styles += `${mediaQuery}{`; +- } +- for (const [className, thirdLevelMap] of secondLevelMap) { +- styles += `.${className}{`; +- for (const [propertyKey, value] of thirdLevelMap) { +- if (value === undefined) { +- continue; +- } +- styles += `${hyphenate(propertyKey)}:${value};`; +- } +- styles += '}'; +- } +- if (mediaQuery) { +- styles += '}'; +- } +- }; +- for (const [mediaQuery, secondLevelMap] of state.mainMap) { +- generate(mediaQuery, secondLevelMap); +- } +- for (const [mediaQuery, secondLevelMap] of state.mqMap) { +- generate(mediaQuery, secondLevelMap); +- } +- return styles; +-}; + //# sourceMappingURL=utils.js.map +\ No newline at end of file +diff --git a/node_modules/react-native-unistyles/lib/module/web/registry.js b/node_modules/react-native-unistyles/lib/module/web/registry.js +index 6362f43..31e3190 100644 +--- a/node_modules/react-native-unistyles/lib/module/web/registry.js ++++ b/node_modules/react-native-unistyles/lib/module/web/registry.js +@@ -6,6 +6,17 @@ export class UnistylesRegistry { + stylesheets = new Map(); + stylesCache = new Set(); + stylesCounter = new Map(); ++ cleanupGeneration = 0; ++ finalizerTokens = new WeakMap(); ++ finalizationRegistry = typeof FinalizationRegistry === 'undefined' ? undefined : new FinalizationRegistry(({ ++ hash, ++ generation ++ }) => { ++ if (generation !== this.cleanupGeneration) { ++ return; ++ } ++ this.decrementAndMaybeCleanup(hash); ++ }); + disposeListenersMap = new Map(); + dependenciesMap = new Map(); + constructor(services) { +@@ -46,26 +57,48 @@ export class UnistylesRegistry { + this.disposeListenersMap.set(stylesheet, dispose); + }; + connect = (ref, hash) => { +- const stylesCounter = this.stylesCounter.get(hash) ?? new Set(); +- stylesCounter.add(ref); +- this.stylesCounter.set(hash, stylesCounter); ++ this.stylesCounter.set(hash, (this.stylesCounter.get(hash) ?? 0) + 1); ++ if (!this.finalizationRegistry) { ++ return; ++ } ++ const token = {}; ++ const tokensByHash = this.finalizerTokens.get(ref) ?? new Map(); ++ const tokens = tokensByHash.get(hash) ?? []; ++ tokens.push(token); ++ tokensByHash.set(hash, tokens); ++ this.finalizerTokens.set(ref, tokensByHash); ++ this.finalizationRegistry.register(ref, { ++ hash, ++ generation: this.cleanupGeneration ++ }, token); + }; + remove = (ref, hash) => { +- const stylesCounter = this.stylesCounter.get(hash) ?? new Set(); +- stylesCounter.delete(ref); +- if (stylesCounter.size === 0) { +- // Move this to the end of the event loop so the element is removed from the DOM +- return Promise.resolve().then(() => { +- // Check if element is still in the DOM +- if (document.querySelector(`.${hash}`)) { +- return false; +- } +- this.css.remove(hash); +- this.stylesCache.delete(hash); +- return true; +- }); ++ const token = this.finalizerTokens.get(ref)?.get(hash)?.pop(); ++ if (token) { ++ this.finalizationRegistry?.unregister(token); ++ } ++ return this.decrementAndMaybeCleanup(hash); ++ }; ++ decrementAndMaybeCleanup = hash => { ++ const next = (this.stylesCounter.get(hash) ?? 0) - 1; ++ if (next > 0) { ++ this.stylesCounter.set(hash, next); ++ return Promise.resolve(false); + } +- return Promise.resolve(false); ++ this.stylesCounter.delete(hash); ++ // Move this to the end of the event loop so the element is removed from the DOM ++ return Promise.resolve().then(() => { ++ // Check if element is still in the DOM ++ if ((this.stylesCounter.get(hash) ?? 0) > 0) { ++ return false; ++ } ++ if (document.querySelector(`.${hash}`)) { ++ return false; ++ } ++ this.css.remove(hash); ++ this.stylesCache.delete(hash); ++ return true; ++ }); + }; + add = (value, forChild) => { + const generatedHash = generateHash(value); +@@ -87,7 +120,10 @@ export class UnistylesRegistry { + this.css.add(hash, value); + }; + reset = () => { ++ this.cleanupGeneration += 1; ++ this.disposeListenersMap.forEach(dispose => dispose()); + this.css.reset(); ++ this.stylesheets.clear(); + this.stylesCache.clear(); + this.dependenciesMap.clear(); + this.disposeListenersMap.clear(); +diff --git a/node_modules/react-native-unistyles/lib/module/web/runtime.js b/node_modules/react-native-unistyles/lib/module/web/runtime.js +index 7f13a06..a4b6570 100644 +--- a/node_modules/react-native-unistyles/lib/module/web/runtime.js ++++ b/node_modules/react-native-unistyles/lib/module/web/runtime.js +@@ -31,10 +31,17 @@ export class UnistylesRuntime { + return this.darkMedia; + } + get colorScheme() { ++ // Read the scheme through fresh lists, never through lightMedia/darkMedia. Chromium defers ++ // MediaQueryList change events while the document is hidden and drops the pending event ++ // of any list whose `matches` was read before the document became visible again, which ++ // would silence the adaptive-theme listeners registered on those two lists. ++ if (isServer()) { ++ return ColorScheme.Unspecified; ++ } + switch (true) { +- case this.getLightMedia()?.matches: ++ case window.matchMedia('(prefers-color-scheme: light)').matches: + return ColorScheme.Light; +- case this.getDarkMedia()?.matches: ++ case window.matchMedia('(prefers-color-scheme: dark)').matches: + return ColorScheme.Dark; + default: + return ColorScheme.Unspecified; +@@ -186,7 +193,6 @@ export class UnistylesRuntime { + return convertTheme(key, value); + }))); + this.services.registry.css.addTheme(themeName, newTheme); +- this.services.registry.css.recreate(); + } + }; + getTheme = (themeName = this.themeName, CSSVars = false) => { +diff --git a/node_modules/react-native-unistyles/src/core/withUnistyles/withUnistyles.native.tsx b/node_modules/react-native-unistyles/src/core/withUnistyles/withUnistyles.native.tsx +index 27723c0..8ab111a 100644 +--- a/node_modules/react-native-unistyles/src/core/withUnistyles/withUnistyles.native.tsx ++++ b/node_modules/react-native-unistyles/src/core/withUnistyles/withUnistyles.native.tsx +@@ -63,6 +63,7 @@ export const withUnistyles = , PropsWithUnistyles>((props, ref) => { + const narrowedProps = props as PropsWithUnistyles & UnistyleStyles ++ const { uniProps, ...componentProps } = narrowedProps + const NativeComponent = Component as ComponentType + + // @ts-ignore we don't know the type of the component +@@ -89,15 +90,15 @@ export const withUnistyles = , PropsWithUnistyles>((props, ref) => { + const narrowedProps = props as PropsWithUnistyles & UnistyleStyles ++ const { uniProps, ...componentProps } = narrowedProps + const styleClassNames = getClassName(narrowedProps.style, true) + const contentContainerStyleClassNames = getClassName(narrowedProps.contentContainerStyle) + const { proxifiedRuntime, proxifiedTheme } = useProxifiedUnistyles() + + const { key: mappingsKey, ...mappingsProps } = mappings ? mappings(proxifiedTheme, proxifiedRuntime) : {} +- const { key: uniPropsKey, ...unistyleProps } = narrowedProps.uniProps +- ? narrowedProps.uniProps(proxifiedTheme, proxifiedRuntime) ++ const { key: uniPropsKey, ...unistyleProps } = uniProps ++ ? uniProps(proxifiedTheme, proxifiedRuntime) + : {} + + const emptyStyles = narrowedProps.style +@@ -46,7 +47,7 @@ export const withUnistyles = , state: CSSState) => { ++type StyleTarget = Pick ++ ++// hash:hover and hash::before belong to hash. Hashes have no colons, a forChild one keeps ' > *' ++export const getClassNameHash = (className: string) => { ++ const pseudoIndex = className.indexOf(':') ++ ++ return pseudoIndex === -1 ? className : className.slice(0, pseudoIndex) ++} ++ ++export const convertToCSS = (hash: string, value: Record, state: StyleTarget) => { + Object.entries(value).forEach(([styleKey, styleValue]) => { + if (styleKey[0] === '_') { + const isStylePseudoClass = isPseudoClass(styleKey) +diff --git a/node_modules/react-native-unistyles/src/web/css/sheet.ts b/node_modules/react-native-unistyles/src/web/css/sheet.ts +new file mode 100644 +index 0000000..cb1afb9 +--- /dev/null ++++ b/node_modules/react-native-unistyles/src/web/css/sheet.ts +@@ -0,0 +1,264 @@ ++import { hyphenate, isServer } from '../utils' ++ ++// Paseo backport of https://github.com/jpudysz/react-native-unistyles/pull/1354 (released in 3.8.0). ++// CSSState used to rewrite the text of the style tag on every added and removed class, and the browser ++// then restyled the whole document. Rules now change one at a time through the CSSOM. ++ ++type Styles = Map ++type StylesMap = Map> ++type RuleParent = CSSStyleSheet | CSSGroupingRule ++type Group = { ++ rule: CSSGroupingRule ++ rules: Array ++ classes: Map ++ rejected: Map ++} ++ ++// Styles without a media query get a group too, so every group is an ordinary child list of one top level rule ++const BASE_MEDIA_QUERY = '@media all' ++ ++export const getSelector = (className: string) => `.${className}` ++ ++export const getDeclarations = (styles: Styles) => { ++ let declarations = '' ++ ++ for (const [propertyKey, value] of styles) { ++ if (value === undefined) { ++ continue ++ } ++ ++ declarations += `${hyphenate(propertyKey)}:${value};` ++ } ++ ++ return declarations ++} ++ ++const insertRule = (parent: RuleParent, rule: string, index = parent.cssRules.length) => { ++ try { ++ return parent.cssRules[parent.insertRule(rule, index)] ++ } catch { ++ // The browser can't parse it, like a pseudo-element it doesn't support yet: a text sheet drops it too ++ return undefined ++ } ++} ++ ++const indexOfRule = (parent: RuleParent, rule: CSSRule) => Array.prototype.indexOf.call(parent.cssRules, rule) ++ ++// Keeps the styles of CSSState in the style tag through the CSSOM, never its text, so another runtime keeps its rules ++export class CSSSheet { ++ private tag: HTMLStyleElement | null = null ++ private sheet: CSSStyleSheet | null = null ++ private groups = new Map() ++ private themes = new Map() ++ private hasServerStyles = false ++ ++ constructor( ++ private themesCSS: Map, ++ private styles: StylesMap, ++ ) { ++ if (isServer()) { ++ return ++ } ++ ++ const existingTag = document.getElementById('unistyles-web') ++ ++ if (existingTag) { ++ this.tag = existingTag as HTMLStyleElement ++ // A tag from another runtime has no text, its rules live in the CSSOM ++ this.hasServerStyles = Boolean(this.tag.textContent) ++ this.sheet = this.hasServerStyles ? null : this.tag.sheet ++ ++ return ++ } ++ ++ this.tag = document.createElement('style') ++ this.tag.id = 'unistyles-web' ++ document.head.appendChild(this.tag) ++ this.sheet = this.tag.sheet ++ } ++ ++ refresh = () => { ++ const sheet = this.getSheet() ++ ++ if (sheet) { ++ this.insertGroups(sheet) ++ } ++ } ++ ++ syncClass = (mediaQuery: string, className: string) => { ++ const sheet = this.getSheet() ++ ++ if (!sheet) { ++ return ++ } ++ ++ this.insertGroups(sheet) ++ ++ const group = this.groups.get(mediaQuery) ++ ++ if (group) { ++ this.syncGroupClass(group, className, this.styles.get(mediaQuery)?.get(className)) ++ } ++ } ++ ++ // False only when the browser rejects the theme, so CSSState keeps the CSS that is applied ++ syncTheme = (key: string, css = this.themesCSS.get(key)) => { ++ const sheet = this.getThemeSheet() ++ const current = this.themes.get(key) ++ ++ if (!sheet || css === undefined) { ++ return true ++ } ++ ++ // The theme goes last on every update, so it wins over the same theme of a runtime added to the tag later ++ const rule = insertRule(sheet, css) ++ ++ // Inserted before the old rule goes, so a theme the browser rejects keeps the previous variables ++ if (!rule) { ++ return false ++ } ++ ++ const currentIndex = current ? indexOfRule(sheet, current) : -1 ++ ++ if (currentIndex >= 0) { ++ sheet.deleteRule(currentIndex) ++ } ++ ++ this.themes.set(key, rule) ++ ++ return true ++ } ++ ++ reset = () => { ++ const sheet = this.tag?.sheet ++ ++ if (sheet && sheet === this.sheet) { ++ this.deleteOwnRules(sheet, new Set(Array.from(this.groups.values(), (group) => group?.rule))) ++ } ++ ++ this.groups.clear() ++ } ++ ++ private getSheet = () => { ++ if (!this.tag) { ++ return null ++ } ++ ++ if (!this.tag.isConnected) { ++ document.head.appendChild(this.tag) ++ } ++ ++ // Another runtime on the tag may have cleared the server text and filled the tag through the CSSOM already ++ if (this.hasServerStyles) { ++ this.hasServerStyles = false ++ ++ if (this.tag.textContent) { ++ this.tag.textContent = '' ++ } ++ } ++ ++ const sheet = this.tag.sheet ++ ++ // A new sheet lost every rule: the server one was replaced, or the tag was rewritten or attached again ++ if (sheet && sheet !== this.sheet) { ++ this.sheet = sheet ++ this.insertAll(sheet) ++ } ++ ++ return sheet ++ } ++ ++ private getThemeSheet = () => { ++ if (this.hasServerStyles) { ++ return this.tag?.sheet ?? null ++ } ++ ++ return this.getSheet() ++ } ++ ++ private insertAll = (sheet: CSSStyleSheet) => { ++ this.groups.clear() ++ // A theme added on top of server styles another runtime already replaced is still in this sheet ++ this.deleteOwnRules(sheet, new Set(this.themes.values())) ++ this.themes.clear() ++ this.themesCSS.forEach((_, key) => this.syncTheme(key)) ++ this.insertGroups(sheet) ++ this.groups.forEach((group, mediaQuery) => { ++ if (!group) { ++ return ++ } ++ ++ this.styles.get(mediaQuery)?.forEach((styles, className) => this.syncGroupClass(group, className, styles)) ++ }) ++ } ++ ++ // Every group of the styles map gets created, empty ones too, so a group appended later is always the last one ++ private insertGroups = (sheet: CSSStyleSheet) => { ++ if (this.groups.size === this.styles.size) { ++ return ++ } ++ ++ this.styles.forEach((_, mediaQuery) => { ++ if (this.groups.has(mediaQuery)) { ++ return ++ } ++ ++ const rule = insertRule(sheet, `${mediaQuery || BASE_MEDIA_QUERY}{}`) as CSSGroupingRule | undefined ++ ++ this.groups.set(mediaQuery, rule ? { rule, rules: [], classes: new Map(), rejected: new Map() } : null) ++ }) ++ } ++ ++ private syncGroupClass = (group: Group, className: string, styles?: Styles) => { ++ const current = group.classes.get(className) ++ ++ if (!styles) { ++ group.rejected.delete(className) ++ ++ if (current) { ++ const index = group.rules.indexOf(current.rule) ++ ++ group.rule.deleteRule(index) ++ group.rules.splice(index, 1) ++ group.classes.delete(className) ++ } ++ ++ return ++ } ++ ++ const declarations = getDeclarations(styles) ++ ++ if (current) { ++ if (current.declarations !== declarations) { ++ current.rule.style.cssText = declarations ++ current.declarations = declarations ++ } ++ ++ return ++ } ++ ++ if (group.rejected.get(className) === declarations) { ++ return ++ } ++ ++ const rule = insertRule(group.rule, `${getSelector(className)}{${declarations}}`) as CSSStyleRule | undefined ++ ++ if (rule) { ++ group.rules.push(rule) ++ group.classes.set(className, { rule, declarations }) ++ group.rejected.delete(className) ++ ++ return ++ } ++ ++ group.rejected.set(className, declarations) ++ } ++ ++ private deleteOwnRules = (sheet: CSSStyleSheet, rules: Set) => { ++ for (let index = sheet.cssRules.length - 1; index >= 0; index--) { ++ if (rules.has(sheet.cssRules[index])) { ++ sheet.deleteRule(index) ++ } ++ } ++ } ++} +diff --git a/node_modules/react-native-unistyles/src/web/css/state.ts b/node_modules/react-native-unistyles/src/web/css/state.ts +index a0eea57..27d71a1 100644 +--- a/node_modules/react-native-unistyles/src/web/css/state.ts ++++ b/node_modules/react-native-unistyles/src/web/css/state.ts +@@ -2,73 +2,86 @@ import type { UnistylesValues } from '../../types' + import type { UnistylesServices } from '../types' + + import { convertUnistyles } from '../convert' +-import { hyphenate, isServer } from '../utils' +-import { convertToCSS } from './core' ++import { hyphenate } from '../utils' ++import { convertToCSS, getClassNameHash } from './core' ++import { CSSSheet, getDeclarations, getSelector } from './sheet' ++import { safeGetMap } from './utils' + + type MapType = Map>> ++type ClassNames = Map> + type SetProps = { + mediaQuery?: string + className: string +- isMq?: boolean + propertyKey: string + value: any + } + type HydrateState = Array<[string, Array<[string, Array<[string, any]>]>]> + +-const safeGetMap = (map: Map>, key: string) => { +- const nextLevelMap = map.get(key) +- +- if (!nextLevelMap) { +- const newMap = new Map() +- +- map.set(key, newMap) +- +- return newMap +- } +- +- return nextLevelMap ++const forEachClassName = ( ++ classNames: ClassNames | undefined, ++ callback: (mediaQuery: string, className: string) => void, ++) => { ++ classNames?.forEach((names, mediaQuery) => names.forEach((className) => callback(mediaQuery, className))) + } + ++// Paseo backport of https://github.com/jpudysz/react-native-unistyles/pull/1354 (released in 3.8.0). + export class CSSState { +- mainMap: MapType = new Map() +- mqMap: MapType = new Map() +- private styleTag: HTMLStyleElement | null = null ++ mainMap: MapType = new Map([['', new Map()]]) + private themesCSS = new Map() ++ private owners = new Map() ++ private hydratedState?: ReturnType ++ private sheet = new CSSSheet(this.themesCSS, this.mainMap) + +- constructor(private services: UnistylesServices) { +- if (isServer()) { +- return +- } ++ constructor(private services: UnistylesServices) {} + +- const ssrTag = document.getElementById('unistyles-web') ++ set = ({ className, propertyKey, value, mediaQuery = '' }: SetProps) => { ++ const secondLevelMap = safeGetMap(this.mainMap, mediaQuery) ++ const thirdLevelMap = safeGetMap(secondLevelMap, className) + +- if (ssrTag) { +- this.styleTag = ssrTag as HTMLStyleElement ++ thirdLevelMap.set(propertyKey, value) + +- return +- } ++ // The owner comes from the class name, so hydrated styles have one too ++ const owner: ClassNames = safeGetMap(this.owners, getClassNameHash(className)) ++ const classNames = owner.get(mediaQuery) ?? new Set() + +- this.styleTag = document.createElement('style') +- this.styleTag.id = 'unistyles-web' +- document.head.appendChild(this.styleTag) ++ classNames.add(className) ++ owner.set(mediaQuery, classNames) + } + +- set = ({ className, propertyKey, value, mediaQuery = '', isMq }: SetProps) => { +- const firstLevelMap = isMq ? this.mqMap : this.mainMap +- const secondLevelMap = safeGetMap(firstLevelMap, mediaQuery) +- const thirdLevelMap = safeGetMap(secondLevelMap, className) ++ add = (hash: string, values: UnistylesValues) => { ++ const styles: MapType = new Map() + +- thirdLevelMap.set(propertyKey, value) +- } ++ convertToCSS(hash, convertUnistyles(values, this.services.runtime), { ++ set: ({ className, propertyKey, value, mediaQuery = '' }) => { ++ safeGetMap(safeGetMap(styles, mediaQuery), className).set(propertyKey, value) ++ }, ++ }) + +- add = (hash: string, values: UnistylesValues) => { +- convertToCSS(hash, convertUnistyles(values, this.services.runtime), this) +- this.recreate() +- } ++ const previousClassNames = this.owners.get(hash) ++ ++ forEachClassName(previousClassNames, (mediaQuery, className) => { ++ this.mainMap.get(mediaQuery)?.get(className)?.clear() ++ }) ++ this.owners.delete(hash) ++ styles.forEach((classes, mediaQuery) => { ++ classes.forEach((properties, className) => { ++ properties.forEach((value, propertyKey) => this.set({ mediaQuery, className, propertyKey, value })) ++ }) ++ }) ++ ++ const classNames = this.owners.get(hash) ++ ++ forEachClassName(previousClassNames, (mediaQuery, className) => { ++ if (!classNames?.get(mediaQuery)?.has(className)) { ++ this.mainMap.get(mediaQuery)?.delete(className) ++ this.sheet.syncClass(mediaQuery, className) ++ } ++ }) ++ forEachClassName(classNames, this.sheet.syncClass) + +- recreate = () => { +- if (this.styleTag) { +- this.styleTag.innerText = this.getStyles() ++ // syncClass already brings back the rules the tag lost, refresh does it when nothing was synced ++ if (!previousClassNames && !classNames) { ++ this.sheet.refresh() + } + } + +@@ -90,20 +103,30 @@ export class CSSState { + Object.entries(values).forEach(([key, value]) => convertToCSS(key, value)) + + if (theme === 'light' || theme === 'dark') { +- this.themesCSS.set(`media ${theme}`, `@media (prefers-color-scheme: ${theme}){:root{${themeVars}}}`) ++ this.setThemeCSS(`media ${theme}`, `@media (prefers-color-scheme: ${theme}){:root{${themeVars}}}`) + } + +- this.themesCSS.set(theme, `:root.${theme}{${themeVars}}`) ++ this.setThemeCSS(theme, `:root.${theme}{${themeVars}}`) ++ } ++ ++ private setThemeCSS = (key: string, css: string) => { ++ if (this.sheet.syncTheme(key, css)) { ++ this.themesCSS.set(key, css) ++ } + } + + remove = (hash: string) => { +- this.mainMap.forEach((styles) => { +- styles.delete(hash) +- }) +- this.mqMap.forEach((styles) => { +- styles.delete(hash) ++ const classNames = this.owners.get(hash) ++ ++ this.owners.delete(hash) ++ forEachClassName(classNames, (mediaQuery, className) => { ++ this.mainMap.get(mediaQuery)?.delete(className) ++ this.sheet.syncClass(mediaQuery, className) + }) +- this.recreate() ++ ++ if (!classNames) { ++ this.sheet.refresh() ++ } + } + + getStyles = () => { +@@ -111,23 +134,13 @@ export class CSSState { + return acc + themeCss + }, '') + +- const generate = (mediaQuery: string, secondLevelMap: Map>) => { ++ for (const [mediaQuery, secondLevelMap] of this.mainMap) { + if (mediaQuery) { + styles += `${mediaQuery}{` + } + + for (const [className, thirdLevelMap] of secondLevelMap) { +- styles += `.${className}{` +- +- for (const [propertyKey, value] of thirdLevelMap) { +- if (value === undefined) { +- continue +- } +- +- styles += `${hyphenate(propertyKey)}:${value};` +- } +- +- styles += '}' ++ styles += `${getSelector(className)}{${getDeclarations(thirdLevelMap)}}` + } + + if (mediaQuery) { +@@ -135,43 +148,38 @@ export class CSSState { + } + } + +- for (const [mediaQuery, secondLevelMap] of this.mainMap) { +- generate(mediaQuery, secondLevelMap) +- } +- +- for (const [mediaQuery, secondLevelMap] of this.mqMap) { +- generate(mediaQuery, secondLevelMap) +- } +- + return styles + } + + getState = () => { +- const getState = (map: MapType) => { +- return Array.from(map).map(([mediaQuery, classNames]) => { +- return [ +- mediaQuery, +- Array.from(classNames.entries()).map(([className, style]) => { +- return [ +- className, +- Array.from(style.entries()).map(([property, value]) => { +- return [property, value] +- }), +- ] +- }), +- ] +- }) as HydrateState +- } +- +- const mainState = getState(this.mainMap) +- const mqState = getState(this.mqMap) ++ const mainState = Array.from(this.mainMap).map(([mediaQuery, classNames]) => { ++ return [ ++ mediaQuery, ++ Array.from(classNames.entries()).map(([className, style]) => { ++ return [ ++ className, ++ Array.from(style.entries()).map(([property, value]) => { ++ return [property, value] ++ }), ++ ] ++ }), ++ ] ++ }) as HydrateState ++ // Always empty, media query styles live in mainState. Kept for the shape hydrate reads ++ const mqState: HydrateState = [] + const config = this.services.state.getConfig() + + return { mainState, mqState, config } + } + +- hydrate = ({ mainState, mqState }: ReturnType) => { +- const hydrateState = (map: HydrateState, isMq = false) => { ++ hydrate = (state: ReturnType) => { ++ if (state === this.hydratedState) { ++ return ++ } ++ ++ this.hydratedState = state ++ ++ const hydrateState = (map: HydrateState) => { + map.forEach(([mediaQuery, classNames]) => { + classNames.forEach(([className, style]) => { + style.forEach(([propertyKey, value]) => { +@@ -180,19 +188,22 @@ export class CSSState { + propertyKey, + value, + mediaQuery, +- isMq, + }) + }) ++ this.sheet.syncClass(mediaQuery, className) + }) + }) + } + +- hydrateState(mainState) +- hydrateState(mqState, true) ++ hydrateState(state.mainState) ++ hydrateState(state.mqState) + } + + reset = () => { +- this.mqMap.clear() + this.mainMap.clear() ++ this.mainMap.set('', new Map()) ++ this.owners.clear() ++ this.hydratedState = undefined ++ this.sheet.reset() + } + } +diff --git a/node_modules/react-native-unistyles/src/web/css/utils.ts b/node_modules/react-native-unistyles/src/web/css/utils.ts +index 6747104..95293aa 100644 +--- a/node_modules/react-native-unistyles/src/web/css/utils.ts ++++ b/node_modules/react-native-unistyles/src/web/css/utils.ts +@@ -1,7 +1,3 @@ +-import type { CSSState } from './state' +- +-import { hyphenate } from '../utils' +- + export const safeGetMap = (map: Map>, key: string) => { + const nextLevelMap = map.get(key) + +@@ -15,41 +11,3 @@ export const safeGetMap = (map: Map>, key: string) => { + + return nextLevelMap + } +- +-export const getStylesFromState = (state: CSSState) => { +- let styles = '' +- +- const generate = (mediaQuery: string, secondLevelMap: Map>) => { +- if (mediaQuery) { +- styles += `${mediaQuery}{` +- } +- +- for (const [className, thirdLevelMap] of secondLevelMap) { +- styles += `.${className}{` +- +- for (const [propertyKey, value] of thirdLevelMap) { +- if (value === undefined) { +- continue +- } +- +- styles += `${hyphenate(propertyKey)}:${value};` +- } +- +- styles += '}' +- } +- +- if (mediaQuery) { +- styles += '}' +- } +- } +- +- for (const [mediaQuery, secondLevelMap] of state.mainMap) { +- generate(mediaQuery, secondLevelMap) +- } +- +- for (const [mediaQuery, secondLevelMap] of state.mqMap) { +- generate(mediaQuery, secondLevelMap) +- } +- +- return styles +-} +diff --git a/node_modules/react-native-unistyles/src/web/registry.ts b/node_modules/react-native-unistyles/src/web/registry.ts +index 39e0d9d..a21ba95 100644 +--- a/node_modules/react-native-unistyles/src/web/registry.ts ++++ b/node_modules/react-native-unistyles/src/web/registry.ts +@@ -9,7 +9,24 @@ import { error, extractUnistyleDependencies, generateHash } from './utils' + export class UnistylesRegistry { + private readonly stylesheets = new Map, StyleSheet>() + private readonly stylesCache = new Set() +- private readonly stylesCounter = new Map>() ++ // Use counter instead of Set to avoid retaining detached DOM nodes ++ // FR is a fallback when remove() is missed ++ private readonly stylesCounter = new Map() ++ // Bumped on reset() so stale FR callbacks are ignored ++ private cleanupGeneration = 0 ++ // Per-registration unregister token, so remove() cancels only its own registration ++ private readonly finalizerTokens = new WeakMap>>() ++ // FR isn't available on every runtime - fall back to counter-only cleanup ++ private readonly finalizationRegistry = ++ typeof FinalizationRegistry === 'undefined' ++ ? undefined ++ : new FinalizationRegistry<{ hash: string; generation: number }>(({ hash, generation }) => { ++ if (generation !== this.cleanupGeneration) { ++ return ++ } ++ ++ this.decrementAndMaybeCleanup(hash) ++ }) + private readonly disposeListenersMap = new Map() + private readonly dependenciesMap = new Map, Set>() + readonly css: CSSState +@@ -78,33 +95,61 @@ export class UnistylesRegistry { + } + + connect = (ref: HTMLElement, hash: string) => { +- const stylesCounter = this.stylesCounter.get(hash) ?? new Set() ++ this.stylesCounter.set(hash, (this.stylesCounter.get(hash) ?? 0) + 1) + +- stylesCounter.add(ref) +- this.stylesCounter.set(hash, stylesCounter) ++ if (!this.finalizationRegistry) { ++ return ++ } ++ ++ const token = {} ++ const tokensByHash = this.finalizerTokens.get(ref) ?? new Map>() ++ const tokens = tokensByHash.get(hash) ?? [] ++ ++ tokens.push(token) ++ tokensByHash.set(hash, tokens) ++ this.finalizerTokens.set(ref, tokensByHash) ++ this.finalizationRegistry.register(ref, { hash, generation: this.cleanupGeneration }, token) + } + + remove = (ref: HTMLElement, hash: string) => { +- const stylesCounter = this.stylesCounter.get(hash) ?? new Set() ++ const token = this.finalizerTokens.get(ref)?.get(hash)?.pop() + +- stylesCounter.delete(ref) ++ if (token) { ++ this.finalizationRegistry?.unregister(token) ++ } + +- if (stylesCounter.size === 0) { +- // Move this to the end of the event loop so the element is removed from the DOM +- return Promise.resolve().then(() => { +- // Check if element is still in the DOM +- if (document.querySelector(`.${hash}`)) { +- return false +- } ++ return this.decrementAndMaybeCleanup(hash) ++ } ++ ++ private decrementAndMaybeCleanup = (hash: string): Promise => { ++ const next = (this.stylesCounter.get(hash) ?? 0) - 1 + +- this.css.remove(hash) +- this.stylesCache.delete(hash) ++ if (next > 0) { ++ this.stylesCounter.set(hash, next) + +- return true +- }) ++ return Promise.resolve(false) + } + +- return Promise.resolve(false) ++ // Drop the empty bucket from the Map ++ this.stylesCounter.delete(hash) ++ ++ // Move this to the end of the event loop so the element is removed from the DOM ++ return Promise.resolve().then(() => { ++ // New connect raced in during the microtask ++ if ((this.stylesCounter.get(hash) ?? 0) > 0) { ++ return false ++ } ++ ++ // Check if element is still in the DOM ++ if (document.querySelector(`.${hash}`)) { ++ return false ++ } ++ ++ this.css.remove(hash) ++ this.stylesCache.delete(hash) ++ ++ return true ++ }) + } + + add = (value: UnistylesValues, forChild?: boolean) => { +@@ -126,7 +171,11 @@ export class UnistylesRegistry { + } + + reset = () => { ++ // Invalidate pending FR callbacks from this generation ++ this.cleanupGeneration += 1 ++ this.disposeListenersMap.forEach((dispose) => dispose()) + this.css.reset() ++ this.stylesheets.clear() + this.stylesCache.clear() + this.dependenciesMap.clear() + this.disposeListenersMap.clear() +diff --git a/node_modules/react-native-unistyles/src/web/runtime.ts b/node_modules/react-native-unistyles/src/web/runtime.ts +index a16dac0..5236f38 100644 +--- a/node_modules/react-native-unistyles/src/web/runtime.ts ++++ b/node_modules/react-native-unistyles/src/web/runtime.ts +@@ -39,10 +39,18 @@ export class UnistylesRuntime { + } + + get colorScheme() { ++ // Read the scheme through fresh lists, never through lightMedia/darkMedia. Chromium defers ++ // MediaQueryList change events while the document is hidden and drops the pending event ++ // of any list whose `matches` was read before the document became visible again, which ++ // would silence the adaptive-theme listeners registered on those two lists. ++ if (isServer()) { ++ return ColorScheme.Unspecified ++ } ++ + switch (true) { +- case this.getLightMedia()?.matches: ++ case window.matchMedia('(prefers-color-scheme: light)').matches: + return ColorScheme.Light +- case this.getDarkMedia()?.matches: ++ case window.matchMedia('(prefers-color-scheme: dark)').matches: + return ColorScheme.Dark + default: + return ColorScheme.Unspecified +@@ -239,7 +247,6 @@ export class UnistylesRuntime { + ) as UnistylesTheme, + ) + this.services.registry.css.addTheme(themeName, newTheme) +- this.services.registry.css.recreate() + } + } + diff --git a/scripts/postinstall-patches.mjs b/scripts/postinstall-patches.mjs index 96d08c1fe1..eb05bc508b 100644 --- a/scripts/postinstall-patches.mjs +++ b/scripts/postinstall-patches.mjs @@ -23,10 +23,29 @@ const patchedPackages = [ // Layout constraints: backport of https://github.com/jpudysz/react-native-unistyles/pull/1357 // (commit from the root the commit hands us, so a concurrent window-size commit is kept). // Remove the ShadowTreeManager hunk when the installed release includes that PR. + // Web stylesheet: backport of https://github.com/jpudysz/react-native-unistyles/pull/1354 + // (3.8.0). Classes are added and removed as CSSOM rules, not by rewriting the style tag, which + // made the browser restyle the whole document. Remove the web/css hunks at >= 3.8.0. { nodeModulesPath: "node_modules/react-native-unistyles", patchPrefix: "react-native-unistyles+", }, + // Portal state lives in a store that each host subscribes to. As the provider's context value it + // changed on every portal add, update and remove, and React searched every fiber under the + // provider (the whole app) for consumers. No upstream fix; keep while the app uses this package. + // Keyed hosts: backport of https://github.com/gorhom/react-native-portal/pull/62, unreleased + // after 1.0.14. Remove the PortalHost hunks when an installed release includes it. + { + nodeModulesPath: "node_modules/@gorhom/portal", + patchPrefix: "@gorhom+portal+", + }, + // Backport of React 19.3.0 to the development builds: clear each render timing after reporting + // it. The browser keeps every performance measure for the life of the page, so a development + // session held millions of them and gigabytes of memory. Remove when react-dom is >= 19.3.0. + { + nodeModulesPath: "node_modules/react-dom", + patchPrefix: "react-dom+", + }, // Backport of https://github.com/software-mansion/react-native-reanimated/pull/10435 // (Reanimated 4.7.1): skip synchronous Android prop updates for unmounted view tags // instead of throwing and printing a full stack trace on the UI thread per tag per event.