diff --git a/docs/styling/custom-stylesheets.md b/docs/styling/custom-stylesheets.md index 4c43af84291..cd4acd8fe1a 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=["/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/+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/news/+page-stylesheets.feature.md b/news/+page-stylesheets.feature.md new file mode 100644 index 00000000000..3b77822d646 --- /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, in an `EmbedPlugin` widget too. 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/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/news/+page-stylesheets.feature.md b/packages/reflex-base/news/+page-stylesheets.feature.md new file mode 100644 index 00000000000..ac9d7ad5e2b --- /dev/null +++ b/packages/reflex-base/news/+page-stylesheets.feature.md @@ -0,0 +1 @@ +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 ``. diff --git a/packages/reflex-base/src/reflex_base/compiler/templates.py b/packages/reflex-base/src/reflex_base/compiler/templates.py index 77f28862881..5516d71484a 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}; """ @@ -772,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. @@ -788,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: @@ -892,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. @@ -991,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/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/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/reflex/app.py b/reflex/app.py index 0800bcf2b10..e04355f5b5d 100644 --- a/reflex/app.py +++ b/reflex/app.py @@ -332,6 +332,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: @@ -351,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, @@ -1581,6 +1583,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. @@ -1596,6 +1599,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, image or on_load is a field with no frontend var. @@ -1613,6 +1619,7 @@ def add_page( on_load, meta, context, + stylesheets=stylesheets, ) ) @@ -1626,6 +1633,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. @@ -1642,6 +1650,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. @@ -1698,6 +1707,10 @@ def _prepare_page( on_load=on_load, meta=meta, context=context or {}, + # 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/reflex/compiler/compiler.py b/reflex/compiler/compiler.py index 83d72e5dd12..5e8dfce84bb 100644 --- a/reflex/compiler/compiler.py +++ b/reflex/compiler/compiler.py @@ -41,13 +41,14 @@ 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 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 @@ -400,55 +401,127 @@ 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: - target_path = stylesheet.relative_to(assets_app_path).with_suffix(".css") +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 _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 _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]: + """Link 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) + 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) 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 + # 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( @@ -464,18 +537,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 +937,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 +949,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 @@ -1235,7 +1356,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/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/reflex/utils/frontend_skeleton.py b/reflex/utils/frontend_skeleton.py index c32e1f0e893..4fd68db41d5 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/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/integration/test_prod_build_pipeline.py b/tests/integration/test_prod_build_pipeline.py index 7fda32d5591..e588204355a 100644 --- a/tests/integration/test_prod_build_pipeline.py +++ b/tests/integration/test_prod_build_pipeline.py @@ -5,6 +5,8 @@ from __future__ import annotations +import re +import sys from collections.abc import Generator from pathlib import Path @@ -38,6 +40,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 +125,56 @@ 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") + 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 + # 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/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)") diff --git a/tests/integration/tests_playwright/test_stateless_app.py b/tests/integration/tests_playwright/test_stateless_app.py index ef566819f48..8e7379baa23 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.link("Styled", href="/styled", id="styled-link"), + ) + + def styled(): + return rx.fragment( + rx.el.p("Styled", class_name="page-styled", id="styled-paragraph"), + rx.link("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,29 @@ 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. + + 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. + """ + 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)") diff --git a/tests/units/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py index 0f42e0ea870..1ab3c9a2f7b 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 @@ -328,6 +329,217 @@ 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 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; }" + ) + + +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 _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); }" + + +@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( @@ -419,6 +631,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 ): @@ -1270,7 +1527,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. @@ -1296,7 +1553,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") @@ -1382,7 +1639,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. @@ -1391,6 +1648,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): @@ -1422,13 +1680,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 ] @@ -1438,6 +1697,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) 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_app.py b/tests/units/test_app.py index 588d3a87162..7391d44ffb6 100644 --- a/tests/units/test_app.py +++ b/tests/units/test_app.py @@ -467,6 +467,41 @@ 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_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. 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", } diff --git a/tests/units/test_prerequisites.py b/tests/units/test_prerequisites.py index d905ed971ec..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,6 +606,42 @@ 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: 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, + "force_full_reload": False, + "experimental_hmr": False, + "sourcemap": False, + } + 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," + ) + + 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) + _compile_vite_config(Config(app_name="test")) + + assert template.call_args.kwargs["fs_allow"] == [tmp_path.as_posix()] + + 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")) 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.