From 269c675e6571b668ac9b4e818ed0c8256252feb7 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Wed, 25 Nov 2026 23:28:15 +0100 Subject: [PATCH 01/22] 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/22] 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/22] 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 a4bdb9a6ab3a1080183207ef537bed711a50a5eb Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 00:56:50 +0100 Subject: [PATCH 04/22] fix: resolve stylesheets' relative urls next to their real file --- news/+linked-stylesheet-urls.bugfix.md | 1 + .../news/+linked-stylesheet-urls.bugfix.md | 1 + .../src/reflex_base/compiler/templates.py | 13 ++- reflex/compiler/compiler.py | 25 +++++- reflex/utils/frontend_skeleton.py | 3 + tests/integration/test_prod_build_pipeline.py | 85 +++++++++++++++++++ tests/units/compiler/test_compiler.py | 81 ++++++++++++++++++ .../test_vite_plugin_react_compiler.py | 5 +- tests/units/test_prerequisites.py | 31 +++++++ 9 files changed, 240 insertions(+), 5 deletions(-) create mode 100644 news/+linked-stylesheet-urls.bugfix.md create mode 100644 packages/reflex-base/news/+linked-stylesheet-urls.bugfix.md diff --git a/news/+linked-stylesheet-urls.bugfix.md b/news/+linked-stylesheet-urls.bugfix.md new file mode 100644 index 00000000000..5abff1c93cd --- /dev/null +++ b/news/+linked-stylesheet-urls.bugfix.md @@ -0,0 +1 @@ +Relative `url()`s in stylesheets from the assets directory, including shared assets that `rx.asset(shared=True)` links in from a package, resolve next to the stylesheet's real file: the build bundles the fonts and images they name instead of leaving URLs that only work at some depths. The styles directory links each stylesheet instead of copying it, falling back to a copy where symlinks are unavailable, and the dev server may serve files under the app root. diff --git a/packages/reflex-base/news/+linked-stylesheet-urls.bugfix.md b/packages/reflex-base/news/+linked-stylesheet-urls.bugfix.md new file mode 100644 index 00000000000..1df45c1a1d0 --- /dev/null +++ b/packages/reflex-base/news/+linked-stylesheet-urls.bugfix.md @@ -0,0 +1 @@ +`vite_config_template` takes `fs_allow`, directories the dev server may serve besides its own root. diff --git a/packages/reflex-base/src/reflex_base/compiler/templates.py b/packages/reflex-base/src/reflex_base/compiler/templates.py index d3b7d79d81f..5516d71484a 100644 --- a/packages/reflex-base/src/reflex_base/compiler/templates.py +++ b/packages/reflex-base/src/reflex_base/compiler/templates.py @@ -776,6 +776,7 @@ def vite_config_template( prod_react: bool = False, warmup_routes: bool = False, react_compiler: bool = False, + fs_allow: Sequence[str] = (), ): """Template for vite.config.js. @@ -792,10 +793,18 @@ def vite_config_template( warmup_routes: Pre-transform every route module when the dev server starts, so the first visit to a page does not wait on Vite. react_compiler: Enable React Compiler for generated components. + fs_allow: Directories the dev server may serve files from besides the + frontend's own, such as the fonts a linked stylesheet references. Returns: Rendered vite.config.js content as string. """ + fs_allow_line = ( + "\n fs: { allow: [searchForWorkspaceRoot(process.cwd()), " + f"...{json.dumps(list(fs_allow))}] }}," + if fs_allow + else "" + ) if allowed_hosts is True: allowed_hosts_line = "\n allowedHosts: true," elif isinstance(allowed_hosts, list) and allowed_hosts: @@ -896,7 +905,7 @@ def vite_config_template( react_compiler_plugin = " reactCompiler(),\n" if react_compiler else "" return rf"""import {{ fileURLToPath, URL }} from "url"; import {{ reactRouter }} from "@react-router/dev/vite"; -import {{ defineConfig }} from "vite"; +import {{ defineConfig, searchForWorkspaceRoot }} from "vite"; import safariCacheBustPlugin from "./vite-plugin-safari-cachebust.js"; {react_compiler_import} // Ensure that bun always uses the react-dom/server.node functions. @@ -995,7 +1004,7 @@ def vite_config_template( hmr: {"true" if experimental_hmr else "false"}, }},{prod_react_str} server: {{ - port: process.env.PORT,{allowed_hosts_line} + port: process.env.PORT,{allowed_hosts_line}{fs_allow_line} hmr: {"true" if hmr else "false"},{warmup_str} watch: {{ ignored: [ diff --git a/reflex/compiler/compiler.py b/reflex/compiler/compiler.py index 7cd668b1488..63fce7756b3 100644 --- a/reflex/compiler/compiler.py +++ b/reflex/compiler/compiler.py @@ -48,6 +48,7 @@ from reflex_components_radix.plugin import RadixThemesPlugin from rich.progress import Progress +from reflex.assets import _link_shared_asset from reflex.compiler import templates, utils from reflex.compiler.plugins import default_page_plugins from reflex.compiler.plugins.memoize import MemoizeStatefulPlugin, scope_memo_body_hooks @@ -452,8 +453,28 @@ def _resolve_stylesheet_files(stylesheet: str) -> list[Path]: return files +def _link_stylesheet(source: Path, target: Path) -> None: + """Link a stylesheet into the styles directory, or copy it where links fail. + + The bundler resolves a linked stylesheet to the file it points at, so its + relative ``url()`` references resolve next to its real location: next to a + shared asset's package file rather than in the styles directory. + + Args: + source: The stylesheet's real path. + target: Where the styles directory gets the stylesheet. + """ + try: + _link_shared_asset(target, source) + except OSError: + # Symlinks need a privilege on Windows. Copying through a link left by + # an earlier compile would overwrite the source, so drop it first. + target.unlink(missing_ok=True) + path_ops.cp(src=source, dest=target, overwrite=True) + + def _compile_stylesheet_files(files: Iterable[Path]) -> list[str]: - """Copy stylesheet asset files into the styles directory, compiling sass. + """Link stylesheet asset files into the styles directory, compiling sass. Args: files: The stylesheet files in the assets directory. @@ -472,7 +493,7 @@ def _compile_stylesheet_files(files: Iterable[Path]) -> list[str]: target.parent.mkdir(parents=True, exist_ok=True) if stylesheet.suffix == ".css": - path_ops.cp(src=stylesheet, dest=target, overwrite=True) + _link_stylesheet(stylesheet.resolve(), target) else: try: from sass import compile as sass_compile diff --git a/reflex/utils/frontend_skeleton.py b/reflex/utils/frontend_skeleton.py index 0c18ffbb3e6..cbde88e44f3 100644 --- a/reflex/utils/frontend_skeleton.py +++ b/reflex/utils/frontend_skeleton.py @@ -648,6 +648,9 @@ def _compile_vite_config(config: Config): sourcemap=environment.VITE_SOURCEMAP.get(), minify=environment.VITE_MINIFY.get(), allowed_hosts=config.vite_allowed_hosts, + # Stylesheets are linked to their files under the app root, whose + # fonts and images the dev server would otherwise refuse to serve. + fs_allow=[Path.cwd().as_posix()], ) diff --git a/tests/integration/test_prod_build_pipeline.py b/tests/integration/test_prod_build_pipeline.py index 7fda32d5591..37e69d9febb 100644 --- a/tests/integration/test_prod_build_pipeline.py +++ b/tests/integration/test_prod_build_pipeline.py @@ -5,6 +5,7 @@ from __future__ import annotations +import re from collections.abc import Generator from pathlib import Path @@ -38,6 +39,42 @@ def index(): ) +def LinkedStylesheetApp(): + """An app whose stylesheets are a package's, linked in like rx.asset(shared=True).""" + import zlib + from pathlib import Path + + import reflex as rx + + # The font and image next to the package's stylesheets are not linked + # themselves. Above Vite's 4 KiB inline limit, the build emits them as files. + package = Path.cwd() / "site_package" + (package / "css").mkdir(parents=True, exist_ok=True) + (package / "fonts").mkdir(exist_ok=True) + (package / "images").mkdir(exist_ok=True) + (package / "fonts" / "x.woff2").write_bytes(zlib.compress(b"font", 0) * 500) + (package / "images" / "y.png").write_bytes(zlib.compress(b"image", 0) * 500) + (package / "css" / "site.css").write_text( + '@font-face { font-family: Site; src: url(../fonts/x.woff2) format("woff2"); }' + ) + (package / "css" / "page.css").write_text( + ".hero { background-image: url(../images/y.png); }" + ) + external = Path.cwd() / "assets" / "external" / "site_package" / "css" + external.mkdir(parents=True, exist_ok=True) + for name in ("site.css", "page.css"): + if not (external / name).is_symlink(): + (external / name).symlink_to(package / "css" / name) + + app = rx.App(stylesheets=["/external/site_package/css/site.css"]) + app.add_page(rx.el.main("Index", style={"font_family": "Site"}), route="/") + app.add_page( + rx.el.main("Styled", class_name="hero"), + route="/styled", + stylesheets=["/external/site_package/css/page.css"], + ) + + @pytest.fixture(scope="module") def all_compression_formats_env() -> Generator[None, None, None]: """Configure the harness to build with every supported compression format. @@ -87,6 +124,54 @@ def _find_build_files(harness: AppHarness, pattern: str) -> list[Path]: return sorted(static_dir.rglob(pattern)) +@pytest.fixture(scope="module") +def linked_stylesheet_app( + app_harness_env: type[AppHarness], + tmp_path_factory: pytest.TempPathFactory, +) -> Generator[AppHarness, None, None]: + """Build and serve the linked stylesheet app in production mode. + + Yields: + A running production app harness. + """ + if app_harness_env is not AppHarnessProd: + pytest.skip("build pipeline checks are prod-only") + + root = tmp_path_factory.mktemp("linked_stylesheet") + # Without Tailwind, which rewrites the urls of the stylesheets it imports + # against its own base instead of the importing stylesheet. + (root / "rxconfig.py").write_text( + 'import reflex as rx\n\nconfig = rx.Config(app_name="linked_stylesheet", plugins=[])\n' + ) + (root / "linked_stylesheet").mkdir() + (root / "linked_stylesheet" / "__init__.py").touch() + with app_harness_env.create( + root=root, + app_name="linked_stylesheet", + app_source=LinkedStylesheetApp, + ) as harness: + yield harness + + +def test_linked_stylesheet_urls_resolve_next_to_their_real_file( + linked_stylesheet_app: AppHarness, +): + """A shared stylesheet's relative urls become fingerprinted build assets. + + Args: + linked_stylesheet_app: The running prod harness. + """ + [font] = _find_build_files(linked_stylesheet_app, "assets/x-*.woff2") + [image] = _find_build_files(linked_stylesheet_app, "assets/y-*.png") + urls = { + url + for css in _find_build_files(linked_stylesheet_app, "assets/*.css") + for url in re.findall(r"url\(([^)]+)\)", css.read_text()) + } + + assert urls == {f"/assets/{font.name}", f"/assets/{image.name}"} + + @pytest.mark.parametrize( ("_format_name", "_accept_encoding", "suffix", "_magic"), ENCODING_CASES, diff --git a/tests/units/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py index a795d583cd7..e4b4f3014bf 100644 --- a/tests/units/compiler/test_compiler.py +++ b/tests/units/compiler/test_compiler.py @@ -413,6 +413,87 @@ def test_page_stylesheet_not_found(tmp_path: Path, mocker: MockerFixture): ) +def _linked_stylesheet_project(tmp_path: Path, mocker: MockerFixture) -> Path: + """Lay out a shared stylesheet linked into the assets directory, like rx.asset(shared=True). + + Args: + tmp_path: The test directory. + mocker: Pytest mocker object. + + Returns: + The real stylesheet in the package directory. + """ + real = tmp_path / "pkg" / "css" / "site.css" + real.parent.mkdir(parents=True) + real.write_text(".site { background: url(../images/y.png); }") + link = tmp_path / "assets" / "external" / "pkg" / "css" / "site.css" + link.parent.mkdir(parents=True) + link.symlink_to(real) + mocker.patch("reflex.compiler.compiler.Path.cwd", return_value=tmp_path) + mocker.patch( + "reflex.compiler.compiler.get_web_dir", + return_value=tmp_path / constants.Dirs.WEB, + ) + return real + + +@pytest.mark.skipif(os.name == "nt", reason="symlinks need a privilege on Windows") +def test_stylesheets_link_to_their_real_file(tmp_path: Path, mocker: MockerFixture): + """App and page stylesheets point at their real file, so its relative urls resolve there. + + Args: + tmp_path: The test directory. + mocker: Pytest mocker object. + """ + real = _linked_stylesheet_project(tmp_path, mocker) + styles = tmp_path / constants.Dirs.WEB / "styles" + + _, code = compiler.compile_root_stylesheet( + ["/external/pkg/css/site.css"], reset_style=False + ) + links = compiler.compile_page_stylesheets(["/external/pkg/css/site.css"]) + + assert code == "@layer __reflex_base;\n@import url('./external/pkg/css/site.css');" + assert str(links) == ( + '[({ ["rel"] : "stylesheet", ["href"] : reflexPageStylesheet0 })]' + ) + target = styles / "external" / "pkg" / "css" / "site.css" + assert target.is_symlink() + assert target.readlink() == real + + +@pytest.mark.skipif(os.name == "nt", reason="symlinks need a privilege on Windows") +def test_stylesheet_copied_where_links_fail(tmp_path: Path, mocker: MockerFixture): + """Without symlinks a stylesheet is copied, never written through an old link. + + Args: + tmp_path: The test directory. + mocker: Pytest mocker object. + """ + real = _linked_stylesheet_project(tmp_path, mocker) + target = ( + tmp_path + / constants.Dirs.WEB + / "styles" + / "external" + / "pkg" + / "css" + / "site.css" + ) + target.parent.mkdir(parents=True) + target.symlink_to(real) + mocker.patch( + "reflex.compiler.compiler._link_shared_asset", + side_effect=OSError("A required privilege is not held by the client"), + ) + + compiler.compile_root_stylesheet(["/external/pkg/css/site.css"], reset_style=False) + + assert not target.is_symlink() + assert target.read_text() == ".site { background: url(../images/y.png); }" + assert real.read_text() == ".site { background: url(../images/y.png); }" + + 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/reflex_base/templates/test_vite_plugin_react_compiler.py b/tests/units/reflex_base/templates/test_vite_plugin_react_compiler.py index 04466c39f7c..52b0d563079 100644 --- a/tests/units/reflex_base/templates/test_vite_plugin_react_compiler.py +++ b/tests/units/reflex_base/templates/test_vite_plugin_react_compiler.py @@ -57,7 +57,10 @@ "package.json": '{"type": "module"}', "vite-plugin-safari-cachebust.js": 'export default () => ({name: "safari"});', "node_modules/vite/package.json": '{"type": "module", "exports": "./index.js"}', - "node_modules/vite/index.js": "export const defineConfig = (config) => config;", + "node_modules/vite/index.js": ( + "export const defineConfig = (config) => config;\n" + "export const searchForWorkspaceRoot = (root) => root;" + ), "node_modules/@react-router/dev/package.json": ( '{"type": "module", "exports": {"./vite": "./index.js"}}' ), diff --git a/tests/units/test_prerequisites.py b/tests/units/test_prerequisites.py index 607b03e5805..721e49aaa5c 100644 --- a/tests/units/test_prerequisites.py +++ b/tests/units/test_prerequisites.py @@ -544,6 +544,37 @@ def test_initialise_vite_config(config, expected_output): assert expected_output in output +def test_vite_config_allows_the_app_root(tmp_path: Path, monkeypatch): + """The dev server may serve files under the app root, which linked stylesheets reference.""" + from reflex_base.compiler.templates import vite_config_template + + kwargs = { + "base": "/", + "hmr": True, + "force_full_reload": False, + "experimental_hmr": False, + "sourcemap": False, + } + fs_line = ( + "\n fs: { allow: [searchForWorkspaceRoot(process.cwd()), " + '...["/app", "/lib"]] },' + ) + without = vite_config_template(**kwargs) + + assert vite_config_template(**kwargs, fs_allow=["/app", "/lib"]) == without.replace( + " port: process.env.PORT,", " port: process.env.PORT," + fs_line + ) + assert "fs:" not in without + + monkeypatch.chdir(tmp_path) + output = _compile_vite_config(Config(app_name="test")) + app_root_line = ( + " fs: { allow: [searchForWorkspaceRoot(process.cwd()), " + f"...{json.dumps([tmp_path.as_posix()])}] }}," + ) + assert [line for line in output.splitlines() if "fs:" in line] == [app_root_line] + + def test_react_compiler_vite_config(): """Only opt-in apps load React Compiler before the router's transforms.""" default_output = _compile_vite_config(Config(app_name="test")) From 0416e78c7cb9aa22d2c63f7e713665a92977a420 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 09:42:40 +0100 Subject: [PATCH 05/22] 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 06/22] 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 07/22] 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 08/22] 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 55b61bcc0d7c598ad836f1ac4ff07fa8f3210ecd Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 09:44:36 +0100 Subject: [PATCH 09/22] fix: never write compiled sass through a stylesheet link left in its place --- reflex/compiler/compiler.py | 3 +++ tests/units/compiler/test_compiler.py | 31 +++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/reflex/compiler/compiler.py b/reflex/compiler/compiler.py index 12cf8c2c5b0..d563cc8f48b 100644 --- a/reflex/compiler/compiler.py +++ b/reflex/compiler/compiler.py @@ -519,6 +519,9 @@ def _compile_stylesheet_files(files: Iterable[Path]) -> list[str]: try: from sass import compile as sass_compile + # Writing through a stylesheet link an earlier compile left + # here would overwrite the file it points at. + target.unlink(missing_ok=True) target.write_text( # libsass is untyped; compiling from a filename returns the CSS. data=cast( diff --git a/tests/units/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py index ff7c5f54bda..ccd4e340d80 100644 --- a/tests/units/compiler/test_compiler.py +++ b/tests/units/compiler/test_compiler.py @@ -508,6 +508,37 @@ def test_stylesheet_copied_where_links_fail(tmp_path: Path, mocker: MockerFixtur assert real.read_text() == ".site { background: url(../images/y.png); }" +@pytest.mark.skipif(os.name == "nt", reason="symlinks need a privilege on Windows") +def test_sass_replaces_a_stylesheet_link(tmp_path: Path, mocker: MockerFixture): + """Compiled sass replaces a link an earlier compile left, never the file behind it. + + 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; }") + target = tmp_path / constants.Dirs.WEB / "styles" / "theme.css" + mocker.patch("reflex.compiler.compiler.Path.cwd", return_value=tmp_path) + mocker.patch("reflex.compiler.compiler.get_web_dir", return_value=tmp_path / ".web") + compiler.compile_root_stylesheet(["/theme.css"], reset_style=False) + assert target.is_symlink() + + (assets_dir / "theme.css").unlink() + (assets_dir / "theme.scss").write_text(".theme { color: blue; }") + _, code = compiler.compile_root_stylesheet(["/theme.scss"], reset_style=False) + + assert code == "@layer __reflex_base;\n@import url('./theme.css');" + assert not target.is_symlink() + assert target.read_text() == ".theme{color:blue}\n" + assert sorted(path.name for path in assets_dir.iterdir()) == ["theme.scss"] + + def test_compile_stylesheets_scss_sass(tmp_path: Path, mocker: MockerFixture): if importlib.util.find_spec("sass") is None: pytest.skip( From 072ccc5b87a80a6b6f9096ff820b3a4db064d363 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 09:45:07 +0100 Subject: [PATCH 10/22] test: compare the vite config in full and import its template at the top --- tests/units/test_prerequisites.py | 40 ++++++++++++++++++------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/tests/units/test_prerequisites.py b/tests/units/test_prerequisites.py index ceaca96e40c..cdc760d691e 100644 --- a/tests/units/test_prerequisites.py +++ b/tests/units/test_prerequisites.py @@ -17,6 +17,7 @@ from click.testing import CliRunner from pytest_mock import MockerFixture from reflex_base import constants +from reflex_base.compiler.templates import vite_config_template from reflex_base.config import Config from reflex_base.environment import environment from reflex_base.registry import RegistrationContext @@ -605,10 +606,16 @@ def test_initialise_vite_config(config, expected_output): assert expected_output in output -def test_vite_config_allows_the_app_root(tmp_path: Path, monkeypatch): - """The dev server may serve files under the app root, which linked stylesheets reference.""" - from reflex_base.compiler.templates import vite_config_template +def test_vite_config_allows_the_app_root( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture +): + """The dev server may serve files under the app root, which linked stylesheets reference. + Args: + tmp_path: The app root. + monkeypatch: Fixture for entering the app root. + mocker: Fixture for spying on the vite config template. + """ kwargs = { "base": "/", "hmr": True, @@ -616,24 +623,23 @@ def test_vite_config_allows_the_app_root(tmp_path: Path, monkeypatch): "experimental_hmr": False, "sourcemap": False, } - fs_line = ( - "\n fs: { allow: [searchForWorkspaceRoot(process.cwd()), " - '...["/app", "/lib"]] },' + server = " port: process.env.PORT,\n hmr: true," + server_with_fs = ( + " port: process.env.PORT,\n" + " fs: { allow: [searchForWorkspaceRoot(process.cwd()), " + '...["/app", "/lib"]] },\n' + " hmr: true," ) - without = vite_config_template(**kwargs) - assert vite_config_template(**kwargs, fs_allow=["/app", "/lib"]) == without.replace( - " port: process.env.PORT,", " port: process.env.PORT," + fs_line - ) - assert "fs:" not in without + assert vite_config_template( + **kwargs, fs_allow=["/app", "/lib"] + ) == vite_config_template(**kwargs).replace(server, server_with_fs) + template = mocker.spy(frontend_skeleton.templates, "vite_config_template") monkeypatch.chdir(tmp_path) - output = _compile_vite_config(Config(app_name="test")) - app_root_line = ( - " fs: { allow: [searchForWorkspaceRoot(process.cwd()), " - f"...{json.dumps([tmp_path.as_posix()])}] }}," - ) - assert [line for line in output.splitlines() if "fs:" in line] == [app_root_line] + _compile_vite_config(Config(app_name="test")) + + assert template.call_args.kwargs["fs_allow"] == [tmp_path.as_posix()] def test_react_compiler_vite_config(): From bbf8c6955bfa9cfc986353f9f6639bcd16435231 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 09:42:40 +0100 Subject: [PATCH 11/22] 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 12/22] 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 13/22] 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 14/22] 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 949b8c5a36e4753198a9ef9fb9a1d4f6a27d1892 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 09:44:36 +0100 Subject: [PATCH 15/22] fix: never write compiled sass through a stylesheet link left in its place --- reflex/compiler/compiler.py | 3 +++ tests/units/compiler/test_compiler.py | 31 +++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/reflex/compiler/compiler.py b/reflex/compiler/compiler.py index 63fce7756b3..df66ad4f505 100644 --- a/reflex/compiler/compiler.py +++ b/reflex/compiler/compiler.py @@ -498,6 +498,9 @@ def _compile_stylesheet_files(files: Iterable[Path]) -> list[str]: try: from sass import compile as sass_compile + # Writing through a stylesheet link an earlier compile left + # here would overwrite the file it points at. + target.unlink(missing_ok=True) target.write_text( # libsass is untyped; compiling from a filename returns the CSS. data=cast( diff --git a/tests/units/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py index e4b4f3014bf..a6620bd7753 100644 --- a/tests/units/compiler/test_compiler.py +++ b/tests/units/compiler/test_compiler.py @@ -494,6 +494,37 @@ def test_stylesheet_copied_where_links_fail(tmp_path: Path, mocker: MockerFixtur assert real.read_text() == ".site { background: url(../images/y.png); }" +@pytest.mark.skipif(os.name == "nt", reason="symlinks need a privilege on Windows") +def test_sass_replaces_a_stylesheet_link(tmp_path: Path, mocker: MockerFixture): + """Compiled sass replaces a link an earlier compile left, never the file behind it. + + 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; }") + target = tmp_path / constants.Dirs.WEB / "styles" / "theme.css" + mocker.patch("reflex.compiler.compiler.Path.cwd", return_value=tmp_path) + mocker.patch("reflex.compiler.compiler.get_web_dir", return_value=tmp_path / ".web") + compiler.compile_root_stylesheet(["/theme.css"], reset_style=False) + assert target.is_symlink() + + (assets_dir / "theme.css").unlink() + (assets_dir / "theme.scss").write_text(".theme { color: blue; }") + _, code = compiler.compile_root_stylesheet(["/theme.scss"], reset_style=False) + + assert code == "@layer __reflex_base;\n@import url('./theme.css');" + assert not target.is_symlink() + assert target.read_text() == ".theme{color:blue}\n" + assert sorted(path.name for path in assets_dir.iterdir()) == ["theme.scss"] + + def test_compile_stylesheets_scss_sass(tmp_path: Path, mocker: MockerFixture): if importlib.util.find_spec("sass") is None: pytest.skip( From 30b4807caeebf3e9bffabea0a6aca9d33125d6c2 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 09:45:07 +0100 Subject: [PATCH 16/22] test: compare the vite config in full and import its template at the top --- tests/units/test_prerequisites.py | 40 ++++++++++++++++++------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/tests/units/test_prerequisites.py b/tests/units/test_prerequisites.py index 721e49aaa5c..8e6dae4c739 100644 --- a/tests/units/test_prerequisites.py +++ b/tests/units/test_prerequisites.py @@ -16,6 +16,7 @@ import pytest from click.testing import CliRunner from reflex_base import constants +from reflex_base.compiler.templates import vite_config_template from reflex_base.config import Config from reflex_base.environment import environment from reflex_base.utils import log @@ -544,10 +545,16 @@ def test_initialise_vite_config(config, expected_output): assert expected_output in output -def test_vite_config_allows_the_app_root(tmp_path: Path, monkeypatch): - """The dev server may serve files under the app root, which linked stylesheets reference.""" - from reflex_base.compiler.templates import vite_config_template +def test_vite_config_allows_the_app_root( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture +): + """The dev server may serve files under the app root, which linked stylesheets reference. + Args: + tmp_path: The app root. + monkeypatch: Fixture for entering the app root. + mocker: Fixture for spying on the vite config template. + """ kwargs = { "base": "/", "hmr": True, @@ -555,24 +562,23 @@ def test_vite_config_allows_the_app_root(tmp_path: Path, monkeypatch): "experimental_hmr": False, "sourcemap": False, } - fs_line = ( - "\n fs: { allow: [searchForWorkspaceRoot(process.cwd()), " - '...["/app", "/lib"]] },' + server = " port: process.env.PORT,\n hmr: true," + server_with_fs = ( + " port: process.env.PORT,\n" + " fs: { allow: [searchForWorkspaceRoot(process.cwd()), " + '...["/app", "/lib"]] },\n' + " hmr: true," ) - without = vite_config_template(**kwargs) - assert vite_config_template(**kwargs, fs_allow=["/app", "/lib"]) == without.replace( - " port: process.env.PORT,", " port: process.env.PORT," + fs_line - ) - assert "fs:" not in without + assert vite_config_template( + **kwargs, fs_allow=["/app", "/lib"] + ) == vite_config_template(**kwargs).replace(server, server_with_fs) + template = mocker.spy(frontend_skeleton.templates, "vite_config_template") monkeypatch.chdir(tmp_path) - output = _compile_vite_config(Config(app_name="test")) - app_root_line = ( - " fs: { allow: [searchForWorkspaceRoot(process.cwd()), " - f"...{json.dumps([tmp_path.as_posix()])}] }}," - ) - assert [line for line in output.splitlines() if "fs:" in line] == [app_root_line] + _compile_vite_config(Config(app_name="test")) + + assert template.call_args.kwargs["fs_allow"] == [tmp_path.as_posix()] def test_react_compiler_vite_config(): From d72b9ba5babafc5af5a7bbc2b2ae991f3ef774fc Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 10:14:54 +0100 Subject: [PATCH 17/22] 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 18/22] 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 19/22] 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 20/22] 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 ``. From 85138f820a96790dcb351b243f7d4790506bdc28 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 10:19:34 +0100 Subject: [PATCH 21/22] fix: replace a link when writing a compiled file instead of writing through it --- reflex/utils/path_ops.py | 6 +++++- tests/units/utils/test_path_ops.py | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/reflex/utils/path_ops.py b/reflex/utils/path_ops.py index 86d1260d0b7..4077f41d9f8 100644 --- a/reflex/utils/path_ops.py +++ b/reflex/utils/path_ops.py @@ -58,7 +58,11 @@ def write_file(path: str | Path, code: str): """ path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) - if path.exists() and path.read_text(encoding="utf-8") == code: + if path.is_symlink(): + # Writing through a link, such as a stylesheet the compile linked into + # the styles directory, would overwrite the file it points at. + path.unlink() + elif path.exists() and path.read_text(encoding="utf-8") == code: return path.write_text(code, encoding="utf-8") diff --git a/tests/units/utils/test_path_ops.py b/tests/units/utils/test_path_ops.py index a346139d908..0c8ee03c6d5 100644 --- a/tests/units/utils/test_path_ops.py +++ b/tests/units/utils/test_path_ops.py @@ -936,6 +936,25 @@ def test_write_file_updates_changed_file(tmp_path: Path) -> None: assert path.read_text(encoding="utf-8") == "after" +@pytest.mark.skipif( + sys.platform == "win32", reason="symlinks need a privilege on Windows" +) +def test_write_file_replaces_a_link(tmp_path: Path) -> None: + """A link at the path, like a linked stylesheet, is replaced, not written through.""" + source = tmp_path / "assets" / "tailwind.css" + source.parent.mkdir() + source.write_text("source", encoding="utf-8") + path = tmp_path / "styles" / "tailwind.css" + path.parent.mkdir() + path.symlink_to(source) + + write_file(path, "generated") + + assert not path.is_symlink() + assert path.read_text(encoding="utf-8") == "generated" + assert source.read_text(encoding="utf-8") == "source" + + def test_update_directory_tree_reports_only_copied_files(tmp_path: Path) -> None: """Copy callbacks include nested files and omit files skipped on later updates. From 64d81aba7f64833fcf4b04a5f0cb789d15cfe986 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 10:19:38 +0100 Subject: [PATCH 22/22] test: skip the linked stylesheet build where symlinks need a privilege --- tests/integration/test_prod_build_pipeline.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/integration/test_prod_build_pipeline.py b/tests/integration/test_prod_build_pipeline.py index 37e69d9febb..e588204355a 100644 --- a/tests/integration/test_prod_build_pipeline.py +++ b/tests/integration/test_prod_build_pipeline.py @@ -6,6 +6,7 @@ from __future__ import annotations import re +import sys from collections.abc import Generator from pathlib import Path @@ -136,6 +137,8 @@ def linked_stylesheet_app( """ if app_harness_env is not AppHarnessProd: pytest.skip("build pipeline checks are prod-only") + if sys.platform == "win32": + pytest.skip("symlinks need a privilege on Windows") root = tmp_path_factory.mktemp("linked_stylesheet") # Without Tailwind, which rewrites the urls of the stylesheets it imports