From 269c675e6571b668ac9b4e818ed0c8256252feb7 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Wed, 25 Nov 2026 23:28:15 +0100 Subject: [PATCH 01/15] feat: add_page(stylesheets=...) for stylesheets only one page loads --- docs/styling/custom-stylesheets.md | 14 ++ news/+page-stylesheets.feature.md | 1 + .../news/+page-stylesheets.feature.md | 1 + .../src/reflex_base/compiler/templates.py | 8 +- .../src/reflex_base/plugins/base.py | 2 + .../src/reflex_base/plugins/compiler.py | 2 + reflex/app.py | 9 ++ reflex/compiler/compiler.py | 146 +++++++++++++----- reflex/compiler/plugins/builtin.py | 1 + reflex/page.py | 9 +- .../tests_playwright/test_stateless_app.py | 46 +++++- tests/units/compiler/test_compiler.py | 85 ++++++++++ tests/units/test_page.py | 2 + 13 files changed, 284 insertions(+), 42 deletions(-) create mode 100644 news/+page-stylesheets.feature.md create mode 100644 packages/reflex-base/news/+page-stylesheets.feature.md diff --git a/docs/styling/custom-stylesheets.md b/docs/styling/custom-stylesheets.md index 4c43af84291..240dd9d2915 100644 --- a/docs/styling/custom-stylesheets.md +++ b/docs/styling/custom-stylesheets.md @@ -33,6 +33,20 @@ Without a leading slash the path is considered relative to the current page rout not work for routes containing more than one path component, like `/blog/my-cool-post`. ``` +## Page Stylesheets + +A stylesheet that only one page needs can be passed to `add_page` (or `@rx.page`) instead. It takes the same files and URLs as `rx.App`: + +```python +app.add_page( + pricing, + route="/pricing", + stylesheets=["/pages/pricing.css"], # This path is relative to assets/ +) +``` + +The page links its stylesheets in the `` after the app's, so its rules win over the app's rules of equal specificity. On client-side navigation the stylesheets load before the page renders, and they are removed when the user leaves the page. + ## Styling with CSS You can use CSS variables directly in your Reflex app by passing them alongside the appropriae props. Create a `style.css` file inside the `assets` folder with the following lines: diff --git a/news/+page-stylesheets.feature.md b/news/+page-stylesheets.feature.md new file mode 100644 index 00000000000..942e6bd36a6 --- /dev/null +++ b/news/+page-stylesheets.feature.md @@ -0,0 +1 @@ +`add_page` and `@rx.page` take `stylesheets=`, stylesheets only that page loads, after the app's: `app.add_page(pricing, stylesheets=["/pages/pricing.css"])`. They take the same asset files and URLs as `rx.App(stylesheets=...)` and become the page's React Router `links`, so they are in the prerendered ``, load before the page renders on client-side navigation and are removed when it is left. diff --git a/packages/reflex-base/news/+page-stylesheets.feature.md b/packages/reflex-base/news/+page-stylesheets.feature.md new file mode 100644 index 00000000000..cc7ef283f39 --- /dev/null +++ b/packages/reflex-base/news/+page-stylesheets.feature.md @@ -0,0 +1 @@ +`page_template` takes `links`, exported from the route module as React Router's `links`, `PageContext` carries the page's `stylesheets`, and the `add_page` a plugin's `register_route` receives takes `stylesheets=`. diff --git a/packages/reflex-base/src/reflex_base/compiler/templates.py b/packages/reflex-base/src/reflex_base/compiler/templates.py index 77f28862881..d3b7d79d81f 100644 --- a/packages/reflex-base/src/reflex_base/compiler/templates.py +++ b/packages/reflex-base/src/reflex_base/compiler/templates.py @@ -10,7 +10,7 @@ from reflex_base import constants from reflex_base.utils import memo_paths from reflex_base.utils.format import json_dumps -from reflex_base.vars.base import VarData +from reflex_base.vars.base import Var, VarData if TYPE_CHECKING: from reflex.compiler.utils import _ImportDict @@ -653,6 +653,7 @@ def page_template( render: dict[str, Any], route: str = "", client_state_owns: Sequence[str] = (), + links: Var | None = None, ): """Template for a single react page. @@ -684,6 +685,8 @@ def page_template( given, the exported component is ``Component`` wrapped in a client state scope claiming them, so hooks in the page body resolve inside it. + links: The link descriptors the route module exports as ``links``, + which React Router renders in the head while the route is shown. Returns: Rendered React page component as string. @@ -703,6 +706,7 @@ def page_template( if client_state_owns else "Component" ) + links_str = f"export const links = () => {links!s};\n" if links is not None else "" return f"""{imports_str} {dynamic_imports_str} @@ -716,7 +720,7 @@ def page_template( {_RenderUtils.render(render)} ) }} -{display_name_str} +{display_name_str}{links_str} export default {export_str}; """ diff --git a/packages/reflex-base/src/reflex_base/plugins/base.py b/packages/reflex-base/src/reflex_base/plugins/base.py index 3f52afe48ee..7221bc5f56b 100644 --- a/packages/reflex-base/src/reflex_base/plugins/base.py +++ b/packages/reflex-base/src/reflex_base/plugins/base.py @@ -80,6 +80,7 @@ def __call__( on_load: "EventType[()] | None" = None, meta: Sequence["Mapping[str, Any] | Component"] = ..., context: dict[str, Any] | None = None, + stylesheets: Sequence[str] = ..., **extra_page_args: Any, ) -> None: """Stage a page contribution owned by the calling plugin. @@ -93,6 +94,7 @@ def __call__( on_load: The event handler(s) called each time the page loads. meta: The metadata of the page. context: Values passed to the page for custom page-specific logic. + stylesheets: Stylesheets only this page loads, after the app's. extra_page_args: Keyword arguments added by concrete ``App`` subclasses that extend page registration. """ diff --git a/packages/reflex-base/src/reflex_base/plugins/compiler.py b/packages/reflex-base/src/reflex_base/plugins/compiler.py index a30aa95fd39..e119da15168 100644 --- a/packages/reflex-base/src/reflex_base/plugins/compiler.py +++ b/packages/reflex-base/src/reflex_base/plugins/compiler.py @@ -599,6 +599,8 @@ class PageContext(BaseContext): output_path: str | None = None output_code: str | None = None source_module: str | None = None + # The stylesheets only this page loads, as ``App.stylesheets`` takes them. + stylesheets: Sequence[str] = () # Stack of ``id(component)`` for components whose subtree is # memoize-suppressed. Populated by ``MemoizeStatefulPlugin`` when it # encounters a ``MemoizationLeaf``-style snapshot boundary and popped on diff --git a/reflex/app.py b/reflex/app.py index 3d9229c599c..229b52d9171 100644 --- a/reflex/app.py +++ b/reflex/app.py @@ -323,6 +323,7 @@ class UnevaluatedPage: on_load: EventType[()] | None = None meta: Sequence[Mapping[str, Any] | Component] = () context: Mapping[str, Any] = dataclasses.field(default_factory=dict) + stylesheets: Sequence[str] = () _source_module: str | None = None def merged_with(self, other: UnevaluatedPage) -> UnevaluatedPage: @@ -1522,6 +1523,7 @@ def add_page( on_load: EventType[()] | None = None, meta: Sequence[Mapping[str, Any] | Component] = constants.DefaultPage.META_LIST, context: dict[str, Any] | None = None, + stylesheets: Sequence[str] = (), ): """Add a page to the app. @@ -1537,6 +1539,9 @@ def add_page( on_load: The event handler(s) that will be called each time the page load. meta: The metadata of the page. context: Values passed to page for custom page-specific logic. + stylesheets: Stylesheets only this page loads, after the app's, as + ``App.stylesheets`` takes them: files or directories in the + assets directory, or URLs. Raises: BackendVarFormatError: When title, description or image is a field with no frontend var. @@ -1554,6 +1559,7 @@ def add_page( on_load, meta, context, + stylesheets=stylesheets, ) ) @@ -1567,6 +1573,7 @@ def _prepare_page( on_load: EventType[()] | None = None, meta: Sequence[Mapping[str, Any] | Component] = constants.DefaultPage.META_LIST, context: dict[str, Any] | None = None, + stylesheets: Sequence[str] = (), ) -> _PreparedPage: """Validate and normalize a page without mutating app route state. @@ -1583,6 +1590,7 @@ def _prepare_page( on_load: The event handler(s) called each time the page loads. meta: The metadata of the page. context: Values passed to page for custom page-specific logic. + stylesheets: Stylesheets only this page loads, after the app's. Returns: The validated page descriptor and its dynamic route arguments. @@ -1635,6 +1643,7 @@ def _prepare_page( on_load=on_load, meta=meta, context=context or {}, + stylesheets=tuple(stylesheets), _source_module=source_module, ) diff --git a/reflex/compiler/compiler.py b/reflex/compiler/compiler.py index 83d72e5dd12..7cd668b1488 100644 --- a/reflex/compiler/compiler.py +++ b/reflex/compiler/compiler.py @@ -41,8 +41,8 @@ ImportVar, ParsedImportDict, ) -from reflex_base.vars.base import LiteralVar, Var -from reflex_base.vars.sequence import LiteralStringVar +from reflex_base.vars.base import LiteralVar, Var, VarData +from reflex_base.vars.sequence import LiteralArrayVar, LiteralStringVar from reflex_components_core.base.app_wrap import AppWrap from reflex_components_core.base.fragment import Fragment from reflex_components_radix.plugin import RadixThemesPlugin @@ -400,44 +400,72 @@ def _compile_root_stylesheet( sheet for plugin in active_plugins for sheet in plugin.get_stylesheet_paths() ]) - failed_to_import_sass = False - assets_app_path = Path.cwd() / constants.Dirs.APP_ASSETS - stylesheets_files: list[Path] = [] stylesheets_urls = [] for stylesheet in stylesheets: - if not utils.is_valid_url(stylesheet): - # check if stylesheet provided exists. - stylesheet_full_path = assets_app_path / stylesheet.strip("/") + if utils.is_valid_url(stylesheet): + stylesheets_urls.append(stylesheet) + else: + stylesheets_files.extend(_resolve_stylesheet_files(stylesheet)) - if not stylesheet_full_path.exists(): - msg = f"The stylesheet file {stylesheet_full_path} does not exist." - raise FileNotFoundError(msg) + sheets.extend(dict.fromkeys(stylesheets_urls)) - if stylesheet_full_path.is_dir(): - all_files = ( - file - for ext in constants.Reflex.STYLESHEETS_SUPPORTED - for file in stylesheet_full_path.rglob("*." + ext) - ) - for file in all_files: - if file.is_dir(): - continue - # Validate the stylesheet. - _validate_stylesheet(file, assets_app_path) - stylesheets_files.append(file) + for target_path in _compile_stylesheet_files(stylesheets_files): + str_target_path = "./" + target_path + sheets.append(str_target_path) if str_target_path not in sheets else None - else: - # Validate the stylesheet. - _validate_stylesheet(stylesheet_full_path, assets_app_path) - stylesheets_files.append(stylesheet_full_path) - else: - stylesheets_urls.append(stylesheet) + return templates.styles_template(stylesheets=sheets) - sheets.extend(dict.fromkeys(stylesheets_urls)) - for stylesheet in stylesheets_files: +def _resolve_stylesheet_files(stylesheet: str) -> list[Path]: + """Find the asset files a stylesheet path names. + + Args: + stylesheet: A stylesheet file or directory, relative to the assets directory. + + Returns: + The stylesheet file, or the supported stylesheet files below the directory. + + Raises: + FileNotFoundError: If the stylesheet does not exist. + """ + assets_app_path = Path.cwd() / constants.Dirs.APP_ASSETS + stylesheet_full_path = assets_app_path / stylesheet.strip("/") + + if not stylesheet_full_path.exists(): + msg = f"The stylesheet file {stylesheet_full_path} does not exist." + raise FileNotFoundError(msg) + + if not stylesheet_full_path.is_dir(): + _validate_stylesheet(stylesheet_full_path, assets_app_path) + return [stylesheet_full_path] + + files = [ + file + for ext in constants.Reflex.STYLESHEETS_SUPPORTED + for file in stylesheet_full_path.rglob("*." + ext) + if not file.is_dir() + ] + for file in files: + _validate_stylesheet(file, assets_app_path) + return files + + +def _compile_stylesheet_files(files: Iterable[Path]) -> list[str]: + """Copy stylesheet asset files into the styles directory, compiling sass. + + Args: + files: The stylesheet files in the assets directory. + + Returns: + The path of each compiled file relative to the styles directory. + """ + failed_to_import_sass = False + assets_app_path = Path.cwd() / constants.Dirs.APP_ASSETS + target_paths = [] + + for stylesheet in files: target_path = stylesheet.relative_to(assets_app_path).with_suffix(".css") target = get_web_dir() / constants.Dirs.STYLES / target_path @@ -464,18 +492,62 @@ def _compile_root_stylesheet( failed_to_import_sass = True # Use POSIX separators: this string is emitted verbatim into a CSS - # `@import url(...)`, where a backslash is an escape introducer, not a + # `@import url(...)` or a module specifier, where a backslash is not a # path separator, so `str(target_path)` would break nested stylesheets # on Windows. - str_target_path = "./" + target_path.as_posix() - sheets.append(str_target_path) if str_target_path not in sheets else None + target_paths.append(target_path.as_posix()) if failed_to_import_sass: logger.error( 'The `libsass` package is required to compile sass/scss stylesheet files. Run `pip install "libsass>=0.23.0"`.' ) - return templates.styles_template(stylesheets=sheets) + return target_paths + + +def compile_page_stylesheets(stylesheets: Sequence[str]) -> Var | None: + """Compile a page's stylesheets into the value of its route module's ``links``. + + React Router renders a route's ``links`` after the global stylesheet in the + prerendered head, loads them before rendering the route on client-side + navigation, and removes them when the route is left. Asset files are + copied (or compiled from sass) into the styles directory and imported as + URLs, so the bundler processes and fingerprints them; URLs are linked as + given. + + Args: + stylesheets: The page's stylesheets, as ``App.stylesheets`` takes them. + + Returns: + The page's stylesheet link descriptors in order, or None if it has none. + """ + hrefs: dict[str, Var | str] = {} + for stylesheet in stylesheets: + if utils.is_valid_url(stylesheet): + hrefs.setdefault(stylesheet, stylesheet) + continue + for target_path in _compile_stylesheet_files( + _resolve_stylesheet_files(stylesheet) + ): + if target_path in hrefs: + continue + name = f"reflexPageStylesheet{len(hrefs)}" + hrefs[target_path] = Var( + _js_expr=name, + _var_type=str, + _var_data=VarData( + imports={ + f"$/{constants.Dirs.STYLES}/{target_path}?url": [ + ImportVar(tag=name, is_default=True) + ] + } + ), + ) + if not hrefs: + return None + return LiteralArrayVar.create([ + {"rel": "stylesheet", "href": href} for href in hrefs.values() + ]) def _compile_component(component: Component) -> str: @@ -820,6 +892,9 @@ def compile_page_from_context(page_ctx: PageContext) -> tuple[str, str]: ).items() } _apply_common_imports(imports) + links = compile_page_stylesheets(page_ctx.stylesheets) + if links is not None and (links_var_data := links._get_all_var_data()): + imports = utils.merge_imports(imports, links_var_data.imports) code = templates.page_template( imports=utils.compile_imports(imports), @@ -829,6 +904,7 @@ def compile_page_from_context(page_ctx: PageContext) -> tuple[str, str]: render=page_ctx.root_component.render(), route=page_ctx.route, client_state_owns=sorted(page_ctx.client_state_names), + links=links, ) return output_path, code diff --git a/reflex/compiler/plugins/builtin.py b/reflex/compiler/plugins/builtin.py index 6f49b7e0f55..4f1cc8bbace 100644 --- a/reflex/compiler/plugins/builtin.py +++ b/reflex/compiler/plugins/builtin.py @@ -68,6 +68,7 @@ def eval_page( route=page.route, root_component=component, source_module=getattr(page, "_source_module", None), + stylesheets=getattr(page, "stylesheets", ()), ) diff --git a/reflex/page.py b/reflex/page.py index 8cadbafc384..142c962461c 100644 --- a/reflex/page.py +++ b/reflex/page.py @@ -13,7 +13,7 @@ from reflex.utils.misc import is_page_meta_set if TYPE_CHECKING: - from collections.abc import Callable + from collections.abc import Callable, Sequence from typing import Any from reflex_base.event import EventType @@ -30,6 +30,7 @@ def page( meta: list[Any] | None = None, script_tags: list[Any] | None = None, on_load: EventType[()] | None = None, + stylesheets: Sequence[str] | None = None, ): """Decorate a function as a page. @@ -48,6 +49,7 @@ def page( meta: Additional meta to add to the page. on_load: The event handler(s) called when the page load. script_tags: scripts to attach to the page + stylesheets: Stylesheets only this page loads, after the app's. Returns: The decorated function. @@ -69,6 +71,8 @@ def decorator(render_fn: Callable): kwargs["script_tags"] = script_tags if on_load: kwargs["on_load"] = on_load + if stylesheets: + kwargs["stylesheets"] = stylesheets RegistrationContext.ensure_context().decorated_pages.append((render_fn, kwargs)) @@ -130,6 +134,7 @@ def __new__( meta: list[Any] | None = None, script_tags: list[Any] | None = None, on_load: EventType[()] | None = None, + stylesheets: Sequence[str] | None = None, ): """Decorate a function as a page. @@ -148,6 +153,7 @@ def __new__( meta: Additional meta to add to the page. on_load: The event handler(s) called when the page load. script_tags: scripts to attach to the page + stylesheets: Stylesheets only this page loads, after the app's. Returns: The decorated function. @@ -160,6 +166,7 @@ def __new__( meta=meta, script_tags=script_tags, on_load=on_load, + stylesheets=stylesheets, ) page = staticmethod(page) diff --git a/tests/integration/tests_playwright/test_stateless_app.py b/tests/integration/tests_playwright/test_stateless_app.py index 0451230a556..e2433289596 100644 --- a/tests/integration/tests_playwright/test_stateless_app.py +++ b/tests/integration/tests_playwright/test_stateless_app.py @@ -12,14 +12,31 @@ def StatelessApp(): - """A stateless app that renders a heading.""" + """A stateless app that renders a heading and a page with its own stylesheet.""" + from pathlib import Path + import reflex as rx def index(): - return rx.heading("This is a stateless app") - - app = rx.App(enable_state=False) + return rx.fragment( + rx.heading("This is a stateless app"), + rx.el.p("Index", class_name="page-styled", id="index-paragraph"), + rx.el.a("Styled", href="/styled", id="styled-link"), + ) + + def styled(): + return rx.fragment( + rx.el.p("Styled", class_name="page-styled", id="styled-paragraph"), + rx.el.a("Home", href="/", id="home-link"), + ) + + assets = Path.cwd() / "assets" + assets.mkdir(exist_ok=True) + (assets / "app.css").write_text(".page-styled { color: rgb(255, 0, 0); }") + (assets / "styled.css").write_text(".page-styled { color: rgb(0, 0, 255); }") + app = rx.App(enable_state=False, stylesheets=["/app.css"]) app.add_page(index) + app.add_page(styled, route="/styled", stylesheets=["/styled.css"]) @pytest.fixture(scope="module") @@ -59,3 +76,24 @@ def test_statelessness(stateless_app: AppHarness, page: Page): page.goto(stateless_app.frontend_url) expect(page.get_by_role("heading")).to_have_text("This is a stateless app") + + +def test_page_stylesheets(stateless_app: AppHarness, page: Page): + """A page's stylesheet applies after the app's, only while the page is shown. + + Args: + stateless_app: A harness for testing the stateless app. + page: A Playwright page. + """ + assert stateless_app.frontend_url is not None + page.goto(stateless_app.frontend_url) + expect(page.locator("#index-paragraph")).to_have_css("color", "rgb(255, 0, 0)") + + page.locator("#styled-link").click() + expect(page.locator("#styled-paragraph")).to_have_css("color", "rgb(0, 0, 255)") + + page.locator("#home-link").click() + expect(page.locator("#index-paragraph")).to_have_css("color", "rgb(255, 0, 0)") + + page.goto(stateless_app.frontend_url.rstrip("/") + "/styled") + expect(page.locator("#styled-paragraph")).to_have_css("color", "rgb(0, 0, 255)") diff --git a/tests/units/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py index 0f42e0ea870..a795d583cd7 100644 --- a/tests/units/compiler/test_compiler.py +++ b/tests/units/compiler/test_compiler.py @@ -328,6 +328,91 @@ def test_compile_stylesheets(tmp_path: Path, mocker: MockerFixture): ).read_text() +def test_page_stylesheets(tmp_path: Path, mocker: MockerFixture): + """A page's stylesheets become its route module's ``links`` export. + + Args: + tmp_path: The test directory. + mocker: Pytest mocker object. + """ + project = tmp_path / "test_project" + assets_dir = project / "assets" + (assets_dir / "pages").mkdir(parents=True) + (assets_dir / "pages" / "pricing.css").write_text(".pricing { color: red; }") + (assets_dir / "pages" / "pricing.txt").write_text("not a stylesheet") + (assets_dir / "shared.css").write_text(".shared { color: blue; }") + web_dir = project / constants.Dirs.WEB + mocker.patch("reflex.compiler.compiler.Path.cwd", return_value=project) + mocker.patch("reflex.compiler.compiler.get_web_dir", return_value=web_dir) + mocker.patch("reflex.compiler.utils.get_web_dir", return_value=web_dir) + + app = rx.App() + app.add_page( + rx.el.div("pricing"), + route="/pricing", + title="Pricing", + image="https://example.com/pricing.png", + stylesheets=[ + "/shared.css", + "https://fonts.example.com/font.css", + "/pages", + "/shared.css", + ], + ) + app.add_page(rx.el.div("plain"), route="/plain", title="Plain") + compile_ctx = CompileContext( + app=app, + pages=list(app._unevaluated_pages.values()), + hooks=CompilerHooks(plugins=default_page_plugins()), + ) + with compile_ctx: + compiled = compile_ctx.compile() + + assert compiled["pricing"].output_code == ( + 'import {Fragment,useEffect} from "react"\n' + 'import {jsx} from "@emotion/react"\n' + 'import reflexPageStylesheet0 from "$/styles/shared.css?url"\n' + 'import reflexPageStylesheet2 from "$/styles/pages/pricing.css?url"\n' + "\n\n\n\n\n" + "function Component() {\n" + "\n\n" + " return (\n" + ' jsx(Fragment,{},jsx("div",{},"pricing"),jsx("title",{},"Pricing"),' + 'jsx("meta",{content:"https://example.com/pricing.png",property:"og:image"},))\n' + " )\n" + "}\n" + 'Component.displayName = "Component(pricing)";\n' + "export const links = () => [" + '({ ["rel"] : "stylesheet", ["href"] : reflexPageStylesheet0 }), ' + '({ ["rel"] : "stylesheet", ["href"] : "https://fonts.example.com/font.css" }), ' + '({ ["rel"] : "stylesheet", ["href"] : reflexPageStylesheet2 })];\n' + "\n" + "export default Component;\n" + ) + assert "export const links" not in (compiled["plain"].output_code or "") + assert (web_dir / "styles" / "shared.css").read_text() == ".shared { color: blue; }" + assert (web_dir / "styles" / "pages" / "pricing.css").read_text() == ( + ".pricing { color: red; }" + ) + + +def test_page_stylesheet_not_found(tmp_path: Path, mocker: MockerFixture): + """A page stylesheet missing from the assets directory fails the compile. + + Args: + tmp_path: The test directory. + mocker: Pytest mocker object. + """ + mocker.patch("reflex.compiler.compiler.Path.cwd", return_value=tmp_path) + + with pytest.raises(FileNotFoundError) as err: + compiler.compile_page_stylesheets(["/missing.css"]) + + assert str(err.value) == ( + f"The stylesheet file {tmp_path / 'assets' / 'missing.css'} does not exist." + ) + + def test_compile_stylesheets_scss_sass(tmp_path: Path, mocker: MockerFixture): if importlib.util.find_spec("sass") is None: pytest.skip( diff --git a/tests/units/test_page.py b/tests/units/test_page.py index ba571cc1691..66e4e4ca020 100644 --- a/tests/units/test_page.py +++ b/tests/units/test_page.py @@ -87,6 +87,7 @@ def load_foo(): meta=[{"name": "keywords", "content": "foo, test"}], script_tags=["foo-script"], on_load=load_foo, + stylesheets=["/foo.css"], )(foo_) assert decorated_foo_ == foo_ assert len(clean_registration_context.decorated_pages) == 1 @@ -98,6 +99,7 @@ def load_foo(): "on_load": load_foo, "route": "foo", "script_tags": ["foo-script"], + "stylesheets": ["/foo.css"], "title": "Foo", } From 8771b81f5f182fb54e2e6ddab28a69b71a7d32ff Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 00:03:22 +0100 Subject: [PATCH 02/15] docs: link the page stylesheet example from the assets root so the docs route check passes --- docs/styling/custom-stylesheets.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/styling/custom-stylesheets.md b/docs/styling/custom-stylesheets.md index 240dd9d2915..cd4acd8fe1a 100644 --- a/docs/styling/custom-stylesheets.md +++ b/docs/styling/custom-stylesheets.md @@ -41,7 +41,7 @@ A stylesheet that only one page needs can be passed to `add_page` (or `@rx.page` app.add_page( pricing, route="/pricing", - stylesheets=["/pages/pricing.css"], # This path is relative to assets/ + stylesheets=["/pricing.css"], # This path is relative to assets/ ) ``` From 1c67e57c82f6b29b81b269a3e3d77c8f09b0c72e Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 00:03:57 +0100 Subject: [PATCH 03/15] docs: link the page stylesheet example from the assets root so the docs route check passes --- docs/styling/custom-stylesheets.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/styling/custom-stylesheets.md b/docs/styling/custom-stylesheets.md index 240dd9d2915..cd4acd8fe1a 100644 --- a/docs/styling/custom-stylesheets.md +++ b/docs/styling/custom-stylesheets.md @@ -41,7 +41,7 @@ A stylesheet that only one page needs can be passed to `add_page` (or `@rx.page` app.add_page( pricing, route="/pricing", - stylesheets=["/pages/pricing.css"], # This path is relative to assets/ + stylesheets=["/pricing.css"], # This path is relative to assets/ ) ``` From 0416e78c7cb9aa22d2c63f7e713665a92977a420 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 09:42:40 +0100 Subject: [PATCH 04/15] fix: keep a page's stylesheets when its @rx.page function is added again --- reflex/app.py | 1 + tests/units/test_app.py | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/reflex/app.py b/reflex/app.py index 30763cf937a..e5554f7a5b2 100644 --- a/reflex/app.py +++ b/reflex/app.py @@ -352,6 +352,7 @@ def merged_with(self, other: UnevaluatedPage) -> UnevaluatedPage: else other.description, on_load=self.on_load if self.on_load is not None else other.on_load, context=self.context if self.context is not None else other.context, + stylesheets=self.stylesheets or other.stylesheets, _source_module=self._source_module if self._source_module is not None else other._source_module, diff --git a/tests/units/test_app.py b/tests/units/test_app.py index 588d3a87162..15809fa8c0f 100644 --- a/tests/units/test_app.py +++ b/tests/units/test_app.py @@ -467,6 +467,29 @@ def test_apply_decorated_pages_uses_app_context( assert "decorated" in app._unevaluated_pages +def test_readded_page_keeps_its_stylesheets( + forked_registration_context: RegistrationContext, + app: App, + index_page: ComponentCallable, +): + """An ``@rx.page`` function the app added with stylesheets keeps them. + + Args: + forked_registration_context: The forked registration context. + app: The app to test. + index_page: The index page. + """ + forked_registration_context.decorated_pages.append(( + index_page, + {"route": "pricing"}, + )) + app.add_page(index_page, route="pricing", stylesheets=["/pricing.css"]) + + app._apply_decorated_pages() + + assert app._unevaluated_pages["pricing"].stylesheets == ("/pricing.css",) + + def test_add_page_invalid_api_route(app: App, index_page: ComponentCallable): """Test adding a page with an invalid route to an app. From 0a7f23610ddb2a17022240c01cdb9c149aad1ea3 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 09:42:51 +0100 Subject: [PATCH 05/15] fix: compile a sass stylesheet named like another one to its own file --- news/+stylesheet-namesakes.bugfix.md | 1 + reflex/compiler/compiler.py | 23 +++++++++++++- tests/units/compiler/test_compiler.py | 45 +++++++++++++++++++++++++++ 3 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 news/+stylesheet-namesakes.bugfix.md diff --git a/news/+stylesheet-namesakes.bugfix.md b/news/+stylesheet-namesakes.bugfix.md new file mode 100644 index 00000000000..3685aaa5a95 --- /dev/null +++ b/news/+stylesheet-namesakes.bugfix.md @@ -0,0 +1 @@ +A sass stylesheet named like another stylesheet next to it, such as `theme.scss` beside `theme.css`, no longer compiles to the same file in `.web/styles`, where whichever compiled last replaced the other: it keeps its suffix there, as `theme.scss.css`. diff --git a/reflex/compiler/compiler.py b/reflex/compiler/compiler.py index 7cd668b1488..23ad194a690 100644 --- a/reflex/compiler/compiler.py +++ b/reflex/compiler/compiler.py @@ -452,6 +452,22 @@ def _resolve_stylesheet_files(stylesheet: str) -> list[Path]: return files +def _has_stylesheet_namesake(stylesheet: Path) -> bool: + """Check whether a stylesheet of another supported type has the same name. + + Args: + stylesheet: The stylesheet file. + + Returns: + Whether a file next to it differs from it only in its stylesheet suffix. + """ + return any( + stylesheet.with_suffix(f".{ext}").is_file() + for ext in constants.Reflex.STYLESHEETS_SUPPORTED + if f".{ext}" != stylesheet.suffix + ) + + def _compile_stylesheet_files(files: Iterable[Path]) -> list[str]: """Copy stylesheet asset files into the styles directory, compiling sass. @@ -466,7 +482,12 @@ def _compile_stylesheet_files(files: Iterable[Path]) -> list[str]: target_paths = [] for stylesheet in files: - target_path = stylesheet.relative_to(assets_app_path).with_suffix(".css") + target_path = stylesheet.relative_to(assets_app_path) + if stylesheet.suffix != ".css" and _has_stylesheet_namesake(stylesheet): + # Compiling to the namesake's file would overwrite its CSS. + target_path = target_path.with_name(target_path.name + ".css") + else: + target_path = target_path.with_suffix(".css") target = get_web_dir() / constants.Dirs.STYLES / target_path target.parent.mkdir(parents=True, exist_ok=True) diff --git a/tests/units/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py index a795d583cd7..77d3d4ea011 100644 --- a/tests/units/compiler/test_compiler.py +++ b/tests/units/compiler/test_compiler.py @@ -504,6 +504,51 @@ def test_compile_stylesheets_scss_sass(tmp_path: Path, mocker: MockerFixture): ).read_text() == expected_result +def test_compile_stylesheets_sharing_a_name(tmp_path: Path, mocker: MockerFixture): + """A sass stylesheet named like another one keeps its suffix in the styles directory. + + Otherwise both would compile to the same file, and whichever compiled last + would supply the CSS for every page and the app. + + Args: + tmp_path: The test directory. + mocker: Pytest mocker object. + """ + if importlib.util.find_spec("sass") is None: + pytest.skip( + 'The `libsass` package is required to compile sass/scss stylesheet files. Run `pip install "libsass>=0.23.0"`.' + ) + assets_dir = tmp_path / "assets" + assets_dir.mkdir() + (assets_dir / "theme.css").write_text(".theme { color: red; }") + (assets_dir / "theme.scss").write_text(".theme { color: blue; }") + (assets_dir / "theme.sass").write_text(".theme\n\tcolor: green") + styles = tmp_path / constants.Dirs.WEB / "styles" + mocker.patch("reflex.compiler.compiler.Path.cwd", return_value=tmp_path) + mocker.patch("reflex.compiler.compiler.get_web_dir", return_value=tmp_path / ".web") + + _, code = compiler.compile_root_stylesheet(["/theme.css"], reset_style=False) + links = compiler.compile_page_stylesheets(["/theme.scss", "/theme.sass"]) + + assert code == "@layer __reflex_base;\n@import url('./theme.css');" + assert links is not None + var_data = links._get_all_var_data() + assert var_data is not None + assert var_data.imports == ( + ( + "$/styles/theme.scss.css?url", + (ImportVar(tag="reflexPageStylesheet0", is_default=True),), + ), + ( + "$/styles/theme.sass.css?url", + (ImportVar(tag="reflexPageStylesheet1", is_default=True),), + ), + ) + assert (styles / "theme.css").read_text() == ".theme { color: red; }" + assert (styles / "theme.scss.css").read_text() == ".theme{color:blue}\n" + assert (styles / "theme.sass.css").read_text() == ".theme{color:green}\n" + + def test_compile_stylesheets_nested_import_uses_posix_separators( tmp_path: Path, mocker: MockerFixture ): From 2ed603bbc1fd1e6842bd9cf111b8739bf52ae29e Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 09:43:26 +0100 Subject: [PATCH 06/15] test: navigate client-side between the pages of the page stylesheet test --- tests/integration/tests_playwright/test_stateless_app.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/tests/integration/tests_playwright/test_stateless_app.py b/tests/integration/tests_playwright/test_stateless_app.py index ec7e804da82..8e7379baa23 100644 --- a/tests/integration/tests_playwright/test_stateless_app.py +++ b/tests/integration/tests_playwright/test_stateless_app.py @@ -21,13 +21,13 @@ def index(): return rx.fragment( rx.heading("This is a stateless app"), rx.el.p("Index", class_name="page-styled", id="index-paragraph"), - rx.el.a("Styled", href="/styled", id="styled-link"), + rx.link("Styled", href="/styled", id="styled-link"), ) def styled(): return rx.fragment( rx.el.p("Styled", class_name="page-styled", id="styled-paragraph"), - rx.el.a("Home", href="/", id="home-link"), + rx.link("Home", href="/", id="home-link"), ) assets = Path.cwd() / "assets" @@ -81,6 +81,9 @@ def test_statelessness(stateless_app: AppHarness, page: Page): def test_page_stylesheets(stateless_app: AppHarness, page: Page): """A page's stylesheet applies after the app's, only while the page is shown. + The links navigate client-side, so React Router itself has to add the + stylesheet and remove it again: a document reload would drop it anyway. + Args: stateless_app: A harness for testing the stateless app. page: A Playwright page. @@ -88,12 +91,14 @@ def test_page_stylesheets(stateless_app: AppHarness, page: Page): assert stateless_app.frontend_url is not None page.goto(stateless_app.frontend_url) expect(page.locator("#index-paragraph")).to_have_css("color", "rgb(255, 0, 0)") + page.evaluate("() => { window.__same_document = true; }") page.locator("#styled-link").click() expect(page.locator("#styled-paragraph")).to_have_css("color", "rgb(0, 0, 255)") page.locator("#home-link").click() expect(page.locator("#index-paragraph")).to_have_css("color", "rgb(255, 0, 0)") + assert page.evaluate("() => window.__same_document") is True page.goto(stateless_app.frontend_url.rstrip("/") + "/styled") expect(page.locator("#styled-paragraph")).to_have_css("color", "rgb(0, 0, 255)") From 15e0b5a826cdccc52286503f8b30fcfe9c3af816 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 09:43:31 +0100 Subject: [PATCH 07/15] test: compare the plain page's compiled output in full --- tests/units/compiler/test_compiler.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/tests/units/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py index 77d3d4ea011..8f8aa6b2b4c 100644 --- a/tests/units/compiler/test_compiler.py +++ b/tests/units/compiler/test_compiler.py @@ -389,7 +389,21 @@ def test_page_stylesheets(tmp_path: Path, mocker: MockerFixture): "\n" "export default Component;\n" ) - assert "export const links" not in (compiled["plain"].output_code or "") + assert compiled["plain"].output_code == ( + 'import {Fragment,useEffect} from "react"\n' + 'import {jsx} from "@emotion/react"\n' + "\n\n\n\n\n" + "function Component() {\n" + "\n\n" + " return (\n" + ' jsx(Fragment,{},jsx("div",{},"plain"),jsx("title",{},"Plain"),' + 'jsx("meta",{content:"favicon.ico",property:"og:image"},))\n' + " )\n" + "}\n" + 'Component.displayName = "Component(plain)";\n' + "\n" + "export default Component;\n" + ) assert (web_dir / "styles" / "shared.css").read_text() == ".shared { color: blue; }" assert (web_dir / "styles" / "pages" / "pricing.css").read_text() == ( ".pricing { color: red; }" From bbf8c6955bfa9cfc986353f9f6639bcd16435231 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 09:42:40 +0100 Subject: [PATCH 08/15] fix: keep a page's stylesheets when its @rx.page function is added again --- reflex/app.py | 1 + tests/units/test_app.py | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/reflex/app.py b/reflex/app.py index 229b52d9171..8366046f727 100644 --- a/reflex/app.py +++ b/reflex/app.py @@ -343,6 +343,7 @@ def merged_with(self, other: UnevaluatedPage) -> UnevaluatedPage: else other.description, on_load=self.on_load if self.on_load is not None else other.on_load, context=self.context if self.context is not None else other.context, + stylesheets=self.stylesheets or other.stylesheets, _source_module=self._source_module if self._source_module is not None else other._source_module, diff --git a/tests/units/test_app.py b/tests/units/test_app.py index b348f5f4eac..b2e31df2b02 100644 --- a/tests/units/test_app.py +++ b/tests/units/test_app.py @@ -426,6 +426,29 @@ def test_apply_decorated_pages_uses_app_context( assert "decorated" in app._unevaluated_pages +def test_readded_page_keeps_its_stylesheets( + forked_registration_context: RegistrationContext, + app: App, + index_page: ComponentCallable, +): + """An ``@rx.page`` function the app added with stylesheets keeps them. + + Args: + forked_registration_context: The forked registration context. + app: The app to test. + index_page: The index page. + """ + forked_registration_context.decorated_pages.append(( + index_page, + {"route": "pricing"}, + )) + app.add_page(index_page, route="pricing", stylesheets=["/pricing.css"]) + + app._apply_decorated_pages() + + assert app._unevaluated_pages["pricing"].stylesheets == ("/pricing.css",) + + def test_add_page_invalid_api_route(app: App, index_page: ComponentCallable): """Test adding a page with an invalid route to an app. From d3ffa211d697edf24a523fb19d51271e46ffa49c Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 09:42:51 +0100 Subject: [PATCH 09/15] fix: compile a sass stylesheet named like another one to its own file --- news/+stylesheet-namesakes.bugfix.md | 1 + reflex/compiler/compiler.py | 23 +++++++++++++- tests/units/compiler/test_compiler.py | 45 +++++++++++++++++++++++++++ 3 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 news/+stylesheet-namesakes.bugfix.md diff --git a/news/+stylesheet-namesakes.bugfix.md b/news/+stylesheet-namesakes.bugfix.md new file mode 100644 index 00000000000..3685aaa5a95 --- /dev/null +++ b/news/+stylesheet-namesakes.bugfix.md @@ -0,0 +1 @@ +A sass stylesheet named like another stylesheet next to it, such as `theme.scss` beside `theme.css`, no longer compiles to the same file in `.web/styles`, where whichever compiled last replaced the other: it keeps its suffix there, as `theme.scss.css`. diff --git a/reflex/compiler/compiler.py b/reflex/compiler/compiler.py index 7cd668b1488..23ad194a690 100644 --- a/reflex/compiler/compiler.py +++ b/reflex/compiler/compiler.py @@ -452,6 +452,22 @@ def _resolve_stylesheet_files(stylesheet: str) -> list[Path]: return files +def _has_stylesheet_namesake(stylesheet: Path) -> bool: + """Check whether a stylesheet of another supported type has the same name. + + Args: + stylesheet: The stylesheet file. + + Returns: + Whether a file next to it differs from it only in its stylesheet suffix. + """ + return any( + stylesheet.with_suffix(f".{ext}").is_file() + for ext in constants.Reflex.STYLESHEETS_SUPPORTED + if f".{ext}" != stylesheet.suffix + ) + + def _compile_stylesheet_files(files: Iterable[Path]) -> list[str]: """Copy stylesheet asset files into the styles directory, compiling sass. @@ -466,7 +482,12 @@ def _compile_stylesheet_files(files: Iterable[Path]) -> list[str]: target_paths = [] for stylesheet in files: - target_path = stylesheet.relative_to(assets_app_path).with_suffix(".css") + target_path = stylesheet.relative_to(assets_app_path) + if stylesheet.suffix != ".css" and _has_stylesheet_namesake(stylesheet): + # Compiling to the namesake's file would overwrite its CSS. + target_path = target_path.with_name(target_path.name + ".css") + else: + target_path = target_path.with_suffix(".css") target = get_web_dir() / constants.Dirs.STYLES / target_path target.parent.mkdir(parents=True, exist_ok=True) diff --git a/tests/units/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py index a795d583cd7..77d3d4ea011 100644 --- a/tests/units/compiler/test_compiler.py +++ b/tests/units/compiler/test_compiler.py @@ -504,6 +504,51 @@ def test_compile_stylesheets_scss_sass(tmp_path: Path, mocker: MockerFixture): ).read_text() == expected_result +def test_compile_stylesheets_sharing_a_name(tmp_path: Path, mocker: MockerFixture): + """A sass stylesheet named like another one keeps its suffix in the styles directory. + + Otherwise both would compile to the same file, and whichever compiled last + would supply the CSS for every page and the app. + + Args: + tmp_path: The test directory. + mocker: Pytest mocker object. + """ + if importlib.util.find_spec("sass") is None: + pytest.skip( + 'The `libsass` package is required to compile sass/scss stylesheet files. Run `pip install "libsass>=0.23.0"`.' + ) + assets_dir = tmp_path / "assets" + assets_dir.mkdir() + (assets_dir / "theme.css").write_text(".theme { color: red; }") + (assets_dir / "theme.scss").write_text(".theme { color: blue; }") + (assets_dir / "theme.sass").write_text(".theme\n\tcolor: green") + styles = tmp_path / constants.Dirs.WEB / "styles" + mocker.patch("reflex.compiler.compiler.Path.cwd", return_value=tmp_path) + mocker.patch("reflex.compiler.compiler.get_web_dir", return_value=tmp_path / ".web") + + _, code = compiler.compile_root_stylesheet(["/theme.css"], reset_style=False) + links = compiler.compile_page_stylesheets(["/theme.scss", "/theme.sass"]) + + assert code == "@layer __reflex_base;\n@import url('./theme.css');" + assert links is not None + var_data = links._get_all_var_data() + assert var_data is not None + assert var_data.imports == ( + ( + "$/styles/theme.scss.css?url", + (ImportVar(tag="reflexPageStylesheet0", is_default=True),), + ), + ( + "$/styles/theme.sass.css?url", + (ImportVar(tag="reflexPageStylesheet1", is_default=True),), + ), + ) + assert (styles / "theme.css").read_text() == ".theme { color: red; }" + assert (styles / "theme.scss.css").read_text() == ".theme{color:blue}\n" + assert (styles / "theme.sass.css").read_text() == ".theme{color:green}\n" + + def test_compile_stylesheets_nested_import_uses_posix_separators( tmp_path: Path, mocker: MockerFixture ): From d1179aceaf418619234d952accaf9f8cb16e6ab3 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 09:43:26 +0100 Subject: [PATCH 10/15] test: navigate client-side between the pages of the page stylesheet test --- tests/integration/tests_playwright/test_stateless_app.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/tests/integration/tests_playwright/test_stateless_app.py b/tests/integration/tests_playwright/test_stateless_app.py index e2433289596..a6ff24c554b 100644 --- a/tests/integration/tests_playwright/test_stateless_app.py +++ b/tests/integration/tests_playwright/test_stateless_app.py @@ -21,13 +21,13 @@ def index(): return rx.fragment( rx.heading("This is a stateless app"), rx.el.p("Index", class_name="page-styled", id="index-paragraph"), - rx.el.a("Styled", href="/styled", id="styled-link"), + rx.link("Styled", href="/styled", id="styled-link"), ) def styled(): return rx.fragment( rx.el.p("Styled", class_name="page-styled", id="styled-paragraph"), - rx.el.a("Home", href="/", id="home-link"), + rx.link("Home", href="/", id="home-link"), ) assets = Path.cwd() / "assets" @@ -81,6 +81,9 @@ def test_statelessness(stateless_app: AppHarness, page: Page): def test_page_stylesheets(stateless_app: AppHarness, page: Page): """A page's stylesheet applies after the app's, only while the page is shown. + The links navigate client-side, so React Router itself has to add the + stylesheet and remove it again: a document reload would drop it anyway. + Args: stateless_app: A harness for testing the stateless app. page: A Playwright page. @@ -88,12 +91,14 @@ def test_page_stylesheets(stateless_app: AppHarness, page: Page): assert stateless_app.frontend_url is not None page.goto(stateless_app.frontend_url) expect(page.locator("#index-paragraph")).to_have_css("color", "rgb(255, 0, 0)") + page.evaluate("() => { window.__same_document = true; }") page.locator("#styled-link").click() expect(page.locator("#styled-paragraph")).to_have_css("color", "rgb(0, 0, 255)") page.locator("#home-link").click() expect(page.locator("#index-paragraph")).to_have_css("color", "rgb(255, 0, 0)") + assert page.evaluate("() => window.__same_document") is True page.goto(stateless_app.frontend_url.rstrip("/") + "/styled") expect(page.locator("#styled-paragraph")).to_have_css("color", "rgb(0, 0, 255)") From 945a824083b5c5298dcbe52cde1f68ce5490f768 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 09:43:31 +0100 Subject: [PATCH 11/15] test: compare the plain page's compiled output in full --- tests/units/compiler/test_compiler.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/tests/units/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py index 77d3d4ea011..8f8aa6b2b4c 100644 --- a/tests/units/compiler/test_compiler.py +++ b/tests/units/compiler/test_compiler.py @@ -389,7 +389,21 @@ def test_page_stylesheets(tmp_path: Path, mocker: MockerFixture): "\n" "export default Component;\n" ) - assert "export const links" not in (compiled["plain"].output_code or "") + assert compiled["plain"].output_code == ( + 'import {Fragment,useEffect} from "react"\n' + 'import {jsx} from "@emotion/react"\n' + "\n\n\n\n\n" + "function Component() {\n" + "\n\n" + " return (\n" + ' jsx(Fragment,{},jsx("div",{},"plain"),jsx("title",{},"Plain"),' + 'jsx("meta",{content:"favicon.ico",property:"og:image"},))\n' + " )\n" + "}\n" + 'Component.displayName = "Component(plain)";\n' + "\n" + "export default Component;\n" + ) assert (web_dir / "styles" / "shared.css").read_text() == ".shared { color: blue; }" assert (web_dir / "styles" / "pages" / "pricing.css").read_text() == ( ".pricing { color: red; }" From d72b9ba5babafc5af5a7bbc2b2ae991f3ef774fc Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 10:14:54 +0100 Subject: [PATCH 12/15] fix: take a single page stylesheet given as a string as one stylesheet --- reflex/app.py | 5 ++++- tests/units/test_app.py | 12 ++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/reflex/app.py b/reflex/app.py index 8366046f727..fc318f3700b 100644 --- a/reflex/app.py +++ b/reflex/app.py @@ -1644,7 +1644,10 @@ def _prepare_page( on_load=on_load, meta=meta, context=context or {}, - stylesheets=tuple(stylesheets), + # A string is a sequence of strings too, one per character. + stylesheets=(stylesheets,) + if isinstance(stylesheets, str) + else tuple(stylesheets), _source_module=source_module, ) diff --git a/tests/units/test_app.py b/tests/units/test_app.py index b2e31df2b02..14117989b37 100644 --- a/tests/units/test_app.py +++ b/tests/units/test_app.py @@ -449,6 +449,18 @@ def test_readded_page_keeps_its_stylesheets( assert app._unevaluated_pages["pricing"].stylesheets == ("/pricing.css",) +def test_add_page_single_stylesheet(app: App, index_page: ComponentCallable): + """A single stylesheet given as a string is one stylesheet, not one per character. + + Args: + app: The app to test. + index_page: The index page. + """ + app.add_page(index_page, route="pricing", stylesheets="/pricing.css") + + assert app._unevaluated_pages["pricing"].stylesheets == ("/pricing.css",) + + def test_add_page_invalid_api_route(app: App, index_page: ComponentCallable): """Test adding a page with an invalid route to an app. From 29267f934fb527e8961460c75776bb04f596153f Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 10:15:22 +0100 Subject: [PATCH 13/15] fix: give page hooks a page's stylesheets in backend-only compiles too --- reflex/compiler/compiler.py | 5 ++++- tests/units/compiler/test_compiler.py | 15 +++++++++++---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/reflex/compiler/compiler.py b/reflex/compiler/compiler.py index 23ad194a690..ad8a91ee9a5 100644 --- a/reflex/compiler/compiler.py +++ b/reflex/compiler/compiler.py @@ -1332,7 +1332,10 @@ def _walk_page_with_plugins( compile_context.hooks = CompilerHooks(plugins=plugins) hooks = compile_context.hooks page_context = PageContext( - name=page.route, route=page.route, root_component=component + name=page.route, + route=page.route, + root_component=component, + stylesheets=page.stylesheets, ) with compile_context, page_context: if any( diff --git a/tests/units/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py index 8f8aa6b2b4c..f4bee2a0bb4 100644 --- a/tests/units/compiler/test_compiler.py +++ b/tests/units/compiler/test_compiler.py @@ -5,6 +5,7 @@ import re import shutil import sys +from collections.abc import Sequence from pathlib import Path, PureWindowsPath import pytest @@ -1414,7 +1415,7 @@ def _compile_backend_only_app( mocker: MockerFixture, plugins: list[rx.plugins.Plugin], ) -> list[str]: - """Run a backend-only compile with no registry over two Radix pages. + """Run a backend-only compile with no registry over two Radix pages, one with a stylesheet. Args: tmp_path: A temporary project directory without a frontend build. @@ -1440,7 +1441,7 @@ def radix_page() -> Component: app = rx.App(_state=BackendWalkState) app.add_page(radix_page, route="/radix") - app.add_page(radix_page, route="/radix-2") + app.add_page(radix_page, route="/radix-2", stylesheets=["/radix.css"]) mocker.patch.object(app, "_apply_decorated_pages") mocker.patch.object(app, "_should_compile", return_value=False) mocker.patch.object(app, "_add_optional_endpoints") @@ -1526,7 +1527,7 @@ def compile_page(self, page_ctx: PageContext, /, **kwargs) -> None: def test_backend_compile_gives_page_hooks_the_compile_view( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture ): - """Page hooks see the replaced root and every page, as in a frontend compile. + """Page hooks see the replaced root, the stylesheets and every page, as in a frontend compile. Args: tmp_path: A temporary project directory without a frontend build. @@ -1535,6 +1536,7 @@ def test_backend_compile_gives_page_hooks_the_compile_view( """ replacements: dict[str, Component] = {} page_roots: dict[str, BaseComponent] = {} + page_stylesheets: dict[str, Sequence[str]] = {} page_routes: dict[str, list[str]] = {} class RootReplacingPlugin(rx.plugins.Plugin): @@ -1566,13 +1568,14 @@ def enter_component( return replacements[page_context.route] def compile_page(self, page_ctx: PageContext, /, **kwargs) -> None: - """Record the page root and the pages of the compile run. + """Record the page root, its stylesheets and the pages of the compile run. Args: page_ctx: The page being compiled. kwargs: The compile hook context. """ page_roots[page_ctx.route] = page_ctx.root_component + page_stylesheets[page_ctx.route] = page_ctx.stylesheets page_routes[page_ctx.route] = [ page.route for page in kwargs["compile_context"].pages ] @@ -1582,6 +1585,10 @@ def compile_page(self, page_ctx: PageContext, /, **kwargs) -> None: ) assert page_roots == replacements + assert page_stylesheets == { + **dict.fromkeys(routes, ()), + "radix-2": ("/radix.css",), + } assert page_routes == dict.fromkeys(routes, routes) From c2d35c556c1df16b22e59172456b151e7dfdcdd3 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 10:17:44 +0100 Subject: [PATCH 14/15] fix: load page stylesheets in an embedded app, which renders no --- news/+page-stylesheets.feature.md | 2 +- .../src/app/entry.client.embed.js | 38 ++++++++++++++++++- .../tests_playwright/test_mount_target.py | 38 ++++++++++++++++++- 3 files changed, 73 insertions(+), 5 deletions(-) diff --git a/news/+page-stylesheets.feature.md b/news/+page-stylesheets.feature.md index 942e6bd36a6..3b77822d646 100644 --- a/news/+page-stylesheets.feature.md +++ b/news/+page-stylesheets.feature.md @@ -1 +1 @@ -`add_page` and `@rx.page` take `stylesheets=`, stylesheets only that page loads, after the app's: `app.add_page(pricing, stylesheets=["/pages/pricing.css"])`. They take the same asset files and URLs as `rx.App(stylesheets=...)` and become the page's React Router `links`, so they are in the prerendered ``, load before the page renders on client-side navigation and are removed when it is left. +`add_page` and `@rx.page` take `stylesheets=`, stylesheets only that page loads, after the app's: `app.add_page(pricing, stylesheets=["/pages/pricing.css"])`. They take the same asset files and URLs as `rx.App(stylesheets=...)` and become the page's React Router `links`, so they are in the prerendered ``, load before the page renders on client-side navigation and are removed when it is left, in an `EmbedPlugin` widget too. diff --git a/packages/reflex-frontend/src/app/entry.client.embed.js b/packages/reflex-frontend/src/app/entry.client.embed.js index 57ef621468e..5099002aedc 100644 --- a/packages/reflex-frontend/src/app/entry.client.embed.js +++ b/packages/reflex-frontend/src/app/entry.client.embed.js @@ -1,10 +1,42 @@ -import { startTransition, createElement } from "react"; +import { startTransition, createElement, Fragment } from "react"; import { createRoot, hydrateRoot } from "react-dom/client"; import { HydratedRouter } from "react-router/dom"; import env from "$/env.json"; const selector = env.MOUNT_TARGET; +// Resolves once the browser has the stylesheet, as React Router waits for a +// route's stylesheets before showing it. +const preloadStylesheet = (href) => + new Promise((resolve) => { + const link = document.createElement("link"); + link.rel = "preload"; + link.as = "style"; + link.href = href; + link.onload = link.onerror = () => { + link.remove(); + resolve(); + }; + document.head.append(link); + }); + +// Without , a page renders the stylesheets its route module exports as +// `links` itself, so they apply while it is shown and go when it is left. +const pageComponent = async (page) => { + const links = page.links?.() ?? []; + if (!links.length) return page.default; + await Promise.all(links.map(({ href }) => preloadStylesheet(href))); + return () => + createElement( + Fragment, + null, + ...links.map((link) => + createElement("link", { key: link.href, ...link }), + ), + createElement(page.default), + ); +}; + if (selector) { const target = document.querySelector(selector); if (!target) { @@ -34,7 +66,9 @@ if (selector) { .then(([, reactRouter, root, manifest]) => { const { createMemoryRouter, RouterProvider, Outlet } = reactRouter; const children = manifest.default.map(({ path, load }) => { - const lazy = async () => ({ Component: (await load()).default }); + const lazy = async () => ({ + Component: await pageComponent(await load()), + }); if (path === "") return { index: true, lazy }; return { path, lazy }; }); diff --git a/tests/integration/tests_playwright/test_mount_target.py b/tests/integration/tests_playwright/test_mount_target.py index baf5d2c4531..c29a356343e 100644 --- a/tests/integration/tests_playwright/test_mount_target.py +++ b/tests/integration/tests_playwright/test_mount_target.py @@ -21,6 +21,8 @@ def MountTargetApp(): + from pathlib import Path + import reflex as rx class S(rx.State): @@ -46,13 +48,15 @@ def index(): rx.button("inc", on_click=S.inc, id="inc"), rx.link("about", href="/about", id="link-about"), rx.link("counter", href="/counter", id="link-counter"), + rx.el.p("index", class_name="page-styled", id="index-styled"), id="index-marker", ) - @rx.page(route="/about", on_load=S.on_load_about) + @rx.page(route="/about", on_load=S.on_load_about, stylesheets=["/about.css"]) def about(): return rx.box( rx.text("about page"), + rx.el.p("about", class_name="page-styled", id="about-styled"), rx.text("loaded: ", S.last_loaded_path, id="loaded-path"), rx.link("home", href="/", id="link-home"), id="about-marker", @@ -66,7 +70,11 @@ def counter(): id="counter-marker", ) - app = rx.App() + assets = Path.cwd() / "assets" + assets.mkdir(exist_ok=True) + (assets / "app.css").write_text(".page-styled { color: rgb(255, 0, 0); }") + (assets / "about.css").write_text(".page-styled { color: rgb(0, 0, 255); }") + app = rx.App(stylesheets=["/app.css"]) app.add_page(index) # Set plugins after rx.App() because App.__post_init__ reloads the config @@ -167,3 +175,29 @@ def test_on_load_fires_for_embedded_route(mount_target_app: AppHarnessProd, page expect(page.locator("#reflex-root #counter-marker")).to_be_visible() expect(page.locator("#reflex-root #count")).to_have_text("count: 1") expect(page.locator("#reflex-root #loaded-path")).to_have_text("loaded: /counter") + + +def test_page_stylesheets_in_widget(mount_target_app: AppHarnessProd, page: Page): + """A page's stylesheet applies after the app's, only while the widget shows the page. + + Args: + mount_target_app: The running harness. + page: A Playwright page. + """ + static = _static_dir(mount_target_app) + _write_host(static) + + base = mount_target_app.frontend_url + assert base is not None + page.goto(f"{base.rstrip('/')}/host.html") + + styled = page.locator("#reflex-root #index-styled") + expect(styled).to_have_css("color", "rgb(255, 0, 0)") + + page.locator("#reflex-root #link-about").click() + expect(page.locator("#reflex-root #about-styled")).to_have_css( + "color", "rgb(0, 0, 255)" + ) + + page.locator("#reflex-root #link-home").click() + expect(styled).to_have_css("color", "rgb(255, 0, 0)") From 24d84bcd1afa0274c550c35215cf07c3542aac82 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 10:17:49 +0100 Subject: [PATCH 15/15] docs: say what plugins see of page stylesheets in the reflex-base news --- packages/reflex-base/news/+page-stylesheets.feature.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/reflex-base/news/+page-stylesheets.feature.md b/packages/reflex-base/news/+page-stylesheets.feature.md index cc7ef283f39..ac9d7ad5e2b 100644 --- a/packages/reflex-base/news/+page-stylesheets.feature.md +++ b/packages/reflex-base/news/+page-stylesheets.feature.md @@ -1 +1 @@ -`page_template` takes `links`, exported from the route module as React Router's `links`, `PageContext` carries the page's `stylesheets`, and the `add_page` a plugin's `register_route` receives takes `stylesheets=`. +Plugins see a page's stylesheets: the `add_page` that `register_route` receives takes `stylesheets=`, and `PageContext.stylesheets` holds them. `page_template` takes `links`, which the route module exports as React Router's `links`, and an embedded app's entry renders them with their page, as it has no ``.